blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
533a3072f08b5c59ba5bf5ccc5bc1a3560ea01b3 | 5bd81f1d0e1e8ca3e9c96810f8639de7906f56b7 | /work-14/src/main/java/ru/otus/work14/config/ItemReaderConfig.java | 8e5b970ac51b0d48aeb3dce8ef4013c10e5ebfc5 | [] | no_license | mgilivanov/2019-11-otus-spring-GilivanovM | 770c398e14de3b2ec0e439fee06883c14a787b3d | 73b8f70a193dee85e8cd2f422e054551b5436f36 | refs/heads/master | 2022-09-20T07:14:13.900313 | 2020-06-01T08:37:33 | 2020-06-01T08:37:33 | 225,004,561 | 0 | 0 | null | 2022-09-08T01:09:45 | 2019-11-30T11:52:17 | Java | UTF-8 | Java | false | false | 1,416 | java | package ru.otus.work14.config;
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.data.MongoItemReader;
import org.springframework.batch.item.data.builder.MongoItemReaderBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.otus.work14.domain.Book;
import ru.otus.work14.domain.Comment;
import org.springframework.data.mongodb.core.MongoOperations;
import java.util.HashMap;
@Configuration
@RequiredArgsConstructor
public class ItemReaderConfig {
private final MongoOperations mongoOperations;
@StepScope
@Bean
public MongoItemReader<Book> bookImportMongoItemReader() {
return new MongoItemReaderBuilder<Book>().name("bookImportMongoItemReader")
.template(mongoOperations)
.targetType(Book.class)
.jsonQuery("{}")
.sorts(new HashMap<>())
.build();
}
@StepScope
@Bean
public MongoItemReader<Comment> commentImportMongoItemReader() {
return new MongoItemReaderBuilder<Comment>().name("commentImportMongoItemReader")
.template(mongoOperations)
.targetType(Comment.class)
.jsonQuery("{}")
.sorts(new HashMap<>())
.build();
}
}
| [
"[email protected]"
] | |
93559a42fca8d2f002bf89b7a557922b89a7e6b9 | 6b1f9865707e2151d140fc81f8c8be54e0402069 | /main/java/com/ex/Order.java | 2143cf95a23a7aa3210e51ab3b2fcef54c8fead7 | [] | no_license | Bdvoga/spring | 8d111478c43c4dd00e6ea458f6a192a172695d29 | 3185b9117f34911c46fa04137e2617b5208d3c07 | refs/heads/master | 2023-03-30T22:24:24.945393 | 2021-03-24T17:56:23 | 2021-03-24T17:56:23 | 346,493,425 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 40 | java | package com.ex;
public class Order {
}
| [
"[email protected]"
] | |
ff011327e6b623fa99a2db3fb6e1983cdf4b1cc3 | 31694ab52b873c4bc1e1adf9804cecea24918fa9 | /graqulus-generator-java/src/main/resources/trimou/java/imports.trimou.java | 5f0fb530e49bab3ff70df4c9245ce25f4f42f9c4 | [
"Apache-2.0"
] | permissive | hwellmann/org.ops4j.graqulus | 9704473afd207c4838a1d3acb9d248f4c1cd3bc3 | fa06173cbcf09ff46eca632f87de77c0cdcdc3c7 | refs/heads/master | 2022-10-05T06:01:43.001582 | 2019-11-06T15:15:12 | 2019-11-06T15:15:12 | 161,987,188 | 0 | 0 | Apache-2.0 | 2022-09-16T21:07:14 | 2018-12-16T09:47:05 | Java | UTF-8 | Java | false | false | 43 | java | {{#imports}}
import {{this}};
{{/imports}}
| [
"[email protected]"
] | |
85ce05813ab9f975479450650994cd958d482c68 | 99c03face59ec13af5da080568d793e8aad8af81 | /hom_classifier/2om_classifier/scratch/AOIU19AOIU4/Pawn.java | b94ec0f3554b854eb6e165b7b86ddd8fa65b71fe | [] | no_license | fouticus/HOMClassifier | 62e5628e4179e83e5df6ef350a907dbf69f85d4b | 13b9b432e98acd32ae962cbc45d2f28be9711a68 | refs/heads/master | 2021-01-23T11:33:48.114621 | 2020-05-13T18:46:44 | 2020-05-13T18:46:44 | 93,126,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,759 | java | // This is a mutant program.
// Author : ysma
import java.util.ArrayList;
public class Pawn extends ChessPiece
{
public Pawn( ChessBoard board, ChessPiece.Color color )
{
super( board, color );
}
public java.lang.String toString()
{
if (color == ChessPiece.Color.WHITE) {
return "♙";
} else {
return "♟";
}
}
public java.util.ArrayList<String> legalMoves()
{
java.util.ArrayList<String> returnList = new java.util.ArrayList<String>();
if (this.getColor().equals( ChessPiece.Color.WHITE )) {
int currentCol = this.getColumn();
int nextRow = this.getRow() + 1;
if (nextRow <= 7) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 1) {
int nextNextRow = this.getRow() + 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, -currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
} else {
int currentCol = this.getColumn();
int nextRow = this.getRow() - 1;
if (nextRow >= 0) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 6) {
int nextNextRow = this.getRow() - 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( -nextRow, rightColumn ) );
}
}
}
}
return returnList;
}
} | [
"[email protected]"
] | |
1373e11823ee4dafebca2d79ea1366cb436c7ee4 | 24643916cd1515911b7837ce81ebd17b0890cc81 | /packages/apps/iSMS/src/com/hissage/util/queue/NmsMessagePump.java | 7d078b35d83e4dac24bb4c7e969d3c4712fe5dd7 | [
"Apache-2.0"
] | permissive | touxiong88/92_mediatek | 3a0d61109deb2fa77f79ecb790d0d3fdd693e5fd | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | refs/heads/master | 2020-05-02T10:20:49.365871 | 2019-04-25T09:12:56 | 2019-04-25T09:12:56 | 177,894,636 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,487 | java | package com.hissage.util.queue;
//import packages.
import java.util.Vector;
import com.hissage.util.log.NmsLog;
public final class NmsMessagePump {
// data member of message pump.
private Vector<NmsMessage> cmdQueue = new Vector<NmsMessage>();
public NmsMessage getMessage() {
NmsMessage msg = null;
do {
synchronized (cmdQueue) {
if (cmdQueue.size() > 0) {
msg = (NmsMessage) cmdQueue.elementAt(0);
cmdQueue.removeElementAt(0);
} else {
try {
cmdQueue.wait();
} catch (Exception e) {
NmsLog.nmsPrintStackTrace(e);
} finally {
cmdQueue.notify();
}
}
}
} while (msg == null);
return msg;
}
// public void sendMessage(NmsMessage msg) {
// // add message to queue.
// synchronized (cmdQueue) {
// cmdQueue.addElement(msg);
// cmdQueue.notifyAll();
// }
//
// // wait message to processed.
// synchronized (msg) {
// try {
// msg.wait();
// } catch (Exception e) {
// msg.setException(e);
// }
// }
// }
public void postMessage(NmsMessage msg) {
// add message to queue.
synchronized (cmdQueue) {
cmdQueue.addElement(msg);
cmdQueue.notifyAll();
}
}
}
| [
"[email protected]"
] | |
d029dae4fdaa83cdeefc15945f736099d08a41db | 4e5d5b2cf98cddc8fdce3aa74eda71f747a4730e | /src/main/java/com/smzh/thread/t2/TestBusiness.java | 2590cdf64079a9070d05a8bd01767fc0e58901ae | [] | no_license | yuzhenjun/jdk-sources | b5b251c73df05dfc5f5d88aff099e33aca02262f | 09da2e70450eecd1b3fc4d80f83362538f47bccc | refs/heads/master | 2020-05-30T18:50:47.852525 | 2015-08-10T05:13:28 | 2015-08-10T05:13:28 | 34,654,735 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 691 | java | /**
* @title TestBusiness.java
* @package com.smzh.thread.t2
* @projectName jdk-sources
* @author zhenjun.yu
* @date 2015年5月25日 下午6:06:14
*/
package com.smzh.thread.t2;
/**
* @author zhenjun.yu
*/
public class TestBusiness {
/**
* @param args
*/
public static void main(String[] args) {
final Business business=new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<50;i++){
business.subs();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<50;i++){
business.main();
}
}
}).start();
}
}
| [
"[email protected]"
] | |
b5cd41da0abcb49adea22d76c77140f373055cd1 | 7b065ab5fc40976bffbb9087d3d3440fd8097838 | /app/src/main/java/com/example/movienightplanner/EventDateTime.java | 4ab7200a4422f8bcb91b96d9dbbab45b11d206a5 | [] | no_license | Peter-Program/MovieNightPlannerApp | 9a38154c546231a355c5c0ec8a999f87d8a09848 | 637e152a79f5826c4225c636aad5bbad2f09611e | refs/heads/master | 2020-06-15T03:50:19.021567 | 2019-07-04T08:00:54 | 2019-07-04T08:00:54 | 195,195,898 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,806 | java | package com.example.movienightplanner;
import android.util.Log;
public class EventDateTime {
int day;
int month;
int year;
int hour;
int minute;
public EventDateTime(int day, int month, int year, int hour, int minute) {
this.day = day;
this.month = month;
this.year = year;
this.hour = hour;
this.minute = minute;
}
public EventDateTime() {
}
private String hourToString() {
String hr;
if (hour < 10)
hr = "0" + hour;
else
hr = "" + hour;
return hr;
}
private String minuteToString() {
String min;
if (minute < 10)
min = "0" + minute;
else
min = "" + minute;
return min;
}
private String monthToString() {
String mon;
int trueMonth = month + 1;
if (trueMonth < 10)
mon = "0" + trueMonth;
else
mon = "" + trueMonth;
return mon;
}
public String toStringDate() {
String s = " " + day + "-" + monthToString() + "-" + year;
return s;
}
public String toStringTime() {
// adjust for if hour is < 10 and same for minute
String s = " " + hourToString() + ":" + minuteToString();
return s;
}
public boolean laterThen(EventDateTime e) {
Long endTime = getEntireDateTime();
Long startTime = e.getEntireDateTime();
if ((endTime == Long.valueOf(0)) || (startTime == Long.valueOf(0))
||getEntireDateTime() <= e.getEntireDateTime())
return false;
else
return true;
}
public Long getEntireDateTime() {
String s = "";
s = s.concat("" + year);
s = s.concat("" + day);
s = s.concat(monthToString());
s = s.concat(hourToString());
s = s.concat(minuteToString());
if (year == 0)
// No date has Been Selected
return Long.valueOf(0);
Long entireDateTime = Long.parseLong(s);
Log.i("EventDateTime" , "DateTime: " + entireDateTime);
return entireDateTime;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
}
}
| [
"[email protected]"
] | |
dfaa6f5771f8fe3f6da90087993adf99709b9a36 | 81a410bb85d1e307b06efbc75ff47d513b6de666 | /app/src/main/java/stark/skshare/demo/WeiboShareActivity.java | c659744743a6b40c73158807fa49325fecfecea9 | [
"Apache-2.0"
] | permissive | jhwing/SKShare | bf5f32dc37f2de1b50c30f22119ed46ecd2d3425 | f692852c7e2d6f21a218868240462c0587a390e2 | refs/heads/master | 2020-05-21T20:08:58.779227 | 2017-03-01T10:10:29 | 2017-03-01T10:10:29 | 65,266,193 | 5 | 6 | null | null | null | null | UTF-8 | Java | false | false | 3,262 | java | package stark.skshare.demo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import stark.skshare.SKShare;
import stark.skshare.weibo.WeiboSKShareContent;
import stark.skshare.weibo.WeiboShare;
/**
* Created by jihongwen on 16/8/25.
*/
public class WeiboShareActivity extends BaseToolbarActivity {
ImageView imageView;
Bitmap bitmap;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weibo_share);
imageView = (ImageView) findViewById(R.id.imageView);
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
bitmap = bitmapDrawable.getBitmap();
}
@Override
public void setToolbar(Toolbar toolbar) {
toolbar.setTitle("weibo");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void textShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareText(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setTitle("新浪分享测试 title")
.build(), this);
}
/**
* @param view
*/
public void imageShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareImage(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setImageBitmap(bitmap)
.setTitle("新浪分享测试 title")
.build(), this);
}
/**
* @param view
*/
public void webPageShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareWebpage(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setTitle("新浪分享测试 title")
.setUrl("http://m.budejie.com")
.setImageBitmap(bitmap)
.build(), this);
}
/**
* @param view
*/
public void musicShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareMusic(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setTitle("新浪分享测试 title")
.build(), this);
}
/**
* @param view
*/
public void videoShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareVideo(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setTitle("新浪分享测试 title")
.build(), this);
}
/**
* @param view
*/
public void voiceShare(View view) {
WeiboShare share = SKShare.create(WeiboShare.class, this);
share.shareVoice(new WeiboSKShareContent.Builder()
.setContent("新浪分享测试")
.setTitle("新浪分享测试 title")
.build(), this);
}
}
| [
"[email protected]"
] | |
0ac97bc3e69ce798c855dc8f33be819a96c1d6a8 | 1da2b66632d3ebe6a0c6f9566caaa52b1ef88cb1 | /src/metro/Metro.java | 4bac145b1e3e71a403da66cdad743a0bde750b6d | [] | no_license | mocodertz/metroui | 16fe9a81f31de5e748f886410d70847d58283d84 | 5f8122a17c9fa9926632406e9e4bbafde98ab3e5 | refs/heads/master | 2020-03-30T08:20:44.387345 | 2018-09-30T23:06:55 | 2018-09-30T23:06:55 | 151,007,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,645 | java | /*
* 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 metro;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
/**
*
* @author MO CODER
*/
public class Metro extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane border=new BorderPane();//For All the Scene
border.autosize();
final TilePane temp=new TilePane();
temp.autosize();
temp.setPadding(new Insets(200));
temp.setStyle("-fx-background-image:url(Image/transparent.jpg);");
//Enabling Background Changing
temp.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
if(event.isSecondaryButtonDown()){
//Show the Menu
//The Allow User to Select the Backgroud Pic
//The Apply the Change
//Store the Picture directory
//temp.setStyle("-fx-background-image:url("picture Directory");");
}
}
});
String[] iconname=new String[]{
"word-128.png",
"flying_stork_with_bundle-128.png",
"mouse-128.png",
"firefox-128.png",
"notebook-128.png",
"firefox-128.png",
"publisher-128.png",
"mouse-128.png",
"mouse-128.png",
"flying_stork_with_bundle-128.png",
"notebook-128.png",
"firefox-128.png",
"firefox-128.png",
"mouse-128.png",
"mouse-128.png",
"flying_stork_with_bundle-128.png",
"notebook-128.png",
"firefox-128.png"};
String[] text=new String[]{
"Microsoft Word",
"Mozilar",
"Office",
"Tweet",
"Facebook",
"Firefox",
"Publisher",
"Mozilar",
"Office",
"Tweet",
"Facebook",
"Firefox",
"Chrome",
"Mozilar",
"Office",
"Tweet",
"Facebook",
"Firefox"};
//Colors for Tiles
String[] colors=new String[]{
"-fx-background-color:Green;",
"-fx-background-color:Teal;",
"-fx-background-color:Purple;",
"-fx-background-color:Blue;",
"-fx-background-color:orange;",
"-fx-background-color:Teal;",
"-fx-background-color:Green;",
"-fx-background-color:magenta;",
"-fx-background-color:Purple;",
"-fx-background-color:lime;",
"-fx-background-color:orange;",
"-fx-background-color:Teal;",
"-fx-background-color:Green;",
"-fx-background-color:magenta;",
"-fx-background-color:Purple;",
"-fx-background-color:lime;",
"-fx-background-color:orange;",
"-fx-background-color:Teal;"};
//Application name To be Opned
final String[] appName={
"C:\\Program Files\\Microsoft Office\\Office15\\WINWORD.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\POWERPNT.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\VISIO.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\OUTLOOK.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\GROOVE.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\MSACCESS.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\MSPUB.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\EXCEL.exe",
"C:\\Program Files\\NetBeans 8.0.1\\bin\\netbeans64.exe",
"C:\\Program Files\\Tracker Software\\PDF Viewer\\PDFXCview.exe",
"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\MSPUB.exe",
"C:\\Program Files\\Microsoft Office\\Office15\\EXCEL.exe",
"C:\\Program Files\\NetBeans 8.0.1\\bin\\netbeans64.exe",
"C:\\Program Files\\Tracker Software\\PDF Viewer\\PDFXCview.exe",
"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"
};
//Manuva
for(int i=0;i<iconname.length;i++){
//final Text text_value=new Text(text[i]);
final StackPane tile=new StackPane();
final Rectangle rect=new Rectangle(150,150);
rect.setSmooth(true);
final VBox vbox=new VBox();//to Tile
final VBox vbox_vbox=new VBox();
//Getting the User Data
vbox_vbox.setUserData(appName[i]);
vbox_vbox.setAlignment(Pos.CENTER);
final Label text_value=new Label(text[i]);
text_value.setStyle("-fx-text-fill:white;");
text_value.setLayoutY(20);
//vbox.setStyle("-fx-background-color:Lime;");
vbox_vbox.setStyle(colors[i]);
final ImageView icon=new ImageView(new Image("Icons/"+iconname[i]));
vbox_vbox.getChildren().addAll(icon,text_value);
tile.getChildren().addAll(rect,vbox_vbox);
VBox.setMargin(tile, new Insets(2));
vbox.getChildren().addAll(tile);
//border.getChildren().addAll(icon,text_value);
//border.getChildren().add(icon);
vbox_vbox.setOnMouseEntered(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
vbox_vbox.setOpacity(0.3);
}
});
vbox_vbox.setOnMouseExited(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
vbox_vbox.setOpacity(1);
}
});
//Changing the tile color of the Vbox
vbox_vbox.setOnMousePressed(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
//Creating the Contextmenu Object
Circle crc=new Circle(5,5,5);
crc.setFill(Color.RED);
ContextMenu contextmenu=new ContextMenu();
MenuItem mnitemred=new MenuItem("Red",crc);
//Event fot this
mnitemred.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
//Change the Color of the Selected Vbox_Vbox
vbox_vbox.setStyle("-fx-background-color:Red;");
}});
Circle crcblue=new Circle(5,5,5);
crcblue.setFill(Color.BLUE);
MenuItem mnitemblue=new MenuItem("Blue",crcblue);
//Event for this
mnitemblue.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
//Change the Color of the Selected Vbox_Vbox
vbox_vbox.setStyle("-fx-background-color:Blue;");
}});
Circle crcgreen=new Circle(5,5,5);
crcgreen.setFill(Color.GREEN);
MenuItem mnitemgreen=new MenuItem("Green",crcgreen);
//EVent for this Menu
mnitemgreen.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
//Change the Color of the Selected Vbox_Vbox
vbox_vbox.setStyle("-fx-background-color:Green;");
}});
//Create a Menu Item
//Adding the Menu to the Context Menu
contextmenu.getItems().addAll(mnitemgreen,mnitemblue,mnitemred);
vbox_vbox.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
if(event.getButton()==MouseButton.SECONDARY){
contextmenu.show(vbox_vbox,event.getSceneX(),event.getSceneY());
}
}
});
}
});
//Trying to Opne Another App
vbox_vbox.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
//Checking whihc Mose Button CLicked
if(event.getButton()==MouseButton.PRIMARY){
try{
Runtime runtime=Runtime.getRuntime();
Process process=runtime.exec(vbox_vbox.getUserData().toString());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
});
temp.getChildren().addAll(vbox);
//border.getChildren().add(temp,);
}
//Manuva
border.setCenter(temp);//Adding Content to the Center
// border.setTop(sytesmDetails());
Scene scene = new Scene(border, 465, 310);
primaryStage.setTitle("DashBoard");
primaryStage.setMaximized(true);
primaryStage.getIcons().add(new Image("Icons/Start Alt.png"));
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
//HBOX for Showing User Deatils
//Getting User Name
//User Account Image
//WIndowss Version
//Computer Name
//Bits
//Ram Size
//Processor Info
public HBox sytesmDetails(){
HBox tempLocal=new HBox();
String osName=System.getProperty("os.name");
String osVersion=System.getProperty("os.version");
String userName=System.getProperty("user.name");
//Image for Accout Picture
ImageView accountPic=new ImageView(new Image("Icons/flying_stork_with_bundle-128.png"));
//Vertical Box For OS Details
VBox osDetails=new VBox();
Label dispOsName=new Label("Operating Sytem: " + osName);
Label dispOsVer=new Label("Operating System Vertion:" +osVersion);
Label dispUserName=new Label("User Name: " + userName);
//Adding the Two Label to Veticsl Box
osDetails.getChildren().addAll(dispUserName,dispOsName,dispOsVer);
//Adding to the Horizontal Box
tempLocal.getChildren().addAll(accountPic,osDetails);
tempLocal.setStyle("-fx-background-image:url(Image/fabulousgirl.jpg);");
tempLocal.setAlignment(Pos.TOP_RIGHT);
return tempLocal;
}
}
| [
"[email protected]"
] | |
11acfc7afc5f5c14d6fc86d619a86114e28f0738 | 63245155f916fc51625dab1c0c99eb6837616c23 | /app/src/main/java/com/framgia/wsm/screen/managelistrequests/memberrequestdetail/MemberRequestDetailViewModel.java | 99bff1bf67ed426ddb135a8537d388b00e015c22 | [] | no_license | AppSecAI-TEST/wsm_android | 263e1302047c8b5e46e7f72f8ff86f66d6da3a66 | 0208c08608a8a34557333dc2df53bf2ba8d4f465 | refs/heads/develop | 2021-01-16T11:39:52.551496 | 2017-08-11T04:15:27 | 2017-08-11T04:15:27 | 100,002,193 | 0 | 0 | null | 2017-08-11T07:00:35 | 2017-08-11T07:00:35 | null | UTF-8 | Java | false | false | 37,027 | java | package com.framgia.wsm.screen.managelistrequests.memberrequestdetail;
import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.support.annotation.IntDef;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import com.framgia.wsm.BR;
import com.framgia.wsm.R;
import com.framgia.wsm.data.model.LeaveRequest;
import com.framgia.wsm.data.model.OffRequest;
import com.framgia.wsm.data.model.OffType;
import com.framgia.wsm.data.model.RequestOverTime;
import com.framgia.wsm.data.model.User;
import com.framgia.wsm.data.source.remote.api.error.BaseException;
import com.framgia.wsm.data.source.remote.api.request.ActionRequest;
import com.framgia.wsm.data.source.remote.api.response.ActionRequestResponse;
import com.framgia.wsm.screen.requestoff.RequestOffViewModel;
import com.framgia.wsm.utils.Constant;
import com.framgia.wsm.utils.RequestType;
import com.framgia.wsm.utils.StatusCode;
import com.framgia.wsm.utils.TypeToast;
import com.framgia.wsm.utils.common.DateTimeUtils;
import com.framgia.wsm.utils.common.StringUtils;
import com.framgia.wsm.utils.navigator.Navigator;
import com.framgia.wsm.widget.dialog.DialogManager;
import java.util.List;
/**
* Created by ths on 11/07/2017.
*/
public class MemberRequestDetailViewModel extends BaseObservable
implements MemberRequestDetailContract.ViewModel {
private static final String TAG = "MemberRequestDetailViewModel";
private static final String ANNUAL = "Annual";
private Context mContext;
private MemberRequestDetailContract.Presenter mPresenter;
private Navigator mNavigator;
private DialogManager mDialogManager;
private OffRequest mOffRequest;
private LeaveRequest mLeaveRequest;
private RequestOverTime mOverTimeRequest;
private DismissDialogListener mDismissDialogListener;
private ActionRequest mActionRequest;
private boolean mIsVisibleApprove;
private boolean mIsVisibleReject;
private boolean mIsStatusAccept;
private boolean mIsStatusReject;
private boolean mIsStatusPending;
private boolean mIsStatusForward;
private int mPosition;
private ApproveOrRejectListener mResultListener;
private int mCurrentRequestType;
private User mUser;
private String mAnnualLeaveAmount;
private String mLeaveForMarriageAmount;
private String mLeaveForChildMarriageAmount;
private String mFuneralLeaveAmount;
private String mLeaveForCareOfSickChildAmount;
private String mPregnancyExaminationLeaveAmount;
private String mSickLeaveAmount;
private String mMiscarriageLeaveAmount;
private String mMaternityLeaveAmount;
private String mWifeLaborLeaveAmount;
private boolean mIsForward;
MemberRequestDetailViewModel(Context context, Fragment fragment,
MemberRequestDetailContract.Presenter presenter, Navigator navigator,
DialogManager dialogManager, Object item, int position,
ApproveOrRejectListener resultListener) {
mContext = context;
mPresenter = presenter;
mPresenter.setViewModel(this);
mPresenter.getUser();
mNavigator = navigator;
mDismissDialogListener = (DismissDialogListener) fragment;
mDialogManager = dialogManager;
mOffRequest = new OffRequest();
mLeaveRequest = new LeaveRequest();
mOverTimeRequest = new RequestOverTime();
mActionRequest = new ActionRequest();
setItemMemberRequest(item);
setIsVisibleApprove(StatusCode.ACCEPT_CODE.equals(mOffRequest.getStatus())
|| StatusCode.ACCEPT_CODE.equals(mLeaveRequest.getStatus())
|| StatusCode.ACCEPT_CODE.equals(mOverTimeRequest.getStatus()));
setIsVisibleReject(StatusCode.REJECT_CODE.equals(mOffRequest.getStatus())
|| StatusCode.REJECT_CODE.equals(mLeaveRequest.getStatus())
|| StatusCode.REJECT_CODE.equals(mOverTimeRequest.getStatus()));
setStatusAccept(StatusCode.ACCEPT_CODE.equals(mOffRequest.getStatus())
|| StatusCode.ACCEPT_CODE.equals(mLeaveRequest.getStatus())
|| StatusCode.ACCEPT_CODE.equals(mOverTimeRequest.getStatus()));
setStatusReject(StatusCode.REJECT_CODE.equals(mOffRequest.getStatus())
|| StatusCode.REJECT_CODE.equals(mLeaveRequest.getStatus())
|| StatusCode.REJECT_CODE.equals(mOverTimeRequest.getStatus()));
setStatusPending(StatusCode.PENDING_CODE.equals(mOffRequest.getStatus())
|| StatusCode.PENDING_CODE.equals(mLeaveRequest.getStatus())
|| StatusCode.PENDING_CODE.equals(mOverTimeRequest.getStatus()));
mPosition = position;
mResultListener = resultListener;
}
private void setItemMemberRequest(Object item) {
if (item instanceof LeaveRequest) {
mLeaveRequest = (LeaveRequest) item;
mActionRequest.setTypeRequest(TypeRequest.LEAVE);
mCurrentRequestType = RequestType.REQUEST_LATE_EARLY;
setForward(!mLeaveRequest.isCanApproveReject());
if (!mLeaveRequest.isCanApproveReject() && StatusCode.FORWARD_CODE.equals(
mLeaveRequest.getStatus())) {
setStatusForward(true);
}
} else if (item instanceof RequestOverTime) {
mOverTimeRequest = (RequestOverTime) item;
mActionRequest.setTypeRequest(TypeRequest.OT);
mCurrentRequestType = RequestType.REQUEST_OVERTIME;
setForward(!mOverTimeRequest.isCanApproveReject());
if (!mOverTimeRequest.isCanApproveReject() && StatusCode.FORWARD_CODE.equals(
mOverTimeRequest.getStatus())) {
setStatusForward(true);
}
} else {
mOffRequest = (OffRequest) item;
mActionRequest.setTypeRequest(TypeRequest.OFF);
mCurrentRequestType = RequestType.REQUEST_OFF;
setForward(!mOffRequest.isCanApproveReject());
if (!mOffRequest.isCanApproveReject() && StatusCode.FORWARD_CODE.equals(
mOffRequest.getStatus())) {
setStatusForward(true);
}
}
}
@Override
public void onStart() {
mPresenter.onStart();
}
@Override
public void onStop() {
mPresenter.onStop();
}
@Override
public void onError(BaseException e) {
mNavigator.showToastCustom(TypeToast.ERROR, e.getMessage());
}
@Override
public void onDismissProgressDialog() {
mDialogManager.dismissProgressDialog();
}
@Override
public void onShowIndeterminateProgressDialog() {
mDialogManager.showIndeterminateProgressDialog();
}
@Override
public void onApproveOrRejectRequestSuccess(ActionRequestResponse actionRequestResponse) {
mResultListener.onApproveOrRejectListener(mCurrentRequestType, mPosition,
actionRequestResponse);
if ((actionRequestResponse.getStatus().equals(StatusCode.ACCEPT_CODE))
|| actionRequestResponse.getStatus().equals(StatusCode.FORWARD_CODE)) {
mNavigator.showToastCustom(TypeToast.SUCCESS,
mContext.getString(R.string.approve_success));
}
if (actionRequestResponse.getStatus().equals(StatusCode.REJECT_CODE)) {
mNavigator.showToastCustom(TypeToast.SUCCESS,
mContext.getString(R.string.reject_success));
}
mDismissDialogListener.onDismissDialog();
}
@Override
public void onGetUserSuccess(User user) {
if (user == null) {
return;
}
mUser = user;
getAmountOffDayCompany(mUser);
getAmountOffDayInsurance(mUser);
}
public boolean isVisibleOffRequest() {
return mOffRequest.getId() != 0;
}
public boolean isVisibleLeaveRequest() {
return mLeaveRequest.getId() != null;
}
public boolean isVisibleOverTimeRequest() {
return mOverTimeRequest.getId() != 0;
}
public LeaveRequest getLeaveRequest() {
return mLeaveRequest;
}
public RequestOverTime getOverTimeRequest() {
return mOverTimeRequest;
}
public OffRequest getOffRequest() {
return mOffRequest;
}
public String getCreateAtOffRequest() {
if (mOffRequest.getCreatedAt() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(mOffRequest.getCreatedAt(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY);
}
public String getCreateAtLeaveRequest() {
if (mLeaveRequest.getCreateAt() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(mLeaveRequest.getCreateAt(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY);
}
public String getCreateAtOverTimeRequest() {
if (mOverTimeRequest.getCreatedAt() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(mOverTimeRequest.getCreatedAt(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY);
}
public String getToTime() {
if (mOverTimeRequest.getToTime() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(mOverTimeRequest.getToTime(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY);
}
public String getFromTime() {
if (mOverTimeRequest.getFromTime() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(mOverTimeRequest.getFromTime(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY);
}
@Bindable
public boolean isVisibleApprove() {
return mIsVisibleApprove;
}
private void setIsVisibleApprove(boolean visibleApprove) {
mIsVisibleApprove = visibleApprove;
notifyPropertyChanged(BR.visibleApprove);
}
@Bindable
public boolean isVisibleReject() {
return mIsVisibleReject;
}
private void setIsVisibleReject(boolean visibleReject) {
mIsVisibleReject = visibleReject;
notifyPropertyChanged(BR.visibleReject);
}
public boolean isVisiableLayoutCompanyPay() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
if (mOffRequest.getNumberDayOffNormal() != null
&& mOffRequest.getNumberDayOffNormal() != 0) {
return true;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if ((offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_MARRIAGE
|| offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CHILD_IS_MARRIAGE
|| offType.getSpecialDayOffSettingId() == OffTypeId.FUNERAL_LEAVE)) {
return true;
}
}
return false;
}
public boolean isVisiableLayoutInsurance() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if ((offType.getSpecialDayOffSettingId() == OffTypeId.MATERNITY_LEAVE
|| offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CARE_OF_SICK_CHILD
|| offType.getSpecialDayOffSettingId() == OffTypeId.WIFE_IS_LABOR_LEAVE
|| offType.getSpecialDayOffSettingId() == OffTypeId.MISCARRIAGE_LEAVE
|| offType.getSpecialDayOffSettingId() == OffTypeId.SICK_LEAVE
|| offType.getSpecialDayOffSettingId()
== OffTypeId.PREGNANCY_EXAMINATION_LEAVE)) {
return true;
}
}
return false;
}
public boolean isVisiableLayoutTimeCompensation() {
if (mLeaveRequest.getId() != null) {
return mLeaveRequest.getCompensation().getFromTime() != null;
}
return false;
}
public boolean isVisiableLayoutHaveSalary() {
if (mOffRequest.getId() != 0) {
return StringUtils.isBlank(mOffRequest.getStartDayHaveSalary().getOffPaidFrom());
}
return false;
}
public boolean isVisiableLayoutOffNoSalary() {
if (mOffRequest.getId() != 0) {
return StringUtils.isBlank(mOffRequest.getStartDayNoSalary().getOffFrom());
}
return false;
}
public boolean isVisiableAnnualLeave() {
return mOffRequest.getNumberDayOffNormal() != null
&& mOffRequest.getNumberDayOffNormal() != 0;
}
public boolean isVisiableLeaveForChildMarriage() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CHILD_IS_MARRIAGE) {
return true;
}
}
return false;
}
public boolean isVisiableLeaveForMarriage() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_MARRIAGE) {
return true;
}
}
return false;
}
public boolean isVisiableFuneralLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.FUNERAL_LEAVE) {
return true;
}
}
return false;
}
public boolean isVisiableLeaveForCareOfSickChild() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CARE_OF_SICK_CHILD) {
return true;
}
}
return false;
}
public boolean isVisiableSickLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.SICK_LEAVE) {
return true;
}
}
return false;
}
public boolean isVisiableMaternityLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.MATERNITY_LEAVE) {
return true;
}
}
return false;
}
public boolean isVisiablePregnancyExaminationLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.PREGNANCY_EXAMINATION_LEAVE) {
return true;
}
}
return false;
}
public boolean isVisiableMiscarriageLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.MISCARRIAGE_LEAVE) {
return true;
}
}
return false;
}
public boolean isVisiableWifeLaborLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return false;
}
for (OffRequest.RequestDayOffType offType : mOffRequest.getRequestDayOffTypes()) {
if (offType.getSpecialDayOffSettingId() == OffTypeId.WIFE_IS_LABOR_LEAVE) {
return true;
}
}
return false;
}
public String getDateWifeLaborLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.WIFE_IS_LABOR_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateMiscarriageLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.MISCARRIAGE_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDatePregnancyExaminationLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.PREGNANCY_EXAMINATION_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateMaternityLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.MATERNITY_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateSickLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.SICK_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateLeaveForCareOfSickChild() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CARE_OF_SICK_CHILD) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateFuneralLeave() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.FUNERAL_LEAVE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateLeaveAnnual() {
if (mOffRequest.getNumberDayOffNormal() == null) {
return "";
}
return String.valueOf(mOffRequest.getNumberDayOffNormal());
}
public String getDateLeaveForChildIsMarriage() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_CHILD_IS_MARRIAGE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getDateLeaveForMarriage() {
if (mOffRequest.getRequestDayOffTypes() == null) {
return "";
}
for (OffRequest.RequestDayOffType offRequest : mOffRequest.getRequestDayOffTypes()) {
if (offRequest.getSpecialDayOffSettingId() == OffTypeId.LEAVE_FOR_MARRIAGE) {
return String.valueOf(offRequest.getNumberDayOff());
}
}
return "";
}
public String getCompensationTime() {
if (mLeaveRequest.getCompensation() == null) {
return "";
}
return DateTimeUtils.convertUiFormatToDataFormat(
mLeaveRequest.getCompensation().getFromTime(), DateTimeUtils.INPUT_TIME_FORMAT,
DateTimeUtils.TIME_FORMAT_HH_MM)
+ Constant.BLANK_DASH_BLANK
+ DateTimeUtils.convertUiFormatToDataFormat(
mLeaveRequest.getCompensation().getToTime(), DateTimeUtils.INPUT_TIME_FORMAT,
DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY_2);
}
public String getStartDayHaveSalary() {
if (mOffRequest.getStartDayHaveSalary() == null) {
return "";
}
return mOffRequest.getStartDayHaveSalary().getOffPaidFrom()
+ Constant.BLANK
+ mOffRequest.getStartDayHaveSalary().getPaidFromPeriod();
}
public String getEndDayHaveSalary() {
if (mOffRequest.getEndDayHaveSalary() == null) {
return "";
}
return mOffRequest.getEndDayHaveSalary().getOffPaidTo()
+ Constant.BLANK
+ mOffRequest.getEndDayHaveSalary().getPaidToPeriod();
}
public String getStartDayNoSalary() {
if (mOffRequest.getStartDayNoSalary() == null) {
return "";
}
return mOffRequest.getStartDayNoSalary().getOffFrom()
+ Constant.BLANK
+ mOffRequest.getStartDayNoSalary().getOffFromPeriod();
}
public String getEndDayNoSalary() {
if (mOffRequest.getEndDayNoSalary() == null) {
return "";
}
return mOffRequest.getEndDayNoSalary().getOffTo()
+ Constant.BLANK
+ mOffRequest.getEndDayNoSalary().getOffToPeriod();
}
public String getTimeLeaveRequest() {
if (mLeaveRequest.getId() != null) {
final String requestCheckInByTimeAndDate = DateTimeUtils.convertUiFormatToDataFormat(
mLeaveRequest.getCheckInTime() + Constant.DATE_TIME_SPACE,
DateTimeUtils.INPUT_TIME_FORMAT,
DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY_2);
final String requestCheckOutByTimeAndDate =
DateTimeUtils.convertUiFormatToDataFormat(mLeaveRequest.getCheckOutTime(),
DateTimeUtils.INPUT_TIME_FORMAT,
DateTimeUtils.DATE_TIME_FORMAT_HH_MM_DD_MM_YYYY_2);
final String requestCheckOutByTime =
DateTimeUtils.convertUiFormatToDataFormat(mLeaveRequest.getCheckOutTime(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.TIME_FORMAT_HH_MM);
final String requestCheckInByTime =
DateTimeUtils.convertUiFormatToDataFormat(mLeaveRequest.getCheckInTime(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.TIME_FORMAT_HH_MM);
final String requestCheckOutByDate =
DateTimeUtils.convertUiFormatToDataFormat(mLeaveRequest.getCheckOutTime(),
DateTimeUtils.INPUT_TIME_FORMAT, DateTimeUtils.FORMAT_DATE);
switch (mLeaveRequest.getLeaveType().getId()) {
case LeaveType.IN_LATE_M:
case LeaveType.IN_LATE_A:
return Constant.BEGIN_MORNING_TIME
+ Constant.BLANK_DASH_BLANK
+ requestCheckInByTimeAndDate;
case LeaveType.LEAVE_EARLY_M:
return requestCheckOutByTime
+ Constant.DATE_TIME_SPACE
+ Constant.END_MORNING_TIME
+ Constant.BLANK
+ requestCheckOutByDate;
case LeaveType.LEAVE_OUT:
case LeaveType.FORGOT_CARD_ALL_DAY:
case LeaveType.FORGOT_CHECK_ALL_DAY:
return requestCheckInByTime
+ Constant.DATE_TIME_SPACE
+ Constant.BLANK
+ requestCheckOutByTimeAndDate;
case LeaveType.FORGOT_CARD_IN:
case LeaveType.IN_LATE_WOMAN_M:
case LeaveType.IN_LATE_WOMAN_A:
case LeaveType.FORGOT_TO_CHECK_IN:
return requestCheckInByTimeAndDate;
case LeaveType.FORGOT_CARD_OUT:
case LeaveType.LEAVE_EARLY_A:
case LeaveType.LEAVE_EARLY_WOMAN_M:
case LeaveType.LEAVE_EARLY_WOMAN_A:
case LeaveType.FORGOT_TO_CHECK_OUT:
return requestCheckOutByTimeAndDate;
default:
return "";
}
}
return "";
}
@Bindable
public boolean isAcceptStatus() {
return mIsStatusAccept;
}
private void setStatusAccept(boolean isStatusAccept) {
mIsStatusAccept = isStatusAccept;
notifyPropertyChanged(BR.acceptStatus);
}
@Bindable
public boolean isPendingStatus() {
return mIsStatusPending;
}
private void setStatusPending(boolean statusPending) {
mIsStatusPending = statusPending;
notifyPropertyChanged(BR.pendingStatus);
}
private void setStatusReject(boolean isStatusReject) {
mIsStatusReject = isStatusReject;
notifyPropertyChanged(BR.rejectStatus);
}
@Bindable
public boolean isRejectStatus() {
return mIsStatusReject;
}
public String getAnnualLeaveAmount() {
return String.format(mContext.getString(R.string.annual_leave), mAnnualLeaveAmount);
}
public void setAnnualLeaveAmount(String annualLeaveAmount) {
mAnnualLeaveAmount = annualLeaveAmount;
}
public String getLeaveForMarriageAmount() {
return String.format(mContext.getString(R.string.leave_for_marriage),
mLeaveForMarriageAmount);
}
public void setLeaveForMarriageAmount(String leaveForMarriageAmount) {
mLeaveForMarriageAmount = leaveForMarriageAmount;
}
public String getLeaveForChildMarriageAmount() {
return String.format(mContext.getString(R.string.leave_for_child_marriage),
mLeaveForChildMarriageAmount);
}
public void setLeaveForChildMarriageAmount(String leaveForChildMarriageAmount) {
mLeaveForChildMarriageAmount = leaveForChildMarriageAmount;
}
public String getFuneralLeaveAmount() {
return String.format(mContext.getString(R.string.funeral_leave), mFuneralLeaveAmount);
}
public void setFuneralLeaveAmount(String funeralLeaveAmount) {
mFuneralLeaveAmount = funeralLeaveAmount;
}
public String getLeaveForCareOfSickChildAmount() {
return String.format(mContext.getString(R.string.leave_for_care_of_sick_child),
mLeaveForCareOfSickChildAmount);
}
public void setLeaveForCareOfSickChildAmount(String leaveForCareOfSickChildAmount) {
mLeaveForCareOfSickChildAmount = leaveForCareOfSickChildAmount;
}
public String getPregnancyExaminationLeaveAmount() {
return String.format(mContext.getString(R.string.pregnancy_examination_leave),
mPregnancyExaminationLeaveAmount);
}
public void setPregnancyExaminationLeaveAmount(String pregnancyExaminationLeaveAmount) {
mPregnancyExaminationLeaveAmount = pregnancyExaminationLeaveAmount;
}
public String getSickLeaveAmount() {
return String.format(mContext.getString(R.string.sick_leave), mSickLeaveAmount);
}
public void setSickLeaveAmount(String sickLeaveAmount) {
mSickLeaveAmount = sickLeaveAmount;
}
public String getMiscarriageLeaveAmount() {
return String.format(mContext.getString(R.string.miscarriage_leave),
mMiscarriageLeaveAmount);
}
public void setMiscarriageLeaveAmount(String miscarriageLeaveAmount) {
mMiscarriageLeaveAmount = miscarriageLeaveAmount;
}
public String getMaternityLeaveAmount() {
return String.format(mContext.getString(R.string.maternity_leave), mMaternityLeaveAmount);
}
public void setMaternityLeaveAmount(String maternityLeaveAmount) {
mMaternityLeaveAmount = maternityLeaveAmount;
}
public String getWifeLaborLeaveAmount() {
return String.format(mContext.getString(R.string.wife_labor_leave), mWifeLaborLeaveAmount);
}
public void setWifeLaborLeaveAmount(String wifeLaborLeaveAmount) {
mWifeLaborLeaveAmount = wifeLaborLeaveAmount;
}
public boolean isVisibleLayoutOffRequestTitle() {
return (isVisiableLayoutCompanyPay() || isVisiableLayoutInsurance());
}
@Bindable
public boolean isForward() {
return mIsForward;
}
private void setForward(boolean forward) {
mIsForward = forward;
notifyPropertyChanged(BR.forward);
}
@Bindable
public boolean isStatusForward() {
return mIsStatusForward;
}
public void setStatusForward(boolean statusForward) {
mIsStatusForward = statusForward;
notifyPropertyChanged(BR.statusForward);
}
private void getAmountOffDayCompany(User user) {
if (!(mOffRequest.getId() != 0 && isVisiableLayoutCompanyPay())) {
return;
}
List<OffType> offTypesCompanyPay = user.getTypesCompany();
for (int i = 0; i < offTypesCompanyPay.size(); i++) {
if (offTypesCompanyPay.get(i).getName().equals(ANNUAL)) {
setAnnualLeaveAmount(String.valueOf(offTypesCompanyPay.get(i).getAmount()));
}
if (offTypesCompanyPay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.LEAVE_FOR_MARRIAGE)) {
setLeaveForMarriageAmount(String.valueOf(offTypesCompanyPay.get(i).getAmount()));
}
if (offTypesCompanyPay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.LEAVE_FOR_CHILD_MARRIAGE)) {
setLeaveForChildMarriageAmount(
String.valueOf(offTypesCompanyPay.get(i).getAmount()));
}
if (offTypesCompanyPay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.FUNERAL_LEAVE)) {
setFuneralLeaveAmount(String.valueOf(offTypesCompanyPay.get(i).getAmount()));
}
}
}
private void getAmountOffDayInsurance(User user) {
if (!(mOffRequest.getId() != 0 && isVisiableLayoutInsurance())) {
return;
}
List<OffType> offTypesInsurancePay = user.getTypesInsurance();
for (int i = 0; i < offTypesInsurancePay.size(); i++) {
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.LEAVE_FOR_CARE_OF_SICK_CHILD)) {
setLeaveForCareOfSickChildAmount(
String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.PREGNANCY_EXAMINATON)) {
setPregnancyExaminationLeaveAmount(
String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.SICK_LEAVE)) {
setSickLeaveAmount(String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.MISCARRIAGE_LEAVE)) {
setMiscarriageLeaveAmount(String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.MATERNTY_LEAVE)) {
setMaternityLeaveAmount(String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
if (offTypesInsurancePay.get(i).getId() == Integer.parseInt(
RequestOffViewModel.TypeOfDays.WIFE_LABOR_LEAVE)) {
setWifeLaborLeaveAmount(String.valueOf(offTypesInsurancePay.get(i).getAmount()));
}
}
}
public void onClickArrowBack() {
mDismissDialogListener.onDismissDialog();
}
public void onClickRejected() {
if (mOffRequest.getId() != 0) {
mActionRequest.setStatus(StatusCode.REJECT_CODE);
mActionRequest.setRequestId(mOffRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
} else if (mOverTimeRequest.getId() != 0) {
mActionRequest.setStatus(StatusCode.REJECT_CODE);
mActionRequest.setRequestId(mOverTimeRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
} else {
mActionRequest.setStatus(StatusCode.REJECT_CODE);
mActionRequest.setRequestId(mLeaveRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
}
}
public void onClickApprove() {
if (mOffRequest.getId() != 0) {
mActionRequest.setStatus(StatusCode.ACCEPT_CODE);
mActionRequest.setRequestId(mOffRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
} else if (mOverTimeRequest.getId() != 0) {
mActionRequest.setStatus(StatusCode.ACCEPT_CODE);
mActionRequest.setRequestId(mOverTimeRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
} else {
mActionRequest.setStatus(StatusCode.ACCEPT_CODE);
mActionRequest.setRequestId(mLeaveRequest.getId());
mPresenter.approveOrRejectRequest(mActionRequest);
}
}
@IntDef({
LeaveType.IN_LATE_M, LeaveType.IN_LATE_A, LeaveType.LEAVE_EARLY_M,
LeaveType.LEAVE_EARLY_A, LeaveType.LEAVE_OUT, LeaveType.FORGOT_CHECK_ALL_DAY,
LeaveType.FORGOT_TO_CHECK_IN, LeaveType.FORGOT_TO_CHECK_OUT,
LeaveType.FORGOT_CARD_ALL_DAY, LeaveType.FORGOT_CARD_IN, LeaveType.FORGOT_CARD_OUT,
LeaveType.IN_LATE_WOMAN_M, LeaveType.IN_LATE_WOMAN_A, LeaveType.LEAVE_EARLY_WOMAN_M,
LeaveType.LEAVE_EARLY_WOMAN_A
})
public @interface LeaveType {
int IN_LATE_M = 1;
int LEAVE_EARLY_M = 2;
int LEAVE_OUT = 3;
int IN_LATE_A = 4;
int IN_LATE_WOMAN_M = 5;
int FORGOT_CHECK_ALL_DAY = 7;
int FORGOT_TO_CHECK_IN = 12;
int FORGOT_TO_CHECK_OUT = 13;
int LEAVE_EARLY_A = 14;
int IN_LATE_WOMAN_A = 15;
int LEAVE_EARLY_WOMAN_M = 16;
int LEAVE_EARLY_WOMAN_A = 17;
int FORGOT_CARD_IN = 19;
int FORGOT_CARD_OUT = 20;
int FORGOT_CARD_ALL_DAY = 21;
}
@IntDef({
OffTypeId.LEAVE_FOR_MARRIAGE, OffTypeId.LEAVE_FOR_CHILD_IS_MARRIAGE,
OffTypeId.MATERNITY_LEAVE, OffTypeId.LEAVE_FOR_CARE_OF_SICK_CHILD,
OffTypeId.FUNERAL_LEAVE, OffTypeId.WIFE_IS_LABOR_LEAVE, OffTypeId.MISCARRIAGE_LEAVE,
OffTypeId.SICK_LEAVE, OffTypeId.PREGNANCY_EXAMINATION_LEAVE
})
public @interface OffTypeId {
int LEAVE_FOR_MARRIAGE = 2;
int LEAVE_FOR_CHILD_IS_MARRIAGE = 3;
int MATERNITY_LEAVE = 6;
int LEAVE_FOR_CARE_OF_SICK_CHILD = 9;
int FUNERAL_LEAVE = 10;
int WIFE_IS_LABOR_LEAVE = 14;
int MISCARRIAGE_LEAVE = 17;
int SICK_LEAVE = 19;
int PREGNANCY_EXAMINATION_LEAVE = 22;
}
@StringDef({
TypeRequest.LEAVE, TypeRequest.OFF, TypeRequest.OT
})
@interface TypeRequest {
String LEAVE = "leave";
String OFF = "off";
String OT = "ot";
}
public interface ApproveOrRejectListener {
void onApproveOrRejectListener(@RequestType int requestType, int itemPosition,
ActionRequestResponse actionRequestResponse);
}
}
| [
"[email protected]"
] | |
e8067138e01da62b56b8b141eae22c1b3547ffa8 | 0ef9046a3e034e2f8717fb2cd4375905a59e04de | /Sample/SpringIOC/src/main/java/com/app/ioc/Test1/MotorBike.java | 1b551752d2d0c3d7670471649e0f206891e9ff05 | [] | no_license | Peddaraju/MyProjectRepository | 4d4a363a98efdb8462146b5b576985c56eb1bfa8 | 0337a3a2d2db319684b322496ee9f527366d6c49 | refs/heads/master | 2021-06-06T18:31:03.757933 | 2018-12-20T12:05:59 | 2018-12-20T12:05:59 | 95,098,893 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 345 | java | package com.app.ioc.Test1;
public class MotorBike implements Vechicle {
private int maxSpeed;
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public void move() {
System.out.println("Fuel Type: Petrol");
System.out.println("Max speed:"+maxSpeed);
System.out.println("Bike started...");
}
}
| [
"[email protected]"
] | |
70e2d9bd7e7d3b44f5153546abbf616bb6e0a02f | ede2136d7f1a60edadc7458cbda5ceeda821bd70 | /AbstractFactory/src/br/com/k19/abstractfactory/models/cartoes/mastercard/teste/TesteMastercardComunicadorFactory.java | 97374e91e950eed83bfa8fbb35f4008c5e3ab5e7 | [] | no_license | viniciusSilvano/K19DesignPatternsCriacao | cea37a42102012e4a1a82dbb98de5f481804b1f5 | 9e98eb41e8e5e2f04c255efc977f2828c0ac3e73 | refs/heads/master | 2020-09-11T20:08:13.155501 | 2019-12-01T21:42:42 | 2019-12-01T21:42:42 | 222,177,152 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 775 | java | package br.com.k19.abstractfactory.models.cartoes.mastercard.teste;
import br.com.k19.abstractfactory.models.Emissor;
import br.com.k19.abstractfactory.models.Receptor;
import br.com.k19.abstractfactory.models.cartoes.factory.ComunicadorFactory;
import br.com.k19.abstractfactory.models.cartoes.mastercard.MastercardComunicadorFactory;
public class TesteMastercardComunicadorFactory {
public static void main(String[] args) {
ComunicadorFactory comunicadorFactory = new MastercardComunicadorFactory();
String transacao = "Valor=660;Senha123";
Emissor emissor = comunicadorFactory.createEmissor();
emissor.envia(transacao);
Receptor receptor = comunicadorFactory.createReceptor();
String mensagem = receptor.recebe();
System.out.println(mensagem);
}
}
| [
"[email protected]"
] | |
d0469484d5696cc73769ef1a138bfa58bb26dc6f | 9593f22e1ef7635c92cdc3ae674a988ec90317c4 | /src/main/java/com/sigurd4/bioshock/passives/PassiveStaticDischarge.java | 2b0c341b55764c28e68705ff60e0e631d608b5a8 | [] | no_license | sigurd4/BioShockMod | 847ca445f1a6fe40487687469067b044c62e3a7a | 2cbe39b673080997ce413d7812c52e5104265aa1 | refs/heads/master | 2020-05-17T23:08:39.269632 | 2015-06-30T22:52:04 | 2015-06-30T22:53:10 | 34,406,444 | 1 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,359 | java | package com.sigurd4.bioshock.passives;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import com.sigurd4.bioshock.element.Element;
public class PassiveStaticDischarge extends Passive
{
public final Element element;
public final float damage;
public final float chance;
public PassiveStaticDischarge(String id, String name, Passive[] required, Passive[] incapatible, Type type, Element element, float damage, float chance)
{
super(id, name, required, incapatible, type);
this.element = element;
this.damage = damage;
this.chance = chance;
}
@Override
public void LivingHurtEvent(LivingHurtEvent event)
{
if(!event.source.isUnblockable() && event.ammount > 0)
{
if(event.source.getEntity() instanceof EntityLivingBase && !event.source.getEntity().isEntityInvulnerable(event.source) && event.source.getEntity() != null)
{
if(event.source.getEntity().attackEntityFrom(Element.electricity(event.entity), event.ammount / 2 * (1 + this.damage / 5)))
{
if(event.entity.worldObj.rand.nextFloat() <= this.chance)
{
Element.setEntityElement((EntityLivingBase)event.source.getEntity(), this.element, (int)(this.damage * 20), false);
}
Element.addToEntityElement(event.entityLiving, this.element, (int)(this.damage * 2));
}
}
}
}
}
| [
"[email protected]"
] | |
d3dbb263e655aa79cb1e4485d876ae8f0c1e992a | 17baa7e14c352564010cba8998d1d1d2440cc340 | /jvmload/src/main/java/com/example/jvmload/JvmloadApplication.java | 9c33df297b706e18d13549dc4370c0ad80158e3d | [] | no_license | liusuifen/file-change | 36601f68734509e3c40d7e1bd8e43545646acbfb | af78e9487312095306937a56e8ac23e2c148295d | refs/heads/master | 2022-07-23T00:39:32.765298 | 2020-04-09T07:21:31 | 2020-04-09T07:21:31 | 254,043,913 | 0 | 0 | null | 2021-06-15T16:04:35 | 2020-04-08T09:30:59 | Java | UTF-8 | Java | false | false | 326 | java | package com.example.jvmload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JvmloadApplication {
public static void main(String[] args) {
SpringApplication.run(JvmloadApplication.class, args);
}
}
| [
"[email protected]"
] | |
c3a09dc18807f228f3154a90e227a7d79a2c88b9 | e128eae6e1ee6080fdd31699daebbe19a5def299 | /M1LectureCode/StudentTester.java | 2854afc41e2a1c975ba9e7d9d1731d06a502d84f | [] | no_license | ericyan3000/CS111C | 4d41af014f0c59f582e728c36cf405f3c657cf97 | f3ad0ae591c33f71a48a8ad9063333683d166cae | refs/heads/master | 2020-12-22T05:34:25.112664 | 2020-05-13T07:41:52 | 2020-05-13T07:41:52 | 236,684,208 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 659 | java |
public class StudentTester {
public static void main(String[] args) {
Student s1 = new Student("Sally", "Studier", 1234);
Student s2 = new Student("Pete", "Procrastinator", 5264);
Student s3 = new Student("Alan", "Asksalot", 3671);
Student s4 = new Student("Sally", "Studier", 1234);
s3.setLastName("Asksaton");
s3.setStudentID(999999);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println("Are they equal? " + s1.equals(s4));
System.out.println("Are they aliases? " + (s1==s4));
Student s = null;
if(s != null && s.equals(s)) {
System.out.println("paid");
}
}
}
| [
"[email protected]"
] | |
025459f9a0c8bde4ba08572e6153684c82a7a365 | 04dc03b750d078bac08129fe9802d680b5d5aa44 | /src/hu/eisys/david/model/Efile.java | fa51dcec77a3ab90ea6d9e552fd0974ea7fd7aad | [] | no_license | eisysDavid/BetaEisysApp | 47b4c0750500520dec0ab0168517a7184a33c983 | 3f608b72529fc141593a0f4676274ff5cfd6c910 | refs/heads/master | 2020-03-27T15:54:57.871729 | 2018-09-05T09:29:55 | 2018-09-05T09:29:55 | 146,747,229 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 719 | java | package hu.eisys.david.model;
import java.io.File;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Efile implements Step {
private String comment;
private String showElement;
private File file;
public Efile(String path, String showElement) {
this.file = new File(path);
this.showElement = showElement;
}
public Efile() {
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getComment() {
return comment;
}
@JsonIgnore
public StepNames getType() {
return StepNames.EFIEL;
}
public String getShowElement() {
return showElement;
}
}
| [
"[email protected]"
] | |
b49e874adecba6118053cf0bb38c03037b523472 | 564c4a932698f887a3f9ea5c21c32f6dae1ea024 | /app/src/main/java/cz/kennny/mobile/bombdefuser/FailedActivity.java | a83ec213bc78141745f91d3ffbde7f55cf4f736b | [] | no_license | MartinUbl/BombDefuseApp | 6b7e17b0e517f1158541304b143344e89f19c9fc | a18d1b3c568e04759e54dd567783bd0c419ccd78 | refs/heads/master | 2020-12-25T05:30:46.308985 | 2016-06-24T16:26:27 | 2016-06-24T16:26:27 | 61,387,294 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package cz.kennny.mobile.bombdefuser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class FailedActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_failed);
}
}
| [
"[email protected]"
] | |
a36ac9bb23040aca0a993fbb071d79d5f169929f | 5e7e6eceb20aa190a39b59c28abbe06c4278ba72 | /src/main/java/com/souche/springboot/config/KafkaConsumerConfig.java | 33386d4834c5ff2e96a6e35dd3ac0cd902102535 | [] | no_license | xiaomingmeng/springboot | ed65c09bc78c98b22680a9353c93bf604be63316 | c17ab44e77aab7aa73f094ed62a5e11ecb1b8594 | refs/heads/master | 2020-03-24T20:05:48.548982 | 2018-07-31T03:54:34 | 2018-07-31T03:54:34 | 142,959,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,431 | java | package com.souche.springboot.config;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import java.util.HashMap;
import java.util.Map;
/**
* 接收者配置类
*/
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
@Value("${souche.kafka.binder.brokers}")
private String brokers;
@Value("${souche.kafka.group}")
private String group;
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(4);
factory.getContainerProperties().setPollTimeout(4000);
return factory;
}
@Bean
public KafkaListeners kafkaListeners() {
return new KafkaListeners();
}
public ConsumerFactory<String, String> consumerFactory() {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
properties.put(ConsumerConfig.GROUP_ID_CONFIG, group);
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
return new DefaultKafkaConsumerFactory<String, String>(properties);
}
}
| [
"[email protected]"
] | |
a140144830ad9eb5799fe38564fbd7f991d4f3a7 | 0bb2834a85209d0e596aa31d3fb6f276a12a4300 | /lang/lucene/src/test/java/org/carrot2/language/extras/IrishLanguageComponentsTest.java | 4f5028cf981389ac30580fa130c848b3996ffaee | [
"Apache-2.0",
"LicenseRef-scancode-bsd-ack-carrot2",
"BSD-3-Clause"
] | permissive | carrot2/carrot2 | 201f7c59b529161a2aad5ce4be95ac5c06463268 | 623bab58c3e1781f1c56a857990b9e1a77df2f48 | refs/heads/master | 2023-07-24T19:03:16.853577 | 2023-05-08T20:00:25 | 2023-05-08T20:00:25 | 2,424,377 | 586 | 168 | null | 2023-07-19T09:03:37 | 2011-09-20T18:19:05 | Java | UTF-8 | Java | false | false | 707 | java | /*
* Carrot2 project.
*
* Copyright (C) 2002-2022, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* https://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.language.extras;
import java.io.IOException;
public class IrishLanguageComponentsTest extends AbstractLanguageComponentsTest {
public IrishLanguageComponentsTest() throws IOException {
super(
IrishLanguageComponents.NAME,
new String[] {"ceathrar", "seachtar"},
new String[][] {
{"siopadóireacht", "siopadóir"},
{"síceapatacha", "síceapaite"},
});
}
}
| [
"[email protected]"
] | |
1ce64d7740c60519c2e76e4b487e2cdbb173ed6b | 4ea5417ecd70f8c6757603ad463bd1abf394d358 | /org.sheepy.lily.openal.core/src/main/java/org/sheepy/lily/openal/core/resource/decoder/VorbisDecoder.java | b9090a7beed8ffb0d07dc8948a1f0bd424dd6a98 | [
"MIT"
] | permissive | Ealrann/Lily-Vulkan | 88fd02373ce7ca390ab3581faf10a7a8b799adea | 04c72b506a1db472b9f23dde25c4e1915480f122 | refs/heads/master | 2023-08-12T16:43:33.403548 | 2023-08-11T21:05:09 | 2023-08-11T21:05:09 | 141,837,401 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 803 | java | package org.sheepy.lily.openal.core.resource.decoder;
import org.lwjgl.system.MemoryStack;
import org.sheepy.lily.openal.core.resource.util.RawAudioBuffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.stb.STBVorbis.stb_vorbis_decode_memory;
public final class VorbisDecoder implements IDecoder
{
@Override
public RawAudioBuffer decode(MemoryStack stack, ByteBuffer encodedData)
{
final IntBuffer channelsBuffer = stack.mallocInt(1);
final IntBuffer sampleRateBuffer = stack.mallocInt(1);
final var rawAudioBuffer = stb_vorbis_decode_memory(encodedData, channelsBuffer, sampleRateBuffer);
final int channels = channelsBuffer.get();
final int sampleRate = sampleRateBuffer.get();
return new RawAudioBuffer(rawAudioBuffer, channels, sampleRate);
}
}
| [
"[email protected]"
] | |
e108d2107c903dec76e51cb0aedb7cb186903009 | f71b006309ee709e844a001cb0d73f0eb125b9e8 | /src/main/java/com/leosamblas/application/validator/ValidEnum.java | 67b8aa70d58294127318dd3402a933550b633e50 | [] | no_license | leosamblas/spring-boot-application | 051d775382ce0c5a27f3c074889ffcaa7372c35f | 4d7ac6e2dce1a1146d3282f718d4c70fb1c2a348 | refs/heads/main | 2023-06-25T16:01:52.256123 | 2021-07-19T00:53:26 | 2021-07-19T00:53:26 | 347,793,104 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 897 | java | package com.leosamblas.application.validator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { EnumValidator.class })
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
public @interface ValidEnum {
abstract String message() default "Campo fora do domínio";
abstract Class<?>[] groups() default {};
abstract Class<? extends Payload>[] payload() default {};
abstract Class<?> invokerClass();
abstract String method() default "getStatus";
abstract boolean ignoreCase() default false;
}
| [
"[email protected]"
] | |
3abd4934c933e6b26f658e762f61bba9c8810d91 | 9eb0140b0378ccfef8cba083cb4c7f51428c4a36 | /YPX_ImagePicker_androidx/imagepicker/src/main/java/com/ypx/imagepicker/activity/singlecrop/SingleCropActivity.java | 6ec872a5aff78ce4922505dd334f8ba5910876d5 | [] | no_license | JayGengi/YImagePicker | 365ef949ec617fadff85d570891e07b89a4a5c85 | 504bd8f47169c90fea26295f900567b21aa56629 | refs/heads/master | 2020-09-22T20:15:59.800189 | 2019-11-29T09:42:21 | 2019-11-29T09:42:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,998 | java | package com.ypx.imagepicker.activity.singlecrop;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.fragment.app.FragmentActivity;
import com.ypx.imagepicker.ImagePicker;
import com.ypx.imagepicker.R;
import com.ypx.imagepicker.activity.PickerActivityManager;
import com.ypx.imagepicker.bean.selectconfig.CropConfig;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.bean.MimeType;
import com.ypx.imagepicker.bean.PickerError;
import com.ypx.imagepicker.data.OnImagePickCompleteListener;
import com.ypx.imagepicker.data.PickerActivityCallBack;
import com.ypx.imagepicker.helper.PickerErrorExecutor;
import com.ypx.imagepicker.helper.launcher.PLauncher;
import com.ypx.imagepicker.presenter.IPickerPresenter;
import com.ypx.imagepicker.utils.PBitmapUtils;
import com.ypx.imagepicker.views.base.SingleCropControllerView;
import com.ypx.imagepicker.widget.cropimage.CropImageView;
import java.io.File;
import java.util.ArrayList;
import static com.ypx.imagepicker.activity.multi.MultiImagePickerActivity.INTENT_KEY_CURRENT_IMAGE;
import static com.ypx.imagepicker.activity.multi.MultiImagePickerActivity.INTENT_KEY_SELECT_CONFIG;
import static com.ypx.imagepicker.activity.multi.MultiImagePickerActivity.INTENT_KEY_PRESENTER;
/**
* Description: 图片剪裁页面
* <p>
* Author: peixing.yang
* Date: 2019/2/21
* 使用文档 :https://github.com/yangpeixing/YImagePicker/wiki/YImagePicker使用文档
*/
public class SingleCropActivity extends FragmentActivity {
private final String PNG = ".png";
private final String JPEG = ".jpg";
private CropImageView cropView;
private CropConfig cropConfig;
private IPickerPresenter presenter;
/**
* 跳转单图剪裁
*
* @param context 跳转的activity
* @param presenter IMultiPickerBindPresenter
* @param cropConfig 剪裁配置
* @param path 需要剪裁的图片的原始路径
* @param listener 剪裁回调
*/
public static void intentCrop(Activity context,
IPickerPresenter presenter,
CropConfig cropConfig,
String path,
final OnImagePickCompleteListener listener) {
Intent intent = new Intent(context, SingleCropActivity.class);
intent.putExtra(INTENT_KEY_PRESENTER, presenter);
intent.putExtra(INTENT_KEY_SELECT_CONFIG, cropConfig);
intent.putExtra(INTENT_KEY_CURRENT_IMAGE, path);
PLauncher.init(context).startActivityForResult(intent, PickerActivityCallBack.create(listener));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent() == null) {
PickerErrorExecutor.executeError(this, PickerError.PRESENTER_NOT_FOUND.getCode());
return;
}
presenter = (IPickerPresenter) getIntent().getSerializableExtra(INTENT_KEY_PRESENTER);
cropConfig = (CropConfig) getIntent().getSerializableExtra(INTENT_KEY_SELECT_CONFIG);
if (presenter == null) {
PickerErrorExecutor.executeError(this, PickerError.PRESENTER_NOT_FOUND.getCode());
return;
}
if (cropConfig == null) {
PickerErrorExecutor.executeError(this, PickerError.SELECT_CONFIG_NOT_FOUND.getCode());
return;
}
String url = getIntent().getStringExtra(INTENT_KEY_CURRENT_IMAGE);
if (url == null || url.trim().length() == 0) {
PickerErrorExecutor.executeError(this, PickerError.CROP_URL_NOT_FOUND.getCode());
return;
}
PickerActivityManager.addActivity(this);
setContentView(R.layout.picker_activity_crop);
cropView = findViewById(R.id.cropView);
cropView.setBackgroundColor(presenter.getUiConfig(this).getCropViewBackgroundColor());
cropView.setMaxScale(7.0f);
cropView.setRotateEnable(false);
cropView.enable();
cropView.setScaleType(ImageView.ScaleType.CENTER_CROP);
cropView.setBounceEnable(!cropConfig.isGap());
cropView.setCropMargin(cropConfig.getCropRectMargin());
if (!cropConfig.isCircle()) {
cropView.setCropRatio(cropConfig.getCropRatioX(), cropConfig.getCropRatioY());
} else {
cropView.setCropRatio(1, 1);
}
cropView.setCircle(cropConfig.isCircle());
ImageItem imageItem = new ImageItem();
imageItem.path = url;
presenter.displayImage(cropView, imageItem, 0, false);
setControllerView();
}
private void setControllerView() {
FrameLayout mCropPanel = findViewById(R.id.mCropPanel);
SingleCropControllerView cropControllerView = presenter.getUiConfig(this)
.getPickerUiProvider()
.getSingleCropControllerView(this);
mCropPanel.addView(cropControllerView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
cropControllerView.setStatusBar();
cropControllerView.setCropViewParams(cropView, (ViewGroup.MarginLayoutParams) cropView.getLayoutParams());
cropControllerView.getCompleteView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cropComplete();
}
});
}
private void cropComplete() {
if (cropView.isEditing()) {
return;
}
String cropUrl = generateCropFile("crop_" + System.currentTimeMillis());
if (cropUrl.startsWith("Exception:")) {
PickerError.CROP_EXCEPTION.setMessage(cropUrl);
PickerErrorExecutor.executeError(SingleCropActivity.this, PickerError.CROP_EXCEPTION.getCode());
return;
}
ImageItem item = new ImageItem();
item.path = cropUrl;
if (cropUrl.endsWith(PNG)) {
item.mimeType = MimeType.JPEG.toString();
} else {
item.mimeType = MimeType.PNG.toString();
}
item.width = cropView.getCropWidth();
item.height = cropView.getCropHeight();
ArrayList<ImageItem> list = new ArrayList<>();
list.add(item);
if (presenter.interceptPickerCompleteClick(SingleCropActivity.this, list, cropConfig)) {
return;
}
notifyOnImagePickComplete(list);
}
public String generateCropFile(String fileName) {
String cropUrl;
Bitmap bitmap;
if (cropConfig.isGap()) {
bitmap = cropView.generateCropBitmapFromView(cropConfig.getCropGapBackgroundColor());
} else {
bitmap = cropView.generateCropBitmap();
}
Bitmap.CompressFormat format = cropConfig.isNeedPng() ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
if (cropConfig.isSaveInDCIM()) {
cropUrl = PBitmapUtils.saveBitmapToDICM(this, bitmap, fileName, format).toString();
} else {
cropUrl = PBitmapUtils.saveBitmapToFile(this, bitmap, fileName, format);
}
return cropUrl;
}
private void notifyOnImagePickComplete(ArrayList<ImageItem> list) {
Intent intent = new Intent();
intent.putExtra(ImagePicker.INTENT_KEY_PICKER_RESULT, list);
setResult(ImagePicker.REQ_PICKER_RESULT_CODE, intent);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
PickerActivityManager.removeActivity(this);
}
}
| [
"[email protected]"
] | |
67af640da25796149019ea760cf3c22cecc8dcae | 46b1970bd103fdab3e39e89cdd2ff1e698542205 | /src/dao/DAO.java | 3fd740abf38c716f362b8d4f97e15c983916e7ac | [] | no_license | shabalindm/warehouse | ededd21c96b46085eb4870659bcb5d0bc7a76f44 | 14833a26e4ac53a6a8912c74750e1dd6c87b9c03 | refs/heads/master | 2021-01-10T19:05:51.893125 | 2014-07-04T11:03:56 | 2014-07-04T11:03:56 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 13,412 | java | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class DAO {
private Connection conn;
private String tableName;
//private String tablePK; // Имя первичного ключа
private Integer PKPlace = null; // позиция первичного ключа c массиве с именами строк
private String[] columnNames; // Имена всех столбцов в таблице
private Class[] columnClasses;
public String getTablePK() {
return columnNames[PKPlace];
}
public Class[] getColumnClasses() {
return columnClasses;
}
public String[] getColumnNames() {
return columnNames;
}
public String getTableName() {
return tableName;
}
public Connection getConnection() {
return conn;
}
private String sqlInsert; //1
private String sqlUpdate; //2
private String sqlUpdateByRowId; //3
private String sqlSearchById; //4
private String sqlSearchByRowId;//5
private String sqlDelete; //6
private String sqlDeleteByRowId;//7
private String sqlChangeID; //8
private PreparedStatement pstmInsert = null;
private PreparedStatement pstmUpdate = null;
private PreparedStatement pstmUpdateByRowId = null;
private PreparedStatement pstmSearchById = null;
private PreparedStatement pstmSearchByRowId = null;
private PreparedStatement pstmDelete = null;
private PreparedStatement pstmDeleteByRowId = null;
private PreparedStatement pstmChangeID = null;
private Statement stmt;
public DAO(Connection conn, String tableName, String PKName) throws SQLException {
this.conn = conn;
this.tableName = tableName;
// Узнаем имена столбцов и типы столбцов, выполнив пробный запрос
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from " +tableName + " where 1<>1");
try{
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from " + tableName + " where 1<>1");
ResultSetMetaData metaData = rs.getMetaData();
columnNames = new String [metaData.getColumnCount()];
columnClasses = new Class[metaData.getColumnCount()];
for(int i = 0; i < columnNames.length; i++){
columnNames[i] = metaData.getColumnName(i+1);
if (columnNames[i].equalsIgnoreCase(PKName))
PKPlace = i;
try {
columnClasses[i] = Class.forName(metaData.getColumnClassName(i+1));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
finally { rs.close();}
//Собираем строчки для sql-запросов и подготавливем их
String [] colls = columnNames;
//1. Подготовка sqlInsert;
sqlInsert = "INSERT INTO " + tableName + " (";
for(int i = 1; i < colls.length; i ++)
sqlInsert += colls[i]+ ", ";
sqlInsert += colls[0] + ") ";
sqlInsert += " VALUES (";
for(int i = 1; i < colls.length; i ++)
sqlInsert += "?, ";
sqlInsert+="?)";
pstmInsert = conn.prepareStatement(sqlInsert);
//2 подготовка sqlUpdate
if (PKPlace != null){
sqlUpdate = "UPDATE " + tableName + " SET ";
for(int i = 0; i<colls.length; i++){
if (i == PKPlace.intValue())
continue;
sqlUpdate += colls[i] + " = ?, ";
}
sqlUpdate = sqlUpdate.substring(0, sqlUpdate.length()-2); // удаляем лишнюю запятую
sqlUpdate += " WHERE " + colls[PKPlace] + " = ?";
pstmUpdate = conn.prepareStatement(sqlUpdate);
}
//3 подготовка sqlUpdateByRowId
sqlUpdateByRowId = "UPDATE " + tableName + " SET ";
for(int i = 0; i<colls.length; i++)
sqlUpdateByRowId += colls[i] + " = ?, ";
sqlUpdateByRowId = sqlUpdateByRowId.substring(0, sqlUpdateByRowId.length()-2); // удаляем лишнюю запятую
sqlUpdateByRowId += " WHERE ROWID = ?";
pstmUpdateByRowId = conn.prepareStatement(sqlUpdateByRowId);
//4 подготовка sqlSearchById
if (PKPlace != null){
sqlSearchById = "SELECT ";
for(int i = 0; i<colls.length; i++)
sqlSearchById += colls[i]+ ", ";
sqlSearchById += " ROWID ";
sqlSearchById += " FROM " + tableName + " WHERE " + colls[PKPlace] + " = ?";
pstmSearchById = conn.prepareStatement(sqlSearchById);
}
//5 подготовка sqlSearchByRowId
sqlSearchByRowId = "SELECT ";
for(int i = 0; i<colls.length; i++)
sqlSearchByRowId += colls[i]+ ", ";
sqlSearchByRowId += " ROWID ";
sqlSearchByRowId += " FROM " + tableName + " WHERE ROWID = ?";
pstmSearchByRowId = conn.prepareStatement(sqlSearchByRowId);
//6 подготовка sqlDelete
if (PKPlace != null){
sqlDelete = "DELETE FROM " + tableName + " WHERE " + colls[PKPlace] + " = ?";
pstmDelete = conn.prepareStatement(sqlDelete);
}
//7 подготовка sqlDeleteByRowID
sqlDeleteByRowId = "DELETE FROM " + tableName + " WHERE ROWID = ?";
pstmDeleteByRowId = conn.prepareStatement(sqlDeleteByRowId);
// 8 подготовка sqlChangeID
if (PKPlace != null){
sqlChangeID = "UPDATE " + tableName + " SET " + colls[PKPlace] +" = ? " + " WHERE " + colls[PKPlace] + " = ? ";
pstmChangeID = conn.prepareStatement(sqlChangeID);
}
stmt = conn.createStatement();
System.out.println("sqlInsert " + sqlInsert);
System.out.println("sqlUpdate " + sqlUpdate);
System.out.println("sqlUpdateByRowId " +sqlUpdateByRowId);
System.out.println("sqlSearchById " + sqlSearchById);
System.out.println("sqlSearchByRowId " + sqlSearchByRowId);
System.out.println("sqlDelete " + sqlDelete);
System.out.println("sqlDeleteByRowId " + sqlDeleteByRowId);
System.out.println("sqlChangeID " + sqlChangeID);
}
/** Ищет по значению ID поле запись в базе данных и выдает новый объект item, поля которого заполнены значениями из этой записи */
public Item searchById(Object id) throws SQLException {
Item result = null;
pstmSearchById.setObject(1, id);
ResultSet rs = null;
try{
rs = pstmSearchById.executeQuery();
if (rs.next()){
result = new Item(columnNames.length, PKPlace);
result.pollFieldsFromRSRowID(rs, columnNames, "ROWID" );
}
return result;
}
finally{rs.close();}
}
/** Ищет по значению ROWID поле запись в базе данных и выдает новый объект item, поля которого заполнены значениями из этой записи */
public Item searchByRowId(String rowid) throws SQLException {
Item result = null;
pstmSearchByRowId.setObject(1, rowid);
ResultSet rs = null;
try{
rs = pstmSearchByRowId.executeQuery();
if (rs.next()){
result = new Item(columnNames.length, PKPlace);
result.pollFieldsFromRSRowID(rs, columnNames, "ROWID");
}
return result;
}
finally{rs.close();}
}
/** Обновляет значения полей объекта item, беря их из базы данных. Возвращает true если обновление прошло успешно */
public boolean refresh(Item item) throws SQLException {
pstmSearchById.setObject(1, item.getId());
ResultSet rs = null;
try{
rs = pstmSearchById.executeQuery();
if (rs.next()){
item.pollFieldsFromRSRowID(rs, columnNames, "ROWID");
return true;
}
return false;
}
finally{rs.close();}
}
/** Обновляет значения полей объекта item, беря их из базы данных по rowId. Возвращает true, если обновление прошло успешно */
public boolean refreshByRowID(Item item) throws SQLException {
pstmSearchByRowId.setObject(1, item.getRowId());
ResultSet rs = null;
try{
rs = pstmSearchByRowId.executeQuery();
if (rs.next()){
item.pollFieldsFromRSRowID(rs, columnNames, "ROWID");
return true;
}
return false;
}
finally{rs.close();}
}
/** Находит по ID запись в базе удалеет ее. Если не удается - возвращает false*/
public boolean delete(Item item) throws SQLException{
pstmDelete.setObject(1, item.getId());
if (pstmDelete.executeUpdate() != 0)
return true;
return false;
}
/**Находит по RowID запись в базе и удаляет ее. Если не удается - возвращает false*/
public boolean deleteByRowId(Item item) throws SQLException{
pstmDeleteByRowId.setObject(1, item.getRowId());
if (pstmDeleteByRowId.executeUpdate() != 0)
return true;
return false;
}
/**Записывает значения полей item в базу данных в виде новой строчки. Сохраняет значения из Item как есть в т.ч и null-значения,
*Вообще-то не нужен, метод storeNew2 лучше работает с null -значениями, хоть медленнее*/
public void storeNew(Item item) throws SQLException{
for (int i = 0; i < columnNames.length ; i++) {
pstmInsert.setObject(i, item.getVal(i));
}
pstmInsert.setObject(columnNames.length, item.getVal(0));
pstmInsert.executeUpdate();
}
/**Записывает значения полей item в базу данных в виде новой строчки, но при этом те поля, которые равны null пропускает.
* Для этого каждый раз собирается PreparedStatement*/
public void storeNew2(Item item ) throws SQLException{
// Собираем номера тех столбцов, которые не пусты
List<Integer> notEmptycols = new ArrayList<>();
for(int i = 0; i < columnNames.length; i ++){
Object val = item.getVal(i);
if(val != null && !(val instanceof String && ((String)val).matches("\\s*")))
notEmptycols.add(i);
}
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO " + tableName + " (");
for (int i : notEmptycols){
sql.append(columnNames[i] );
sql.append(", ");
}
sql.delete(sql.length()-2 , sql.length());
sql.append( ") VALUES ( ");
for (int i : notEmptycols)
sql.append("?, " );
sql.delete(sql.length()-2 , sql.length());
sql.append(")");
System.out.println(sql);
PreparedStatement pstm = null;
try{
pstm = conn.prepareStatement(sql.toString());
int k =0;
for (int i : notEmptycols){
Object val = item.getVal(i);
System.out.println( (k+1) + val.toString());
pstm.setObject(k+1, val);
k++;
}
pstm.executeUpdate();
} finally {pstm.close();}
}
/**Находит по значению iD запись в базе данных и переписывает в нее значения полей из item */
public int store(Item item) throws SQLException
{
for (int i = 0, j = 0; i < columnNames.length ; i++){
if(i == PKPlace.intValue())
continue;
pstmUpdate.setObject(j+1, item.getVal(i));
j++;
}
pstmUpdate.setObject(columnNames.length , item.getId());
return pstmUpdate.executeUpdate();
}
/**Находит по значению rowiD запись в базе данных и переписывает в нее значения полей из item */
public int storebyRowId(Item item) throws SQLException
{
for (int i = 0; i < columnNames.length ; i++) {
pstmUpdateByRowId.setObject(i+1, item.getVal(i));
}
pstmUpdateByRowId.setString(columnNames.length+1, item.getRowId());
return pstmUpdateByRowId.executeUpdate();
}
/**Меняет Id записи в базе */
public int changeID(Object oldID , Object newID ) throws SQLException
{
pstmChangeID.setObject(1, newID );
pstmChangeID.setObject(2, oldID );
return pstmChangeID.executeUpdate();
}
public Item getEmptyItem(){
Item item = new Item(columnNames.length, PKPlace);
item.dao = this;
return item;
}
public int getFieldIndex(String name){
for (int i = 0 ; i < columnNames.length; i++){
if (columnNames[i].equals(name))
return i;
}
throw new RuntimeException(" Не найден столбец " + name);
}
public void close() {
try
{
if (pstmInsert != null) pstmInsert.close();
if (pstmUpdate != null) pstmUpdate.close();
if (pstmUpdateByRowId != null) pstmUpdateByRowId.close();
if (pstmSearchById != null) pstmSearchById.close();
if (pstmSearchByRowId != null) pstmSearchByRowId.close();
if (pstmDelete != null) pstmDelete.close();
if (pstmDeleteByRowId != null) pstmDeleteByRowId.close();
if (pstmChangeID != null) pstmChangeID.close();
if (stmt != null) stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
0016480774c74f95d84d535d1ab69c42daa102dd | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/elastic--elasticsearch/5bea31cb96ded0308408788deefbf57abc036ccf/before/RestRestoreSnapshotAction.java | db8c1a03cb38388f970d7e1dd3a93cd138704a69 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,609 | java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.rest.action.admin.cluster.snapshots.restore;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.client.Requests.restoreSnapshotRequest;
import static org.elasticsearch.rest.RestRequest.Method.POST;
/**
* Restores a snapshot
*/
public class RestRestoreSnapshotAction extends BaseRestHandler {
@Inject
public RestRestoreSnapshotAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(POST, "/_snapshot/{repository}/{snapshot}/_restore", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
RestoreSnapshotRequest restoreSnapshotRequest = restoreSnapshotRequest(request.param("repository"), request.param("snapshot"));
restoreSnapshotRequest.masterNodeTimeout(request.paramAsTime("master_timeout", restoreSnapshotRequest.masterNodeTimeout()));
restoreSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false));
restoreSnapshotRequest.source(request.content().toUtf8());
client.admin().cluster().restoreSnapshot(restoreSnapshotRequest, new RestToXContentListener<RestoreSnapshotResponse>(channel));
}
} | [
"[email protected]"
] | |
494269cac4fbbcad906cc70fd2c25404d5c8af31 | e114ab03fcda58897f522dc8603365d50b098131 | /japs/java/src/net/mumie/cocoon/xml/SAXFilter.java | dab50b9925a961a6759bfdbd9506a70203bddde8 | [
"MIT"
] | permissive | TU-Berlin/Mumie | 07ff6ed89cae043f0a942fa1b32916b0a319a7d0 | 322f6772f5bf1ce42fc00d0c6f8c3eba27ecc010 | refs/heads/master | 2016-08-12T11:33:53.553539 | 2016-01-13T11:01:20 | 2016-01-13T11:01:20 | 49,567,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,477 | java | /*
* The MIT License (MIT)
*
* Copyright (c) 2010 Technische Universitaet Berlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.mumie.cocoon.xml;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* A component (in the sence of Avalon) that recieves SAX events as input and sends SAX
* events as output. Extends {@link org.xml.sax.ContentHandler} to be able to act as a SAX
* event reciever. Sends the output SAX events to another {@link org.xml.sax.ContentHandler}.
*
* @author Tilman Rassy
*
* @version <span class="file">$Id: SAXFilter.java,v 1.6 2007/07/11 15:38:54 grudzin Exp $</span>
*/
public interface SAXFilter extends ContentHandler
{
/**
* Role of an implementing class as an Avalon component. Value is
* <span class="string">"net.mumie.cocoon.xml.SAXFilter"</span>.
*/
String ROLE = "net.mumie.cocoon.xml.SAXFilter";
/**
* Sets the content handler to which to send the output SAX events.
*/
public void setContentHandler (ContentHandler handler);
/**
* Enables or disables namespace adding.
*/
public void setNamespaceAdding (boolean namespaceAddingEnabled)
throws SAXException;
/**
* Returns whether namespace adding is in effect or not.
*/
public boolean getNamespaceAdding ();
/**
* Sets the namespace URI and prefix.
*/
public void setNamespace (String namespaceURI, String namespacePrefix);
}
| [
"[email protected]"
] | |
923d27f36cb7a724c2d297c40e4a6062f59c4c27 | d8c92d5b6527b2139ebc2599f2a6fca875e80909 | /BubbleSort.java | 6bfdda6bf42c0571a362e285111252c90eb9dd46 | [] | no_license | averydl/sorting-comparison | bd8d27c78c49f04469900e2bab36f070bb32e684 | a132d8f82ae238e64194ce0f32d5bd56604e3768 | refs/heads/master | 2020-05-21T12:49:44.267280 | 2019-06-03T21:44:18 | 2019-06-03T21:44:18 | 186,051,066 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 742 | java | public class BubbleSort implements Sort {
private Comparable[] arr;
public BubbleSort(Comparable[] arr) {
this.arr = arr;
}
/*
* implements sort using
* the bubble sort algorithm
*/
@Override
public void sort() {
boolean swap = true;
// swap any unordered adjacent elements until all elements are ordered
while (swap == true) {
swap = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
swap = true;
swap(arr, i, i + 1);
}
}
}
}
@Override
public String toString() {
return "Bubble Sort";
}
}
| [
"[email protected]"
] | |
4675998ab9d5157e94bc6a2f337617baf1f1dee7 | a9c1b007c8530bf3caab3aceb7437b0d8fc9da8d | /wizardDetective/src/byui/cit260/detectiveWizard/view/StartProgramView.java | 45308c691cb10d8aef401f5962165db5b28e70db | [] | no_license | lauryncosette/wizard | 4981102701642c3c6b24e4d899018e8efcc6c05d | 884f4e8cb8bdad6d3e633230bd82a94a821ce947 | refs/heads/master | 2021-03-12T22:39:30.744249 | 2015-04-09T15:09:20 | 2015-04-09T15:09:20 | 29,870,295 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,068 | java | package byui.cit260.detectiveWizard.view;
import byui.cit260.detectiveWizard.control.ProgramControl;
import byui.cit260.detectiveWizard.model.Player;
import detectiveWizard.DetectiveWizard;
import java.io.BufferedReader;
import java.io.PrintWriter;
public class StartProgramView extends View {
public StartProgramView() {
super("");
}
// protected final BufferedReader keyboard = DetectiveWizard.getInFile();
// protected final PrintWriter console = DetectiveWizard.getOutFile();
public void startProgram() {
// System.out.println("test2");
//Display the banner screen - tested/passed
this.displayBanner();
//prompt the player to enter their name, retrieve the name of the player - tested/passed
String playersName = this.getPlayersName();
//create and save the player object - tested/passed
Player player = ProgramControl.createPlayer(playersName);
//display a personalized welcome message
this.displayWelcomeMessage(player);
//display the main menu
MainMenuView mainMenu = new MainMenuView();
mainMenu.display();
}
public void displayBanner() {
// System.out.println("test");
this.console.println("\n\n*******************************************");
this.console.println("* *"
+ "\n* This is the game of Wizard Detective. *"
+ "\n* In this game you are a detective by day *"
+ "\n* and a wizard by night. One night you *"
+ "\n* were called into work to investigate a *"
+ "\n* murder. The poor victim is a local *"
+ "\n* rich boy who was staying at the best *"
+ "\n* hotel in town. The bellboy was the one *"
+ "\n* who found the body. *");
this.console.println("* *"
+ "\n* Frustratingly, there were no witnesses, *"
+ "\n* but the night staff at the hotel has *"
+ "\n* been asked to stay for you to question. *"
+ "\n* The chief would like to keep this quiet *"
+ "\n* until the morning so the other visitors *"
+ "\n* at the hotel have been kept in the *"
+ "\n* dark. The hotel's exits are being *"
+ "\n* watched - no one has entered or left *"
+ "\n* the building. It is up to you and your *"
+ "\n* partner, Tim, to find the killer. *");
this.console.println("* *"
+ "\n* You must be able to search each room to *"
+ "\n* find clues without arousing the *"
+ "\n* suspicion of the killer or any of the *"
+ "\n* other guests. Witnesses will be *"
+ "\n* waiting in each room for you to talk to *"
+ "\n* and to gain information from. *"
+ "\n* *"
+ "\n*******************************************");
}
public String getPlayersName() {
//indicates if the name has been retrieved
boolean valid = false;
String playersName = null;
try {
//while a valid name has not been retrieved
while (!valid) {
//prompt for the player's name
this.console.println("Enter the player's name below:");
//get the name from the keyboard and trim of the blanks
playersName = this.keyboard.readLine();
playersName = playersName.trim();
//if the name is invalid (less than two character in length)
if (playersName.length() < 2) {
this.console.println("Invalid name = the name must not be blank");
//and repeat again
continue;
}
//exit the repetition
break;
}
} catch (Exception e) {
ErrorView.display(this.getClass().getName(), "Error reading input: " + e.getMessage());
}
//return the name
return playersName;
}
private void displayWelcomeMessage(Player player) {
this.console.println("\n\n============================================");
this.console.println("\tWelcome to the game " + player.getName());
this.console.println("\tWe hope you have a lot of fun!");
this.console.println("============================================");
}
@Override
public void doAction(String Value) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| [
"Cassandra@VanLydegraf"
] | Cassandra@VanLydegraf |
50cd1b693f34dca2927060a21c9306d6844a5ac7 | 7a056cde5712425956064d576084ce5d69644a23 | /studio/src/runner/TestRunner.java | bca09286a7921fccea43c630b312cf9d22ab1b0d | [] | no_license | krishnayadava/java-project | 3103d6e8492ce54d2d5f5b8a29794fd4275a09d5 | f1b494a95aadb70368945a0adff4fdec25c31cb2 | refs/heads/master | 2022-07-10T21:08:11.213895 | 2019-06-17T13:12:28 | 2019-06-17T13:12:28 | 76,626,758 | 0 | 0 | null | 2022-06-29T17:26:48 | 2016-12-16T06:08:54 | JavaScript | UTF-8 | Java | false | false | 745 | java | package runner;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/studio/7_Digits_input.feature",
glue= {"stepDefinitions"}
)
public class TestRunner {
/* private TestNGCucumberRunner testNGCucumberRunner;
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
@Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
*/
}
| [
"[email protected]"
] | |
ecabf59674060dcb79bfd8f280ee9d5d90b0ee9d | 08831c5a0ee84e2b811daa58e83bdc0692a85c8c | /app/src/main/java/database/google/com/denguespot/history_Mode.java | 5c910462b389870ad95f3acbbb017dff82bacd3c | [] | no_license | Rayhanshuvo/DengueSpot | 09ff4488fe1fbfd49dec0f6f91981baa0a89ad22 | 789f37dd699fa6378879febda3237bc60292c055 | refs/heads/master | 2021-07-08T08:09:10.947631 | 2017-10-05T17:02:16 | 2017-10-05T17:02:16 | 105,916,983 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,317 | java | package database.google.com.denguespot;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class history_Mode extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String json_string;
String fund,fund2;
String datee="k";
String latitudee="a",longg="b",addd="d";
double a,b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dengue_case);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
json_string = getIntent().getExtras().getString("json_data");
fund= (String) getIntent().getExtras().get("ok");
fund2=fund.toLowerCase();
fund2 = fund2.replaceAll("\\s+", "");
try {
JSONObject parentobject = new JSONObject(json_string);
JSONArray parentarray = parentobject.getJSONArray("server_response");
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
latitudee = finalobject.getString("latitude");
longg = finalobject.getString("longitude");
addd = finalobject.getString("address");
datee=finalobject.getString("date");
a = Double.parseDouble(latitudee);//Crash problem solved
b = Double.parseDouble(longg);
if (addd.length() <= 1) {
addd = addd.toLowerCase();}
else {
addd =addd.toLowerCase();
addd = addd.replaceAll("\\s+", "");
if((addd.contains(fund2)))
{
LatLng sydney = new LatLng(a, b);
mMap.addMarker(new MarkerOptions().position(sydney).title(datee));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}}}} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
a5c6c66461e17817a9901fb1b9074d85338976af | 5bd7eb364cc4c4465f827dfc4c8067bb66bba167 | /src/test/java/br/com/alura/challenge/backend/repository/UsuarioRepositoryTest.java | 037a6bfe6e1ff27c5225d951f15ff8890084fa95 | [] | no_license | felipefriserio/AluraChallenge2 | 9e23688af2fb1fb39b6b6db28e8069165204be26 | e5e3fc282232bde7bc7825f1e465b9745c721eed | refs/heads/main | 2023-07-05T01:31:54.930289 | 2021-08-23T00:27:19 | 2021-08-23T00:27:19 | 388,266,914 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,679 | java | package br.com.alura.challenge.backend.repository;
import br.com.alura.challenge.backend.entity.Usuario;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("test")
public class UsuarioRepositoryTest {
@Autowired
private UsuarioRepository repository;
@Autowired
private TestEntityManager em;
@Test
void deveriaBuscarUsuarioPeloEmail() {
String nome = "Jose da Silva";
String email = "[email protected]";
String senha = "123456";
Usuario usuario = new Usuario(nome, email, senha);
em.persist(usuario);
Optional<Usuario> usuarioOptional = repository.findByEmail(email);
assertNotNull(usuarioOptional);
assertEquals(usuarioOptional.get().getEmail(), email);
}
@Test
void naoDeveriaBuscarUsuarioInexistentePeloEmail() {
String email = "[email protected]";
Optional<Usuario> usuarioOptional = repository.findByEmail(email);
assertFalse(usuarioOptional.isPresent());
}
}
| [
"%RMPkx578OMIi$2"
] | %RMPkx578OMIi$2 |
6cffd72208b5192e662394edfbf4691bb7580f9f | 489e44a7187c0963acce47cbaef3b3bd5e02ccc9 | /src/main/java/com/exam/entities/exam/Category.java | ed204a15dc5296a6c30c07bbd8106688643e3e66 | [] | no_license | Kingsrv/examserver | 6c59b2b06ac63246eabe4b90a24d43a41736552c | 0bd61a160eb584eab9d07ceb86efda42032badf7 | refs/heads/master | 2023-06-24T18:07:16.780474 | 2021-07-23T17:31:36 | 2021-07-23T17:31:36 | 388,878,135 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,070 | java | package com.exam.entities.exam;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.LinkedHashSet;
import java.util.Set;
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long cid;
private String title;
private String description;
@OneToMany(mappedBy = "category",cascade = CascadeType.ALL)
@JsonIgnore
private Set<Quiz> quizzes = new LinkedHashSet<>();
public Category() {
}
public Category(String title, String description) {
this.title = title;
this.description = description;
}
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| [
"[email protected]"
] | |
466ea8c720403c5d7c90a06fe46604e4431f4bc4 | cd8793e4c4a73cf4b5724a94c843af7bc480f64d | /src/test/java/com/mycompany/myapp/service/MailServiceIT.java | c9c2de71067d8882ce9c797178654c2968e9189f | [] | no_license | pcoloigner/jhipsterv2 | 2c9cb6dfba72a4fbb0eb2a65aa98b803602bf2e1 | edc0bbb4398d52b15d93704f2167800c249d51c3 | refs/heads/main | 2023-03-11T00:53:08.194668 | 2021-02-24T23:05:48 | 2021-02-24T23:05:48 | 342,060,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,620 | java | package com.mycompany.myapp.service;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.mycompany.myapp.Jhipsterv2App;
import com.mycompany.myapp.config.Constants;
import com.mycompany.myapp.domain.User;
import io.github.jhipster.config.JHipsterProperties;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.thymeleaf.spring5.SpringTemplateEngine;
/**
* Integration tests for {@link MailService}.
*/
@SpringBootTest(classes = Jhipsterv2App.class)
public class MailServiceIT {
private static final String[] languages = {
// jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array
};
private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})");
private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})");
@Autowired
private JHipsterProperties jHipsterProperties;
@Autowired
private MessageSource messageSource;
@Autowired
private SpringTemplateEngine templateEngine;
@Spy
private JavaMailSenderImpl javaMailSender;
@Captor
private ArgumentCaptor<MimeMessage> messageCaptor;
private MailService mailService;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(javaMailSender).send(any(MimeMessage.class));
mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine);
}
@Test
public void testSendEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", false, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent().toString()).isEqualTo("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
public void testSendHtmlEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", false, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent().toString()).isEqualTo("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
public void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendEmailFromTemplate() throws Exception {
User user = new User();
user.setLogin("john");
user.setEmail("[email protected]");
user.setLangKey("en");
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("test title");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendActivationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("[email protected]");
mailService.sendActivationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testCreationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("[email protected]");
mailService.sendCreationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendPasswordResetMail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("[email protected]");
mailService.sendPasswordResetMail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendEmailWithException() {
doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
try {
mailService.sendEmail("[email protected]", "testSubject", "testContent", false, false);
} catch (Exception e) {
fail("Exception shouldn't have been thrown");
}
}
@Test
public void testSendLocalizedEmailForAllSupportedLanguages() throws Exception {
User user = new User();
user.setLogin("john");
user.setEmail("[email protected]");
for (String langKey : languages) {
user.setLangKey(langKey);
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
String propertyFilePath = "i18n/messages_" + getJavaLocale(langKey) + ".properties";
URL resource = this.getClass().getClassLoader().getResource(propertyFilePath);
File file = new File(new URI(resource.getFile()).getPath());
Properties properties = new Properties();
properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")));
String emailTitle = (String) properties.get("email.test.title");
assertThat(message.getSubject()).isEqualTo(emailTitle);
assertThat(message.getContent().toString())
.isEqualToNormalizingNewlines("<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n");
}
}
/**
* Convert a lang key to the Java locale.
*/
private String getJavaLocale(String langKey) {
String javaLangKey = langKey;
Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey);
if (matcher2.matches()) {
javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase();
}
Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey);
if (matcher3.matches()) {
javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase();
}
return javaLangKey;
}
}
| [
"[email protected]"
] | |
3a839ac6be0a80422dd5acb1d9e3beba013bc0c8 | 32cd70512c7a661aeefee440586339211fbc9efd | /aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/transform/RulesPackageJsonMarshaller.java | 7ea9c2454e54e8809f5b9a4e05f1cf4ae1bd99d4 | [
"Apache-2.0"
] | permissive | twigkit/aws-sdk-java | 7409d949ce0b0fbd061e787a5b39a93db7247d3d | 0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be | refs/heads/master | 2020-04-03T16:40:16.625651 | 2018-05-04T12:05:14 | 2018-05-04T12:05:14 | 60,255,938 | 0 | 1 | Apache-2.0 | 2018-05-04T12:48:26 | 2016-06-02T10:40:53 | Java | UTF-8 | Java | false | false | 2,917 | java | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.inspector.model.transform;
import java.util.Map;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.inspector.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;
/**
* RulesPackageMarshaller
*/
public class RulesPackageJsonMarshaller {
/**
* Marshall the given parameter object, and output to a SdkJsonGenerator
*/
public void marshall(RulesPackage rulesPackage,
StructuredJsonGenerator jsonGenerator) {
if (rulesPackage == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
try {
jsonGenerator.writeStartObject();
if (rulesPackage.getArn() != null) {
jsonGenerator.writeFieldName("arn").writeValue(
rulesPackage.getArn());
}
if (rulesPackage.getName() != null) {
jsonGenerator.writeFieldName("name").writeValue(
rulesPackage.getName());
}
if (rulesPackage.getVersion() != null) {
jsonGenerator.writeFieldName("version").writeValue(
rulesPackage.getVersion());
}
if (rulesPackage.getProvider() != null) {
jsonGenerator.writeFieldName("provider").writeValue(
rulesPackage.getProvider());
}
if (rulesPackage.getDescription() != null) {
jsonGenerator.writeFieldName("description").writeValue(
rulesPackage.getDescription());
}
jsonGenerator.writeEndObject();
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static RulesPackageJsonMarshaller instance;
public static RulesPackageJsonMarshaller getInstance() {
if (instance == null)
instance = new RulesPackageJsonMarshaller();
return instance;
}
}
| [
"[email protected]"
] | |
eb226063f3e88454e4dc1a4f51866c403b43777e | b844208f6be28c9dd29321ea62c0742361b6b6ee | /src/util/GsonHelp.java | 4b9cbf8e7defb4571b58dac8e7c059f47c384380 | [] | no_license | tanglonghui/Retrofit2Server | d3cd65d7403e18bedea0d781ef12b24fe0640dc3 | a65e9bd3ed00681d51124793944fc20715e7a7f8 | refs/heads/master | 2020-03-28T13:34:27.035334 | 2018-09-12T02:07:41 | 2018-09-12T02:07:41 | 148,406,691 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 180 | java | package util;
import com.google.gson.Gson;
public class GsonHelp {
private static Gson gson=new Gson();
private GsonHelp() {
}
public static Gson getGson(){
return gson;
}
}
| [
"[email protected]"
] | |
b241e195bcf6f4a14c846160e01a301f65f8adb6 | 7d71026b19c21dcdcd90803780ae6a4c8151b5b6 | /databridge/src/main/java/com/advantech/apphub/databridge/constants/DataBridgeError.java | 17f3ea1aeed8b88e3167029021f86229c6036f33 | [] | no_license | EdgeSolution/ApphubDataBridge | 0cbaa7547fd001c2cdc153638ee35a2b0bd7529a | 2d7a053427b0d853649262e42df10e3dbfc93b88 | refs/heads/main | 2023-07-17T18:19:35.963892 | 2021-09-03T05:10:04 | 2021-09-03T05:10:04 | 401,551,818 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,399 | java | package com.advantech.apphub.databridge.constants;
/**
* ClassName: DataBridgeError
* Description: Some common error codes are defined, and users can add their own error codes on this basis
* CreateDate 2021/08/26
* Author: [email protected]
*/
public class DataBridgeError {
public static final int DATABRIDGE_ERR_NO_ERROR = 0;
public static final int DATABRIDGE_ERR_UNKNOWN_ERROR = 1;
public static final int DATABRIDGE_ERR_OPERATION_NOT_ALLOWED = 2;
public static final int DATABRIDGE_ERR_UNKNOWN_FUNCID = 3;
public static final int DATABRIDGE_ERR_PARAMETER_ERROR = 4;
public static final int DATABRIDGE_ERR_SERVICE_NULL_POINTER = 100;
public static final int DATABRIDGE_ERR_SERVICE_UNKNWON_EXCEPTION = 101;
public static final int DATABRIDGE_ERR_SERVICE_REMOTE_CALLBACK_LIST_NOT_FOUND = 102;
public static final int DATABRIDGE_ERR_CLIENT_NULL_POINTER = 200;
public static final int DATABRIDGE_ERR_CLIENT_FAILED_TO_BIND_SERVICE = 201;
public static final int DATABRIDGE_ERR_CLIENT_SERVICE_ALREADY_CONNECTED = 202;
public static final int DATABRIDGE_ERR_CLIENT_SERVICE_DISCONNECTED = 203;
public static final int DATABRIDGE_ERR_CLIENT_REMOTE_EXCEPTION = 204;
public static final int DATABRIDGE_ERR_CLIENT_FAILED_TO_UNBIND_SERVICE = 205;
public static final int DATABRIDGE_ERR_CLIENT_UNKNWON_EXCEPTION = 206;
}
| [
"[email protected]"
] | |
c0bc752dfacb44091734f27d57f8a45b9160325a | cf9ec4a44ea26d5b3fc21c335a2c71c08abcb49a | /src/algorithms/com/guan/mianshi/huanweiOJ/YangHuiTriangleDeformation.java | 02786420bbe10d173656003c7f1a37429646a717 | [] | no_license | zhongwen7710/algorithm | 22b8ba860ae84f5b9bca6c7e6611a4de982150e6 | 5735237dc48dffa6c02fc982756e1c39978690dd | refs/heads/master | 2021-01-18T17:15:16.523909 | 2020-12-13T07:35:39 | 2020-12-13T07:35:39 | 23,423,697 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 1,847 | java | package algorithms.com.guan.mianshi.huanweiOJ;
import java.util.Scanner;
/**
* 问题描述:
1
1 1 1
1 2 3 2 1
1 3 6 7 6 3 1
1 4 10 16 19 16 10 4 1
以上三角形的数阵,第一行只有一个数1,以下每行的每个数,是恰好是它上面的数,左上角数到右上角的数,3个数之和(如果不存在某个数,认为该数就是0)。
求第n行第一个偶数出现的位置。如果没有偶数,则输出-1。例如输入3,则输出2,输入4则输出3。
输入n(n <= 1000000000)<>
public static int run(int x)
{
return -1;
}
<= 1000000000)<><= 1000000000)<><= 1000000000)<><= 1000000000)<>
<= 1000000000)<><= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<><= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<>
<= 1000000000)<>
* @author guanxiangqing
*
*/
public class YangHuiTriangleDeformation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(run(sc.nextInt()));
sc.close();
}
public static int run(int n) {
int result = -1;
int mat[][] = new int[n][];
int i, j, k = 0;
for (i = 0; i < n; i++) {
mat[i] = new int[2 * (i + 1) - 1];
mat[i][0] = 1;
for (j = 1; j < 2 * (i + 1) - 1; j++) {
if (j <= i) {
if (j - 2 < 0) {
if (j < mat[i - 1].length) {
mat[i][j] = mat[i - 1][j] + mat[i - 1][j - 1];
} else {
mat[i][j] = mat[i - 1][j - 1];
}
} else {
mat[i][j] = mat[i - 1][j] + mat[i - 1][j - 1]
+ mat[i - 1][j - 2];
}
k = j;
} else {
mat[i][j] = mat[i][--k];
}
}
}
for (j = 0; j < mat[n - 1].length; j++) {
if (mat[n - 1][j] % 2 == 0) {
result = j + 1;
break;
}
}
return result;
}
}
| [
"[email protected]"
] | |
da9d545241393814d15b32c68f8484a33152c640 | aef94b8d46236244a8c5272cca4dee83b2a8c5e6 | /customer-project/src/main/java/com/example/customerproject/controller/CustomerController.java | b55645bc6b7dea9ffcefe55bb1de1aa4c352a54e | [] | no_license | tendulkar1997/Redhat-jenkins | 218247ea79af9e9a61697a59fa09245abc92faeb | 445ec77657466c32d23747d8a35960f760e392e7 | refs/heads/main | 2023-06-25T19:37:32.782202 | 2021-07-20T06:18:03 | 2021-07-20T06:18:03 | 387,498,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,534 | java | package com.example.customerproject.controller;
import com.example.customerproject.dao.CustomerDao;
import com.example.customerproject.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class CustomerController {
private CustomerDao customerDao;
private Environment environment;
@Autowired
public CustomerController(CustomerDao customerDao, Environment environment) {
this.customerDao = customerDao;
this.environment=environment;
}
@GetMapping
public ResponseEntity<String> getStatus()
{
return ResponseEntity.ok("up and running on port: "+environment.getProperty("local.server.port"));
}
@GetMapping("/customers")
public ResponseEntity<List<Customer>> getAllCustomer()
{
return ResponseEntity.ok(customerDao.findAll());
}
@PostMapping("/customers")
public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer)
{
return ResponseEntity.status(HttpStatus.CREATED).body(customerDao.save(customer));
}
}
| [
"[email protected]"
] | |
c72f04fc84b4f63e968ffe98bd98694373fcb5ed | 5e6cfdb43b75810f03021d1890e6ed1d4fa1f362 | /tests/TestBasicAnimationModel.java | 54a5a751c30aee197f56f296440b76c47ec2d9ea | [] | no_license | zohebaziz/Animator | cceb3e4c6e1930c8637911ad559179bde34fcf62 | afb2ff9e9863287b7fe109641a4383a5ca264dc4 | refs/heads/master | 2023-03-02T11:54:33.087869 | 2021-02-14T23:00:51 | 2021-02-14T23:00:51 | 338,919,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,807 | java | import static org.junit.Assert.assertEquals;
import cs3500.animator.models.AnimationModel;
import cs3500.animator.models.BasicAnimationModel;
import cs3500.animator.models.Position2D;
import cs3500.animator.models.Shape;
import cs3500.animator.models.Shape.ShapeType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
/**
* Test class for the Basic Animation Model.
*/
public class TestBasicAnimationModel {
/* ----------create(...) Tests------------ */
@Test
public void createAllParams() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 0, 255, 0,
new Position2D(50, 50), 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void createNoPos() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 255, 255, 255, 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 255, 255, 255, 50, 50);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void createOnlyNameAndType() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 0, 0, 0, 0));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void createNameTypeColor() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 0, 255));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 0, 255);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void createNameTypeSize() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 50, 50);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test(expected = IllegalArgumentException.class)
public void createWrongWidth() {
Map<String, Shape> shapeMapError = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapError);
anim.create("r", ShapeType.RECTANGLE, -50, 50);
}
@Test(expected = IllegalArgumentException.class)
public void createWrongWeightZero() {
Map<String, Shape> shapeMapError = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapError);
anim.create("r", ShapeType.RECTANGLE, 0, 50);
}
@Test(expected = IllegalArgumentException.class)
public void createWrongHeight() {
Map<String, Shape> shapeMapError = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapError);
anim.create("r", ShapeType.RECTANGLE, 4, -200);
}
@Test(expected = IllegalArgumentException.class)
public void createWrongHeightZero() {
Map<String, Shape> shapeMapError = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapError);
anim.create("r", ShapeType.RECTANGLE, 40, 0);
}
@Test(expected = IllegalArgumentException.class)
public void createWrongShapeType() {
Map<String, Shape> shapeMapError = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapError);
anim.create("r", ShapeType.RECTANGLE);
anim.create("r", ShapeType.CIRCLE);
}
/* ----------remove(...) Tests------------ */
@Test
public void removeShape() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 0, 255, 0,
new Position2D(50, 50), 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
assertEquals(shapeMapExpected, shapeMapActual);
shapeMapExpected.clear();
anim.remove("r");
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test(expected = IllegalArgumentException.class)
public void removeShapeNotThere() {
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.remove("rectangle");
}
@Test
public void editAllParams() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 255, 165, 0,
new Position2D(200, 200), 100, 10));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.setCanvas(0, 0, 1000, 1000);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 0, new Position2D(10, 10), 50, 50, 255, 165, 0);
anim.motion("r", 4, new Position2D(75, 75), 100, 100, 255, 165, 0);
anim.motion("r", 6, new Position2D(200, 200), 100, 10, 255, 165, 0);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void editOnlyColor() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 255, 165, 0,
new Position2D(50, 50), 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 4, new Position2D(50, 50), 50, 50, 255, 165, 0);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void editOnlyPosition() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 0, 255, 0,
new Position2D(100, 100), 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 4, new Position2D(100, 100), 50, 50, 0, 255, 0);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void editHeightAndColor() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 255, 165, 0,
new Position2D(50, 50), 50, 100));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 5, new Position2D(50, 50), 50, 100, 255, 165, 0);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test
public void editWidthAndColor() {
Map<String, Shape> shapeMapExpected = new HashMap<>();
shapeMapExpected.put("r", new Shape("r", ShapeType.RECTANGLE, 0, 255, 165, 0,
new Position2D(50, 50), 100, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 8, new Position2D(50, 50), 100, 50, 255, 165, 0);
assertEquals(shapeMapExpected, shapeMapActual);
}
@Test(expected = IllegalArgumentException.class)
public void editBadNaming() {
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("p", 5, new Position2D(50, 50), 50, 50, 0, 255, 0);
}
@Test
public void moveShape() {
List<Shape> shapeMapExpected = new ArrayList<>();
shapeMapExpected.add(new Shape("r", ShapeType.RECTANGLE, 5, 0, 255, 0,
new Position2D(55, 55), 50, 50));
Map<String, Shape> shapeMapActual = new HashMap<>();
AnimationModel anim = new BasicAnimationModel(shapeMapActual);
anim.create("r", ShapeType.RECTANGLE, 0, 255, 0,
new Position2D(50, 50), 50, 50);
anim.motion("r", 5, new Position2D(55, 55), 50, 50, 0, 255, 0);
assertEquals(shapeMapExpected, anim.getFrames().get(5));
}
@Test
public void testGettingFrames() {
AnimationModel actual = new BasicAnimationModel();
actual.create("rect", ShapeType.RECTANGLE);
actual.motion("rect", 0, new Position2D(50, 50), 25, 25, 0, 255, 0);
actual.motion("rect", 1, new Position2D(50, 100), 25, 25, 0, 255, 0);
List<Shape> helper = new ArrayList<>();
List<Shape> helper2 = new ArrayList<>();
helper.add(new Shape("rect", ShapeType.RECTANGLE, 0, 0, 255,
0, new Position2D(50, 50), 25, 25));
helper2.add(new Shape("rect", ShapeType.RECTANGLE, 1, 0, 255,
0, new Position2D(50, 100), 25, 25));
Map<Integer, List<Shape>> expected = new HashMap<>();
expected.put(0, helper);
expected.put(1, helper2);
assertEquals(actual.getFrames(), expected);
}
@Test(expected = IllegalArgumentException.class)
public void testOverlappingMotions() {
AnimationModel model = new BasicAnimationModel();
model.create("rect", ShapeType.RECTANGLE);
model.motion("rect", 4, new Position2D(50, 50), 25, 25, 0, 255, 0);
model.motion("rect", 3, new Position2D(50, 100), 25, 25, 0, 255, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testOutOfBounds() {
AnimationModel model = new BasicAnimationModel();
model.create("rect", ShapeType.RECTANGLE);
model.motion("rect", 0, new Position2D(50, 50), 25, 25, 0, 255, 0);
model.motion("rect", 0, new Position2D(50, 100), 500, 25, 0, 255, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidColor() {
AnimationModel model = new BasicAnimationModel();
model.create("rect", ShapeType.RECTANGLE);
model.motion("rect", 0, new Position2D(50, 50), 25, 25, 0, 255, 0);
model.motion("rect", 0, new Position2D(50, 100), 500, 25, 0, 500, 0);
}
/* ----------getAllShapes(...) Tests------------ */
@Test
public void testGettingShapes() {
AnimationModel actual = new BasicAnimationModel();
actual.create("circ", ShapeType.CIRCLE);
actual.create("rect", ShapeType.RECTANGLE);
Map<String, Shape> expected = new HashMap<>();
expected.put("circ", new Shape("circ", ShapeType.CIRCLE, 0, 0, 0, 0, 0));
expected.put("rect", new Shape("rect", ShapeType.RECTANGLE, 0, 0, 0, 0, 0));
assertEquals(actual.getAllShapes(), expected);
}
/* ----------removeMotion(...) Tests------------ */
@Test
public void testRemoveMotion() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 2, new Position2D(100, 100), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(50, 100), 20, 20, 255, 1, 1);
anim.removeMotion("r", 2);
List<Shape> helper = new ArrayList<>();
List<Shape> helper2 = new ArrayList<>();
helper.add(new Shape("r", ShapeType.RECTANGLE, 0, 1, 1,
1, new Position2D(50, 50), 20, 20));
helper2.add(new Shape("r", ShapeType.RECTANGLE, 3, 255, 1,
1, new Position2D(50, 100), 20, 20));
Map<Integer, List<Shape>> expected = new HashMap<>();
expected.put(0, helper);
expected.put(3, helper2);
assertEquals(expected, anim.getFrames());
}
@Test(expected = IllegalArgumentException.class)
public void removeInvalidTime() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 2, new Position2D(100, 100), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(50, 100), 20, 20, 255, 1, 1);
anim.removeMotion("r", 4);
}
@Test(expected = IllegalArgumentException.class)
public void removeInvalidShapeMotion() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 2, new Position2D(100, 100), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(50, 100), 20, 20, 255, 1, 1);
anim.removeMotion("c", 4);
}
@Test
public void testGetShapesAt() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 1, new Position2D(75, 75), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(100, 100), 20, 20, 1, 1, 1);
anim.create("c", ShapeType.CIRCLE);
anim.motion("c", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("c", 1, new Position2D(50, 50), 60, 60, 1, 1, 1);
anim.motion("c", 3, new Position2D(50, 50), 100, 100, 1, 1, 1);
anim.create("s", ShapeType.SQUARE);
anim.motion("s", 4, new Position2D(50, 50), 20, 20, 1, 1, 1);
List<Shape> expected = new ArrayList<>();
expected.add(new Shape("r", ShapeType.RECTANGLE, 2, 1, 1, 1, new Position2D(88, 88), 20, 20));
expected.add(new Shape("c", ShapeType.RECTANGLE, 2, 1, 1, 1, new Position2D(50, 50), 80, 80));
assertEquals(expected, anim.shapesAtTime(2));
}
@Test
public void getFinalTime() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 1, new Position2D(75, 75), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(100, 100), 20, 20, 1, 1, 1);
assertEquals(3, anim.getFinalTime());
}
@Test
public void testShapeAtATime() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("c", ShapeType.CIRCLE);
anim.motion("c", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("c", 2, new Position2D(75, 75), 20, 20, 1, 1, 1);
anim.motion("c", 4, new Position2D(100, 100), 20, 20, 1, 1, 1);
List<Shape> expected = new ArrayList<>();
expected.add(new Shape("c", ShapeType.CIRCLE, 2, 1, 1, 1,
new Position2D(75, 75), 20, 20));
assertEquals(expected, anim.shapesAtTime(2));
anim.create("r", ShapeType.RECTANGLE);
anim.motion("r", 2, new Position2D(50, 50), 20, 20, 1, 50, 1);
expected.add(new Shape("r", ShapeType.RECTANGLE, 2, 1, 50, 1,
new Position2D(50, 50), 20, 20));
}
@Test
public void testGetFinalTime() {
BasicAnimationModel anim = new BasicAnimationModel();
anim.create("r", ShapeType.RECTANGLE);
assertEquals(0, anim.getFinalTime()); // base case
anim.motion("r", 0, new Position2D(50, 50), 20, 20, 1, 1, 1);
anim.motion("r", 1, new Position2D(75, 75), 20, 20, 1, 1, 1);
anim.motion("r", 3, new Position2D(100, 100), 20, 20, 1, 1, 1);
assertEquals(3, anim.getFinalTime());
}
}
| [
"[email protected]"
] | |
bcf259317e810d8dc53fc34cacea9f272ba48b08 | 28c7917bd9b62e875d4fd265ac5bbd1da215cc51 | /Source/airlinebooking.core.ws/src/test/java/airlinebooking/core/ws/test/CrawlerTest.java | fa4b29701f7d7d40a5abeebaefe669fb64952719 | [] | no_license | ledona1509/AirplaneBooking | a1ca0d76f4b0f719d94f97b488921cb4082f919b | 1a4f94b3ea2f7a3e2f1192a8aefcb67d03c1f9f0 | refs/heads/master | 2020-06-01T16:15:12.558987 | 2015-03-17T16:53:47 | 2015-03-17T16:53:47 | 31,423,182 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,916 | java | package airlinebooking.core.ws.test;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import airlinebooking.common.enumtype.AirlineType;
import airlinebooking.common.model.Ticket;
import airlinebooking.common.model.TicketParserParam;
import airlinebooking.core.ws.dao.TicketDao;
import airlinebooking.core.ws.dao.TicketParserParamDao;
import arilinebooking.core.ws.webbot.Crawler;
import arilinebooking.core.ws.webbot.CrawlerJetImpl;
import arilinebooking.core.ws.webbot.CrawlerVNAImpl;
import arilinebooking.core.ws.webbot.CrawlerVietJetImpl;
import arilinebooking.core.ws.webbot.WebBot;
import arilinebooking.core.ws.webbot.WebBotJetImpl;
import arilinebooking.core.ws.webbot.WebBotVNAImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })
public class CrawlerTest {
@Autowired
TicketParserParamDao ticketParserParamDao;
@Autowired
TicketDao ticketDao;
@Test
public void crawlerVNA() {
try {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_MONTH, 30);
Date pickedDate = cal.getTime();
String oriCode = "BOS";
String desCode = "SGN";
AirlineType airlineType = AirlineType.VNAIRLINE;
List<TicketParserParam> parserPathList = ticketParserParamDao.getParserPathByAirlineType(airlineType);
WebBot wbJet = new WebBotVNAImpl();
String htmlResultMH = wbJet.getHtmlResult(oriCode, desCode, pickedDate, 1, 0, 0);
Crawler crJet = new CrawlerVNAImpl();
List<Ticket> tickets = crJet.getTicketInfor(htmlResultMH, parserPathList, oriCode, desCode, pickedDate, airlineType);
ticketDao.saveListTickets(tickets);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
@Test
public void crawlerJetstar() {
try {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_MONTH, 30);
Date pickedDate = cal.getTime();
String oriCode = "HNL";
String desCode = "AVV";
AirlineType airlineType = AirlineType.JETSTAR;
List<TicketParserParam> parserPathList = ticketParserParamDao.getParserPathByAirlineType(airlineType);
WebBot wbJet = new WebBotJetImpl();
String htmlResultMH = wbJet.getHtmlResult(oriCode, desCode, pickedDate, 1, 0, 0);
Crawler crJet = new CrawlerJetImpl();
List<Ticket> tickets = crJet.getTicketInfor(htmlResultMH, parserPathList, oriCode, desCode, pickedDate, airlineType);
// ticketDao.saveListTickets(tickets);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void crawlerVietJet() {
try {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, Calendar.APRIL);
cal.set(Calendar.DAY_OF_MONTH, 30);
Date pickedDate = cal.getTime();
String oriCode = "SGN";
String desCode = "HAN";
AirlineType airlineType = AirlineType.VIETJET;
List<TicketParserParam> parserPathList = ticketParserParamDao.getParserPathByAirlineType(airlineType);
File input = new File("/Users/Dona/Desktop/untitled2.html");
Document doc = Jsoup.parse(input, "UTF-8");
String htmlResultString = doc.toString();
Crawler crVietJet = new CrawlerVietJetImpl();
@SuppressWarnings("unused")
List<Ticket> tickets = crVietJet.getTicketInfor(htmlResultString, parserPathList, oriCode, desCode, pickedDate, airlineType);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void mockTest() {
try {
// Parser parserJsoup = new ParserJsoupImpl();
//
// TicketParserParam tkPP0 = new TicketParserParam();
// TicketParserParam tkPP1 = new TicketParserParam();
// TicketParserParam tkPP2 = new TicketParserParam();
// TicketParserParam tkPP3 = new TicketParserParam();
// TicketParserParam tkPP4 = new TicketParserParam();
//
// /* = Setup our mock object with the expected values */
// tkPP0.setAirlineType(AirlineType.VNAIRLINE);
// tkPP0.setCodeType("flight_code");
// tkPP0.setSelectorPath("a.translate[title=\"Xem chi tiết chuyến bay\"]");
// tkPP0.setTicketTypeCode("");
//
// tkPP1.setAirlineType(AirlineType.VNAIRLINE);
// tkPP1.setCodeType("from_time");
// tkPP1.setSelectorPath("tr.yui-dt-even > td:nth-child(3) > span.translate.wasTranslated, tr.yui-dt-odd > td:nth-child(3) > span.translate.wasTranslated");
// tkPP1.setTicketTypeCode("");
//
// tkPP2.setAirlineType(AirlineType.VNAIRLINE);
// tkPP2.setCodeType("to_time");
// tkPP2.setSelectorPath("tr.yui-dt-even > td:nth-child(4) > span.translate.wasTranslated, tr.yui-dt-odd > td:nth-child(4) > span.translate.wasTranslated");
// tkPP2.setTicketTypeCode("");
//
// tkPP3.setAirlineType(AirlineType.VNAIRLINE);
// tkPP3.setCodeType("amount");
// tkPP3.setSelectorPath("div.flight-list-section.flight-list > table > tbody > tr > td[fare-family-key=\"BF\"] span.prices-amount, div.flight-list-section.flight-list > table > tbody > tr > td[fare-family-key=\"BF\"] span.farefamily-cell-unavailable.translate.wasTranslated");
// tkPP3.setTicketTypeCode("VNA_TGLH");
//
// tkPP4.setAirlineType(AirlineType.VNAIRLINE);
// tkPP4.setCodeType("amount");
// tkPP4.setSelectorPath("div.flight-list-section.flight-list > table > tbody > tr > td[fare-family-key=\"BS\"] span.prices-amount, div.flight-list-section.flight-list > table > tbody > tr > td[fare-family-key=\"BS\"] span.farefamily-cell-unavailable.translate.wasTranslated");
// tkPP4.setTicketTypeCode("VNA_TGTC");
//
// List<TicketParserParam> parserPathList = new ArrayList<TicketParserParam>();
// parserPathList.add(tkPP0);
// parserPathList.add(tkPP1);
// parserPathList.add(tkPP2);
// parserPathList.add(tkPP3);
// parserPathList.add(tkPP4);
//
// File input = new File("C:/Users/nald/Desktop/united.html");
// Document doc = Jsoup.parse(input, "UTF-8");
// HtmlResultMH htmlResult = new HtmlResultMH();
// htmlResult.setHtmlResult(doc.toString());
// htmlResult.setAirlineType(AirlineType.VNAIRLINE);
//
// HashMap<String, Object> result = parserJsoup.getObjectInfor(
// htmlResult, parserPathList);
//
// TicketInforRawMaker converter = new TicketInforRawMakerImpl();
// List<TicketInforRawMH> ticketInforMHList = converter
// .convertParserToTicketInforMH(result);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
87d8f923f1b7673700af8d6ce8849f266b9856c7 | 80c51a130a9d24a69d7fe2d4f7cdc12c5a2b7bec | /src/main/java/by/training/webapplication/model/Question.java | 684f1d6dae5bec3f1555101da6c5ddf51bf1c559 | [] | no_license | lutanya/final-project | 21532e0fc0600cf6cc58f4786183680227329ca9 | 84cd06d23e6cd692723556e03fa1a1c7d70e4418 | refs/heads/master | 2020-06-23T19:34:29.056240 | 2016-10-10T05:08:25 | 2016-10-10T05:08:25 | 67,934,987 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,095 | java | package by.training.webapplication.model;
/**
* Created by Tanya on 14.09.2016.
*/
public class Question {
private int questionId;
private String questionerName;
private String backEmail;
private String questionText;
private int replied;
public String getQuestionerName() {
return questionerName;
}
public void setQuestionerName(String questionerName) {
this.questionerName = questionerName;
}
public String getBackEmail() {
return backEmail;
}
public void setBackEmail(String backEmail) {
this.backEmail = backEmail;
}
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
public int getReplied() {
return replied;
}
public void setReplied(int replied) {
this.replied = replied;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
}
| [
"[email protected]"
] | |
831115d5bf4d4410271e3a6e00602a7865614788 | fdda9ec6ee2de20d403f942fb8c18c356f7f7c14 | /src/Sockets/Server.java | 970c74ad9a68c264ec0aac6f8d4a3ce7a2069dc5 | [] | no_license | DwightIke/FlightsApp | 08c408a337109afcaf0c7571cdea98958c158e6e | 7fb9946bfd452d8f347dd212875f78635d12b757 | refs/heads/master | 2021-01-23T06:45:38.230710 | 2017-04-06T08:12:59 | 2017-04-06T08:12:59 | 86,399,825 | 0 | 1 | null | 2017-04-05T13:16:21 | 2017-03-28T01:10:11 | Java | UTF-8 | Java | false | false | 1,485 | java | package Sockets;
import Database.Database;
import Domain.LoginData;
import Repository.UserRepository;
import Services.UserService;
import com.google.gson.Gson;
import java.io.*;
import java.net.*;
import java.sql.Connection;
public class Server {
public static final String IP = "localhost";
public static final int PORT = 6789;
private static Gson GSON = new Gson();
public static void main(String argv[]) throws Exception {
Database database = new Database();
Connection connection = database.getConnection();
UserRepository userRepo = new UserRepository(connection);
UserService userService = new UserService(userRepo);
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
String message = inFromClient.readLine();
System.out.println("Got text: " + message);
LoginData loginData = GSON.fromJson(message, LoginData.class);
loginData.canLogIn = userService.canLogIn(loginData.loginCode);
String outMessage = GSON.toJson(loginData);
outToClient.writeBytes(outMessage);
connectionSocket.close();
}
}
} | [
"[email protected]"
] | |
2d12184db91a5a52df993f908eb6d04640c1f906 | bf2523e1da431f26937614de9c9640295899d7d5 | /src/main/java/com/njq/chain/Handler.java | 90ca7a2f0f4bb6ef7bcc15cf872a547fbcae9bab | [] | no_license | zbnfy/SpringProxy | c2276befd754f1cc3fcbff8aaac950701f479565 | bbbdc5d55699bb0b7663c9140b1cdb36c7714546 | refs/heads/master | 2021-07-08T05:47:44.906250 | 2017-10-05T17:06:41 | 2017-10-05T17:06:41 | 105,917,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 515 | java | package com.njq.chain;
/**
* 链式调用
* Created by NIJIAQI on 2017/10/6.
*/
public abstract class Handler {
//判断后续是否有处理
private Handler sucessor;
public Handler getSucessor() {
return sucessor;
}
public void setSucessor(Handler sucessor) {
this.sucessor = sucessor;
}
public void execute() {
handleProcess();
if(sucessor!=null) {
sucessor.execute();
}
}
protected abstract void handleProcess();
}
| [
"[email protected]"
] | |
8b0e77553c058b4a01f1b0d6c6100d7383900574 | 8cae4c912d66c3a530cd1e13025285be1da259bd | /sdk/src/main/java/org/bitcoinj/wallet/Protos.java | 86b3499c9d27375f27b62384e6f0632da60ef72a | [
"MIT"
] | permissive | elastos/Elastos.DID.Java.SDK | c7c7b2c24bc25c2c92a10836fdd94f29dcc21e9e | 7cf79021379e89683e19a31ae88ab3885e7a34a1 | refs/heads/master | 2023-07-10T23:08:25.077391 | 2023-06-29T03:11:41 | 2023-06-29T03:34:53 | 227,095,310 | 8 | 7 | MIT | 2023-06-29T03:34:55 | 2019-12-10T10:52:20 | Java | UTF-8 | Java | false | true | 17,339 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: wallet.proto
package org.bitcoinj.wallet;
import org.bitcoinj.core.ByteString;
public final class Protos {
private Protos() {}
public interface ScryptParametersOrBuilder {
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
boolean hasSalt();
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
ByteString getSalt();
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
boolean hasN();
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
long getN();
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
boolean hasR();
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
int getR();
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
boolean hasP();
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
int getP();
}
/**
* <pre>
** The parameters used in the scrypt key derivation function.
* The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf.
* They can be increased - n is the number of iterations performed and
* r and p can be used to tweak the algorithm - see:
* http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors
* </pre>
*
* Protobuf type {@code wallet.ScryptParameters}
*/
public static final class ScryptParameters implements
// @@protoc_insertion_point(message_implements:wallet.ScryptParameters)
ScryptParametersOrBuilder {
private ScryptParameters(ScryptParametersOrBuilder builder) {
//super(builder);
}
private ScryptParameters() {
salt_ = ByteString.EMPTY;
n_ = 16384L;
r_ = 8;
p_ = 1;
}
private int bitField0_;
public static final int SALT_FIELD_NUMBER = 1;
private ByteString salt_;
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
@Override
public boolean hasSalt() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
@Override
public ByteString getSalt() {
return salt_;
}
public static final int N_FIELD_NUMBER = 2;
private long n_;
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
@Override
public boolean hasN() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
@Override
public long getN() {
return n_;
}
public static final int R_FIELD_NUMBER = 3;
private int r_;
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
@Override
public boolean hasR() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
@Override
public int getR() {
return r_;
}
public static final int P_FIELD_NUMBER = 4;
private int p_;
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
@Override
public boolean hasP() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
@Override
public int getP() {
return p_;
}
private byte memoizedIsInitialized = -1;
private int memoizedHashCode = 0;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasSalt()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.bitcoinj.wallet.Protos.ScryptParameters)) {
return super.equals(obj);
}
org.bitcoinj.wallet.Protos.ScryptParameters other = (org.bitcoinj.wallet.Protos.ScryptParameters) obj;
if (hasSalt() != other.hasSalt()) return false;
if (hasSalt()) {
if (!getSalt()
.equals(other.getSalt())) return false;
}
if (hasN() != other.hasN()) return false;
if (hasN()) {
if (getN()
!= other.getN()) return false;
}
if (hasR() != other.hasR()) return false;
if (hasR()) {
if (getR()
!= other.getR()) return false;
}
if (hasP() != other.hasP()) return false;
if (hasP()) {
if (getP()
!= other.getP()) return false;
}
return true;
}
private static int hashLong(long n) {
return (int) (n ^ (n >>> 32));
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
if (hasSalt()) {
hash = (37 * hash) + SALT_FIELD_NUMBER;
hash = (53 * hash) + getSalt().hashCode();
}
if (hasN()) {
hash = (37 * hash) + N_FIELD_NUMBER;
hash = (53 * hash) + hashLong(getN());
}
if (hasR()) {
hash = (37 * hash) + R_FIELD_NUMBER;
hash = (53 * hash) + getR();
}
if (hasP()) {
hash = (37 * hash) + P_FIELD_NUMBER;
hash = (53 * hash) + getP();
}
memoizedHashCode = hash;
return hash;
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.bitcoinj.wallet.Protos.ScryptParameters prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
/**
* <pre>
** The parameters used in the scrypt key derivation function.
* The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf.
* They can be increased - n is the number of iterations performed and
* r and p can be used to tweak the algorithm - see:
* http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors
* </pre>
*
* Protobuf type {@code wallet.ScryptParameters}
*/
public static final class Builder implements
// @@protoc_insertion_point(builder_implements:wallet.ScryptParameters)
org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder {
// Construct using org.bitcoinj.wallet.Protos.ScryptParameters.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
}
public org.bitcoinj.wallet.Protos.ScryptParameters build() {
org.bitcoinj.wallet.Protos.ScryptParameters result = buildPartial();
if (!result.isInitialized()) {
throw new IllegalStateException(result.toString());
}
return result;
}
public org.bitcoinj.wallet.Protos.ScryptParameters buildPartial() {
org.bitcoinj.wallet.Protos.ScryptParameters result = new org.bitcoinj.wallet.Protos.ScryptParameters(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.salt_ = salt_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.n_ = n_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.r_ = r_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.p_ = p_;
result.bitField0_ = to_bitField0_;
return result;
}
public Builder clear() {
salt_ = ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
n_ = 16384L;
bitField0_ = (bitField0_ & ~0x00000002);
r_ = 8;
bitField0_ = (bitField0_ & ~0x00000004);
p_ = 1;
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
public Builder mergeFrom(org.bitcoinj.wallet.Protos.ScryptParameters other) {
if (other == org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance()) return this;
if (other.hasSalt()) {
setSalt(other.getSalt());
}
if (other.hasN()) {
setN(other.getN());
}
if (other.hasR()) {
setR(other.getR());
}
if (other.hasP()) {
setP(other.getP());
}
return this;
}
public final boolean isInitialized() {
if (!hasSalt()) {
return false;
}
return true;
}
private int bitField0_;
private ByteString salt_ = ByteString.EMPTY;
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
@Override
public boolean hasSalt() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
@Override
public ByteString getSalt() {
return salt_;
}
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
public Builder setSalt(ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
salt_ = value;
return this;
}
/**
* <pre>
* Salt to use in generation of the wallet password (8 bytes)
* </pre>
*
* <code>required bytes salt = 1;</code>
*/
public Builder clearSalt() {
bitField0_ = (bitField0_ & ~0x00000001);
salt_ = getDefaultInstance().getSalt();
return this;
}
private long n_ = 16384L;
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
@Override
public boolean hasN() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
@Override
public long getN() {
return n_;
}
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
public Builder setN(long value) {
bitField0_ |= 0x00000002;
n_ = value;
return this;
}
/**
* <pre>
* CPU/ memory cost parameter
* </pre>
*
* <code>optional int64 n = 2 [default = 16384];</code>
*/
public Builder clearN() {
bitField0_ = (bitField0_ & ~0x00000002);
n_ = 16384L;
return this;
}
private int r_ = 8;
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
@Override
public boolean hasR() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
@Override
public int getR() {
return r_;
}
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
public Builder setR(int value) {
bitField0_ |= 0x00000004;
r_ = value;
return this;
}
/**
* <pre>
* Block size parameter
* </pre>
*
* <code>optional int32 r = 3 [default = 8];</code>
*/
public Builder clearR() {
bitField0_ = (bitField0_ & ~0x00000004);
r_ = 8;
return this;
}
private int p_ = 1;
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
@Override
public boolean hasP() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
@Override
public int getP() {
return p_;
}
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
public Builder setP(int value) {
bitField0_ |= 0x00000008;
p_ = value;
return this;
}
/**
* <pre>
* Parallelisation parameter
* </pre>
*
* <code>optional int32 p = 4 [default = 1];</code>
*/
public Builder clearP() {
bitField0_ = (bitField0_ & ~0x00000008);
p_ = 1;
return this;
}
// @@protoc_insertion_point(builder_scope:wallet.ScryptParameters)
}
// @@protoc_insertion_point(class_scope:wallet.ScryptParameters)
private static final org.bitcoinj.wallet.Protos.ScryptParameters DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.bitcoinj.wallet.Protos.ScryptParameters();
}
public static org.bitcoinj.wallet.Protos.ScryptParameters getDefaultInstance() {
return DEFAULT_INSTANCE;
}
}
/**
* <pre>
** A bitcoin wallet
* </pre>
*
* Protobuf type {@code wallet.Wallet}
*/
public static final class Wallet {
/**
* <pre>
**
* The encryption type of the wallet.
* The encryption type is UNENCRYPTED for wallets where the wallet does not support encryption - wallets prior to
* encryption support are grandfathered in as this wallet type.
* When a wallet is ENCRYPTED_SCRYPT_AES the keys are either encrypted with the wallet password or are unencrypted.
* </pre>
*
* Protobuf enum {@code wallet.Wallet.EncryptionType}
*/
public enum EncryptionType {
/**
* <pre>
* All keys in the wallet are unencrypted
* </pre>
*
* <code>UNENCRYPTED = 1;</code>
*/
UNENCRYPTED(1),
/**
* <pre>
* All keys are encrypted with a passphrase based KDF of scrypt and AES encryption
* </pre>
*
* <code>ENCRYPTED_SCRYPT_AES = 2;</code>
*/
ENCRYPTED_SCRYPT_AES(2),
;
/**
* <pre>
* All keys in the wallet are unencrypted
* </pre>
*
* <code>UNENCRYPTED = 1;</code>
*/
public static final int UNENCRYPTED_VALUE = 1;
/**
* <pre>
* All keys are encrypted with a passphrase based KDF of scrypt and AES encryption
* </pre>
*
* <code>ENCRYPTED_SCRYPT_AES = 2;</code>
*/
public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2;
public final int getNumber() {
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static EncryptionType valueOf(int value) {
return forNumber(value);
}
public static EncryptionType forNumber(int value) {
switch (value) {
case 1: return UNENCRYPTED;
case 2: return ENCRYPTED_SCRYPT_AES;
default: return null;
}
}
private final int value;
private EncryptionType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:wallet.Wallet.EncryptionType)
}
}
}
| [
"[email protected]"
] | |
c271c78ecc2b04dbe6ff3a603a97752e812f4bbd | 7a96e3f5249bcac741ca25809a0a69fd1d086ba6 | /src/ElectionDriver.java | 90bf785f88dcfbb945fc6c3825ce5f95bafdd70a | [] | no_license | le000043/Voting-System | 0f55b7a31f5695ee47241084ad8f971ae5ad8c19 | 6b8839d8b017c7ac7ce0e17a8c2d4d07c4a3254d | refs/heads/master | 2022-12-15T10:06:17.483339 | 2020-08-30T22:57:31 | 2020-08-30T22:57:31 | 291,564,522 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,322 | java | /**
* <h1>Election Driver</h1>
* The Election Driver is a static class with the main event loop for the Election Voting system.
* This Class handles setting up the election voting system as well as user ballot file input and light parsing.
* <p>
*
* @author Griffin Higley
* @version 1.0
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* <h1>Election Driver</h1>
*
* <p>
* Election Driver is the Driver class that runs the VCS.
* Election Driver links all other classes to the UI as well as calls the Election Builder to create the VCS
* </p>
*
* @author Griffin Higley
* @version 1.0
*/
public class ElectionDriver {
private static File electionInputFile;
private static Election election;
private static String electionType;
private static String fileName;
private static ArrayList<String> candidateList = new ArrayList<>();
private static ArrayList<String> ballotList = new ArrayList<>();
private static ArrayList<String> electionInformation = new ArrayList<>();
private static String CPLPartyList = "";
private static Audit audit;
public static void clearDriver() {
/**
* This function is used to clear out the static data held by the election driver class.
* @return void
**/
ElectionDriver.electionInputFile = null;
ElectionDriver.election = null;
ElectionDriver.electionType = "";
ElectionDriver.fileName = "";
ElectionDriver.candidateList = new ArrayList<>();
ElectionDriver.ballotList = new ArrayList<>();
ElectionDriver.electionInformation = new ArrayList<>();
ElectionDriver.CPLPartyList = "";
}
public static void main(String[] args) throws IOException {
/**
* This function is used to run the main event loop for the VCS
* This function also handles getting the ballot file from the users CLA
* The function sets up the Driver and gets the ball rolling
* @param args This is the name of the ballot file
* @return void
**/
Input input = new Input((args.length > 0)? args[0] : "");
audit = Audit.getInstance();
audit.LOG("Election Driver starting up");
// This can be used if an absolute path to a file is needed
// String current = new java.io.File(".").getCanonicalPath();
ElectionDriver.SetElectionFileAndFileName(input.GetFileName());
try {
ElectionDriver.Init();
ElectionDriver.Run();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void SetElectionFileAndFileName(String fileName) {
/**
* This functions job is to make sure that the file can be oppend
* and to set up the File io for the Election Driver.
* We also store a copy of the file name just in case we need it later
* @param fileName This is the name that main got from the user
* @return void
**/
try {
ElectionDriver.fileName = fileName;
ElectionDriver.electionInputFile = new File(fileName);
audit.LOG("File " + fileName + " being parsed");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void Init() throws FileNotFoundException {
/**
* This functions job is to setup all the data for the Election driver
* all the function calls for data of objects that must be made or
* read into the system before being used should be called here.
* @throws FileNotFoundException
* @return void
**/
Scanner sc = new Scanner(ElectionDriver.electionInputFile);
if (sc.hasNextLine()) {
String nextLine = sc.nextLine();
ElectionDriver.electionType = nextLine;
audit.LOG("Election type found:\t" + electionType + "\n");
}
while (sc.hasNextLine()) {
String nextLine = sc.nextLine();
// Case matches candidate formatting
if (nextLine.contains("[")) {
// This handles the case for the first [ in the cpl file being the party list
if (ElectionDriver.electionType.toUpperCase().equals("CPL") && ElectionDriver.CPLPartyList.equals("")) {
ElectionDriver.CPLPartyList = nextLine;
audit.LOG("Found Election information:\t" + nextLine + "\n");
} else {
candidateList.add(nextLine);
audit.LOG("Candidate found:\t" + nextLine + "\n");
}
// Case matches ballot formatting
} else if (nextLine.contains("1") && nextLine.contains(",")) {
ballotList.add(nextLine);
audit.LOG("Ballot found:\t" + nextLine + "\n");
} else {
// Case for default general election information (like seat counts)
electionInformation.add(nextLine);
}
}
if (ElectionDriver.getElectionType().toLowerCase().equals("opl")) {
ElectionDriver.election = ElectionBuilder.build(
ElectionDriver.getElectionType(),
ElectionDriver.getElectionInformation(),
ElectionDriver.getCandidateList(),
ElectionDriver.getBallotList()
);
} else {
ElectionDriver.election = ElectionBuilder.build(
ElectionDriver.getElectionType(),
ElectionDriver.getElectionInformation(),
ElectionDriver.getCandidateList(),
ElectionDriver.getBallotList(),
ElectionDriver.getCPLPartyList()
);
}
}
private static int Run() {
/**
* This function calls to the built elections run file to start running the election
* @throws FileNotFoundException
* @return int This value represents if the election ran with (-1) or without an error (0)
**/
try {
audit.LOG("++++++++++++++++++++++++++");
ElectionDriver.election.Run();
audit.LOG("++++++++++++++++++++++++++");
audit.close();
//System.exit(0);
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public static File getElectionInputFile() {
return electionInputFile;
}
public static Election getElection() {
return election;
}
public static void setElection(Election election) {
ElectionDriver.election = election;
}
public static String getElectionType() {
return electionType;
}
public static String getFileName() {
return fileName;
}
public static ArrayList<String> getCandidateList() {
return candidateList;
}
public static ArrayList<String> getElectionInformation() {
return electionInformation;
}
public static ArrayList<String> getBallotList() {
return ballotList;
}
public static String getCPLPartyList() {
return CPLPartyList;
}
}
| [
"[email protected]"
] | |
98cc84056c781ed20ccea0653803de57c6a43f78 | 2a822060c0e66379e23bdc13225676246717571a | /ProjetoElevador/src/passageiro/EventoPassageiro.java | 720f3b556ade0cd24b3fea6a4b4d4fbc01f16011 | [] | no_license | apljjr/elevador | a105ea85ba213e69079741b3eac89c093cf9c370 | 4beac184fd93365e6fcd65ce3f4dac801e7b95fa | refs/heads/master | 2020-05-19T15:20:04.460101 | 2019-05-07T03:48:13 | 2019-05-07T03:48:13 | 185,082,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 498 | java | package passageiro;
public class EventoPassageiro {
private Integer andarSolicitado;
private Integer andarOrigem;
public Integer getAndarSolicitado() {
return andarSolicitado;
}
public void setAndarSolicitado(Integer andarSolicitado) {
this.andarSolicitado = andarSolicitado;
}
public Integer getAndarOrigem() {
return andarOrigem;
}
public void setAndarOrigem(Integer andarOrigem) {
this.andarOrigem = andarOrigem;
}
}
| [
"[email protected]"
] | |
ba7934d62e8b0df6fd7839776dda905877ad1701 | f84b91e90653be5cf76ccf6699f01c77175ac55e | /src/java/models/Empleado.java | c54a91f32c5d27bb27b33015a02fc74a22b5113a | [] | no_license | serraguti/proyectostruts | 71ae845598109a15ab539db68d3f52685934d948 | aba187282518b0f04b317c208ab39a5b21fffb72 | refs/heads/master | 2023-03-06T21:18:50.493106 | 2021-02-18T16:23:25 | 2021-02-18T16:23:25 | 337,115,393 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,417 | java | package models;
public class Empleado {
private int idEmpleado;
private String apellido;
private String oficio;
private int salario;
private int iddepartamento;
public Empleado() {
}
public Empleado(int id, String ape, String ofi, int sal) {
this.idEmpleado = id;
this.apellido = ape;
this.oficio = ofi;
this.salario = sal;
}
public Empleado(int id, String ape, String ofi, int sal, int iddept) {
this.idEmpleado = id;
this.apellido = ape;
this.oficio = ofi;
this.salario = sal;
this.iddepartamento = iddept;
}
public int getIdEmpleado() {
return idEmpleado;
}
public void setIdEmpleado(int idEmpleado) {
this.idEmpleado = idEmpleado;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getOficio() {
return oficio;
}
public void setOficio(String oficio) {
this.oficio = oficio;
}
public int getSalario() {
return salario;
}
public void setSalario(int salario) {
this.salario = salario;
}
public int getIddepartamento() {
return iddepartamento;
}
public void setIddepartamento(int iddepartamento) {
this.iddepartamento = iddepartamento;
}
}
| [
"[email protected]"
] | |
17beb0e759208432c7acef0e21ba001cf44aac2c | 55bece5af06037849166e0b8a0867c3cefa3f9d1 | /Web/src/Controlleur/ControlleurGenerationPlan.java | af3a5d3921fb1ab876a651a5ed1f1d7ec16edd83 | [
"Apache-2.0"
] | permissive | yachakou/coaching-muscu | 7a46c96792f204097176e42216b559b0167b323a | e64280ad299a2e319ef92640e1c3fc83c416b4ae | refs/heads/master | 2021-01-19T00:46:49.923564 | 2016-08-07T21:27:50 | 2016-08-07T21:27:50 | 65,154,832 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,016 | java | package Controlleur;
import Modele.Utilisateur;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by Mathieu on 25/03/2015.
*/
public class ControlleurGenerationPlan extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher;
HttpSession session=request.getSession();
dispatcher = request.getRequestDispatcher("listePlanEntrainement.jsp");
Utilisateur u = (Utilisateur) session.getAttribute("user");
u.genererPlanENtrainement(1);
dispatcher.forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| [
"[email protected]"
] | |
a0570eca46315c3eb74ac792bc4027b0fdd43b5e | 016d66f32d9ac2e1d7a2fa0661e03a48e21af302 | /desktop applications/hsqldb-master/src/org/hsqldb/lib/DoubleIntIndex.java | f535240f12215d9fb01763491ef00ac125cb250a | [] | no_license | 18745332164/co-occurrence | 62f9af4c4bf6089c486adfea5c17c74421dfd4e4 | f7c8e4f4c0e904d66867bd81808b4f4d5826c79f | refs/heads/master | 2023-06-25T11:09:31.817159 | 2021-07-20T08:45:13 | 2021-07-20T08:45:13 | 387,396,410 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 25,197 | java | /* Copyright (c) 2001-2020, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.lib;
import java.util.Arrays;
import java.util.NoSuchElementException;
/**
* Maintains an ordered integer->integer lookup table, consisting of two
* columns, one for keys, the other for values. Equal keys are allowed.
*
* The table is sorted on either the key or value column, depending on the calls to
* setKeysSearchTarget() or setValuesSearchTarget(). By default, the table is
* sorted on values. Equal values are sorted by key.<p>
*
* findXXX() methods return the array index into the list
* pair containing a matching key or value, or or -1 if not found.<p>
*
* Sorting methods originally contributed by Tony Lai (tony_lai@users dot sourceforge.net).
* Non-recursive implementation of fast quicksort added by Sergio Bossa sbtourist@users dot sourceforge.net)
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 2.5.1
* @since 1.8.0
*/
public class DoubleIntIndex implements LongLookup {
private int count = 0;
private int capacity;
private boolean sorted = true;
private boolean sortOnValues = false;
private final boolean fixedSize;
private int[] keys;
private int[] values;
//
private int targetSearchValue;
public DoubleIntIndex(int capacity) {
this(capacity, false);
}
public DoubleIntIndex(int capacity, boolean fixedSize) {
this.capacity = capacity;
keys = new int[capacity];
values = new int[capacity];
this.fixedSize = fixedSize;
}
public int getKey(int i) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
return keys[i];
}
public long getLongKey(int i) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
return keys[i] & 0xffffffffL;
}
public long getLongValue(int i) {
return values[i];
}
public int getValue(int i) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
return values[i];
}
/**
* Modifies an existing pair.
* @param i the index
* @param key the key
*/
public void setKey(int i, int key) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (!sortOnValues) {
sorted = false;
}
keys[i] = key;
}
/**
* Modifies an existing pair.
* @param i the index
* @param value the value
*/
public void setValue(int i, int value) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (sortOnValues) {
sorted = false;
}
values[i] = value;
}
/**
* Modifies an existing pair.
* @param i the index
* @param value the value
*/
public void setLongValue(int i, long value) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (sortOnValues) {
sorted = false;
}
values[i] = (int) value;
}
public int size() {
return count;
}
public int capacity() {
return capacity;
}
public int[] getKeys() {
return keys;
}
public int[] getValues() {
return values;
}
public long getTotalValues() {
long total = 0;
for (int i = 0; i < count; i++) {
total += values[i];
}
return total;
}
public void setSize(int newSize) {
count = newSize;
}
public boolean addUnsorted(long key, long value) {
if (key > Integer.MAX_VALUE || key < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return addUnsorted((int) key, (int) value);
}
/**
* Adds a pair into the table.
*
* @param key the key
* @param value the value
* @return true or false depending on success
*/
public boolean addUnsorted(int key, int value) {
if (count == capacity) {
if (fixedSize) {
return false;
} else {
doubleCapacity();
}
}
if (sorted && count != 0) {
if (sortOnValues) {
if (value < values[count - 1]) {
sorted = false;
}
} else {
if (key < keys[count - 1]) {
sorted = false;
}
}
}
keys[count] = key;
values[count] = value;
count++;
return true;
}
public boolean addUnsorted(LongLookup other) {
if (!ensureCapacityToAdd(other.size())) {
return false;
}
sorted = false;
for (int i = 0; i < other.size(); i++) {
long key = other.getLongKey(i);
long value = other.getLongValue(i);
this.addUnsorted(key, value);
}
return true;
}
private boolean ensureCapacityToAdd(int extra) {
if (count + extra > capacity) {
if (fixedSize) {
return false;
} else {
while (count + extra > capacity) {
doubleCapacity();
}
}
}
return true;
}
/**
* Adds a key, value pair into the table with the guarantee that the key
* is equal or larger than the largest existing key. This prevents a sort
* from taking place on next call to find()
*
* @param key the key
* @param value the value
* @return true or false depending on success
*/
public boolean addSorted(int key, int value) {
if (count == capacity) {
if (fixedSize) {
return false;
} else {
doubleCapacity();
}
}
if (count != 0) {
if (sortOnValues) {
if (value < values[count - 1]) {
return false;
} else if (value == values[count - 1]
&& key < keys[count - 1]) {
return false;
}
} else {
if (key < keys[count - 1]) {
return false;
}
}
}
keys[count] = key;
values[count] = value;
count++;
return true;
}
/**
* Adds a pair, ensuring no duplicate key xor value already exists in the
* current search target column.
* @param key the key
* @param value the value
* @return true or false depending on success
*/
public boolean addUnique(int key, int value) {
if (sortOnValues) {
throw new IllegalArgumentException();
}
if (count == capacity) {
if (fixedSize) {
return false;
} else {
doubleCapacity();
}
}
if (!sorted) {
fastQuickSort();
}
targetSearchValue = sortOnValues ? value
: key;
int i = binaryEmptySlotSearch();
if (i == -1) {
return false;
}
if (count != i) {
moveRows(i, i + 1, count - i);
}
keys[i] = key;
values[i] = value;
count++;
return true;
}
/**
* must be sorted on key
*/
public boolean removeKey(int key) {
if (sortOnValues) {
throw new IllegalArgumentException();
}
if (!sorted) {
fastQuickSort();
}
targetSearchValue = key;
int i = binarySlotSearch(false);
if (i == count) {
return false;
}
if (keys[i] != key) {
return false;
}
remove(i);
return true;
}
/**
* must be sorted on key
*/
public boolean addOrReplaceUnique(int key, int value) {
if (sortOnValues) {
throw new IllegalArgumentException();
}
if (!sorted) {
fastQuickSort();
}
targetSearchValue = key;
int i = binarySlotSearch(false);
if (i < count) {
if (keys[i] == key) {
values[i] = value;
return true;
}
if (count == capacity) {
if (fixedSize) {
return false;
} else {
doubleCapacity();
}
}
moveRows(i, i + 1, count - i);
}
keys[i] = key;
values[i] = value;
count++;
return true;
}
/**
* Used for values as counters. Adds the value to the existing value for the
* key. Or adds the key - value pair.
*/
public int addCount(int key, int value) {
sortOnValues = false;
if (addUnique(key, value)) {
return value;
}
targetSearchValue = key;
int i = this.binarySlotSearch(false);
values[i] += value;
return values[i];
}
public int addCount(int key) {
return addCount(key, 1);
}
public int add(long key, long value) {
if (key > Integer.MAX_VALUE || key < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return add((int) key, (int) value);
}
/**
* Adds a pair, maintaining sort order on
* current search target column.
* @param key the key
* @param value the value
* @return index of added key or -1 if full
*/
public int add(int key, int value) {
if (count == capacity) {
if (fixedSize) {
return -1;
} else {
doubleCapacity();
}
}
if (!sorted) {
fastQuickSort();
}
targetSearchValue = sortOnValues ? value
: key;
int i = binarySlotSearch(true);
if (count != i) {
moveRows(i, i + 1, count - i);
}
keys[i] = key;
values[i] = value;
count++;
return i;
}
public long lookup(long key) throws NoSuchElementException {
if (key > Integer.MAX_VALUE || key < Integer.MIN_VALUE) {
throw new NoSuchElementException();
}
return lookup((int) key);
}
public int lookup(int key) throws NoSuchElementException {
if (sortOnValues) {
sorted = false;
sortOnValues = false;
}
int i = findFirstEqualKeyIndex(key);
if (i == -1) {
throw new NoSuchElementException();
}
return getValue(i);
}
public long lookup(long key, long def) {
if (key > Integer.MAX_VALUE || key < Integer.MIN_VALUE) {
return def;
}
if (sortOnValues) {
sorted = false;
sortOnValues = false;
}
int i = findFirstEqualKeyIndex((int) key);
if (i == -1) {
return def;
}
return getValue(i);
}
public int lookup(int key, int def) {
if (sortOnValues) {
sorted = false;
sortOnValues = false;
}
int i = findFirstEqualKeyIndex(key);
if (i == -1) {
return def;
}
return getValue(i);
}
public void clear() {
removeAll();
}
public LongLookup duplicate() {
DoubleIntIndex duplicate = new DoubleIntIndex(capacity);
copyTo(duplicate);
return duplicate;
}
public int lookupFirstGreaterEqual(int key) throws NoSuchElementException {
if (sortOnValues) {
sorted = false;
sortOnValues = false;
}
int i = findFirstGreaterEqualKeyIndex(key);
if (i == -1) {
throw new NoSuchElementException();
}
return getValue(i);
}
public void setValuesSearchTarget() {
if (!sortOnValues) {
sorted = false;
}
sortOnValues = true;
}
public void setKeysSearchTarget() {
if (sortOnValues) {
sorted = false;
}
sortOnValues = false;
}
/**
* @param value the value
* @return the index
*/
public int findFirstGreaterEqualKeyIndex(int value) {
int index = findFirstGreaterEqualSlotIndex(value);
return index == count ? -1
: index;
}
/**
* @param value the value
* @return the index
*/
public int findFirstEqualKeyIndex(int value) {
if (!sorted) {
fastQuickSort();
}
targetSearchValue = value;
return binaryFirstSearch();
}
public boolean compactLookupAsIntervals() {
if (size() == 0) {
return false;
}
setKeysSearchTarget();
if (!sorted) {
fastQuickSort();
}
int base = 0;
for (int i = 1; i < count; i++) {
long limit = keys[base] + values[base];
if (limit == keys[i]) {
values[base] += values[i]; // base updated
} else {
base++;
keys[base] = keys[i];
values[base] = values[i];
}
}
for (int i = base + 1; i < count; i++) {
keys[i] = 0;
values[i] = 0;
}
if (count != base + 1) {
setSize(base + 1);
return true;
}
return false;
}
/**
* This method is similar to findFirstGreaterEqualKeyIndex(int) but
* returns the index of the empty row past the end of the array if
* the search value is larger than all the values / keys in the searched
* column.
* @param value the value
* @return the index
*/
public int findFirstGreaterEqualSlotIndex(int value) {
if (!sorted) {
fastQuickSort();
}
targetSearchValue = value;
return binarySlotSearch(false);
}
/**
* Returns the index of the lowest element == the given search target,
* or -1
* @return index or -1 if not found
*/
private int binaryFirstSearch() {
int low = 0;
int high = count;
int mid = 0;
int compare = 0;
int found = count;
while (low < high) {
mid = (low + high) >>> 1;
compare = compare(mid);
if (compare < 0) {
high = mid;
} else if (compare > 0) {
low = mid + 1;
} else {
high = mid;
found = mid;
}
}
return found == count ? -1
: found;
}
/**
* Returns the index of the lowest element >= the given search target,
* or count
* @return the index
*/
private int binarySlotSearch(boolean fullCompare) {
int low = 0;
int high = count;
int mid = 0;
int compare = 0;
while (low < high) {
mid = (low + high) >>> 1;
compare = compare(mid);
if (compare <= 0) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
/**
* Returns the index of the lowest element > the given search target
* or count or -1 if target is found
* @return the index
*/
private int binaryEmptySlotSearch() {
int low = 0;
int high = count;
int mid = 0;
int compare = 0;
while (low < high) {
mid = (low + high) >>> 1;
compare = compare(mid);
if (compare < 0) {
high = mid;
} else if (compare > 0) {
low = mid + 1;
} else {
return -1;
}
}
return low;
}
public void sortOnKeys() {
sortOnValues = false;
fastQuickSort();
}
public void sortOnValues() {
sortOnValues = true;
fastQuickSort();
}
public void sort() {
if (sortOnValues || count <= 1024 * 16) {
fastQuickSortRecursive();
} else {
fastQuickSort();
}
}
/**
* fast quicksort using a stack on the heap to reduce stack use
*/
private void fastQuickSort() {
DoubleIntIndex indices = new DoubleIntIndex(32768);
int threshold = 16;
indices.push(0, count - 1);
while (indices.size() > 0) {
int start = indices.peekKey();
int end = indices.peekValue();
indices.pop();
if (end - start >= threshold) {
int pivot = partition(start, end);
indices.push(start, pivot - 1);
indices.push(pivot + 1, end);
}
}
insertionSort(0, count - 1);
sorted = true;
}
private int partition(int start, int end) {
int pivot = (start + end) >>> 1;
// pivot is median of three values
if (keys[pivot] < keys[(start + pivot) >>> 1]) {
swap(pivot, (start + pivot) >>> 1);
}
if (keys[(end + pivot) >>> 1] < keys[(start + pivot) >>> 1]) {
swap((end + pivot) >>> 1, (start + pivot) >>> 1);
}
if (keys[(end + pivot) >>> 1] < keys[pivot]) {
swap((end + pivot) >>> 1, pivot);
}
int pivotValue = keys[pivot];
int i = start - 1;
int j = end;
swap(pivot, end);
for (;;) {
while (keys[++i] < pivotValue) {}
while (pivotValue < keys[--j]) {}
if (j < i) {
break;
}
swap(i, j);
}
swap(i, end);
return i;
}
/**
* fast quicksort with recursive quicksort implementation
*/
private void fastQuickSortRecursive() {
quickSort(0, count - 1);
insertionSort(0, count - 1);
sorted = true;
}
private void quickSort(int l, int r) {
int M = 16;
int i;
int j;
int v;
if ((r - l) > M) {
i = (r + l) >>> 1;
if (lessThan(i, l)) {
swap(l, i); // Tri-Median Method!
}
if (lessThan(r, l)) {
swap(l, r);
}
if (lessThan(r, i)) {
swap(i, r);
}
j = r - 1;
swap(i, j);
i = l;
v = j;
for (;;) {
while (lessThan(++i, v)) {}
while (lessThan(v, --j)) {}
if (j < i) {
break;
}
swap(i, j);
}
swap(i, r - 1);
quickSort(l, j);
quickSort(i + 1, r);
}
}
private void insertionSort(int lo0, int hi0) {
int i;
int j;
for (i = lo0 + 1; i <= hi0; i++) {
j = i;
while ((j > lo0) && lessThan(i, j - 1)) {
j--;
}
if (i != j) {
moveAndInsertRow(i, j);
}
}
}
protected void moveAndInsertRow(int i, int j) {
int col1 = keys[i];
int col2 = values[i];
moveRows(j, j + 1, i - j);
keys[j] = col1;
values[j] = col2;
}
protected void swap(int i1, int i2) {
int col1 = keys[i1];
int col2 = values[i1];
keys[i1] = keys[i2];
values[i1] = values[i2];
keys[i2] = col1;
values[i2] = col2;
}
/**
* Check if targeted column value in the row indexed i is less than the
* search target object.
* @param i the index
* @return -1, 0 or +1
*/
protected int compare(int i) {
if (sortOnValues) {
if (targetSearchValue > values[i]) {
return 1;
} else if (targetSearchValue < values[i]) {
return -1;
} else {
return 0;
}
}
if (targetSearchValue > keys[i]) {
return 1;
} else if (targetSearchValue < keys[i]) {
return -1;
}
return 0;
}
/**
* Check if row indexed i is less than row indexed j
* @param i the first index
* @param j the second index
* @return true or false
*/
protected boolean lessThan(int i, int j) {
if (sortOnValues) {
if (values[i] < values[j]) {
return true;
} else if (values[i] > values[j]) {
return false;
}
}
if (keys[i] < keys[j]) {
return true;
}
return false;
}
protected void moveRows(int fromIndex, int toIndex, int rows) {
System.arraycopy(keys, fromIndex, keys, toIndex, rows);
System.arraycopy(values, fromIndex, values, toIndex, rows);
}
protected void doubleCapacity() {
keys = (int[]) ArrayUtil.resizeArray(keys, capacity * 2);
values = (int[]) ArrayUtil.resizeArray(values, capacity * 2);
capacity *= 2;
}
public void removeRange(int start, int limit) {
ArrayUtil.adjustArray(ArrayUtil.CLASS_CODE_INT, keys, count, start,
start - limit);
ArrayUtil.adjustArray(ArrayUtil.CLASS_CODE_INT, values, count, start,
start - limit);
count -= (limit - start);
}
public void removeAll() {
Arrays.fill(keys, 0);
Arrays.fill(values, 0);
count = 0;
sorted = true;
}
public void copyTo(DoubleIntIndex other) {
System.arraycopy(keys, 0, other.keys, 0, count);
System.arraycopy(values, 0, other.values, 0, count);
other.setSize(count);
other.sorted = false;
}
public final void remove(int position) {
moveRows(position + 1, position, count - position - 1);
count--;
keys[count] = 0;
values[count] = 0;
}
/**
* peek the key at top of stack. Uses the data structure as a stack.
* @return int key
*/
int peekKey() {
return getKey(count - 1);
}
/**
* peek the value at top of stack
* @return int value
*/
int peekValue() {
return getValue(count - 1);
}
/**
* pop the pair at top of stack
* @return boolean if there was an element
*/
boolean pop() {
if (count > 0) {
count--;
return true;
}
return false;
}
/**
* push key, value pair
* @return boolean true if successful
*/
boolean push(int key, int value) {
return addUnsorted(key, value);
}
}
| [
"[email protected]"
] | |
f2e93ee15d96f5be5dcf611909544c45640121b5 | 91151c1711e829a5ac3b9e6e88e99422e15f1eb2 | /src/main/java/io/github/computician/enterprise/resources/Helloworld.java | f7d5690ed22d65c5d151641256ef1ce6379570c3 | [
"Apache-2.0"
] | permissive | benwtrent/javaplay | 7895acb53cd9a83818c7a9750cae3366b09b1e3f | 2aadf60e81c8e6299417007c10d905ebbaa867f9 | refs/heads/master | 2021-04-15T13:13:27.260777 | 2018-03-23T17:52:41 | 2018-03-23T17:52:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 544 | java | package io.github.computician.enterprise.resources;
import io.github.computician.enterprise.entities.subdir.subsubdir.HelloworldObjectFactoryGeneratorReallyLongEnterprisyName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@Path("/hello")
public class Helloworld {
@GET
@Path("/{who}/world")
public HelloworldObjectFactoryGeneratorReallyLongEnterprisyName world(@PathParam("who") String who) {
return new HelloworldObjectFactoryGeneratorReallyLongEnterprisyName("Hello " + who);
}
}
| [
"[email protected]"
] | |
dd29a5eae03752addba8c9841289a777153b09c2 | b1b017a9948f083f97a3e19c754af897dc2ffd27 | /tools/license-gen/java/src/licensecreation/LicenseSection.java | 821bde1eb5207d2c3306a4826f7640437e58561e | [
"Apache-2.0"
] | permissive | MIT-Informatics/LegalTags | 2571244e13e131d26339d06fbca010c78e16ff41 | 1af7cbc10a44b9e4e6e4886a57440c655eec27cc | refs/heads/master | 2020-12-02T18:05:11.686927 | 2019-09-26T01:34:12 | 2019-09-26T01:34:12 | 96,456,669 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,376 | java | package licensecreation;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Each section of the license which takes automated input has its
* own enum, which contains the placeholder to search for and replace
* in the license text, a default replacement if no terms are provided,
* and a custom {@link ListJoiner} to determine how to concatenate terms.
* @author obasi42
*/
public enum LicenseSection {
RELEVANT_LAWS ("[TERMS:RELEVANT LAWS]", "", new SimpleListJoiner("; ", "; and ", "")),
PREAMBLE ("[TERMS:PREAMBLE]", "", new SimpleListJoiner(";\n\n", "; and\n\n", ".")),
LICENSE ("[TERMS:LICENSE]", "**License.** ", new SimpleListJoiner(" ")),
DEFINITIONS ("[TERMS:DEFINITIONS]", "**Definitions.**\n\n", new SortListJoiner("\n\n")),
USE ("[TERMS:USE]", "**Restrictions on use.** The Data Recipient shall:\n\n", new SimpleListJoiner(";\n", "; and\n", ".\n").setPrefix("a) ")),
PERMITTED_USES ("[TERMS:PERMITTED USES]", "", new SimpleListJoiner("\n\n")),
CONFIDENTIALITY ("[TERMS:CONFIDENTIALITY]", "**Data confidentiality.** The Data Recipient shall:\n\n", new SimpleListJoiner(";\n", "; and\n", ".\n").setPrefix("a) ")),
IRB ("[TERMS:IRB]", "**Institutional review board (IRB).** ", new SimpleListJoiner("\n\n")),
AGENT ("[TERMS:AGENT]", "", new SimpleListJoiner("\n\n")),
SECURITY ("[TERMS:SECURITY]", "**Data security.** The Data Recipient shall:\n\n", new SimpleListJoiner(";\n", "; and\n", ".\n").setPrefix("a) ")),
BREACH_REPORTING ("[TERMS:BREACH REPORTING]", "**Data breach.** The Data Recipient shall:\n\n", new SimpleListJoiner(";\n", "; and\n", ".\n").setPrefix("a) ")),
DESTRUCTION ("[TERMS:DESTRUCTION]", "When destroying records from the Data:\n", new SimpleListJoiner("\n\n")),
SHARING ("[TERMS:SHARING]", "**Data sharing.**\n", new SimpleListJoiner("\n\n")),
ATTRIBUTION ("[TERMS:ATTRIBUTION]", "**Attribution.** ", new SimpleListJoiner("\n\n"));
/**
* Provide lookup from the placeholder string to the LicenseSection
*/
private static Map<String, LicenseSection> memo = null;
/**
* The placeholder text in the license template where we will put the terms in this section.
*/
private final String placeholder;
/**
* The heading for this section. This string should be empty if no heading is needed, otherwise it is markdown text.
*/
private final String heading;
/**
* The way that a list of strings (i.e., terms) should be combined into markdown text for inclusion in the license.
*/
private final ListJoiner listJoiner;
LicenseSection(String ph, String heading, ListJoiner listJoiner) {
this.placeholder = ph;
this.heading = heading;
this.listJoiner = listJoiner;
}
public String getPlaceholder() {
return this.placeholder;
}
public String getHeading() {
return this.heading;
}
/**
* Given a placeholder string, get the Licensesection associatged with it.
* @param ph
* @return
*/
public static synchronized LicenseSection lookup(String ph) {
if (memo == null) {
memo = new HashMap<>();
for (LicenseSection c : LicenseSection.values()) {
memo.put(c.placeholder, c);
}
}
return memo.get(ph);
}
/**
* Turns a list of terms into a Pandoc markdown formatted String, based on the license section.
* @param list
* @return
*/
public String concatenate(List<String> list) {
StringBuffer sb = new StringBuffer();
sb.append(getHeading());
this.listJoiner.join(sb, list);
return sb.toString();
}
/**
* An interface for concatenating a List of Strings.
*/
private static interface ListJoiner {
public void join(StringBuffer sb, List<String> list);
}
/**
* Simply joins a List of Strings using a separator defined in the constructor.
* Allows for one, two, or three different, case-specific separators.
*/
private static class SimpleListJoiner implements ListJoiner {
protected final String normalSeparator;
protected final String secondLastSeparator;
protected final String lastSeparator;
protected String prefix;
SimpleListJoiner(String sep) {
this.normalSeparator = sep;
this.secondLastSeparator = null;
this.lastSeparator = null;
}
SimpleListJoiner(String sep, String lastSep) {
this.normalSeparator = sep;
this.secondLastSeparator = null;
this.lastSeparator = lastSep;
}
SimpleListJoiner(String sep, String secondLastSep, String lastSep) {
this.normalSeparator = sep;
this.secondLastSeparator = secondLastSep;
this.lastSeparator = lastSep;
}
SimpleListJoiner setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public void join(StringBuffer sb, List<String> list) {
for (int i = 0; i < list.size(); i++) {
if (prefix != null) {
sb.append(prefix);
}
sb.append(list.get(i));
String sep = normalSeparator;
if (secondLastSeparator != null && i == list.size()-2) {
sep = secondLastSeparator;
}
if (lastSeparator != null && i == list.size() - 1) {
sep = lastSeparator;
}
sb.append(sep);
}
}
}
private static class SortListJoiner extends SimpleListJoiner {
public SortListJoiner(String sep) {
super(sep);
}
@Override
public void join(StringBuffer sb, List<String> list) {
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
super.join(sb, list);
}
}
}
| [
"[email protected]"
] | |
b13a7d4d516e421dbe6aca631bba9155dd82cfd4 | 47cf5b996e8f9954e5fbd989f29aad0deb3aeb9d | /springfox-bean-validators/src/main/java/springfox/bean/validators/configuration/BeanValidatorPluginsConfiguration.java | f7b4e28e553dcb1f350ae1dc06b9591d14b2f859 | [
"Apache-2.0"
] | permissive | rubencepeda/springfox | 8423883b140f033ad3bb431ddb7caf642becb658 | ec07ccaa7b525b555bbec29e5b158a449b972f57 | refs/heads/master | 2020-02-26T13:27:58.523992 | 2016-05-17T21:55:04 | 2016-05-17T21:55:04 | 59,061,667 | 0 | 0 | null | 2016-05-17T21:50:27 | 2016-05-17T21:50:27 | null | UTF-8 | Java | false | false | 1,366 | java | /*
*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package springfox.bean.validators.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.bean.validators.plugins.MinMaxAnnotationPlugin;
import springfox.bean.validators.plugins.NotNullAnnotationPlugin;
import springfox.bean.validators.plugins.SizeAnnotationPlugin;
@Configuration
public class BeanValidatorPluginsConfiguration {
@Bean
public MinMaxAnnotationPlugin minMaxPlugin() {
return new MinMaxAnnotationPlugin();
}
@Bean
public SizeAnnotationPlugin sizePlugin() {
return new SizeAnnotationPlugin();
}
@Bean
public NotNullAnnotationPlugin notNullPlugin() {
return new NotNullAnnotationPlugin();
}
}
| [
"[email protected]"
] | |
b0c1326adccd1becd7909864f02d539701d6a358 | 84b81b32c0129316aa89f0197caa587ef0f9156c | /app/src/test/java/com/sliit/get/ExampleUnitTest.java | 0b80694984e68b5dda1d3f984927d8a917f7687c | [] | no_license | davisaaron/hacking | b834ca0cde3d8ef0fd93e21bd2b81824a90e7cc9 | b00424aa732c3c3b09426e3d1f2459dbfb1adabe | refs/heads/master | 2021-07-09T06:50:54.388886 | 2021-05-04T10:28:01 | 2021-05-04T10:28:01 | 242,978,112 | 0 | 2 | null | 2021-05-04T10:28:01 | 2020-02-25T10:57:57 | Java | UTF-8 | Java | false | false | 374 | java | package com.sliit.get;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
e08313ee90ea347201c923550a1faf143c3e0092 | 2437e4d8f037ee8cc81a61e41340ea4620d50ef2 | /app/src/main/java/me/elmira/simpletwitterclient/composetweet/ComposeDialogFragment.java | 7046c5c4e1ec4919c831172bb79f0c45cbc99887 | [
"Apache-2.0"
] | permissive | Orina/TwitterClient | 92f52e524816ad98c690f9b4839edf163012fcc5 | 00b113db16a0120c90f337130e0e6964f5653f63 | refs/heads/master | 2021-01-23T04:34:27.413727 | 2017-09-20T01:07:06 | 2017-09-20T01:07:06 | 86,212,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,773 | java | package me.elmira.simpletwitterclient.composetweet;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import me.elmira.simpletwitterclient.R;
public class ComposeDialogFragment extends DialogFragment {
public static final String LOG_TAG = "ComposeDialog";
EditText bodyEditText;
Button postButton;
TextView remainingTextView;
private static final int POST_CHARS_COUNT = 140;
public interface PostTweetDialogListener {
void onTweetPost(String inputText);
}
public ComposeDialogFragment() {
}
public static ComposeDialogFragment newInstance() {
ComposeDialogFragment frag = new ComposeDialogFragment();
Bundle bundle = new Bundle();
frag.setArguments(bundle);
return frag;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return getActivity().getLayoutInflater().inflate(R.layout.fragment_compose, container);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
postButton = (Button) view.findViewById(R.id.btnTweet);
remainingTextView = (TextView) view.findViewById(R.id.tvRemainingCount);
bodyEditText = (EditText) view.findViewById(R.id.edBody);
remainingTextView.setText("" + POST_CHARS_COUNT);
postButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
composeTweet();
}
});
postButton.setEnabled(false);
bodyEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int remaining = POST_CHARS_COUNT - s.length();
remainingTextView.setText("" + remaining);
remainingTextView.setTextColor(ContextCompat.getColor(getContext(), (remaining >= 0 ? R.color.light_gray_text : R.color.colorAccent)));
postButton.setEnabled(s.length() > 0 && s.length() <= POST_CHARS_COUNT);
}
});
Dialog dialog = getDialog();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
public void composeTweet() {
((PostTweetDialogListener) getActivity()).onTweetPost(bodyEditText.getText().toString());
dismiss();
}
} | [
"[email protected]"
] | |
ba217c7506f7b1c14c5c0c8bcddc041b685bca5e | 9cdf4a803b5851915b53edaeead2546f788bddc6 | /machinelearning/5.0.x/drools-core/src/main/java/org/drools/common/TripleBetaConstraints.java | 8aca409bbdcd75d093757fad4c102bba54c99ca9 | [
"Apache-2.0"
] | permissive | kiegroup/droolsjbpm-contributed-experiments | 8051a70cfa39f18bc3baa12ca819a44cc7146700 | 6f032d28323beedae711a91f70960bf06ee351e5 | refs/heads/master | 2023-06-01T06:11:42.641550 | 2020-07-15T15:09:02 | 2020-07-15T15:09:02 | 1,184,582 | 1 | 13 | null | 2021-06-24T08:45:52 | 2010-12-20T15:42:26 | Java | UTF-8 | Java | false | false | 14,506 | java | package org.drools.common;
/*
* Copyright 2005 JBoss Inc
*
* 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.
*/
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import org.drools.RuleBaseConfiguration;
import org.drools.base.evaluators.Operator;
import org.drools.reteoo.BetaMemory;
import org.drools.reteoo.LeftTuple;
import org.drools.reteoo.LeftTupleMemory;
import org.drools.reteoo.RightTupleMemory;
import org.drools.rule.ContextEntry;
import org.drools.rule.VariableConstraint;
import org.drools.spi.BetaNodeFieldConstraint;
import org.drools.util.LeftTupleIndexHashTable;
import org.drools.util.LeftTupleList;
import org.drools.util.LinkedList;
import org.drools.util.LinkedListEntry;
import org.drools.util.RightTupleIndexHashTable;
import org.drools.util.RightTupleList;
import org.drools.util.AbstractHashTable.FieldIndex;
public class TripleBetaConstraints
implements
BetaConstraints {
/**
*
*/
private static final long serialVersionUID = 400L;
private BetaNodeFieldConstraint constraint0;
private BetaNodeFieldConstraint constraint1;
private BetaNodeFieldConstraint constraint2;
private boolean indexed0;
private boolean indexed1;
private boolean indexed2;
public TripleBetaConstraints() {
}
public TripleBetaConstraints(final BetaNodeFieldConstraint[] constraints,
final RuleBaseConfiguration conf) {
this( constraints,
conf,
false );
}
public TripleBetaConstraints(final BetaNodeFieldConstraint[] constraints,
final RuleBaseConfiguration conf,
final boolean disableIndexing) {
if ( disableIndexing || (!conf.isIndexLeftBetaMemory() && !conf.isIndexRightBetaMemory()) ) {
this.indexed0 = false;
this.indexed1 = false;
this.indexed2 = false;
} else {
final int depth = conf.getCompositeKeyDepth();
// Determine if this constraints are indexable
final boolean i0 = isIndexable( constraints[0] );
final boolean i1 = isIndexable( constraints[1] );
final boolean i2 = isIndexable( constraints[2] );
if ( depth >= 1 && i0 ) {
this.indexed0 = true;
}
if ( i1 ) {
if ( depth >= 1 && !this.indexed0 ) {
this.indexed0 = true;
swap( constraints,
1,
0 );
} else if ( depth >= 2 ) {
this.indexed1 = true;
}
}
if ( i2 ) {
if ( depth >= 1 && !this.indexed0 ) {
this.indexed0 = true;
swap( constraints,
2,
0 );
} else if ( depth >= 2 && this.indexed0 && !this.indexed1 ) {
this.indexed1 = true;
swap( constraints,
2,
1 );
} else if ( depth >= 3 ) {
this.indexed2 = true;
}
}
}
this.constraint0 = constraints[0];
this.constraint1 = constraints[1];
this.constraint2 = constraints[2];
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
constraint0 = (BetaNodeFieldConstraint)in.readObject();
constraint1 = (BetaNodeFieldConstraint)in.readObject();
constraint2 = (BetaNodeFieldConstraint)in.readObject();
indexed0 = in.readBoolean();
indexed1 = in.readBoolean();
indexed2 = in.readBoolean();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(constraint0);
out.writeObject(constraint1);
out.writeObject(constraint2);
out.writeBoolean(indexed0);
out.writeBoolean(indexed1);
out.writeBoolean(indexed2);
}
private void swap(final BetaNodeFieldConstraint[] constraints,
final int p1,
final int p2) {
final BetaNodeFieldConstraint temp = constraints[p2];
constraints[p2] = constraints[p1];
constraints[p1] = temp;
}
private boolean isIndexable(final BetaNodeFieldConstraint constraint) {
if ( constraint instanceof VariableConstraint ) {
final VariableConstraint variableConstraint = (VariableConstraint) constraint;
return (variableConstraint.getEvaluator().getOperator() == Operator.EQUAL);
} else {
return false;
}
}
/* (non-Javadoc)
* @see org.drools.common.BetaNodeConstraints#updateFromTuple(org.drools.reteoo.ReteTuple)
*/
public void updateFromTuple(final ContextEntry[] context,
final InternalWorkingMemory workingMemory,
final LeftTuple tuple) {
context[0].updateFromTuple( workingMemory,
tuple );
context[1].updateFromTuple( workingMemory,
tuple );
context[2].updateFromTuple( workingMemory,
tuple );
}
/* (non-Javadoc)
* @see org.drools.common.BetaNodeConstraints#updateFromFactHandle(org.drools.common.InternalFactHandle)
*/
public void updateFromFactHandle(final ContextEntry[] context,
final InternalWorkingMemory workingMemory,
final InternalFactHandle handle) {
context[0].updateFromFactHandle( workingMemory,
handle );
context[1].updateFromFactHandle( workingMemory,
handle );
context[2].updateFromFactHandle( workingMemory,
handle );
}
public void resetTuple(final ContextEntry[] context) {
context[0].resetTuple();
context[1].resetTuple();
context[2].resetTuple();
}
public void resetFactHandle(final ContextEntry[] context) {
context[0].resetFactHandle();
context[1].resetFactHandle();
context[2].resetFactHandle();
}
/* (non-Javadoc)
* @see org.drools.common.BetaNodeConstraints#isAllowedCachedLeft(java.lang.Object)
*/
public boolean isAllowedCachedLeft(final ContextEntry[] context,
final InternalFactHandle handle) {
// return ( this.indexed0 || this.constraint0.isAllowedCachedLeft( context0,
// object ) ) && this.constraint1.isAllowedCachedLeft( context1,
// object ) && this.constraint2.isAllowedCachedLeft( context2,
// object );
return (this.indexed0 || this.constraint0.isAllowedCachedLeft( context[0],
handle )) && (this.indexed1 || this.constraint1.isAllowedCachedLeft( context[1],
handle )) && (this.indexed2 || this.constraint2.isAllowedCachedLeft( context[2],
handle ));
}
/* (non-Javadoc)
* @see org.drools.common.BetaNodeConstraints#isAllowedCachedRight(org.drools.reteoo.ReteTuple)
*/
public boolean isAllowedCachedRight(final ContextEntry[] context,
final LeftTuple tuple) {
return this.constraint0.isAllowedCachedRight( tuple,
context[0] ) && this.constraint1.isAllowedCachedRight( tuple,
context[1] ) && this.constraint2.isAllowedCachedRight( tuple,
context[2] );
}
public boolean isIndexed() {
return this.indexed0;
}
public int getIndexCount() {
int count = 0;
if ( this.indexed0 ) {
count++;
}
if ( this.indexed1 ) {
count++;
}
if ( this.indexed2 ) {
count++;
}
return count;
}
public boolean isEmpty() {
return false;
}
public BetaMemory createBetaMemory(final RuleBaseConfiguration conf) {
BetaMemory memory;
final List list = new ArrayList( 2 );
if ( this.indexed0 ) {
final VariableConstraint variableConstraint = (VariableConstraint) this.constraint0;
final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(),
variableConstraint.getRequiredDeclarations()[0],
variableConstraint.getEvaluator() );
list.add( index );
}
if ( this.indexed1 ) {
final VariableConstraint variableConstraint = (VariableConstraint) this.constraint1;
final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(),
variableConstraint.getRequiredDeclarations()[0],
variableConstraint.getEvaluator() );
list.add( index );
}
if ( this.indexed2 ) {
final VariableConstraint variableConstraint = (VariableConstraint) this.constraint2;
final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(),
variableConstraint.getRequiredDeclarations()[0],
variableConstraint.getEvaluator() );
list.add( index );
}
if ( !list.isEmpty() ) {
final FieldIndex[] indexes = (FieldIndex[]) list.toArray( new FieldIndex[list.size()] );
LeftTupleMemory tupleMemory;
if ( conf.isIndexLeftBetaMemory() ) {
tupleMemory = new LeftTupleIndexHashTable( indexes );
} else {
tupleMemory = new LeftTupleList();
}
RightTupleMemory factHandleMemory;
if ( conf.isIndexRightBetaMemory() ) {
factHandleMemory = new RightTupleIndexHashTable( indexes );
} else {
factHandleMemory = new RightTupleList();
}
memory = new BetaMemory( conf.isSequential() ? null : tupleMemory,
factHandleMemory,
this.createContext() );
} else {
memory = new BetaMemory( conf.isSequential() ? null : new LeftTupleList(),
new RightTupleList(),
this.createContext() );
}
return memory;
}
public int hashCode() {
return this.constraint0.hashCode() ^ this.constraint1.hashCode() ^ this.constraint2.hashCode();
}
/* (non-Javadoc)
* @see org.drools.common.BetaNodeConstraints#getConstraints()
*/
public LinkedList getConstraints() {
final LinkedList list = new LinkedList();
list.add( new LinkedListEntry( this.constraint0 ) );
list.add( new LinkedListEntry( this.constraint1 ) );
list.add( new LinkedListEntry( this.constraint2 ) );
return list;
}
/**
* Determine if another object is equal to this.
*
* @param object
* The object to test.
*
* @return <code>true</code> if <code>object</code> is equal to this,
* otherwise <code>false</code>.
*/
public boolean equals(final Object object) {
if ( this == object ) {
return true;
}
if ( object == null || getClass() != object.getClass() ) {
return false;
}
final TripleBetaConstraints other = (TripleBetaConstraints) object;
if ( this.constraint0 != other.constraint0 && !this.constraint0.equals( other.constraint0 ) ) {
return false;
}
if ( this.constraint1 != other.constraint1 && !this.constraint1.equals( other.constraint1 ) ) {
return false;
}
if ( this.constraint2 != other.constraint2 && !this.constraint2.equals( other.constraint2 ) ) {
return false;
}
return true;
}
public ContextEntry[] createContext() {
return new ContextEntry[]{this.constraint0.createContextEntry(), this.constraint1.createContextEntry(), this.constraint2.createContextEntry()};
}
} | [
"[email protected]"
] | |
e746807775298cabe10c5e898aed101f55769eb1 | 17d6ba8d11c870eb1c74ba9256574f6bfcd4a359 | /src/controllers/AdminViewPatientControllerFX.java | 7d221d2009d85c0bebadb0e3f4f7185d84843d33 | [] | no_license | AditiSJadhav/Medoc_JavaProject | 6aea2d99e1959aa306c99e9594cdce0f0debb58c | 60ae2639c5e8d683e7147f7e1012b6829c204147 | refs/heads/master | 2023-04-20T10:17:53.557663 | 2021-05-20T17:33:46 | 2021-05-20T17:33:46 | 369,288,361 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,300 | java | package controllers;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.util.Callback;
import models.Patient;
import models.Patientdao;
/**
*
* Controller which manages operations and event on the ViewPatient partial page
*
*/
public class AdminViewPatientControllerFX implements Initializable {
@FXML
private AnchorPane main;
@FXML
private TableView<Patient> patientTable;
@FXML
private TableColumn<Patient, String> idCol;
@FXML
private TableColumn<Patient, String> nameCol;
@FXML
private TableColumn<Patient, String> addressCol;
@FXML
private TableColumn<Patient, String> phoneCol;
@FXML
private TableColumn<Patient, String> emailCol;
@FXML
private TableColumn<Patient, String> personidCol;
@FXML
private TextField Patient_Id;
@FXML
private TextField Patient_Name;
@FXML
private TextField Patient_Address;
@FXML
private TextField Patient_Phone;
@FXML
private TextField Patient_Email;
@FXML
private TextField Person_id;
@FXML
private Button commit;
@FXML
private Button cancel;
@FXML
private AnchorPane editPatientPane;
ObservableList<Patient> patients = FXCollections.observableArrayList();
public AdminViewPatientControllerFX() {
}
@Override
public void initialize(URL location, ResourceBundle resources) {
idCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("patient_id"));
nameCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("patient_name"));
addressCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("patient_add"));
phoneCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("patient_phone"));
emailCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("patient_email"));
personidCol.setCellValueFactory(new PropertyValueFactory<Patient, String>("uid"));
// add delete button on row
TableColumn<Patient, Boolean> col_action = new TableColumn<Patient, Boolean>("Action");
patientTable.getColumns().add(col_action);
col_action.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Patient, Boolean>, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Patient, Boolean> p) {
return new SimpleBooleanProperty(p.getValue() != null);
}
});
// Adding the Button to the cell
col_action.setCellFactory(new Callback<TableColumn<Patient, Boolean>, TableCell<Patient, Boolean>>() {
@Override
public TableCell<Patient, Boolean> call(TableColumn<Patient, Boolean> p) {
return new ButtonCell();
}
});
// bind data of the database to the table
bindData();
// edit row on click
editRow();
}
// edit row of the table on double click
private void editRow() {
patientTable.toFront();
patientTable.getSelectionModel().selectedItemProperty().addListener((obs, ov, nv) -> {
if (nv != null) {
Patient_Id.setText(String.valueOf(nv.getPatient_id()));
Patient_Name.setText(nv.getPatient_name());
Patient_Address.setText(nv.getPatient_add());
Patient_Phone.setText(nv.getPatient_phone());
Patient_Email.setText(nv.getPatient_email());
Person_id.setText(String.valueOf((nv.getUid())));
}
});
commit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
Patientdao patdao = new Patientdao();
Patient item = patientTable.getSelectionModel().getSelectedItem();
item.setPatient_id(Integer.parseInt(Patient_Id.getText()));
item.setPatient_name(Patient_Name.getText());
item.setPatient_add(Patient_Address.getText());
item.setPatient_phone(Patient_Phone.getText());
item.setPatient_email(Patient_Email.getText());
item.setUid(Integer.parseInt(Person_id.getText()));
try {
patdao.update(item);
patientTable.refresh();
showAlert(Alert.AlertType.INFORMATION, "Record Updated!",
"Patient id " + item.getPatient_id() + " is updated in the database");
}
catch (Exception e) {
showAlert(AlertType.ERROR, "Patient",
"Error occurred while updating entry, message:" + e.getMessage());
}
patientTable.toFront();
}
});
cancel.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
patientTable.toFront();
}
});
patientTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
if (evt.getClickCount() == 2) {
editPatientPane.toFront();
}
}
});
}
private void bindData() {
// DaoModel model = new DaoModel();
Patientdao Patientdao = new Patientdao();
List<Patient> resultSet = Patientdao.getRecords(new Patient());
for (Patient doc : resultSet) {
patients.add(doc);
}
patientTable.setItems(patients);
}
// Define the button cell
class ButtonCell extends TableCell<Patient, Boolean> {
final Button cellButton = new Button("Delete");
ButtonCell() {
// Action when the button is pressed
cellButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
// get Selected Item
Patient currentPerson = (Patient) ButtonCell.this.getTableView().getItems()
.get(ButtonCell.this.getIndex());
// remove selected item from the table list
patients.remove(currentPerson);
Patient pat = new Patient();
Patientdao patdao = new Patientdao();
pat.setPatient_id(currentPerson.getPatient_id());
try {
patdao.delete(pat);
patientTable.refresh();
showAlert(Alert.AlertType.INFORMATION, "Record deleted!",
"Patient id " + currentPerson.getPatient_id() + " is deleted from the database");
}
catch (Exception e) {
showAlert(AlertType.ERROR, "Patient",
"Error occurred while deleting entry, message:" + e.getMessage());
}
}
});
cellButton.getStyleClass().add("danger");
}
// Display button if the row is not empty
@Override
protected void updateItem(Boolean t, boolean empty) {
super.updateItem(t, empty);
if (!empty) {
setGraphic(cellButton);
}
}
}
public void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.show();
}
} | [
"[email protected]"
] | |
11cdcf4570bb855182951c1ed1d8e5b1352d9bdc | ab4c6ac52952fbf1332cb3fe39afcb1f2e0e7e9b | /app/src/main/java/com/example/dxc/xfdemo/view/LoadingDialog.java | 54531b694f7119b4755784e69973da071d965015 | [] | no_license | In-Heart/XFDemo | e7595d96a72298c4d222fe0bc744c43f2471c178 | 9b5c7f8f8257f496fa5aaeaf23a71e8aeb1caf0a | refs/heads/master | 2022-12-23T14:21:01.613276 | 2020-09-23T08:55:03 | 2020-09-23T08:55:03 | 114,955,438 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,107 | java | package com.example.dxc.xfdemo.view;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import com.example.dxc.xfdemo.R;
/**
* @Class:
* @Description:
* @Author: haitaow([email protected])
* @Date: 4/1/2018-7:26 PM.
* @Version 1.0
*/
public class LoadingDialog extends Dialog{
private String loadingText = "";
public LoadingDialog(Context context) {
super(context, R.style.LoadingDialogStyle);
}
private LoadingDialog(Context context, int theme) {
super(context, theme);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_loadingdialog);
TextView tv = (TextView)this.findViewById(R.id.textView);
tv.setText(loadingText);
// LinearLayout linearLayout = (LinearLayout)this.findViewById(R.id.LinearLayout);
// linearLayout.getBackground().setAlpha(210);
}
public void setLoadingText(String loadingText) {
this.loadingText = loadingText;
}
}
| [
"[email protected]"
] | |
ee08bb15ff7a7ec3b83fbf6367813bbe2032b075 | 006be2dd903340b19a4ce39264dfdaf5fbc671cd | /core/src/hu/hdani1337/marancsicsDash/ParentClasses/Scene2D/MultiSpriteActor.java | c2c6af6021b0fc97e92236007cbbaaeba40942ea | [
"MIT"
] | permissive | hdani1337/MarancsicsDash | b81bcf5b89668e199043cc43e311ec8d1f1cca03 | e41febc5f742013a5258d457a61ae011b8b787ea | refs/heads/master | 2020-04-22T12:43:04.864077 | 2019-12-08T12:36:37 | 2019-12-08T12:36:37 | 170,382,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,658 | java | package hu.hdani1337.marancsicsDash.ParentClasses.Scene2D;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import hu.hdani1337.marancsicsDash.ParentClasses.Game.InitableInterface;
import java.util.Collection;
import java.util.HashMap;
/**
* Created by M on 12/14/2017.
*/
public abstract class MultiSpriteActor extends MyActor implements InitableInterface {
protected HashMap<String, OffsetSprite> spriteMap = new HashMap<String, OffsetSprite>();
public static int debugLineNumbers = 16;
public MultiSpriteActor(float width, float height) {
super();
super.setWidth(width);
super.setHeight(height);
init();
}
/* OffsetSprite... olyam mint egy tömb de simán fel lehet sorolni a paramétereket. Nincs fix hossza.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs */
public MultiSpriteActor(float width, float height, OffsetSprite... offsetSprites) {
super();
super.setWidth(width);
super.setHeight(height);
for (OffsetSprite spite: offsetSprites) {
addSprite(spite);
}
init();
}
/* OffsetSprite... olyam mint egy tömb de simán fel lehet sorolni a paramétereket. Nincs fix hossza.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs */
public MultiSpriteActor(float width, float height, ShapeType shapeType, OffsetSprite... offsetSprites) {
super();
super.setWidth(width);
super.setHeight(height);
for (OffsetSprite spite: offsetSprites) {
addSprite(spite, shapeType);
}
init();
}
@Override
public void act(float delta) {
super.act(delta);
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
for (OffsetSprite sprite: spriteMap.values()) {
if (sprite.visible) {
sprite.draw(batch);
}
}
}
/*
@Override
protected void sizeChanged() {
super.sizeChanged();
for (OffsetSprite sprite: spriteMap.values()) {
sprite.setOrigin(getOriginX() - sprite.getOffsetVector().x, getOriginY() - sprite.getOffsetVector().y);
}
}
*/
@Override
public void setSize(float width, float height) {
float w = width / getWidth();
float h = height / getHeight();
for (OffsetSprite sprite : spriteMap.values()) {
//System.out.println(sprite.getOriginX()*w);
sprite.setSize(sprite.getWidth() * w, sprite.getHeight() * h);
sprite.getOffsetVector().x *= w;
sprite.getOffsetVector().y *= h;
//sprite.setOrigin(sprite.getOriginX()*w, sprite.getOriginY()*h);
}
//setOrigin(getOriginX()*w, getOriginY()*h);
positionChanged();
super.setSize(width, height);
}
@Override
public void setHeight(float height) {
setSize(getWidth(),height);
}
@Override
public void setWidth(float width) {
setSize(width, getHeight());
}
@Override
protected void positionChanged() {
super.positionChanged();
for (OffsetSprite sprite: spriteMap.values()) {
sprite.setPosition(getX() + sprite.getOffsetVector().x, getY() + sprite.getOffsetVector().y);
}
}
@Override
protected void originChanged() {
super.originChanged();
for (OffsetSprite sprite: spriteMap.values()) {
//System.out.println(getOriginX());
sprite.setOrigin(getOriginX() - sprite.getOffsetVector().x, getOriginY() - sprite.getOffsetVector().y);
}
}
@Override
protected void rotationChanged() {
super.rotationChanged();
for (OffsetSprite sprite: spriteMap.values()) {
sprite.setRotation(getRotation());
}
}
public void addSprite(OffsetSprite sprite) {
spriteMap.put("Sprite"+ spriteMap.size(), sprite);
sprite.setPosition(getX() + sprite.getOffsetVector().x, getY() + sprite.getOffsetVector().y);
sprite.setOrigin(getOriginX() - sprite.getOffsetVector().x, getOriginY() - sprite.getOffsetVector().y);
}
public void addSprite(OffsetSprite sprite, ShapeType shapeType){
addSprite(sprite, "Sprite"+ spriteMap.size(), shapeType);
}
public void addSprite(OffsetSprite sprite, String key) {
spriteMap.put(key, sprite);
sprite.setPosition(getX() + sprite.getOffsetVector().x, getY() + sprite.getOffsetVector().y);
sprite.setOrigin(getOriginX() - sprite.getOffsetVector().x, getOriginY() - sprite.getOffsetVector().y);
}
public void addSprite(OffsetSprite sprite, String key, ShapeType shapeType){
spriteMap.put(key, sprite);
sprite.setPosition(getX() + sprite.getOffsetVector().x, getY() + sprite.getOffsetVector().y);
sprite.setOrigin(getOriginX() - sprite.getOffsetVector().x, getOriginY() - sprite.getOffsetVector().y);
if (shapeType == ShapeType.Rectangle) {
addCollisionShape(key, new MyRectangle(sprite.getWidth(), sprite.getHeight(), sprite.getOffsetVector().x, sprite.getOffsetVector().y, getOriginX(), getOriginY(), getRotation(), sprite.getRotation(), getX(), getY(), true));
}
if (shapeType == ShapeType.Circle) {
addCollisionShape(key, new MyCircle((float)Math.sqrt(sprite.getWidth() * sprite.getHeight())/2.0f, sprite.getOffsetVector().x, sprite.getOffsetVector().y, getOriginX(), getOriginY(), getX(), getY(), true));
}
}
public void changeSprite(String key, OffsetSprite sprite){
for(OffsetSprite offsetSprite : spriteMap.values()){
if(getSprite(key)==offsetSprite){
float y = offsetSprite.getY();
float x = offsetSprite.getX();
float height = offsetSprite.getHeight();
float width = offsetSprite.getWidth();
offsetSprite.set(sprite);
offsetSprite.setSize(width, height);
offsetSprite.setPosition(x,y);
}
}
}
public boolean removeSprite(String key) {
if(spriteMap.containsKey(key)){
//System.out.println("removing sprite");
spriteMap.remove(key);
return true;
}
return false;
}
public OffsetSprite getSprite(String key ){
if(spriteMap.containsKey(key)) return spriteMap.get(key);
else return null;
}
public HashMap<String, OffsetSprite> getSpritesMap() {
return spriteMap;
}
public Collection<OffsetSprite> getSprites(){
return spriteMap.values();
}
@Override
protected void drawDebugBounds(ShapeRenderer shapes) {
super.drawDebugBounds(shapes);
if (spriteMap != null) {
for (OffsetSprite sprite: spriteMap.values()) {
//float w = (int)(0.8f + (float)Math.sin(elapsedTime * 10f)/5f+0.2f);
//System.out.println(elapsedTime);
if (((int)((elapsedTime)*5))%2 ==0 && sprite.visible)
{
Color c = new Color(Color.MAGENTA);
shapes.setColor(c);
drawDebugLines(sprite.getCorners(), shapes);
//shapes.setColor(Color.ORANGE);
shapes.circle(sprite.getOriginX() + sprite.getX(), sprite.getOriginY() + sprite.getY(), getWidth() / debugPointSize, 5);
}
}
}
}
}
| [
"[email protected]"
] | |
4ff57348c18e99b88108e4724cbc6ba7d5edf296 | bf0b198c8b0adb6c3231b7d33fc6e0f58d8e3202 | /src/pang/insert_student_ui.java | ebf032dd74c53f3171893296c213aebddb20072e | [] | no_license | pangtongtong/--XD | cec1696b67af1f32317b81acc9e0efb782b84d19 | d99e04994ee9eef33e778fe37bef5069602a03ba | refs/heads/master | 2021-03-18T02:10:44.193280 | 2020-03-13T09:51:32 | 2020-03-13T09:51:32 | 247,037,976 | 1 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,054 | java | package pang;
import java.awt.BorderLayout;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Scrollable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class insert_student_ui extends JFrame implements ActionListener{
private JButton insert_button;
private JButton back_button;
private JPanel jp1;
private DefaultTableModel defaultTableModel;
private JTable table;
private JScrollPane sPane;
public insert_student_ui() {
insert_button = new JButton("插入");
back_button = new JButton("返回");
String [] columnNames = {"学号","班号","姓名","年龄","性别"};
String [][] rows = {{"","","","",""}};
table = new JTable(rows,columnNames);
sPane = new JScrollPane(table);
jp1 = new JPanel();
insert_button.addActionListener(this);
back_button.addActionListener(this);
jp1.add(insert_button);
jp1.add(back_button);
this.setLayout(new BorderLayout());
this.setTitle("插入学生信息");
this.setSize(600, 400);
this.setLocation(200, 300);
this.add(jp1,BorderLayout.WEST);
this.add(sPane);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource()==insert_button) {
String [] row = new String[5];
for(int i=0;i<5;i++) {
row[i] = (String) table.getValueAt(table.getSelectedRow(),i);
}
try {
insert_student.insert(row[0], row[1], row[2],Integer.parseInt(row[3]), row[4]);
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "插入失败,该数据可能已在数据库中", "警告", JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
}
}
else if(event.getSource()==back_button) {
dispose();
new UI();
}
}
}
| [
"[email protected]"
] | |
16109105520be659be51300051f4c5ae09d35be7 | 0d7220b4a680f220e04ecad46d51b6532d90bf64 | /dev/nuker/pyro/faL.java | feebb2814097d4f3072b911de395ea4b97937153 | [] | no_license | HelpMopDog/PyroClient-Deobf | d2816bd39de7a792748e52e7b1de611b9fe07473 | 23cdef6fed8ae19025757c076f2147fbb9816802 | refs/heads/main | 2023-08-28T01:57:25.423834 | 2021-10-23T03:16:53 | 2021-10-23T03:16:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 761 | java | /**
* Obfuscator: Binsecure Decompiler: FernFlower
* De-obfuscated by Gopro336
*/
package dev.nuker.pyro;
import java.util.function.Consumer;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
public class faL implements Consumer {
// $FF: renamed from: c dev.nuker.pyro.faN
public faN field_1477;
public void accept(Object var1) {
this.method_2653((f0w)var1);
}
// $FF: renamed from: c (dev.nuker.pyro.f0w) void
public void method_2653(@NotNull f0w var1) {
this.field_1477.method_116((Boolean)this.field_1477.c.method_3034(), (EntityPlayerSP)null, (World)null);
}
public faL(faN var1) {
this.field_1477 = var1;
super();
}
}
| [
"[email protected]"
] | |
9c4755d670e1dfb7d71761cb5da791364ad7f7b3 | 9be7a8876fa7bbe84301e9fc92503fc408ac0133 | /homework04/homework04/src/main/java/com/kubrafelek/homework04/Homework04Application.java | b6c8dfa41baee55b72546730fdfb7874a42688dd | [
"MIT"
] | permissive | kubrafelek/Gittigidiyor-Spring-Bootcamp | c320f4be1ce6042e696a85039ee9c3ab82798022 | bde2f49d3b6cf3eae0b4efaf99f8a75efa20dd06 | refs/heads/main | 2023-08-04T16:56:48.057130 | 2021-09-15T16:42:08 | 2021-09-15T16:42:08 | 405,196,875 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 423 | java | package com.kubrafelek.homework04;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class Homework04Application {
public static void main(String[] args) {
SpringApplication.run(Homework04Application.class, args);
}
}
| [
"[email protected]"
] | |
2b6442f0ede39d5a2a0ba96f3c27bc08199230be | 625d782abb119993a10fd336b3d06cf7d321a824 | /app/src/main/java/com/example/bazarbaba/checksum.java | c6ab5d2c1a67b284a3fdf9b4261003dd95150ef0 | [] | no_license | archisman-dey/BazarBaba2 | 526d0dc3907a590a0f584878ee827b46a7dce227 | 7365af8d66bb90ef0bd4a7768bb214c82fa5acd1 | refs/heads/master | 2020-08-22T15:54:16.933456 | 2019-10-20T21:48:35 | 2019-10-20T21:48:35 | 216,430,931 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,483 | java | package com.example.bazarbaba;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Parcelable;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Created by kamal_bunkar on 15-01-2019.
*/
public class checksum extends AppCompatActivity implements PaytmPaymentTransactionCallback {
String custid="", orderId="", mid="";
private String uid,dil="";
private boolean dib=false;
private Double s;
private List<Product_details> itemList,cartList;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(checksum.this);
//initOrderId();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent intent = getIntent();
uid=intent.getStringExtra("uid");
// int n = 100000 + random_float() * 900000;
int n = 10000 + new Random().nextInt(90000);
orderId =String.valueOf(n) ;
cartList=intent.getParcelableArrayListExtra("List");
s=intent.getDoubleExtra("cost",0);
dil=intent.getStringExtra("dil");
dib=intent.getBooleanExtra("dib",false);
//s=(double)1;
Log.e("sum ", Double.toString(s));
custid = intent.getStringExtra("uid");
mid = "ScXwUW43791690584123"; /// your marchant key
sendUserDetailTOServerdd dl = new sendUserDetailTOServerdd();
dl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// vollye , retrofit, asynch
}
public class sendUserDetailTOServerdd extends AsyncTask<ArrayList<String>, Void, String> {
private ProgressDialog dialog = new ProgressDialog(checksum.this);
//private String orderId , mid, custid, amt;
String url ="https://bazarbaba.000webhostapp.com/generateChecksum.php";
String varifyurl = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";
// "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID"+orderId;
String CHECKSUMHASH ="";
@Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected String doInBackground(ArrayList<String>... alldata) {
JSONParser jsonParser = new JSONParser(checksum.this);
String param=
"MID="+mid+
"&ORDER_ID=" + orderId+
"&CUST_ID="+custid+
"&CHANNEL_ID=WAP&TXN_AMOUNT="+Double.toString(s)+"&WEBSITE=DEFAULT"+
"&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";
JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
// yaha per checksum ke saht order id or status receive hoga..
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.e("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return CHECKSUMHASH;
}
@Override
protected void onPostExecute(String result) {
Log.e(" setup acc "," signup result " + result);
if (dialog.isShowing()) {
dialog.dismiss();
}
PaytmPGService Service = PaytmPGService.getProductionService();
// when app is ready to publish use production service
// PaytmPGService Service = PaytmPGService.getProductionService();
// now call paytm service here
//below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
HashMap<String, String> paramMap = new HashMap<String, String>();
//these are mandatory parameters
paramMap.put("MID", mid); //MID provided by paytm
paramMap.put("ORDER_ID", orderId);
paramMap.put("CUST_ID", custid);
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("TXN_AMOUNT", Double.toString(s));
paramMap.put("WEBSITE", "DEFAULT");
paramMap.put("CALLBACK_URL" ,varifyurl);
//paramMap.put( "EMAIL" , "[email protected]"); // no need
// paramMap.put( "MOBILE_NO" , "9144040888"); // no need
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
//paramMap.put("PAYMENT_TYPE_ID" ,"CC"); // no need
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
PaytmOrder Order = new PaytmOrder(paramMap);
Log.e("checksum ", "param "+ paramMap.toString());
Service.initialize(Order,null);
// start payment service call here
Service.startPaymentTransaction(checksum.this, true, true,
checksum.this );
}
}
@Override
public void onTransactionResponse(Bundle bundle) {
Log.e("checksum ", " respon true " + bundle.toString());
// progressDialog=new ProgressDialog(this);
// progressDialog.setMessage("Loading...");
// progressDialog.show();
// progressDialog.setCancelable(false);
// progressDialog.setCanceledOnTouchOutside(false);
FirebaseFirestore db = FirebaseFirestore.getInstance();
Map<String, Object> city = new HashMap<>();
city.put("uid", uid);
city.put("orderlist", cartList);
city.put("curstatus",0);
city.put("status","Your order is being processed...");
city.put("delivery address",dil);
// city.put("")
db.collection("Orders").document(orderId)
.set(city)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("abc", "DocumentSnapshot successfully written!");
Intent intent=new Intent(checksum.this,conformation.class);
// Bundle bundle=new Bundle();
// bundle.putParcelableArray();
// progressDialog.hide();
intent.putExtra("uid",uid);
intent.putExtra("orderid",orderId);
intent.putExtra("dil",dil);
intent.putExtra("dib",dib);
intent.putParcelableArrayListExtra("List",(ArrayList< ? extends Parcelable >)cartList);
// intent.putParcelableArrayListExtra("List",(ArrayList< ? extends Parcelable>)cartList);
// intent.putExtra("uemail",uemail);
startActivity(intent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w("abc", "Error writing document", e);
}
});
}
@Override
public void networkNotAvailable() {
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void clientAuthenticationFailed(String s) {
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void someUIErrorOccurred(String s) {
Log.e("checksum ", " ui fail respon "+ s );
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onErrorLoadingWebPage(int i, String s, String s1) {
Log.e("checksum ", " error loading pagerespon true "+ s + " s1 " + s1);
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onBackPressedCancelTransaction() {
Log.e("checksum ", " cancel call back respon " );
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onTransactionCancel(String s, Bundle bundle) {
Log.e("checksum ", " transaction cancel " );
Toast.makeText(getApplicationContext(),"Transaction Failed Please Retry", Toast.LENGTH_SHORT).show();
finish();
}
} | [
"[email protected]"
] | |
ed7f30a28d44f6def0721d4898beebf3b775b156 | 300c48be93911b238587c3c0e963948b61627638 | /megadesk-recipes/src/main/java/com/liveramp/megadesk/recipes/gear/worker/NaiveWorker.java | 23859dbd7815ded26bda95c62d69f977d1587c6d | [] | no_license | conglei/megadesk | a22ffa15a48440887b20bded021dde0edb3e5577 | 36d08dca34d54abc9913f14b56425244a502bedd | refs/heads/master | 2021-01-22T23:20:38.507871 | 2014-01-26T22:34:50 | 2014-01-26T22:34:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,726 | java | /**
* Copyright 2014 LiveRamp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liveramp.megadesk.recipes.gear.worker;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.log4j.Logger;
import com.liveramp.megadesk.core.transaction.Binding;
import com.liveramp.megadesk.recipes.gear.BaseGearExecutor;
import com.liveramp.megadesk.recipes.gear.Gear;
import com.liveramp.megadesk.recipes.gear.GearExecutor;
import com.liveramp.megadesk.recipes.gear.Outcome;
public class NaiveWorker extends BaseWorker implements Worker {
private static final Logger LOG = Logger.getLogger(NaiveWorker.class);
private final List<BoundGear> gears;
private final Thread executor;
private boolean stopping = false;
public NaiveWorker() {
gears = Lists.newArrayList();
executor = new Thread(new ExecutorRunnable(), this + " executor");
executor.start();
}
@Override
public void run(Gear gear, Binding binding) {
synchronized (gears) {
gears.add(new BoundGear(gear, binding));
}
}
@Override
public void stop() {
stopping = true;
}
@Override
public void join() throws InterruptedException {
executor.join();
}
private class ExecutorRunnable implements Runnable {
private static final long SLEEP_PERIOD_MS = 100;
private final GearExecutor gearExecutor = new BaseGearExecutor();
@Override
public void run() {
while (true) {
synchronized (gears) {
if (stopping && gears.isEmpty()) {
return;
}
Iterator<BoundGear> it = gears.iterator();
while (it.hasNext()) {
BoundGear gear = it.next();
try {
Outcome outcome = gearExecutor.execute(gear.gear(), gear.binding());
if (outcome == Outcome.ABANDON) {
it.remove();
}
} catch (Exception e) {
LOG.error(e); // TODO
throw new RuntimeException(e); // TODO
}
}
}
try {
Thread.sleep(SLEEP_PERIOD_MS);
} catch (InterruptedException e) {
return;
}
}
}
}
}
| [
"[email protected]"
] | |
78a19c3266ba1a0f6803777a82fa10da25201977 | 1d461d829bcd1451f64b4447918ed817bab3516f | /src/com/timexautoweb/domain/EmployeeHome.java | 4de8815069121891a3281f5cee59de0cc99d9a36 | [] | no_license | alvaroe/timex_java | 8f5e5d47148aa2b43b674329e4d1bce4d976cad4 | a63723a5dde6d5d4bbba838f542efbf1b86414f4 | refs/heads/master | 2021-01-01T05:14:07.702391 | 2014-04-25T01:06:43 | 2014-04-25T01:06:43 | 58,427,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,030 | java | package com.timexautoweb.domain;
// Generated Feb 13, 2013 6:38:59 PM by Hibernate Tools 3.4.0.CR1
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import com.timexautoweb.util.HibernateUtil;
/**
* Home object for domain model class Employee.
*
* @see .Employee
* @author Hibernate Tools
*/
public class EmployeeHome {
private static final Log log = LogFactory.getLog(EmployeeHome.class);
protected SessionFactory getSessionFactory() {
try {
return HibernateUtil.getSessionFactory();
} catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
public void persist(Employee transientInstance) {
log.debug("persisting Employee instance");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.persist(transientInstance);
log.debug("persist successful");
session.getTransaction().commit();
} catch (RuntimeException re) {
log.error("persist failed", re);
session.getTransaction().rollback();
throw re;
}
}
public void attachDirty(Employee instance) {
log.debug("attaching dirty Employee instance");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.saveOrUpdate(instance);
log.debug("attach successful");
session.getTransaction().commit();
} catch (RuntimeException re) {
log.error("attach failed", re);
session.getTransaction().rollback();
throw re;
}
}
public void attachClean(Employee instance) {
log.debug("attaching clean Employee instance");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.lock(instance, LockMode.NONE);
log.debug("attach successful");
session.getTransaction().commit();
} catch (RuntimeException re) {
log.error("attach failed", re);
session.getTransaction().rollback();
throw re;
}
}
public void delete(Employee persistentInstance) {
log.debug("deleting Employee instance");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.delete(persistentInstance);
log.debug("delete successful");
session.getTransaction().commit();
} catch (RuntimeException re) {
log.error("delete failed", re);
session.getTransaction().rollback();
throw re;
}
}
public Employee merge(Employee detachedInstance) {
log.debug("merging Employee instance");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
Employee result = (Employee) session.merge(detachedInstance);
log.debug("merge successful");
session.getTransaction().commit();
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
session.getTransaction().rollback();
throw re;
}
}
public Employee findById(java.lang.Integer id) {
log.debug("getting Employee instance with id: " + id);
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
Employee instance = (Employee) getSessionFactory().getCurrentSession().get(
"com.timexautoweb.domain.Employee", id);
session.getTransaction().commit();
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
try {
session.getTransaction().rollback();
} catch (HibernateException he) {
}
throw re;
}
}
public List findByExample(Employee instance) {
log.debug("finding Employee instance by example");
Session session = getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
List results = session.createCriteria(Employee.class).add(Example.create(instance))
.list();
log.debug("find by example successful, result size: " + results.size());
session.getTransaction().commit();
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
session.getTransaction().rollback();
throw re;
}
}
/**
* Returns list of all employees.
*/
@SuppressWarnings("unchecked")
public List<Employee> getAllEmployees() {
List<Employee> employeeList = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
employeeList = session.createQuery("from Employee ORDER BY name").list();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return employeeList;
}
/**
* Returns list of all Employee records reporting to Employee with given
* employeeId.
*/
@SuppressWarnings("unchecked")
public List<Employee> getReportingEmployees(int employeeId) {
List<Employee> employeeList = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
employeeList = session.createQuery("from Employee WHERE managerEmployeeId = ? ORDER BY name")
.setInteger(0, employeeId).list();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return employeeList;
}
/**
* Returns list of all managers and executives.
*/
@SuppressWarnings("unchecked")
public List<Employee> getManagers() {
List<Employee> managersList = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
managersList = session.createQuery(
"from Employee WHERE employeeCode='" + Employee.MANAGER + "' OR employeeCode='"
+ Employee.EXECUTIVE + "' ORDER BY name").list();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return managersList;
}
/**
* Returns Employee with the given user name passed as a parameter.
*
*/
@SuppressWarnings("unchecked")
public Employee findByUsername(String userName) {
Employee employee = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
employee = (Employee) session.createQuery("from Employee WHERE username = ?").setString(0, userName)
.uniqueResult();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return employee;
}
}
| [
"alvaro@3ed9dff2-893a-d44d-aa01-dc056e061ce7"
] | alvaro@3ed9dff2-893a-d44d-aa01-dc056e061ce7 |
221619f267ecbdddb0684f9c9be63853ec708368 | d1a6d1e511df6db8d8dd0912526e3875c7e1797d | /genny_JavaWithoutLambdasApi21/applicationModule/src/test/java/applicationModulepackageJava15/Foo962Test.java | 9c970ed2a71d60319609da99511db06dbe949dc4 | [] | no_license | NikitaKozlov/generated-project-for-desugaring | 0bc1443ab3ddc84cd289331c726761585766aea7 | 81506b3711004185070ca4bb9a93482b70011d36 | refs/heads/master | 2020-03-20T00:35:06.996525 | 2018-06-12T09:30:37 | 2018-06-12T09:30:37 | 137,049,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 482 | java | package applicationModulepackageJava15;
import org.junit.Test;
public class Foo962Test {
@Test
public void testFoo0() {
new Foo962().foo0();
}
@Test
public void testFoo1() {
new Foo962().foo1();
}
@Test
public void testFoo2() {
new Foo962().foo2();
}
@Test
public void testFoo3() {
new Foo962().foo3();
}
@Test
public void testFoo4() {
new Foo962().foo4();
}
@Test
public void testFoo5() {
new Foo962().foo5();
}
}
| [
"[email protected]"
] | |
62f4ecff730bd997b9719735f1afb76b7cea5d82 | eb97ee5d4f19d7bf028ae9a400642a8c644f8fe3 | /tags/2010-02-27/seasar2-2.4.41/s2jdbc-gen/s2jdbc-gen/src/main/java/org/seasar/extension/jdbc/gen/internal/command/GenerateEntityTestCommand.java | 45dcb21ddf3630105e24f3edac50a5c826740547 | [
"Apache-2.0"
] | permissive | svn2github/s2container | 54ca27cf0c1200a93e1cb88884eb8226a9be677d | 625adc6c4e1396654a7297d00ec206c077a78696 | refs/heads/master | 2020-06-04T17:15:02.140847 | 2013-08-09T09:38:15 | 2013-08-09T09:38:15 | 10,850,644 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 18,206 | java | /*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* 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 org.seasar.extension.jdbc.gen.internal.command;
import java.io.File;
import org.seasar.extension.jdbc.EntityMeta;
import org.seasar.extension.jdbc.gen.command.Command;
import org.seasar.extension.jdbc.gen.generator.GenerationContext;
import org.seasar.extension.jdbc.gen.generator.Generator;
import org.seasar.extension.jdbc.gen.internal.exception.RequiredPropertyNullRuntimeException;
import org.seasar.extension.jdbc.gen.internal.util.FileUtil;
import org.seasar.extension.jdbc.gen.meta.EntityMetaReader;
import org.seasar.extension.jdbc.gen.model.ClassModel;
import org.seasar.extension.jdbc.gen.model.EntityTestModel;
import org.seasar.extension.jdbc.gen.model.EntityTestModelFactory;
import org.seasar.extension.jdbc.gen.model.NamesModelFactory;
import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ClassUtil;
/**
* エンティティに対するテストクラスのJavaファイルを生成する{@link Command}の実装です。
* <p>
* このコマンドは、エンティティクラスのメタデータからテストクラスのJavaファイルを生成します。 そのため、
* コマンドを実行するにはエンティティクラスを参照できるようにエンティティクラスが格納されたディレクトリをあらかじめクラスパスに設定しておく必要があります。
* また、そのディレクトリは、プロパティ{@link #classpathDir}に設定しておく必要があります。
* </p>
* <p>
* このコマンドは、エンティティクラス1つにつき1つのテストクラスのJavaファイルを生成します。
* </p>
*
* @author taedium
*/
public class GenerateEntityTestCommand extends AbstractCommand {
/** ロガー */
protected static Logger logger = Logger
.getLogger(GenerateEntityTestCommand.class);
/** クラスパスのディレクトリ */
protected File classpathDir;
/** ルートパッケージ名 */
protected String rootPackageName = "";
/** エンティティパッケージ名 */
protected String entityPackageName = "entity";
/** 対象とするエンティティクラス名の正規表現 */
protected String entityClassNamePattern = ".*";
/** 対象としないエンティティクラス名の正規表現 */
protected String ignoreEntityClassNamePattern = "";
/** テストクラス名のサフィックス */
protected String testClassNameSuffix = "Test";
/** テストクラスでS2JUnit4を使用する場合{@code true}、S2Unitを使用する場合{@code false} */
protected boolean useS2junit4;
/** テストクラスのテンプレート名 */
protected String templateFileName = "java/entitytest.ftl";
/** テンプレートファイルのエンコーディング */
protected String templateFileEncoding = "UTF-8";
/** テンプレートファイルを格納するプライマリディレクトリ */
protected File templateFilePrimaryDir = null;
/** 名前クラスを使用する場合{@code true} */
protected boolean useNamesClass = true;
/** 名前クラス名のサフィックス */
protected String namesClassNameSuffix = "Names";
/** 名前クラスのパッケージ名 */
protected String namesPackageName = "entity";
/** 生成するJavaファイルの出力先ディレクトリ */
protected File javaFileDestDir = new File(new File("src", "test"), "java");
/** Javaファイルのエンコーディング */
protected String javaFileEncoding = "UTF-8";
/** 上書きをする場合{@code true}、しない場合{@code false} */
protected boolean overwrite = false;
/** エンティティメタデータのリーダ */
protected EntityMetaReader entityMetaReader;
/** テストのモデルのファクトリ */
protected EntityTestModelFactory entityTestModelFactory;
/** 名前モデルのファクトリ */
protected NamesModelFactory namesModelFactory;
/** ジェネレータ */
protected Generator generator;
/**
* テストクラス名のサフィックスを返します。
*
* @return テストクラス名のサフィックス
*/
public String getTestClassNameSuffix() {
return testClassNameSuffix;
}
/**
* テストクラス名のサフィックスを設定します。
*
* @param testClassNameSuffix
* テストクラス名のサフィックス
*/
public void setTestClassNameSuffix(String testClassNameSuffix) {
this.testClassNameSuffix = testClassNameSuffix;
}
/**
* エンティティのパッケージ名を返します。
*
* @return エンティティのパッケージ名
*/
public String getEntityPackageName() {
return entityPackageName;
}
/**
* エンティティのパッケージ名を設定します。
*
* @param entityPackageName
* エンティティのパッケージ名
*/
public void setEntityPackageName(String entityPackageName) {
this.entityPackageName = entityPackageName;
}
/**
* 対象とするエンティティクラス名の正規表現を返します。
*
* @return 対象とするエンティティクラス名の正規表現
*/
public String getEntityClassNamePattern() {
return entityClassNamePattern;
}
/**
* 対象とするエンティティクラス名の正規表現を設定します。
*
* @param entityClassNamePattern
* 対象とするエンティティクラス名の正規表現
*/
public void setEntityClassNamePattern(String entityClassNamePattern) {
this.entityClassNamePattern = entityClassNamePattern;
}
/**
* 対象としないエンティティクラス名の正規表現を返します。
*
* @return 対象としないエンティティクラス名の正規表現
*/
public String getIgnoreEntityClassNamePattern() {
return ignoreEntityClassNamePattern;
}
/**
* 対象としないエンティティクラス名の正規表現を設定します。
*
* @param ignoreEntityClassNamePattern
* 対象としないエンティティクラス名の正規表現
*/
public void setIgnoreEntityClassNamePattern(
String ignoreEntityClassNamePattern) {
this.ignoreEntityClassNamePattern = ignoreEntityClassNamePattern;
}
/**
* テストクラスのテンプレート名を返します。
*
* @return テストクラスのテンプレート名
*/
public String getTemplateFileName() {
return templateFileName;
}
/**
* テストクラスのテンプレート名を設定します。
*
* @param templateFileName
* テストクラスのテンプレート名
*/
public void setTemplateFileName(String templateFileName) {
this.templateFileName = templateFileName;
}
/**
* 生成するJavaファイルの出力先ディレクトリを返します。
*
* @return 生成するJavaファイルの出力先ディレクトリ
*/
public File getJavaFileDestDir() {
return javaFileDestDir;
}
/**
* 生成するJavaファイルの出力先ディレクトリを設定します。
*
* @param javaFileDestDir
* 生成するJavaファイルの出力先ディレクトリ
*/
public void setJavaFileDestDir(File javaFileDestDir) {
this.javaFileDestDir = javaFileDestDir;
}
/**
* Javaファイルのエンコーディングを返します。
*
* @return Javaファイルのエンコーディング
*/
public String getJavaFileEncoding() {
return javaFileEncoding;
}
/**
* Javaファイルのエンコーディングを設定します。
*
* @param javaFileEncoding
* Javaファイルのエンコーディング
*/
public void setJavaFileEncoding(String javaFileEncoding) {
this.javaFileEncoding = javaFileEncoding;
}
/**
* 上書きをする場合{@code true}、しない場合{@code false}を返します。
*
* @return 上書きをする場合{@code true}、しない場合{@code false}
*/
public boolean isOverwrite() {
return overwrite;
}
/**
* 上書きをする場合{@code true}、しない場合{@code false}を設定します。
*
* @param overwrite
* 上書きをする場合{@code true}、しない場合{@code false}
*/
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
/**
* ルートパッケージ名を設定します。
*
* @return ルートパッケージ名
*/
public String getRootPackageName() {
return rootPackageName;
}
/**
* ルートパッケージ名を返します。
*
* @param rootPackageName
* ルートパッケージ名
*/
public void setRootPackageName(String rootPackageName) {
this.rootPackageName = rootPackageName;
}
/**
* テンプレートファイルのエンコーディングを返します。
*
* @return テンプレートファイルのエンコーディング
*/
public String getTemplateFileEncoding() {
return templateFileEncoding;
}
/**
* テンプレートファイルのエンコーディングを設定します。
*
* @param templateFileEncoding
* テンプレートファイルのエンコーディング
*/
public void setTemplateFileEncoding(String templateFileEncoding) {
this.templateFileEncoding = templateFileEncoding;
}
/**
* テンプレートファイルを格納するプライマリディレクトリを返します。
*
* @return テンプレートファイルを格納するプライマリディレクトリ
*/
public File getTemplateFilePrimaryDir() {
return templateFilePrimaryDir;
}
/**
* テンプレートファイルを格納するプライマリディレクトリを設定します。
*
* @param templateFilePrimaryDir
* テンプレートファイルを格納するプライマリディレクトリ
*/
public void setTemplateFilePrimaryDir(File templateFilePrimaryDir) {
this.templateFilePrimaryDir = templateFilePrimaryDir;
}
/**
* クラスパスのディレクトリを返します。
*
* @return クラスパスのディレクトリ
*/
public File getClasspathDir() {
return classpathDir;
}
/**
* クラスパスのディレクトリを設定します。
*
* @param classpathDir
* クラスパスのディレクトリ
*/
public void setClasspathDir(File classpathDir) {
this.classpathDir = classpathDir;
}
/**
* テストクラスでS2JUnit4を使用する場合{@code true}、S2Unitを使用する場合{@code false}を返します。
*
* @return テストクラスでS2JUnit4を使用する場合{@code true}、S2Unitを使用する場合{@code false}
*/
public boolean isUseS2junit4() {
return useS2junit4;
}
/**
* テストクラスでS2JUnit4を使用する場合{@code true}、S2Unitを使用する場合{@code false}を設定します。
*
* @param useS2junit4
* テストクラスでS2JUnit4を使用する場合{@code true}、S2Unitを使用する場合{@code false}
*/
public void setUseS2junit4(boolean useS2junit4) {
this.useS2junit4 = useS2junit4;
}
/**
* 名前クラス名のサフィックスを返します。
*
* @return 名前クラス名のサフィックス
*/
public String getNamesClassNameSuffix() {
return namesClassNameSuffix;
}
/**
* 名前クラス名のサフィックスを設定します。
*
* @param namesClassNameSuffix
* 名前クラス名のサフィックス
*/
public void setNamesClassNameSuffix(String namesClassNameSuffix) {
this.namesClassNameSuffix = namesClassNameSuffix;
}
/**
* 名前クラスのパッケージ名を返します。
*
* @return 名前クラスのパッケージ名
*/
public String getNamesPackageName() {
return namesPackageName;
}
/**
* 名前クラスのパッケージ名を設定します。
*
* @param namesPackageName
* 名前クラスのパッケージ名
*/
public void setNamesPackageName(String namesPackageName) {
this.namesPackageName = namesPackageName;
}
/**
* 名前クラスを使用する場合{@code true}、しない場合{@code false}を返します。
*
* @return 名前クラスを使用する場合{@code true}、しない場合{@code false}
*/
public boolean isUseNamesClass() {
return useNamesClass;
}
/**
* 名前クラスを使用する場合{@code true}、しない場合{@code false}を設定します。
*
* @param useNamesClass
* 名前クラスを使用する場合{@code true}、しない場合{@code false}
*/
public void setUseNamesClass(boolean useNamesClass) {
this.useNamesClass = useNamesClass;
}
@Override
protected void doValidate() {
if (classpathDir == null) {
throw new RequiredPropertyNullRuntimeException("classpathDir");
}
}
/**
* 初期化します。
*/
@Override
protected void doInit() {
entityMetaReader = createEntityMetaReader();
namesModelFactory = createNamesModelFactory();
entityTestModelFactory = createEntityTestModelFactory();
generator = createGenerator();
}
@Override
protected void doExecute() {
for (EntityMeta entityMeta : entityMetaReader.read()) {
generateTest(entityMeta);
}
}
@Override
protected void doDestroy() {
}
/**
* テストクラスのJavaファイルを生成します。
*
* @param entityMeta
* エンティティメタデータ
*/
protected void generateTest(EntityMeta entityMeta) {
EntityTestModel entityTestModel = entityTestModelFactory
.getEntityTestModel(entityMeta);
GenerationContext context = createGenerationContext(entityTestModel,
templateFileName);
generator.generate(context);
}
/**
* {@link EntityMetaReader}の実装を作成します。
*
* @return {@link EntityMetaReader}の実装
*/
protected EntityMetaReader createEntityMetaReader() {
return factory.createEntityMetaReader(this, classpathDir, ClassUtil
.concatName(rootPackageName, entityPackageName), jdbcManager
.getEntityMetaFactory(), entityClassNamePattern,
ignoreEntityClassNamePattern, false, null, null);
}
/**
* {@link NamesModelFactory}の実装を作成します。
*
* @return {@link NamesModelFactory}の実装
*/
protected NamesModelFactory createNamesModelFactory() {
return factory.createNamesModelFactory(this, ClassUtil.concatName(
rootPackageName, namesPackageName), namesClassNameSuffix);
}
/**
* {@link EntityTestModelFactory}の実装を作成します。
*
* @return {@link EntityTestModelFactory}の実装
*/
protected EntityTestModelFactory createEntityTestModelFactory() {
return factory.createEntityTestModelFactory(this, configPath,
jdbcManagerName, testClassNameSuffix, namesModelFactory,
useNamesClass, useS2junit4);
}
/**
* {@link Generator}の実装を作成します。
*
* @return {@link Generator}の実装
*/
protected Generator createGenerator() {
return factory.createGenerator(this, templateFileEncoding,
templateFilePrimaryDir);
}
/**
* {@link GenerationContext}の実装を作成します。
*
* @param model
* モデル
* @param templateName
* テンプレート名
* @return {@link GenerationContext}の実装
*/
protected GenerationContext createGenerationContext(ClassModel model,
String templateName) {
File file = FileUtil.createJavaFile(javaFileDestDir, model
.getPackageName(), model.getShortClassName());
return factory.createGenerationContext(this, model, file, templateName,
javaFileEncoding, overwrite);
}
@Override
protected Logger getLogger() {
return logger;
}
}
| [
"koichik@319488c0-e101-0410-93bc-b5e51f62721a"
] | koichik@319488c0-e101-0410-93bc-b5e51f62721a |
8e010d8298cd6007051ff034ed7398950c542d9a | 71d2e973cc67f252ee631852b9b35e124dca6e4e | /app/src/main/java/com/darshan/tutorial08/DatabaseHelper.java | a23a937763e3ad3658c069dcb82c6aec0c4512bc | [] | no_license | akadarshan/Android-Tutorial-08 | 3cf8bf09c2798097b0920f6c730c8e51f828fc07 | 00d52f7415175c22acfc6854250c61827ab32b79 | refs/heads/master | 2022-12-17T12:57:43.912049 | 2020-09-20T16:05:02 | 2020-09-20T16:05:02 | 297,110,646 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,875 | java | package com.darshan.tutorial08;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="student.db";
public static final String TABLE_NAME="Registration";
public static final String COL_1="ID";
public static final String COL_2="FNAME";
public static final String COL_3="LNAME";
public static final String COL_4="EMAIL";
public static final String COL_5="PASSWORD";
public static final String COL_6="CEIT";
public static final String COL_7="GENDER";
public static final String COL_8="CITY";
public static final String COL_9="STATUS";
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ TABLE_NAME +" (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ COL_2 +" TEXT, "+ COL_3 +" TEXT, " + COL_4 + " TEXT, "+ COL_5 +" TEXT, "+ COL_6 +" TEXT, "+ COL_7 + " TEXT, "+ COL_8 + " TEXT, "+ COL_9 + " TEXT)");
}
public boolean InsertData(String fname,String lname,String email,String password,String ceit,String gender,String city,String status){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_2,fname);
values.put(COL_3,lname);
values.put(COL_4,email);
values.put(COL_5,password);
values.put(COL_6,ceit);
values.put(COL_7,gender);
values.put(COL_8,city);
values.put(COL_9,status);
return db.insert(TABLE_NAME,null,values) != -1;
}
public boolean duplicate_user(String email) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
new String[]{COL_4},
"email=?",
new String[]{email},
null,
null,
null
);
return ((cursor != null && cursor.getCount() > 0) ? true : false);
}
public boolean checkUserExist(String email, String password){
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_4, COL_5}, "email=? and password=?", new String[]{email, password}, null, null, null);
int count = cursor.getCount();
cursor.close();
close();
return count > 0;
}
public ArrayList<String> getUserList() {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
new String[]{COL_4},
null,
null,
null,
null,
null
);
ArrayList<String> list = new ArrayList<String>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return list;
}
public Cursor getSingleUserDetail(String userdata) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
null,
"email=?",
new String[]{userdata},
null,
null,
null
);
return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
| [
"[email protected]"
] | |
0e8d82ab84adc9710ddfec146755e0fe67583936 | d92e1c1a13e1a2211fdc12d47cbc7ef12fde75e9 | /src/org/spireader/zlibrary/core/drm/embedding/EmbeddingInputStream.java | e64819d1c9b42d0c0ab66c02f01c5765f00c71af | [] | no_license | PhieF/spireader | 32741edfbb5de07ba540c234c801b4dcd57d5d9e | 259f7f8aaa94fba899cc20904f981dc47fcba7d8 | refs/heads/master | 2021-08-22T22:11:32.405007 | 2017-12-01T12:15:27 | 2017-12-01T12:15:27 | 112,736,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,021 | java | /*
* Copyright (C) 2007-2015 FBReader.ORG Limited <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.spireader.zlibrary.core.drm.embedding;
import java.io.InputStream;
import java.io.IOException;
import java.security.MessageDigest;
import org.spireader.zlibrary.core.util.InputStreamWithOffset;
public class EmbeddingInputStream extends InputStreamWithOffset {
private final byte[] myKey;
public EmbeddingInputStream(InputStream base, String uid) throws IOException {
super(base);
try {
myKey = MessageDigest.getInstance("SHA").digest(uid.getBytes("utf-8"));
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public int read() throws IOException {
final int o = offset();
final int bt = super.read();
if (bt == -1) {
return -1;
}
return o > 1040 ? bt : ((bt ^ myKey[o % myKey.length]) & 0xFF);
}
@Override
public int read(byte[] buffer, int bOffset, int bCount) throws IOException {
final int o = offset();
final int len = super.read(buffer, bOffset, bCount);
if (o < 1040) {
final int e = Math.min(1040 - o, len);
for (int c = 0; c < e; ++c) {
buffer[bOffset + c] ^= myKey[(o + c) % myKey.length];
}
}
return len;
}
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
}
| [
"[email protected]"
] | |
a883e1b420b7a1b65bfa017d18a597c17a03b206 | c3f27897b5659345ed6018148b0313eb0f74f80a | /344-Reverse-String/solution.java | 6478cef4015689790c22b8f198133f26e286ff42 | [] | no_license | benjiyue/PersonalProjects | a4dd56b3ecc83fac5d1a1800a01dc0b812c851ef | df0b6e5f14526fb5352e2a5f81d656f86ddfebe4 | refs/heads/master | 2021-01-19T05:01:09.694868 | 2016-12-26T15:35:00 | 2016-12-26T15:35:00 | 66,719,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 298 | java | public class Solution {
public String reverseString(String s) {
char[] c = s.toCharArray();
for(int i=0;i<s.length()/2;i++){
char temp = c[i];
c[i] = c[s.length()-1-i];
c[s.length()-1-i] = temp;
}
return new String(c);
}
} | [
"[email protected]"
] | |
2104b1eb4339161bff88dba85c2865a867bc26e7 | b7936f9a99afb096bc6d68448c32631d7416e177 | /build/tmp/recompileMc/sources/net/minecraft/world/storage/loot/LootContext.java | 4d40b08bfc306aaf19c968f196c99df9cefa3808 | [] | no_license | AlphaWolf21/JATMA | ff786893893879d1f158a549659bbf13a5e0763c | 93cf49cca9e23fa1660099999b2b46ce26fb3bbb | refs/heads/master | 2021-01-19T02:43:34.989869 | 2016-11-07T04:06:16 | 2016-11-07T04:06:16 | 73,483,501 | 2 | 0 | null | 2016-11-11T14:20:06 | 2016-11-11T14:20:05 | null | UTF-8 | Java | false | false | 5,040 | java | package net.minecraft.world.storage.loot;
import com.google.common.collect.Sets;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.DamageSource;
import net.minecraft.world.WorldServer;
public class LootContext
{
private final float luck;
private final WorldServer worldObj;
private final LootTableManager lootTableManager;
@Nullable
private final Entity lootedEntity;
@Nullable
private final EntityPlayer player;
@Nullable
private final DamageSource damageSource;
private final Set<LootTable> lootTables = Sets.<LootTable>newLinkedHashSet();
public LootContext(float luckIn, WorldServer worldIn, LootTableManager lootTableManagerIn, @Nullable Entity lootedEntityIn, @Nullable EntityPlayer playerIn, @Nullable DamageSource damageSourceIn)
{
this.luck = luckIn;
this.worldObj = worldIn;
this.lootTableManager = lootTableManagerIn;
this.lootedEntity = lootedEntityIn;
this.player = playerIn;
this.damageSource = damageSourceIn;
}
@Nullable
public Entity getLootedEntity()
{
return this.lootedEntity;
}
@Nullable
public Entity getKillerPlayer()
{
return this.player;
}
@Nullable
public Entity getKiller()
{
return this.damageSource == null ? null : this.damageSource.getEntity();
}
public boolean addLootTable(LootTable lootTableIn)
{
return this.lootTables.add(lootTableIn);
}
public void removeLootTable(LootTable lootTableIn)
{
this.lootTables.remove(lootTableIn);
}
public LootTableManager getLootTableManager()
{
return this.lootTableManager;
}
public float getLuck()
{
return this.luck;
}
@Nullable
public Entity getEntity(LootContext.EntityTarget target)
{
switch (target)
{
case THIS:
return this.getLootedEntity();
case KILLER:
return this.getKiller();
case KILLER_PLAYER:
return this.getKillerPlayer();
default:
return null;
}
}
public WorldServer getWorld()
{
return worldObj;
}
public static class Builder
{
private final WorldServer worldObj;
private float luck;
private Entity lootedEntity;
private EntityPlayer player;
private DamageSource damageSource;
public Builder(WorldServer worldIn)
{
this.worldObj = worldIn;
}
public LootContext.Builder withLuck(float luckIn)
{
this.luck = luckIn;
return this;
}
public LootContext.Builder withLootedEntity(Entity entityIn)
{
this.lootedEntity = entityIn;
return this;
}
public LootContext.Builder withPlayer(EntityPlayer playerIn)
{
this.player = playerIn;
return this;
}
public LootContext.Builder withDamageSource(DamageSource dmgSource)
{
this.damageSource = dmgSource;
return this;
}
public LootContext build()
{
return new LootContext(this.luck, this.worldObj, this.worldObj.getLootTableManager(), this.lootedEntity, this.player, this.damageSource);
}
}
public static enum EntityTarget
{
THIS("this"),
KILLER("killer"),
KILLER_PLAYER("killer_player");
private final String targetType;
private EntityTarget(String type)
{
this.targetType = type;
}
public static LootContext.EntityTarget fromString(String type)
{
for (LootContext.EntityTarget lootcontext$entitytarget : values())
{
if (lootcontext$entitytarget.targetType.equals(type))
{
return lootcontext$entitytarget;
}
}
throw new IllegalArgumentException("Invalid entity target " + type);
}
public static class Serializer extends TypeAdapter<LootContext.EntityTarget>
{
public void write(JsonWriter p_write_1_, LootContext.EntityTarget p_write_2_) throws IOException
{
p_write_1_.value(p_write_2_.targetType);
}
public LootContext.EntityTarget read(JsonReader p_read_1_) throws IOException
{
return LootContext.EntityTarget.fromString(p_read_1_.nextString());
}
}
}
} | [
"[email protected]"
] | |
c4a2facc0f54ef5466303c48e9d8fc145a4697ca | 03d61086047f041168f9a77b02a63a9af83f0f3f | /newrelic/src/main/java/com/newrelic/agent/deps/com/google/common/util/concurrent/ListeningExecutorService.java | 9afa724715ea3def01a3f0bfad88c77566ad322b | [] | no_license | masonmei/mx2 | fa53a0b237c9e2b5a7c151999732270b4f9c4f78 | 5a4adc268ac1e52af1adf07db7a761fac4c83fbf | refs/heads/master | 2021-01-25T10:16:14.807472 | 2015-07-30T21:49:33 | 2015-07-30T21:49:35 | 39,944,476 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | //
// Decompiled by Procyon v0.5.29
//
package com.newrelic.agent.deps.com.google.common.util.concurrent;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Future;
import java.util.List;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
public interface ListeningExecutorService extends ExecutorService
{
<T> ListenableFuture<T> submit(Callable<T> p0);
ListenableFuture<?> submit(Runnable p0);
<T> ListenableFuture<T> submit(Runnable p0, T p1);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> p0) throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> p0, long p1, TimeUnit p2) throws InterruptedException;
}
| [
"[email protected]"
] | |
427b9f0306df2e924fdb0fb6a87ac0437c4afafa | 3a072155199ffa44e85d78f9d90b682731eb8121 | /Java/Topic5/1/testpackage/Foundation.java | 2a7f45ece7190b3f599c351521d561501db9abb7 | [] | no_license | ArunkumarSennimalai/java-assignment | 4de199e2cabaae88efdc51fd1cd48070cc507e9e | 3629cccee77cbed3622b5ad93d56c6f96519480f | refs/heads/master | 2022-07-18T03:11:17.028830 | 2020-05-20T06:03:17 | 2020-05-20T06:03:17 | 265,465,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 338 | java | package testpackage;
public class Foundation
{
private int var1;
int var2;
protected int var3;
public int var4;
Foundation()
{
}
Foundation(int var1,int var2,int var3,int var4)
{
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
}
| [
"[email protected]"
] | |
44f87ae77ce95cd937ab05388d8c0bbe2f81d311 | 61b2d0e7043932479ab88b36a4ff86db20985cec | /wear/src/main/java/com/example/shahnaz/beatwatch/HeartbeatService.java | 17cbf1dddb1f82154b825b7e0cb25bb75e9cea81 | [] | no_license | Shahnazps/HeartBeatWatchApp | 45b6f579f95dca2d958e20916ac863d38cd37dd7 | 34a7f22e9678dc5e40ed27cbd1171e5e908047e6 | refs/heads/master | 2020-03-10T17:59:48.098474 | 2018-04-14T12:16:20 | 2018-04-14T12:16:20 | 129,514,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,719 | java | package com.example.shahnaz.beatwatch;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.util.List;
public class HeartbeatService extends Service implements SensorEventListener {
private SensorManager mSensorManager;
private int currentValue=0;
private static final String LOG_TAG = "MyHeart";
private IBinder binder = new HeartbeatServiceBinder();
private OnChangeListener onChangeListener;
private GoogleApiClient mGoogleApiClient;
// interface to pass a heartbeat value to the implementing class
public interface OnChangeListener {
void onValueChanged(int newValue);
}
/**
* Binder for this service. The binding activity passes a listener we send the heartbeat to.
*/
public class HeartbeatServiceBinder extends Binder {
public void setChangeListener(OnChangeListener listener) {
onChangeListener = listener;
// return currently known value
listener.onValueChanged(currentValue);
// listener.onValueChanged(60);
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
// register us as a sensor listener
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
// delay SENSOR_DELAY_UI is sufficiant
boolean res = mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_UI);
Log.d(LOG_TAG, " sensor registered: " + (res ? "yes" : "no"));
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
@Override
public void onDestroy() {
super.onDestroy();
mSensorManager.unregisterListener(this);
Log.d(LOG_TAG," sensor unregistered");
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
// is this a heartbeat event and does it have data?
if(sensorEvent.sensor.getType()==Sensor.TYPE_HEART_RATE && sensorEvent.values.length>0 ) {
int newValue = Math.round(sensorEvent.values[0]);
// int newValue = 60;
//Log.d(LOG_TAG,sensorEvent.sensor.getName() + " changed to: " + newValue);
// only do something if the value differs from the value before and the value is not 0.
if(currentValue != newValue && newValue!=0) {
// save the new value
currentValue = newValue;
// send the value to the listener
if(onChangeListener!=null) {
Log.d(LOG_TAG,"sending new value to listener: " + newValue);
onChangeListener.onValueChanged(newValue);
sendMessageToHandheld(Integer.toString(newValue));
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
/**
* sends a string message to the connected handheld using the google api client (if available)
* @param message
*/
private void sendMessageToHandheld(final String message) {
if (mGoogleApiClient == null)
return;
Log.d(LOG_TAG,"sending a message to handheld: "+message);
// use the api client to send the heartbeat value to our handheld
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
@Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, null);
}
}
}
});
}
}
| [
"[email protected]"
] | |
7b70a483bf779c1c5b0dbe2bf1112f0941544b5c | 452305662c1b4c2a3261f7348309cba5d6f58c67 | /myapp6/src/main/java/com/example/myapp6/MainActivity.java | 8d5de43526b89b8d9f1d50de1199fd9465ef3c3d | [] | no_license | jmw93/myfirstapp4 | 594529883e22331e86fd3c3fbc8a0a90bdfaff71 | aebed64ac319c796fbf4a0c0d9e82ccf42e8f636 | refs/heads/master | 2020-05-07T22:25:14.640388 | 2019-04-12T06:15:42 | 2019-04-12T06:15:42 | 180,944,535 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package com.example.myapp6;
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);
}
}
| [
"[email protected]"
] | |
1aeab497ff0a766aa3fc1ea10df3e51705a47c24 | 0354a384325d8c243ff183017b143be46a314d62 | /spring-boot-jpa-lock/src/main/java/cn/mariojd/jpa/lock/service/TeacherService.java | c0d56e1ed387853903b489e40e1fb77e4d613213 | [] | no_license | hetingde/spring-boot-learning | bb66e1d4912a5691fc5db545a75c2b690b8ee8d5 | 1c663d2dd56564fe22abf404005daf84200583e1 | refs/heads/master | 2023-02-18T05:38:29.939304 | 2020-06-07T13:42:09 | 2020-06-07T13:42:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,957 | java | package cn.mariojd.jpa.lock.service;
import cn.mariojd.jpa.lock.entity.Teacher;
import cn.mariojd.jpa.lock.repository.TeacherRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* @author Jared
* @date 2019/1/14 15:42
*/
@Slf4j
@Service
public class TeacherService {
@Resource
private TeacherRepository teacherRepository;
/**
* 新增教师
*
* @param teacher
*/
@Transactional
public Teacher add(Teacher teacher) {
return teacherRepository.save(teacher);
}
/**
* 悲观锁①:更新教师
*
* @param teacher
* @param sleepMillis
*/
@Transactional
public void pessimisticLock(Teacher teacher, long sleepMillis) {
teacherRepository.findById(teacher.getId()).ifPresent(t -> {
log.info(t.toString());
t.setName("Pessimistic Lock: " + t.getName() + " Sleep millis: " + sleepMillis);
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
teacherRepository.save(t);
});
}
/**
* 悲观锁②:更新教师
*
* @param teacher
* @param sleepMillis
*/
@Transactional
public void pessimisticLock2(Teacher teacher, long sleepMillis) {
teacherRepository.findTeacherForUpdate(teacher.getId()).ifPresent(t -> {
log.info(t.toString());
t.setName("Pessimistic Lock2: " + t.getName() + " Sleep millis: " + sleepMillis);
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
teacherRepository.save(t);
});
}
}
| [
"[email protected]"
] | |
8a2911a72cde3704a3be60c3c36c2cee049f13bf | 43bc71c15ae56de3d99b0404e4f9c6ea95f3fc05 | /src/bai_3_mang_va_phuong_thuc_trong_java/thuc_hanh/UngDungDemSoLuongSVThiDo.java | 5566e6295a3ceba760831a014bd7683bd28ebc45 | [] | no_license | sontra2611/C0321G1_NguyenDinhSonTra_Module_2 | 086b2a0f09cf4f66af71edac1e4dffc85f455a6b | 5307695c3488933da70ef0da45d5b1b085e63bcd | refs/heads/master | 2023-05-10T13:00:27.376323 | 2021-06-04T08:30:05 | 2021-06-04T08:30:05 | 363,975,429 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,048 | java | package bai_3_mang_va_phuong_thuc_trong_java.thuc_hanh;
import java.util.Scanner;
public class UngDungDemSoLuongSVThiDo {
public static void main(String[] args) {
int size;
int[] array;
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter a size:");
size = scanner.nextInt();
if (size > 30)
System.out.println("Size should not exceed 30");
} while (size > 30);
array = new int[size];
int i = 0;
while (i < array.length) {
System.out.print("Enter a mark for student " + (i + 1) + ": ");
array[i] = scanner.nextInt();
i++;
}
int count = 0;
System.out.print("List of mark: ");
for (int j = 0; j < array.length; j++) {
System.out.print(array[j] + "\t");
if (array[j] >= 5 && array[j] <= 10)
count++;
}
System.out.print("\n The number of students passing the exam is " + count);
}
}
| [
"[email protected]"
] | |
48c062acaa241ad3992234ffc9e3a53dcd1b4a83 | 58d5e23ca9f9bb0dd6e951d147f6f625476ab1ce | /LeetCodeWeekly/April3/415.java | 00b0721a1c16d1afe6197d5c568c8ce8d5f6fa4b | [] | no_license | zhan2209/Algorithm | 9449e5bc8f3a9dacea73e66b5ef9cf7038ace5a7 | f72ab6122be255bad8e682bc035cefa1864d0656 | refs/heads/master | 2021-06-01T13:54:39.779118 | 2020-09-14T00:24:15 | 2020-09-14T00:24:15 | 93,651,338 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,338 | java | class Solution {
public String addStrings(String nums1, String nums2) {
StringBuilder sb = new StringBuilder();
int i = nums1.length() - 1;
int j = nums2.length() - 1;
int flag = 0;
while( i >= 0 || j >= 0){
if( i >=0 && j >= 0 ){
sb.append((Character.getNumericValue(nums1.charAt(i))
+ flag
+ Character.getNumericValue(nums2.charAt(j))) % 10 );
flag = ( Character.getNumericValue(nums1.charAt(i))
+ Character.getNumericValue(nums2.charAt(j)) + flag)/10;
i--;
j--;
}
if( i >= 0 && j < 0){
sb.append((Character.getNumericValue(nums1.charAt(i)) + flag) % 10);
flag = (flag + Character.getNumericValue(nums1.charAt(i))) / 10;
i--;
}
if(i < 0 && j >= 0 ){
sb.append((Character.getNumericValue(nums2.charAt(j)) + flag) % 10);
flag = (flag + Character.getNumericValue(nums2.charAt(j))) / 10;
j--;
}
}
if(flag > 0){
sb.append(flag);
}
return sb.reverse().toString();
}
} | [
"[email protected]"
] | |
528cd4517425ad530e32c22bd134ef64be092902 | 9b2f68d6af27b0def7a294b604db25c4a81f38f6 | /src/main/java/bammerbom/ultimatecore/sponge/modules/ban/commands/IpCommand.java | 84bf83379eb9ad9630cc34487b751217de893d34 | [
"MIT"
] | permissive | JonathanBrouwer/UltimateCore | 29a7b8bcad2f1271ebeca5e69593728f61b791a0 | 35537cd4b5c4b4cc9a13295955e880ebb0b8ac37 | refs/heads/master | 2022-01-23T14:38:57.843270 | 2019-03-30T08:33:32 | 2019-03-30T08:33:32 | 20,760,008 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,572 | java | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.sponge.modules.ban.commands;
import bammerbom.ultimatecore.sponge.UltimateCore;
import bammerbom.ultimatecore.sponge.api.command.HighPermCommand;
import bammerbom.ultimatecore.sponge.api.command.annotations.CommandInfo;
import bammerbom.ultimatecore.sponge.api.command.annotations.CommandPermissions;
import bammerbom.ultimatecore.sponge.api.command.argument.arguments.GameprofileArgument;
import bammerbom.ultimatecore.sponge.api.config.defaultconfigs.datafiles.PlayerDataFile;
import bammerbom.ultimatecore.sponge.api.language.utils.Messages;
import bammerbom.ultimatecore.sponge.api.permission.PermissionLevel;
import bammerbom.ultimatecore.sponge.modules.ban.BanModule;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.text.Text;
@CommandInfo(module = BanModule.class, aliases = {"ip"})
@CommandPermissions(level = PermissionLevel.MOD)
public class IpCommand implements HighPermCommand {
@Override
public CommandElement[] getArguments() {
return new CommandElement[]{new GameprofileArgument(Text.of("player"))};
}
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
String ip;
GameProfile profile = args.<GameProfile>getOne("player").get();
if (UltimateCore.get().getUserService().getUser(profile).get().getUser().isOnline()) {
Player p = UltimateCore.get().getUserService().getUser(profile).get().getUser().getPlayer().get();
ip = p.getConnection().getAddress().getAddress().toString().replace("/", "");
} else {
PlayerDataFile config = new PlayerDataFile(profile.getUniqueId());
CommentedConfigurationNode node = config.get();
ip = node.getNode("lastip").getString();
}
Messages.send(src, "ban.command.ip.success", "%player%", profile.getName().orElse(""), "%ip%", ip);
return CommandResult.success();
}
}
| [
"[email protected]"
] | |
76ee091a58520cc270aaf82bbf2e7db00432eaa4 | 6b4047f51fabb18169e0030024871ddbfb0fe306 | /app/src/main/java/com/coolweather/android/service/AutoUpdateService.java | e26ccd6b3f1f4bd99b1d0a2e412ee2a27fad2c27 | [
"Apache-2.0"
] | permissive | qrwds/coolweathor | 17cc21bf8d4201ce08e0c072540bce11dd3f69a8 | ab8e0141778229032058759c6181cc3387353b5a | refs/heads/master | 2020-03-14T09:58:49.876504 | 2018-06-18T13:40:30 | 2018-06-18T13:40:30 | 131,556,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,704 | java | package com.coolweather.android.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.media.MediaMetadataCompat;
import android.util.Log;
import android.widget.Toast;
import com.coolweather.android.CoolweatherAppWidgetReceiver;
import com.coolweather.android.WeatherActivity;
import com.coolweather.android.db.AddCity;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.gson.WeatherCond;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AutoUpdateService extends Service {
private boolean flag=false;
private boolean isRequestWeather=false;
private boolean isRequestWeatherCond=false;
private boolean isError=false;
public AutoUpdateService() {
}
@Override
public void onCreate() {
/*AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=3*60*60*1000;
long triggerAtTime= SystemClock.elapsedRealtime()+anHour;
Intent i=new Intent(this,AutoUpdateService.class);
PendingIntent pi=PendingIntent.getService(this,0,i,0);
manager.cancel(pi);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);*/
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
//updateWeatherCond();
// updateWeather();
//updateBingPic();
updateAddCity();
// try{ Thread.sleep(3000);}catch (Exception e){}
Intent intent1 = new Intent(CoolweatherAppWidgetReceiver.UPDATE_ACTION);
this.sendBroadcast(intent1);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int anHour = 3 * 60 * 60 * 1000;
long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
Intent i = new Intent(this, AutoUpdateService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
manager.cancel(pi);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent,flags,startId);
}
private void updateWeatherCond() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weatherCond", null);
if (weatherString != null) {
WeatherCond weatherCond = Utility.handlerWeatherNowResponse(weatherString);
String weatherId = weatherCond.basic.weatherId;
String weatherUrl = "https://free-api.heweather.com/s6/weather/now?location=" + weatherId + "&key=f360abdf1f8a43e8bbb77cd68a3e8977";
HttpUtil.sendOkHttpResquest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final WeatherCond weatherCond = Utility.handlerWeatherNowResponse(responseText);
if (weatherCond != null && "ok".equals(weatherCond.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weatherCond", responseText);
editor.apply();
}
}
});
}
}
private void updateWeather() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
if (weatherString!= null) {
Weather weather=Utility.handlerWeatherResponse(weatherString);
String weatherId = weather.basic.weatherId;
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=f360abdf1f8a43e8bbb77cd68a3e8977";
HttpUtil.sendOkHttpResquest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handlerWeatherResponse(responseText);
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weather", responseText);
editor.apply();
AddCity addCity = new AddCity();
addCity.setResponseText(responseText);
addCity.updateAll("cityname=?",weather.basic.cityName);
}
}
});
}
}
private void updateAddCity(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weatherCond", null);
if (weatherString!=null) {
List<AddCity> addCityList= DataSupport.findAll(AddCity.class);
WeatherCond weatherCond = Utility.handlerWeatherNowResponse(weatherString);
final String weatherNowId = weatherCond.basic.weatherId;
for (AddCity addCity : addCityList) {
final String weatherId = addCity.getWeatherId();
String weatherUrl = "https://free-api.heweather.com/s6/weather/now?location=" + weatherId + "&key=f360abdf1f8a43e8bbb77cd68a3e8977";
HttpUtil.sendOkHttpResquest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
isError=true;
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final WeatherCond weatherCond = Utility.handlerWeatherNowResponse(responseText);
if (weatherCond != null && "ok".equals(weatherCond.status)) {
if (weatherNowId.equals(weatherId)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weatherCond", responseText);
editor.apply();
}
AddCity addCity = new AddCity();
addCity.setWeatherInfo(weatherCond.now.weatherInfo);
addCity.setWeatherTmp(weatherCond.now.tmp);
addCity.setResponseCondText(responseText);
addCity.updateAll("cityname=?", weatherCond.basic.cityName);
Intent i1 = new Intent("com.coolweather.android.LOCAL_BROADCAST_UPDATE_SHOW");
LocalBroadcastManager.getInstance(AutoUpdateService.this).sendBroadcast(i1);
//Log.d("auto_update","ok");
}
}
});
String weatherUrl1 = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=f360abdf1f8a43e8bbb77cd68a3e8977";
HttpUtil.sendOkHttpResquest(weatherUrl1, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
isError=true;
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handlerWeatherResponse(responseText);
if (weather != null && "ok".equals(weather.status)) {
if (weatherNowId.equals(weatherId)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weather", responseText);
editor.apply();
}
AddCity addCity = new AddCity();
addCity.setResponseText(responseText);
addCity.updateAll("cityname=?",weather.basic.cityName);
Intent i1 = new Intent("com.coolweather.android.LOCAL_BROADCAST_UPDATE_SHOW");
LocalBroadcastManager.getInstance(AutoUpdateService.this).sendBroadcast(i1);
}
}
});
}
}
}
private void updateBingPic(){
String requestBingPic="http://guolin.tech./api/bing_pic";
HttpUtil.sendOkHttpResquest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String bingPic=response.body().string();
SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("bing_pic",bingPic);
editor.apply();
}
});
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
| [
"[email protected]"
] | |
616cc7ee9244627507fcb0886879de119bad2384 | 4f03f9ca6cb52a2eb25c1735913b34c29bad781b | /backend/src/test/java/com/sinobre/robo_4n69/Robo4n69ApplicationTests.java | 2a7ce1fe73f46c0ccce04f96a5946a78aa70b432 | [] | no_license | FabioSinobre/Robo_4n69 | 52fd1058d239591aa30a027dfd0d7e922c686d34 | 43eafc4e7967f933610816f7f823f341c0914a55 | refs/heads/main | 2023-08-30T10:02:59.624102 | 2021-11-14T01:39:58 | 2021-11-14T01:39:58 | 417,808,445 | 3 | 4 | null | 2021-11-13T00:57:11 | 2021-10-16T11:32:43 | TypeScript | UTF-8 | Java | false | false | 215 | java | package com.sinobre.robo_4n69;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Robo4n69ApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
4f13e4248eb2fbc87083ddbfc2d93efb120398e5 | d00e6bbd5ef846d95f324ded19824dc8eaeaff97 | /src/main/java/com/chy/service/impl/AbstractServiceImpl.java | 1e0008a9f0106c9de0380ba4d079b5eb4e275ce6 | [] | no_license | octopanda/games | 3899f6a03e68f51d952677b243160e0a5c2442d6 | 9ef088d406cda5e9cbf8c96262588bdc1ebc118c | refs/heads/master | 2021-01-21T03:30:10.836528 | 2013-10-30T19:02:09 | 2013-10-30T19:02:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 843 | java | package com.chy.service.impl;
import com.chy.dao.AbstractDao;
import com.chy.service.AbstractService;
import java.io.Serializable;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AbstractServiceImpl<E, I extends Serializable>
implements AbstractService<E, I>
{
private AbstractDao<E, I> dao;
public AbstractServiceImpl(AbstractDao<E, I> dao)
{
this.dao = dao;
}
@Transactional(readOnly=true)
public List<E> findAll()
{
return this.dao.findAll();
}
@Transactional(readOnly=false)
public E saveOrUpdate(E e)
{
return this.dao.saveOrUpdate(e);
}
@Transactional(readOnly=false)
public void delete(E e)
{
this.dao.delete(e);
}
@Transactional(readOnly=true)
public E get(I id)
{
return this.dao.findById(id);
}
} | [
"[email protected]"
] | |
bebcd33bce76d83ed46325e48112842efa39562b | ceb2b2ad9c3979d51c03ffecc34112a0dfa93b78 | /src/com/chen/ucatch/ui/TestForData.java | 0153044143f6054a80446c06f1ba2bcca4734da1 | [] | no_license | chenjiqiang/UcatchAS | 6e51c0174b3ef665ae03bd93c0ef54d259698f3f | cba8aff1215492a0590a93f784d2666851ae10f3 | refs/heads/master | 2021-01-01T05:28:44.395933 | 2016-05-24T09:04:21 | 2016-05-24T09:04:21 | 59,496,959 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,442 | java | package com.chen.ucatch.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.chen.ucatch.R;
import com.chen.ucatch.adapter.LocationAdapter;
import com.chen.ucatch.model.LocationBean;
import com.chen.ucatch.utils.ShapeLoadingDialog;
import com.chen.ucatch.view.RefreshableContainer;
import com.chen.ucatch.view.RefreshableContainer.OnFooterRefreshListener;
public class TestForData extends Activity implements AMapLocationListener,
OnPoiSearchListener, OnFooterRefreshListener, OnClickListener {
/**
* 标题
*/
private TextView mtitle_left;
/**
* 确定按钮
*/
private Button bt_head_ok;
private SearchBound seach;
private Context mContext;
private Query query;
private int currentPage = 1;
/**
* 刷新容器
*/
private RefreshableContainer refresh;
/**
* listview控件sss
*/
private ListView listView;
private List<LocationBean> listDatas = new ArrayList<LocationBean>();
private LocationAdapter adapter;
/**
* 经纬度
*/
private LatLonPoint point;
/**
* edittext
*/
private EditText mEt_Seach;
/**
* 搜索按钮
*/
private Button mBt_Seach;
private LocationManagerProxy mLocationManagerProxy;
private ShapeLoadingDialog dialog;
public static final int LOCATION_CHANGE_RESULT_CODE = 1111;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_location_change);
mContext = this;
init();
initView();
// initData();
}
@Override
protected void onPause() {
super.onPause();
// 移除定位请求
mLocationManagerProxy.removeUpdates(this);
// 销毁定位
mLocationManagerProxy.destroy();
}
protected void onDestroy() {
super.onDestroy();
}
/**
* 初始化定位
*/
private void init() {
// 初始化定位,只采用网络定位
mLocationManagerProxy = LocationManagerProxy.getInstance(this);
mLocationManagerProxy.setGpsEnable(false);
// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用removeUpdates()方法来取消定位请求
// 在定位结束后,在合适的生命周期调用destroy()方法
// 其中如果间隔时间为-1,则定位只定一次,
// 在单次定位情况下,定位无论成功与否,都无需调用removeUpdates()方法移除请求,定位sdk内部会移除
mLocationManagerProxy.requestLocationData(
LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
}
private void initData(String key) {
// TODO Auto-generated method stub
query = new PoiSearch.Query(key, "", "");
query.setPageSize(10);// 设置每页最多返回多少条poiitem
query.setPageNum(currentPage);// 设置查第一页
PoiSearch poiSearch = new PoiSearch(this, query);
if (point == null) {
point = new LatLonPoint(22.374296, 113.563196);
}
poiSearch.setBound(new SearchBound(point, 5000));// 设置周边搜索的中心点以及区域
// 1,keyWord表示搜索字符串,第二个参数表示POI搜索类型,默认为:生活服务、餐饮服务、商务住宅
// 共分为以下20种:汽车服务|汽车销售|
// 汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
// 住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
// 金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
// cityCode表示POI搜索区域,(这里可以传空字符串,空字符串代表全国在全国范围内进行搜索)
poiSearch.setOnPoiSearchListener(this);// 设置数据返回的监听器
poiSearch.searchPOIAsyn();// 开始搜索
}
private void initView() {
dialog = new ShapeLoadingDialog(mContext);
dialog.setLoadingText("正在加载中。。。");
dialog.show();
mEt_Seach = (EditText) findViewById(R.id.et_location_change);
mBt_Seach = (Button) findViewById(R.id.location_change_search);
mBt_Seach.setOnClickListener(this);
mtitle_left = (TextView) findViewById(R.id.head_left);
mtitle_left.setText("选择地理位置");
bt_head_ok = (Button) findViewById(R.id.bt_head_ok);
bt_head_ok.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
adapter = new LocationAdapter(mContext, listDatas,
R.layout.location_change_item);
listView.setAdapter(adapter);
refresh = (RefreshableContainer) findViewById(R.id.refresh_data);
refresh.setOnFooterRefreshListener(this);
refresh.setPull(false);
refresh.setFooter(true);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
mEt_Seach.setText(listDatas.get(position).getTitle());
}
});
}
@Override
public void onPoiItemDetailSearched(PoiItemDetail arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onPoiSearched(PoiResult result, int rCode) {
refresh.onFooterRefreshComplete();
dialog.dismiss();
if (rCode == 0) {
// 在回调函数中解析result获取POI信息
// result.getPois()可以获取到PoiItem列表,Poi详细信息可参考PoiItem类
// 若当前城市查询不到所需Poi信息,可以通过result.getSearchSuggestionCitys()获取当前Poi搜索的建议城市
// 如果搜索关键字明显为误输入,则可通过result.getSearchSuggestionKeywords()方法得到搜索关键词建议
// 返回结果成功或者失败的响应码。0为成功,其他为失败(详细信息参见网站开发指南-错误码对照表)
List<LocationBean> datas = new ArrayList<LocationBean>();
for (PoiItem item : result.getPois()) {
LocationBean b = new LocationBean();
b.setPoiId(item.getPoiId());
b.setTitle(item.getTitle());
b.setSnippet(item.getSnippet());
b.setTypedes(item.getTypeDes());
b.setDistance(item.getDistance());
b.setEmail(item.getEmail());
b.setLatLonPoint(item.getLatLonPoint());
datas.add(b);
}
if (datas.size() > 0) {
listDatas.addAll(datas);
currentPage++;
adapter.notifyDataSetChanged();
} else {
Toast.makeText(mContext, "没有更多数据", Toast.LENGTH_SHORT).show();
}
// MyAdapter adapter = new MyAdapter(mContext, datas,
// R.layout.listview_item);
// listView.setAdapter(adapter);
} else {
Toast.makeText(mContext, "后期处理" + rCode, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFooterRefresh(RefreshableContainer view) {
// TODO Auto-generated method stub
initData("");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (amapLocation != null
&& amapLocation.getAMapException().getErrorCode() == 0) {
point = new LatLonPoint(amapLocation.getLatitude(),
amapLocation.getLongitude());
initData("");
// 定位成功回调信息,设置相关消息
// mLocationLatlngTextView.setText(amapLocation.getLatitude() + " "
// + amapLocation.getLongitude());
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(bt_head_ok)) {
Toast.makeText(
mContext,
mEt_Seach.getEditableText().toString()
+ point.getLatitude() + point.getLongitude(), 2000)
.show();
Intent intent = new Intent();
Bundle b = new Bundle();
b.putString("location", mEt_Seach.getEditableText().toString());
b.putDouble("Latitude", point.getLatitude());
b.putDouble("Longitude", point.getLongitude());
intent.putExtras(b);
setResult(LOCATION_CHANGE_RESULT_CODE, intent);
finish();
} else if (v.equals(mBt_Seach)) {
String key = mEt_Seach.getEditableText().toString();
initData(key);
listDatas.clear();
adapter.notifyDataSetChanged();
dialog.show();
}
}
}
| [
"[email protected]"
] | |
8b50f6d580cc06c3a1444b2839408434621ca946 | a7b49d70c8f350ffb991fc446fa226ef8a603756 | /src/test/java/com/puppycrawl/tools/checkstyle/grammars/AstRegressionTest.java | 63549011f32aec8ea718228ccba8a898b52bd91b | [] | no_license | wenjianliang/check-style-ext | a6afc1d45b9f622a8fbdd066f9ef0715842ecdce | ad835f980bd16f1c095d6d46aa2e3c3a64fc8ff2 | refs/heads/master | 2021-06-19T20:10:43.525738 | 2017-07-18T10:18:15 | 2017-07-18T10:18:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,682 | java | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.grammars;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.Test;
import antlr.NoViableAltForCharException;
import antlr.ParserSharedInputState;
import antlr.SemanticException;
import antlr.TokenBuffer;
import com.puppycrawl.tools.checkstyle.AstTreeStringPrinter;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.api.FileText;
public class AstRegressionTest extends BaseCheckTestSupport {
@Override
protected String getPath(String filename) throws IOException {
return super.getPath("grammars" + File.separator + filename);
}
@Override
protected String getNonCompilablePath(String filename) throws IOException {
return super.getNonCompilablePath("grammars" + File.separator + filename);
}
@Test
public void testClassAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJavaClass1Ast.txt"),
getPath("InputRegressionJavaClass1.java"));
}
@Test
public void testClassAstTree2() throws Exception {
verifyAst(getPath("InputRegressionJavaClass2Ast.txt"),
getPath("InputRegressionJavaClass2.java"));
}
@Test
public void testJava8ClassAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJava8Class1Ast.txt"),
getPath("InputRegressionJava8Class1.java"));
}
@Test
public void testInterfaceAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJavaInterface1Ast.txt"),
getPath("InputRegressionJavaInterface1.java"));
}
@Test
public void testInterfaceAstTree2() throws Exception {
verifyAst(getPath("InputRegressionJavaInterface2Ast.txt"),
getPath("InputRegressionJavaInterface2.java"));
}
@Test
public void testJava8InterfaceAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJava8Interface1Ast.txt"),
getPath("InputRegressionJava8Interface1.java"));
}
@Test
public void testEnumAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJavaEnum1Ast.txt"),
getPath("InputRegressionJavaEnum1.java"));
}
@Test
public void testEnumAstTree2() throws Exception {
verifyAst(getPath("InputRegressionJavaEnum2Ast.txt"),
getPath("InputRegressionJavaEnum2.java"));
}
@Test
public void testAnnotationAstTree1() throws Exception {
verifyAst(getPath("InputRegressionJavaAnnotation1Ast.txt"),
getPath("InputRegressionJavaAnnotation1.java"));
}
@Test
public void testUnusedConstructors1() throws Exception {
final Class<?> clss = GeneratedJavaLexer.class;
final Constructor<?> constructor = clss.getDeclaredConstructor(InputStream.class);
assertNotNull(constructor.newInstance((InputStream) null));
}
@Test
public void testUnusedConstructors2() throws Exception {
final Class<?> clss = GeneratedJavaRecognizer.class;
final Constructor<?> constructor = clss
.getDeclaredConstructor(ParserSharedInputState.class);
assertNotNull(constructor.newInstance((ParserSharedInputState) null));
}
@Test
public void testUnusedConstructors3() throws Exception {
final Class<?> clss = GeneratedJavaRecognizer.class;
final Constructor<?> constructor = clss.getDeclaredConstructor(TokenBuffer.class);
assertNotNull(constructor.newInstance((TokenBuffer) null));
}
@Test
public void testCustomAstTree() throws Exception {
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\t");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\r\n");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\n");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\r\r");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\r");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "\u000c\f");
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "// \n", true);
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "// \r", true);
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "// \r\n", true);
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "/* \n */", true);
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "/* \r\n */", true);
verifyAstRaw(getPath("InputRegressionEmptyAst.txt"), "/* \r" + "\u0000\u0000" + " */",
true);
}
@Test
public void testNewlineCr() throws Exception {
verifyAst(super.getPath("/checks/InputNewlineCrAtEndOfFileAst.txt"),
super.getPath("/checks/InputNewlineCrAtEndOfFile.java"), true);
}
@Test
public void testImpossibleExceptions() throws Exception {
AssertGeneratedJavaLexer.verifyFail("mSTD_ESC", 'a');
AssertGeneratedJavaLexer.verifyFail("mSTD_ESC", '0', (char) 0xFFFF);
AssertGeneratedJavaLexer.verifyFail("mSTD_ESC", '4', (char) 0xFFFF);
AssertGeneratedJavaLexer.verifyFail("mCHAR_LITERAL", '\'', '\'');
AssertGeneratedJavaLexer.verifyFail("mHEX_DIGIT", ';');
AssertGeneratedJavaLexer.verifyFail("mEXPONENT", ';');
AssertGeneratedJavaLexer.verifyFail("mBINARY_DIGIT", '2');
AssertGeneratedJavaLexer.verifyFail("mSIGNED_INTEGER", 'a');
AssertGeneratedJavaLexer.verifyFail("mID_START", '%');
AssertGeneratedJavaLexer.verifyFail("mID_START", (char) 0xBF);
AssertGeneratedJavaLexer.verifyFailNoGuessing("mID_START", (char) 0xBF);
AssertGeneratedJavaLexer.verifyFail("mID_PART", '%');
AssertGeneratedJavaLexer.verifyFail("mID_PART", (char) 0xBF);
AssertGeneratedJavaLexer.verifyFailNoGuessing("mID_PART", (char) 0xBF);
AssertGeneratedJavaLexer.verifyFail("mESC", '\\', 'a');
AssertGeneratedJavaLexer.verifyFail("mLONG_LITERAL", '0', ';');
AssertGeneratedJavaLexer.verifyFail("mLONG_LITERAL", '1', ';');
AssertGeneratedJavaLexer.verifyFail("mLONG_LITERAL", ';');
AssertGeneratedJavaLexer.verifyFail("mINT_LITERAL", ';');
AssertGeneratedJavaLexer.verifyFail("mHEX_DOUBLE_LITERAL", '0', 'a');
AssertGeneratedJavaLexer.verifyFail("mHEX_FLOAT_LITERAL", '0', 'a');
}
@Test
public void testImpossibleValid() throws Exception {
AssertGeneratedJavaLexer.verifyPass("mSTD_ESC", 'n');
AssertGeneratedJavaLexer.verifyPass("mELLIPSIS", '.', '.', '.');
AssertGeneratedJavaLexer.verifyPass("mDOT", '.');
AssertGeneratedJavaLexer.verifyPass("mBINARY_EXPONENT", 'p', '0', ';');
AssertGeneratedJavaLexer.verifyPass("mHEX_DIGIT", '0');
AssertGeneratedJavaLexer.verifyPass("mEXPONENT", 'e', '0', ';');
AssertGeneratedJavaLexer.verifyPass("mBINARY_DIGIT", '0');
AssertGeneratedJavaLexer.verifyPass("mSIGNED_INTEGER", '0', ';');
AssertGeneratedJavaLexer.verifyPass("mWS", ' ', ';');
AssertGeneratedJavaLexer.verifyPass("mID_START", '$');
AssertGeneratedJavaLexer.verifyPass("mID_PART", '$');
AssertGeneratedJavaLexer.verifyPass("mESC", '\\', '\\');
AssertGeneratedJavaLexer.verifyPass("mLONG_LITERAL", '1', 'L');
AssertGeneratedJavaLexer.verifyPass("mINT_LITERAL", '0', ';');
AssertGeneratedJavaLexer.verifyPass("mFLOAT_LITERAL", '0', 'f');
AssertGeneratedJavaLexer.verifyPass("mDOUBLE_LITERAL", '0', 'd');
AssertGeneratedJavaLexer.verifyPass("mHEX_FLOAT_LITERAL", '0', 'x', '2', '_', '4', '.',
'4', '4', '.', '4', 'P', '4', ';');
AssertGeneratedJavaLexer.verifyPass("mHEX_DOUBLE_LITERAL", '0', 'x', '2', '_', '4', '.',
'4', '4', '.', '4', 'P', '4', 'D', ';');
}
private static void verifyAstRaw(String expectedTextPrintFileName, String actualJava)
throws Exception {
verifyAstRaw(expectedTextPrintFileName, actualJava, false);
}
private static void verifyAstRaw(String expectedTextPrintFileName, String actualJava,
boolean withComments) throws Exception {
final File expectedFile = new File(expectedTextPrintFileName);
final String expectedContents = new FileText(expectedFile, System.getProperty(
"file.encoding", "UTF-8")).getFullText().toString().replace("\r", "");
final FileText actualFileContents = FileText.fromLines(new File(""),
Arrays.asList(actualJava.split("\\n|\\r\\n?")));
final String actualContents = AstTreeStringPrinter.printAst(actualFileContents,
withComments);
assertEquals("Generated AST from Java code should match pre-defined AST", expectedContents,
actualContents);
}
private static final class AssertGeneratedJavaLexer extends GeneratedJavaLexer {
private int laPosition;
private char[] laResults;
private AssertGeneratedJavaLexer() {
super((InputStream) null);
}
public static void verifyFailNoGuessing(String methodName, char... laResults)
throws Exception {
verify(methodName, false, 0, laResults);
}
public static void verifyPass(String methodName, char... laResults) throws Exception {
verify(methodName, true, 1, laResults);
}
public static void verifyFail(String methodName, char... laResults) throws Exception {
verify(methodName, false, 1, laResults);
}
public static void verify(String methodName, boolean expectPass, int guessing,
char... laResults) throws Exception {
final AssertGeneratedJavaLexer instance = new AssertGeneratedJavaLexer();
instance.laPosition = 0;
instance.laResults = laResults.clone();
instance.inputState.guessing = guessing;
final Method method = GeneratedJavaLexer.class.getDeclaredMethod(methodName,
boolean.class);
boolean exception;
try {
method.invoke(instance, true);
exception = false;
}
catch (InvocationTargetException ex) {
if (expectPass) {
throw ex;
}
final Class<?> clss = ex.getTargetException().getClass();
if (clss != NoViableAltForCharException.class
&& clss != SemanticException.class) {
throw ex;
}
exception = true;
}
if (expectPass) {
assertFalse("Call to GeneratedJavaLexer." + methodName
+ " resulted in an exception", exception);
}
else {
assertTrue("Call to GeneratedJavaLexer." + methodName
+ " did not result in an exception", exception);
}
}
@Override
public char LA(int i) {
return laResults[laPosition + i - 1];
}
@Override
public void consume() {
laPosition++;
}
@Override
public int mark() {
return 1;
}
}
}
| [
"[email protected]"
] | |
bcd073ccc30564badd661bbd8eadff466476582c | 2acbc2b6067efee7b644248eefa6c98e680d9d06 | /taotao_web/src/main/java/com/taotao/shop/controller/PageController.java | c9a025c113999d822630bbcfb238880d2930344f | [] | no_license | zhangfanzxx/taotao | 749dca98c541eaad1e22573500da8166935f8ad5 | 238f930d6a7b7a55851b0abf1e481ccfa3a1fd08 | refs/heads/master | 2021-08-28T06:39:45.584524 | 2017-12-11T12:02:18 | 2017-12-11T12:03:14 | 113,851,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 450 | java | package com.taotao.shop.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* ${DESCRIPTION}
*
* @author zzff
* @create 2017-12-11 16:44
**/
@Controller
public class PageController {
@RequestMapping("/{page}")
public String getPage(@PathVariable("page") String page){
return page;
}
}
| [
"[email protected]"
] | |
5eb31892694ae377d5dbcb9d169e611a5e3ea270 | 36d1eb13a33ea89684e1c1309d58bfc45bc0a889 | /server/src/main/java/com/gtfo/res/S3Connection.java | 8746d2cd388c4f3c94efb5704c5d8a4524fecbb4 | [] | no_license | hjchun96/GTFO | df2030bbec03a9b855a163c3dd77704e496bc4e3 | 09a1fc343672967f204f3b55b6989fc8fa469dcb | refs/heads/master | 2020-03-29T11:17:18.132512 | 2019-04-12T15:16:30 | 2019-04-12T15:16:30 | 149,844,504 | 0 | 0 | null | 2019-04-07T22:26:08 | 2018-09-22T04:16:17 | Python | UTF-8 | Java | false | false | 1,615 | java | package com.gtfo.res;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Scanner;
public class S3Connection {
private AWSCredentials credentials;
private AmazonS3 s3client;
public Bucket s3bucket;
public S3Connection() {
File keys = new File("./keys");
String accessKey = null;
String secretKey = null;
try {
Scanner sc = new Scanner(keys);
accessKey = sc.nextLine();
secretKey = sc.nextLine();
} catch (FileNotFoundException e) {
System.out.println("Make sure you've set up your keys file!");
}
credentials = new BasicAWSCredentials(
accessKey,
secretKey
);
s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
List<Bucket> buckets = s3client.listBuckets();
for (Bucket bucket : buckets) {
if (bucket.getName().equals("gtfo")) {
s3bucket = bucket;
}
}
}
public AmazonS3 getInstance() {
return this.s3client;
}
}
| [
"[email protected]"
] | |
a856d51aa4671af1e2e0a3eb22881a53d524653d | 47d50eca7584315888da50263ec10fa89ff121e0 | /contract-frameworks/contract-guice/contract-guice-mvel/src/main/java/com/github/sebhoss/contract/module/DefaultMVELModule.java | 60c600baefbb392c33738906bdb33e17e1d5e212 | [
"Unlicense",
"WTFPL",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sebhoss/annotated-contracts | c9d0482764d09faa173ebd78d3dcce86d979264e | f4d99f9bcd58b184123dfa60ab3f9ed2aafdfaa5 | refs/heads/master | 2021-01-18T21:30:41.123041 | 2016-11-20T18:35:19 | 2016-11-20T18:35:19 | 5,302,847 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,678 | java | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*/
package com.github.sebhoss.contract.module;
import com.github.sebhoss.contract.verifier.MvelModule;
/**
* Guice module for the default behavior for annotated contracts. Uses MVEL and Paranamer for contract checking.
*/
public final class DefaultMVELModule extends AbstractContractModule {
@Override
protected void installExtensions() {
install(new MvelModule());
}
}
| [
"[email protected]"
] | |
2fc44f2d4d2bec9b5ef305df34d14f05b5de28e5 | a7b868c8c81984dbcb17c1acc09c0f0ab8e36c59 | /src/main/java/com/alipay/api/domain/FaceMachineInfo.java | acc51aba2576b7b4ea2b3dd69bd85a8f954c469b | [
"Apache-2.0"
] | permissive | 1755616537/alipay-sdk-java-all | a7ebd46213f22b866fa3ab20c738335fc42c4043 | 3ff52e7212c762f030302493aadf859a78e3ebf7 | refs/heads/master | 2023-02-26T01:46:16.159565 | 2021-02-02T01:54:36 | 2021-02-02T01:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,310 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 人脸识别机具信息
*
* @author auto create
* @since 1.0, 2018-11-20 14:56:05
*/
public class FaceMachineInfo extends AlipayObject {
private static final long serialVersionUID = 1883473699959154676L;
/**
* 摄像头驱动版本号
*/
@ApiField("camera_drive_ver")
private String cameraDriveVer;
/**
* 摄像头型号
*/
@ApiField("camera_model")
private String cameraModel;
/**
* 摄像头名称
*/
@ApiField("camera_name")
private String cameraName;
/**
* 摄像头版本号
*/
@ApiField("camera_ver")
private String cameraVer;
/**
* 扩展信息
*/
@ApiField("ext")
private String ext;
/**
* 机具编码
*/
@ApiField("machine_code")
private String machineCode;
/**
* 机具型号
*/
@ApiField("machine_model")
private String machineModel;
/**
* 机具版本号
*/
@ApiField("machine_ver")
private String machineVer;
public String getCameraDriveVer() {
return this.cameraDriveVer;
}
public void setCameraDriveVer(String cameraDriveVer) {
this.cameraDriveVer = cameraDriveVer;
}
public String getCameraModel() {
return this.cameraModel;
}
public void setCameraModel(String cameraModel) {
this.cameraModel = cameraModel;
}
public String getCameraName() {
return this.cameraName;
}
public void setCameraName(String cameraName) {
this.cameraName = cameraName;
}
public String getCameraVer() {
return this.cameraVer;
}
public void setCameraVer(String cameraVer) {
this.cameraVer = cameraVer;
}
public String getExt() {
return this.ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getMachineCode() {
return this.machineCode;
}
public void setMachineCode(String machineCode) {
this.machineCode = machineCode;
}
public String getMachineModel() {
return this.machineModel;
}
public void setMachineModel(String machineModel) {
this.machineModel = machineModel;
}
public String getMachineVer() {
return this.machineVer;
}
public void setMachineVer(String machineVer) {
this.machineVer = machineVer;
}
}
| [
"[email protected]"
] | |
ca78ff8aa2bb303fcdc3f1539010f77654cb77a6 | 2b26fdfbc554e5aa24b01ca5dbc94b9f15db4ee6 | /src/main/java/com/nb/crm/settings/dao/IParkDao.java | 60adae974da5a8f518976c14ca77d83f2190b0af | [] | no_license | qun15/zhuzhaixiaoquwuyeguanli- | b057a7450084cd5c2c567c05e09a65cf4453d1af | 1d96d57b22dd1d770dea25372a7c7ecd07b84aa0 | refs/heads/master | 2023-05-04T00:47:05.698950 | 2021-05-28T06:39:33 | 2021-05-28T06:39:33 | 365,657,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 429 | java | package com.nb.crm.settings.dao;
import com.nb.crm.settings.domain.Park;
import java.util.List;
import java.util.Map;
public interface IParkDao {
int getTotalByCondition(Map<String, Object> map);
List<Park> getUserListByCondition(Map<String, Object> map);
Park getParkListById(String id);
int update(Park park);
int deletePark(String[] ids);
int save(Park park);
List<Park> getUserList();
}
| [
"[email protected]"
] | |
6f333059b044c1358cc6b71bbf7a2d93f10c474a | c1afde3fba89411202486f665cb7d90565fd5038 | /src/main/java/hu/frontrider/arcana/recipes/PotionRegistry.java | a6ebc6fcd021311438a9a448074d6cfd8d9a7810 | [] | no_license | meitangdehulu/thaumic_arcana | f23e826b492544fce76c667866393423f9bfd0df | b2ed4cb1f45982e49414e57accdf039020deb2cd | refs/heads/master | 2020-03-27T08:24:39.101686 | 2018-08-27T02:07:33 | 2018-08-27T02:07:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 109 | java | package hu.frontrider.arcana.recipes;
public class PotionRegistry {
static void register() {
}
}
| [
"[email protected]"
] | |
12377caecd6c3b5ed302b1ae4d786bff0e23341c | 10f72da46f36670e8dc1a06fd3c5794c6538640f | /xchange/src/main/java/org/knowm/xchange/internal/service/trade/TradeService.java | ee7bb7871dd703fe390cb8e44486c222208cebdc | [] | no_license | BlockUnison/batm-ext-decent | ae6e31c71d670911db8cab766ed22991e2a125f9 | 446d4b40562014936c66276f57f2b59c20b02f49 | refs/heads/master | 2020-04-02T06:37:18.909405 | 2019-01-29T19:04:50 | 2019-01-29T19:04:50 | 154,159,320 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,343 | java | package org.knowm.xchange.internal.service.trade;
import java.io.IOException;
import java.util.Collection;
import org.knowm.xchange.internal.Exchange;
import org.knowm.xchange.internal.dto.Order;
import org.knowm.xchange.internal.dto.trade.LimitOrder;
import org.knowm.xchange.internal.dto.trade.MarketOrder;
import org.knowm.xchange.internal.dto.trade.OpenOrders;
import org.knowm.xchange.internal.dto.trade.StopOrder;
import org.knowm.xchange.internal.dto.trade.UserTrades;
import org.knowm.xchange.internal.exceptions.ExchangeException;
import org.knowm.xchange.internal.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.internal.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.internal.service.BaseService;
import org.knowm.xchange.internal.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.internal.service.trade.params.CancelOrderParams;
import org.knowm.xchange.internal.service.trade.params.DefaultCancelOrderParamId;
import org.knowm.xchange.internal.service.trade.params.TradeHistoryParamsAll;
import org.knowm.xchange.internal.service.trade.params.orders.DefaultQueryOrderParam;
import org.knowm.xchange.internal.service.trade.params.orders.OpenOrdersParams;
import org.knowm.xchange.internal.service.trade.params.orders.OrderQueryParams;
/**
* Interface to provide the following to {@link Exchange}:
*
* <ul>
* <li>Retrieve the user's open orders on the exchange
* <li>Cancel user's open orders on the exchange
* <li>Place market orders on the exchange
* <li>Place limit orders on the exchange
* </ul>
*
* <p>The implementation of this service is expected to be based on a client polling mechanism of
* some kind
*/
public interface TradeService extends BaseService {
/**
* Gets the open orders
*
* @return the open orders, null if some sort of error occurred. Implementers should log the
* error.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default OpenOrders getOpenOrders() throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Gets the open orders
*
* @param params The parameters describing the filter. Note that {@link OpenOrdersParams} is an
* empty interface. Exchanges should implement its own params object. Params should be create
* with {@link #createOpenOrdersParams()}.
* @return the open orders, null if some sort of error occurred. Implementers should log the
* error.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Place a market order
*
* @param marketOrder
* @return the order ID
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default String placeMarketOrder(MarketOrder marketOrder) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Place a limit order
*
* @param limitOrder
* @return the order ID
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default String placeLimitOrder(LimitOrder limitOrder) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Place a stop order
*
* @param stopOrder
* @return the order ID
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default String placeStopOrder(StopOrder stopOrder) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* cancels order with matching orderId (conveniance method, typical just delegate to
* cancelOrder(CancelOrderByIdParams))
*
* @param orderId
* @return true if order was successfully cancelled, false otherwise.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default boolean cancelOrder(String orderId) throws IOException {
return cancelOrder(new DefaultCancelOrderParamId(orderId));
}
/**
* cancels order with matching orderParams
*
* @param orderParams
* @return true if order was successfully cancelled, false otherwise.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default boolean cancelOrder(CancelOrderParams orderParams) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Fetch the history of user trades.
*
* <p>If you are calling this method for single exchange, known at the development time, you may
* pass an object of specific *TradeHistoryParam class that is nested it that exchange's trade
* service.
*
* <p>If, however, you are fetching user trade history from many exchanges using the same code,
* you will find useful to create the parameter object with {@link #createTradeHistoryParams()}
* and check which parameters are required or supported using instanceof operator. See
* subinterfaces of {@link TradeHistoryParams}. Note that whether an interface is required or
* supported will vary from exchange to exchange and it's described only through the javadoc.
*
* <p>There is also implementation of all the common interfaces, {@link TradeHistoryParamsAll} ,
* that, with all properties set non-null, should work with any exchange.
*
* <p>Some exchanges allow extra parameters, not covered by any common interface. To access them,
* you will have to use the object returned by {@link #createTradeHistoryParams()} and cast it to
* the exchange-specific type.
*
* @param params The parameters describing the filter. Note that {@link TradeHistoryParams} is an
* empty interface. Exact set of interfaces that are required or supported by this method is
* described by the type of object returned from {@link #createTradeHistoryParams()} and the
* javadoc of the method.
* @return UserTrades as returned by the exchange API
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
* @see #createTradeHistoryParams()
* @see TradeHistoryParamsAll
*/
default UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
throw new NotYetImplementedForExchangeException();
}
/**
* Create {@link TradeHistoryParams} object specific to this exchange. Object created by this
* method may be used to discover supported and required {@link
* #getTradeHistory(TradeHistoryParams)} parameters and should be passed only to the method in the
* same class as the createTradeHistoryParams that created the object.
*/
default TradeHistoryParams createTradeHistoryParams() {
throw new NotYetImplementedForExchangeException();
}
/**
* Create {@link OpenOrdersParams} object specific to this exchange. Object created by this method
* may be used to discover supported and required {@link #getOpenOrders(OpenOrdersParams)}
* parameters and should be passed only to the method in the same class as the
* createOpenOrdersParams that created the object.
*/
default OpenOrdersParams createOpenOrdersParams() {
throw new NotYetImplementedForExchangeException();
}
/**
* Verify the order against the exchange meta data. Most implementations will require that {@link
* Exchange#remoteInit()} be called before this method
*/
default void verifyOrder(LimitOrder limitOrder) {
throw new NotYetImplementedForExchangeException();
}
/**
* Verify the order against the exchange meta data. Most implementations will require that {@link
* Exchange#remoteInit()} be called before this method
*/
default void verifyOrder(MarketOrder marketOrder) {
throw new NotYetImplementedForExchangeException();
}
/**
* get's the latest order form the order book that with matching orderId
*
* @return the order as it is on the exchange.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default Collection<Order> getOrder(String... orderIds) throws IOException {
return getOrder(toOrderQueryParams(orderIds));
}
static OrderQueryParams[] toOrderQueryParams(String... orderIds) {
OrderQueryParams[] res = new OrderQueryParams[orderIds.length];
for (int i = 0; i < orderIds.length; i++) {
String orderId = orderIds[i];
res[i] = new DefaultQueryOrderParam(orderId);
}
return res;
}
/**
* get's the latest order form the order book that with matching orderQueryParams
*
* @return the order as it is on the exchange.
* @throws ExchangeException - Indication that the exchange reported some kind of error with the
* request or response
* @throws NotAvailableFromExchangeException - Indication that the exchange does not support the
* requested function or data
* @throws NotYetImplementedForExchangeException - Indication that the exchange supports the
* requested function or data, but it has not yet been implemented
* @throws IOException - Indication that a networking error occurred while fetching JSON data
*/
default Collection<Order> getOrder(OrderQueryParams... orderQueryParams) throws IOException {
throw new NotAvailableFromExchangeException();
}
}
| [
"[email protected]"
] | |
bb873a915dedfb21863f09c073f73a363b424771 | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /ant_cluster/2987/src_1.java | d55361173c4fc79dec2f1ff5f9492a42c6725f94 | [] | no_license | martinezmatias/GenPat-data-C3 | 63cfe27efee2946831139747e6c20cf952f1d6f6 | b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4 | refs/heads/master | 2022-04-25T17:59:03.905613 | 2020-04-15T14:41:34 | 2020-04-15T14:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,101 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.tools.ant.util.optional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.ProjectComponent;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.FileUtils;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.tools.ant.types.Path;
/**
* This class is used to run BSF scripts
*
*/
public class ScriptRunner {
// Register Groovy ourselves, since BSF does not
// natively support it (yet).
// This "hack" can be removed once BSF has been
// modified to support Groovy or more dynamic
// registration.
static {
BSFManager.registerScriptingEngine(
"groovy",
"org.codehaus.groovy.bsf.GroovyEngine",
new String[] {"groovy", "gy"});
}
/** Script language */
private String language;
/** Script content */
private String script = "";
/** Beans to be provided to the script */
private Map beans = new HashMap();
/** Classpath to be used when running the script. */
private Path classpath = null;
/** Project this runner is used in */
private Project project = null;
/**
* Add a list of named objects to the list to be exported to the script
*
* @param dictionary a map of objects to be placed into the script context
* indexed by String names.
*/
public void addBeans(Map dictionary) {
for (Iterator i = dictionary.keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
try {
Object val = dictionary.get(key);
addBean(key, val);
} catch (BuildException ex) {
// The key is in the dictionary but cannot be retrieved
// This is usually due references that refer to tasks
// that have not been taskdefed in the current run.
// Ignore
}
}
}
/**
* Add a single object into the script context.
*
* @param key the name in the context this object is to stored under.
* @param bean the object to be stored in the script context.
*/
public void addBean(String key, Object bean) {
boolean isValid = key.length() > 0
&& Character.isJavaIdentifierStart(key.charAt(0));
for (int i = 1; isValid && i < key.length(); i++) {
isValid = Character.isJavaIdentifierPart(key.charAt(i));
}
if (isValid) {
beans.put(key, bean);
}
}
/**
* Do the work.
*
* @param execName the name that will be passed to BSF for this script
* execution.
*
* @exception BuildException if someting goes wrong exectuing the script.
*/
public void executeScript(String execName) throws BuildException {
if (language == null) {
throw new BuildException("script language must be specified");
}
ClassLoader origContextClassLoader =
Thread.currentThread().getContextClassLoader();
ClassLoader scriptLoader = getClass().getClassLoader();
if (classpath != null && project != null) {
scriptLoader = project.createClassLoader(
scriptLoader, classpath);
}
try {
Thread.currentThread().setContextClassLoader(scriptLoader);
BSFManager manager = new BSFManager ();
manager.setClassLoader(scriptLoader);
for (Iterator i = beans.keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Object value = beans.get(key);
if (value != null) {
manager.declareBean(key, value, value.getClass());
} else {
// BSF uses a hashtable to store values
// so cannot declareBean with a null value
// So need to remove any bean of this name as
// that bean should not be visible
manager.undeclareBean(key);
}
}
// execute the script
manager.exec(language, execName, 0, 0, script);
} catch (BSFException be) {
Throwable t = be;
Throwable te = be.getTargetException();
if (te != null) {
if (te instanceof BuildException) {
throw (BuildException) te;
} else {
t = te;
}
}
throw new BuildException(t);
} finally {
Thread.currentThread().setContextClassLoader(
origContextClassLoader);
}
}
/**
* Defines the language (required).
*
* @param language the scripting language name for the script.
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* Get the script language
*
* @return the script language
*/
public String getLanguage() {
return language;
}
/**
* Set the class path to be used.
* @param classpath the path to use.
*/
public void setClasspath(Path classpath) {
this.classpath = classpath;
}
/**
* Load the script from an external file ; optional.
*
* @param file the file containing the script source.
*/
public void setSrc(File file) {
if (!file.exists()) {
throw new BuildException("file " + file.getPath() + " not found.");
}
int count = (int) file.length();
byte[] data = new byte[count];
FileInputStream inStream = null;
try {
inStream = new FileInputStream(file);
inStream.read(data);
} catch (IOException e) {
throw new BuildException(e);
} finally {
FileUtils.close(inStream);
}
script += new String(data);
}
/**
* Set the script text.
*
* @param text a component of the script text to be added.
*/
public void addText(String text) {
this.script += text;
}
/**
* Bind the runner to a project component.
* Properties, targets and references are all added as beans;
* project is bound to project, and self to the component.
* @param component to become <code>self</code>
*/
public void bindToComponent(ProjectComponent component) {
project = component.getProject();
addBeans(project.getProperties());
addBeans(project.getUserProperties());
addBeans(project.getTargets());
addBeans(project.getReferences());
addBean("project", project);
addBean("self", component);
}
/**
* Bind the runner to a project component.
* The project and self are the only beans set.
* @param component to become <code>self</code>
*/
public void bindToComponentMinimum(ProjectComponent component) {
project = component.getProject();
addBean("project", project);
addBean("self", component);
}
}
| [
"[email protected]"
] | |
5104c871461556228b7ed1e97ccb46b94caff313 | 3293fb62516d7a673a3504792d661cec009a0013 | /src/main/java/Sword_finger_offer/BinaryBitNumber.java | bc019588e06dd6781488a70a483fe6a6c6a6c386 | [] | no_license | LJJ1994/algorithm-for-interview | 67ee6f4c814dd9daf27abca4c6e366c90ccd47b9 | 97b67faba79ef5c4d647c44bfba818fb2d5f5921 | refs/heads/main | 2023-05-22T18:51:47.302228 | 2021-06-16T18:32:57 | 2021-06-16T18:32:57 | 343,346,179 | 0 | 0 | null | 2021-05-01T14:05:54 | 2021-03-01T08:44:03 | Java | UTF-8 | Java | false | false | 1,931 | java | package Sword_finger_offer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 二进制中1的个数
*
* 请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9表示成二进制是 1001,有 2 位是 1。
* 因此,如果输入 9,则该函数输出 2。
*
* 示例 1:
*
* 输入:00000000000000000000000000001011
* 输出:3
* 解释:输入的二进制串 00000000000000000000000000001011中,共有三位为 '1'。
* 示例 2:
*
* 输入:00000000000000000000000010000000
* 输出:1
* 解释:输入的二进制串 00000000000000000000000010000000中,共有一位为 '1'。
* 示例 3:
*
* 输入:11111111111111111111111111111101
* 输出:31
* 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
*
*/
public class BinaryBitNumber {
public int count(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
}
return count;
}
public int count01(int n) {
int count = 0;
while (n != 0) {
count++;
n = (n-1) & n;
}
return count;
}
public int count02(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((flag & n) == 1) {
count++;
}
flag = flag << 1;
}
return count;
}
public static void main(String[] args) {
int n = 9;
BinaryBitNumber bitNumber = new BinaryBitNumber();
int count = bitNumber.count(n);
int count01 = bitNumber.count01(n);
int count02 = bitNumber.count02(n);
System.out.println(count);
System.out.println(count01);
System.out.println(count02);
}
}
| [
"[email protected]"
] | |
b36e1d2278b9b24c8c626e551305559bf1231403 | 607bd7c101cc200204e959ea2d73d3f75ba1e36c | /Java/LRUCache.java | 022579844b280e4e79a58addf1e9e7b93614bb2d | [] | no_license | qianwen/LeetCode-Solutions | 7f989ff17432de8a407c13a7ea616388cfa6bbda | b94eb16d3c0f5556ec8ec185d4b0849f27eb0151 | refs/heads/master | 2021-01-19T15:32:32.108127 | 2014-08-27T06:23:31 | 2014-08-27T06:23:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,291 | java | /* LRU (Least Recently Used) Cache
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
* get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
* set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity,
* it should invalidate the least recently used item before inserting a new item.
*/
import java.util.LinkedHashMap;
import java.util.Map;
// use LinkedHashMap
public class LRUCache extends LinkedHashMap<Integer, Integer> {
public static void main(String[] args) {
LRUCache lru = new LRUCache(2);
System.out.println(lru.get(2));
lru.put(1, 10);
lru.put(2, 20);
System.out.println(lru.get(1));
lru.put(3, 30);
System.out.println(lru.get(2));
}
private int capacity;
public LRUCache(int capacity) {
super(capacity+1, 1.0f, true);
this.capacity = capacity;
}
public Integer get(Object key) {
Integer v = super.get(key);
if (v != null)
return v;
else
return -1;
}
public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
public void set(int key, int value) {
super.put(key, value);
}
}
| [
"[email protected]"
] | |
4404fa16af86cd0b9a2fab75cf75fdbff1261442 | 30ce2437da14f0a2f84ac99a9a3acad7148512ae | /手指测心率/gen/com/wl/adrxin/BuildConfig.java | e28895385c969692b04afe1b2c8291281880bf4a | [] | no_license | wuleihenbang/MyFirstRepo1 | 8754cbbc90ea6f86986a2dadfea3ea0a59529532 | 6165db5b4cf7034a8a98dac3c04f7bc6fcfef35d | refs/heads/master | 2021-01-19T07:57:14.825334 | 2014-03-29T09:12:03 | 2014-03-29T09:12:03 | 17,465,194 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 155 | java | /** Automatically generated file. DO NOT MODIFY */
package com.wl.adrxin;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | [
"[email protected]"
] | |
8f15ff1bf8372a0e5f0948bfa2a1752e5d939b25 | e399874d5ae2af48ac4394cc4b5b725155ed3efa | /PrimerEjercicio/Ejemplo_Relaciones.java | 3fc8ae25ffe1cbd00037f7444fe8eddff3d3e069 | [] | no_license | adriujo/Proyecto-ENDES | 617e466f8d34971e3867602e395bed839bd00120 | ffc7bd99983951eaa565564143d13ede9ec0a19d | refs/heads/master | 2023-01-20T21:35:48.028328 | 2020-11-27T19:32:14 | 2020-11-27T19:32:14 | 316,581,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,021 | java | /**
*
*/
package PrimerEjercicio;
import java.util.*;
/**
* @author TARDES
*
*/
public class Ejemplo_Relaciones {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//clase scanner para peticion de datos
Scanner teclado = new Scanner (System.in);
int x, y;
String cadena;
boolean resultado;
System.out.print("Introducir primer numero: ");
x = teclado.nextInt();
System.out.print("Introducir segundo numero: ");
y = teclado.nextInt();
cadena =(x==y)?"iguales":"diferentes";
System.out.printf("Los numeros %d y %d son %s\n" ,x,y,cadena);
resultado = (x!=y);
System.out.println("x != y // es "+ resultado);
resultado = (x<y);
System.out.println("x < y // es "+ resultado);
resultado = (x>y);
System.out.println("x > y // es "+ resultado);
resultado = (x<=y);
System.out.println("x<!= y // es "+ resultado);
resultado = (x>=y);
System.out.println("x >= y // es "+ resultado);
teclado.close();
}
}
| [
"[email protected]"
] | |
fc784e552b2c7530b88f77cdce8e294cf1d30931 | 1f10320ee66a0379661c123ee6019fa495fa0744 | /src/server/Order.java | f731d864d81c7082569a7ab2ed8f4fbc36cdfa3f | [] | no_license | preslava98/SAP-PROJECT-TastyPizza- | 432cd3f6b5ed5eccbd3bca09fa3afb7b7cefa10e | 28dd7166b0719efd5d3f576c97b18c6d13f48290 | refs/heads/master | 2020-06-17T07:30:31.038559 | 2019-07-12T09:16:42 | 2019-07-12T09:16:42 | 195,846,934 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 710 | java | package server;
public class Order
{
private String name;
private int quantity;
private int id;
private double price;
private Food food;
public Order(String name, int id, int quantity, double price, Food food)
{
this.name = name;
this.id = id;
this.quantity = quantity;
this.price=price;
this.food = food;
}
public String toString()
{
return " Item: " + name + ", Id: " + id + "., Quantity: " + quantity +
", Price: " + price + "\n";
}
public String getName()
{
return name;
}
public int getQuantity()
{
return quantity;
}
public int getId()
{
return id;
}
public double getPrice()
{
return price;
}
public Food getFood()
{
return food;
}
}
| [
"[email protected]"
] | |
c2a022047055c46fa94efe3e2e40bf6df9ecb96e | 454e0b0c9d000d03d3767b2d7231ab0dfe1344a7 | /src/Code/Commands/Reset_fly_speed.java | dfe58f396140546cec81eb175e0615be36e90e8f | [] | no_license | 580baby/Narwall-Plugin | f4661ca6484d418aeed53de282f4a85ca2b94526 | 42d839c8b2e9e0d1f3d1d93c38a1b092c96510d3 | refs/heads/master | 2020-05-26T15:22:16.914337 | 2018-03-08T02:17:54 | 2018-03-08T02:17:54 | 85,010,112 | 2 | 2 | null | 2018-03-08T03:16:38 | 2017-03-15T00:16:37 | Java | UTF-8 | Java | false | false | 809 | java | package Code.Commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import Code.Main;
public class Reset_fly_speed implements CommandExecutor {
@SuppressWarnings("unused")
private Main core;
public Reset_fly_speed(Main main) {
this.core = main;
}
public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) {
if (cmd.getName().equalsIgnoreCase("resetflyspeed")) {
if (sender.hasPermission("narwall.fastfly")) {
if (sender instanceof Player) {
Player player = (Player) sender;
player.setFlySpeed(0.2f);
player.sendMessage(org.bukkit.ChatColor.BLUE + "Fly speed " + org.bukkit.ChatColor.RED + "Reset");
}
}
}
return false;
}
}
| [
"[email protected]"
] | |
2fa6a7831b9b9d8ce6634145929554da06836870 | de1aa7d6c44b2243208d033c3a7daf4782033322 | /src/main/java/pl/tobynartowski/database/executor/MySQLExecutor.java | 18768cb67de36d0144e775cac1d4dbe868a3a8ca | [] | no_license | TobyNartowski/FileReader | 171765088b91b2a3cfb1f4cf5801b12008c2f758 | c4142ebb5a0368647b5925a6bddb192bd7ab8dda | refs/heads/master | 2022-12-17T06:30:07.047288 | 2020-09-27T18:45:30 | 2020-09-27T18:45:30 | 298,822,379 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,492 | java | package pl.tobynartowski.database.executor;
import pl.tobynartowski.database.query.create.CreateQuery;
import pl.tobynartowski.utils.TopologicalSorter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class MySQLExecutor implements Executor {
private final Connection connection;
public MySQLExecutor(Connection connection) {
this.connection = connection;
}
@Override
public void createTablesIfNeeded() {
final TopologicalSorter<CreateQuery> sorter = new TopologicalSorter<>();
sorter.sortData(CreateQuery.definedTables, CreateQuery::getDependencyTables).forEach(this::createTable);
}
private void createTable(final CreateQuery createQuery) {
try {
Statement statement = connection.createStatement();
statement.executeUpdate(createQuery.getQuery());
} catch (SQLException throwables) {
System.err.println("Cannot create table with query: " + createQuery.getQuery());
throwables.printStackTrace();
}
}
@Override
public void insertData(List<PreparedStatement> statements) {
try {
for (PreparedStatement s : statements) {
s.executeUpdate();
}
} catch (SQLException throwables) {
System.err.println("Cannot insert data");
throwables.printStackTrace();
}
}
} | [
"[email protected]"
] | |
048bb83ba102f5028b4cbf23afc7dd8790b62d90 | fc2a742044c72e1e08aafc9d337425e7c19d1eb4 | /src/main/java/com/iluo/rabbitmq/MQSender.java | 66afc8e9d1719857d664db5e3956310299c8165e | [] | no_license | ILUO/vacations | 906df4daa3fe9b887e6a12196af7086faed70203 | 492a218ae3d79df22db5fe76ad0e987e180b0333 | refs/heads/master | 2022-06-26T06:16:01.972326 | 2020-01-02T09:29:34 | 2020-01-02T09:29:34 | 228,647,982 | 0 | 1 | null | 2022-06-17T02:49:03 | 2019-12-17T15:39:22 | Java | UTF-8 | Java | false | false | 1,406 | java | package com.iluo.rabbitmq;
import com.iluo.redis.RedisService;
import com.iluo.vo.MiaoShaMessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MQSender {
private static Logger log = LoggerFactory.getLogger(MQSender.class);
@Autowired
AmqpTemplate amqpTemplate ;
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMiaoshaMessage(MiaoshaMessage mm) {
String msg = RedisService.beanToString(mm);
log.info("send message:"+msg);
amqpTemplate.convertAndSend(MQConfig.MIAOSHA_QUEUE, msg);
}
/**
* 站内信
* @param mm
*/
public void sendMessage(MiaoshaMessage mm) {
// String msg = RedisService.beanToString(mm);
log.info("send message:"+"11111");
rabbitTemplate.convertAndSend(MQConfig.EXCHANGE_TOPIC,"miaosha_*", "111111111");
}
/**
* 站内信
* @param
*/
public void sendRegisterMessage(MiaoShaMessageVo miaoShaMessageVo) {
String msg = RedisService.beanToString(miaoShaMessageVo);
log.info("send message:{}" , msg);
rabbitTemplate.convertAndSend(MQConfig.MIAOSHATEST,msg);
// rabbitTemplate.convertAndSend(MQConfig.EXCHANGE_TOPIC,"miaosha_*", msg);
}
}
| [
"[email protected]"
] | |
0eac2423963a6bcac4aa88f68644426f324ff479 | a0f6cf75af5cc26f2b9e3ffe5d1f0e81fc4538bb | /audio2mp3/src/main/java/com/czt/mp3recorder/MP3Recorder.java | e5b3bc25b1886b8b7e01bec958a7296741cc5c16 | [] | no_license | juyingguo/AndroidJavaDemoTestForAS | 5ac4ab022e854e6033761af830f0857d8b59d0a8 | 259db4653a58926a90cd3046aa3e8bf883f4b935 | refs/heads/master | 2023-04-14T16:25:00.394511 | 2023-04-05T13:55:04 | 2023-04-05T13:55:04 | 198,392,366 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,341 | java | package com.czt.mp3recorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import com.czt.mp3recorder.util.LameUtil;
import java.io.File;
import java.io.IOException;
public class MP3Recorder {
//=======================AudioRecord Default Settings=======================
private static final int DEFAULT_AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
/**
* 以下三项为默认配置参数。Google Android文档明确表明只有以下3个参数是可以在所有设备上保证支持的。
*/
private static final int DEFAULT_SAMPLING_RATE = 44100;//模拟器仅支持从麦克风输入8kHz采样率
private static final int DEFAULT_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
/**
* 下面是对此的封装
* private static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
*/
private static final PCMFormat DEFAULT_AUDIO_FORMAT = PCMFormat.PCM_16BIT;
//======================Lame Default Settings=====================
private static final int DEFAULT_LAME_MP3_QUALITY = 7;
/**
* 与DEFAULT_CHANNEL_CONFIG相关,因为是mono单声,所以是1
*/
private static final int DEFAULT_LAME_IN_CHANNEL = 1;
/**
* Encoded bit rate. MP3 file will be encoded with bit rate 32kbps
*/
private static final int DEFAULT_LAME_MP3_BIT_RATE = 32;
//==================================================================
private static final int STATR = 1;
private static final int STOP = 2;
/**
* 自定义 每160帧作为一个周期,通知一下需要进行编码
*/
private static final int FRAME_COUNT = 160;
private AudioRecord mAudioRecord = null;
private int mBufferSize;
private short[] mPCMBuffer;
private DataEncodeThread mEncodeThread;
private boolean mIsRecording = false;
private File mRecordFile;
private OnMp3RecorderListener listener;
/**
* Default constructor. Setup recorder with default sampling rate 1 channel,
* 16 bits pcm
* @param recordFile target file
*/
public MP3Recorder(File recordFile) {
mRecordFile = recordFile;
}
/**
* Start recording. Create an encoding thread. Start record from this
* thread.
*
* @throws IOException initAudioRecorder throws
*/
public void start() throws IOException {
if (mIsRecording) return;
initAudioRecorder();
mAudioRecord.startRecording();
Message uMsg = handler.obtainMessage();
uMsg.what = STATR;
handler.sendMessage(uMsg);
mAudioRecord.startRecording();
new Thread() {
@Override
public void run() {
//设置线程权限
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
mIsRecording = true;
while (mIsRecording) {
int readSize = mAudioRecord.read(mPCMBuffer, 0, mBufferSize);
if (readSize > 0) {
mEncodeThread.addTask(mPCMBuffer, readSize);
calculateRealVolume(mPCMBuffer, readSize);
}
}
// release and finalize audioRecord
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
// stop the encoding thread and try to wait
// until the thread finishes its job
Message msg = Message.obtain(mEncodeThread.getHandler(),
DataEncodeThread.PROCESS_STOP);
msg.sendToTarget();
Message uMsg = handler.obtainMessage();
uMsg.what = STOP;
handler.sendMessage(uMsg);
}
/**
* 此计算方法来自samsung开发范例
*
* @param buffer buffer
* @param readSize readSize
*/
private void calculateRealVolume(short[] buffer, int readSize) {
int sum = 0;
for (int i = 0; i < readSize; i++) {
// 这里没有做运算的优化,为了更加清晰的展示代码
sum += buffer[i] * buffer[i];
}
if (readSize > 0) {
double amplitude = sum / readSize;
mVolume = (int) Math.sqrt(amplitude);
}
};
}.start();
}
private int mVolume;
public int getVolume(){
return mVolume;
}
private static final int MAX_VOLUME = 1000;
public int getMaxVolume(){
return MAX_VOLUME;
}
public void stop(){
mIsRecording = false;
}
public boolean isRecording() {
return mIsRecording;
}
/**
* Initialize audio recorder
*/
private void initAudioRecorder() throws IOException {
mBufferSize = AudioRecord.getMinBufferSize(DEFAULT_SAMPLING_RATE,
DEFAULT_CHANNEL_CONFIG, DEFAULT_AUDIO_FORMAT.getAudioFormat());
int bytesPerFrame = DEFAULT_AUDIO_FORMAT.getBytesPerFrame();
/* Get number of samples. Calculate the buffer size
* (round up to the factor of given frame size)
* 使能被整除,方便下面的周期性通知
* */
int frameSize = mBufferSize / bytesPerFrame;
if (frameSize % FRAME_COUNT != 0) {
frameSize += (FRAME_COUNT - frameSize % FRAME_COUNT);
mBufferSize = frameSize * bytesPerFrame;
}
/* Setup audio recorder */
mAudioRecord = new AudioRecord(DEFAULT_AUDIO_SOURCE,
DEFAULT_SAMPLING_RATE, DEFAULT_CHANNEL_CONFIG, DEFAULT_AUDIO_FORMAT.getAudioFormat(),
mBufferSize);
mPCMBuffer = new short[mBufferSize];
/*
* Initialize lame buffer
* mp3 sampling rate is the same as the recorded pcm sampling rate
* The bit rate is 32kbps
*
*/
LameUtil.init(DEFAULT_SAMPLING_RATE, DEFAULT_LAME_IN_CHANNEL, DEFAULT_SAMPLING_RATE, DEFAULT_LAME_MP3_BIT_RATE, DEFAULT_LAME_MP3_QUALITY);
// Create and run thread used to encode data
// The thread will
mEncodeThread = new DataEncodeThread(mRecordFile, mBufferSize);
mEncodeThread.start();
mAudioRecord.setRecordPositionUpdateListener(mEncodeThread, mEncodeThread.getHandler());
mAudioRecord.setPositionNotificationPeriod(FRAME_COUNT);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (listener != null) {
switch (msg.what) {
case STATR:
if (listener != null) {
listener.startMP3Recorder();
}
break;
case STOP:
// listener.stopMP3Recorder();
break;
}
}
}
};
public void setOnMp3RecorderListener(OnMp3RecorderListener listener) {
this.listener = listener;
if (mEncodeThread != null) {
mEncodeThread.setMp3RecorderListener(listener);
}
}
public interface OnMp3RecorderListener {
public void startMP3Recorder();
public void stopMP3Recorder();
}
} | [
"[email protected]"
] | |
e54807ebc8eafb6db178ac6e0e52d3b82b998d20 | c885ef92397be9d54b87741f01557f61d3f794f3 | /results/JacksonDatabind-103/com.fasterxml.jackson.databind.deser.std.StdValueInstantiator/BBC-F0-opt-20/tests/20/com/fasterxml/jackson/databind/deser/std/StdValueInstantiator_ESTest.java | a27f4acb679b1c7eb405d9f7957ccaecd20e5c4c | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 63,555 | java | /*
* This file was automatically generated by EvoSuite
* Thu Oct 21 22:52:54 GMT 2021
*/
package com.fasterxml.jackson.databind.deser.std;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.fasterxml.jackson.annotation.Nulls;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.annotation.ObjectIdResolver;
import com.fasterxml.jackson.annotation.SimpleObjectIdResolver;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.cfg.BaseSettings;
import com.fasterxml.jackson.databind.cfg.ConfigOverrides;
import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fasterxml.jackson.databind.deser.BeanDeserializerFactory;
import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.AnnotatedWithParams;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.introspect.BasicBeanDescription;
import com.fasterxml.jackson.databind.introspect.ClassIntrospector;
import com.fasterxml.jackson.databind.introspect.SimpleMixInResolver;
import com.fasterxml.jackson.databind.introspect.TypeResolutionContext;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapLikeType;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.PlaceholderForType;
import com.fasterxml.jackson.databind.type.ResolvedRecursiveType;
import com.fasterxml.jackson.databind.type.TypeBindings;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.RootNameLookup;
import java.io.PushbackInputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.sql.BatchUpdateException;
import java.sql.ClientInfoStatus;
import java.sql.SQLClientInfoException;
import java.sql.SQLDataException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLNonTransientException;
import java.sql.SQLRecoverableException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTransactionRollbackException;
import java.sql.SQLTransientException;
import java.sql.SQLWarning;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.evosuite.runtime.mock.java.lang.MockThrowable;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class StdValueInstantiator_ESTest extends StdValueInstantiator_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
DeserializerFactoryConfig deserializerFactoryConfig0 = new DeserializerFactoryConfig();
BeanDeserializerFactory beanDeserializerFactory0 = new BeanDeserializerFactory(deserializerFactoryConfig0);
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
JsonMappingException jsonMappingException0 = JsonMappingException.from((JsonParser) null, "");
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLTransientException sQLTransientException0 = new SQLTransientException("", "L^d$kIa/yG\u0006M$-4c,f", (-1), jsonMappingException0);
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, sQLTransientException0);
assertEquals("`java.lang.ExceptionInInitializerError`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test01() throws Throwable {
ObjectMapper objectMapper0 = new ObjectMapper();
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
ObjectReader objectReader0 = objectMapper0.readerFor(class0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test02() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, (JavaType) null, settableBeanPropertyArray0);
Nulls nulls0 = Nulls.DEFAULT;
// Undeclared exception!
try {
stdValueInstantiator0.createUsingArrayDelegate((DeserializationContext) null, nulls0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No delegate constructor for UNKNOWN TYPE
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test03() throws Throwable {
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._delegateArguments = settableBeanPropertyArray0;
// Undeclared exception!
try {
stdValueInstantiator0.createUsingDelegate((DeserializationContext) null, class0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No delegate constructor for `java.lang.ExceptionInInitializerError`
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test04() throws Throwable {
ObjectMapper objectMapper0 = new ObjectMapper();
PlaceholderForType placeholderForType0 = new PlaceholderForType(2086);
ObjectReader objectReader0 = objectMapper0.readerFor((JavaType) placeholderForType0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test05() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, (JavaType) null, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, settableBeanPropertyArray0);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test06() throws Throwable {
Class<SimpleModule> class0 = SimpleModule.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, (JavaType) null, settableBeanPropertyArray0, (AnnotatedWithParams) null, settableBeanPropertyArray0);
assertEquals("`com.fasterxml.jackson.databind.module.SimpleModule`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test07() throws Throwable {
Class<PushbackInputStream> class0 = PushbackInputStream.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<Integer> class1 = Integer.class;
ResolvedRecursiveType resolvedRecursiveType0 = new ResolvedRecursiveType(class1, (TypeBindings) null);
MapLikeType mapLikeType0 = MapLikeType.upgradeFrom(resolvedRecursiveType0, resolvedRecursiveType0, resolvedRecursiveType0);
stdValueInstantiator0._arrayDelegateType = (JavaType) mapLikeType0;
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertEquals("`java.io.PushbackInputStream`", stdValueInstantiator1.getValueTypeDesc());
assertTrue(stdValueInstantiator1.canInstantiate());
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Class<ExceptionInInitializerError> class0 = ExceptionInInitializerError.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._delegateArguments = settableBeanPropertyArray0;
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertEquals("`java.lang.ExceptionInInitializerError`", stdValueInstantiator1.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test09() throws Throwable {
Class<DeserializationFeature> class0 = DeserializationFeature.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._constructorArguments = settableBeanPropertyArray0;
StdValueInstantiator stdValueInstantiator1 = new StdValueInstantiator(stdValueInstantiator0);
assertEquals("`com.fasterxml.jackson.databind.DeserializationFeature`", stdValueInstantiator1.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test10() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromStringCreator((AnnotatedWithParams) null);
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test11() throws Throwable {
Class<Integer> class0 = Integer.TYPE;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromLongCreator((AnnotatedWithParams) null);
assertEquals("`int`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test12() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromIntCreator((AnnotatedWithParams) null);
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.configureFromDoubleCreator((AnnotatedWithParams) null);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test14() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
PlaceholderForType placeholderForType0 = new PlaceholderForType(40);
ArrayType arrayType0 = typeFactory0.constructArrayType((JavaType) placeholderForType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.configureFromBooleanCreator((AnnotatedWithParams) null);
assertEquals("[array type, component type: $41]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test15() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
ObjectMapper objectMapper0 = new ObjectMapper();
DeserializationContext deserializationContext0 = objectMapper0.getDeserializationContext();
SerializerProvider serializerProvider0 = objectMapper0.getSerializerProviderInstance();
JsonMappingException jsonMappingException0 = JsonMappingException.from(serializerProvider0, "i[H^P_/Q|%7j");
stdValueInstantiator0.wrapAsJsonMappingException(deserializationContext0, jsonMappingException0);
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test16() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getWithArgsCreator();
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test17() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
String string0 = stdValueInstantiator0.getValueTypeDesc();
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", string0);
}
@Test(timeout = 4000)
public void test18() throws Throwable {
Class<Integer> class0 = Integer.TYPE;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertEquals("`int`", stdValueInstantiator0.getValueTypeDesc());
assertTrue(class1.isPrimitive());
assertNotNull(class1);
}
@Test(timeout = 4000)
public void test19() throws Throwable {
Class<ObjectIdResolver> class0 = ObjectIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertNotNull(class1);
assertEquals("interface com.fasterxml.jackson.annotation.ObjectIdResolver", class1.toString());
assertEquals("`com.fasterxml.jackson.annotation.ObjectIdResolver`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test20() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<?> class1 = stdValueInstantiator0.getValueClass();
assertEquals(16385, class1.getModifiers());
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
assertNotNull(class1);
}
@Test(timeout = 4000)
public void test21() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
PlaceholderForType placeholderForType0 = new PlaceholderForType(40);
ArrayType arrayType0 = typeFactory0.constructArrayType((JavaType) placeholderForType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
Class<?> class0 = stdValueInstantiator0.getValueClass();
assertEquals(1041, class0.getModifiers());
assertEquals("[array type, component type: $41]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test22() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getIncompleteParameter();
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test23() throws Throwable {
JavaType javaType0 = TypeFactory.unknownType();
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
AnnotatedParameter annotatedParameter0 = new AnnotatedParameter((AnnotatedWithParams) null, javaType0, (TypeResolutionContext) null, (AnnotationMap) null, 0);
stdValueInstantiator0.configureIncompleteParameter(annotatedParameter0);
AnnotatedParameter annotatedParameter1 = stdValueInstantiator0.getIncompleteParameter();
assertNotNull(annotatedParameter1);
assertEquals("[simple type, class java.lang.Object]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test24() throws Throwable {
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getFromObjectArguments((DeserializationConfig) null);
assertEquals("`com.fasterxml.jackson.databind.introspect.BasicBeanDescription`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test25() throws Throwable {
Class<SimpleModule> class0 = SimpleModule.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[9];
stdValueInstantiator0._constructorArguments = settableBeanPropertyArray0;
SettableBeanProperty[] settableBeanPropertyArray1 = stdValueInstantiator0.getFromObjectArguments((DeserializationConfig) null);
assertNotNull(settableBeanPropertyArray1);
assertEquals("`com.fasterxml.jackson.databind.module.SimpleModule`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test26() throws Throwable {
Class<SimpleModule> class0 = SimpleModule.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0._constructorArguments = settableBeanPropertyArray0;
SettableBeanProperty[] settableBeanPropertyArray1 = stdValueInstantiator0.getFromObjectArguments((DeserializationConfig) null);
assertNotNull(settableBeanPropertyArray1);
assertEquals("`com.fasterxml.jackson.databind.module.SimpleModule`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test27() throws Throwable {
Class<ObjectIdGenerators.UUIDGenerator> class0 = ObjectIdGenerators.UUIDGenerator.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class1);
CollectionType collectionType1 = collectionType0.withStaticTyping();
stdValueInstantiator0._delegateType = (JavaType) collectionType1;
JavaType javaType0 = stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertNotNull(javaType0);
assertEquals("`com.fasterxml.jackson.annotation.ObjectIdGenerators$UUIDGenerator`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test28() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<Map> class0 = Map.class;
Class<Integer> class1 = Integer.class;
Class<NamedType> class2 = NamedType.class;
MapType mapType0 = typeFactory0.constructMapType(class0, class1, class2);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, mapType0);
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, mapType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
}
@Test(timeout = 4000)
public void test29() throws Throwable {
Class<ObjectIdGenerators.UUIDGenerator> class0 = ObjectIdGenerators.UUIDGenerator.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class1);
Class<JsonDeserializer> class2 = JsonDeserializer.class;
NamedType namedType0 = new NamedType(class2, "");
CollectionType collectionType1 = collectionType0.withTypeHandler(namedType0);
stdValueInstantiator0._delegateType = (JavaType) collectionType1;
JavaType javaType0 = stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertEquals("`com.fasterxml.jackson.annotation.ObjectIdGenerators$UUIDGenerator`", stdValueInstantiator0.getValueTypeDesc());
assertNotNull(javaType0);
}
@Test(timeout = 4000)
public void test30() throws Throwable {
JavaType javaType0 = TypeFactory.unknownType();
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
stdValueInstantiator0.configureFromObjectSettings((AnnotatedWithParams) null, (AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null, (AnnotatedWithParams) null, (SettableBeanProperty[]) null);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
}
@Test(timeout = 4000)
public void test31() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
PlaceholderForType placeholderForType0 = new PlaceholderForType(40);
ArrayType arrayType0 = typeFactory0.constructArrayType((JavaType) placeholderForType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, arrayType0);
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, arrayType0, (SettableBeanProperty[]) null);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canCreateUsingArrayDelegate());
}
@Test(timeout = 4000)
public void test32() throws Throwable {
JavaType javaType0 = TypeFactory.unknownType();
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, javaType0, (SettableBeanProperty[]) null);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canInstantiate());
}
@Test(timeout = 4000)
public void test33() throws Throwable {
StdSubtypeResolver stdSubtypeResolver0 = new StdSubtypeResolver();
SimpleMixInResolver simpleMixInResolver0 = new SimpleMixInResolver((ClassIntrospector.MixInResolver) null);
RootNameLookup rootNameLookup0 = new RootNameLookup();
ConfigOverrides configOverrides0 = new ConfigOverrides();
DeserializationConfig deserializationConfig0 = new DeserializationConfig((BaseSettings) null, stdSubtypeResolver0, simpleMixInResolver0, rootNameLookup0, configOverrides0);
Class<ClassNameIdResolver> class0 = ClassNameIdResolver.class;
NamedType namedType0 = new NamedType(class0, "com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer");
DeserializationProblemHandler deserializationProblemHandler0 = mock(DeserializationProblemHandler.class, new ViolatedAssumptionAnswer());
doReturn(namedType0).when(deserializationProblemHandler0).handleMissingInstantiator(any(com.fasterxml.jackson.databind.DeserializationContext.class) , any(java.lang.Class.class) , any(com.fasterxml.jackson.databind.deser.ValueInstantiator.class) , any(com.fasterxml.jackson.core.JsonParser.class) , anyString());
DeserializationConfig deserializationConfig1 = deserializationConfig0.withHandler(deserializationProblemHandler0);
JsonParser.Feature jsonParser_Feature0 = JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION;
DeserializationConfig deserializationConfig2 = deserializationConfig1.with(jsonParser_Feature0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator(deserializationConfig1, (JavaType) null);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
InjectableValues.Std injectableValues_Std0 = new InjectableValues.Std();
DefaultDeserializationContext defaultDeserializationContext0 = defaultDeserializationContext_Impl0.createInstance(deserializationConfig2, (JsonParser) null, injectableValues_Std0);
stdValueInstantiator0.createFromString(defaultDeserializationContext0, "com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer");
assertFalse(stdValueInstantiator0.canInstantiate());
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test34() throws Throwable {
StdSubtypeResolver stdSubtypeResolver0 = new StdSubtypeResolver();
SimpleMixInResolver simpleMixInResolver0 = new SimpleMixInResolver((ClassIntrospector.MixInResolver) null);
RootNameLookup rootNameLookup0 = new RootNameLookup();
ConfigOverrides configOverrides0 = new ConfigOverrides();
DeserializationConfig deserializationConfig0 = new DeserializationConfig((BaseSettings) null, stdSubtypeResolver0, simpleMixInResolver0, rootNameLookup0, configOverrides0);
DeserializationProblemHandler deserializationProblemHandler0 = mock(DeserializationProblemHandler.class, new ViolatedAssumptionAnswer());
doReturn((Object) null).when(deserializationProblemHandler0).handleMissingInstantiator(any(com.fasterxml.jackson.databind.DeserializationContext.class) , any(java.lang.Class.class) , any(com.fasterxml.jackson.databind.deser.ValueInstantiator.class) , any(com.fasterxml.jackson.core.JsonParser.class) , anyString());
DeserializationConfig deserializationConfig1 = deserializationConfig0.withHandler(deserializationProblemHandler0);
JsonParser.Feature jsonParser_Feature0 = JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION;
DeserializationConfig deserializationConfig2 = deserializationConfig1.with(jsonParser_Feature0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator(deserializationConfig2, (JavaType) null);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
InjectableValues.Std injectableValues_Std0 = new InjectableValues.Std();
DefaultDeserializationContext defaultDeserializationContext0 = defaultDeserializationContext_Impl0.createInstance(deserializationConfig2, (JsonParser) null, injectableValues_Std0);
stdValueInstantiator0.createFromInt(defaultDeserializationContext0, 0);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test35() throws Throwable {
StdSubtypeResolver stdSubtypeResolver0 = new StdSubtypeResolver();
SimpleMixInResolver simpleMixInResolver0 = new SimpleMixInResolver((ClassIntrospector.MixInResolver) null);
RootNameLookup rootNameLookup0 = new RootNameLookup();
ConfigOverrides configOverrides0 = new ConfigOverrides();
DeserializationConfig deserializationConfig0 = new DeserializationConfig((BaseSettings) null, stdSubtypeResolver0, simpleMixInResolver0, rootNameLookup0, configOverrides0);
Class<ClassNameIdResolver> class0 = ClassNameIdResolver.class;
NamedType namedType0 = new NamedType(class0, "com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer");
DeserializationProblemHandler deserializationProblemHandler0 = mock(DeserializationProblemHandler.class, new ViolatedAssumptionAnswer());
doReturn(namedType0).when(deserializationProblemHandler0).handleMissingInstantiator(any(com.fasterxml.jackson.databind.DeserializationContext.class) , any(java.lang.Class.class) , any(com.fasterxml.jackson.databind.deser.ValueInstantiator.class) , any(com.fasterxml.jackson.core.JsonParser.class) , anyString());
DeserializationConfig deserializationConfig1 = deserializationConfig0.withHandler(deserializationProblemHandler0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator(deserializationConfig0, (JavaType) null);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
InjectableValues.Std injectableValues_Std0 = new InjectableValues.Std();
DefaultDeserializationContext defaultDeserializationContext0 = defaultDeserializationContext_Impl0.createInstance(deserializationConfig1, (JsonParser) null, injectableValues_Std0);
stdValueInstantiator0.createFromInt(defaultDeserializationContext0, 0);
assertEquals("UNKNOWN TYPE", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test36() throws Throwable {
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingDelegate();
assertEquals("`com.fasterxml.jackson.databind.introspect.BasicBeanDescription`", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test37() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<EnumSet> class0 = EnumSet.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class0, class0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, collectionType0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingDefault();
assertFalse(boolean0);
assertEquals("[collection type; class java.util.EnumSet, contains [collection type; class java.util.EnumSet, contains [simple type, class java.lang.Enum]]]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test38() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingArrayDelegate();
assertFalse(boolean0);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test39() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromObjectWith();
assertFalse(boolean0);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test40() throws Throwable {
Class<Integer> class0 = Integer.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLSyntaxErrorException sQLSyntaxErrorException0 = new SQLSyntaxErrorException("", (String) null, 1);
SQLNonTransientConnectionException sQLNonTransientConnectionException0 = new SQLNonTransientConnectionException("com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BooleanDeserializer", "", (-1), sQLSyntaxErrorException0);
sQLSyntaxErrorException0.initCause(sQLNonTransientConnectionException0);
SQLTransactionRollbackException sQLTransactionRollbackException0 = new SQLTransactionRollbackException("com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BooleanDeserializer", "", 1, sQLNonTransientConnectionException0);
// Undeclared exception!
stdValueInstantiator0.wrapException(sQLTransactionRollbackException0);
}
@Test(timeout = 4000)
public void test41() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.wrapException((Throwable) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test42() throws Throwable {
Class<DeserializationFeature> class0 = DeserializationFeature.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLIntegrityConstraintViolationException sQLIntegrityConstraintViolationException0 = new SQLIntegrityConstraintViolationException();
SQLRecoverableException sQLRecoverableException0 = new SQLRecoverableException("", "END_ARRAY", (-1730), sQLIntegrityConstraintViolationException0);
SQLDataException sQLDataException0 = new SQLDataException("", "", sQLRecoverableException0);
SQLWarning sQLWarning0 = new SQLWarning("", sQLDataException0);
SQLTransactionRollbackException sQLTransactionRollbackException0 = new SQLTransactionRollbackException(sQLWarning0);
// Undeclared exception!
try {
stdValueInstantiator0.wrapAsJsonMappingException((DeserializationContext) null, sQLTransactionRollbackException0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test43() throws Throwable {
Class<NamedType> class0 = NamedType.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
HashMap<String, ClientInfoStatus> hashMap0 = new HashMap<String, ClientInfoStatus>();
SQLClientInfoException sQLClientInfoException0 = new SQLClientInfoException("j'O-dw*}b_jkex$L:", "j'O-dw*}b_jkex$L:", 6, hashMap0);
SQLNonTransientException sQLNonTransientException0 = new SQLNonTransientException("com.fasterxml.jackson.databind.deser.std.AtomicBooleanDeserializer", "", 6, sQLClientInfoException0);
sQLClientInfoException0.initCause(sQLNonTransientException0);
// Undeclared exception!
stdValueInstantiator0.unwrapAndWrapException((DeserializationContext) null, sQLClientInfoException0);
}
@Test(timeout = 4000)
public void test44() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = null;
try {
stdValueInstantiator0 = new StdValueInstantiator((StdValueInstantiator) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test45() throws Throwable {
Class<BasicBeanDescription> class0 = BasicBeanDescription.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Class<SimpleObjectIdResolver> class1 = SimpleObjectIdResolver.class;
TypeBindings typeBindings0 = TypeBindings.emptyBindings();
JavaType javaType0 = TypeFactory.unknownType();
JavaType[] javaTypeArray0 = new JavaType[5];
javaTypeArray0[2] = javaType0;
CollectionType collectionType0 = CollectionType.construct(class1, typeBindings0, javaType0, javaTypeArray0, javaTypeArray0[2]);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, collectionType0, settableBeanPropertyArray0);
boolean boolean0 = stdValueInstantiator0.canCreateUsingArrayDelegate();
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test46() throws Throwable {
StdSubtypeResolver stdSubtypeResolver0 = new StdSubtypeResolver();
RootNameLookup rootNameLookup0 = new RootNameLookup();
ConfigOverrides configOverrides0 = new ConfigOverrides();
DeserializationConfig deserializationConfig0 = new DeserializationConfig((BaseSettings) null, stdSubtypeResolver0, (SimpleMixInResolver) null, rootNameLookup0, configOverrides0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<EnumSet> class0 = EnumSet.class;
Class<String> class1 = String.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class0, class1);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator(deserializationConfig0, collectionType0);
boolean boolean0 = stdValueInstantiator0.canCreateFromBoolean();
assertEquals("[collection type; class java.util.EnumSet, contains [simple type, class java.lang.String]]", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test47() throws Throwable {
JavaType javaType0 = TypeFactory.unknownType();
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
boolean boolean0 = stdValueInstantiator0.canCreateFromDouble();
assertFalse(boolean0);
assertEquals("[simple type, class java.lang.Object]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test48() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromLong();
assertFalse(boolean0);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test49() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromInt();
assertEquals("`com.fasterxml.jackson.databind.JsonMappingException`", stdValueInstantiator0.getValueTypeDesc());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test50() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canCreateFromString();
assertFalse(boolean0);
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test51() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
SQLWarning sQLWarning0 = new SQLWarning("Y!f6-{LdxsqPgHJ$AO", "Y!f6-{LdxsqPgHJ$AO");
InvocationTargetException invocationTargetException0 = new InvocationTargetException(sQLWarning0, "Y!f6-{LdxsqPgHJ$AO");
// Undeclared exception!
try {
stdValueInstantiator0.rewrapCtorProblem((DeserializationContext) null, invocationTargetException0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test52() throws Throwable {
Class<JsonMappingException> class0 = JsonMappingException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
ExceptionInInitializerError exceptionInInitializerError0 = new ExceptionInInitializerError((Throwable) null);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.rewrapCtorProblem(defaultDeserializationContext_Impl0, exceptionInInitializerError0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test53() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<JsonMappingException> class0 = JsonMappingException.class;
Class<ExceptionInInitializerError>[] classArray0 = (Class<ExceptionInInitializerError>[]) Array.newInstance(Class.class, 0);
JavaType javaType0 = typeFactory0.constructParametricType(class0, classArray0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
SQLSyntaxErrorException sQLSyntaxErrorException0 = new SQLSyntaxErrorException("!!Tb%vS8o^B", "");
JsonMappingException jsonMappingException0 = JsonMappingException.from((DeserializationContext) defaultDeserializationContext_Impl0, "><`F", (Throwable) sQLSyntaxErrorException0);
stdValueInstantiator0.rewrapCtorProblem(defaultDeserializationContext_Impl0, jsonMappingException0);
assertEquals("[simple type, class com.fasterxml.jackson.databind.JsonMappingException]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test54() throws Throwable {
DeserializerFactoryConfig deserializerFactoryConfig0 = new DeserializerFactoryConfig();
BeanDeserializerFactory beanDeserializerFactory0 = new BeanDeserializerFactory(deserializerFactoryConfig0);
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
int[] intArray0 = new int[8];
BatchUpdateException batchUpdateException0 = new BatchUpdateException(intArray0);
JsonMappingException jsonMappingException0 = stdValueInstantiator0.wrapException(batchUpdateException0);
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, jsonMappingException0);
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test55() throws Throwable {
DeserializerFactoryConfig deserializerFactoryConfig0 = new DeserializerFactoryConfig();
BeanDeserializerFactory beanDeserializerFactory0 = new BeanDeserializerFactory(deserializerFactoryConfig0);
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
int[] intArray0 = new int[3];
BatchUpdateException batchUpdateException0 = new BatchUpdateException(intArray0);
// Undeclared exception!
try {
stdValueInstantiator0.unwrapAndWrapException(defaultDeserializationContext_Impl0, batchUpdateException0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test56() throws Throwable {
Class<TypeIdResolver> class0 = TypeIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
ObjectMapper objectMapper0 = new ObjectMapper();
SerializerProvider serializerProvider0 = objectMapper0.getSerializerProviderInstance();
JsonMappingException jsonMappingException0 = JsonMappingException.from(serializerProvider0, "i[H^P_/Q|%7j");
MockThrowable mockThrowable0 = new MockThrowable(jsonMappingException0);
JsonMappingException jsonMappingException1 = stdValueInstantiator0.wrapException(mockThrowable0);
assertSame(jsonMappingException1, jsonMappingException0);
assertEquals("`com.fasterxml.jackson.databind.jsontype.TypeIdResolver`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test57() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromBoolean((DeserializationContext) null, true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.ValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test58() throws Throwable {
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
PlaceholderForType placeholderForType0 = new PlaceholderForType(450);
MapLikeType mapLikeType0 = MapLikeType.upgradeFrom(placeholderForType0, placeholderForType0, placeholderForType0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, mapLikeType0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromDouble(defaultDeserializationContext_Impl0, 450);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test59() throws Throwable {
DeserializerFactoryConfig deserializerFactoryConfig0 = new DeserializerFactoryConfig();
BeanDeserializerFactory beanDeserializerFactory0 = new BeanDeserializerFactory(deserializerFactoryConfig0);
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromLong(defaultDeserializationContext_Impl0, 2730L);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test60() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromString((DeserializationContext) null, "JSON");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.deser.ValueInstantiator", e);
}
}
@Test(timeout = 4000)
public void test61() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<JsonMappingException> class0 = JsonMappingException.class;
Class<ExceptionInInitializerError>[] classArray0 = (Class<ExceptionInInitializerError>[]) Array.newInstance(Class.class, 0);
JavaType javaType0 = typeFactory0.constructParametricType(class0, classArray0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromObjectWith((DeserializationContext) defaultDeserializationContext_Impl0, (Object[]) classArray0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test62() throws Throwable {
DeserializerFactoryConfig deserializerFactoryConfig0 = new DeserializerFactoryConfig();
BeanDeserializerFactory beanDeserializerFactory0 = new BeanDeserializerFactory(deserializerFactoryConfig0);
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
// Undeclared exception!
try {
stdValueInstantiator0.createUsingDefault(defaultDeserializationContext_Impl0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test63() throws Throwable {
Class<ObjectIdGenerators.UUIDGenerator> class0 = ObjectIdGenerators.UUIDGenerator.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class1);
stdValueInstantiator0._delegateType = (JavaType) collectionType0;
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertTrue(stdValueInstantiator0.canCreateUsingDelegate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test64() throws Throwable {
ObjectMapper objectMapper0 = new ObjectMapper();
Integer integer0 = new Integer((-262));
Class<SimpleObjectIdResolver> class0 = SimpleObjectIdResolver.class;
try {
objectMapper0.convertValue((Object) integer0, class0);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Cannot construct instance of `com.fasterxml.jackson.annotation.SimpleObjectIdResolver` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (-262)
// at [Source: UNKNOWN; line: -1, column: -1]
//
verifyException("com.fasterxml.jackson.databind.ObjectMapper", e);
}
}
@Test(timeout = 4000)
public void test65() throws Throwable {
Class<ClassNameIdResolver> class0 = ClassNameIdResolver.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
Stack<JavaType> stack0 = new Stack<JavaType>();
TypeBindings typeBindings0 = TypeBindings.create((Class<?>) class0, (List<JavaType>) stack0);
JavaType javaType0 = TypeFactory.unknownType();
ArrayType arrayType0 = ArrayType.construct(javaType0, typeBindings0, (Object) typeBindings0, (Object) stack0);
SettableBeanProperty[] settableBeanPropertyArray0 = new SettableBeanProperty[0];
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, arrayType0, settableBeanPropertyArray0);
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertTrue(stdValueInstantiator0.canCreateUsingArrayDelegate());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test66() throws Throwable {
Class<ObjectIdGenerators.UUIDGenerator> class0 = ObjectIdGenerators.UUIDGenerator.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<List> class1 = List.class;
CollectionType collectionType0 = typeFactory0.constructCollectionType(class1, class1);
stdValueInstantiator0._delegateType = (JavaType) collectionType0;
boolean boolean0 = stdValueInstantiator0.canCreateUsingDelegate();
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test67() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
boolean boolean0 = stdValueInstantiator0.canInstantiate();
assertFalse(boolean0);
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test68() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (JavaType) null);
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<Map> class0 = Map.class;
Class<SimpleObjectIdResolver> class1 = SimpleObjectIdResolver.class;
MapType mapType0 = typeFactory0.constructMapType(class0, class0, class1);
MapLikeType mapLikeType0 = mapType0.withValueHandler(typeFactory0);
stdValueInstantiator0.configureFromArraySettings((AnnotatedWithParams) null, mapLikeType0, (SettableBeanProperty[]) null);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertTrue(stdValueInstantiator0.canInstantiate());
}
@Test(timeout = 4000)
public void test69() throws Throwable {
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, (Class<?>) null);
assertFalse(stdValueInstantiator0.canCreateFromBoolean());
}
@Test(timeout = 4000)
public void test70() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
ObjectMapper objectMapper0 = new ObjectMapper();
String string0 = objectMapper0.writeValueAsString(stdValueInstantiator0);
assertEquals("{\"incompleteParameter\":null,\"arrayDelegateCreator\":null,\"defaultCreator\":null,\"delegateCreator\":null,\"withArgsCreator\":null,\"valueClass\":\"com.fasterxml.jackson.annotation.Nulls\",\"valueTypeDesc\":\"`com.fasterxml.jackson.annotation.Nulls`\"}", string0);
}
@Test(timeout = 4000)
public void test71() throws Throwable {
Class<Nulls> class0 = Nulls.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getDefaultCreator();
assertEquals("`com.fasterxml.jackson.annotation.Nulls`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test72() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<JsonMappingException> class0 = JsonMappingException.class;
Class<ExceptionInInitializerError>[] classArray0 = (Class<ExceptionInInitializerError>[]) Array.newInstance(Class.class, 0);
JavaType javaType0 = typeFactory0.constructParametricType(class0, classArray0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
stdValueInstantiator0.getArrayDelegateType((DeserializationConfig) null);
assertEquals("[simple type, class com.fasterxml.jackson.databind.JsonMappingException]", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test73() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<JsonMappingException> class0 = JsonMappingException.class;
Class<ExceptionInInitializerError>[] classArray0 = (Class<ExceptionInInitializerError>[]) Array.newInstance(Class.class, 0);
JavaType javaType0 = typeFactory0.constructParametricType(class0, classArray0);
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, javaType0);
BeanDeserializerFactory beanDeserializerFactory0 = BeanDeserializerFactory.instance;
DefaultDeserializationContext.Impl defaultDeserializationContext_Impl0 = new DefaultDeserializationContext.Impl(beanDeserializerFactory0);
// Undeclared exception!
try {
stdValueInstantiator0.createFromInt(defaultDeserializationContext_Impl0, (-1476));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.fasterxml.jackson.databind.DeserializationContext", e);
}
}
@Test(timeout = 4000)
public void test74() throws Throwable {
Class<InvocationTargetException> class0 = InvocationTargetException.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getArrayDelegateCreator();
assertEquals("`java.lang.reflect.InvocationTargetException`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test75() throws Throwable {
TypeFactory typeFactory0 = TypeFactory.defaultInstance();
Class<JsonMappingException> class0 = JsonMappingException.class;
Class<ExceptionInInitializerError>[] classArray0 = (Class<ExceptionInInitializerError>[]) Array.newInstance(Class.class, 0);
JavaType javaType0 = typeFactory0.constructParametricType(class0, classArray0);
JsonFactory jsonFactory0 = new JsonFactory();
ObjectMapper objectMapper0 = new ObjectMapper(jsonFactory0);
ObjectReader objectReader0 = objectMapper0.readerFor(javaType0);
assertNotNull(objectReader0);
}
@Test(timeout = 4000)
public void test76() throws Throwable {
Class<Object> class0 = Object.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getDelegateCreator();
assertEquals("`java.lang.Object`", stdValueInstantiator0.getValueTypeDesc());
}
@Test(timeout = 4000)
public void test77() throws Throwable {
Class<ObjectIdGenerators.UUIDGenerator> class0 = ObjectIdGenerators.UUIDGenerator.class;
StdValueInstantiator stdValueInstantiator0 = new StdValueInstantiator((DeserializationConfig) null, class0);
stdValueInstantiator0.getDelegateType((DeserializationConfig) null);
assertEquals("`com.fasterxml.jackson.annotation.ObjectIdGenerators$UUIDGenerator`", stdValueInstantiator0.getValueTypeDesc());
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.