blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
50609da13d88705b11682f2d457355be71e5e0b2
|
Java
|
pliesveld/spring-boot-hookahlounge
|
/src/main/java/tutorial/repository/BasicInventoryRepository.java
|
UTF-8
| 286
| 1.625
| 2
|
[] |
no_license
|
package tutorial.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import tutorial.domain.BasicInventory;
@Repository
public interface BasicInventoryRepository extends CrudRepository<BasicInventory, String> {
}
| true
|
4a8064cd41f54514719ed8c9dabca1765ceb9d60
|
Java
|
farmerworking/leveldb-in-java
|
/leveldb-data-structure/src/test/java/com/farmerworking/leveldb/in/java/data/structure/log/LogTest.java
|
UTF-8
| 1,076
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package com.farmerworking.leveldb.in.java.data.structure.log;
import com.farmerworking.leveldb.in.java.common.ICRC32C;
import com.farmerworking.leveldb.in.java.common.ICoding;
import com.farmerworking.leveldb.in.java.file.SequentialFile;
import com.farmerworking.leveldb.in.java.file.WritableFile;
public class LogTest extends ILogTest {
@Override
protected ICRC32C getCrc32CImpl() {
return ICRC32C.getInstance();
}
@Override
protected ICoding getCodingImpl() {
return ICoding.getInstance();
}
@Override
protected ILogReader getLogReaderImpl(SequentialFile sequentialFile, ILogReporter logReporter, boolean checksum, long initialOffset) {
return new LogReader(sequentialFile, logReporter, checksum, initialOffset);
}
@Override
protected ILogWriter getLogWriterImpl(WritableFile writableFile) {
return new LogWriter(writableFile);
}
@Override
protected ILogWriter getLogWriterImpl(WritableFile writableFile, long offset) {
return new LogWriter(writableFile, offset);
}
}
| true
|
85af0df4f03470f6c59c919f9b0fe1a9ab94beed
|
Java
|
leejiliang/lee-security
|
/lee-security-core/src/main/java/com/lee/social/qq/provider/QQServiceProvider.java
|
UTF-8
| 856
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.lee.social.qq.provider;
import com.lee.social.qq.api.QQApi;
import com.lee.social.qq.api.QQApiUserInfoImpl;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
import org.springframework.social.oauth2.OAuth2Template;
/**
* @program: lee-security
* @description:
* @author: Jiliang.Lee
* @create: 2018-11-15 20:08
**/
public class QQServiceProvider extends AbstractOAuth2ServiceProvider<QQApi>{
private static final String URL_AUTHORIZE="https://graph.qq.com/oauth2.0/authorize";
private static final String URL_TOKEN="https://graph.qq.com/oauth2.0/token";
String appid;
@Override
public QQApi getApi(String accessToken) {
return new QQApiUserInfoImpl(accessToken,appid);
}
public QQServiceProvider(String appid,String appSecret) {
super(new OAuth2Template(appid,appSecret,URL_AUTHORIZE,URL_TOKEN));
}
}
| true
|
5bdb89931f248743184236d8a587691c2d959278
|
Java
|
kroctus/Forgotten_World
|
/src/juego/Arco.java
|
UTF-8
| 1,202
| 2.75
| 3
|
[] |
no_license
|
/*
* 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 juego;
/**
*
* @author kroctus
*/
public class Arco extends Arma implements HabilidadesArco {
public Arco(Double ataque, String nombre, Double velocidad, boolean magica) {
super(ataque, nombre, velocidad, magica);
}
@Override
public double azoteSilvary(MainCharacter pj) {
pj.setMp(pj.getMp() - 40);
return pj.getArma().getAtaque() * 4;
}
@Override
public double tiro(MainCharacter pj) {
return 20;
}
@Override
public double flechaExplosiva(MainCharacter pj) {
pj.setMp(pj.getMp() - 50);
return (pj.getArma().getAtaque() + pj.getArma().getAtaque() * 0.50);
}
@Override
public double lluviaDeEstrellas(MainCharacter pj) {
pj.setMp(0.00);
return 999.0;
}
@Override
public double flechaPerforante(MainCharacter pj) {
return 90;
}
@Override
public double estruendoDivino(MainCharacter pj) {
pj.setMp(pj.getMp() - 50);
return 70;
}
}
| true
|
d9550316f1a40080c737fd193c50a91ed9ab89a2
|
Java
|
curtisnoonan/Java-Code
|
/Gomoku/Gomoku.java
|
UTF-8
| 14,225
| 3.796875
| 4
|
[] |
no_license
|
import cs251.lab2.*;
/** Curtis Noonan
This class is used to play Gomoku, get 5 X's or 5 0's in a row to win!*/
public class Gomoku implements GomokuModel{
public static void main( String[] args ) {
Gomoku game = new Gomoku();
if(args.length > 0) {
game.setComputerPlayer(args[0]);
}
GomokuGUI.showGUI(game);
}
Square[][] gameBoardTiles = new Square[NUM_VSQUARES][NUM_HSQUARES]; //2D array for coordinates
boolean computerEnabled = false; //to determine who is playing
/* clears the game board with empty squares */
public void newGame(){
for (int row = 0; row < NUM_VSQUARES; row++) { // Iterate over each row.
for (int col = 0; col < NUM_HSQUARES; col++) { // Iterate over each column.
gameBoardTiles[row][col] = Square.EMPTY;
}
}
}
/* returns a string representation of the Gomoku board */
public String boardString ( ){
String boardInString = "";
for (int row = 0; row < NUM_VSQUARES; row++) { // Iterate over each row.
for (int col = 0; col < NUM_HSQUARES; col++) { // Iterate over each column.
boardInString += gameBoardTiles[row][col].toChar();
}
boardInString += "\n";
}
return boardInString;
}
/* returns an Outcome and takes the coordinates of a click from the mouse
currently does not work as I can not get the computer to draw rings, but
it is close*/
public Outcome doClick ( int row, int col ){
int counter = 0;
if(counter == 0){
counter++;
gameBoardTiles[row][col] = Square.CROSS;
if(checkForCrossWin()){
return Outcome.CROSS_WINS;
}
else if (checkForDraw()){
return Outcome.DRAW;
}
else{
return Outcome.GAME_NOT_OVER;
}
}
if(computerEnabled == true){
if(counter == 1){
counter--;
if(gameBoardTiles[row][col-1] == Square.EMPTY){ //places a O to the left if it can
gameBoardTiles[row][col-1] = Square.RING;
}
else if(gameBoardTiles[row][col+1] == Square.EMPTY){ //places a O to the right if it can
gameBoardTiles[row][col+1] = Square.RING;
}
else if(gameBoardTiles[row+1][col] == Square.EMPTY){
gameBoardTiles[row+1][col] = Square.RING;
}
else if(gameBoardTiles[row-1][col] == Square.EMPTY){
gameBoardTiles[row-1][col] = Square.RING;
}
else if(gameBoardTiles[row+1][col+1] == Square.EMPTY){
gameBoardTiles[row+1][col+1] = Square.RING;
}
else if(gameBoardTiles[row+1][col-1] == Square.EMPTY){
gameBoardTiles[row+1][col-1] = Square.RING;
}
else if(gameBoardTiles[row-1][col+1] == Square.EMPTY){
gameBoardTiles[row-1][col+1] = Square.RING;
}
else if(gameBoardTiles[row+1][col-1] == Square.EMPTY){
gameBoardTiles[row+1][col-1] = Square.RING;
}
else{
for (int row1 = 0; row1 < NUM_VSQUARES; row1++) { //if it can place from above chooses first available
for (int col1 = 0; col1 < NUM_HSQUARES; col1++) {
if(gameBoardTiles[row1][col1] != Square.EMPTY){
gameBoardTiles[row1][col1] = Square.RING;
}
}
}
}
if(checkForRingWin()){
return Outcome.RING_WINS;
}
else if (checkForDraw()){
return Outcome.DRAW;
}
else{
return Outcome.GAME_NOT_OVER;
}
}
}
else{
gameBoardTiles[row][col] = Square.RING;
if(checkForRingWin()){
return Outcome.RING_WINS;
}
else if (checkForDraw()){
return Outcome.DRAW;
}
else{
return Outcome.GAME_NOT_OVER;
}
}
return Outcome.GAME_NOT_OVER;
}
/* returns a boolean if 5 X are in a row*/
public boolean checkForCrossWin(){
for(int col = 0; col < NUM_HSQUARES; col++){
for(int row = 0; row < NUM_VSQUARES; row++){
if(gameBoardTiles[row][col] == Square.CROSS){
int numCrossLeft = 0; //probably an easier way, but this works
int numCrossRight = 0;
int numCrossUp = 0;
int numCrossDown = 0;
int numCrossRightHoriz = 0;
int numCrossLeftHoriz = 0;
int numCrossBotLeftHoriz = 0;
int numCrossBotRightHoriz = 0;
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row][col+counter+1] == Square.CROSS){ //right side
numCrossRight++;
if (numCrossRight == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row][col-counter-1] == Square.CROSS){ //left side
numCrossLeft++;
if (numCrossLeft == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col] == Square.CROSS){ //vertical
numCrossUp++;
if (numCrossUp == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col] == Square.CROSS){ //down
numCrossDown++;
if (numCrossDown == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col+counter+1] == Square.CROSS){ //right horiz
numCrossRightHoriz++;
if (numCrossRightHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col-counter-1] == Square.CROSS){ //left horiz
numCrossLeftHoriz++;
if (numCrossLeftHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col-counter-1] == Square.CROSS){ //bot left horiz
numCrossBotLeftHoriz++;
if (numCrossBotLeftHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col+counter+1] == Square.CROSS){ //bot right horiz
numCrossBotRightHoriz++;
if (numCrossBotRightHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
}
}
}
return false;
}
/* returns a boolean if 5 O are in a row */
public boolean checkForRingWin(){
for(int col = 0; col < NUM_HSQUARES; col++){
for(int row = 0; row < NUM_VSQUARES; row++){
if(gameBoardTiles[row][col] == Square.RING){
int numRingLeft = 0;
int numRingRight = 0;
int numRingUp = 0;
int numRingDown = 0;
int numRingRightHoriz = 0;
int numRingLeftHoriz = 0;
int numRingBotLeftHoriz = 0;
int numRingBotRightHoriz = 0;
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row][col+counter+1] == Square.RING){ //right side
numRingRight++;
if (numRingRight == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row][col-counter-1] == Square.RING){ //left side
numRingLeft++;
if (numRingLeft == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col] == Square.RING){ //vertical
numRingUp++;
if (numRingUp == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col] == Square.RING){ //down
numRingDown++;
if (numRingDown == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col+counter+1] == Square.RING){ //right horiz
numRingRightHoriz++;
if (numRingRightHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row+counter+1][col-counter-1] == Square.RING){ //left horiz
numRingLeftHoriz++;
if (numRingLeftHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col-counter-1] == Square.RING){ //bot left horiz
numRingBotLeftHoriz++;
if (numRingBotLeftHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
for(int counter = 0; counter < SQUARES_IN_LINE_FOR_WIN-1; counter++){
if(gameBoardTiles[row-counter-1][col+counter+1] == Square.RING){ //bot right horiz
numRingBotRightHoriz++;
if (numRingBotRightHoriz == SQUARES_IN_LINE_FOR_WIN-1){
return true;
}
}
}
}
}
}
return false;
}
/* checks if there is a draw*/
public boolean checkForDraw(){
int numPlayed = 0;
for (int row = 0; row < NUM_VSQUARES; row++) {
for (int col = 0; col < NUM_HSQUARES; col++) {
if (gameBoardTiles[row][col] == Square.CROSS || gameBoardTiles[row][col] == Square.RING){ //check if not empty
numPlayed++;
}
}
}
if(numPlayed == NUM_VSQUARES*NUM_HSQUARES){ //checks to see if the board is full
return true;
}
else{
return false;
}
}
/* checks if there is an opponent or if you are playing against a computer takes a string arg*/
public void setComputerPlayer(String opponent){
if(opponent.equals("COMPUTER")){ //checking command line arg
computerEnabled = true; //enables computer
}
}
}
| true
|
702b3a5b80186b9e67bc642c558cc0da4bf32b48
|
Java
|
fegg/Weekly75-1
|
/app/src/main/java/org/qiwoo/weekly75/Weekly75.java
|
UTF-8
| 7,264
| 2.609375
| 3
|
[] |
no_license
|
package org.qiwoo.weekly75;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.qiwoo.weekly75.moduel.Article;
import org.qiwoo.weekly75.moduel.ArticlePager;
import org.qiwoo.weekly75.moduel.Category;
import org.qiwoo.weekly75.moduel.Issue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by hujun-iri on 16/3/26.
* 该类是 api 接口, 用来获取数据
*
*/
public class Weekly75 {
// 获取最新期刊
public static final String API_LATEST = "http://weeklyapi.75team.com/issue/latest";
/**
* 周刊详情
* 接口格式:/issue/detail/${iid}
* 参数说明:
* iid:具体某一期期刊 id。可以从 /issue/list/ 接口中获取;
* 示例:
* http://weeklyapi.75team.com/issue/detail/134
*/
public static final String API_ISSUE_DETAIL = "http://weeklyapi.75team.com/issue/detail/";
public static final String API_SEARCH = "http://weeklyapi.75team.com/article/search/%1$s/%2$s/hl/0";
private static int BUFFER_SIZE = 4096;
// 获取最新的期刊
public static Issue getLatestIssue() throws IOException, JSONException {
String result = httpGet(API_LATEST);
//Issue issue = parseIssue(result);
return parseIssue(result);
}
// 根据期刊编号获取周刊详情
public static Issue getIssueById(String id) throws IOException, JSONException {
String result = httpGet(API_ISSUE_DETAIL + id);
return parseIssue(result);
}
public static ArticlePager search(String key, String page) throws IOException, JSONException {
String url = createSearchUrl(key, page);
String result = httpGet(url);
return paseArticle(result);
}
private static ArticlePager paseArticle(String result) throws JSONException {
ArticlePager articles = new ArticlePager();
JSONObject jo = new JSONObject(result);
articles.count = jo.getInt("count");
articles.totalPages = jo.getInt("totalPages");
articles.numsPerPage = jo.getInt("numsPerPage");
articles.currentPage = jo.getInt("currentPage");
List<ArticlePager.Article> data = new ArrayList<>();
articles.articles = data;
JSONArray ja = jo.getJSONArray("data");
for(int i =0 ;i < ja.length(); i++) {
JSONObject joo = ja.getJSONObject(i);
// 常规内部类需要通过外部类的实例才能创建对象,与实例变量需要通过对象来访问相似
ArticlePager.Article aa = articles.new Article();
aa.aid = joo.getInt("aid");
aa.iid = joo.getInt("iid");
aa.title = joo.getString("title");
aa.url = joo.getString("url");
aa.description = joo.getString("description");
aa.tags = joo.getString("tags");
aa.readability_url = joo.getString("readability_url");
data.add(aa);
}
return articles;
}
/**
* 发送get请求
* 把请求的结果用一个字符串的形式返回
*/
private static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
String resultStr = readInputStreamAsString(stream);
return resultStr;
}
private static String readInputStreamAsString(InputStream in) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while( (count = in.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
outputStream.write(buffer, 0, count);
}
return new String(outputStream.toByteArray(), "UTF-8");
}
private static Issue parseIssue(String str) throws JSONException {
Issue issue = new Issue();
JSONObject jsonObject = new JSONObject(str);
issue.setIid(jsonObject.getInt("iid"));
issue.setDate(jsonObject.getString("date"));
issue.setEditor(jsonObject.getString("editor"));
issue.setTopic(jsonObject.getString("topic"));
JSONArray categoryObj = jsonObject.getJSONArray("article");
List<Category> categoryList = new ArrayList<>();
issue.setCategoryList(categoryList);
for(int i= 0; i <categoryObj.length() ; i++) {
JSONObject cateItem = categoryObj.getJSONObject(i);
Iterator<String> itKeys = cateItem.keys();
// 只是获取一级
String key = itKeys.next();
Category category = new Category();
List<Article> articleList = new ArrayList<>();
category.setTitle(key);
category.setArticleList(articleList);
JSONArray articlesArray = cateItem.getJSONArray(key);
for( int j = 0; j < articlesArray.length(); j++ ) {
JSONObject tempObj = articlesArray.getJSONObject(j);
// 创建 Article 对象
Article article = new Article();
article.setTitle(tempObj.getString("title"));
article.setUrl(tempObj.getString("url"));
article.setReadabilityUrl(tempObj.getString("readability_url"));
article.setDescription(tempObj.getString("description"));
article.setProvider(tempObj.getString("provider"));
// 解析标签
List<String> tagList = new ArrayList<>();
JSONArray tagsJSONArray = tempObj.getJSONArray("tags");
for( int k=0; k< tagsJSONArray.length(); k++){
tagList.add(tagsJSONArray.getString(k));
}
article.setTagArr(tagList);
article.setTags(Arrays.toString(tagList.toArray()));
// 将 article 添加到 List 中
articleList.add(article);
}
categoryList.add(category);
}
return issue;
}
private static String createSearchUrl(String key, String page) {
return String.format(API_SEARCH, encodeURIComponent(key), page);
}
private static String encodeURIComponent(String s) {
String result = null;
try {
result = URLEncoder.encode(s, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
// This exception should never occur.
result = s;
}
return result;
}
}
| true
|
8424d08b10b5e5c1c7c51fba29370d5f19c88b0d
|
Java
|
chenxin185/Algorithm
|
/app/src/main/java/com/chenxin/algorithm/MainActivity.java
|
UTF-8
| 516
| 2.203125
| 2
|
[] |
no_license
|
package com.chenxin.algorithm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int[] array = new int[]{622,32,42,52,62,72,82,92,102,112,122,132,142,152,162, 53, 4123, 321, 2, 1};
SortUtils.baseSort(array,4);
SortUtils.printArray(array);
}
}
| true
|
960d4798de85bb6c9858325a4cc4574acaa6edc6
|
Java
|
fosbsb/ugas
|
/src/main/java/br/com/e2f/institutodepilar/resource/LoginClienteResource.java
|
UTF-8
| 4,668
| 1.992188
| 2
|
[] |
no_license
|
package br.com.e2f.institutodepilar.resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import br.com.e2f.institutodepilar.entity.Cliente;
import br.com.e2f.institutodepilar.repository.ClienteRepository;
import br.com.e2f.institutodepilar.service.ClienteService;
import br.com.e2f.institutodepilar.util.EnumEmailTemplate;
import br.com.e2f.institutodepilar.util.GeradorSenha;
import br.com.e2f.institutodepilar.util.SenhaUtil;
import br.com.e2f.institutodepilar.util.SenhaUtil.Algoritmo;
import br.com.e2f.institutodepilar.vo.EmailVO;
import br.com.e2f.institutodepilar.vo.RetornoVO;
import net.kaczmarzyk.spring.data.jpa.domain.Equal;
import net.kaczmarzyk.spring.data.jpa.web.annotation.And;
import net.kaczmarzyk.spring.data.jpa.web.annotation.Spec;
@RestController
@RequestMapping("/api/login-cliente")
public class LoginClienteResource extends BasicResource {
@Autowired
private ClienteRepository clienteRepository;
@Autowired
private ClienteService clienteService;
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RetornoVO recuperarLogin(@RequestParam(value = "email", required = false) String email,
@And({ @Spec(path = "email", spec = Equal.class) }) Specification<Cliente> spec) {
@SuppressWarnings("unchecked")
Cliente login = (Cliente) clienteRepository.findOne(spec);
if (login == null) {
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.NO_CONTENT));
}
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.OK));
}
@RequestMapping(path = "/esqueci-senha/{email}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RetornoVO esqueciMinhaSenha(@RequestParam(value = "email", required = false) String email,
@And({ @Spec(path = "email", spec = Equal.class) }) Specification<Cliente> spec) {
@SuppressWarnings("unchecked")
Cliente login = (Cliente) clienteRepository.findOne(spec);
if (login == null) {
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.NO_CONTENT));
} else {
try {
String senhaGerada = GeradorSenha.getSenha(6);
login.setSenha(senhaGerada);
login = clienteService.atualizarCliente(login);
EmailVO emailVo = new EmailVO();
emailVo.setAssunto("Esqueci Minha Senha :: Instituto Depilar");
emailVo.setDestino(login.getEmail());
emailVo.setSenhaGerada(senhaGerada);
emailVo.setNome(login.getNome());
emailVo.setMensagem("Solicitação de recuperação de Senha");
emailVo.setTemplate(EnumEmailTemplate.ESQUECI_SENHA);
return getRetornoVO(clienteService.enviarEmail(emailVo));
} catch (Exception e) {
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.INTERNAL_SERVER_ERROR));
}
}
}
@RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RetornoVO recuperarLogin(@PathVariable("id") Long id) {
Cliente login = clienteService.recuperarCliente(id);
if (login == null) {
return getRetornoVO(new ResponseEntity<Cliente>(HttpStatus.NOT_FOUND));
}
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.OK));
}
@SuppressWarnings("unused")
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public RetornoVO alterarSenhaLogin(@RequestParam(name = "id") Long id,
@RequestParam(name = "senhaAntiga") String senhaAntiga,
@RequestParam(name = "novaSenha") String novaSenha) {
Cliente login = clienteService.recuperarCliente(id);
String hashPassword = SenhaUtil.gerarHash(novaSenha, login.getEmail(), Algoritmo.SHA256);
if (login != null) {
if (login.getSenha().equals(SenhaUtil.gerarHash(senhaAntiga,login.getEmail(),Algoritmo.SHA256))) {
login.setSenha(hashPassword);
login = clienteService.atualizarCliente(login);
return getRetornoVO(new ResponseEntity<Cliente>(login, HttpStatus.OK));
} else {
return getRetornoVO(new ResponseEntity<Cliente>(HttpStatus.UNAUTHORIZED));
}
}
return getRetornoVO(new ResponseEntity<Cliente>(HttpStatus.NOT_FOUND));
}
}
| true
|
4240605bee3735891dadc0e34cd7aee68b517f59
|
Java
|
Searge-DP/SquidUtils
|
/java/coolsquid/squidutils/config/compat/minetweaker/BlockUtils.java
|
UTF-8
| 1,347
| 2.015625
| 2
|
[
"LicenseRef-scancode-generic-cla"
] |
no_license
|
/*******************************************************************************
* Copyright (c) 2015 CoolSquid.
* All rights reserved.
*******************************************************************************/
package coolsquid.squidutils.config.compat.minetweaker;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import coolsquid.squidutils.SquidUtils;
@ZenClass("mods.squidutils.Blocks")
public class BlockUtils {
@ZenMethod
public static void setHardness(String name, float value) {
Block.getBlockFromName(name).blockHardness = value;
}
@ZenMethod
public static void setMaterial(String name, String material) {
Block.getBlockFromName(name).blockMaterial = SquidUtils.API.getMaterials().get(material);
}
@ZenMethod
public static void setResistance(String name, float value) {
Block.getBlockFromName(name).blockResistance = value;
}
@ZenMethod
public static void setCreativeTab(String name, String tab) {
Block.getBlockFromName(name).setCreativeTab(SquidUtils.COMMON.getCreativeTabs().get(tab));
}
@ZenMethod
public static void setFlammibility(String name, int flammibility, int encouragement) {
Blocks.fire.setFireInfo(Block.getBlockFromName(name), encouragement, flammibility);
}
}
| true
|
d82626ddecb26c2377e16bb373ab1ae25ea09b54
|
Java
|
Mattlomet/Capstone-2
|
/admin-api/src/main/java/com/company/adminapi/viewmodel/OrderViewModel.java
|
UTF-8
| 3,391
| 2.375
| 2
|
[] |
no_license
|
package com.company.adminapi.viewmodel;
import com.company.adminapi.model.Customer;
import com.company.adminapi.model.InvoiceItem;
import com.company.adminapi.model.LevelUp;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
public class OrderViewModel {
@Valid
@NotNull(message = "Enter customer details.")
private Customer customer;
private Integer invoiceId;
private LocalDate purchaseDate;
@Valid
@NotNull(message = "Enter product or invoice item.")
@NotEmpty(message = "Enter product or invoice item.")
private List<InvoiceItem> invoiceItems;
private BigDecimal orderTotal;
private Integer awardedPoints;
private LevelUp memberPoints;
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Integer getInvoiceId() {
return invoiceId;
}
public void setInvoiceId(Integer invoiceId) {
this.invoiceId = invoiceId;
}
public LocalDate getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(LocalDate purchaseDate) {
this.purchaseDate = purchaseDate;
}
public List<InvoiceItem> getInvoiceItems() {
return invoiceItems;
}
public void setInvoiceItems(List<InvoiceItem> invoiceItems) {
this.invoiceItems = invoiceItems;
}
public BigDecimal getOrderTotal() {
return orderTotal;
}
public void setOrderTotal(BigDecimal orderTotal) {
this.orderTotal = orderTotal;
}
public Integer getAwardedPoints() {
return awardedPoints;
}
public void setAwardedPoints(Integer awardedPoints) {
this.awardedPoints = awardedPoints;
}
public LevelUp getMemberPoints() {
return memberPoints;
}
public void setMemberPoints(LevelUp memberPoints) {
this.memberPoints = memberPoints;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderViewModel that = (OrderViewModel) o;
return Objects.equals(customer, that.customer) &&
Objects.equals(invoiceId, that.invoiceId) &&
Objects.equals(purchaseDate, that.purchaseDate) &&
Objects.equals(invoiceItems, that.invoiceItems) &&
Objects.equals(orderTotal, that.orderTotal) &&
Objects.equals(awardedPoints, that.awardedPoints) &&
Objects.equals(memberPoints, that.memberPoints);
}
@Override
public int hashCode() {
return Objects.hash(customer, invoiceId, purchaseDate, invoiceItems, orderTotal, awardedPoints, memberPoints);
}
@Override
public String toString() {
return "OrderViewModel{" +
"customer=" + customer +
", invoiceId=" + invoiceId +
", purchaseDate=" + purchaseDate +
", invoiceItems=" + invoiceItems +
", orderTotal=" + orderTotal +
", awardedPoints=" + awardedPoints +
", memberPoints=" + memberPoints +
'}';
}
}
| true
|
e468e252eaae7ef4245a006f02e2939d08237e03
|
Java
|
thilo-behnke/android-ninja-clicker-game
|
/app/src/main/java/com/tbeh/ninjaclicker/spawn/BaseSpawnManager.java
|
UTF-8
| 2,469
| 2.921875
| 3
|
[] |
no_license
|
package com.tbeh.ninjaclicker.spawn;
import com.tbeh.ninjaclicker.model.sprite.CharacterEnum;
import com.tbeh.ninjaclicker.model.sprite.Sprite;
import java.util.Random;
import static com.tbeh.ninjaclicker.model.sprite.CharacterEnum.NINJA_BLUE;
import static com.tbeh.ninjaclicker.model.sprite.CharacterEnum.NINJA_RED;
import static com.tbeh.ninjaclicker.model.sprite.CharacterEnum.GIRL;
import static com.tbeh.ninjaclicker.model.sprite.PowerUpEnum.HAMMER;
import static com.tbeh.ninjaclicker.model.sprite.PowerUpEnum.SWORD;
public abstract class BaseSpawnManager implements ISpawnManager {
private static Random random = new Random();
private Sprite marioTemplate;
private Sprite luigiTemplate;
private Sprite peachTemplate;
private Spawner marioSpawner;
private Spawner luigiSpawner;
private Spawner peachSpawner;
private Spawner hammerSpawner;
private Spawner swordSpawner;
public BaseSpawnManager() {
marioTemplate = NINJA_RED.makePrototype();
marioSpawner = new Spawner(marioTemplate);
luigiTemplate = NINJA_BLUE.makePrototype();
luigiSpawner = new Spawner(luigiTemplate);
peachTemplate = GIRL.makePrototype();
peachSpawner = new Spawner(peachTemplate);
hammerSpawner = new Spawner(HAMMER.makePrototype());
swordSpawner = new Spawner(SWORD.makePrototype());
}
Spawner getMarioSpawner() {
return marioSpawner;
}
Spawner getLuigiSpawner() {
return luigiSpawner;
}
Spawner getPeachSpawner() {
return peachSpawner;
}
private Spawner getHammerSpawner() {
return hammerSpawner;
}
private Spawner getSwordSpawner() {
return swordSpawner;
}
public Sprite getCharacterPrototype(CharacterEnum characterEnum) {
if (characterEnum.equals(NINJA_RED)) {
return marioTemplate;
} else if (characterEnum.equals(NINJA_BLUE)) {
return luigiTemplate;
} else if (characterEnum.equals(GIRL)) {
return peachTemplate;
} else {
throw new IllegalArgumentException();
}
}
public Sprite spawnPowerUp() {
int randomNumber = random.nextInt(10);
if (randomNumber <= 5) {
return getHammerSpawner().getSpriteCopy();
} else if (randomNumber > 5 && randomNumber <= 10) {
return getSwordSpawner().getSpriteCopy();
}
return null;
}
}
| true
|
572a194289102fee4eb1262e391a2c699143a62c
|
Java
|
Rooman/SpringStudy
|
/src/main/java/lab1/example/IntServiceLocator.java
|
UTF-8
| 336
| 2.53125
| 3
|
[] |
no_license
|
package lab1.example;
import java.util.HashMap;
import java.util.Map;
public class IntServiceLocator {
private final static Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("printerCount", 5);
}
};
public static Integer get(String key) {
return map.get(key);
}
}
| true
|
554e453305ee82bb81140659aec66b23fd13770e
|
Java
|
gavin2lee/dwss
|
/monitor/monitor-common/src/main/java/com/gl/monitor/common/object/CommonMsgBuilder.java
|
UTF-8
| 1,430
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.gl.monitor.common.object;
public class CommonMsgBuilder {
public static final String DEF_SYS_ID = "000000";
public static final String DEF_TO_SYS_ID = "000001";
public static final String DEF_MSG_STATE = "0";
public static final int DEF_MSG_TYPE = CommonMsgType.NOMAL.ordinal();
public static final String DEF_RET_CODE = "0000";
public static final String DEF_RET_MSG = "";
private static final String SYS_ID;
static{
SYS_ID = System.getProperty("sysId", DEF_SYS_ID);
}
public static CommonMsg buildDefMsg(){
CommonMsg defMsg = new CommonMsg(buildDefHeader(), null);
return defMsg;
}
public static CommonMsg buildMsg(MonitorReqMsg inMsg){
CommonMsg outMsg = buildDefMsg();
outMsg.getHeader().setTargetSysId(inMsg.getHeader().getSrcSysId());
outMsg.getHeader().setSrcSysId(SYS_ID);
return outMsg;
}
public static CommonMsg buildReqMsgTemplate(){
CommonMsgHeader header = buildDefHeader();
CommonMsgBody body = new CommonRequest();
return new CommonMsg(header, body);
}
private static CommonMsgHeader buildDefHeader(){
CommonMsgHeader header = new CommonMsgHeader();
header.setMsgId(String.valueOf(System.nanoTime()));
header.setMsgState(DEF_MSG_STATE);
header.setMsgType(DEF_MSG_TYPE);
header.setSrcSysId(DEF_SYS_ID);
header.setTargetSysId(DEF_TO_SYS_ID);
header.setRetCode(DEF_RET_CODE);
header.setRetMsg(DEF_RET_MSG);
return header;
}
}
| true
|
1b4c79eec32b33c53e2cec4765018ad6471a8d5c
|
Java
|
Miscellian/NetReaders
|
/NetReaders-Service/src/main/java/com/netreaders/controller/BookController.java
|
UTF-8
| 7,442
| 2.15625
| 2
|
[] |
no_license
|
package com.netreaders.controller;
import com.netreaders.dto.UserBookLibrary;
import com.netreaders.models.Book;
import com.netreaders.service.BookService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
@RestController
@AllArgsConstructor
@RequestMapping("/api/books")
public class BookController {
private final BookService bookService;
@GetMapping(value = "{id}")
public Book getBookById(@PathVariable Integer id) {
return bookService.findBookById(id);
}
@GetMapping(value = "range")
public Collection<Book> getById(
@RequestParam(name = "amount", defaultValue = "0") Integer amount,
@RequestParam(name = "offset", defaultValue = "0") Integer offset) {
return bookService.getBooksById(amount, offset);
}
@GetMapping(value = "bygenre")
public Collection<Book> getByGenre(
@RequestParam(name = "id") Integer genreId,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.findBooksByGenre(genreId, amount, offset);
}
@GetMapping(value = "byauthor")
public Collection<Book> getByAuthor(
@RequestParam(name = "id") Integer authorId,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.findBooksByAuthor(authorId, amount, offset);
}
@GetMapping(value = "byname")
public Collection<Book> getByName(
@RequestParam(name = "name") String name,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.getBooksByName(name, amount, offset);
}
@GetMapping(value = "byusername")
public Collection<Book> getByUsername(
@RequestParam(name = "username") String username,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.getBooksUsername(username, amount, offset);
}
@GetMapping(value = "preferences")
public Collection<Book> getByUserPreferences(
@RequestParam(name = "username") String username) {
return bookService.getByUserPreferences(username);
}
@GetMapping(value = "byusernameFavourites")
public Collection<Book> getFavouritesByUsername(
@RequestParam(name = "username") String username,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.getFavouritesByUsername(username, amount, offset);
}
@GetMapping(value = "byusernameToReadList")
public Collection<Book> getToReadListByUsername(
@RequestParam(name = "username") String username,
@RequestParam(name = "amount") Integer amount,
@RequestParam(name = "offset") Integer offset) {
return bookService.getToReadListByUsername(username, amount, offset);
}
@GetMapping(value = "count")
public Integer getCount() {
return bookService.getCount();
}
@GetMapping(value = "countByAuthor")
public Integer getCountByAuthor(
@RequestParam(name = "id") Integer authorId) {
return bookService.getCountByAuthor(authorId);
}
@GetMapping(value = "countByGenre")
public Integer getCountByGenre(
@RequestParam(name = "id") Integer genreId) {
return bookService.getCountByGenre(genreId);
}
@GetMapping(value = "countByName")
public Integer getCountByName(
@RequestParam(name = "name") String name) {
return bookService.getCountByName(name);
}
@GetMapping(value = "countByUsername")
public Integer getCountByUsername(
@RequestParam(name = "username") String username) {
return bookService.getCountByUsername(username);
}
@GetMapping(value = "countFavouritesByUsername")
public Integer getFavouritesCountByUsername(
@RequestParam(name = "username") String username) {
return bookService.getFavouritesCountByUsername(username);
}
// not done
@GetMapping(value = "countToReadListByUsername")
public Integer getToReadListCountByUsername(
@RequestParam(name = "username") String username) {
return bookService.getToReadListCountByUsername(username);
}
@PostMapping(value = "addToLibrary")
public void addBookToUserLibrary(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.addBookToUserLibrary(userBookLibrary);
}
@PostMapping(value = "removeFromLibrary")
public void removeBookFromUserLibrary(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.removeBookFromUserLibrary(userBookLibrary);
}
@PostMapping(value = "checkInLibrary")
public boolean checkIfBookInLibrary(
@RequestBody UserBookLibrary userBookLibrary) {
return bookService.checkIfBookInLibrary(userBookLibrary);
}
@PostMapping(value = "addToFavourites")
public void addBookToFavorites(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.addBookToUserFavourites(userBookLibrary);
}
@PostMapping(value = "removeFromFavourites")
public void removeBookFromFavorites(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.removeBookFromUserFavourites(userBookLibrary);
}
@PostMapping(value = "checkInFavourites")
public boolean checkIfBookInFavorites(
@RequestBody UserBookLibrary userBookLibrary) {
return bookService.checkIfBookInFavourites(userBookLibrary);
}
//not done
@PostMapping(value = "addToToReadList")
public void addBookToToReadList(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.addBookToUserToReadList(userBookLibrary);
}
//not done
@PostMapping(value = "removeFromToReadList")
public void removeBookToReadList(
@RequestBody UserBookLibrary userBookLibrary) {
bookService.removeBookFromUserToReadList(userBookLibrary);
}
//not done
@PostMapping(value = "checkInToReadList")
public boolean checkIfBookInToReadList(
@RequestBody UserBookLibrary userBookLibrary) {
return bookService.checkIfBookInUserToReadList(userBookLibrary);
}
@PostMapping(value = "add")
public void addBook(@RequestBody Book book) {
bookService.addBook(book);
}
@PostMapping(value = "publish")
public void publishBook(@RequestBody Integer bookId) {
bookService.publishBook(bookId);
}
@GetMapping(value = "unpublished")
public Collection<Book> getUnpublished(
@RequestParam(name = "amount", defaultValue = "0") Integer amount,
@RequestParam(name = "offset", defaultValue = "0") Integer offset) {
return bookService.getUnpublished(amount, offset);
}
@GetMapping(value = "unpublishedCount")
public Integer getUnpublishedCount() {
return bookService.getUnpublishedCount();
}
@PostMapping(value = "checkExists")
public boolean checkBookExists(@RequestBody String title) {
return bookService.checkBookExists(title);
}
}
| true
|
d43b472ec636e80755847a5baa8a8b034ea7eee6
|
Java
|
Corbie325/RESTsafePlatform
|
/src/main/java/com/example/restsafeplatform/admin/service/UserAndAdminRegistrationService.java
|
UTF-8
| 7,601
| 1.960938
| 2
|
[] |
no_license
|
package com.example.restsafeplatform.admin.service;
import com.example.restsafeplatform.admin.dto.data.UserData;
import com.example.restsafeplatform.admin.dto.entity.PassportInfo;
import com.example.restsafeplatform.admin.dto.entity.UserEntity;
import com.example.restsafeplatform.authorization.dto.model.Role;
import com.example.restsafeplatform.authorization.dto.model.Status;
import com.example.restsafeplatform.admin.repository.PassportRepository;
import com.example.restsafeplatform.authorization.repository.UserRepository;
import com.example.restsafeplatform.authorization.service.JwtTokenProvider;
import com.example.restsafeplatform.common.configuration.SecurityConfiguration;
import com.example.restsafeplatform.common.exception.AlreadyExistException;
import com.example.restsafeplatform.common.exception.UserNonExistException;
import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
@Slf4j
public class UserAndAdminRegistrationService implements UserDetails{
private final UserRepository userRepository;
private final PassportRepository passportRepository;
private final SecurityConfiguration securityConfiguration;
@Autowired
private JwtTokenProvider token;
public UserAndAdminRegistrationService(UserRepository userRepository, PassportRepository passportRepository, SecurityConfiguration securityConfiguration) {
this.userRepository = userRepository;
this.passportRepository = passportRepository;
this.securityConfiguration = securityConfiguration;
}
@Transactional
public UserEntity userRegistration(UserData userData) throws AlreadyExistException {
Optional<UserEntity> userEntityIUserEntityOptional = userRepository.findByEmail(userData.getEmail());
if (userEntityIUserEntityOptional.isPresent()) {
throw new AlreadyExistException("Пользователь уже зарегестрирован");
}
PassportInfo passportInfo = PassportInfo
.builder()
.passportDateOfIssue(userData.getPassportData().getPassportDateOfIssue())
.passportNumberAndSerial(userData.getPassportData().getPassportSerial() + "-" + userData.getPassportData().getPassportNumber())
.registrationAddress(userData.getPassportData().getRegistrationAddress())
.passportPlaceOfIssue(userData.getPassportData().getPassportPlaceOfIssue())
.build();
passportRepository.saveAndFlush(passportInfo);
UserEntity userEntity = UserEntity
.builder()
.birthDate(userData.getBirthDate())
.fio(userData.getFio())
.email(userData.getEmail())
.passport(passportInfo)
.password(securityConfiguration.passwordEncoder().encode(userData.getPassword()))
.role(Role.USER)
.contactPhone(userData.getContactPhone().get(0))
.contactPhone1(userData.getContactPhone().get(1))
.status(userData.getStatus())
.firstName(userData.getFirstName())
.lastName(userData.getLastName())
.middleName(userData.getMiddleName())
.build();
userRepository.saveAndFlush(userEntity);
// mailSender.send(userData.getEmail(), "Registration in SafePlatform", message);
return userEntity;
}
public UserEntity getUserByToken(ServletRequest servletRequest) throws UserNonExistException {
String userId = token.getUserId(token.resolveToken((HttpServletRequest) servletRequest));
Optional<UserEntity> userFromEntity = userRepository.findById(Long.valueOf(userId));
if (userFromEntity.isEmpty()){
throw new UserNonExistException("Пользователя не существует");
}
return userFromEntity.get();
}
public List<UserEntity> gelAllUser() {
return userRepository.findAll();
}
public UserEntity getUser(Integer id){
return userRepository.getById(Long.valueOf(id));
}
public void deleteUser(Integer id){
userRepository.deleteById(Long.valueOf(id));
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
public static UserDetails fromUser(UserEntity user) {
return new org.springframework.security.core.userdetails.User(
user.getEmail(), user.getPassword(),
user.getStatus().equals(Status.ACTIVE),
user.getStatus().equals(Status.ACTIVE),
user.getStatus().equals(Status.ACTIVE),
user.getStatus().equals(Status.ACTIVE),
user.getRole().getAuthorities()
);
}
@Transactional
public UserEntity adminRegistration(UserData userData) throws AlreadyExistException {
Optional<UserEntity> userEntityIUserEntityOptional = userRepository.findByEmail(userData.getEmail());
if (userEntityIUserEntityOptional.isPresent()) {
throw new AlreadyExistException("Пользователь уже зарегестрирован");
}
PassportInfo passportInfo = PassportInfo
.builder()
.passportDateOfIssue(userData.getPassportData().getPassportDateOfIssue())
.passportNumberAndSerial(userData.getPassportData().getPassportSerial() + "-" + userData.getPassportData().getPassportNumber())
.registrationAddress(userData.getPassportData().getRegistrationAddress())
.passportPlaceOfIssue(userData.getPassportData().getPassportPlaceOfIssue())
.build();
passportRepository.saveAndFlush(passportInfo);
UserEntity userEntity = UserEntity
.builder()
.birthDate(userData.getBirthDate())
.fio(userData.getFio())
.email(userData.getEmail())
.passport(passportInfo)
.password(securityConfiguration.passwordEncoder().encode(userData.getPassword()))
.role(Role.ADMIN)
.contactPhone(userData.getContactPhone().get(0))
.contactPhone1(userData.getContactPhone().get(1))
.status(userData.getStatus())
.firstName(userData.getFirstName())
.lastName(userData.getLastName())
.middleName(userData.getMiddleName())
.build();
userRepository.saveAndFlush(userEntity);
return userEntity;
}
}
| true
|
b4a8c6faf1fb304b128cb1c59fc6097607dc450f
|
Java
|
max333/FixedFontOCR
|
/src/main/java/fixedfontocr/GeneratorOfFontGlyphsWithLeakedPixels.java
|
UTF-8
| 7,373
| 2.71875
| 3
|
[] |
no_license
|
package fixedfontocr;
import fixedfontocr.glyph.FontGlyphWithLeakedPixels;
import fixedfontocr.glyph.FontGlyph;
import fixedfontocr.glyph.LeakingFontGlyph;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* First finds the symbols that leak pixels outside their bounding boxes and then builds all possible
* glyphs by combining pixels from a glyphs and those leaked by its neighbors.
*/
public class GeneratorOfFontGlyphsWithLeakedPixels {
// nonContextualGlyphs: Standard glyphs which do not contain extra pixels from their neighbors.
// Not that a glyph that receives some pixels from neighbors, but those pixels just overlap
// existing pixels, then the glyph is also moved to contextualGlyphs.
protected List<FontGlyph> nonContextualGlyphs;
protected Set<FontGlyphWithLeakedPixels> contextualGlyphs;
protected Set<FontGlyph> allGlyphs;
protected Set<FontGlyph> allGlyphsNotRequiringPrecedingGlyph;
protected Set<FontGlyph> allGlyphsWhichCanStartALine;
protected Set<LeakingFontGlyph> leakersToLeft; // Some can be both leakersToLeft and Right
protected Set<LeakingFontGlyph> leakersToRight;
protected Map<FontGlyph, Set<FontGlyph>> mapGlyphToGlyphOnLeft;
protected Map<FontGlyph, Set<FontGlyph>> mapGlyphToGlyphOnRight;
public GeneratorOfFontGlyphsWithLeakedPixels(List<FontGlyph> originalGlyphs) {
nonContextualGlyphs = new ArrayList<>();
nonContextualGlyphs.addAll(originalGlyphs); // but the leakers are removed below
leakersToLeft = new HashSet<>();
leakersToRight = new HashSet<>();
for (LeakingFontGlyph leaker : LeakingFontGlyph.processAlphabet(originalGlyphs)) {
nonContextualGlyphs.remove(leaker);
if (!leaker.getLeakedPixelsToLeft().isEmpty())
leakersToLeft.add(leaker);
if (!leaker.getLeakedPixelsToRight().isEmpty())
leakersToRight.add(leaker);
}
generateAllCompoundGlyphs();
Set<FontGlyph> newGlyphs = new HashSet<>();
newGlyphs.addAll(mapGlyphToGlyphOnLeft.keySet());
newGlyphs.addAll(mapGlyphToGlyphOnRight.keySet());
contextualGlyphs = new HashSet<>();
for (FontGlyph newGlyph : newGlyphs) {
FontGlyphWithLeakedPixels newContextualGlyph =
new FontGlyphWithLeakedPixels(newGlyph,
mapGlyphToGlyphOnLeft.get(newGlyph), mapGlyphToGlyphOnRight.get(newGlyph));
contextualGlyphs.add(newContextualGlyph);
}
allGlyphs = new HashSet<>();
allGlyphs.addAll(nonContextualGlyphs);
allGlyphs.addAll(contextualGlyphs);
allGlyphsNotRequiringPrecedingGlyph = new HashSet<>();
allGlyphsNotRequiringPrecedingGlyph.addAll(nonContextualGlyphs);
for (FontGlyphWithLeakedPixels glyph : contextualGlyphs)
if (!glyph.requiresPrecedingGlyph())
allGlyphsNotRequiringPrecedingGlyph.add(glyph);
allGlyphsWhichCanStartALine = new HashSet<>();
allGlyphsWhichCanStartALine.addAll(nonContextualGlyphs);
for (FontGlyphWithLeakedPixels glyph : contextualGlyphs)
if (!glyph.canStartLine())
allGlyphsWhichCanStartALine.add(glyph);
}
protected final void generateAllCompoundGlyphs() {
mapGlyphToGlyphOnLeft = new HashMap<>();
mapGlyphToGlyphOnRight = new HashMap<>();
Set<FontGlyph> nonContextualPlusLeakers = new HashSet<>();
nonContextualPlusLeakers.addAll(nonContextualGlyphs);
nonContextualPlusLeakers.addAll(leakersToLeft);
nonContextualPlusLeakers.addAll(leakersToRight);
HashSet<LeakingFontGlyph> leakersToLeftPlusNull = new HashSet<>();
leakersToLeftPlusNull.addAll(leakersToLeft);
leakersToLeftPlusNull.add(null);
HashSet<LeakingFontGlyph> leakersToRightPlusNull = new HashSet<>();
leakersToRightPlusNull.addAll(leakersToRight);
leakersToRightPlusNull.add(null);
for (LeakingFontGlyph glyphOnLeft : leakersToRightPlusNull)
for (FontGlyph centerGlyph : nonContextualPlusLeakers)
for (LeakingFontGlyph glyphOnRight : leakersToLeftPlusNull) {
FontGlyph modifiedGlyphOnLeft = addPixelsToMiddleGlyph(null, glyphOnLeft, centerGlyph);
FontGlyph modifiedGlyphOnRight = addPixelsToMiddleGlyph(centerGlyph, glyphOnRight, null);
FontGlyph modifiedCenterGlyph = addPixelsToMiddleGlyph(glyphOnLeft, centerGlyph, glyphOnRight);
addToMapsLeftAndRight(modifiedGlyphOnLeft, modifiedCenterGlyph);
addToMapsLeftAndRight(modifiedCenterGlyph, modifiedGlyphOnRight);
}
}
/**
* The middleGlyph will have some pixels added in its bounding box if the left/right glyphs leak
* pixels in the right direction.
*/
protected FontGlyph addPixelsToMiddleGlyph(FontGlyph leftGlyph, FontGlyph middleGlyph, FontGlyph rightGlyph) {
if (middleGlyph == null)
return null;
List<Point> activePixels = new ArrayList<>();
activePixels.addAll(middleGlyph.getActivePixels());
if (leftGlyph != null && (leftGlyph instanceof LeakingFontGlyph))
for (Point pixel : ((LeakingFontGlyph) leftGlyph).getLeakedPixelsToRight())
activePixels.add(new Point(pixel.x - leftGlyph.getDimension().width, pixel.y));
if (rightGlyph != null && (rightGlyph instanceof LeakingFontGlyph))
for (Point pixel : ((LeakingFontGlyph) rightGlyph).getLeakedPixelsToLeft())
activePixels.add(new Point(pixel.x + middleGlyph.getDimension().width, pixel.y));
return new FontGlyph(middleGlyph.getGeneratingString(), middleGlyph.getFont(),
middleGlyph.getDimension(), activePixels);
}
/**
* One of the two glyphs can be null and the null value will be added to the corresponding map of
* the other non-null glyph.
*/
protected void addToMapsLeftAndRight(FontGlyph leftGlyph, FontGlyph rightGlyph) {
if (leftGlyph != null) {
if (!mapGlyphToGlyphOnRight.containsKey(leftGlyph))
mapGlyphToGlyphOnRight.put(leftGlyph, new HashSet<FontGlyph>());
mapGlyphToGlyphOnRight.get(leftGlyph).add(rightGlyph);
}
if (rightGlyph != null) {
if (!mapGlyphToGlyphOnLeft.containsKey(rightGlyph))
mapGlyphToGlyphOnLeft.put(rightGlyph, new HashSet<FontGlyph>());
mapGlyphToGlyphOnLeft.get(rightGlyph).add(leftGlyph);
}
}
public Set<FontGlyph> getAllGlyphs() {
return Collections.unmodifiableSet(allGlyphs);
}
/**
* All glyphs that can start a line. This includes all FontGlyphs which are not
* ContextualFontGlyphs, and those ContextualFontGlyphs which only had pixels leaked from the
* right.
*/
public Set<FontGlyph> getAllGlyphsNotRequiringPrecedingGlyph() {
return Collections.unmodifiableSet(allGlyphsNotRequiringPrecedingGlyph);
}
public Set<FontGlyph> getAllGlyphsWhichCanStartALine() {
return Collections.unmodifiableSet(allGlyphsWhichCanStartALine);
}
public Set<FontGlyphWithLeakedPixels> getContextualGlyphs() {
return Collections.unmodifiableSet(contextualGlyphs);
}
public List<FontGlyph> getNonContextualGlyphs() {
return Collections.unmodifiableList(nonContextualGlyphs);
}
}
| true
|
f9d9cbd11fb949e71f3b28b9720533fc127999d9
|
Java
|
MohammadFaizan007/kkmShopping
|
/core/src/main/java/kkm/com/core/model/request/RequestAddCart.java
|
UTF-8
| 2,255
| 2.015625
| 2
|
[] |
no_license
|
package kkm.com.core.model.request;
import com.google.gson.annotations.SerializedName;
public class RequestAddCart {
@SerializedName("SrNo")
private String srNo;
@SerializedName("ProductAmt")
private String productAmt;
@SerializedName("Pk_ProductDetailId")
private String pkProductDetailId;
@SerializedName("ProductQty")
private String productQty;
@SerializedName("ProductId")
private String productId;
@SerializedName("AddedBy")
private String addedBy;
@SerializedName("SizeID")
private String sizeID;
public String getSrNo() {
return srNo;
}
public void setSrNo(String srNo) {
this.srNo = srNo;
}
public String getProductAmt() {
return productAmt;
}
public void setProductAmt(String productAmt) {
this.productAmt = productAmt;
}
public String getPkProductDetailId() {
return pkProductDetailId;
}
public void setPkProductDetailId(String pkProductDetailId) {
this.pkProductDetailId = pkProductDetailId;
}
public String getProductQty() {
return productQty;
}
public void setProductQty(String productQty) {
this.productQty = productQty;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getAddedBy() {
return addedBy;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
public String getSizeID() {
return sizeID;
}
public void setSizeID(String sizeID) {
this.sizeID = sizeID;
}
@Override
public String toString() {
return
"RequestAddCart{" +
"srNo = '" + srNo + '\'' +
",productAmt = '" + productAmt + '\'' +
",pk_ProductDetailId = '" + pkProductDetailId + '\'' +
",productQty = '" + productQty + '\'' +
",productId = '" + productId + '\'' +
",addedBy = '" + addedBy + '\'' +
",sizeID = '" + sizeID + '\'' +
"}";
}
}
| true
|
15c30ae999c77b430f054d9a5b3de80a7a243fdd
|
Java
|
alessiofiore/gestguide
|
/gestguide-core/src/main/java/it/mdps/gestguide/database/dao/GenericDao.java
|
UTF-8
| 1,146
| 2.28125
| 2
|
[] |
no_license
|
package it.mdps.gestguide.database.dao;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
public abstract class GenericDao<T> implements IGenericDao<T> {
@Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
@Override
@Transactional
public T save(T t) {
Session session = sessionFactory.getCurrentSession();
return (T) session.save(t);
}
@Override
@Transactional
public void saveOrUpdate(T t) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(t);
}
@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly=true)
public T find(Class<T> type, Serializable id) {
Session session = sessionFactory.getCurrentSession();
return (T) session.get(type, id);
}
@Override
@Transactional
public T update(T t) {
// TODO Auto-generated method stub
return null;
}
// public abstract void delete(Object id);
@Override
public abstract List<T> findAll();
}
| true
|
091660f367817e38d8e4096efcf60f5d090f38e9
|
Java
|
atricore/atricore-idbus
|
/idojos/idbus-virtual-identitystore/src/main/java/org/atricore/idbus/idojos/virtualidentitystore/rule/QualifyUID.java
|
UTF-8
| 1,204
| 2.125
| 2
|
[] |
no_license
|
package org.atricore.idbus.idojos.virtualidentitystore.rule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.atricore.idbus.idojos.virtualidentitystore.UIDMappingRule;
import org.atricore.idbus.idojos.virtualidentitystore.BaseUIDMappingRule;
import java.util.Collection;
/**
* @author <a href="mailto:gbrigand@josso.org">Gianluca Brigandi</a>
* @version $Id: QualifyUID.java 1644 2010-07-27 19:31:39Z sgonzalez $
* @org.apache.xbean.XBean element="qualify-uid"
* <p/>
* Issue a qualified virtual user identifier entry by prefixing a source entry with
* the supplied namespace URI.
*/
public class QualifyUID extends BaseUIDMappingRule implements UIDMappingRule {
private static final Log logger = LogFactory.getLog(QualifyUID.class);
private String namespace;
public String transform(String jointUID) {
logger.debug("Qualifying UID [" + jointUID + "] with namespace [" + namespace + "]");
return getNamespace() != null ? getNamespace() + ",uid=" + jointUID : null;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
| true
|
66180145d6f6987fdc85a75867918ecb00bee8b9
|
Java
|
yxbgithub/OA
|
/OA/src/com/baidu/OA/util/OAListener.java
|
UTF-8
| 2,140
| 2.296875
| 2
|
[] |
no_license
|
package com.baidu.OA.util;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.baidu.OA.model.Privilege;
import com.baidu.OA.service.PrivilegeService;
public class OAListener implements ServletContextListener {
private Logger logger = LoggerFactory.getLogger(OAListener.class);
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent sce) {
//从event中获取servletContext对象
ServletContext application = sce.getServletContext();
//通过spring为我们提供的工具类罗去servletContext里面的applicationContext属性
ApplicationContext factory = WebApplicationContextUtils.getWebApplicationContext(application);
//取出顶级权限
PrivilegeService privilegeService = (PrivilegeService) factory.getBean("privilegeService");
List<Privilege> topPrivileges = privilegeService.findTopPrivileges();
//将顶级权限放入application中,以备后面使用
application.setAttribute("topPrivileges", topPrivileges);
System.out.println("------------------------已经将topPrivileges放入application中----------------------");
logger.info("------------------------已经将topPrivileges放入application中----------------------");
//将所有权限的url放入list当中加入application(去掉权限url为null为重复的)
List<String> privilegeUrls = privilegeService.findAllUrls();
application.setAttribute("privilegeUrls", privilegeUrls);
logger.info("------------------------已经将privilegeUrls放入application中----------------------");
System.out.println("------------------------已经将privilegeUrls放入application中----------------------");
}
}
| true
|
57fe9f8316f2cf15db07b21864b35b5e7e15481b
|
Java
|
sonveertomar/IIITB_C_DS
|
/comp/PDF.java
|
UTF-8
| 462
| 2.359375
| 2
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
class PDF{
public static void main(String arr[])throws IOException{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
char charArr[]=br.readLine().toCharArray();
System.out.println(Arrays.toString(charArr));
String word=br.readLine();
System.out.println(word);
br.close();
}
}
| true
|
05d7f6a84e1da8c4320218ec625e1a0dc1959adf
|
Java
|
ErikWittern/sfm-toolsuite
|
/edu.kit.sfm.editor/src/edu/kit/sfm/utils/SFMPersistencyOperations.java
|
UTF-8
| 2,411
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
package edu.kit.sfm.utils;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import edu.kit.sfm.servicefeaturemodel.Service;
public class SFMPersistencyOperations {
/* LOAD EMF MODELS - procedures */
public static Service loadModel(String modelName) {
// Load service model:
String projectName = "";
IEditorPart editorPart = (IEditorPart) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart
.getEditorInput();
IFile file = input.getFile();
IProject activeProject = file.getProject();
projectName = activeProject.getName();
}
String path = Platform.getLocation().toString() + "/" + projectName
+ "/" + modelName;
ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = resourceSet.getResource(URI.createFileURI(path),
true);
return (Service) resource.getContents().get(0);
}
public static Service loadModelFromWorkspace(String modelName) {
/* local variables */
URI workspaceURI = null;
// construct workspace URI
IEditorPart editorPart = (IEditorPart) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart
.getEditorInput();
IFile file = input.getFile();
IProject activeProject = file.getProject();
String projectName = activeProject.getName();
String path = "/" + projectName + "/" + modelName;
workspaceURI = URI.createPlatformResourceURI(path, true);
}
// generate resource
ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = resourceSet.getResource(workspaceURI, true);
return (Service) resource.getContents().get(0);
}
/* save EMF Model */
public static void saveModel(Resource resource) {
// save
try {
resource.save(null);
// error handling
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
c644ce1de7a5fd54e1951b16a30abc0756abec9f
|
Java
|
linkingluck/clockwork-midware
|
/midware-ormcache/src/main/java/com/linkingluck/midware/ormcache/service/Filter.java
|
UTF-8
| 491
| 2.296875
| 2
|
[] |
no_license
|
package com.linkingluck.midware.ormcache.service;
import com.linkingluck.midware.ormcache.IEntity;
/**
* 查询结果过滤器
*
* @param <T>
*/
@SuppressWarnings("rawtypes")
public interface Filter<T extends IEntity> {
/**
* 检查是否排除该实体
* @param entity 被检查的实体,不会为null
* @return true:排除被检查的实体(不会出现在返回结果中),false:不排除被检查的实体(会出现在返回结果中)
*/
boolean isExclude(T entity);
}
| true
|
89b4078c9b957e366fce504e4ef00a05f9e369ed
|
Java
|
imdevelopco/caja-siase
|
/src/siase_caja/models/ConexionBD.java
|
UTF-8
| 1,391
| 2.578125
| 3
|
[] |
no_license
|
/*
* 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 siase_caja.models;
import java.sql.*;
import java.util.Properties;
/**
*
* @author SOLUCIONES
*/
public class ConexionBD {
public static Connection conexion() throws SQLException{
String url = "jdbc:postgresql://localhost:5432/caja_Test";
Properties conectionData = new Properties();
conectionData.setProperty("user","postgres");
conectionData.setProperty("password","postgres");
//conectionData.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, conectionData);
return conn;
}
public static void test() throws SQLException{
Connection conn = conexion();
conn.setAutoCommit(false);
// Turn use of the cursor on.
try (Statement st = conn.createStatement()) {
// Turn use of the cursor on.
try (ResultSet rs = st.executeQuery("SELECT * FROM public.\"Servicio\"")) {
while (rs.next()) {
System.out.println(rs.getString(1) + "||" + rs.getString(2) + "||" + rs.getString(3) );
}
// Close the statement.
}
}
}
}
| true
|
323e40f6e80035af6ec72d24823f1b246346c4a1
|
Java
|
dalia-maher/Shopping
|
/src/java/beans/ShoppingCart.java
|
UTF-8
| 829
| 2.734375
| 3
|
[] |
no_license
|
package beans;
/**
*
* @author TahanyFawzy
*/
public class ShoppingCart
{
private Product product;
private User customer;
private int quantity;
public ShoppingCart() {
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public User getCustomer() {
return customer;
}
public void setCustomer(User customer) {
this.customer = customer;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public ShoppingCart(Product product, User customer, int quantity) {
this.product = product;
this.customer = customer;
this.quantity = quantity;
}
}
| true
|
5bf6037eafef3426b20715f14f799c80165a3424
|
Java
|
Hypario/Memory
|
/src/dut/archilog/intro/GraphicalCell.java
|
UTF-8
| 769
| 2.875
| 3
|
[] |
no_license
|
package dut.archilog.intro;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
public class GraphicalCell extends Cell {
private final CellButton ui;
public GraphicalCell(char content) {
super(content);
ui = new CellButton(this.toString(), this);
ui.setFont(new Font(ui.getFont().getFontName(), Font.BOLD, 30));
ui.setPreferredSize(new Dimension(80, 80));
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
ui.setText(this.toString());
if (visible) {
ui.setBackground(new Color(71, 100, 111));
ui.setEnabled(false);
} else {
ui.setBackground(new JButton().getBackground());
ui.setEnabled(true);
}
}
public CellButton getUI() {
return ui;
}
}
| true
|
f5f2e6e6f7b640cd8cd4466ea6e6fa3c1fd7e8dc
|
Java
|
doveylovey/java8-in-action
|
/src/main/java/com/study/optional/OptionalUser.java
|
UTF-8
| 423
| 1.914063
| 2
|
[] |
no_license
|
package com.study.optional;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List;
/**
* Optional 测试用的 User 实体类
*
* @author Administrator
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class OptionalUser {
private Long userId;
private String userName;
private List<OptionalOrder> orderList;
}
| true
|
1efd5bcd27e47f6d7d01ec63a1b1d6cbe4358a14
|
Java
|
KajP/Communicator-2.0
|
/app/src/main/java/edu/kajpitynski/communicator2/ui/chathistory/ChatHistoryViewModel.java
|
UTF-8
| 1,400
| 2.265625
| 2
|
[] |
no_license
|
package edu.kajpitynski.communicator2.ui.chathistory;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import edu.kajpitynski.communicator2.application.BasicApp;
import edu.kajpitynski.communicator2.db.relations.ConversationWithMessages;
import edu.kajpitynski.communicator2.repository.MessageRepository;
public class ChatHistoryViewModel extends ViewModel {
private MessageRepository repository;
private LiveData<ConversationWithMessages> conversation;
public ChatHistoryViewModel(@NonNull Application app, long id) {
repository = ((BasicApp) app).getRepository();
conversation = repository.getConversationWithMessages(id);
}
public LiveData<ConversationWithMessages> getConversation() {
return conversation;
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private final Application app;
private final long id;
public Factory(Application app, long id) {
this.app = app;
this.id = id;
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new ChatHistoryViewModel(app, id);
}
}
}
| true
|
e51a8bd97136d49b365989e8720ea1af493b1e41
|
Java
|
Yeami/parallel-computational-processes
|
/5-laboratory-work/src/Main.java
|
UTF-8
| 671
| 3.75
| 4
|
[
"MIT"
] |
permissive
|
class Main {
public static void main(String[] args) {
final double A = 1, B = 2, C = 3;
System.out.println("--- Initial data ---\nA: " + A + "\nB: " + B + "\nC: " + C + "\n--------------------\n");
ExpCalculator firstPair = new ExpCalculator(A, '+', C);
ExpCalculator secondPair = new ExpCalculator(firstPair, '-', B);
ExpCalculator thirdPair = new ExpCalculator(A, '-', C);
ExpCalculator fourthPair = new ExpCalculator(thirdPair, '*', B);
ExpCalculator fifthPair = new ExpCalculator(secondPair, '/', fourthPair);
System.out.println("Result:\n(A+C-B) / (B*(A-C)) = " + fifthPair.getResult());
}
}
| true
|
d945a2e6c02b0321201f612a42b31e5f899b49f7
|
Java
|
kayazas123/Modern-API-Development-with-Spring-and-Spring-Boot
|
/Chapter14/src/main/java/com/packt/modern/api/instrumentation/TracingInstrumentation.java
|
UTF-8
| 3,318
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package com.packt.modern.api.instrumentation;
import graphql.ExecutionResult;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.InstrumentationState;
import graphql.execution.instrumentation.SimpleInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters;
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLOutputType;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author : github.com/sharmasourabh
* @project : chapter14 - Modern API Development with Spring and Spring Boot
**/
@Component
public class TracingInstrumentation extends SimpleInstrumentation {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Override
public InstrumentationState createState() {
return new TracingState();
}
@Override
public InstrumentationContext<ExecutionResult> beginExecution(
InstrumentationExecutionParameters parameters) {
TracingState tracingState = parameters.getInstrumentationState();
tracingState.startTime = System.currentTimeMillis();
return super.beginExecution(parameters);
}
@Override
public DataFetcher<?> instrumentDataFetcher(DataFetcher<?> dataFetcher,
InstrumentationFieldFetchParameters parameters) {
if (parameters.isTrivialDataFetcher()) {
return dataFetcher;
}
return environment -> {
long initTime = System.currentTimeMillis();
Object result = dataFetcher.get(environment);
String msg = "Instrumentation of datafetcher {} took {} ms";
if (result instanceof CompletableFuture) {
((CompletableFuture<?>) result).whenComplete((r, ex) -> {
long timeTaken = System.currentTimeMillis() - initTime;
LOG.info(msg, findDatafetcherTag(parameters), timeTaken);
});
} else {
long timeTaken = System.currentTimeMillis() - initTime;
LOG.info(msg, findDatafetcherTag(parameters), timeTaken);
}
return result;
};
}
@Override
public CompletableFuture<ExecutionResult> instrumentExecutionResult(
ExecutionResult executionResult, InstrumentationExecutionParameters parameters) {
TracingState tracingState = parameters.getInstrumentationState();
long timeTaken = System.currentTimeMillis() - tracingState.startTime;
LOG.info("Request processing took: {} ms", timeTaken);
return super.instrumentExecutionResult(executionResult, parameters);
}
private String findDatafetcherTag(InstrumentationFieldFetchParameters parameters) {
GraphQLOutputType type = parameters.getExecutionStepInfo().getParent().getType();
GraphQLObjectType parent;
if (type instanceof GraphQLNonNull) {
parent = (GraphQLObjectType) ((GraphQLNonNull) type).getWrappedType();
} else {
parent = (GraphQLObjectType) type;
}
return parent.getName() + "." + parameters.getExecutionStepInfo().getPath().getSegmentName();
}
static class TracingState implements InstrumentationState {
long startTime;
}
}
| true
|
dd551d09c7132c80506e75cf9b7eda517e7c10da
|
Java
|
valeriididenko/webService
|
/src/main/java/com/rest/service/impl/UserRoleServiceImpl.java
|
UTF-8
| 1,260
| 2.203125
| 2
|
[] |
no_license
|
package com.rest.service.impl;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rest.entity.UserRole;
import com.rest.repository.UserRoleRepository;
import com.rest.service.UserRoleService;
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {
@Autowired
private UserRoleRepository userRoleRepository;
@Override
public void deleteUserRole(UserRole userRole) {
userRoleRepository.delete(userRole);
}
@Override
public void saveOrUpdateUserRole(UserRole userRole) {
userRoleRepository.save(userRole);
}
@Override
public List<UserRole> gerUserRolesByUserId(int userId) {
return userRoleRepository.findByUserId(userId);
}
@Override
public String getStringWithUserRolesByUserId(int userId) {
List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
StringBuilder roles = new StringBuilder();
for (UserRole role : userRoles) {
roles.append(role.getRole().substring(5).toLowerCase());
roles.append("; ");
}
return roles.toString();
}
}
| true
|
771512858c230364f2c0a537e69a76f87b568e83
|
Java
|
sebastianzillessen/hdr-generator
|
/src/View/Log.java
|
UTF-8
| 642
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
package View;
/**
* Interface to provide some basic debugging and logging functionality.
*
* @author sebastianzillessen
*/
public interface Log {
/**
* Appends a new Line with the object s as output (calls to String on it e.g)
*
* @param s the object to print
*/
public void append(Object s);
/**
* appends the object s as output (no new line before)
*
* @param s the object to print
*/
public void write(Object s);
/**
* Displays an alert which is normally used when an error occurs.
* @param s the message to display.
*/
public void alert(String s);
}
| true
|
29f93e77ed2d83f2bb9d44669b991de49ce9196e
|
Java
|
xyj155/RVideoPlayer
|
/pilivideo/src/main/java/com/dancechar/pilivideo/ScreenUtil.java
|
UTF-8
| 2,374
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.dancechar.pilivideo;
import android.content.Context;
import android.util.DisplayMetrics;
import java.lang.reflect.Field;
/**
* Created by Administrator on 2018/5/7.
*/
public class ScreenUtil {
/**
* 根据手机分辨率将dp转为px单位
*/
public static int dip2px(Context mContext, float dpValue) {
final float scale = mContext.getResources()
.getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context mContext, float pxValue) {
final float scale = mContext.getResources()
.getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 屏幕宽高
*
* @param mContext 上下文
* @return
*/
private static int[] getScreenSize(Context mContext) {
DisplayMetrics dm = mContext
.getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
return new int[]{screenWidth, screenHeight};
}
/**
* 获取状态栏高度
*
* @param mContext 上下文
* @return
*/
public static int getStatusBarHeight(Context mContext) {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = mContext.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
/**
* 获取手机屏幕的宽度
*
* @param mContext 上下文
* @return
*/
public static int getScreenWidth(Context mContext) {
int screen[] = getScreenSize(mContext);
return screen[0];
}
/**
* 获取手机屏幕的高度
*
* @param mContext 上下文
* @return
*/
public static int getScreenHeight(Context mContext) {
int screen[] = getScreenSize(mContext);
return screen[1];
}
}
| true
|
010de94200097baf6346331465e46b01d29ead29
|
Java
|
1tsuki/sante
|
/WEB-INF/src/com/astrider/sfc/app/lib/BaseModel.java
|
UTF-8
| 310
| 2.078125
| 2
|
[] |
no_license
|
package com.astrider.sfc.app.lib;
/**
* Model基底クラス
*
* @author astrider
* <p>
* FlashMessageを持つ
* </p>
*/
public class BaseModel {
protected FlashMessage flashMessage = new FlashMessage();
public FlashMessage getFlashMessage() {
return flashMessage;
}
}
| true
|
38bb34711cf1d0ae7deaf6f48a272a009c6ba2d5
|
Java
|
BGratta94/The-Family-Game
|
/The Family/src/the/family/TheFamily.java
|
UTF-8
| 1,095
| 3.28125
| 3
|
[] |
no_license
|
package the.family;
/**
*
* @author Brandon
*/
public class TheFamily
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
/*
The Family is about a top notch detective deep upstate who, with his partner,
are investigating the disappearance of a teenaged girl and her friends. Their leads eventually
point to a family living in a private residence, a large area, away from most
of the towns. Upon arrival and snooping around, You decide to knock and get
invited in while your partner sneakily explores the outer grounds. You meet the family
and are talking and just starting to ask questions when your partner is overheard. You try to
distract the family, but are ultimately caught and both of you knocked out. your escape
not only leads to the discovery of the little girl, but decides the fate of your partner
as well.
*/
TitleScreen.runGame();
}
}
| true
|
60b3afb6662583d841cd102f6c95830bd07b6654
|
Java
|
Lokesh-VJ/BloodBanking
|
/Bloodbanking/src/main/java/net/bloodbanking/dao/LoginDao.java
|
UTF-8
| 2,295
| 1.75
| 2
|
[] |
no_license
|
package net.bloodbanking.dao;
import java.util.List;
import net.bloodbanking.dto.BloodBankStockDTO;
import net.bloodbanking.dto.BloodDonationDTO;
import net.bloodbanking.dto.BloodGroupMstDTO;
import net.bloodbanking.dto.BloodRequestDTO;
import net.bloodbanking.dto.EnquiryFormDTO;
import net.bloodbanking.dto.FeedbackDTO;
import net.bloodbanking.dto.LocationAddressDTO;
import net.bloodbanking.dto.RegistrationDTO;
import net.bloodbanking.dto.SecurityQuestionDTO;
import net.bloodbanking.dto.UserTypeMstDTO;
import net.bloodbanking.entity.BloodGroupMst;
import net.bloodbanking.entity.EnquiryForm;
import net.bloodbanking.entity.Feedback;
import net.bloodbanking.entity.LocationAddress;
import net.bloodbanking.entity.PatientBloodbankMapping;
import net.bloodbanking.entity.Registration;
import net.bloodbanking.entity.SecurityQuestion;
import net.bloodbanking.entity.UserTypeMapping;
import net.bloodbanking.entity.UserTypeMst;
public interface LoginDao extends BaseDao{
public Registration loadRegistration(RegistrationDTO registrationDTO);
public List<UserTypeMst> listUserTypes(UserTypeMstDTO userTypeMstDTO);
public List<SecurityQuestion> listSecurityQuestions(SecurityQuestionDTO securityQuestionDTO);
public List<BloodGroupMst> listBloodGroups(BloodGroupMstDTO bloodGroupMstDTO);
public UserTypeMst loadUserType(UserTypeMstDTO userTypeMstDTO);
public List<UserTypeMapping> listUserTypeMappings(UserTypeMstDTO userTypeMstDTO);
public BloodGroupMst loadBloodGroup(BloodGroupMstDTO bloodGroupMstDTO);
public LocationAddress loadLocationAddress(LocationAddressDTO locationAddressDTO);
public List<Registration> viewUser(RegistrationDTO registrationDTO);
public List<Feedback> viewFeedback(FeedbackDTO feedbackDTO);
public List<EnquiryForm> viewEnquiry(EnquiryFormDTO enquiryFormDTO);
public List<BloodDonationDTO> viewBloodDonation(BloodDonationDTO bloodDonationDTO);
public List<BloodRequestDTO> viewBloodRequest(BloodRequestDTO bloodRequestDTO);
public PatientBloodbankMapping loadPatientBloodMapping(BloodRequestDTO bloodRequestDTO);
public List<BloodDonationDTO> viewDonor(RegistrationDTO registrationDTO);
public List<BloodRequestDTO> viewPatient(RegistrationDTO registrationDTO);
public List<BloodBankStockDTO> viewBloodBankStock(RegistrationDTO registrationDTO);
}
| true
|
29c84714f047457f7d4373aa37f0acbfd06ab96c
|
Java
|
SynTax64/BFI
|
/src/HowToSort/sort_with_Comparable/Kreis.java
|
UTF-8
| 637
| 3.71875
| 4
|
[] |
no_license
|
package HowToSort.sort_with_Comparable;
class Kreis implements Geometrie {
protected double radius;
Kreis(double radius) {
this.radius = radius;
}
@Override
public double berechneUmfang() {
return 2 * radius * Math.PI;
}
@Override
public double berechneFlaeche() {
return radius * radius * Math.PI;
}
@Override
public int compareTo(Geometrie other) {
double thisObjektFlaeche = this.berechneFlaeche();
double otherObjektFlaeche = other.berechneFlaeche();
if (thisObjektFlaeche == otherObjektFlaeche)
return 0;
else if (thisObjektFlaeche > otherObjektFlaeche)
return 1;
else
return -1;
}
}
| true
|
e6e47a920aa4b95b9424d5909e20a19f773c3aa2
|
Java
|
art333/booker
|
/src/main/java/com/booker/api/model/AppointmentApi.java
|
UTF-8
| 885
| 2.40625
| 2
|
[] |
no_license
|
package com.booker.api.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode
public class AppointmentApi {
private String id;
private StylistApi stylist;
@ApiModelProperty(notes = "The only valid format is yyyy-MM-dd HH:mm", example = "2020-01-01 16:30")
private LocalDateTime startTime;
private String customerId;
public AppointmentApi() {
}
public AppointmentApi(final String id, final StylistApi stylist, final LocalDateTime startTime, final String customerId) {
this.id = id;
this.stylist = stylist;
this.startTime = startTime;
this.customerId = customerId;
}
@Override
public String toString() {
return String.format("Appointment: %s, %s, %s.", id, startTime, stylist);
}
}
| true
|
5f7e67e882ee6c2162724e5e0620b3308a2ba71e
|
Java
|
RexHHuang/gmall
|
/gmall-cart-service/src/main/java/com/atguigu/gmall/cart/service/impl/CartServiceImpl.java
|
UTF-8
| 3,402
| 2.140625
| 2
|
[] |
no_license
|
package com.atguigu.gmall.cart.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.bean.OmsCartItem;
import com.atguigu.gmall.cart.mapper.CartMapper;
import com.atguigu.gmall.service.CartService;
import com.atguigu.gmall.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class CartServiceImpl implements CartService {
@Autowired
CartMapper cartMapper;
@Autowired
RedisUtil redisUtil;
@Override
public OmsCartItem getCartItemByUser(String memberId, String skuId) {
OmsCartItem cartItem = new OmsCartItem();
cartItem.setMemberId(memberId);
cartItem.setProductSkuId(skuId);
OmsCartItem itemFromDb = cartMapper.selectOne(cartItem);
return itemFromDb;
}
@Override
public void addToCart(OmsCartItem cartItem) {
if (StringUtils.isNotBlank(cartItem.getMemberId())) {
cartMapper.insert(cartItem);
}
}
@Override
public void updateCart(OmsCartItem itemInDb) {
Example e = new Example(OmsCartItem.class);
e.createCriteria().andEqualTo("id", itemInDb.getId());
cartMapper.updateByExampleSelective(itemInDb, e);
}
@Override
public void synchronizeCartCache(String memberId) {
OmsCartItem cartItem = new OmsCartItem();
cartItem.setMemberId(memberId);
List<OmsCartItem> cartItems = cartMapper.select(cartItem);
Map<String , String> map = new HashMap<>();
for (OmsCartItem item : cartItems) {
item.setTotalPrice(item.getPrice().multiply(item.getQuantity()));
map.put(item.getProductSkuId(), JSON.toJSONString(item));
}
// 同步到redis缓存中
final Jedis jedis = redisUtil.getJedis();
jedis.del("user:" + memberId + ":cart");
jedis.hmset("user:" + memberId + ":cart", map);
jedis.close();
}
@Override
public List<OmsCartItem> cartList(String memberId) {
Jedis jedis = null;
List<OmsCartItem> cartItems = new ArrayList<>();
try {
jedis = redisUtil.getJedis();
List<String> hvals = jedis.hvals("user:" + memberId + ":cart");
for (String hval : hvals) {
OmsCartItem cartItem = JSON.parseObject(hval, OmsCartItem.class);
// cartItem.setTotalPrice(cartItem.getPrice().multiply(cartItem.getQuantity()));
cartItems.add(cartItem);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
jedis.close();
}
return cartItems;
}
@Override
public void checkCart(String isChecked, String skuId, String memberId) {
Example e = new Example(OmsCartItem.class);
e.createCriteria().andEqualTo("memberId", memberId).andEqualTo("productSkuId", skuId);
OmsCartItem cartItem = new OmsCartItem();
cartItem.setIsChecked(isChecked);
cartMapper.updateByExampleSelective(cartItem, e);
// 缓存同步
synchronizeCartCache(memberId);
}
}
| true
|
af59e9839620a11fc670a32579bad62f46287e99
|
Java
|
Loongson2015/gz7class
|
/demo1/src/com/shop/TestDemo1.java
|
UTF-8
| 232
| 1.5625
| 2
|
[] |
no_license
|
package com.shop;
public class TestDemo1 {
public static void main(String[] args) {
System.out.println("这是我是每一次使用idea提交代码.....");
System.out.println("help git。。。。。");
}
}
| true
|
9e18bf7974b57bed1c5509115cde5db0b2400e9b
|
Java
|
eddiefiggie/CSVForJava
|
/src/com/eddiefiggie/util/Main.java
|
UTF-8
| 375
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package com.eddiefiggie.util;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String filename = "test.txt";
char delimiter = ',';
int header = 1;
CSVHandler csv = new CSVHandler(filename, delimiter, header);
for (String s : csv.getData()) {
System.out.println(s);
}
}
}
| true
|
20c941d74fc4ad9539d2c2f63e29808abf869317
|
Java
|
do55/SDA-Kurs
|
/rest/src/main/java/pl/mj/sda/javaadv/rest/Konfiguracja.java
|
UTF-8
| 398
| 1.9375
| 2
|
[] |
no_license
|
package pl.mj.sda.javaadv.rest;
import org.glassfish.jersey.server.ResourceConfig;
import pl.mj.sda.javaadv.rest.uslugi.Kalkulator;
import pl.mj.sda.javaadv.rest.uslugi.Serwis;
import pl.mj.sda.javaadv.rest.uslugi.SklepSerwis;
public class Konfiguracja extends ResourceConfig {
public Konfiguracja() {
register(Kalkulator.class);
register(Serwis.class);
register(SklepSerwis.class);
}
}
| true
|
bff2e51cfe23318e86406ad2f1bce766625e56e4
|
Java
|
WesleyOne/gh-demo
|
/netty-demo/src/main/java/io/github/wesleyone/netty/inandoutboundhandler/MyByteToLongDecoder2.java
|
UTF-8
| 559
| 2.421875
| 2
|
[] |
no_license
|
package io.github.wesleyone.netty.inandoutboundhandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import java.util.List;
/**
* @author http://wesleyone.github.io/
*/
public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
System.out.println("MyByteToLongDecoder2 被调用");
out.add(in.readLong());
}
}
| true
|
2cca33d1b6323132bcf12af4de97b85056f88ca6
|
Java
|
weixiaoming666/TextDemo
|
/app/src/main/java/com/example/administrator/textdemo/litepal/LitepalAty.java
|
UTF-8
| 5,559
| 2.171875
| 2
|
[] |
no_license
|
package com.example.administrator.textdemo.litepal;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.EditText;
import com.example.administrator.textdemo.R;
import com.example.administrator.textdemo.utils.ToastUtils;
import com.example.administrator.textdemo.litepal.table.BookBean;
import org.litepal.LitePal;
import java.util.List;
public class LitepalAty extends AppCompatActivity {
private EditText et_name;
private EditText et_id;
private EditText et_address;
private EditText et_price;
private EditText et_cotent;
private EditText et_location;
private EditText et_author;
private EditText et_find;
private String name_find;
private String name_del;
private EditText et_del;
private ListViewCompat lv;
private MyDB myDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liteoal_aty);
bindView();
}
private void bindView() {
et_name = (EditText) findViewById(R.id.et_name);
et_id = (EditText) findViewById(R.id.et_id);
et_address = (EditText) findViewById(R.id.et_address);
et_price = (EditText) findViewById(R.id.et_price);
et_cotent = (EditText) findViewById(R.id.et_cotent);
et_location = (EditText) findViewById(R.id.et_location);
et_author = (EditText) findViewById(R.id.et_author);
et_find = (EditText) findViewById(R.id.find);
et_del = (EditText) findViewById(R.id.del);
lv = (ListViewCompat) findViewById(R.id.lv);
}
private String getEtString(EditText editText) {
String s = null;
String hint = editText.getHint().toString();
if (editText.getText()!=null&&!editText.getText().toString().isEmpty()){
s = editText.getText().toString();
return s;
}else {
return "...";
}
}
private void getDatas(String name, int id, String price, String content, String author, String address,int Type){
switch (Type){
case ConfigType.DB_ADD_TYPE:
BookBean bookBean = new BookBean(name,id,price,content,author,address);
bookBean.save();
break;
case ConfigType.DB_DEL_TYPE:
LitePal.deleteAll(BookBean.class,"name=?",name_del);
break;
case ConfigType.DB_UP_TYPE:
BookBean bookBean1 = new BookBean(name,id,price,content,author,address);
bookBean1.saveOrUpdate("name=?",name_find);
break;
}
}
private void judge(int type) {
String name = getEtString(et_name),price = getEtString(et_price),content = getEtString(et_cotent),location = getEtString(et_location),address = getEtString(et_address);
String author = getEtString(et_author);
int id = 0;
if (name.equals("...")){
ToastUtils.centermsg(this,"书名");
return;
}
if (getEtString(et_id).equals("...")){
ToastUtils.centermsg(this,"id");
return;
}else {
id = Integer.parseInt(getEtString(et_id));
}
if ( address.equals("...")){
ToastUtils.centermsg(this,"地址");
return;
}
if ( price.equals("...")){
ToastUtils.centermsg(this,"价钱");
return;
}
if (content.equals("...")){
ToastUtils.centermsg(this,"内容");
return;
}
if ( location.equals("...")){
location = "";
}
if ( author.equals("...")){
ToastUtils.centermsg(this,"作者");
return;
}
getDatas(name,id,price,content,author,address,type);
}
// 增删改查
public void addBook(View view) {
judge(ConfigType.DB_ADD_TYPE);
}
public void delBook(View view) {
if (et_del.getText().toString().isEmpty()){
ToastUtils.centermsg(this,"删除的书名");
}else {
name_del =et_del.getText().toString();
LitePal.deleteAll(BookBean.class,"name=?",name_del);
}
}
private BookAdapter adapter;
public void findBook(View view) {
List<BookBean> beanList = LitePal.findAll(BookBean.class);
if (beanList.isEmpty()){
ToastUtils.centermsg(this,"查无此书");
}else {
if (adapter == null){
adapter = new BookAdapter(beanList,this);
lv.setAdapter(adapter);
}else {
adapter.dataChanges(beanList);
}
}
}
public void upBook(View view) {
if (et_find.getText().toString().isEmpty()){
ToastUtils.centermsg(this,"请输入更新书名");
}else {
name_find =et_find.getText().toString();
findBookByName(name_find);
}
}
private void findBookByName(String name ){
List<BookBean> beanList = LitePal.where("name=?",name).find(BookBean.class);
if (beanList.isEmpty()){
ToastUtils.centermsg(this,"查无此书");
}else {
if (adapter == null){
adapter = new BookAdapter(beanList,this);
lv.setAdapter(adapter);
}else {
adapter.dataChanges(beanList);
}
}
}
}
| true
|
c56dc401b1c58d8676a31412aceca3e72382fa2b
|
Java
|
virl/vcdroid
|
/vcdroidkit/src/main/java/io/vcdroidkit/controllers/ImagePickerController.java
|
UTF-8
| 6,715
| 2.03125
| 2
|
[] |
no_license
|
package io.vcdroidkit.controllers;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
// Camera/gallery chooser: http://stackoverflow.com/a/12347567/1449965
// Photo path: http://stackoverflow.com/a/27293655/1449965
public class ImagePickerController extends ViewController
{
public interface Listener
{
void onPickedImage(ImageInfo imageInfo);
void onCancel();
}
public class ImageInfo implements Closeable
{
private Uri uri;
private File tempFile;
public ImageInfo()
{
}
@Override
public void close()
{
if(tempFile == null)
return;
tempFile.delete();
tempFile = null;
}
public Uri getUri()
{
return uri;
}
} // ImageInfo
private boolean appeared = false;
private boolean appearedAnimated;
private int REQUEST_TAKE_PHOTO = 5322;
private int REQUEST_SHOW_GALLERY = 5322;
private Listener listener;
private File photoFile;
private Uri photoFileUri;
public ImagePickerController(AppCompatActivity activity, Listener listener)
{
super(activity);
setOpaque(false);
this.listener = listener;
}
@Override
public void onViewDidAppear(boolean animated)
{
super.onViewDidAppear(animated);
appearedAnimated = animated;
if(appeared)
return;
appeared = true;
boolean success;
success = showChooser();
//success = takePhoto();
//success = showGallery();
if(!success)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
dismissController(null, appearedAnimated, new Runnable()
{
@Override
public void run()
{
if(listener != null)
listener.onCancel();
}
});
}
});
return;
}
} // onViewDidAppear
private boolean prepareFile()
{
final String dirPath = getActivity().getExternalCacheDir().getAbsolutePath();
File dir = new File(dirPath);
dir.mkdirs();
try
{
photoFile = File.createTempFile("photo", ".jpg", dir);
}
catch (IOException ex)
{
return false;
}
photoFileUri = Uri.fromFile(photoFile);
return true;
} // prepareFile
private boolean showChooser()
{
if(!prepareFile())
return false;
// Camera.
final List<Intent> cameraIntents = new ArrayList<>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getActivity().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam)
{
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
intent.putExtra("imagePicker_cameraCapture", true);
cameraIntents.add(intent);
}
// Filesystem.
final Intent docsIntent = new Intent(Intent.ACTION_GET_CONTENT);
docsIntent.setType("image/*");
final Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
cameraIntents.add(galleryIntent);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(docsIntent, getTitle());
// Add the camera options.
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[cameraIntents.size()])
);
startActivityForResult(chooserIntent, REQUEST_TAKE_PHOTO);
return true;
}
private boolean takePhoto()
{
if(!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
{
//Logger.error("Camera not found on this device.");
return false;
}
if(!prepareFile())
return false;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
if (intent.resolveActivity(getActivity().getPackageManager()) == null)
{
//Logger.error("Take photo intent cannot be handled.");
return false;
}
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
return true;
} // takePhoto
private boolean showGallery()
{
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
/*Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});*/
startActivityForResult(getIntent, REQUEST_SHOW_GALLERY);
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode != REQUEST_TAKE_PHOTO && requestCode != REQUEST_SHOW_GALLERY)
return;
if(resultCode != Activity.RESULT_OK)
{
//Logger.error("onActivityResult failed with code {}", resultCode);
dismissController(null, appearedAnimated, new Runnable()
{
@Override
public void run()
{
if(listener != null)
listener.onCancel();
}
});
return;
}
final ImageInfo imageInfo = new ImageInfo();
boolean isCamera;
if (intent == null) {
isCamera = true;
} else {
final String action = intent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if(photoFile.length() != 0)
isCamera = true;
if(isCamera)
{
imageInfo.uri = photoFileUri;
imageInfo.tempFile = photoFile;
}
else
{
imageInfo.uri = intent == null ? null : intent.getData();
photoFile.delete();
}
dismissController(null, appearedAnimated, new Runnable()
{
@Override
public void run()
{
if(imageInfo.uri == null)
{
if (listener != null)
listener.onCancel();
return;
}
if (listener != null)
listener.onPickedImage(imageInfo);
}
});
} // onActivityResult
} // ImagePickerController
| true
|
e6fe328a6f4c39496a0feaaf549bb84e3c2937f5
|
Java
|
littlefish-littlefish/ift-java-springboot-sample
|
/src/main/java/com/ibm/bcs/ift/ift_authenticate/exceptions/InternalServerErrorException.java
|
UTF-8
| 1,070
| 1.984375
| 2
|
[] |
no_license
|
/**
*********************************************************************
* Licensed Materials - Property of IBM
* Restricted Materials of IBM
* 5900-A1Y
*
* © Copyright IBM Corp. 2018 All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*********************************************************************
*/
package com.ibm.bcs.ift.ift_authenticate.exceptions;
import com.ibm.bcs.ift.ift_authenticate.responses.InternalErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalServerErrorException extends RuntimeException {
private InternalErrorResponse response;
public InternalServerErrorException(InternalErrorResponse response) {
super(response.getMessage());
this.response = response;
}
public InternalErrorResponse getResponse() {
return this.response;
}
}
| true
|
8b8ddd626513c351067e3d3e8c942fd2e8ff9f07
|
Java
|
aibar/dawn
|
/src/com/vaadin/theme/valo/demo/ValoDemoUI.java
|
UTF-8
| 4,431
| 2.21875
| 2
|
[] |
no_license
|
package com.vaadin.theme.valo.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinRequest;
import com.vaadin.theme.valo.demo.calendarview.CalendarView;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("valo-demo")
@Title("Valo Theme Demo")
public class ValoDemoUI extends UI {
private static final long serialVersionUID = 1L;
VerticalLayout root = new VerticalLayout();
CssLayout content = new CssLayout();
private MenuBar nav = new MenuBar();
private MenuBar userNav = new MenuBar();
private Navigator navigator;
@Override
protected void init(VaadinRequest request) {
Page.getCurrent().setTitle("Valo Theme Demo");
initLayout();
initNav();
initUserNav();
navigator = new Navigator(this, content);
ContactsView contactsView = new ContactsView();
navigator.addView("", contactsView);
navigator.addView(ContactsView.NAME.toLowerCase(), contactsView);
navigator.addView(CalendarView.NAME.toLowerCase(), new CalendarView());
navigator.addView(TasksView.NAME.toLowerCase(), new TasksView());
navigator.addViewChangeListener(new ViewChangeListener() {
@Override
public boolean beforeViewChange(ViewChangeEvent event) {
// TODO Auto-generated method stub
return true;
}
@Override
public void afterViewChange(ViewChangeEvent event) {
if (event.getViewName() == null
|| event.getViewName().equals("")) {
updateNavSelection("contacts");
} else {
updateNavSelection(event.getViewName());
}
}
});
}
private void initLayout() {
root.setSizeFull();
setContent(root);
HorizontalLayout topbar = new HorizontalLayout();
topbar.addStyleName("topbar");
topbar.setWidth("100%");
topbar.setSpacing(true);
root.addComponent(topbar);
content.setSizeFull();
root.addComponent(content);
root.setExpandRatio(content, 1);
Label title = new Label("Tasku");
title.setSizeUndefined();
title.addStyleName("h2");
title.addStyleName("no-margin");
topbar.addComponent(title);
topbar.setComponentAlignment(title, Alignment.MIDDLE_LEFT);
nav.addStyleName("nav");
topbar.addComponent(nav);
userNav.addStyleName("user-nav");
topbar.addComponent(userNav);
topbar.setComponentAlignment(userNav, Alignment.TOP_RIGHT);
}
private void initNav() {
nav.addItem(ContactsView.NAME, navCommand).setCheckable(true);
nav.addItem(CalendarView.NAME, navCommand).setCheckable(true);
nav.addItem(TasksView.NAME, navCommand).setCheckable(true);
}
private void initUserNav() {
MenuItem username = userNav.addItem("Jouni Koivuviita",
FontAwesome.CHEVRON_DOWN, null);
username.addItem("Edit Profile", null);
username.addItem("Settings", null);
username.addSeparator();
username.addItem("Sign Out", null);
}
private Command navCommand = new Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
updateNavSelection(selectedItem.getText());
navigator.navigateTo(selectedItem.getText().toLowerCase());
}
};
private void updateNavSelection(String selectedItem) {
for (MenuItem item : nav.getItems()) {
item.setChecked(item.getText().toLowerCase()
.equals(selectedItem.toLowerCase()));
}
}
void navigateTo(String menuItem) {
for (MenuItem item : nav.getItems()) {
if (item.getText().toLowerCase().equals(menuItem.toLowerCase())) {
navCommand.menuSelected(item);
return;
}
}
}
}
| true
|
7a71153ae573a74a6b53bf37d1f0a63cb778d44e
|
Java
|
Markoy8/Foundry
|
/Components/TextCore/Test/gov/sandia/cognition/text/document/DefaultDateFieldTest.java
|
UTF-8
| 2,854
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
/*
* File: DefaultDateFieldTest.java
* Authors: Justin Basilico
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright December 22, 2009, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government. Export
* of this program may require a license from the United States Government.
* See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.text.document;
import java.text.DateFormat;
import java.util.Date;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for class DefaultDateField.
*
* @author Justin Basilico
*/
public class DefaultDateFieldTest
{
/**
* Creates a new test.
*/
public DefaultDateFieldTest()
{
super();
}
/**
* Test of constructors of class DefaultDateField.
*/
@Test
public void testConstructors()
{
String name = null;
Date date = null;
DefaultDateField instance = new DefaultDateField();
assertSame(name, instance.getName());
assertSame(date, instance.getDate());
name = "something awesome";
date = new Date(1234567);
instance = new DefaultDateField(name, date);
assertSame(name, instance.getName());
assertSame(date, instance.getDate());
}
/**
* Test of getText method, of class DefaultDateField.
*/
@Test
public void testGetText()
{
String name = "something";
Date date = new Date();
DefaultDateField instance = new DefaultDateField(name, date);
assertEquals(DateFormat.getDateTimeInstance().format(date),
instance.getText());
instance.setDate(null);
assertEquals(null, instance.getText());
}
/**
* Test of getDate method, of class DefaultDateField.
*/
@Test
public void testGetDate()
{
this.testSetDate();
}
/**
* Test of setDate method, of class DefaultDateField.
*/
@Test
public void testSetDate()
{
Date date = null;
DefaultDateField instance = new DefaultDateField();
assertSame(date, instance.getDate());
date = new Date();
instance.setDate(date);
assertSame(date, instance.getDate());
date = new Date(987654321);
instance.setDate(date);
assertSame(date, instance.getDate());
date = null;
instance.setDate(date);
assertSame(date, instance.getDate());
date = new Date(0);
instance.setDate(date);
assertSame(date, instance.getDate());
date = new Date();
instance.setDate(date);
assertSame(date, instance.getDate());
}
}
| true
|
4228b60880f971f68dc38ca8500e3d9e3b771636
|
Java
|
edianzuxiehui/api
|
/api/api-permission/api-permission-service/src/main/java/com/xiehui/api/permission/service/user/UserServiceImpl.java
|
UTF-8
| 4,104
| 2.421875
| 2
|
[] |
no_license
|
package com.xiehui.api.permission.service.user;
import java.util.concurrent.*;
import javax.annotation.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import com.xiehui.api.common.exception.APIException;
import com.xiehui.api.common.util.EncryptHelper;
import com.xiehui.api.permission.constant.CUserStatus;
import com.xiehui.api.permission.repository.database.DUser;
import com.xiehui.api.permission.repository.database.DUserDAO;
import com.xiehui.api.permission.repository.redis.RTokenUserValue;
import com.xiehui.api.permission.repository.redis.RUserTokenValue;
import com.xiehui.api.permission.secret.Authenticator;
/**
* 用户服务实现类
*
* @author xiehui
*
*/
@Service("userService")
public class UserServiceImpl implements UserService {
/** DAO相关 */
/** 用户DAO */
@Resource(name = "dUserDAO")
private DUserDAO dUserDAO = null;
/** 令牌用户值 */
@Resource(name = "rTokenUserValue")
private RTokenUserValue rTokenUserValue = null;
/** 用户令牌值 */
@Resource(name = "rUserTokenValue")
private RUserTokenValue rUserTokenValue = null;
/** 属性相关 */
/** 令牌超时时间(毫秒) */
@Value("${user.token.timeout}")
private Long tokenTimeout = null;
/**
* 获取我的标识
*
* @param token
* 登录令牌
* @return 我的标识
* @throws APIException
* API异常
*/
@Override
public Long getMyId(String token) throws APIException {
// 初始化
Long myId = rTokenUserValue.get(token);
// 重设超时
if (myId != null) {
rTokenUserValue.setExpire(token, tokenTimeout, TimeUnit.MILLISECONDS);
}
// 返回数据
return myId;
}
/**
* 登录
*
* @param email
* 用户邮箱
* @param password
* 用户密码
* @return 登录令牌
* @throws APIException
* API异常
*/
@Override
public String login(String email, String password) throws APIException {
// 检查用户
DUser dUser = dUserDAO.getByEmail(email);
if (dUser == null) {
throw new APIException("用户不存在");
}
if (dUser.getStatus().equals(CUserStatus.DISABLE.getValue())) {
throw new APIException("用户被禁用");
}
String secret = dUser.getLoginSecret();
boolean validatorSecret = Authenticator.check(secret, Integer.parseInt(password));
// 方便测试
validatorSecret = true;
if (!validatorSecret) {
throw new APIException("用户密码错误");
}
// 删除令牌
String token = rUserTokenValue.get(dUser.getId());
if (token != null) {
rTokenUserValue.remove(token);
}
rUserTokenValue.remove(dUser.getId());
// 添加令牌
token = EncryptHelper.toMD5(email + System.currentTimeMillis());
rTokenUserValue.set(token, dUser.getId(), tokenTimeout, TimeUnit.MILLISECONDS);
rUserTokenValue.set(dUser.getId(), token);
// 返回数据
return token;
}
/**
* 登出
*
* @param myId
* 我的标识
* @throws APIException
* API异常
*/
@Override
public void logout(Long myId) throws APIException {
// 删除令牌
String token = rUserTokenValue.get(myId);
if (token != null) {
rTokenUserValue.remove(token);
}
rUserTokenValue.remove(myId);
}
/**
* 获取我的用户
*
* @param myId
* 我的标识
* @return 我的用户
* @throws APIException
* API异常
*/
@Override
public MyUser getMyUser(Long myId) throws APIException {
// 初始化
MyUser user = new MyUser();
DUser dUser = dUserDAO.get(myId);
if (dUser != null) {
user.setId(dUser.getId());
user.setName(dUser.getName());
user.setPhone(dUser.getPhone());
}
// 返回数据
return user;
}
/**
* 修改我的密码
*
* @param myId
* 我的标识
* @param oldPassword
* 原始密码
* @param newPassword
* 新的密码
* @throws APIException
* API异常
*/
@Override
public void modifyMyPassword(Long myId, String oldPassword, String newPassword) throws APIException {
// TODO: 实现代码
}
}
| true
|
4d9e2300d6895746b8d1677da36b0cacfb1de5b6
|
Java
|
ev3dev-lang-java/usb-devices
|
/src/main/java/ev3dev/sensors/arduino/bn055/model/BNO055Response.java
|
UTF-8
| 349
| 1.726563
| 2
|
[
"MIT"
] |
permissive
|
package ev3dev.sensors.arduino.bn055.model;
import lombok.Data;
/**
* Created by jabrena on 12/8/17.
*/
public @Data class BNO055Response {
private final Quaternion quaternion;
private final Euler euler;
private final Acceleration acceleration;
private final Magnetometer magnetometer;
private final Gyroscope gyroscope;
}
| true
|
1e7e13fa125e6d9097b2edf6f7e2de81732397cb
|
Java
|
LinkLiLiLi/HSSF
|
/manage/src/main/java/team/nercita/manage/cms/contoller/jxc/JxcProductManageController.java
|
UTF-8
| 3,656
| 1.875
| 2
|
[] |
no_license
|
/*
* JxcProductManageController.java
* 创建者:L
* 创建日期:2017年12月21日 上午9:53:25
*
* 版权所有(C) 2015-2018。英泰伟业科技(北京)有限公司。
* 保留所有权利。
*/
package team.nercita.manage.cms.contoller.jxc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import team.nercita.manage.cms.po.jxc.ProductManage;
import team.nercita.manage.cms.service.jxc.ProductManageService;
import team.nercita.manage.cms.service.jxc.ProductStoreService;
import team.nercita.manage.cms.vo.ManageVo;
/**
*
* @author L
* @date: 2017年12月21日 上午9:53:25
*/
@Controller
@RequestMapping("/jxc/manage")
public class JxcProductManageController {
@Autowired
ProductManageService productManageService;
@Autowired
ProductStoreService productStoreService;
@RequestMapping("/list")
public ModelAndView list(Integer goPage, @ModelAttribute(value="typeid") String typeid){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("typeid", typeid);
ModelAndView view = new ModelAndView("jxc/manage/list");
view.addAllObjects(productManageService.doJoinTransFindManageList(goPage, paramMap));
view.addObject("typeList", productStoreService.doJoinTransFindProductType());
return view;
}
@RequestMapping("/toaddparent")
public ModelAndView toaddparent(){
ModelAndView view = new ModelAndView("jxc/manage/addparent");
view.addObject("typeList", productStoreService.doJoinTransFindProductType());
return view;
}
@RequestMapping("/addparent")
public String addparent(ProductManage productManage, RedirectAttributes attr){
try {
productManageService.doTransSaveParentProduct(productManage);
attr.addFlashAttribute("msg", "添加成功!");
} catch (Exception e) {
attr.addFlashAttribute("msg", e.getMessage());
}
return "redirect:/jxc/manage/list";
}
@RequestMapping("/show/{id}")
public ModelAndView show(@PathVariable String id){
ModelAndView view = new ModelAndView("jxc/manage/show");
view.addObject("id", id);
return view;
}
@RequestMapping("/json/{id}")
@ResponseBody
public Map<String, List<ManageVo>> json(@PathVariable String id){
Map<String, List<ManageVo>> resultMap = new HashMap<>();
resultMap.put("data", productManageService.doJoinTransFindManageVo(id));
return resultMap;
}
@RequestMapping("/toaddchild/{id}/{baseid}")
public ModelAndView toaddchild(@PathVariable String id, @PathVariable String baseid){
ModelAndView view = new ModelAndView("jxc/manage/addchild");
view.addObject("manage", productManageService.doJoinTransFindManageById(id));
view.addObject("baseid", baseid);
view.addObject("typeList", productStoreService.doJoinTransFindProductTypeByManageId(id));
return view;
}
@RequestMapping("/addchild")
public String addchild(ProductManage productManage, String baseid, RedirectAttributes attr){
productManageService.doTransSaveChildProduct(productManage);
attr.addFlashAttribute("msg", "添加成功!");
return "redirect:/jxc/manage/show/" + baseid;
}
}
| true
|
283f7160c26d9067cb1d2fceb22ce94578ff2a60
|
Java
|
HarrYoha/Twitter_Like
|
/Test/src/servlets/ListConnectedServlet.java
|
UTF-8
| 735
| 2.28125
| 2
|
[] |
no_license
|
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import services.UserService;
public class ListConnectedServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
JSONObject res = UserService.listConnected(user);
response.setContentType("text/plain");
response.getWriter().println(res.toString());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| true
|
cae0c7b5fabff85fba63314544ffdfab87d5d3d7
|
Java
|
OmgIknowIt/Library-Management-System
|
/src/main/java/com/lms/repository/AuthorRepo.java
|
UTF-8
| 202
| 1.578125
| 2
|
[] |
no_license
|
package com.lms.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.lms.models.Author;
public interface AuthorRepo extends JpaRepository<Author, Integer> {
}
| true
|
375806dec6cc4a8ce676358b1c375a7eae2ef9cc
|
Java
|
maybew/Yuemu
|
/yuemu/src/yuemu/web/SessionSet.java
|
UTF-8
| 629
| 2.5
| 2
|
[] |
no_license
|
package yuemu.web;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpSession;
public class SessionSet {
private final static Set<HttpSession> sessionSet = new
HashSet<HttpSession>();
public synchronized static void addSession(HttpSession session) {
sessionSet.add(session);
}
public synchronized static void removeSession(HttpSession session) {
sessionSet.remove(session);
}
public synchronized static void emptySessions() {
Set<HttpSession> temp = new HashSet<HttpSession>(sessionSet);
sessionSet.clear();
for(HttpSession session: temp)
session.invalidate();
}
}
| true
|
5ac83f54895a4937b6ad2e82d1ce3007f7159eaf
|
Java
|
Nukil/coding
|
/firstincity/src/main/java/netposa/firstincity/analysis/lib/db/FirstincityOutputValue.java
|
UTF-8
| 3,431
| 1.945313
| 2
|
[] |
no_license
|
package netposa.firstincity.analysis.lib.db;
import scala.Serializable;
public class FirstincityOutputValue implements Serializable {
private static final long serialVersionUID = 893326176876660025L;
private String trafficid;
private long passtime;
private int speed;
private String orgid;
private String roadmonitorid;
private String channelid;
private String platenumber;
private String platecolor;
private String platetype;
private String vehiclecolor;
private String vehicletype;
private String vehiclebrand;
private String vehiclesubbrand;
private String vehiclemodelyear;
private String backtype;
public FirstincityOutputValue(){}
public FirstincityOutputValue(OpaqInputValue value, String backtype) {
this.trafficid = value.getJlbh();
this.passtime = value.getJgsj();
this.speed = value.getClsd();
this.orgid = value.getXzqh();
this.roadmonitorid = value.getKkbh();
this.channelid = value.getCdbh();
this.platenumber = value.getHphm();
this.platecolor = value.getHpys();
this.platetype = value.getHpzl();
this.vehiclecolor = value.getCsys();
this.vehicletype = value.getCllx();
this.vehiclebrand = value.getClpp();
this.vehiclesubbrand = value.getClzpp();
this.vehiclemodelyear = value.getClnk();
this.backtype = backtype;
}
public String getTrafficid() {
return trafficid;
}
public void setTrafficid(String trafficid) {
this.trafficid = trafficid;
}
public long getPasstime() {
return passtime;
}
public void setPasstime(long passtime) {
this.passtime = passtime;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public String getOrgid() {
return orgid;
}
public void setOrgid(String orgid) {
this.orgid = orgid;
}
public String getRoadmonitorid() {
return roadmonitorid;
}
public void setRoadmonitorid(String roadmonitorid) {
this.roadmonitorid = roadmonitorid;
}
public String getChannelid() {
return channelid;
}
public void setChannelid(String channelid) {
this.channelid = channelid;
}
public String getPlatenumber() {
return platenumber;
}
public void setPlatenumber(String platenumber) {
this.platenumber = platenumber;
}
public String getPlatecolor() {
return platecolor;
}
public void setPlatecolor(String platecolor) {
this.platecolor = platecolor;
}
public String getPlatetype() {
return platetype;
}
public void setPlatetype(String platetype) {
this.platetype = platetype;
}
public String getVehiclecolor() {
return vehiclecolor;
}
public void setVehiclecolor(String vehiclecolor) {
this.vehiclecolor = vehiclecolor;
}
public String getVehicletype() {
return vehicletype;
}
public void setVehicletype(String vehicletype) {
this.vehicletype = vehicletype;
}
public String getVehiclebrand() {
return vehiclebrand;
}
public void setVehiclebrand(String vehiclebrand) {
this.vehiclebrand = vehiclebrand;
}
public String getVehiclesubbrand() {
return vehiclesubbrand;
}
public void setVehiclesubbrand(String vehiclesubbrand) {
this.vehiclesubbrand = vehiclesubbrand;
}
public String getVehiclemodelyear() {
return vehiclemodelyear;
}
public void setVehiclemodelyear(String vehiclemodelyear) {
this.vehiclemodelyear = vehiclemodelyear;
}
public String getBacktype() {
return backtype;
}
public void setBacktype(String backtype) {
this.backtype = backtype;
}
}
| true
|
56732e73eb38b3b97214a7d1e32b3e7e7e37b67d
|
Java
|
chellongCoder/ChelLong98Coder
|
/LapTrinhJAVA/bai_tap/QuanLyNhanVien/src/quanlynhanvien/Main.java
|
UTF-8
| 1,564
| 3.296875
| 3
|
[] |
no_license
|
/*
* 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 quanlynhanvien;
import java.util.Scanner;
/**
*
* @author Long Nguyen Nhat
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("nhập vào số lượng nhân viên: ");
int SIZE = sc.nextInt();
sc.nextLine(); //fflush
Employee emps[] = new Employee[SIZE];
System.out.println("Nhập thông tin nhân viên: ");
for (int i = 0; i < emps.length; i++) {
System.out.println("nhập vào tên đường: ");
String tenDuong = sc.nextLine();
System.out.println("nhập vào họ tên: ");
String name = sc.nextLine();
System.out.println("nhập vào số năm KN: ");
int SoNamKN = sc.nextInt();
sc.nextLine(); //fflush
Address add = new Address (tenDuong);
Employee emp = new Employee (name, SoNamKN);
emp.setAddress(add);
emps[i] = emp;
}
System.out.println("hiển thị thông tin nhân viên: ");
for (Employee emp: emps) {
System.out.println(emp.getName() + " | " + emp.getAddress().getTenDuong() + " | " + emp.luong());
}
}
}
| true
|
055ec00ae67b520ea14bfc202c71a4a21caac614
|
Java
|
ir2pid/codingchallenges
|
/projecteuler/EvenFibonacciNumbers.java
|
UTF-8
| 555
| 3.125
| 3
|
[] |
no_license
|
package projecteuler;
import java.math.BigInteger;
public class EvenFibonacciNumbers {
public static void main(String args[]) throws Exception {
int a = 1;
int b = 2;
BigInteger n = new BigInteger("4000000");
BigInteger sum = new BigInteger("2");
//System.out.println(a);
//System.out.println(b);
for (int i = 1; sum.compareTo(n)<1 ; i++) {
int temp = a;
a = b;
b = a+temp;
if(b%2 == 0)
sum = sum.add(new BigInteger(String.valueOf(b)));
//System.out.println(b);
}
System.out.println(sum);
}
}
| true
|
0d260e46f8f8f3c06f9da05d66e3dca2ba4ab276
|
Java
|
itoak/testProgram
|
/Problem11.java
|
UTF-8
| 1,778
| 3.53125
| 4
|
[] |
no_license
|
package testProgram;
public class Problem11 {
public static void main(String[] args){
System.out.println("Hello World :)");
}
}
class Problem12{
public static void main(String[] args){
int x = 11;
System.out.println("x=" + x);
}
}
class Problem13{
public static void main(String[] args){
int x = 13;
int y = 17;
System.out.println("x=" + x + ",y=" + y );
}
}
class Problem14{
public static void main(String[] args){
int x = 13 + 17;
System.out.println("x=" + x);
}
}
class Problem15{
public static void main(String[] args){
System.out.println(13*17);
}
}
class Problem16{
public static void main(String[] args){
int x = 7;
int y = x*3;
System.out.println(y);
int z = x/2;
System.out.println(z);
}
}
class Problem17{
public static void main(String[] args){
int x = 6;
int y = 9;
int z = x;
x = y;
y = z;
System.out.println("x=" + x + ", y=" + y);
}
}
class Problem18{
public static void main(String[] args){
int x = 19;
int y = 23;
int z = x*y;
System.out.println("z=" + z);
}
}
class Problem19{
public static void main(String[] args){
int x = 6;
System.out.println(x*2);
System.out.println(x*3);
System.out.println(x*4);
}
}
class Problem110{
public static void main(String[] args){
//Math.powも使用可
int x = 6;
int y = x;
for (int i=0; i<2; i++){
x *= y;
}
System.out.println("x=" + x);
}
}
class Problem111{
public static void main(String[] args){
int x = 6;
System.out.println(x/4);
System.out.println(x%4);
}
}
class Problem112{
public static void main(String[] args){
int x = 6;
x++;
System.out.println(x);
x--;
x--;
System.out.println(x);
}
}
| true
|
bdef2a5a8b4b649165109075cfbaafc4f6e50401
|
Java
|
egarcia91/TP2Algos3
|
/src/fiuba/algo3/algoformers/AlgoFormerVacio.java
|
UTF-8
| 256
| 2.203125
| 2
|
[] |
no_license
|
package fiuba.algo3.algoformers;
import fiuba.algo3.algoformers.AlgoFormer;
public class AlgoFormerVacio extends AlgoFormer {
public AlgoFormerVacio(){
super();
this.nombre = "AlgoFormerVacio";
}
public boolean estaVacio(){
return true;
}
}
| true
|
e1a3928990df84064a2d5e55bc231fb375da9aba
|
Java
|
aumabansag/MinMaxGame
|
/src/gui/MainMenuPanel.java
|
UTF-8
| 4,895
| 2.671875
| 3
|
[] |
no_license
|
package gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainMenuPanel extends JPanel{
private CardPanel parent;
private JPanel midPanel;
private JButton play;
private JComboBox<String> profiles;
private JButton help;
private JButton quit;
private Font font = new Font("Times New Roman", 50,30);
public MainMenuPanel(CardPanel parent){
this.parent = parent;
init();
}
/*
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
BufferedImage bi;
try {
bi = ImageIO.read(new File("src/assets/menu.png"));
g.drawImage(bi,0,0,this);
} catch (IOException e) {
e.printStackTrace();
}
background.setIcon(new ImageIcon(getClass().getResource("src/assets/menu.png")));
}*/
private void init() {
setLayout(new BorderLayout());
//setBorder(BorderFactory.createLineBorder(Color.BLACK));
initComponents();
}
private void initComponents(){
play = new JButton("Play as");
play.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
parent.showPanel("levelSelect");
parent.setProfile((String)profiles.getSelectedItem());
}
});
profiles = new JComboBox<String>();
readProfiles();
profiles.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox<String> combo = (JComboBox<String>) e.getSource();
String selection = (String) combo.getSelectedItem();
if(selection.equals("New Profile")){
createProfile();
}
else if(selection.equals("Delete Profile")){
deleteProfile();
}
}
});
DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
listRenderer.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
profiles.setRenderer(listRenderer);
help = new JButton("Help");
help.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
parent.showPanel("help");
}
});
quit = new JButton("Quit");
quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
/*
Icon menubg = new ImageIcon("src/assets/menu.png");
background = new JLabel(menubg);
*/
midPanel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage bi;
try {
bi = ImageIO.read(new File("src/assets/menu.png"));
g.drawImage(bi,0,0,this);
} catch (IOException e) {
e.printStackTrace();
}
}
};
midPanel.setBorder(BorderFactory.createEmptyBorder(30,30,30,30));
midPanel.setLayout(new GridLayout(4,1,40,40));
midPanel.setPreferredSize(new Dimension(350,350));
midPanel.add(play);
midPanel.add(profiles);
midPanel.add(help);
midPanel.add(quit);
setFont(midPanel);
add(midPanel);
}
private void setFont(JPanel midPanel) {
Component[] contents = midPanel.getComponents();
for(int i =0; i < contents.length; i++){
contents[i].setFont(font);
}
}
private void readProfiles(){
profiles.removeAllItems();
File file = new File("src/saves");
String[] files = file.list();
if(files.length == 0){
createProfile();
}
else{
for(int i=0; i<files.length; i++) {
if(files[i].substring((files[i].length()-4), files[i].length()).equals(".sav")){
profiles.addItem(files[i].substring(0, files[i].length()-4));
}
}
profiles.addItem("New Profile");
profiles.addItem("Delete Profile");
}
}
private void createProfile(){
String input = (String)JOptionPane.showInputDialog(null, "Enter name:");
if(input != null && input.trim().length() > 0){
File newSave = new File("src/saves/"+input+".sav");
try {
if(newSave.exists()){
JOptionPane.showMessageDialog(null,"Profile already exists!");
}
else if(input.equals("New Profile") || input.equals("Delete Profile")){
JOptionPane.showMessageDialog(null,"Invalid Name!");
}
else{
BufferedWriter bw = new BufferedWriter(new FileWriter(newSave));
bw.write("1\n1");
bw.flush();
bw.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(null,"Name cannot be blank!");
}
readProfiles();
}
private void deleteProfile(){
String input = (String) JOptionPane.showInputDialog(null, "Enter profile to delete:");
if(input != null && input.trim().length() > 0){
File toDelete = new File("src/saves/" + input+ ".sav");
try{
if(toDelete.delete()){
JOptionPane.showMessageDialog(null,input+" has been deleted");
}
else{
JOptionPane.showMessageDialog(null, "Profile not found");
}
}catch(SecurityException e){
e.printStackTrace();
}
}
readProfiles();
}
}
| true
|
182856c87c74d5dbc9636343986e6ec379ae4e51
|
Java
|
iOS-Lab/tracker-server
|
/ntsiot-data-engine/src/main/java/com/nts/iot/rest/OrderController.java
|
UTF-8
| 3,116
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* @(#)OrderController.java 2019-05-14
*
* Copyright 2019 Liaoning RNS Technology Co., Ltd.All rights reserved.
* RNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*******************************************************************************/
package com.nts.iot.rest;
import com.nts.iot.dto.OrderBikeQueryDTO;
import com.nts.iot.dto.OrderBikeStaticDTO;
import com.nts.iot.entity.Order;
import com.nts.iot.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* <p>
* </p>
*
* @author <a href="mailto:gaop@rnstec.com">Gaven</a>
* @version cyoubike 1.0 $ 2019-05-14 20:11
*/
@RestController
@RequestMapping("")
public class OrderController {
@Autowired
private OrderService orderService;
/**
* 订单保存
*
* @param order
* @return
*/
@RequestMapping("/order/save")
public ResponseEntity save(@RequestBody Order order) {
orderService.save(order);
return new ResponseEntity(HttpStatus.OK);
}
/**
* 根据订单编号将订单相关的所有信息都处理好,然后存储到ES中
*
* @param orderNo
* @return
*/
@RequestMapping("/order/save/{orderNo}")
public ResponseEntity saveByDeviceNo(@PathVariable String orderNo) {
orderService.saveByDeviceNo(orderNo);
return new ResponseEntity(HttpStatus.OK);
}
/**
* 根据订单编号查询订单信息
*
* @param orderId
* @return
*/
@GetMapping("order/ridingTrack/{orderId}")
public ResponseEntity findOne(@PathVariable String orderId) {
return new ResponseEntity(orderService.findOne(orderId), HttpStatus.OK);
}
/**
* 根据车辆编号,查询历史轨迹
* @param bikeBarcode
* @param startTime
* @param endTime
* @return
*/
@GetMapping("bikes/historicalRoute")
public ResponseEntity queryAll(@RequestParam("bikeBarcode") String bikeBarcode, @RequestParam("startTime") Long startTime,
@RequestParam("endTime") Long endTime) {
return new ResponseEntity(orderService.queryAll(bikeBarcode, startTime, endTime), HttpStatus.OK);
}
/**
* 根据订单List获得订单轨迹
*
* @param ids
* @return
*/
@PostMapping("/order/findAllByIdIn")
public List<List<Map<String, Object>>> findAllByIdIn(@RequestBody List<String> ids) {
return orderService.findAllByIdIn(ids);
}
/**
* 根据订单List获得统计信息
*
* @param orderBikeQuerys
* @return
*/
@PostMapping("/order/getBikeStateByIds")
public List<OrderBikeStaticDTO> getBikeStateByIds(@RequestBody List<OrderBikeQueryDTO> orderBikeQuerys) {
return orderService.getBikeStateByIds(orderBikeQuerys);
}
}
| true
|
7771f14f4f5153d7f72794156993e96553f3e61c
|
Java
|
tianrui189/tianrui18990278
|
/期末智能机大作业/Mall-master/app/src/main/java/com/wythe/mall/activity/BaseActivity.java
|
UTF-8
| 1,495
| 2.109375
| 2
|
[] |
no_license
|
package com.wythe.mall.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.wythe.mall.R;
import com.wythe.mall.utils.AppManager;
/**
* Created by wythe on 2016/7/6.
*/
public abstract class BaseActivity extends Activity implements View.OnClickListener{
public static final String TAG = BaseActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
Fresco.initialize(getApplicationContext());
super.onCreate(savedInstanceState);
AppManager.getInstance().addActivity(this);
}
protected void initView(){
findViewById(R.id.title_left_button).setOnClickListener(this);
findViewById(R.id.title_right_button).setOnClickListener(this);
}
protected void initListener(){
}
protected void setNormalTitle(int resId){
((TextView)findViewById(R.id.titleText)).setText(resId);
}
protected void setNormalTitle(String title){
((TextView)findViewById(R.id.titleText)).setText(title);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.title_left_button:{
System.out.print("title_left_button");
finish();
break;
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
| true
|
ffcdbd746e285abdcaf970c10a2d58cd01b50230
|
Java
|
fm1995/TapWater
|
/SyProject/src/com/sy/service/rd/RdUserService.java
|
GB18030
| 2,117
| 2.296875
| 2
|
[] |
no_license
|
package com.sy.service.rd;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.sy.entity.UsUser;
import com.sy.mappdao.UsUserMapper;
import com.sy.projectUtils.rd.TermUtil;
/**
* ûҵ
* @author xulong
*/
@Service
public class RdUserService {
@Autowired
private UsUserMapper userMapper;
/**
* ݱidѯû дǰҳ
* @param response
* @param term
*/
public void selByTerm(HttpServletResponse response,UsUser user, TermUtil term){
System.out.println(term.getRows()+"........"+term.getStartIndex());
List<UsUser> users = userMapper.selByTerm(user,term);
int count = userMapper.selByTermCount(user);
Map map=new HashMap<String, Object>();
map.put("users", users);
map.put("count",count);
map.put("pageCount", (count-1)/term.getRows()+1);
mapToJson(response,map);
}
/**
* mapתΪjsonдǰ
* @param response
* @param map
*/
@SuppressWarnings("rawtypes")
private void mapToJson(HttpServletResponse response,Map map){
String json = new Gson().toJson(map);
response.setContentType("text/json;charset=utf-8");
try {
System.out.println(json);
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ûidΪidûıIdΪ
* @param volumeId
*/
public void UpVolumeId(int volumeId){
userMapper.upVolumeId(volumeId);
}
public void upVolumeIdToNull(HttpServletResponse response, String userNos,String volumeId) throws IOException {
String[] arr = userNos.split(":");
userMapper.upVolumeIdToNull(arr,volumeId);
response.getWriter().write("1");
}
public void upUserVolumeIndex(UsUser user) {
userMapper.updateByPrimaryKeySelective(user);
}
}
| true
|
31e148a34fb436551239276462db4de36c723f9d
|
Java
|
spring-projects/spring-data-examples
|
/jpa/deferred/src/main/java/example/repo/Customer1642Repository.java
|
UTF-8
| 284
| 1.875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package example.repo;
import example.model.Customer1642;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1642Repository extends CrudRepository<Customer1642, Long> {
List<Customer1642> findByLastName(String lastName);
}
| true
|
779e1a95c9baa1d293564aa7c0fea1e38ed088c9
|
Java
|
ManfredTremmel/gwt-bean-validators
|
/gwt-bean-validators/src/main/java/de/knightsoftnet/validators/client/impl/AbstractGwtValidator.java
|
UTF-8
| 5,067
| 1.765625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2010 Google Inc. Copyright 2016 Manfred Tremmel
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.knightsoftnet.validators.client.impl;
import de.knightsoftnet.validators.client.impl.metadata.ValidationGroupsMetadata;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.ParameterNameProvider;
import javax.validation.TraversableResolver;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
/**
* Base methods for implementing {@link Validator} in GWT.
* <p>
* All methods that do not need to be generated go here.
* </p>
*/
public abstract class AbstractGwtValidator implements Validator {
private final Set<Class<?>> validGroups;
private final ValidationGroupsMetadata validationGroupsMetadata;
private ConstraintValidatorFactory contraintValidatorFactory;
private MessageInterpolator messageInterpolator;
private TraversableResolver traversableResolver;
private ParameterNameProvider parameterNameProvider;
/**
* Creates a validator initialized with the default group inheritance map.
*
* @see #AbstractGwtValidator(ValidationGroupsMetadata)
*/
public AbstractGwtValidator() {
this(ValidationGroupsMetadata.builder().build());
}
/**
* constructor.
*
* @param validationGroupsMetadata Validation group metadata.
*/
public AbstractGwtValidator(final ValidationGroupsMetadata validationGroupsMetadata) {
validGroups = validationGroupsMetadata.getAllGroupsAndSequences();
this.validationGroupsMetadata = validationGroupsMetadata;
}
public ValidationGroupsMetadata getValidationGroupsMetadata() {
return validationGroupsMetadata;
}
/**
* initialize values.
*
* @param factory constraint validator factory to set
* @param messageInterpolator message interpolator to set
* @param traversableResolver traversable resolver to set
* @param pparameterNameProvider parameter resolver to set
*/
public void init(final ConstraintValidatorFactory factory,
final MessageInterpolator messageInterpolator, final TraversableResolver traversableResolver,
final ParameterNameProvider pparameterNameProvider) {
contraintValidatorFactory = factory;
this.messageInterpolator = messageInterpolator;
this.traversableResolver = traversableResolver;
parameterNameProvider = pparameterNameProvider;
}
@Override
public <T> T unwrap(final Class<T> type) {
throw new ValidationException();
}
public abstract <T> Set<ConstraintViolation<T>> validate(GwtValidationContext<T> context,
Object object, Class<?>... groups) throws ValidationException;
protected void checkGroups(final Class<?>... groups) {
if (!validGroups.containsAll(Arrays.asList(groups))) {
final HashSet<Class<?>> unknown = new HashSet<>();
unknown.addAll(Arrays.asList(groups));
unknown.removeAll(validGroups);
throw new IllegalArgumentException(getClass() + " only processes the following groups "
+ validGroups + ". " + "The following groups could not be processed " + unknown);
}
}
protected void checkNotNull(final Object object, final String name)
throws IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException(name + " can not be null.");
}
}
protected ConstraintValidatorFactory getConstraintValidatorFactory() {
return contraintValidatorFactory;
}
public MessageInterpolator getMessageInterpolator() {
return messageInterpolator;
}
public TraversableResolver getTraversableResolver() {
return traversableResolver;
}
protected ParameterNameProvider getParameterNameProvider() {
return parameterNameProvider;
}
@Override
public ExecutableValidator forExecutables() {
// TODO Auto-generated method stub
return null;
}
/**
* reflection replacement to get property of an object.
*
* @param object object to get property from
* @param propertyName property name
* @return object value
* @throws NoSuchMethodException if there is no getter for this property name
* @throws ReflectiveOperationException if no reflection for this class is available
*/
public abstract Object getProperty(final Object object, final String propertyName)
throws NoSuchMethodException, ReflectiveOperationException;
}
| true
|
101d136d0cec0e0af80f64485ef048870c486589
|
Java
|
plangebfw/risk_game_1801
|
/src/bfw/risiko/Kontinent.java
|
UTF-8
| 1,751
| 3.46875
| 3
|
[] |
no_license
|
package bfw.risiko;
/**
* <h1>Kontinent</h1>
* <p>
* Ein Kontintent, mit einem Namen, einer Liste von Ländern,
* und einem Bonus für den Spieler, dem der ganze Kontinent
* gehört.
*
* @since 2019-02-25
*/
public class Kontinent {
/**
* Der Name des Kontinents (Nordamerika, Südamerika, Europa, Afrika, Asien oder Australien).
*/
private String name;
/**
* Die Länder, die auf dem Kontinent liegen.
*/
private Land[] laenderListe;
/**
* Der Bonus für den Kontinent
*/
private int bonus;
/**
* Erstellt einen neuen Kontinent.
*
* @param name der Name des Kontinents
* @param laenderListe eine Liste von Ländern
* @param bonus der Bonuswert
*/
public Kontinent(String name, Land[] laenderListe, int bonus) {
this.name = name;
this.laenderListe = laenderListe;
this.bonus = bonus;
}
/**
* Gibt den Namen dieses Kontinents zurück.
* @return der Namen
*/
public String getName() {
return name;
}
/**
* Ändert den Namen dieses Kontinents.
* @param name der neue Name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gibt die Länder, die auf diesem Kontinent liegen, zurück.
* @return Liste von Ländern
*/
public Land[] getLaenderListe() {
return laenderListe;
}
/**
* Ändert die Länderliste dieses Kontinents.
* @param laenderListe die neue Liste von Ländern
*/
public void setLaenderListe(Land[] laenderListe) {
this.laenderListe = laenderListe;
}
/**
* Gibt den Bonus für den Kontinent zurück.
* @return der Bonus
*/
public int getBonus() {
return bonus;
}
/**
* Ändert den Bonus dieses Kontinents.
* @param bonus der neue Kontinent
*/
public void setBonus(int bonus) {
this.bonus = bonus;
}
}
| true
|
3ecd21026bb67a1436feeb7617efeb64de56dd23
|
Java
|
JeeVeeVee/univ
|
/1steBachelor/OGPROG/Prog2-master/src/prog2/nio/ToUpperMain.java
|
UTF-8
| 660
| 2.703125
| 3
|
[] |
no_license
|
/* ToUpperMain.java
* ============================================================
* Copyright (C) 2015 Universiteit Gent
*
* Bijlage bij het vak 'Programmeren 2'.
*
* Auteur: Kris Coolsaet
*/
package prog2.nio;
/**
* Leest een bestand in, zet de inhoud om naar hoofdletters en schrijft het bestand opnieuw uit.
* Bestandsnamen moeten worden opgegeven op de opdrachtlijn.
*/
public class ToUpperMain {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java prog2.nio.ToUpperMain infile outfile");
} else {
new ToUpper().translate (args[0], args[1]);
}
}
}
| true
|
df0c74f56e245f49008e2d5d59d20cfdef53eacf
|
Java
|
Flashfyre/Spectrite
|
/src/main/java/com/samuel/spectrite/items/ItemSpectriteArrowSpecial.java
|
UTF-8
| 369
| 2.03125
| 2
|
[] |
no_license
|
package com.samuel.spectrite.items;
import net.minecraft.entity.item.EntityItem;
public class ItemSpectriteArrowSpecial extends ItemSpectriteArrow implements IPerfectSpectriteItem {
public ItemSpectriteArrowSpecial() {
super();
}
@Override
public boolean onEntityItemUpdate(EntityItem entityItem) {
return this.onEntitySpectriteItemUpdate(entityItem);
}
}
| true
|
48b7955d605e8f73a90ec7c286f1dae1214ef645
|
Java
|
DeathHere/wandocpc
|
/SpeedScripts/src/iFisher.java
|
UTF-8
| 44,663
| 1.75
| 2
|
[] |
no_license
|
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
import org.rsbot.bot.*;
import org.rsbot.script.*;
import org.rsbot.bot.input.Mouse;
import org.rsbot.script.wrappers.*;
import org.rsbot.script.wrappers.RSNPC;
import org.rsbot.script.wrappers.RSInterface;
import org.rsbot.script.wrappers.RSObject;
import org.rsbot.script.wrappers.RSTile;
import org.rsbot.event.events.ServerMessageEvent;
import org.rsbot.event.listeners.ServerMessageListener;
import org.rsbot.event.listeners.PaintListener;
import org.rsbot.util.ScreenshotUtil;
import org.rsbot.util.GlobalConfiguration;
import org.rsbot.script.ScriptManifest;
@ScriptManifest(authors = { "Issues" }, category = "Fishing", name = "iFisher", version = 2.8, description = "<html>" +"<body bgcolor='#B0C4DE'>" + "<h2><font color='#191970' size='6'><center>iFisher</center></font></h2>" +"" +"<center><font color='white' size='3'>All setting's can be configured in the GUI</font></center>" +"<center><font color='white' size='3'>Just select your account and press ok.</font></center>" +"</body>" +"</html>")
public class iFisher extends Script implements PaintListener, ServerMessageListener {
final ScriptManifest props = getClass().getAnnotation(ScriptManifest.class);
public long moneyGained, checkTime, lastCheck, time, xpHour, levelIn;
public long startTime = System.currentTimeMillis();
public int runEnergy = random(50, 100);
public int bassPrice, mackerelPrice, codPrice, gearfails, levelGained, catchesPerHour, startexp, gearMode, fishSpot, fishId, fished, fishEquip, XPToGo, shrimpsPrice,anchoviesPrice, lobsterPrice, swordfishPrice, tunaPrice, herringPrice, sardinesPrice, sharkPrice, troutPrice, salmonPrice, pikePrice;
public boolean useAntiBan, dropTuna, drop, sell, catherbyLoc, kjMode, paused, barbMode, antiBanModeBox, paint, startScript, fishingGuild;
public String status, fishing, location2, fishComm = "";
public RSTile fishTile, bankTile;
public RSTile[] toBank, toFish;
private GUI GUI;
public boolean onStart(Map<String, String> args) {
GUI = new GUI();
GUI.setVisible(true);
while (!startScript) {
fished = 0;
wait(10);
}
startTime = System.currentTimeMillis();
return true;
}
public void onFinish() {
GUI.setVisible(false);
return;
}
public void onRepaint(Graphics g) {
long millis = System.currentTimeMillis() - startTime;
long hours = millis / (1000 * 60 * 60);
millis -= hours * (1000 * 60 * 60);
long minutes = millis / (1000 * 60);
millis -= minutes * (1000 * 60);
long seconds = millis / 1000;
long minutes2 = minutes + (hours * 60);
int xpGained = 0;
if (startexp == 0) { startexp = skills.getCurrentSkillExp(STAT_FISHING); }
xpGained = skills.getCurrentSkillExp(STAT_FISHING) - startexp;
XPToGo = skills.getXPToNextLevel(STAT_FISHING);
time = (System.currentTimeMillis() - startTime) / 1000;
if (time > 0) {
catchesPerHour = (int)((fished*60*60)/time);
xpHour = (xpGained*60*60)/time;
levelIn = (long)(60*60*(XPToGo/(double)xpHour));
}
Mouse m = Bot.getClient().getMouse();
Point p = new Point(m.x,m.y);
//Status Button
if (startScript && paint) {
g.setColor(new Color(0, 0, 0));
g.drawRect(6, 175, 68, 14);
g.setColor(new Color(25, 25, 112, 100));
g.fillRect(7, 182, 67, 7);
g.setColor(new Color(0, 0, 205, 100));
g.fillRect(7, 176, 67, 6);
g.setColor(Color.WHITE);
g.setFont(new Font("Segoe UI", Font.BOLD, 10));
g.drawString("iFisher v" + props.version(), 9, 186);
g.setColor(new Color(0, 0, 0));
g.drawRect(6, 192, 68, 14);
g.setColor(new Color(25, 25, 112, 100));//Bottom
g.fillRect(7, 199, 67, 7);
g.setColor(new Color(0, 0, 205, 100));//Top
g.fillRect(7, 193, 67, 6);
if (isWithinBounds(p, 6, 192, 68, 14)) {
g.setColor(new Color(255, 140, 0));
} else {
g.setColor(Color.WHITE);
}
g.setFont(new Font("Segoe UI", Font.BOLD, 10));
g.drawString("- Status", 9, 203);//Text
//Exp Button
g.setColor(new Color(0, 0, 0));
g.drawRect(6, 209, 68, 14);
g.setColor(new Color(25, 25, 112, 100));//Bottom
g.fillRect(7, 216, 67, 7);
g.setColor(new Color(0, 0, 205, 100));//Top
g.fillRect(7, 210, 67, 6);
if (isWithinBounds(p, 6, 209, 68, 14)) {
g.setColor(new Color(255, 140, 0));
} else {
g.setColor(Color.WHITE);
}
g.setFont(new Font("Segoe UI", Font.BOLD, 10));
g.drawString("- Experience", 9, 220);//Text
//Gold Button
g.setColor(new Color(0, 0, 0));
g.drawRect(6, 226, 68, 14);
g.setColor(new Color(25, 25, 112, 100));//Bottom
g.fillRect(7, 233, 67, 7);
g.setColor(new Color(0, 0, 205, 100));//Top
g.fillRect(7, 227, 67, 6);
if (isWithinBounds(p, 6, 226, 68, 14)) {
g.setColor(new Color(255, 140, 0));
} else {
g.setColor(Color.WHITE);
}
g.setFont(new Font("Segoe UI", Font.BOLD, 10));
g.drawString("- Profit", 9, 237);//Text
if (isWithinBounds(p, 6, 226, 68, 14)) {//Gold
g.setColor(new Color(0, 0, 0));
g.drawRect(75, 226, 113, 65);
g.setColor(new Color(0, 0, 205, 100));
g.fillRect(76, 227, 112, 32);
g.setColor(new Color(25, 25, 112, 100));
g.fillRect(76, 258, 112, 33);
g.setFont(new Font("Arial", Font.BOLD, 10));
g.setColor(Color.WHITE);
g.drawString("Fish: " + fished, 79, 240);
g.drawString("Fish/Hour: " + catchesPerHour, 79, 255);
if (drop) {
g.drawString("Gold: N/A", 79, 270);
g.drawString("Gold/Hour: N/A", 79, 285);
} else {
g.drawString("Gold: " + moneyGained, 79, 270);
if (fished > 0)
g.drawString("Gold/Hour: " + moneyGained/time*3600, 79, 285);
else
g.drawString("Please Wait...", 79, 285);
}
}
if (isWithinBounds(p, 6, 209, 68, 14)) {//EXP
g.setColor(new Color(0, 0, 0));
g.drawRect(75, 209, 113, 84);
g.setColor(new Color(0, 0, 205, 100));
g.fillRect(76, 210, 112, 34);
g.setColor(new Color(25, 25, 112, 100));
g.fillRect(76, 243, 112, 50);
g.setFont(new Font("Arial", Font.BOLD, 10));
g.setColor(Color.WHITE);
g.drawString("Exp Gained: " + xpGained, 79, 223);//Text
g.drawString("Exp/Hour: " + xpHour, 79, 238);//Text
if (fished > 0) {
g.drawString("Level in: " + levelIn / 3600 + ":" + ((levelIn / 60 % 60 < 10) ? "0" : "") + levelIn / 60 % 60 + ":" + ((levelIn % 60 < 10) ? "0" : "")+ levelIn % 60, 79, 253);
} else {
g.drawString("Level In: 0:00:00", 79, 253);//Text
}
g.drawString("Levels Gained: " + levelGained, 79, 268);
g.setColor(new Color(0, 0, 0));
g.drawRect(80, 275, 100, 12);
g.setColor(new Color(255, 0, 0));
g.fillRect(81, 276, 99, 11);
g.setColor(new Color(34, 139, 34));
g.fillRect(81, 276, skills.getPercentToNextLevel(STAT_FISHING), 11);
g.setColor(Color.BLACK);
g.drawString(" " + skills.getPercentToNextLevel(STAT_FISHING) + "% to next Level", 79, 285);
}
if (isWithinBounds(p, 6, 192, 68, 14)) {//Status
g.setColor(new Color(0, 0, 0));
g.drawRect(75, 192, 113, 84);
g.setColor(new Color(0, 0, 205, 100));
g.fillRect(76, 193, 112, 34);
g.setColor(new Color(25, 25, 112, 100));
g.fillRect(76, 226, 112, 50);
g.setFont(new Font("Segoe UI", Font.BOLD, 10));
g.setColor(new Color(255, 140, 0));
g.drawString("" + status, 79, 208);
g.setFont(new Font("Arial", Font.BOLD, 10));
g.setColor(Color.WHITE);
g.drawString("" + location2, 79, 223);//Text
g.drawString("" + fishing, 79, 238);//Text
if (drop) {
g.drawString("Droping Fish", 79, 253);
} else {
g.drawString("Banking Fish", 79, 253);
}
g.drawString("Run for: " + hours + ":" + minutes + ":" + seconds + "", 79, 268);
}
}
}
public void serverMessageRecieved(ServerMessageEvent e) {
String message = e.getMessage().toLowerCase();
if (message.contains("advanced")) {
levelGained++;
wait(random(500, 1000));
clickContinue();
}
if (message.contains("bass")) {
moneyGained += bassPrice;
fished++;
}
if (message.contains("mackerel")) {
moneyGained += mackerelPrice;
fished++;
}
if (message.contains("cod")) {
moneyGained += codPrice;
fished++;
}
if (message.contains("you catch a crayfish")) {
fished++;
}
if (message.contains("shrimps")) {
moneyGained += shrimpsPrice;
fished++;
}
if (message.contains("anchovies")) {
moneyGained += anchoviesPrice;
fished++;
}
if (message.contains("you catch a lobster")) {
moneyGained += lobsterPrice;
fished++;
}
if (message.contains("you catch a tuna") && !dropTuna) {
moneyGained += tunaPrice;
fished++;
}
if (message.contains("you catch a swordfish")) {
moneyGained += swordfishPrice;
fished++;
}
if (message.contains("you catch a shark")) {
moneyGained += sharkPrice;
fished++;
}
if (message.contains("herring")) {
herringPrice = herringPrice;
fished++;
}
if (message.contains("sardines")) {
moneyGained += sardinesPrice;
fished++;
}
if (message.contains("trout")) {
moneyGained += troutPrice;
fished++;
}
if (message.contains("salmon")) {
moneyGained += salmonPrice;
fished++;
}
if (message.contains("pike")) {
moneyGained += pikePrice;
fished++;
}
}
public void openBank() {
if (kjMode) {
if (RSInterface.getInterface(11).isValid()) {
atInterface(RSInterface.getInterface(11).getChild(15));
wait(random(500, 1000));
}
RSObject depositbox = getNearestObjectByID(36788);
if(inventoryContains(fishId)) {
atInventoryItem(fishId, "Use");
wait(random(300, 500));
if(depositbox != null) {
if (!atObject(depositbox, "-> Bank")) {
setCameraAltitude(true);
setCameraRotation(getCameraAngle() + random(-90, 90));
}
wait(random(2000, 3000));
if (RSInterface.getInterface(232).isValid()) {
atInterface(RSInterface.getInterface(232).getChild(5));
wait(random(1000, 1500));
}
}
}
if(inventoryContains(359)) {//Tunas
atInventoryItem(359, "Use");
wait(random(300, 500));
if(depositbox != null) {
if (!atObject(depositbox, "-> Bank")) {
setCameraAltitude(true);
setCameraRotation(getCameraAngle() + random(-90, 90));
}
wait(random(2000, 3000));
if (RSInterface.getInterface(232).isValid()) {
atInterface(RSInterface.getInterface(232).getChild(5));
wait(random(1000, 1500));
}
}
}
} else {
RSNPC banker = getNearestNPCByID(494, 495, 496, 5912, 5913);
if (banker != null) {
if(!atNPC(banker, "Bank Banker")) {
setCameraAltitude(true);
setCameraRotation(getCameraAngle() + random(-90, 90));
}
wait(random(500, 1000));
} else {
wait(random(1000, 1500));
}
}
}
public void fish() {
if (getMyPlayer().getAnimation() == -1 && !getMyPlayer().isMoving()) {
RSNPC nSpot = getNearestNPCByID(fishSpot);
if (nSpot == null) {
if (catherbyLoc) {
walkTileMM(new RSTile(2847, 3422));//If not found walk here
}
wait(random(50, 150));
}
if (nSpot != null) {
if (distanceTo(nSpot.getLocation()) > 4 || !nSpot.isOnScreen()) {
RSTile destination = randomizeTile(nSpot.getLocation(), 2, 2);
walkTileMM(destination);
waitToStop();
wait(random(500, 1000));
}
if (nSpot.isOnScreen()) {
atTile(nSpot.getLocation(), fishComm);
waitToStop();
wait(random(2000,3500));
}
}
}
}
public int walkFish() {
if (takeBoatToKaramja())
return random(5000, 6000);
if (distanceTo(getDestination()) < random(8, 12) || distanceTo(getDestination()) > 40) {
if (!walkPathMM(toFish)) {
walkToClosestTile(toFish);
return random(50, 150);
}
}
return random(50, 150);
}
public int walkBank() {
if (takeBoatFromKaramja())
return random(5000, 6000);
if (dropTunas())
return random(200, 300);
if (fishingGuild) {
if (distanceTo(getDestination()) < random(5, 8) || distanceTo(getDestination()) > 40) {
if (!walkPathMM(toBank)) {
walkToClosestTile(toBank, 1,1);
return random(50, 150);
}
}
} else {
if (distanceTo(getDestination()) < random(8, 12) || distanceTo(getDestination()) > 40) {
if (!walkPathMM(toBank)) {
walkToClosestTile(toBank);
return random(50, 150);
}
}
}
return random(50, 150);
}
public void gearCheck() {
if (kjMode && getInventoryCount(995) < 30) {
log("Not enough Gold to pay the fee.");
gearfails++;
}
if (!barbMode) {
if (gearMode == 2) {//Bait
if (!inventoryContains(313, 307)) {
log("No Rod or Bait...");
gearfails++;
return;
}
}
if (gearMode == 1) {//Feathers
if (!inventoryContains(314, 309)) {
log("No Fly Rod or Feathers...");
gearfails++;
return;
}
}
if (gearMode == 3) {
if (!inventoryContains(303)) {
log("No Net...");
gearfails++;
return;
}
}
if (gearMode == 4) {
if (!inventoryContains(301)) {
log("No Lobster Cage...");
gearfails++;
return;
}
}
if (gearMode == 5) {
if (!inventoryContains(311)) {
log("No Harpoon...");
gearfails++;
return;
}
}
if (gearMode == 6) {
if (!inventoryContains(305)) {
log("No Net...");
gearfails++;
return;
}
}
if (gearMode == 7) {
if (!inventoryContains(13431)) {
log("No Crayfish Cage...");
gearfails++;
return;
}
}
gearfails = 0;
}
return;
}
public boolean inArea(int maxX, int minY, int minX, int maxY) {
int x = getMyPlayer().getLocation().getX();
int y = getMyPlayer().getLocation().getY();
return x >= minX && x <= maxX && y >= minY && y <= maxY;
}
public boolean isWithinBounds(Point p, int x, int y, int w, int h) {
if (p.x > x && p.x < x+w && p.y > y && p.y < y+h) {
return true;
} else {
return false;
}
}
public static double getVersion() {
try {
URL url = new URL("http://*******s.webs.com/iFisher/iFisherV.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(
new BufferedInputStream(url.openConnection().getInputStream())));
double ver = Double.parseDouble(br.readLine().trim());
br.close();
return ver;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void checkUpdate() {
double curV = getVersion();
if (curV > props.version()) {
log("New update! Please update your iFisher to v" + curV);
return;
}
return;
}
public void waitToStop() {
while (getMyPlayer().isMoving()) {
wait(150);
}
}
public int loop() {
if (atWelcomButton()) {
return 500;
}
if (!paused && startScript) {
gearCheck();
if (!isRunning() && getEnergy() >= runEnergy) {
runEnergy = random(50, 100);
setRun(true);
wait(random(300, 700));
}
switch (getState()) {
case FISH:
fish();
break;
case GOTO_FISH:
walkFish();
break;
case GOTO_BANK:
walkBank();
break;
case IDLE:
wait(random(1000, 2000));
if (useAntiBan) {
antiBan();
}
break;
case OPEN_BANK:
openBank();
break;
case USE_BANK:
if (kjMode) {
bank.depositAllExcept(fishEquip, 314, 309, 307, 303, 313, 311, 301, 995);//Money
} else {
bank.depositAllExcept(fishEquip, 314, 309, 307, 303, 313, 311, 301);
}
break;
case DROP:
dropAllExcept_(fishEquip, 314, 309, 307, 303, 313, 311, 301, 13431);
break;
}
}
return (random(500, 1000));
}
private enum State {
OPEN_BANK, USE_BANK, FISH, GOTO_BANK, GOTO_FISH, IDLE, DROP
}
private State getState() {
if (isInventoryFull() && drop) {
status = "Droping fish";
return State.DROP;
}
if (isInventoryFull()) {
if (bank.isOpen() && !kjMode) {
status = "Depositing fish";
return State.USE_BANK;
} else if (distanceTo(bankTile) < 8 && !getMyPlayer().isMoving()) {
status = "Opening bank";
return State.OPEN_BANK;
} else {
status = "Walking to bank";
return State.GOTO_BANK;
}
} else {
if (getMyPlayer().getAnimation() != -1) {
return State.IDLE;
} else if (catherbyLoc && inArea(2862, 3422, 2834, 3434) || distanceTo(fishTile) < 10) {
status = "Fishing";
return State.FISH;
} else {
status = "Walking to fish";
return State.GOTO_FISH;
}
}
}
public void dropAllExcept_(final int... items) {
try {
for (int c = 0; c < 4; c++) {
for (int r = 0; r < 7; r++) {
boolean found = false;
for (int i = 0; i < items.length && !found; i++) {
found = items[i] == getInventoryArray()[c + r * 4];
}
if (!found) {
dropItem(c, r);
}
}
}
} catch (final Exception e) {
log("Prevented fatal error.");
}
}
public boolean atWelcomButton() {
RSInterface welcomeInterface = RSInterface.getInterface(378);
if (welcomeInterface.getChild(45).getAbsoluteX() > 20 || (!welcomeInterface.getChild(117).getText().equals("10.1120.190") && !welcomeInterface.getChild(117).getText().equals(""))) {
clickMouse(random(215, 555), random(420, 440), true);
return true;
} else {
return false;
}
}
public boolean takeBoatFromKaramja() {
try {
RSNPC customsOfficer = getNearestNPCByID(380);
RSObject plank = getNearestObjectByID(2084);
if (plank != null) {
if (!getMyPlayer().isMoving()) {
atObject(plank, "Cross");
wait(random(1000, 1500));
return true;
}
}
if (RSInterface.getInterface(228).isValid()) {
atInterface(RSInterface.getInterface(228).getChild(2));
wait(random(200, 300));
return true;
}
if (RSInterface.getInterface(242).isValid()) {
atInterface(RSInterface.getInterface(242).getChild(6));
wait(random(200, 300));
return true;
}
if (RSInterface.getInterface(230).isValid()) {
atInterface(RSInterface.getInterface(230).getChild(3));
wait(random(200, 300));
return true;
}
if (RSInterface.getInterface(241).isValid()) {
atInterface(RSInterface.getInterface(241).getChild(5));
wait(random(200, 300));
return true;
}
if (RSInterface.getInterface(64).isValid()) {
atInterface(RSInterface.getInterface(64).getChild(5));
wait(random(200, 300));
gearfails = 0;
return true;
}
if (RSInterface.getInterface(228).isValid()) {
atInterface(RSInterface.getInterface(228).getChild(2));
wait(random(200, 300));
return false;
}
if (RSInterface.getInterface(241).isValid()) {
atInterface(RSInterface.getInterface(241).getChild(5));
wait(random(200, 300));
return false;
}
if (customsOfficer != null) {
if (tileOnScreen(customsOfficer.getLocation())) {
atNPC(customsOfficer, "Pay-Fare");
waitToStop();
wait(random(500, 1000));
return true;
} else {
walkTileMM(randomizeTile(customsOfficer.getLocation(), 2, 2));
waitToStop();
wait(random(500, 1000));
return true;
}
}
wait(random(2000, 3000));
} catch (Exception e) {
//IGNORED
}
return false;
}
public boolean takeBoatToKaramja() {
try {
int[] seamanIDs = new int[] { 376, 377, 378 };
RSNPC seaman = getNearestNPCByID(seamanIDs);
RSObject plank = getNearestObjectByID(2082);
if (plank != null) {
if (!getMyPlayer().isMoving()) {
atObject(plank, "Cross");
wait(random(1000, 1500));
return true;
}
}
if (RSInterface.getInterface(64).isValid()) {
atInterface(RSInterface.getInterface(64).getChild(5));
wait(random(6000, 7000));
gearfails = 0;
return true;
}
if (RSInterface.getInterface(228).isValid()) {
atInterface(RSInterface.getInterface(228).getChild(2));
wait(random(200, 300));
return true;
}
if (RSInterface.getInterface(241).isValid()) {
atInterface(RSInterface.getInterface(241).getChild(5));
wait(random(200, 300));
return true;
}
if (seaman != null) {
if (tileOnScreen(seaman.getLocation())) {
atNPC(seaman, "Pay-fare");
waitToStop();
wait(random(500, 1000));
return true;
} else {
walkTileMM(randomizeTile(seaman.getLocation(), 2, 2));
waitToStop();
wait(random(500, 1000));
return true;
}
}
wait(random(2000, 3000));
} catch (Exception e) {
//IGNORED
}
return false;
}
public boolean dropTunas() {
int[] keep = new int[] { 311, 301, 995, 377, 371 };
if (dropTuna) {
if(inventoryContains(359)){
dropAllExcept_(keep);
dropAllExcept_(keep);//Drop 3 times to make sure all are gone.
dropAllExcept_(keep);
return true;
}
}
return false;
}
private void antiBan() {
if (random(0, 10) == 0) {
final char[] LR = new char[] { KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT };
final char[] UD = new char[] { KeyEvent.VK_DOWN, KeyEvent.VK_UP };
final char[] LRUD = new char[] { KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP, KeyEvent.VK_UP };
final int random2 = random(0, 2);
final int random1 = random(0, 2);
final int random4 = random(0, 4);
if (random(0, 3) == 0) {
Bot.getInputManager().pressKey(LR[random1]);
wait(random(100, 400));
Bot.getInputManager().pressKey(UD[random2]);
wait(random(300, 600));
Bot.getInputManager().releaseKey(UD[random2]);
wait(random(100, 400));
Bot.getInputManager().releaseKey(LR[random1]);
} else {
Bot.getInputManager().pressKey(LRUD[random4]);
if (random4 > 1) {
wait(random(300, 600));
} else {
wait(random(500, 900));
}
Bot.getInputManager().releaseKey(LRUD[random4]);
}
if(random(0, 1) == 0) {
int x = random(0, 750);
int y = random(0, 500);
moveMouse(x, y);
}
} else {
wait(random(200, 2000));
}
}
public class GUI extends javax.swing.JFrame {
private final File settingsFile = new File(new File(GlobalConfiguration.Paths.getSettingsDirectory()), "iFisher.txt");
public GUI() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
startButton = new javax.swing.JButton();
pauseButton = new javax.swing.JButton();
applyButton = new javax.swing.JButton();
barbBox = new javax.swing.JCheckBox();
dropTunaBox = new javax.swing.JCheckBox();
dropBox = new javax.swing.JCheckBox();
locationCBox = new javax.swing.JComboBox();
fishingCBox = new javax.swing.JComboBox();
locationLabel = new javax.swing.JLabel();
fishingLabel = new javax.swing.JLabel();
paintBox = new javax.swing.JCheckBox();
antibanBox = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("iFisher v2.8");
setIconImages(null);
setResizable(false);
startButton.setText("Start Script");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
pauseButton.setText("Pause Script");
pauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseButtonActionPerformed(evt);
}
});
applyButton.setText("Apply Settings");
applyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
applyButtonActionPerformed(evt);
}
});
barbBox.setText("Barbarian Mode");
dropTunaBox.setText("Anti-Tuna");
dropBox.setText("Power Fishing");
locationCBox.setMaximumRowCount(5);
locationCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Al-Kharid", "Barbarian Village", "Catherby", "Draynor Village", "Fishing Guild", "Lumbridge", "Karamja", "Seers' Village" }));
locationCBox.setAutoscrolls(true);
locationCBox.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
locationCBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
locationCBoxActionPerformed(evt);
}
});
fishingCBox.setMaximumRowCount(5);
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shrimp & Anchovies", "Herring & Sardines" }));
fishingCBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fishingCBoxActionPerformed(evt);
}
});
locationLabel.setText("Location:");
fishingLabel.setText("Fishing:");
paintBox.setSelected(true);
paintBox.setText("Paint Progress");
antibanBox.setSelected(true);
antibanBox.setText("Anti-Ban");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(locationCBox, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(barbBox)
.addComponent(dropBox)
.addComponent(dropTunaBox)
.addComponent(locationLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antibanBox)
.addComponent(paintBox)
.addComponent(fishingLabel)
.addComponent(fishingCBox, 0, 162, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addComponent(startButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pauseButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(applyButton)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(fishingLabel)
.addComponent(locationLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(locationCBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(fishingCBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(paintBox)
.addComponent(dropTunaBox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(antibanBox)
.addComponent(dropBox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(barbBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pauseButton)
.addComponent(applyButton)
.addComponent(startButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(settingsFile));
String[] settings = new String[7];
String line = "";
for (int i = 0; i < settings.length && (line = in.readLine()) != null; i++) {
settings[i] = line;
}
try {
locationCBox.setSelectedIndex(Integer.parseInt(settings[1]));
makeChanges();
fishingCBox.setSelectedIndex(Integer.parseInt(settings[0]));
makeChanges();
barbBox.setSelected(settings[2].equals("1"));
dropBox.setSelected(settings[3].equals("1"));
dropTunaBox.setSelected(settings[4].equals("1"));
paintBox.setSelected(settings[5].equals("1"));
antibanBox.setSelected(settings[6].equals("1"));
} catch (Exception e) {
dropTunaBox.setSelected(false);
}
in.close();
} catch (IOException e) {
log("No Settings File Found!");
}
makeChanges();
pack();
}
public void makeChanges() {
String fish = (String) fishingCBox.getSelectedItem();
if (fish.equals("Swordfish & Tuna")) {
dropTunaBox.setEnabled(true);
dropTunaBox.setSelected(false);
} else {
dropTunaBox.setEnabled(false);
dropTunaBox.setSelected(false);
}
if (fish.equals("Swordfish & Tuna") || fish.equals("Sharks")) {
barbBox.setEnabled(true);
barbBox.setSelected(false);
} else {
barbBox.setEnabled(false);
barbBox.setSelected(false);
}
}
private void applyChanges() {
barbMode = barbBox.isSelected();
dropTuna = dropTunaBox.isSelected();
drop = dropBox.isSelected();
paint = paintBox.isSelected();
useAntiBan = antibanBox.isSelected();
String fish = (String) fishingCBox.getSelectedItem();
String location = (String) locationCBox.getSelectedItem();
if (location.equals("Barbarian Village")) {
location2 = "Barbarian Village";
bankTile = new RSTile(3094, 3490);
fishTile = new RSTile(3104, 3431);
toBank = new RSTile[] {new RSTile(3104,3431),new RSTile(3100,3434),new RSTile(3094,3439),new RSTile(3091,3445),new RSTile(3090,3451),new RSTile(3090,3457),new RSTile(3087,3463),new RSTile(3093,3464),new RSTile(3099,3474),new RSTile(3100,3480),new RSTile(3093,3484),new RSTile(3090,3490),new RSTile(3094,3491)};
toFish = reversePath(toBank);
if (fish.equals("Trout & Salmon")) {
fishing = "Trout & Salmon";
fishSpot = 328;
fishComm = "Lure";
gearMode = 1;
}
if (fish.equals("Pike")) {
fishing = "Pike";
fishSpot = 328;
fishComm = "Bait";
gearMode = 2;
}
}
if (location.equals("Lumbridge")) {
location2 = "Lumbridge";
drop = true;
if (fish.equals("Trout & Salmon")) {
fishTile = new RSTile(3240, 3247);
fishing = "Trout & Salmon";
fishSpot = 329;
fishComm = "Lure";
gearMode = 1;
}
if (fish.equals("Pike")) {
fishTile = new RSTile(3240, 3247);
fishing = "Pike";
fishSpot = 329;
fishComm = "Bait";
gearMode = 2;
}
if (fish.equals("Shrimp & Anchovies")) {
fishTile = new RSTile(3240, 3152);
fishing = "Shrimp & Anchovies";
fishSpot = 4908;
fishComm = "Net";
gearMode = 3;
}
if (fish.equals("Herring & Sardines")) {
fishTile = new RSTile(3240, 3152);
fishing = "Herring & Sardines";
fishSpot = 4908;
fishComm = "Bait";
gearMode = 2;
}
if (fish.equals("Crayfish")) {
fishTile = new RSTile(3256, 3205);
fishing = "Crayfish";
fishSpot = 6267;
fishComm = "Cage";
gearMode = 7;
}
toFish = generateFixedPath(fishTile);//To stop from wandering off..
}
if (location.equals("Draynor Village")) {
location2 = "Draynor";
bankTile = new RSTile(3093, 3243);
fishTile = new RSTile(3087, 3228);
toBank = new RSTile[] { new RSTile(3086, 3238), new RSTile(3092, 3243) };
toFish = new RSTile[] { new RSTile(3086, 3238), new RSTile(3088, 3230) };
if (fish.equals("Shrimp & Anchovies")) {
fishing = "Shrimp & Anchovies";
fishSpot = 327;
fishComm = "Net";
gearMode = 3;
}
if (fish.equals("Herring & Sardines")) {
fishing = "Herring & Sardines";
fishSpot = 327;
fishComm = "Bait";
gearMode = 2;
}
}
if (location.equals("Al-Kharid")) {
location2 = "Al-Kharid";
bankTile = new RSTile(3269, 3166);
fishTile = new RSTile(3271, 3145);
toBank = new RSTile[] { new RSTile(3271, 3144),new RSTile(3276, 3157),new RSTile(3270, 3167) };
toFish = reversePath(toBank);
if (fish.equals("Shrimp & Anchovies")) {
fishing = "Shrimp & Anchovies";
fishSpot = 330;
fishComm = "Net";
gearMode = 3;
}
if (fish.equals("Herring & Sardines")) {
fishing = "Herring & Sardines";
fishSpot = 330;
fishComm = "Bait";
gearMode = 2;
}
}
if (location.equals("Fishing Guild")) {
fishingGuild = true;
location2 = "Fishing Guild";
fishTile = new RSTile(2603, 3416);
bankTile = new RSTile(2589, 3418);
toBank = new RSTile[] { new RSTile(2594, 3415), new RSTile(2588, 3419) };
toFish = new RSTile[] { new RSTile(2599, 3421) };
if (fish.equals("Sharks")) {
fishSpot = 313;
fishComm = "Harpoon";
gearMode = 5;
fishing = "Sharks";
}
if (fish.equals("Swordfish & Tuna")) {
fishSpot = 312;
fishComm = "Harpoon";
gearMode = 5;//Harpoon
fishing = "Swordfish & Tuna";
}
if (fish.equals("Lobster")) {
fishSpot = 312;
fishComm = "Cage";
gearMode = 4;//Harpoon
fishing = "Lobster";
}
if (fish.equals("Bass & Cod & Mackerel")) {
fishing = "Bass & Cod & Mackerel";
fishSpot = 313;
fishComm = "Net";
gearMode = 6;
}
} else {
fishingGuild = false;
}
if (location.equals("Catherby")) {
location2 = "Catherby";
catherbyLoc = true;
fishTile = new RSTile(2847, 3430);
bankTile = new RSTile(2809, 3440);
toBank = new RSTile[] {new RSTile(2853, 3428), new RSTile(2849, 3431), new RSTile(2843, 3433), new RSTile(2837, 3435), new RSTile(2830, 3436), new RSTile(2824, 3437), new RSTile(2817, 3436), new RSTile(2811, 3436), new RSTile(2809, 3440)};
toFish = new RSTile[] {new RSTile(2811, 3435), new RSTile(2818, 3436), new RSTile(2824, 3437), new RSTile(2830, 3436), new RSTile(2835, 3435), new RSTile(2837, 3432)};
if (fish.equals("Sharks")) {
fishSpot = 322;
fishComm = "Harpoon";
gearMode = 5;
fishing = "Sharks";
}
if (fish.equals("Swordfish & Tuna")) {
fishSpot = 321;
fishComm = "Harpoon";
gearMode = 5;
fishing = "Swordfish & Tuna";
}
if (fish.equals("Lobster")) {
fishSpot = 321;
fishComm = "Cage";
gearMode = 4;
fishing = "Lobster";
}
if (fish.equals("Shrimp & Anchovies")) {
fishing = "Shrimp & Anchovies";
fishSpot = 320;
fishComm = "Net";
gearMode = 3;
}
if (fish.equals("Herring & Sardines")) {
fishing = "Herring & Sardines";
fishSpot = 320;
fishComm = "Bait";
gearMode = 2;
}
if (fish.equals("Bass & Cod & Mackerel")) {
fishing = "Bass & Cod & Mackerel";
fishSpot = 322;
fishComm = "Net";
gearMode = 6;
}
} else {
catherbyLoc = false;
}
if (location.equals("Karamja")) {
location2 = "Karamja";
kjMode = true;
bankTile = new RSTile(3047, 3235);
fishTile = new RSTile(2925, 3177);
toFish = new RSTile[] { new RSTile(3047, 3235), new RSTile(3041, 3236),
new RSTile(3034, 3236), new RSTile(3028, 3236),
new RSTile(3028, 3231), new RSTile(3028, 3227),
new RSTile(3028, 3222), new RSTile(3027, 3217),
new RSTile(2954, 3146), new RSTile(2948, 3146),
new RSTile(2943, 3145), new RSTile(2937, 3146),
new RSTile(2932, 3149), new RSTile(2925, 3150), //The longer the better...
new RSTile(2919, 3152), new RSTile(2915, 3156),
new RSTile(2919, 3160), new RSTile(2920, 3165),
new RSTile(2922, 3169), new RSTile(2925, 3173),
new RSTile(2925, 3179)};
toBank = reversePath(toFish);
if (fish.equals("Shrimp & Anchovies")) {
fishing = "Shrimp & Anchovies";
fishSpot = 323;
fishComm = "Net";
gearMode = 3;//Net
}
if (fish.equals("Herring & Sardines")) {
fishing = "Herring & Sardines";
fishSpot = 323;
fishComm = "Bait";
gearMode = 2;//net
}
if (fish.equals("Lobster")) {
fishId = 377;
fishing = "Lobster";
fishSpot = 324;
fishComm = "Cage";
gearMode = 4;//Lobster Cage
}
if (fish.equals("Swordfish & Tuna")) {
fishId = 371;
fishing = "Swordfish & Tuna";
fishSpot = 324;
fishComm = "Harpoon";
gearMode = 5;//Harpoon
}
} else {
kjMode = false;
}
if (location.equals("Seers' Village")) {
location2 = "Seers' Village";
bankTile = new RSTile(2726, 3493);
fishTile = new RSTile(2722, 3529);
toBank = new RSTile[] {new RSTile(2722, 3529), new RSTile(2727, 3528), new RSTile(2732, 3526), new RSTile(2736, 3521), new RSTile(2740, 3514), new RSTile(2740, 3510), new RSTile(2742, 3504), new RSTile(2738, 3495), new RSTile(2735, 3490), new RSTile(2728, 3485), new RSTile(2725, 3491)};
toFish = reversePath(toBank);
if (fish.equals("Trout & Salmon")) {
fishing = "Trout & Salmon";
fishSpot = 315;
fishComm = "Lure";
gearMode = 1;
}
if (fish.equals("Pike")) {
fishing = "Pike";
fishSpot = 315;
fishComm = "Bait";
gearMode = 2;
}
}
PrintWriter out = null;
try {//Saves
out = new PrintWriter(new FileWriter(settingsFile));
String[] settings = {
"" + fishingCBox.getSelectedIndex(),
"" + locationCBox.getSelectedIndex(),
barbBox.isSelected() ? "1" : "0",
dropBox.isSelected() ? "1" : "0",
dropTunaBox.isSelected() ? "1" : "0",
paintBox.isSelected() ? "1" : "0",
antibanBox.isSelected() ? "1" : "0",
};
for (String line : settings) {
out.println(line);
}
out.close();
} catch (IOException e) {
log("Saveing settings file failed!");
}
getPrices();
}
public void getPrices() {
String fish = (String) fishingCBox.getSelectedItem();
if (fish.equals("Bass & Cod & Mackerel")) {//Bass
GEItemInfo rawFish = grandExchange.loadItemInfo(363);
bassPrice = rawFish.getMarketPrice();
}
if (fish.equals("Bass & Cod & Mackerel")) {//Cod
GEItemInfo rawFish = grandExchange.loadItemInfo(341);
codPrice = rawFish.getMarketPrice();
}
if (fish.equals("Bass & Cod & Mackerel")) {//Mackerel
GEItemInfo rawFish = grandExchange.loadItemInfo(353);
mackerelPrice = rawFish.getMarketPrice();
}
if (fish.equals("Shrimp & Anchovies")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(317);
shrimpsPrice = rawFish.getMarketPrice();
}
if (fish.equals("Shrimp & Anchovies")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(321);
anchoviesPrice = rawFish.getMarketPrice();
}
if (fish.equals("Lobster")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(377);
lobsterPrice = rawFish.getMarketPrice();
}
if (fish.equals("Swordfish & Tuna")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(359);
tunaPrice = rawFish.getMarketPrice();
}
if (fish.equals("Swordfish & Tuna")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(371);
swordfishPrice = rawFish.getMarketPrice();
}
if (fish.equals("Herring & Sardines")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(345);
herringPrice = rawFish.getMarketPrice();
}
if (fish.equals("Herring & Sardines")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(345);
sardinesPrice = rawFish.getMarketPrice();
}
if (fish.equals("Trout & Salmon")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(335);
troutPrice = rawFish.getMarketPrice();
}
if (fish.equals("Trout & Salmon")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(331);
salmonPrice = rawFish.getMarketPrice();
}
if (fish.equals("Pike")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(349);
pikePrice = rawFish.getMarketPrice();
}
if (fish.equals("Sharks")) {
GEItemInfo rawFish = grandExchange.loadItemInfo(383);
sharkPrice = rawFish.getMarketPrice();
}
}
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (!startScript) {
startScript = true;
applyChanges();
startButton.setText("Stop Script");
} else {
stopScript();
}
}
private void pauseButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (!paused) {
paused = true;
pauseButton.setText("Resume Script");
} else {
paused = false;
pauseButton.setText("Pause Script");
}
}
private void applyButtonActionPerformed(java.awt.event.ActionEvent evt) {
applyChanges();
}
private void locationCBoxActionPerformed(java.awt.event.ActionEvent evt) {
String location = (String) locationCBox.getSelectedItem();
if (location.equals("Lumbridge")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Crayfish", "Shrimp & Anchovies", "Herring & Sardines", "Trout & Salmon", "Pike" }));
dropBox.setEnabled(false);
dropBox.setSelected(true);
} else {
dropBox.setEnabled(true);
dropBox.setSelected(false);
}
if (location.equals("Al-Kharid")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shrimp & Anchovies", "Herring & Sardines" }));
}
if (location.equals("Barbarian Village") || location.equals("Seers' Village")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Trout & Salmon", "Pike" }));
}
if (location.equals("Draynor Village")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shrimp & Anchovies", "Herring & Sardines" }));
}
if (location.equals("Karamja")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shrimp & Anchovies", "Herring & Sardines", "Lobster", "Swordfish & Tuna" }));
}
if (location.equals("Catherby")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shrimp & Anchovies", "Herring & Sardines", "Bass & Cod & Mackerel", "Lobster", "Swordfish & Tuna", "Sharks" }));
}
if (location.equals("Fishing Guild")) {
fishingCBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bass & Cod & Mackerel", "Lobster", "Swordfish & Tuna", "Sharks" }));
}
makeChanges();
}
private void fishingCBoxActionPerformed(java.awt.event.ActionEvent evt) {
makeChanges();
}
private javax.swing.JCheckBox antibanBox;
private javax.swing.JButton applyButton;
private javax.swing.JCheckBox barbBox;
private javax.swing.JCheckBox dropBox;
private javax.swing.JCheckBox dropTunaBox;
private javax.swing.JComboBox fishingCBox;
private javax.swing.JLabel fishingLabel;
private javax.swing.JComboBox locationCBox;
private javax.swing.JLabel locationLabel;
private javax.swing.JCheckBox paintBox;
private javax.swing.JButton pauseButton;
private javax.swing.JButton startButton;
}
}
| true
|
0f7cdc81f7653eabdd24666c742695ecb09f1f47
|
Java
|
jmd7p7/JustInTimeCBT
|
/app/src/main/java/com/jmd2479/justintimecbt/TwoSectionActivity.java
|
UTF-8
| 7,215
| 2.140625
| 2
|
[] |
no_license
|
package com.jmd2479.justintimecbt;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Toast;
import routing.TwoSectionActivityRouter;
public class TwoSectionActivity extends AppCompatActivity implements BehaviorListFragment.onBehaviorSelectedListener,
TriggerListFragment.onTriggerSelectedListener, ConsequenceListFragment.onConsequenceSelectedListener,
ShutdownListFragment.onShutdownSelectedListener, RationalizationListFragment.onRationalizationSelectedListener,
AlternativeListFragment.onAlternativeSelectedListener, LogicalResponseListFragment.onLogicalResponseSelectedListener{
private FragmentManager fm;
private AddNewFragment addNewFragment;
private Bundle extras;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_section);
extras = getIntent().getExtras();
TwoSectionActivityRouter router = new TwoSectionActivityRouter(extras, this);
router.handleRoute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_two_section, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Calls the HomeActivity's DisplayFragment() method
@Override
public void onBehaviorSelected(Behavior behavior) {
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("HomeActivityIndex", R.string.HOME_ACTIVITY_SELECTED_BEHAVIOR_INDEX);
intent.putExtra("SelectedBehavior", behavior.getName());
intent.putExtra("BehaviorId", behavior.getId());
startActivity(intent);
}
@Override
public void onBehaviorEdit(Behavior behavior){
Bundle newArgs = new Bundle();
ChangeItemDialogFragment changeItemDialogFragment = new ChangeItemDialogFragment();
newArgs.putString("EditItemType", "Behavior");
newArgs.putString("EditItemText", behavior.getName());
newArgs.putInt("EditItemId", behavior.getId());
newArgs.putString("DBTable", "Behavior");
newArgs.putInt("EditItemTypeIndex", R.string.EDIT_ITEM_TYPE_BEHAVIOR_INDEX);
changeItemDialogFragment.setArguments(newArgs);
FragmentManager fragmentManager = getSupportFragmentManager();
changeItemDialogFragment.show(fragmentManager, "EditBehaviorDialogFragment");
}
@Override
public void onTriggerSelected(Trigger selectedTrigger) {
Bundle args = new Bundle();
args.putInt("TwoSectionActivityIndex",R.string.TWO_SECTION_SHUTDOWN_INDEX);
args.putString("TriggerName", selectedTrigger.getName());
args.putInt("ParentId", selectedTrigger.getId());
TwoSectionActivityRouter router = new TwoSectionActivityRouter(args, this);
router.handleRoute();
}
@Override
public void onTriggerEdit(Trigger selectedTrigger) {
Bundle newArgs = new Bundle();
ChangeItemDialogFragment changeItemDialogFragment = new ChangeItemDialogFragment();
newArgs.putString("EditItemType", "Trigger");
newArgs.putString("EditItemText", selectedTrigger.getName());
newArgs.putInt("EditItemId", selectedTrigger.getId());
newArgs.putString("DBTable", "Trigger");
newArgs.putInt("EditItemTypeIndex", R.string.EDIT_ITEM_TYPE_TRIGGER_INDEX);
changeItemDialogFragment.setArguments(newArgs);
FragmentManager fragmentManager = getSupportFragmentManager();
changeItemDialogFragment.show(fragmentManager, "EditTriggerDialogFragment");
}
@Override
public void onConsequenceSelected(Consequence selectedConsequence) {
Toast.makeText(this, "You clicked on a consequence!", Toast.LENGTH_LONG).show();
}
@Override
public void onConsequenceEdit(Consequence selectedConsequence) {
Bundle newArgs = new Bundle();
ChangeItemDialogFragment changeItemDialogFragment = new ChangeItemDialogFragment();
newArgs.putString("EditItemType", "Consequence");
newArgs.putString("EditItemText", selectedConsequence.getName());
newArgs.putInt("EditItemId", selectedConsequence.getId());
newArgs.putString("DBTable", "Consequence");
newArgs.putInt("EditItemTypeIndex", R.string.EDIT_ITEM_TYPE_CONSEQUENCE_INDEX);
changeItemDialogFragment.setArguments(newArgs);
FragmentManager fragmentManager = getSupportFragmentManager();
changeItemDialogFragment.show(fragmentManager, "EditConsequenceDialogFragment");
}
@Override
public void onShutdownSelected(ShutDown selectedShutdown) {
Toast.makeText(this, "You clicked on a ShutDown!", Toast.LENGTH_LONG).show();
}
@Override
public void onRationalizationSelected(Rationalization selectedRationalization) {
Bundle args = new Bundle();
args.putInt("TwoSectionActivityIndex", R.string.TWO_SECTION_LOGICALRESPONSE_INDEX);
//args.putString("TriggerName", selectedTrigger.getName());
args.putInt("ParentId", selectedRationalization.getId());
TwoSectionActivityRouter router = new TwoSectionActivityRouter(args, this);
router.handleRoute();
}
@Override
public void onRationalizationEdit(Rationalization selectedRationalization) {
}
@Override
public void onAlternativeSelected(Alternative selectedAlternative) {
}
@Override
public void onAlternativeEdit(Alternative selectedAlternative) {
Bundle newArgs = new Bundle();
ChangeItemDialogFragment changeItemDialogFragment = new ChangeItemDialogFragment();
newArgs.putString("EditItemType", "Alternative");
newArgs.putString("EditItemText", selectedAlternative.getName());
newArgs.putInt("EditItemId", selectedAlternative.getId());
newArgs.putString("DBTable", "Alternative");
newArgs.putInt("EditItemTypeIndex", R.string.EDIT_ITEM_TYPE_ALTERNATIVE_INDEX);
changeItemDialogFragment.setArguments(newArgs);
FragmentManager fragmentManager = getSupportFragmentManager();
changeItemDialogFragment.show(fragmentManager, "EditAlternativeDialogFragment");
}
@Override
public void onLogicalResponseSelected(LocicalResponse selectedLogicalResponse) {
}
@Override
public void onLogicalResponseEdit(LocicalResponse selectedLogicalResponse) {
}
}
| true
|
ea1bcd3195f750ab213133e36e977da2b481a897
|
Java
|
zhang1998/browser
|
/second/quark/src/main/java/com/ui/edittext/q.java
|
UTF-8
| 2,877
| 1.679688
| 2
|
[] |
no_license
|
package com.ui.edittext;
import android.text.Editable;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
/* compiled from: ProGuard */
class q implements SpanWatcher, TextWatcher {
final /* synthetic */ TextView a;
private CharSequence b;
private z c;
private q(TextView textView) {
this.a = textView;
this.c = new z(textView);
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (!(!AccessibilityManager.getInstance(this.a.mContext).isEnabled() || TextView.e(this.a.at) || (this.a.ay instanceof PasswordTransformationMethod))) {
this.b = charSequence.toString();
}
this.a.b(charSequence, i, i2, i3);
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
TextView textView = this.a;
ac acVar = textView.f;
if (acVar == null || acVar.f == 0) {
textView.g();
}
if (acVar != null) {
acVar.i = true;
if (acVar.j < 0) {
acVar.j = i;
acVar.k = i + i2;
} else {
acVar.j = Math.min(acVar.j, i);
acVar.k = Math.max(acVar.k, (i + i2) - acVar.l);
}
acVar.l += i3 - i2;
}
textView.a(charSequence, i, i2, i3);
textView.n();
this.c.a(charSequence);
if (!AccessibilityManager.getInstance(this.a.mContext).isEnabled()) {
return;
}
if (this.a.isFocused() || (this.a.isSelected() && this.a.isShown())) {
textView = this.a;
CharSequence charSequence2 = this.b;
AccessibilityEvent obtain = AccessibilityEvent.obtain(16);
obtain.setFromIndex(i);
obtain.setRemovedCount(i2);
obtain.setAddedCount(i3);
obtain.setBeforeText(charSequence2);
textView.sendAccessibilityEventUnchecked(obtain);
this.b = null;
}
}
public void afterTextChanged(Editable editable) {
this.a.a(editable);
if (g.a((CharSequence) editable, 2048) != 0) {
g.e(editable);
}
}
public void onSpanChanged(Spannable spannable, Object obj, int i, int i2, int i3, int i4) {
this.a.a((Spanned) spannable, obj, i, i3, i2, i4);
}
public void onSpanAdded(Spannable spannable, Object obj, int i, int i2) {
this.a.a((Spanned) spannable, obj, -1, i, -1, i2);
}
public void onSpanRemoved(Spannable spannable, Object obj, int i, int i2) {
this.a.a((Spanned) spannable, obj, i, -1, i2, -1);
}
}
| true
|
4926271b8ba5a4b1d8b088627b494ca7da1546ee
|
Java
|
miraclehjt/imooccoupon
|
/imooc-coupon-service/coupon-distribution/src/main/java/com/imooc/distribution/feign/hystrix/TemplateClientHystrix.java
|
UTF-8
| 1,440
| 2.125
| 2
|
[] |
no_license
|
package com.imooc.distribution.feign.hystrix;
import com.imooc.distribution.vo.CommonResponse;
import com.imooc.distribution.vo.CouponTemplateSDK;
import com.imooc.distribution.feign.TemplateClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* 优惠券模板 Feign 熔断降级策略
*/
@Slf4j
@Component
public class TemplateClientHystrix implements TemplateClient {
/**
* 查找所有了用的优惠券模板
*
* @return
*/
@Override
public CommonResponse<List<CouponTemplateSDK>> findAllUsableTemplate() {
log.error("[eureka-client-distribution-template] findAllUsableTemplate " +
"request error");
return new CommonResponse<>(
-1,
"[eureka-client-distribution-template] request error",
Collections.emptyList()
);
}
/**
* 获取模板 ids 到CouponTemplateSDK的映射
*
* @param ids
* @return
*/
@Override
public CommonResponse<Map<Integer, CouponTemplateSDK>> findIds2TemplateSDK(Collection<Integer> ids) {
log.error("[eureka-client-distribution-template] findIds2TemplateSDK " +
"request error");
return new CommonResponse<>(
-1,
"[eureka-client-distribution-template] request error",
new HashMap<>()
);
}
}
| true
|
fc7529ca130475afed84b87d9e46b19005ff5c9b
|
Java
|
ErickSilv/TestSelenium
|
/src/test/java/acessotest/acessoteste.java
|
UTF-8
| 1,196
| 2.109375
| 2
|
[] |
no_license
|
package acessotest;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import acesso.AcessarPagina;
import acesso.AcessarVideo;
public class acessoteste {
static WebDriver driver;
static AcessarPagina acessarpagina;
static AcessarVideo acessarvideo;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.youtube.com/");
acessarpagina = new AcessarPagina(driver);
driver.manage().window().maximize();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
boolean i = driver.getPageSource().contains("Rubens Leme");
acessarvideo = new AcessarVideo(driver);
acessarvideo.AcessarVideo();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
acessarpagina.AcessarPagina();
}
}
| true
|
47c4ee004365cc05e137280b11396bf09738e346
|
Java
|
gladiator87/singtel_test_task
|
/src/test/java/ru/ivanov/singtel/CountTest.java
|
UTF-8
| 1,087
| 2.875
| 3
|
[] |
no_license
|
package ru.ivanov.singtel;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CountTest {
@Test
public void test() {
AnimalFactory factory = new AnimalFactory();
Animal[] animals = new Animal[]{
factory.createBird(AnimalType.DUCK, null),
factory.createBird(AnimalType.CHICKEN, null),
factory.createBird(AnimalType.ROOSTER, null),
factory.createBird(AnimalType.PARROT, () -> "Cock-a-doodle-doo"),
factory.createFish(AnimalType.SHARK),
factory.createFish(AnimalType.CLOWNFISH),
factory.createMammal(AnimalType.DOLPHIN),
factory.createMammal(AnimalType.DOG),
factory.createMammal(AnimalType.CAT),
factory.createInsect(AnimalType.BUTTERFLY)
};
assertEquals(3L, factory.getCanFlyCount());
assertEquals(6L, factory.getCanWalkCount());
assertEquals(4L, factory.getCanSingCount());
assertEquals(5L, factory.getCanSwimCount());
}
}
| true
|
48c3e4e4b4fdb17e0fd2bf6d8b59a0816f392dc4
|
Java
|
esialb/Trees
|
/Trees/src/main/java/FamilyTree.java
|
UTF-8
| 1,393
| 3.21875
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
public class FamilyTree {
Tree<String> tree = new SimpleTree<String>();
Position<String> bob = new SimplePosition<String>("Bob");
Position<String> jane = new SimplePosition<String>("Jane");
Position<String> tim = new SimplePosition<String>("tim");
Position<String> kate = new SimplePosition<String>("kate");
public FamilyTree(Tree<String> tree){
tree.setRoot(bob);
tree.insert(bob, jane);
tree.insert(bob, tim);
tree.insert(tim, kate);
FamilyTree family = new FamilyTree(tree);
}
public String getParent(Position<String> person){
if(tree.parent(person) == null)
return null;
return tree.parent(person).getElement();
}
public String getGrandparent(Position<String> person){
if(tree.parent(person) == null || tree.parent(tree.parent(person)) == null)
return null;
return tree.parent(tree.parent(person)).getElement();
}
public List<String> getChildren(Position<String> person){
List<String> kids = new ArrayList<>();
for(Position<String> kid : tree.children(person))
kids.add(kid.getElement());
return kids;
}
public List<String> getGrandChildren(Position<String> person){
List<String> gkids = new ArrayList<>();
for(Position<String> kid : tree.children(person)) {
for(Position<String> gkid : tree.children(kid))
gkids.add(gkid.getElement());
}
return gkids;
}
}
| true
|
71484b86ad7a759f7b9d7712b26b9e216fe8a5ee
|
Java
|
smjergie/Seans_Vesion_Of_P4
|
/CS314_GroupG_P4/src/cs314/groupg/p4/V1/displayQuiz.java
|
UTF-8
| 9,875
| 2.328125
| 2
|
[] |
no_license
|
package cs314.groupg.p4.V1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class displayQuiz extends Activity{
public final static String EXTRA_RESULTS = "cs314.groupg.p4.V1.RESULTS";
private final static int DEFAULT_QUESTION_COUNT = 10;
private final static int QUESTIONS_IN_FILE = 50;
private Question[] questions;
private int[] questionStatus;
private int questionCount;
private int currentQ;
private TextView stub;
private RadioGroup answerGroup;
private RadioButton radio0;
private RadioButton radio1;
private RadioButton radio2;
private RadioButton radio3;
private Button backBtn;
private Button skipBtn;
private Button answerBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
questionCount = DEFAULT_QUESTION_COUNT;
//create array to hold statuses of all questions
//-1:notAttempted, 0:answeredWrong, 1:answeredCorrect
questionStatus = new int[questionCount];
for(int i = 0; i < questionCount; i++){
questionStatus[i] = -1; //set statuses all to notAttempted
}
setContentView(R.layout.display_quiz);
//getGUIObjects
stub = (TextView) findViewById(R.id.question);
answerGroup = (RadioGroup) findViewById(R.id.answergroup);
radio0 = (RadioButton) findViewById(R.id.answer1);
radio1 = (RadioButton) findViewById(R.id.answer2);
radio2 = (RadioButton) findViewById(R.id.answer3);
radio3 = (RadioButton) findViewById(R.id.answer4);
backBtn = (Button) findViewById(R.id.back_button);
skipBtn = (Button) findViewById(R.id.next_button);
answerBtn = (Button) findViewById(R.id.answer_button);
//fill Question[] with questions from file
questions = importQuestions("P4 Questions.txt");
//Add listener to enable answer button when
answerGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged (RadioGroup group, int checkedId) {
answerBtn.setEnabled(true);
}
});
//Setup Initial Question
currentQ = 0;
updateQuestion();
resetRadios();
backBtn.setEnabled(false);
backBtn.setBackgroundResource(R.drawable.back_button_disabled);
answerBtn.setEnabled(false);
}
private Question[] importQuestions(String fileName) {
Question[] allQs = new Question[QUESTIONS_IN_FILE];
AssetManager aManager = getAssets();
InputStream iStream = null;
try {
iStream = aManager.open(fileName);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
String line;
for(int ctr = 0; ctr < QUESTIONS_IN_FILE; ctr++){
Question question = new Question();
//Stub
try {
line = bReader.readLine();
question.setStub(line.toString().substring(3));
} catch (IOException e) {
e.printStackTrace();
}
String[] ans = new String[4];
//C
try {
line = bReader.readLine();
ans[0] = (line.toString().substring(3));
} catch (IOException e) {
e.printStackTrace();
}
//D1
try {
line = bReader.readLine();
ans[1] = (line.toString().substring(3));
} catch (IOException e) {
e.printStackTrace();
}
//D2
try {
line = bReader.readLine();
ans[2] = (line.toString().substring(3));
} catch (IOException e) {
e.printStackTrace();
}
//D3
try {
line = bReader.readLine();
ans[3] = (line.toString().substring(3));
} catch (IOException e) {
e.printStackTrace();
}
question.setAnswers(ans[1], ans[2], ans[3], ans[0]);
allQs[ctr] = question;
}
return getRandomQuestions(allQs, questionCount);
}
/**
* Randomizes questions from allQs into an array of size questionCt
* @return array[questionCt] containing random questions from allQs
*/
private Question[] getRandomQuestions(Question[] allQs, int questionCt) {
Question[] _qs = new Question[questionCt];
for(int i = 0; i < questionCount; i++){
//Randomly pick questionCount number of questions
int r1 = (int) (Math.random() * allQs.length);
Question randQ = allQs[r1];
while(!randQ.getClean()){
//randQ has already been read, so read another
r1 = (int) (Math.random() * allQs.length);
randQ = allQs[r1];
}
//question has not been read already, add it to question list in next position and set clean=false to prevent duplicates
_qs[i] = randQ;
allQs[r1].setClean(false);
}
return _qs;
}
/**
* Updates the GUI to show the question at index currentQ in questions[]
* Modifies answers[] to no longer have the leading "(c)" in front of correct answer
* @return Radio index of correct answer
*/
private void updateQuestion() {
String[] answers = questions[currentQ].getAnswers();
stub.setText((currentQ + 1) + ") " + questions[currentQ].getStub());
radio0.setText(answers[0]);
radio1.setText(answers[1]);
radio2.setText(answers[2]);
radio3.setText(answers[3]);
//Check radio that user already answered
resetRadios();
if(questionStatus[currentQ] != -1){
int userAnsIndex = questions[currentQ].getUserAnswer();
RadioButton userAnswer = (RadioButton) answerGroup.getChildAt(userAnsIndex);
userAnswer.setChecked(true);
answerBtn.setEnabled(false);
}
if(currentQ == 0){
//disable skip btn, end of question list
backBtn.setEnabled(false);
backBtn.setBackgroundResource(R.drawable.back_button_disabled);
}else {
backBtn.setEnabled(true);
backBtn.setBackgroundResource(R.drawable.back_button);
}
if(currentQ == questionCount -1){
//disable skip btn, end of question list
skipBtn.setEnabled(false);
skipBtn.setBackgroundResource(R.drawable.forward_button_disabled);
}else {
skipBtn.setEnabled(true);
skipBtn.setBackgroundResource(R.drawable.forward_button);
}
}
private int getSelectedAnsIndex() {
int index = -1;
if(radio0.isChecked())
index = 0;
else if(radio1.isChecked())
index = 1;
else if(radio2.isChecked())
index = 2;
else if(radio3.isChecked())
index = 3;
return index;
}
/**
* Clear radios and disable answer btn
*/
private void resetRadios() {
RadioGroup radios = ((RadioGroup) findViewById(R.id.answergroup)) ;
radios.clearCheck();
answerBtn.setEnabled(false);
}
/** onClick listener for backBtn **/
public void backClick(View view){
//Mark Q as not answered and load previous Q
if(currentQ == questionCount -1){
//enable skip btn, not on last one anymore
skipBtn.setEnabled(true);
}
//Setup Q unless at end
currentQ--;
updateQuestion();
if(currentQ == 0){
//enable backBtn
backBtn.setEnabled(false);
}
}
/** onClick listener for skipBtn **/
public void skipClick(View view){
//Mark Q as not answered and load next Q
if(currentQ == 0){
//enable backBtn
backBtn.setEnabled(true);
backBtn.setBackgroundResource(R.drawable.back_button_disabled);
}
//Setup Q uless at end
currentQ++;
updateQuestion();
if(currentQ == questionCount -1){
//disable skip btn, end of question list
skipBtn.setEnabled(false);
skipBtn.setBackgroundResource(R.drawable.forward_button_disabled);
}
}
/** onClick listener for answerBtn **/
public void answerClick(View view){
//Show next Q, save ans
int userAns = getSelectedAnsIndex();
questions[currentQ].setUserAnswer(userAns);
//resetRadios();
//answerBtn.setEnabled(false);
if( userAns == questions[currentQ].getCorrectAnswer()){
//user answered correctly
questionStatus[currentQ] = 1;
//show correct dialog
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
TextView correctTxt = new TextView(this);
correctTxt.setText("Correct!");
correctTxt.setGravity(Gravity.CENTER_HORIZONTAL);
correctTxt.setTextSize(40);
correctTxt.setTextColor(Color.parseColor("#2ECC71"));
dialog.setView(correctTxt);
dialog.setPositiveButton("OK", null);
dialog.setCancelable(true);
dialog.create().show();
} else {
//user answered wrong
questionStatus[currentQ] = 0;
//show incorrect dialog
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
TextView incorrectTxt = new TextView(this);
incorrectTxt.setText("Incorrect!");
incorrectTxt.setGravity(Gravity.CENTER_HORIZONTAL);
incorrectTxt.setTextSize(40);
incorrectTxt.setTextColor(Color.parseColor("#E74C3C"));
dialog.setView(incorrectTxt);
dialog.setPositiveButton("OK", null);
dialog.setCancelable(true);
dialog.create().show();
}
if(currentQ == 0){
//enable backBtn
backBtn.setEnabled(true);
}
if(currentQ == questionCount -2){
//disable skip btn, end of question list
skipBtn.setEnabled(false);
}
if(currentQ == questionCount -1){
//answered final question, sent to results
Intent intent = new Intent(this, displayResults.class);
intent.putExtra(EXTRA_RESULTS, questionStatus);
finish();
startActivity(intent);
return;
}
//Setup Q uless at end
//Delete the bellow comment to enable question change when you answer a question
/*currentQ++;
updateQuestion();*/
}
/** onClick listener for endQuizBtn **/
public void endQuizClick(View view){
resetRadios();
Intent intent = new Intent(this, displayResults.class);
intent.putExtra(EXTRA_RESULTS, questionStatus);
finish();
startActivity(intent);
}
}
| true
|
7b0c05ccabe31730f0797cd2a0acee6089865be3
|
Java
|
moutainhigh/new_laiyifen
|
/demo/src/com/netease/nim/demo/chatroom/adapter/ChatRoomChoiceAdapter.java
|
UTF-8
| 3,041
| 2.03125
| 2
|
[] |
no_license
|
package com.netease.nim.demo.chatroom.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.netease.nim.demo.R;
import com.netease.nim.demo.chatroom.activity.ChatRoomActivity;
import com.netease.nim.demo.chatroom.model.SearchRoomModel;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.common.ui.imageview.HeadImageView;
import java.util.List;
/**
* @author SevenCheng
*/
public class ChatRoomChoiceAdapter extends RecyclerView.Adapter {
private Context mContext;
private List<SearchRoomModel.DataBean.ChatRoomsBean> chatRoomsList;
public ChatRoomChoiceAdapter(Context context, List<SearchRoomModel.DataBean.ChatRoomsBean> chatRoomsList) {
this.mContext = context;
this.chatRoomsList = chatRoomsList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chatlist, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
ViewHolder viewHolder = (ViewHolder) holder;
final SearchRoomModel.DataBean.ChatRoomsBean chatRoomsBean = chatRoomsList.get(position);
Glide.with(mContext).load(chatRoomsBean.getCreatorAvatar()).asBitmap().placeholder(NimUIKit.getUserInfoProvider().getDefaultIconResId()).into(viewHolder.mIcon);
viewHolder.mLeader.setText(chatRoomsBean.getCreator());
viewHolder.mNo.setText(chatRoomsBean.getRoomId() + "");
viewHolder.mName.setText(chatRoomsBean.getName() + "");
viewHolder.mine.setVisibility(View.VISIBLE);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//进入聊天室
ChatRoomActivity.start(mContext, chatRoomsBean.getRoomId() + "", chatRoomsBean.getName());
}
});
}
}
@Override
public int getItemCount() {
return chatRoomsList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public HeadImageView mIcon;
TextView mLeader;
TextView mNo;
TextView mName;
View mine;
public ViewHolder(View itemView) {
super(itemView);
mIcon = (HeadImageView) itemView.findViewById(R.id.icon);
mLeader = (TextView) itemView.findViewById(R.id.leader);
mNo = (TextView) itemView.findViewById(R.id.no);
mName = (TextView) itemView.findViewById(R.id.name);
mine = itemView.findViewById(R.id.mine);
}
}
}
| true
|
54e2cedf77e3f7dd4c1a61b7b826f73635a7724d
|
Java
|
SerjNF/academIT
|
/List/src/ru/inbox/foreman/test/Test.java
|
UTF-8
| 3,633
| 3.46875
| 3
|
[] |
no_license
|
package ru.inbox.foreman.test;
import ru.inbox.foreman.myList.SingleLinkedList;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Test
*
* @author SergeyNF
*/
public class Test {
public static void main(String[] arg) {
SingleLinkedList<String> singleLinkedList = new SingleLinkedList<>();
try (Scanner scanner = new Scanner(new FileInputStream("input.txt"))) {
while (scanner.hasNext()) {
singleLinkedList.add(scanner.next().split("[\\s ,.()]")[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Size = " + singleLinkedList.getSize());
System.out.println(singleLinkedList.toString());
SingleLinkedList<String> newList = singleLinkedList.copy();
System.out.println("copy");
System.out.println(newList.toString());
System.out.println("Size = " + newList.getSize());
singleLinkedList.reverse();
System.out.println("revers");
System.out.println(singleLinkedList.toString());
System.out.println("Первый элемент: " + singleLinkedList.get());
int indexElement = 2;
System.out.printf("Элемент №%d: %s%n", indexElement, singleLinkedList.getAtIndex(indexElement));
System.out.printf("Элемент №%d: %s заменен на: ЗАМЕНА%n", indexElement, singleLinkedList.setAtIndex(indexElement, "ЗАМЕНА"));
System.out.printf("Элемент №%d: %s%n", indexElement, singleLinkedList.getAtIndex(indexElement));
System.out.println(singleLinkedList.toString());
System.out.printf("Элемент №%d: %s удален%n", indexElement, singleLinkedList.removeAtIndex(indexElement));
System.out.printf("Элемент №%d: %s%n", indexElement -1, singleLinkedList.getAtIndex(indexElement-1));
System.out.println("Size = " + singleLinkedList.getSize());
System.out.println(singleLinkedList.toString());
String word = "ВСТАВКА";
singleLinkedList.addAtIndex(indexElement -1, word);
System.out.printf("Перед элементом №%d вставлен %s%n", indexElement, word);
indexElement = 0;
System.out.printf("Элемент №%d: %s%n", indexElement, singleLinkedList.getAtIndex(indexElement));
System.out.println("Size = " + singleLinkedList.getSize());
System.out.println(singleLinkedList.toString());
word = "the";
System.out.printf("Удаление элемента %s: %s%n", word, singleLinkedList.remove(word));
System.out.println(singleLinkedList.toString());
System.out.println("Size = " + singleLinkedList.getSize());
singleLinkedList.add(null);
singleLinkedList.add(null);
word = "if";
System.out.printf("Удаление элемента %s: %s%n", word, singleLinkedList.remove(word));
System.out.println(singleLinkedList.toString());
System.out.println("Size = " + singleLinkedList.getSize());
System.out.println("Удаление элементов");
while (singleLinkedList.getSize() != 0) {
singleLinkedList.remove();
}
System.out.println(singleLinkedList.toString());
System.out.println("Size = " + singleLinkedList.getSize());
System.out.println("Реверс пустого");
singleLinkedList.reverse();
// System.out.println("Удаление в пустом" + singleLinkedList.remove());
}
}
| true
|
3c147815549b23e20f38aa5c3c7381e34bbe0e3a
|
Java
|
oncioiu/Sudoku
|
/Sudoku-program/src/com/joc/sudoku/PuzzleView.java
|
UTF-8
| 1,316
| 2.546875
| 3
|
[] |
no_license
|
package com.joc.sudoku;
import android.view.View;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
public class PuzzleView extends View {
private static final String TAG = "Sudoku";
private final Game game;
public PuzzleView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
}
private float width; // width of one tile
private float height; // height of one tile
private int selX; // X index of selection
private int selY; // Y index of selection
private final Rect selRect = new Rect();
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w / 9f;
height = h / 9f;
getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(w, h, oldw, oldh);
}
private void getRect(int x, int y, Rect rect) {
rect.set((int) (x * width), (int) (y * height),
(int) (x * width + width), (int) (y * height + height));
}
}
| true
|
0f54c8b0341895d5d55ccd86c3766c4da223f050
|
Java
|
mohitrajvardhan17/java1.8.0_151
|
/java/nio/file/CopyMoveHelper.java
|
UTF-8
| 4,812
| 2.546875
| 3
|
[] |
no_license
|
package java.nio.file;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
class CopyMoveHelper
{
private CopyMoveHelper() {}
private static CopyOption[] convertMoveToCopyOptions(CopyOption... paramVarArgs)
throws AtomicMoveNotSupportedException
{
int i = paramVarArgs.length;
CopyOption[] arrayOfCopyOption = new CopyOption[i + 2];
for (int j = 0; j < i; j++)
{
CopyOption localCopyOption = paramVarArgs[j];
if (localCopyOption == StandardCopyOption.ATOMIC_MOVE) {
throw new AtomicMoveNotSupportedException(null, null, "Atomic move between providers is not supported");
}
arrayOfCopyOption[j] = localCopyOption;
}
arrayOfCopyOption[i] = LinkOption.NOFOLLOW_LINKS;
arrayOfCopyOption[(i + 1)] = StandardCopyOption.COPY_ATTRIBUTES;
return arrayOfCopyOption;
}
static void copyToForeignTarget(Path paramPath1, Path paramPath2, CopyOption... paramVarArgs)
throws IOException
{
CopyOptions localCopyOptions = CopyOptions.parse(paramVarArgs);
LinkOption[] arrayOfLinkOption = { followLinks ? new LinkOption[0] : LinkOption.NOFOLLOW_LINKS };
BasicFileAttributes localBasicFileAttributes = Files.readAttributes(paramPath1, BasicFileAttributes.class, arrayOfLinkOption);
if (localBasicFileAttributes.isSymbolicLink()) {
throw new IOException("Copying of symbolic links not supported");
}
if (replaceExisting) {
Files.deleteIfExists(paramPath2);
} else if (Files.exists(paramPath2, new LinkOption[0])) {
throw new FileAlreadyExistsException(paramPath2.toString());
}
Object localObject1;
if (localBasicFileAttributes.isDirectory())
{
Files.createDirectory(paramPath2, new FileAttribute[0]);
}
else
{
localObject1 = Files.newInputStream(paramPath1, new OpenOption[0]);
Object localObject2 = null;
try
{
Files.copy((InputStream)localObject1, paramPath2, new CopyOption[0]);
}
catch (Throwable localThrowable3)
{
localObject2 = localThrowable3;
throw localThrowable3;
}
finally
{
if (localObject1 != null) {
if (localObject2 != null) {
try
{
((InputStream)localObject1).close();
}
catch (Throwable localThrowable5)
{
((Throwable)localObject2).addSuppressed(localThrowable5);
}
} else {
((InputStream)localObject1).close();
}
}
}
}
if (copyAttributes)
{
localObject1 = (BasicFileAttributeView)Files.getFileAttributeView(paramPath2, BasicFileAttributeView.class, new LinkOption[0]);
try
{
((BasicFileAttributeView)localObject1).setTimes(localBasicFileAttributes.lastModifiedTime(), localBasicFileAttributes.lastAccessTime(), localBasicFileAttributes.creationTime());
}
catch (Throwable localThrowable1)
{
try
{
Files.delete(paramPath2);
}
catch (Throwable localThrowable4)
{
localThrowable1.addSuppressed(localThrowable4);
}
throw localThrowable1;
}
}
}
static void moveToForeignTarget(Path paramPath1, Path paramPath2, CopyOption... paramVarArgs)
throws IOException
{
copyToForeignTarget(paramPath1, paramPath2, convertMoveToCopyOptions(paramVarArgs));
Files.delete(paramPath1);
}
private static class CopyOptions
{
boolean replaceExisting = false;
boolean copyAttributes = false;
boolean followLinks = true;
private CopyOptions() {}
static CopyOptions parse(CopyOption... paramVarArgs)
{
CopyOptions localCopyOptions = new CopyOptions();
for (CopyOption localCopyOption : paramVarArgs) {
if (localCopyOption == StandardCopyOption.REPLACE_EXISTING)
{
replaceExisting = true;
}
else if (localCopyOption == LinkOption.NOFOLLOW_LINKS)
{
followLinks = false;
}
else if (localCopyOption == StandardCopyOption.COPY_ATTRIBUTES)
{
copyAttributes = true;
}
else
{
if (localCopyOption == null) {
throw new NullPointerException();
}
throw new UnsupportedOperationException("'" + localCopyOption + "' is not a recognized copy option");
}
}
return localCopyOptions;
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\java\nio\file\CopyMoveHelper.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
| true
|
c070a3de21c39f607818a4cc524fd8163c58e4fa
|
Java
|
dlvip/jiushiguang
|
/app/src/main/java/com/old/time/beans/CommentBean.java
|
UTF-8
| 1,694
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.old.time.beans;
import com.old.time.utils.TimeUtil;
import java.io.Serializable;
/**
* Created by NING on 2018/9/26.
*/
public class CommentBean implements Serializable {
private String id;
private String commentId;
private String userId;
private String topicId;
private String comment;
private String praiseCount;
private String createTime;
private UserInfoBean userEntity;
public UserInfoBean getUserEntity() {
return userEntity;
}
public void setUserEntity(UserInfoBean userEntity) {
this.userEntity = userEntity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCommentId() {
return commentId;
}
public void setCommentId(String commentId) {
this.commentId = commentId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTopicId() {
return topicId;
}
public void setTopicId(String topicId) {
this.topicId = topicId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPraiseCount() {
return praiseCount;
}
public void setPraiseCount(String praiseCount) {
this.praiseCount = praiseCount;
}
public String getCreateTime() {
return TimeUtil.getDateTimeOld(createTime);
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
| true
|
5531e21756c78e2f671288753602b70af26fc200
|
Java
|
LukaszRybicki5/rabbitmq-09-04
|
/src/main/java/receiver/MessageReceiver.java
|
UTF-8
| 3,822
| 2.953125
| 3
|
[] |
no_license
|
package receiver;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.*;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import receiver.jsonParser.JSONFileMaker;
import receiver.messageObject.MessageObject;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;
import static java.lang.System.exit;
public class MessageReceiver {
private static String EXCHANGE_NAME = "TopicDurable";
private static String QUEUE_NAME = "DummyLoad";
public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, NullPointerException, InterruptedException, TimeoutException {
System.out.println("<-------------------------------------->" +
"\n\tWitaj w systemie odbierania danych!");
boolean optionFlag = true;
while (optionFlag) {
Scanner input = new Scanner(System.in);
System.out.println("<--------------------------------------> " +
"\nWybierz co chcesz zrobić:" +
"\na) Włączenie programu odbierającego z ustawieniami domyślnymi" +
"\nb) Zmiana domyślnej ścieżki programu" +
"\nx) Zamknięcie programu");
String choice = input.nextLine();
switch (choice) {
case "a":
receivingFiles("C:\\Users\\User\\Desktop\\newJson\\");
break;
case "b":
changingPathOfReceivedFiles();
break;
case "x":
System.out.println("Zamykamy program do wysyłania danych.");
exit(0);
optionFlag = false;
break;
default:
System.out.println("\tBłąd!!!\nWybierz opcje " +
"(wpisz małą literę a, b lub x w konsolę).");
break;
}
}
}
private static void changingPathOfReceivedFiles() throws InterruptedException, TimeoutException, IOException, InputMismatchException {
Scanner put = new Scanner(System.in);
System.out.println("Podaj ścieżkę folderu do którego chcesz otrzymywać pliki:\n" +
"Domyślna: C:\\Users\\User\\Desktop\\newJson\\");
String Path = put.nextLine();
receivingFiles(Path);
}
private static void receivingFiles(String Path) throws InterruptedException, IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, queueingConsumer);
ObjectMapper mapper = new ObjectMapper();
while (true) {
Delivery delivery = queueingConsumer.nextDelivery();
if (delivery.getBody()[0] == 123) {
MessageObject messageObject = mapper.readValue(delivery.getBody(), MessageObject.class);
System.out.println("Odebrano plik: " + messageObject.getFileName() + "!");
System.out.println(messageObject.getCSVList());
JSONFileMaker jsonFileMaker = new JSONFileMaker();
jsonFileMaker.putDataToPersonList(messageObject.getCSVList(), messageObject.getFileName(), Path);
System.out.println("Stworzono plik JSON");
}
}
}
}
| true
|
83113c401510a4169b1680e681d6ab0822173988
|
Java
|
wangzhifengharrison/6442_fianal_lab
|
/src/WordTest.java
|
UTF-8
| 474
| 2.640625
| 3
|
[] |
no_license
|
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static org.junit.Assert.assertTrue;
public class WordTest {
@Rule
public Timeout globalTimeout = Timeout.millis(5000);
@Test
public void testWord() {
Word value = new Word('a');
int length = value.toString().length();
boolean p1 = false;
if (length == 10)
p1 = true;
assertTrue("Word style is not right", p1);
}
}
| true
|
a64dd73a4f7a189ce956ff2bc730290a4b12d81c
|
Java
|
christianqw/tesisGit
|
/netbeans/TestServerFalso/src/serverPackages/Sentencia.java
|
UTF-8
| 1,131
| 2.734375
| 3
|
[] |
no_license
|
package serverPackages;
public class Sentencia {
private String id;
private String nombre;
private String valor;
private String estado;
private String mensaje;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
@Override
public String toString() {
return "\n Sentencia{" + "id=" + id + ", nombre=" + nombre + ", valor=" + valor + ", estado=" + estado + ", mensaje=" + mensaje + "} \n";
}
}
| true
|
9662a9086d9b254b01e971924dfa5e3689abdd77
|
Java
|
rail1000/NumberSystem
|
/src/java/test/AuditContiBean.java
|
UTF-8
| 1,484
| 1.890625
| 2
|
[] |
no_license
|
package test;
public class AuditContiBean {
int[] id;
String[] numBegin;
String[] numEnd;
int[] agreeFlag;
int num;
String[] descrip;
String[] type;
String[] typeA;
String[] typeB;
String[] typeC;
public void setTypeA(String[] a){
typeA = a;
}
public void setTypeB(String[] a){
typeB = a;
}
public void setTypeC(String[] a){
typeC = a;
}
public String[] getTypeA(){
return typeA;
}
public String[] getTypeB(){
return typeB;
}
public String[] getTypeC(){
return typeC;
}
public void setId(int[] a){
id = a;
}
public void setType(String[] a){
type = a;
}
public void setNumBegin(String[] a){
numBegin = a;
}
public void setNumEnd(String[] a){
numEnd = a;
}
public void setAgreeFlag(int[] a){
agreeFlag = a;
}
public void setNum(int a){
num = a;
}
public void setDescrip(String[] a){
descrip = a;
}
public int[] getId(){
return id;
}
public String[] getNumBegin(){
return numBegin;
}
public String[] getNumEnd(){
return numEnd;
}
public int[] getAgreeFlag(){
return agreeFlag;
}
public int getNum(){
return num;
}
public String[] getDescrip(){
return descrip;
}
public String[] getType(){
return type;
}
}
| true
|
8cdfc379fa58e46ae9ec45369ec3a4fa2847c1e0
|
Java
|
UmeshBaldaniya46/MVPSample-Kotlin-
|
/app/src/main/java/com/umesh/MVPSample/ui/activities/SplashActivity.java
|
UTF-8
| 911
| 2.171875
| 2
|
[] |
no_license
|
package com.umesh.MVPSample.ui.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.umesh.MVPSample.R;
public class SplashActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread t = new Thread() {
public void run() {
try {
sleep(2000);
gotoLogin();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
public void gotoLogin() {
Intent intent;
intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
| true
|
67ed557a322847596d63dec416ab343fa8924492
|
Java
|
stuharley8/CS2852-Labs
|
/Lab4/IndexDictionary.java
|
UTF-8
| 1,962
| 3.578125
| 4
|
[] |
no_license
|
/*
* Course: CS2852
* Spring 2019
* Lab: Lab 4 - AutoComplete
* Name: Stuart Harley
* Created: 4/9/19
*/
package harleys;
import java.util.LinkedList;
import java.util.List;
/**
* Dictionary class that uses indexing methods to navigate the list
*/
public class IndexDictionary extends Dictionary implements AutoCompleter {
/**
* Constructor for an Enhanced Dictionary
* @param words the list of words
*/
public IndexDictionary(List<String> words) {
super(words);
}
/**
* Constructor that copies the words from original into list and uses it
* to store the words for this dictionary
* @param original dictionary to have words copied from
* @param list list to store the words copied
*/
public IndexDictionary(Dictionary original, List<String> list) {
super(original, list);
}
/**
* Returns a list of all prefix matches in the dictionary, a.k.a., all
* entries in the dictionary that begin with prefix
*
* @param prefix the prefix the to check the dictionary with
* @return a list of all prefix matches in the dictionary
* @throws IllegalStateException if initialize has not been called
* prior to calling this method
*/
@Override
public List<String> allThatBeginWith(String prefix) throws IllegalStateException {
if(getLastOperationTime() == -1) {
throw new IllegalStateException("Must call initialize() prior to calling" +
"this method");
}
long startTime = System.nanoTime();
List<String> matches = new LinkedList<>();
for(int i = 0; i < words.size(); i++) {
String word = words.get(i);
if(word.startsWith(prefix)) {
matches.add(word);
}
}
lastOperationTime = System.nanoTime()-startTime;
return matches;
}
}
| true
|
73bdfd657dd38c62a52c15544d0281744d654a6c
|
Java
|
karlajajic/Marinero-AND
|
/app/src/main/java/com/example/marinero_kj/persistance/networking/ServiceGenerator.java
|
UTF-8
| 595
| 2.25
| 2
|
[] |
no_license
|
package com.example.marinero_kj.persistance.networking;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
private static Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.baseUrl("https://api.sunrise-sunset.org/")
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = retrofitBuilder.build();
private static SunriseApi sunriseApi = retrofit.create(SunriseApi.class);
public static SunriseApi getSunriseApi() {
return sunriseApi;
}
}
| true
|
cba07f85e7f93cc2347d46e4b3cd4fa06d00e116
|
Java
|
pasj/contactos
|
/src/main/java/com/servicios/serviceImpl/SalasServiceImpl.java
|
UTF-8
| 1,322
| 2.0625
| 2
|
[] |
no_license
|
package com.servicios.serviceImpl;
import com.datos.dao.SalasDAO;
import com.entidades.Salas;
import com.googlecode.genericdao.search.Search;
import com.servicios.service.SalasService;
import com.utils.BusinessException;
import com.utils.DAOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Pablo Sevilla on 3/2/2017.
*/
@Service
public class SalasServiceImpl implements SalasService {
@Autowired
SalasDAO salasDAO;
@Override
@Transactional
public void guardar(Salas salas) throws BusinessException, DAOException {
salasDAO.save(salas);
}
@Override
@Transactional
public void modificar(Salas salas) throws BusinessException, DAOException {
salasDAO.update(salas);
}
@Override
@Transactional
public void eliminar(Salas salas) throws BusinessException, DAOException {
salasDAO.remove(salas);
}
@Override
@Transactional
public List<Salas> obtenerAgendaSalas(Integer id) throws BusinessException, DAOException {
Search search = new Search();
search.addFilterEqual("oficinaIdPorId.id", id);
return salasDAO.search(search);
}
}
| true
|
fd20e2ede684cea867240e399212a26602cbe9ae
|
Java
|
Timtg/taveo-server
|
/src/main/java/no/timesaver/service/otp/CodeGenerationService.java
|
UTF-8
| 1,011
| 2.71875
| 3
|
[] |
no_license
|
package no.timesaver.service.otp;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
public class CodeGenerationService {
private static final int LENGTH = 6;
private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUM = "0123456789";
private static SecureRandom rnd = new SecureRandom();
public String generateConfirmationCode() {
return generateCodeOfLength(LENGTH,true);
}
public String generateOTP(int len) {
return generateCodeOfLength(len,true);
}
public String generateNumericOTP(int len) {
return generateCodeOfLength(len,false);
}
private String generateCodeOfLength(int length,boolean mixedMode) {
String src = mixedMode ? AB : NUM;
StringBuilder sb = new StringBuilder(length);
for( int i = 0; i < length; i++ )
sb.append( src.charAt( rnd.nextInt(src.length()) ) );
return sb.toString();
}
}
| true
|
e024db12ada8d7cc38a57480165ca249267e242f
|
Java
|
lfdarbs/qa2-auto
|
/src/test/java/DelfiTests.java
|
UTF-8
| 3,710
| 2.65625
| 3
|
[] |
no_license
|
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import javax.sound.midi.Soundbank;
import java.util.List;
public class DelfiTests {
private final By ACCEPT_COOKIE_BTN = By.xpath(".//button[@mode='primary']");
private final By ARTICLE_TITLE = By.xpath(".//span[@itemprop = 'headline name']");
private final Logger LOGGER = LogManager.getLogger(DelfiTests.class);
@Test
public void firstDelfiTest() {
LOGGER.info("This test will check accept cookie btn");
LOGGER.info("Setting up driver path");
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
LOGGER.info("Opening browser window");
WebDriver driver = new ChromeDriver();
LOGGER.info("Maximazing window");
driver.manage().window().maximize();
LOGGER.info("Open homepage");
driver.get("http://delfi.lv");
LOGGER.info("Waitng for accept cookies modal window");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(ACCEPT_COOKIE_BTN));
LOGGER.info("Pressing accept btn");
WebElement acceptBtn = driver.findElement(ACCEPT_COOKIE_BTN);
acceptBtn.click();
}
}
/*
@Test
public void tvnetTest() {
String articleToOpen = "Eiropas Komisija sūdzēs tiesā Bulgāriju un Grieķiju";
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http:/tvnet.lv");
List<WebElement> articles = driver.findElements(ARTICLE_TITLE);
for (int i = 0; i < articles.size(); i++) {
String currentTitle = articles.get(i).getText();
if (currentTitle.startsWith(articleToOpen)) {
articles.get(i).click();
break;
}
// System.out.println(i + " " + articles.get(i).getText());
// articles.get(3).click();
}
//------------------------------------------------------
//-------------------foreach cycle----------------------
//------------------------------------------------------
for (WebElement we:
articles) {
if (we.getText().startsWith(articleToOpen)){
we.click();
break;
}
}
driver.close();
}
}
/*
tvnet.lv
1) прокликать элементы так чтобы оказаться на стринце самой статьи и потом оказаться на странице комментариев
2)* перейти на указанную по счету статью (используя списки)
3)** перейти на статью по заголовку (цикл)
4)*** сделать проверку что название статьи совпадает на всех страницах
(главная, страница комментариев, страница статьи)
5)**** проверять кол-во комментариев (используя инты) что оно совпадает
6)***** проверять кол-во комментариев не только по счетчику, но и посчитать комменты
*/
//System.out.println(we.getText());
| true
|
313e08a05ba7e51a7c74ee82ecb9bf36dc02eb79
|
Java
|
phamviettu-98/GamedoVui_With_Firebase
|
/app/src/main/java/viettu/pvt/gamedovui/RankActivity.java
|
UTF-8
| 2,719
| 2.03125
| 2
|
[] |
no_license
|
package viettu.pvt.gamedovui;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Collections;
public class RankActivity extends AppCompatActivity {
ImageView view;
RecyclerView Bangxephang;
FirebaseFirestore db = FirebaseFirestore.getInstance();
ArrayList<User> usersList = new ArrayList<>();
XepHangAdapter xephangAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rank);
Bangxephang = findViewById(R.id.recycle);
view = findViewById(R.id.quayve);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RankActivity.this, HomeActivity.class);
startActivity(intent);
}
});
xephangAdapter = new XepHangAdapter(usersList);
Bangxephang.setAdapter(xephangAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
Bangxephang.setLayoutManager(linearLayoutManager);
getAllUser();
}
private void getAllUser(){
db.collection("User")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if ( task.isSuccessful()){
for (QueryDocumentSnapshot dc : task.getResult()) {
String name = (String) dc.get("name");
Long diem1 = (Long) dc.get("diem");
int diem = diem1.intValue();
User u = new User(name,diem);
usersList.add(u);
}
Collections.sort(usersList,User.userComparator);
xephangAdapter.notifyDataSetChanged();
}
}
});
}
}
| true
|
3cc289d8d247561863c1708753ed4a6aa6ee932c
|
Java
|
shanghaif/Hive2
|
/app/src/main/java/com/hivee2/mvp/model/bean/RoleRightsBeans.java
|
UTF-8
| 1,955
| 2.09375
| 2
|
[] |
no_license
|
package com.hivee2.mvp.model.bean;
import java.util.ArrayList;
/**
* Created by Lenovo on 2018/3/19.
*/
public class RoleRightsBeans {
private String userid;
private int Result;
private String ErrorMsg;
private ArrayList<RoleRight>DataList;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public int getResult() {
return Result;
}
public void setResult(int result) {
Result = result;
}
public String getErrorMsg() {
return ErrorMsg;
}
public void setErrorMsg(String errorMsg) {
ErrorMsg = errorMsg;
}
public ArrayList<RoleRight> getDataList() {
return DataList;
}
public void setDataList(ArrayList<RoleRight> dataList) {
DataList = dataList;
}
public static class RoleRight{
private int menu_id;
private boolean is_ban;
private boolean can_show;
private boolean can_read;
private boolean can_manage;
public int getMenu_id() {
return menu_id;
}
public void setMenu_id(int menu_id) {
this.menu_id = menu_id;
}
public boolean isIs_ban() {
return is_ban;
}
public void setIs_ban(boolean is_ban) {
this.is_ban = is_ban;
}
public boolean isCan_show() {
return can_show;
}
public void setCan_show(boolean can_show) {
this.can_show = can_show;
}
public boolean isCan_read() {
return can_read;
}
public void setCan_read(boolean can_read) {
this.can_read = can_read;
}
public boolean isCan_manage() {
return can_manage;
}
public void setCan_manage(boolean can_manage) {
this.can_manage = can_manage;
}
}
}
| true
|
93404977b09bc94a7f5e3c3306695f8906513608
|
Java
|
Tiger656/StreamAPI
|
/stream-api/src/main/java/by/courses/java/streamapi/operation/DefaultStream.java
|
UTF-8
| 2,055
| 3.21875
| 3
|
[] |
no_license
|
package by.courses.java.streamapi.operation;
import by.courses.java.streamapi.entity.UserBase;
import java.util.Collection;
import java.util.stream.Collectors;
public class DefaultStream implements Operation<UserBase> {
@Override
public Collection<UserBase> removeWithMaxAge(Collection<UserBase> entities) {
return entities.stream().filter(user -> user.getAge() < (entities.stream().map(UserBase::getAge).mapToInt(v -> v).max().getAsInt())).collect(Collectors.toList());
}
@Override
public Collection<UserBase> removeAllOlder(Collection<UserBase> entities, int age) {
return entities.stream().filter(user -> user.getAge() <= age).collect(Collectors.toList());
}
@Override
public double getAverageAge(Collection<UserBase> entities) {
return entities.stream().map(UserBase::getAge).mapToInt(v -> v).average().getAsDouble();
}
@Override
public UserBase getThirdInCollection(Collection<UserBase> entities) {
return entities.stream().skip(2).findFirst().get();
}
@Override
public Collection<UserBase> getTwoUsersStartingFromSecond(Collection<UserBase> entities) {
return entities.stream().skip(1).limit(2).collect(Collectors.toList());
}
@Override
public boolean isCharacterPresentInAllNames(Collection<UserBase> entities, String character) {
return entities.stream().allMatch(person -> person.getName().toLowerCase().contains(character.toLowerCase()));
}
@Override
public Collection<UserBase> addValueToAllNames(Collection<UserBase> entities, String value) {
return entities.stream().peek(person -> person.setName(person.getName() + value)).collect(Collectors.toList());
}
@Override
public Collection<UserBase> sortByNameThanByAge(Collection<UserBase> entities) {
return entities.stream().sorted((p1, p2) ->
p1.getName() != p2.getName() ? p1.getName().compareTo(p2.getName()) :
p1.getAge().compareTo(p2.getAge())).collect(Collectors.toList());
}
}
| true
|
416eb62bfa11c57f58e21585237368f934a43ad3
|
Java
|
HanHyeongjin/project
|
/src/main/java/vo/GameVO.java
|
UTF-8
| 452
| 1.546875
| 2
|
[] |
no_license
|
package vo;
import org.springframework.web.multipart.MultipartFile;
import lombok.Data;
@Data
public class GameVO {
private int idno;
private String gname;
private String gservice;
private String categories1;
private String categories2;
private int rec;
private double grade;
private String contents;
private String img;
private MultipartFile imgf;
private int grank;
private String reldate;
private int rating;
}
| true
|
c4aeb6da6e3e948bc9a8e9e04180e4eb7ec8ba79
|
Java
|
devlights/try-java
|
/tryjava/src/com/github/devlights/tryjava/basic/collections/listop/Empty.java
|
UTF-8
| 742
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
package com.github.devlights.tryjava.basic.collections.listop;
import java.util.Collections;
import java.util.List;
import com.github.devlights.tryjava.exceptions.ExampleFailedException;
import com.github.devlights.tryjava.interfaces.Example;
/**
* リストについてのサンプルです. (空のリスト)
*
*/
public final class Empty implements Example {
@Override
public void execute() throws ExampleFailedException {
var empty = this.getList();
var empty2 = this.getList();
System.out.printf("size: %d\n", empty.size());
System.out.printf("%d %d\n", empty.hashCode(), empty2.hashCode());
}
private List<String> getList() {
return Collections.emptyList();
}
}
| true
|
3193a9726021a8bb18e962f14c741d8ffded7366
|
Java
|
ronaldfdg/faunaHealth
|
/src/main/java/com/faunahealth/web/service/Impl/ProviderServiceImpl.java
|
UTF-8
| 1,083
| 2.203125
| 2
|
[] |
no_license
|
package com.faunahealth.web.service.Impl;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.faunahealth.web.entity.Provider;
import com.faunahealth.web.repository.ProviderRepository;
import com.faunahealth.web.service.ProviderService;
@Service
public class ProviderServiceImpl implements ProviderService {
@Autowired
private ProviderRepository repositoryProvider;
@Override
public List<Provider> findAll() {
return repositoryProvider.findAll(Sort.by("businessName").ascending());
}
@Override
public void save(Provider provider) {
repositoryProvider.save(provider);
}
@Override
public Provider findById(int id) {
Optional<Provider> optional = repositoryProvider.findById(id);
if(optional.isPresent())
return optional.get();
return null;
}
@Override
public boolean existsById(int id) {
return repositoryProvider.existsById(id);
}
}
| true
|
25c4728034c27ae2113905c5f5e84c08a21bdcc9
|
Java
|
Truman186/study
|
/sportplayer/src/main/java/com/deyun/controller/UserController.java
|
UTF-8
| 5,399
| 2.03125
| 2
|
[] |
no_license
|
package com.deyun.controller;
import ch.qos.logback.core.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.deyun.bean.*;
import com.deyun.dao.UserDao;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by fangling on 2020/7/12.
*/
@RestController
public class UserController {
@Autowired
UserDao userDao;
@RequestMapping("/alluser")
public String getUserList(QueryInfo queryInfo){
//获取1查询信息和当前编号
int numbers= userDao.getUserCounts("%"+queryInfo.getQuery()+"%");
int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
List<User> users= userDao.getAllUser("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
// System.out.println(users);
HashMap<String,Object> res = new HashMap<>();
res.put("numbers",numbers);
res.put("data",users);
String res_string = JSON.toJSONString(res);
return res_string;
}
@RequestMapping("/updateUserState")
public String updateUserState(@RequestParam String username){
/* User user =userDao.selectByID(id);
System.out.println(user);
Boolean states =user.getState();
Boolean state =!states;
System.out.println(state);*/
int i = userDao.updateState(username);
System.out.println(i);
return i>0?"success":"error";
}
/*@RequestMapping("/updateUserState")
public String updateUserState(@RequestParam("userInfo") User userInfo) {
int id = userInfo.getId();
Boolean state = userInfo.getState();
System.out.println(state);
int i = userDao.updateState(id, state);
System.out.println(state);
return i > 0 ? "success" : "error";
}*/
@RequestMapping("/addUser")
public String addUser(@RequestBody UserDto user){
user.setRoleId(1);
/* System.out.println("1111111");
System.out.println(user.getEmail());
System.out.println(user.getPassword());
System.out.println(user.getUsername());*/
user.setState(false);
int num =userDao.getUserCounts(user.getUsername());
if(num>0){
return "exist";
}
int i= userDao.addUser(user);
return i>0?"success":"error";
}
@RequestMapping("/deleteUser")
public String deleteUser(String username){
//int id =8;
int i=userDao.deleteUser(username);
return i>0?"success":"error";
}
@RequestMapping("/getUpdateUser")
public String getUpdateUser(String username){
User user = userDao.selectByName(username);
String str = JSON.toJSONString(user);
return str;
}
@RequestMapping("/editUser")
public String editUser(@RequestBody User user){
int i= userDao.editUser(user);
return i>0?"success":"error";
}
@GetMapping("/getList")
public List<User> getList(){
List<User> list =userDao.getList();
return list;
}
@RequestMapping("/editRole")
public String editRole(@RequestBody UserDto user){
System.out.println(user.getUsername());
System.out.println(user.getRoleId());
String username =user.getUsername();
int roleId =user.getRoleId();
int i =userDao.editRole(username,roleId);
return i>0?"success":"error";
}
@RequestMapping("/queryUserInfo")
public String queryUserInfo(String username){
UserInfo userInfo =userDao.queryUserInfo(username);
if (userInfo==null){
UserInfo userInfo1=new UserInfo();
userInfo1.setUsername(username);
String str = JSON.toJSONString(userInfo1);
return str;
}
String str = JSON.toJSONString(userInfo);
return str;
}
@PostMapping("/updateUserInfo")
public String updateUserInfo(@RequestBody UserInfo userInfo) {
/*if(userInfo.getBirth()!=null){
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(userInfo.getBirth());
userInfo.setBirth(date+"");
}*/
int num =userDao.queryNum(userInfo.getUsername());
if(num==1){
int i= userDao.updateUserInfo(userInfo);
return i>0?"success":"error";
}
int j=userDao.addUserInfo(userInfo);
return j>0?"success":"error";
}
@PostMapping("/editPsw")
public String editPsw(@RequestBody PswForm pswForm) {
if (!pswForm.getOldPsw().equals(pswForm.getNewPsw()) ) {
if (pswForm.getNewPsw() .equals( pswForm.getSurePsw())) {
if (pswForm.getOldPsw() .equals(userDao.selectByName(pswForm.getUsername()).getPassword())) {
int i = userDao.editPsw(pswForm);
return i > 0 ? "success" : "error3";
}
return "erro2";
}
return "erro1";
}
return "erro4";
}
}
| true
|
97ce290116a434c51857fa84e33c035fcba0113d
|
Java
|
butorinsasha/javafortesters
|
/src/test/java/com/javafortesters/chap017datasandtimes/TimeTest.java
|
UTF-8
| 1,457
| 3.015625
| 3
|
[] |
no_license
|
package com.javafortesters.chap017datasandtimes;
import com.javafortesters.chap017datesandtimes.domainentities.User;
import com.javafortesters.chap017datesandtimes.exceptions.InvalidPasswordException;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TimeTest {
@Test
public void currentTimeMillisReturnsCurrentTimeInMilliSecondsFromTheEpoch(){
long startTime = System.currentTimeMillis();
for(int x=0; x < 10; x++){
System.out.println("Current Time " +
System.currentTimeMillis());
}
long endTime = System.currentTimeMillis();
System.out.println("Total Time " + (endTime - startTime));
}
@Test
public void nanoTimeReturnsCurrentsJavaVirtualMachineTimeInNanoSeconds(){
long startTime = System.nanoTime();
for(int x=0; x < 10; x++){
System.out.println("Current Time " +
System.nanoTime());
}
long endTime = System.nanoTime();
System.out.println("Total Time " + (endTime - startTime));
}
@Test
public void userIdConsistsOfCharsOnly() throws InvalidPasswordException {
User usr0 = new User();
String regExNoDigits = "[^0-9]+";
System.out.println(usr0.getId());
assertTrue(usr0.getId().matches(regExNoDigits));
}
}
| true
|
31ea09c6d49c5cb74e2724326fa367d29cdcd744
|
Java
|
danaigua/JXC
|
/src/main/java/com/hengyue/service/UserService.java
|
UTF-8
| 1,215
| 2.34375
| 2
|
[] |
no_license
|
package com.hengyue.service;
import java.util.List;
import org.springframework.data.domain.Sort.Direction;
import com.hengyue.entity.User;
/**
* 用户service接口
* @author 章家宝
*
*/
public interface UserService {
/**
* 根据用户名查找实体
* @param userName
* @return
*/
public User findByUserName(String userName);
/**
* 根据条件分页查询用户信息
* @param user
* @param page
* @param pageSize
* @param direction
* @param properties
* @return
*/
public List<User> list(User user, Integer page, Integer pageSize, Direction direction, String...properties);
/**
* 获取总记录数
* @param user
* @return
*/
public Long getCount(User user);
/**
* 添加或者修改用户信息
* @param user
*/
public void save(User user);
/**
* 根据id删除用户
* @param id
*/
public void delete(Integer id);
/**
* 通过id查找用户
* @param id
* @return
*/
public User findById(Integer id);
/**
* 查找所有的用户
* @return
*/
public List<User> findAll();
/**
* 通过查找用户真实姓名返回用户实体
* @param userName
* @return
*/
public User findByUserTrueName(String userName);
}
| true
|