blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
64815b47fb12d5c31110d696eb18afab90d72f77 | Java | ajpahl1008/elasticagent | /src/test/java/ElasticAgentTest.java | UTF-8 | 1,857 | 2.328125 | 2 | [] | no_license |
import co.elastic.agent.models.configuration.Configuration;
import org.junit.Assert;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ElasticAgentTest {
@Test
public void ReadConfigFileForUrl() throws Exception {
Yaml yaml = new Yaml();
InputStream in = Files.newInputStream(Paths.get("src/test/resources/elasticagent.yml"));
Configuration config = yaml.loadAs(in, Configuration.class);
Assert.assertEquals("http://192.168.0.214:8200", config.getConnection().getUrl());
}
@Test
public void ReadConfigFileForPackageWithJDK() throws Exception {
Yaml yaml = new Yaml();
InputStream in = Files.newInputStream(Paths.get("src/test/resources/elasticagent.yml"));
Configuration config = yaml.loadAs(in, Configuration.class);
Assert.assertEquals("jdk", config.getSkip().get(2)); //should be the 3rd package in the list
}
@Test
public void ReadConfigAndCheckForPackage() throws Exception {
Yaml yaml = new Yaml();
InputStream in = Files.newInputStream(Paths.get("src/test/resources/elasticagent.yml"));
Configuration config = yaml.loadAs(in, Configuration.class);
int location = config.getSkip().indexOf("jdk");
Assert.assertEquals(location, 2); //should be the 3rd package in the list
}
@Test
public void ReadConfigAndDoesntContainPackage() throws Exception {
Yaml yaml = new Yaml();
InputStream in = Files.newInputStream(Paths.get("src/test/resources/elasticagent.yml"));
Configuration config = yaml.loadAs(in, Configuration.class);
int location = config.getSkip().indexOf("dude");
Assert.assertEquals(location, -1); //should be the 3rd package in the list
}
}
| true |
de4e7a77ed5563aac275e8fdd85d98ed1395e584 | Java | zrbtmn/DataBase | /daos/DAO.java | UTF-8 | 188 | 2.3125 | 2 | [] | no_license | package daos;
import java.util.List;
public interface DAO<T> {
void add(T object);
List <T> getAll();
T get(T obj);
void update(T object);
void remove(T object);
}
| true |
c66e865d70b60c8336ecdd14eb462da73bce5021 | Java | gavin1332/complib | /src/util/Util.java | UTF-8 | 1,220 | 3.375 | 3 | [] | no_license | package util;
public class Util {
private static void swap(int[] data, int from, int to) {
int temp = data[from];
data[from] = data[to];
data[to] = temp;
}
public static int partition(int[] data, int begin, int end) {
if (end - begin <= 1)
return -1;
int pivotIdx = (begin + end) / 2;
int pivot = data[pivotIdx];
int tail = end - 1;
swap(data, pivotIdx, tail);
int small = begin - 1;
for (int i = begin; i < tail; ++i) {
if (data[i] < pivot) {
++small;
if (small != i) {
swap(data, small, i);
}
}
}
++small;
swap(data, small, tail);
return small;
}
public static int partition2(int[] data, int begin, int end) {
if (end - begin <= 1)
return -1;
int pivotIdx = (begin + end) / 2;
int pivot = data[pivotIdx];
swap(data, pivotIdx, end - 1);
int l = begin;
int r = end - 2;
while (true) {
for (; data[l] < pivot; ++l) {
}
for (; r >= l && data[r] >= pivot; --r) {
}
if (l > r)
break;
swap(data, l, r);
}
swap(data, l, end - 1);
return l;
}
}
| true |
30b4ccaca0b399b7446a2961131a4e461b1f9092 | Java | rpuerta85/JEE_ECP | /src/main/java/es/miw/jeeecp/view/web/beans/ViewBean.java | UTF-8 | 893 | 2.09375 | 2 | [] | no_license | package es.miw.jeeecp.view.web.beans;
import javax.faces.bean.ManagedProperty;
import com.google.gson.Gson;
import es.miw.jeeecp.controllers.ControllerFactory;
import es.miw.jeeecp.controllers.ejbs.ControllerEjbFactory;
public abstract class ViewBean {
@ManagedProperty(value = "#{controllerFactory}")
private ControllerFactory controllerFactory ;
public ViewBean() {
}
public void setControllerFactory(ControllerFactory controllerFactory) {
this.controllerFactory = controllerFactory;
}
protected ControllerFactory getControllerFactory() {
return controllerFactory;
}
public String toJsonString(){
return new Gson().toJson(this);
}
public <T> T jsonStringToObject(Class<T> clase,String json){
T tipo = new Gson().fromJson(json, clase);
return tipo;
}
}
| true |
f0fee615d1f39b02bae1f2fc144c053bf88ae774 | Java | 772515104/MONKOVEL | /app/src/main/java/com/monke/monkeybook/help/ReadBookControl.java | UTF-8 | 8,704 | 2.046875 | 2 | [] | no_license | //Copyright (c) 2017. 章钦豪. All rights reserved.
package com.monke.monkeybook.help;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import com.monke.monkeybook.MApplication;
import com.monke.monkeybook.R;
import com.monke.monkeybook.utils.DensityUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReadBookControl {
public static final int DEFAULT_TEXT = 3;
public static final int DEFAULT_BG = 1;
private static List<Map<String, Integer>> textKind;
private static List<Map<String, Integer>> textDrawable;
private int textSize;
private int textExtra;
private int textColor;
private int textBackground;
private float lineMultiplier;
private int lineNum;
private int textKindIndex = DEFAULT_TEXT;
private int textDrawableIndex = DEFAULT_BG;
private Boolean canClickTurn = true;
private Boolean canKeyTurn = true;
private Boolean keepScreenOn = false;
private int clickSensitivity = 1;
private Boolean clickAllNext = false;
private Boolean clickAnim = true;
private SharedPreferences preference;
private SharedPreferences defaultPreference;
private static ReadBookControl readBookControl;
public static ReadBookControl getInstance() {
if (readBookControl == null) {
synchronized (ReadBookControl.class) {
if (readBookControl == null) {
readBookControl = new ReadBookControl();
}
}
}
return readBookControl;
}
private ReadBookControl() {
initTextKind();
initTextDrawable();
preference = MApplication.getInstance().getSharedPreferences("CONFIG", 0);
defaultPreference = PreferenceManager.getDefaultSharedPreferences(MApplication.getInstance());
this.textKindIndex = preference.getInt("textKindIndex", DEFAULT_TEXT);
this.textSize = textKind.get(textKindIndex).get("textSize");
this.textExtra = textKind.get(textKindIndex).get("textExtra");
this.textDrawableIndex = preference.getInt("textDrawableIndex", DEFAULT_BG);
this.textColor = textDrawable.get(textDrawableIndex).get("textColor");
this.textBackground = textDrawable.get(textDrawableIndex).get("textBackground");
this.canClickTurn = preference.getBoolean("canClickTurn", true);
this.canKeyTurn = preference.getBoolean("canKeyTurn", true);
this.keepScreenOn = preference.getBoolean("keepScreenOn", false);
this.lineMultiplier = preference.getFloat("lineMultiplier", 1);
this.lineNum = preference.getInt("lineNum", 0);
this.clickSensitivity = preference.getInt("clickSensitivity", 10);
this.clickAllNext = preference.getBoolean("clickAllNext", false);
this.clickAnim = preference.getBoolean("clickAnim", true);
}
//字体大小
private void initTextKind() {
if (null == textKind) {
textKind = new ArrayList<>();
for (int i = 14; i<=30; i=i+2) {
Map<String, Integer> temp = new HashMap<>();
temp.put("textSize", i);
temp.put("textExtra", DensityUtil.dp2px(MApplication.getInstance(), i/2));
textKind.add(temp);
}
}
}
//阅读背景
private void initTextDrawable() {
if (null == textDrawable) {
textDrawable = new ArrayList<>();
Map<String, Integer> temp1 = new HashMap<>();
temp1.put("textColor", Color.parseColor("#3E3D3B"));
temp1.put("textBackground", R.drawable.shape_bg_readbook_white);
textDrawable.add(temp1);
Map<String, Integer> temp2 = new HashMap<>();
temp2.put("textColor", Color.parseColor("#5E432E"));
temp2.put("textBackground", R.drawable.bg_readbook_yellow);
textDrawable.add(temp2);
Map<String, Integer> temp3 = new HashMap<>();
temp3.put("textColor", Color.parseColor("#22482C"));
temp3.put("textBackground", R.drawable.bg_readbook_green);
textDrawable.add(temp3);
Map<String, Integer> temp4 = new HashMap<>();
temp4.put("textColor", Color.parseColor("#808080"));
temp4.put("textBackground", R.drawable.bg_readbook_black);
textDrawable.add(temp4);
}
}
public int getTextSize() {
return textSize;
}
public int getTextExtra() {
return textExtra;
}
public int getTextColor() {
if (defaultPreference.getBoolean("nightTheme", false)) {
return textDrawable.get(3).get("textColor");
}
return textColor;
}
public int getTextBackground() {
if (defaultPreference.getBoolean("nightTheme", false)) {
return textDrawable.get(3).get("textBackground");
}
return textBackground;
}
public int getTextKindIndex() {
return textKindIndex;
}
public void setTextKindIndex(int textKindIndex) {
this.textKindIndex = textKindIndex;
SharedPreferences.Editor editor = preference.edit();
editor.putInt("textKindIndex", textKindIndex);
editor.apply();
this.textSize = textKind.get(textKindIndex).get("textSize");
this.textExtra = textKind.get(textKindIndex).get("textExtra");
}
public int getTextDrawableIndex() {
return textDrawableIndex;
}
public void setTextDrawableIndex(int textDrawableIndex) {
this.textDrawableIndex = textDrawableIndex;
SharedPreferences.Editor editor = preference.edit();
editor.putInt("textDrawableIndex", textDrawableIndex);
editor.apply();
this.textColor = textDrawable.get(textDrawableIndex).get("textColor");
this.textBackground = textDrawable.get(textDrawableIndex).get("textBackground");
}
public static List<Map<String, Integer>> getTextKind() {
return textKind;
}
public static List<Map<String, Integer>> getTextDrawable() {
return textDrawable;
}
public Boolean getCanKeyTurn() {
return canKeyTurn;
}
public void setCanKeyTurn(Boolean canKeyTurn) {
this.canKeyTurn = canKeyTurn;
SharedPreferences.Editor editor = preference.edit();
editor.putBoolean("canKeyTurn", canKeyTurn);
editor.apply();
}
public Boolean getCanClickTurn() {
return canClickTurn;
}
public void setCanClickTurn(Boolean canClickTurn) {
this.canClickTurn = canClickTurn;
SharedPreferences.Editor editor = preference.edit();
editor.putBoolean("canClickTurn", canClickTurn);
editor.apply();
}
public Boolean getKeepScreenOn() {
return keepScreenOn;
}
public void setKeepScreenOn(Boolean keepScreenOn) {
this.keepScreenOn = keepScreenOn;
SharedPreferences.Editor editor = preference.edit();
editor.putBoolean("keepScreenOn", keepScreenOn);
editor.apply();
}
public float getLineMultiplier() {
return lineMultiplier;
}
public void setLineMultiplier(float lineMultiplier) {
this.lineMultiplier = lineMultiplier;
SharedPreferences.Editor editor = preference.edit();
editor.putFloat("lineMultiplier", lineMultiplier);
editor.apply();
}
public int getLineNum() {
return lineNum;
}
public void setLineNum(int lineNum) {
this.lineNum = lineNum;
SharedPreferences.Editor editor = preference.edit();
editor.putInt("lineNum", lineNum);
editor.apply();
}
public int getClickSensitivity() {
return clickSensitivity;
}
public void setClickSensitivity(int clickSensitivity) {
this.clickSensitivity = clickSensitivity;
SharedPreferences.Editor editor = preference.edit();
editor.putInt("clickSensitivity", clickSensitivity);
editor.apply();
}
public Boolean getClickAllNext() {
return clickAllNext;
}
public void setClickAllNext(Boolean clickAllNext) {
this.clickAllNext = clickAllNext;
SharedPreferences.Editor editor = preference.edit();
editor.putBoolean("clickAllNext", clickAllNext);
editor.apply();
}
public Boolean getClickAnim() {
return clickAnim;
}
public void setClickAnim(Boolean clickAnim) {
this.clickAnim = clickAnim;
SharedPreferences.Editor editor = preference.edit();
editor.putBoolean("clickAnim", clickAnim);
editor.apply();
}
} | true |
45b4ac0bf5367c50ce6e8231ee2c50c450e8f087 | Java | WendySun58/Java-Programming | /CaesarCipher/CaesarCipher.java | UTF-8 | 3,617 | 3.84375 | 4 | [] | no_license |
/**
* Write a description of CaesarCipher here.
*
* @WendySun
* @version (a version number or a date)
*/
import edu.duke.*;
public class CaesarCipher {
//This method returns a string that has been encrypted using the Caesar
// Cipher Algorithm explained in the videos
public String encrypt(String input, int key) {
StringBuilder encrypted=new StringBuilder(input);
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String shiftedAlphabet=alphabet.substring(key)+alphabet.substring(0,key);
for(int i=0;i<encrypted.length();i++) {
char ch=encrypted.charAt(i);
int idx=alphabet.indexOf(ch);
if(idx!=-1) {
char newChar=shiftedAlphabet.charAt(idx);
encrypted.setCharAt(i,newChar);
}
}
return encrypted.toString();
}
// Modify the encrypt method to be able to handle both uppercase and lowercase letters
public String encrypt2(String input, int key) {
StringBuilder encrypted=new StringBuilder(input);
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String shiftedAlphabet=alphabet.substring(key)+alphabet.substring(0,key);
for(int i=0;i<encrypted.length();i++) {
char ch=encrypted.charAt(i);
// Transfer to upperCase to compare
int idx=alphabet.indexOf(Character.toUpperCase(ch));
if(idx!=-1) {
char newChar=shiftedAlphabet.charAt(idx);
// if current char is lowerCase, set newChar to lowerCase
if(Character.isLowerCase(ch)==true)
newChar=Character.toLowerCase(newChar);
encrypted.setCharAt(i,newChar);
}
}
return encrypted.toString();
}
//This method returns a String that has been encrypted using the following algorithm.
//Parameter key1is used to encrypt every other character with the Caesar Cipher algorithm,
//starting with the first character, and key2is used to encrypt every other character,
//starting with the second character.
public String encryptTwoKeys(String input, int key1, int key2) {
StringBuilder encrypted=new StringBuilder(input);
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String shiftedAlphabet1=alphabet.substring(key1)+alphabet.substring(0,key1);
String shiftedAlphabet2=alphabet.substring(key2)+alphabet.substring(0,key2);
for(int i=0;i<encrypted.length();i++) {
char ch=encrypted.charAt(i);
int idx=alphabet.indexOf(Character.toUpperCase(ch));
if(idx!=-1) {
char newChar;
if(i%2==0) newChar=shiftedAlphabet1.charAt(idx);
else newChar=shiftedAlphabet2.charAt(idx);
if(Character.isLowerCase(ch)==true)
newChar=Character.toLowerCase(newChar);
encrypted.setCharAt(i,newChar);
}
}
return encrypted.toString();
}
// test function
public void testCaesar() {
FileResource fr=new FileResource();
String message=fr.asString();
int key=23;
int key2=17;
String encrypted1=encrypt(message,key);
System.out.println("1.Key is "+key+"\n" +encrypted1);
String encrypted2=encrypt2(message,key);
System.out.println("2.Key is "+key+"\n" +encrypted2);
String encrypted3=encryptTwoKeys(message,key,key2);
System.out.println("3.Key1 is "+key+", Key2 is "+key2+"\n" +encrypted3);
}
}
| true |
389dd7ecd07c85551dd05fcd519378d01457bb53 | Java | fanjingdan012/sns | /src/main/java/com/fjd/controller/HelloController.java | UTF-8 | 11,908 | 2.40625 | 2 | [] | no_license | package com.fjd.controller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.fjd.facebook.FacebookClientServiceImpl;
import com.fjd.facebook.FacebookOauthServiceImpl;
@Controller
public class HelloController {
/**
* Be sure to specify the name of your application. If the application name is {@code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static String appId = "";
private static String appSecret = "";
private static String redirectUri = "";
private static String proxyHost = "";
private static String proxyPort = "";
@RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
@RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET)
public ModelAndView hello(@PathVariable("name") String name) {
ModelAndView model = new ModelAndView();
model.setViewName("hello");
model.addObject("msg", name);
return model;
}
@RequestMapping(value = "/gmail", method = RequestMethod.GET)
public ModelAndView gmail(String name, HttpServletResponse response) throws Exception {
/*
* GoogleOAuth oauth = new GoogleOAuth();
* oauth.accessTokenRequest(response);
*/
FacebookOauthServiceImpl fbos=new FacebookOauthServiceImpl();
String url =fbos.getAuthorizationUrl(appId,appSecret,redirectUri);
response.sendRedirect(url);
ModelAndView model = new ModelAndView();
model.setViewName("facebook");
return model;
}
// @RequestMapping(value = "/receive", method = RequestMethod.POST)
// public ModelAndView oauth2callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
// append("./messagesPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.txt", "messagereceived\n");
// ServletInputStream reader = request.getInputStream();
// // Parse the JSON message to the POJO model class.
// JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(reader);
// parser.skipToKey("message");
// PubsubMessage message = parser.parseAndClose(PubsubMessage.class);
// // Base64-decode the data and work with it.
// String data = new String(message.decodeData(), "UTF-8");
// append("./messagesPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.txt", "messageid:" + message.getMessageId() + "\n");
// // Work with your message
// // Respond with a 20X to acknowledge receipt of the message.
// response.setStatus(HttpServletResponse.SC_NO_CONTENT);
//
// System.out.println(message.getMessageId());
// response.getWriter().write(message.getMessageId());
// // response.setStatus(HttpServletResponse.SC_NO_CONTENT);
//
// response.getWriter().close();
// ModelAndView model = new ModelAndView();
// model.addObject("message", "messageid:" + message.getMessageId());
// return model;
// }
public static void append(String fileName, String content) {
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
// @RequestMapping(value = "/", method = RequestMethod.GET)
// public ModelAndView receive(String name, HttpServletResponse response) throws Exception {
// /*
// * GoogleOAuth oauth = new GoogleOAuth();
// * oauth.accessTokenRequest(response);
// */
//
// GoogleAuthorizationCodeFlow flow = AuthUtil.getFlow();
//
// String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
// response.sendRedirect(url);
// ModelAndView model = new ModelAndView();
// model.setViewName("gmail");
// return model;
// }
// @RequestMapping(value = "/oauth2callback", method = RequestMethod.GET)
// public ModelAndView oauth2callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
//
// System.out.println("oauth2callback");
//
// String code = request.getParameter("code");
// requestCode = code;
//
// // String token = GoogleOAuth.getAccessToken(code);
// GoogleCredential credential = AuthUtil.exchangeCode(code);
//
// Gmail service = EmailSender.createGmailService(credential);
// /*
// * MimeMessage email = EmailSender.createEmail("shaoqin.chen@sap.com", "chenshao0594@126.com", "test",
// * "work good");
// * EmailSender.sendMessage(service, "chenshao0594@gmail.com", email);
// */
//
// String q = "in:inbox";
// // ListMessagesResponse messageResp = service.users().messages().list(userGmailAddress).setQ(q).execute();
//
// List<Message> messages = new ArrayList<Message>();
// if (startHistoryId == null) {
// messages.addAll(listMessagesMatchingQuery(service, userGmailAddress, q));
// } else {
// messages.addAll(listHistory(service, userGmailAddress, startHistoryId));
// }
// // messageResp.getMessages());//
// /*
// * while (messageResp.getMessages() != null) {
// * messages.addAll(messageResp.getMessages());
// * if (messageResp.getNextPageToken() != null) {
// * String pageToken = messageResp.getNextPageToken();
// * messageResp = service.users().messages().list(userGmailAddress).setQ(null)
// * .setPageToken(pageToken).execute();
// * } else {
// * break;
// * }
// * }
// */
//
// System.out.println(messages.size());
// Message m;
// if (messages.isEmpty()) {
// m = this.lastMessage;
// } else {
// m = messages.get(0);
// }
// if (m == null) {
// ModelAndView model = new ModelAndView();
// model.addObject("subject", "");
// model.addObject("from", "");
// model.addObject("recipient", "");
// model.addObject("content", "");
// model.addObject("messageid", "");
// model.addObject("number", messages.size());
// model.setViewName("gmail");
// return model;
// }
// lastMessage = m;
// Message message = service.users().messages().get(userGmailAddress, m.getId()).setFormat("raw").execute();
//
// System.out.println(message.toPrettyString());
//
// byte[] emailBytes = Base64.decodeBase64(message.getRaw());
//
// Properties props = new Properties();
// Session session = Session.getDefaultInstance(props, null);
//
// MimeMessage mime = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
//
// System.out.println(mime.getSubject());
// System.out.println(mime.getFrom().toString());
// System.out.println("------------------------");
// String recipient = "";
// for (Address each : mime.getRecipients(RecipientType.TO)) {
// recipient = each.toString();
// }
// System.out.println("------------------------");
//
// System.out.println(mime.getContent().toString());
// startHistoryId = message.getHistoryId();
// ModelAndView model = new ModelAndView();
// model.addObject("subject", mime.getSubject());
// model.addObject("from", ((InternetAddress) mime.getFrom()[0]).getAddress());
// model.addObject("recipient", recipient);
// model.addObject("content", mime.getContent().toString());
// model.addObject("messageid", mime.getMessageID());
// model.addObject("number", messages.size());
// model.setViewName("gmail");
// return model;
//
// }
//
// public static List<Message> listHistory(Gmail service, String userId, BigInteger startHistoryId) throws
// IOException {
// List<History> histories = new ArrayList<History>();
// ListHistoryResponse response = service.users().history().list(userId).setStartHistoryId(startHistoryId)
// .execute();
// while (response.getHistory() != null) {
// histories.addAll(response.getHistory());
// if (response.getNextPageToken() != null) {
// String pageToken = response.getNextPageToken();
// response = service.users().history().list(userId).setPageToken(pageToken)
// .setStartHistoryId(startHistoryId).execute();
// } else {
// break;
// }
// }
// List<Message> messages = new ArrayList<Message>();
// for (int i = histories.size() - 1; i >= 0; i--) {
// History history = histories.get(i);
// List<HistoryMessageAdded> hmaList = new ArrayList();
// if (history.getMessagesAdded() != null)
// hmaList.addAll(history.getMessagesAdded());
//
// for (int j = hmaList.size() - 1; j >= 0; j--) {
// HistoryMessageAdded hma = hmaList.get(j);
// messages.add(hma.getMessage());
// }
// System.out.println(history.toPrettyString());
// }
// return messages;
// }
@RequestMapping(value = "/oauth2callback", method = RequestMethod.GET)
public ModelAndView oauth2fetchnew(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("oauth2fetchnew");
String code = request.getParameter("code");
FacebookOauthServiceImpl fbos = new FacebookOauthServiceImpl();
Map<String,Object> token = fbos.getAccessToken(appId,appSecret,proxyHost,proxyPort,redirectUri,code);
// String token = GoogleOAuth.getAccessToken(code);
/*
* MimeMessage email = EmailSender.createEmail("shaoqin.chen@sap.com", "chenshao0594@126.com", "test",
* "work good");
* EmailSender.sendMessage(service, "chenshao0594@gmail.com", email);
*/
FacebookClientServiceImpl fbcs = new FacebookClientServiceImpl();
Facebook facebook = new FacebookTemplate((String)(token.get("access_token")));
FacebookClientServiceImpl.addProxy("proxy.sin.sap.corp","8080",null);
String result = fbcs.searchUsersWork(facebook, "a", 0);
System.out.println("is working:"+result);
System.out.println("------------------------");
ModelAndView model = new ModelAndView();
// model.addObject("subject", mime.getSubject());
// model.addObject("from", ((InternetAddress) mime.getFrom()[0]).getAddress());
// model.addObject("recipient", recipient);
// model.addObject("content", mime.getContent().toString());
// model.addObject("messageid", mime.getMessageID());
model.addObject("subject", "");
model.addObject("from", "");
model.addObject("recipient", "");
model.addObject("content", "");
model.addObject("messageid",result);
model.setViewName("gmail");
return model;
}
}
| true |
eb7f1daa0af5f439bc2c9a925e2b3d3945c0a82c | Java | unclewhd/java-practice | /2020_7_21/src/Main.java | UTF-8 | 3,287 | 3.21875 | 3 | [] | no_license | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String a = in.nextLine();
String[] arr = a.split("_");
System.out.print(arr[0]);
for(int i = 1;i < arr.length;i++){
System.out.print(arr[i].substring(0,1).toUpperCase()+arr[i].substring(1));
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String a = in.nextLine();
char[] arr1 = a.toCharArray();
int count = 0;
char[] arr2 = new char[arr1.length];
int b = 0;
for(int i = 0;i<arr1.length;i++){
if(arr1[i] != '_'){
arr2[count] = arr1[i];
count++;
}else{
b++;
}
}
for(int i = 0;i<arr1.length - b - 1;i++){
System.out.print(arr2[i]);
}
System.out.println(arr2[arr1.length-b]);
}
}
}
/*
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
int[] arr = new int[n];
for(int i = 0;i < n;i++){
arr[i] = scanner.nextInt();
}
Stack<Integer> stack = new Stack<>();
int j = 0;
for(int i = 0;i<n;i++){
int left = Integer.MIN_VALUE;
int right = Integer.MIN_VALUE;
while(j<i){
j++;
stack.push(arr[j]);
if(arr[j]<arr[i]){
left = arr[j];
}
}
if(left ==Integer.MIN_VALUE){
left = -1;
}
j = i;
while(j < n){
stack.push(arr[j]);
j++;
}
while(j != i){
j--;
if(stack.peek()<arr[i])
right = stack.pop();
}
if(right == Integer.MIN_VALUE) right = -1;
System.out.println(left+" "+right);
}
}
}
}
*/
/*
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
int[] arr = new int[n];
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
int count = 0;
for(int i = 0;i < n;i++){
for(int j = 0;j < n; j++){
count++;
if(arr[i]==arr[j]&&i != j){
count--;
}
if(count == n){
System.out.println(arr[i]);
}
}
}
}
}
}*/
| true |
85eb21f5db99a2ed34431dac67b697eb33159934 | Java | weijeuye/library | /src/main/java/com/weason/library/service/impl/BookUserServiceImpl.java | UTF-8 | 1,774 | 2.15625 | 2 | [] | no_license | package com.weason.library.service.impl;
import com.weason.library.dao.BookUserDao;
import com.weason.library.po.BookUser;
import com.weason.library.service.BookUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class BookUserServiceImpl implements BookUserService {
@Autowired
private BookUserDao bookUserDao;
@Override
public List<BookUser> queryBookUsers(Map<String, Object> param) {
List<BookUser> bookUsers = bookUserDao.queryBookUsers(param);
return bookUsers;
}
@Override
public BookUser findBookUser(Map<String, Object> param) {
BookUser bookUser = bookUserDao.findBookUserByPassword(param);
return bookUser;
}
@Override
public Integer findBookUsersCount(Map<String, Object> param) {
Integer count = bookUserDao.findBookUsersCount(param);
return count;
}
@Override
public Integer addBookUser(BookUser bookUser) {
if (bookUser==null){
return 0;
}
int result =bookUserDao.addBookUser(bookUser);
return result;
}
@Override
public Integer updateBookUser(BookUser bookUser) {
if (bookUser==null){
return 0;
}
Integer count = bookUserDao.updateBookUserById(bookUser);
return count;
}
@Override
public Integer deleteBookUser(Long userId) {
Integer count = bookUserDao.deleteBookUserById(userId);
return count;
}
@Override
public BookUser findBookUserByPassword(Map<String, Object> param) {
return bookUserDao.findBookUserByPassword(param);
}
}
| true |
dffe5643d704eabcdbf62f242c246e780b44e477 | Java | Sparsh2309/Data-structure-in-java | /Queue.java | UTF-8 | 566 | 3.5 | 4 | [] | no_license |
public class Queue {
int queue[]= new int[5];
int size;
int front;
int rear;
public void enQueue(int data){
queue [rear]= data;
rear++;
size++;
}
public int deQueue() {
int data= queue[front];
front++;
size--;
return data;
}
public boolean compare() {
if (rear==front) {
System.out.println("Your turn next");
return true;
}
else {
System.out.println("Wait for your turn");
return false;
}
}
}
| true |
b1ec3be2c4263342a900e3cce26af79827bad9ba | Java | BYGran/Test-Java | /Day04/src/Demo/M2048.java | UTF-8 | 18,472 | 2.984375 | 3 | [] | no_license | package Demo;
import java.util.Date;
import java.util.Random; // 产生随机数
import java.awt.event.*; // 提供各类事件的接口和类
import java.awt.Color; // 提供用于颜色的类
import java.awt.Font; // 提供与字体相关的类和接口
import java.awt.EventQueue; //将来自于基础同位体类和受信任的应用程序类的事件列入队列
import javax.swing.JFrame; // 框架
import javax.swing.JPanel; // 面板容器 可以加入到 JFrame 中
import javax.swing.JLabel; // 显示文本、图像或同时显示二者
import javax.swing.BorderFactory; // 设计边框
import javax.swing.SwingConstants;
import javax.swing.JTextField; // 单行文本输入
public class M2048 extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel ScoresPanel;
private JPanel MainPanel;
private JPanel TimeSpentPanel;
private JPanel TipsPanel;
private JLabel MaxScoreLabel;
private JLabel CurrentScoreLabel; // 当前得分
private JLabel TipsLabel; // 提示
private JLabel ScoreValueLabel; // 当前的分数值
private JLabel[][] Texts; // 文本
private JLabel TimeSpentLabel; // 显示此次程序运行 经历的时间
private JLabel TimeSpentValueLabel;
private JTextField MaxScoreField; // 记录最大分数文本
// private JTextField TimeSpentField; // 记录此次游戏经历的时间的文本框
private int SurDiamonts = 16; // 表示剩余方块数目
private int RecordScores = 0; // 记录当前的分数
private String CurrentTime = "" ; // 当前时间
private int Mark1, Mark2, Mark3, Mark4; // 判断游戏是否结束
Font Font1 = new Font("",Font.BOLD,15);
Font Font2 = new Font("",Font.BOLD,30);
Random MyRandom = new Random(); // 产生随机数
public String Current_time() throws InterruptedException{ // 获取时间
Date dt = new Date(System.currentTimeMillis());
while(1>0){
Thread.sleep(1000);
dt.setTime(System.currentTimeMillis());
//CurrentTime = dt.toString();
return dt.toString();
}
}
//CurrentTime = Current_time();
public M2048() throws InterruptedException{ // 构造方法
super();
setResizable(false); // 设置不允许 调整窗口大小
getContentPane().setLayout(null); // 设置布局管理器
setBounds(700, 20, 500, 650); // 设置在容器中位置 及大小
setTitle(" 2048 game "); // 标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口,程序不在内存驻留
TimeSpentPanel = new JPanel(); // 创建时间显示栏
TimeSpentPanel.setBackground(Color.RED); //
TimeSpentPanel.setBounds(20, 20, 450, 25);
TimeSpentPanel.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.RED));
getContentPane().add(TimeSpentPanel);
TimeSpentPanel.setLayout(null); //
/* ScoresPanel = new JPanel(); // 创建计分板
ScoresPanel.setBackground(Color.GREEN); // 计分板的背景颜色
ScoresPanel.setBounds(20, 50, 450, 30); // 计分板的 位置
ScoresPanel.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.RED));
getContentPane().add(ScoresPanel); // 将计分板添加到窗体
ScoresPanel.setLayout(null); // 设置布局*/
MainPanel = new JPanel(); // 创建主面板
MainPanel.setBounds(20, 75, 450, 440);
//MainPanel.setBackground(Color.BLUE);
getContentPane().add(MainPanel);
MainPanel.setLayout(null);
Texts = new JLabel[4][4];
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < 4 ;j++){
Texts[i][j] = new JLabel(); // 创建标签
Texts[i][j].setFont(Font2); // 设置字体大小
Texts[i][j].setHorizontalAlignment(SwingConstants.CENTER); // 设置文字居中
Texts[i][j].setBounds(120*i, 115*j, 90 ,90); // 设置每个框大小,位置
Texts[i][j].setOpaque(true); //
Texts[i][j].setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLACK));
MainPanel.add(Texts[i][j]); // 将每个小块加入到 mainPanel 中
} // for j
} // for i
ScoresPanel = new JPanel(); // 创建计分板
ScoresPanel.setBackground(Color.GREEN); // 计分板的背景颜色
ScoresPanel.setBounds(20, 520, 450, 30); // 计分板的 位置
ScoresPanel.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.RED));
getContentPane().add(ScoresPanel); // 将计分板添加到窗体
ScoresPanel.setLayout(null); // 设置布局
TipsPanel = new JPanel(); // 提示容器
TipsPanel.setBackground(Color.YELLOW);
TipsPanel.setFont(Font1); // 设置提示字体的大小
TipsPanel.setBounds(20, 560, 450, 30);
TipsPanel.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLACK));
getContentPane().add(TipsPanel);
MaxScoreLabel = new JLabel("最高分: "); // 设置最高分标签
MaxScoreLabel.setFont(Font1);
MaxScoreLabel.setBounds(10, 3, 220, 27);
ScoresPanel.add(MaxScoreLabel); // 将最高分标签加入到 ScoresPanel 中
ScoreValueLabel = new JLabel("当前得分: "); // 设置当前得分标签
ScoreValueLabel.setFont(Font1);
ScoreValueLabel.setBounds(230, 3, 220, 27);
//ScoreValueLabel.
ScoresPanel.add(ScoreValueLabel);
MaxScoreField = new JTextField(" 0"); // 最大分数文本区域
MaxScoreField.setBackground(Color.GREEN);
MaxScoreField.setFont(Font1);
MaxScoreField.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.GREEN));
MaxScoreField.setBounds(80, 4, 100, 20);
MaxScoreField.setEditable(false);
ScoresPanel.add(MaxScoreField);
CurrentScoreLabel = new JLabel(String.valueOf(RecordScores)); // 设置当前得分值标签
CurrentScoreLabel.setFont(Font1);
CurrentScoreLabel.setBounds(320, 4, 100, 20);
CurrentScoreLabel.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.GREEN));
CurrentScoreLabel.setBackground(Color.red);
ScoresPanel.add(CurrentScoreLabel);
TipsLabel = new JLabel("请使用小键盘8,2,4,6或者↑,↓,←,→来控制 ^_^");
TipsLabel.setFont(Font1);
TipsLabel.setBounds(70, 4, 250, 20);
TipsPanel.add(TipsLabel);
TimeSpentLabel = new JLabel("游戏开始时间为 : ");
TimeSpentLabel.setFont(Font1);
TimeSpentLabel.setBounds(20, 3, 150, 27);
TimeSpentPanel.add(TimeSpentLabel);
//SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//CurrenTime = dt.format(new Date());
//System.out.println(CurrenTime);
TimeSpentValueLabel = new JLabel(String.valueOf(CurrentTime));
TimeSpentValueLabel.setFont(Font1);
TimeSpentValueLabel.setBounds(160, 3, 300, 27);
TimeSpentPanel.add(TimeSpentValueLabel);
TimeSpentValueLabel.setText(String.valueOf(Current_time()));
MaxScoreField.addKeyListener(new KeyAdapter() { // 为最高分标签添加监听器
public void keyPressed(KeyEvent e){
Major(e);
}
});
Creat_2(); // 产生俩个 新的 2
Creat_2();
} // my_2048
protected void SetColor(int i,int j,String str){ // 对某数字个方块进行颜色的设置
switch(str){
case "" :
case "2" :
Texts[i][j].setBackground(Color.WHITE); // 浅灰
break;
case "4" :
Texts[i][j].setBackground(Color.LIGHT_GRAY);
break;
case "8" :
Texts[i][j].setBackground(Color.YELLOW); // 橙色
break;
case "16" :
Texts[i][j].setBackground(Color.ORANGE);
break;
case "32" :
Texts[i][j].setBackground(Color.PINK);
break;
case "64":
Texts[i][j].setBackground(Color.RED);
break;
case "128":
Texts[i][j].setBackground(Color.MAGENTA);
break;
case "256":
Texts[i][j].setBackground(Color.GREEN);
break;
case "512" :
Texts[i][j].setBackground(Color.BLUE);
break;
case "1024":
Texts[i][j].setBackground(Color.GRAY);
break;
case "2048" :
Texts[i][j].setBackground(Color.LIGHT_GRAY);
break;
case "4096" :
Texts[i][j].setBackground(Color.DARK_GRAY);
break;
default:
break;
} // switch
} // SetColor
protected void Creat_2(){ // 新产生一个 2
int i ,j;
boolean r = false;
String str;
if(SurDiamonts > 0){ // 如果剩余方块
while(!r){
i = MyRandom.nextInt(4);
j = MyRandom.nextInt(4);
str = Texts[i][j].getText();
if((str.compareTo("") == 0)){
//texts[i][j].setIcon(icon2);
Texts[i][j].setText("2");
SetColor(i, j, "2");
SurDiamonts --; // 剩余方块数减 1
r = true;
Mark1 = Mark2 = Mark3 = Mark4 = 0;
}
}
}
else if(Mark1 >0 && Mark2 >0 && Mark3 > 0 && Mark4 > 0){ // mark1 到mark4同时被键盘赋值为1说明任何方向键都不能产生新的数字2,说明游戏失败
TipsLabel.setText(" GAME OVER !");
}
} // Craet
protected void Major(final KeyEvent e){ // 对相应动作做出的反应
int KeyCode = e.getKeyCode(); // 获取按键代码
int Pre; // 防止连加
int Num;
String Str;
String Str_1;
switch (KeyCode){
case KeyEvent.VK_4 :
case KeyEvent.VK_LEFT : // 当键盘输入 ← 或者 4时
for(int j = 0; j < 4; j++){
Pre = 5;
for(int k = 0; k < 3; k++){
for(int i = 1; i < 4; i++){ // 遍历 16 个空格
Str = Texts[i][j].getText(); // 获取当前空格的内容
Str_1 = Texts[i - 1][j].getText(); // 获得当前当前空格左边的第一个空格的内容
if(Str_1.compareTo("") == 0){ // 如果当前空格的左边第一个空格内容为空
Texts[i - 1][j].setText(Str); // 设定 左 1 的值为 当前方块的值
SetColor(i-1, j, Str); // 设定左 1 的颜色
Texts[i][j].setText(""); // 将当前方块的值置为 空
SetColor(i, j, ""); // 设定当前方块的颜色
} // if 左 1 内容为空
else if(Str.compareTo(Str_1) == 0 && i != Pre && i != Pre -1){ // 俩个方框内容相等 且 没发生多次相加情况
Num = Integer.parseInt(Str); // 将当前方框的 内容转化 为 整型
RecordScores += Num ; // 记录的当前得分 增加
SurDiamonts ++; // 空余方格的数目增加
Str = String.valueOf(2 * Num);
Texts[i - 1][j].setText(Str); // 将两个数相加后 添加到 左 1
SetColor(i-1, j, Str); // 给左 1 设置颜色
Texts[i][j].setText(""); // 将当前方块 值 置为 空
SetColor(i, j, "");
Pre = i;
} // else if 两个方块值相等 且
} // for i
} // for k
} // for j
Mark3 = 1;
Creat_2(); // 创建一个新的 2
break;
case KeyEvent.VK_6 :
case KeyEvent.VK_RIGHT : // 键盘输入 → 或者 2
for(int j = 0; j < 4; j ++){
Pre = 5;
for(int k = 0; k < 5; k++){
for(int i = 2; i >= 0; i--){
Str = Texts[i][j].getText();
Str_1 = Texts[i + 1][j].getText();
if(Str_1.compareTo("") == 0){
Texts[i + 1][j].setText(Str);
SetColor(i+1, j, Str);
Texts[i][j].setText("");
SetColor(i, j, "");
}
else if(Str.compareTo(Str_1) == 0 && i != Pre && i != Pre + 1){
Num = Integer.parseInt(Str);
RecordScores += Num ;
SurDiamonts ++;
Str = String.valueOf(2 * Num);
Texts[i + 1][j].setText(Str );
SetColor(i+1, j, Str);
Texts[i][j].setText("");
SetColor(i, j, "");
Pre= i;
}
}
}
}
Mark4 = 1;
Creat_2();
break;
case KeyEvent.VK_2 :
case KeyEvent.VK_DOWN : // 当键盘 ↓ 或者 2 时
for(int i = 0; i < 4; i ++){
Pre = 5;
for(int k = 0; k < 3; k++){
for(int j = 2; j >= 0; j--){ // 遍历16个方格
Str = Texts[i][j].getText(); // 获得当前空格的内容
Str_1 = Texts[i][j + 1].getText(); // 获取当前空格下面第一个空格的内容
if(Str_1.compareTo("") == 0){ // 当 当前空格下面的第一个空格为空
Texts[i][j + 1].setText(Str);
SetColor(i, j+1, Str);
Texts[i][j].setText("");
SetColor(i, j, "");
} // if 当前空格下面第一个空格的内容为空
else if(Str.compareTo(Str_1) == 0 && j !=Pre && j != Pre+ 1){
Num = Integer.parseInt(Str);
RecordScores += Num ;
SurDiamonts ++;
Str = String.valueOf(2 * Num);
Texts[i][j + 1].setText(Str);
SetColor(i, j+1, Str);
Texts[i][j].setText("");
SetColor(i, j, "");
Pre = j;
}
} // for j
} // for k
} // for i
Mark2 = 1;
Creat_2();
break;
case KeyEvent.VK_8 :
case KeyEvent.VK_UP: // 按键为← 或者 4
for(int i = 0; i < 4;i++){
Pre = 5;
for(int j = 0; j < 3;j++){
for(int k = 1;k < 4;k++){ // 遍历全部方块
Str = Texts[i][k].getText(); // 获取当前位置的字符
Str_1 = Texts[i][k-1].getText(); // 获取当前位置的上边的第一个字符
if(Str_1.compareTo("") == 0){ // 如果左边第一个字符为空
Texts[i][k-1].setText(Str); // 将字符左移(字符赋值)
SetColor(i, k-1, Str);
Texts[i][k].setText(""); // 当前字符置为 空
SetColor(i, k, "");
} // if
else if ((Str.compareTo(Str_1) == 0) && (k != Pre) &&( k != Pre-1)) { // 如果当前字符和左边第一个字符相等
Num = Integer.parseInt(Str); // 将字符型变量转化为整型变量
RecordScores += Num; // 记录的当前分数要增加
SurDiamonts ++; // 剩余的空方格的数目增加
Str = String.valueOf(2 * Num); // str 的值 增加一倍
Texts[i][k-1] .setText(Str); // 左边的第一个方块字符变成俩倍
SetColor(i, k-1, Str); // 给左边的方块改变颜色
Texts[i][k].setText(""); // 当前方块值置空
SetColor(i, k, "");
Pre = k;
}
} // for k
} // for j
} // for i
Mark1 = 1;
Creat_2(); // 新产生一个 2
default:
break;
} // switch
CurrentScoreLabel.setText(String.valueOf(RecordScores));
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable(){ // 创建一个线程 好处:这个方法调用完毕后,它会被销毁
public void run(){
try{
M2048 frame = new M2048();
frame.setVisible(true);
// Thread thread = new Thread(frame);
// thread.start();
}
catch(Exception e1){ // 捕捉异常
e1.printStackTrace();
}
}
});
}
}
| true |
8d411444cfb50bbac0ac4704e61677d8731f9cf0 | Java | ketankk/itech2017 | /src/main/java/dao/ITECHDataSource.java | UTF-8 | 3,489 | 2.359375 | 2 | [] | no_license | package dao;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* This class includes initialization of combo pooled data source and provide
* centralized place for retrieving database connection
*
* @author 19217
*
*/
public enum ITECHDataSource {
INSTANCE {
@Override
public Connection getConnection() {
Connection conn = null;
try {
conn = cpds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
};
/**
* Gives database connection
*
* @return database connection
*/
public abstract Connection getConnection();
private static ComboPooledDataSource cpds;
/**
* this class holds logger instance
*
* @author 19217
*
*/
private static class LoggerHolder {
private static final Logger LOGGER = Logger.getLogger(ITECHDataSource.class);
}
private ITECHDataSource() {
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Function responsible for initializing of combo pooled data source
*/
private static void init() throws Exception {
LoggerHolder.LOGGER.debug("initializing ComboPooledDataSource");
try {
String driver = ConfigurationReader.getProperty("DRIVER");
String dbUrl = ConfigurationReader.getProperty("DB_URL");
String user = ConfigurationReader.getProperty("USERNAME");
String password = ConfigurationReader.getProperty("PASSWD");
Integer minPoolSize = Integer.parseInt(ConfigurationReader
.getProperty("WEB_C3PO_MIN_POOL_SIZE"));
Integer acqireIncrementCount = Integer.parseInt(ConfigurationReader
.getProperty("WEB_C3PO_ACQIRE_INCREMENT"));
Integer maxPoolSize = Integer.parseInt(ConfigurationReader
.getProperty("WEB_C3PO_MAX_POOL_SIZE"));
Integer unreturnedConnectionTimeout = Integer
.parseInt(ConfigurationReader
.getProperty("WEB_C3PO_UNRET_CONN_TIMEOUT"));
Boolean debugUnreturnedConnectionStackTraces = Boolean
.parseBoolean(ConfigurationReader
.getProperty("WEB_C3PO_DEBUG_UNRETURNED_CONN"));
LoggerHolder.LOGGER.debug("value read from property file: "
+ " driver: " + driver + " dbUrl: " + dbUrl + "user: " + user
+ " password: " + password + " minPoolSize: " + minPoolSize
+ " acqireIncrementCount: " + acqireIncrementCount
+ " maxPoolSize: " + maxPoolSize
+ " unreturnedConnectionTimeout: "
+ unreturnedConnectionTimeout
+ " debugUnreturnedConnectionStackTraces: "
+ debugUnreturnedConnectionStackTraces);
cpds = new ComboPooledDataSource();
cpds.setDriverClass(driver); // loads the jdbc driver
cpds.setJdbcUrl(dbUrl);
cpds.setUser(user);
cpds.setPassword(password);
// -- c3p0 settings --
cpds.setMinPoolSize(minPoolSize);// 5
cpds.setAcquireIncrement(acqireIncrementCount);// 8
cpds.setMaxPoolSize(maxPoolSize);// 50
// cpds.setUnreturnedConnectionTimeout(unreturnedConnectionTimeout);// 30
//cpds.setDebugUnreturnedConnectionStackTraces(debugUnreturnedConnectionStackTraces);// true
//required to handle Communication-link failure issue
cpds.setTestConnectionOnCheckout(true);
LoggerHolder.LOGGER
.debug("successfully initialized ComboPooledDataSource");
} catch (PropertyVetoException e) {
LoggerHolder.LOGGER
.debug("Problem while initializing ComboPooledDataSource");
e.printStackTrace();
}
}
}
| true |
f1bb1dd498c6c3146168717ee46ddbd665eeeaeb | Java | kronos18/java-mvn-ice1525 | /src/main/java/com/uga/energie/model/Consommation.java | UTF-8 | 1,575 | 2.203125 | 2 | [] | no_license | package com.uga.energie.model;
import com.uga.energie.Parse.p_Consommation;
/**
* Created by jack on 06/06/16.
*/
public class Consommation {
private int idDate;
private int idHeure;
private int idAppareil;
private int etat;
private int energy_wh;
public Consommation(int idDate, int idHeure, int idAppareil, int etat, int energy_wh) {
this.idDate = idDate;
this.idHeure = idHeure;
this.idAppareil = idAppareil;
this.etat = etat;
this.energy_wh = energy_wh;
}
public Consommation(){
}
public int getIdDate() {
return idDate;
}
public void setIdDate(int idDate){
this.idDate = idDate;
}
public int getIdHeure() {
return idHeure;
}
public void setIdHeure(int idHeure){
this.idHeure = idHeure;
}
public int getIdAppareil() {
return idAppareil;
}
public void setIdAppareil(int idAppareil){
this.idAppareil = idAppareil;
}
public int getEtat() {
return etat;
}
public void setEtat(int etat){
this.etat = etat;
}
public int getEnergy_wh() {
return energy_wh;
}
public void setEnergy_wh(int energy){
this.energy_wh = energy;
}
@Override
public String toString() {
return "Consommation{" +
" date=" + idDate +
" heure=" + idHeure +
" appareil=" + idAppareil +
" etat=" + etat +
" energy_wh=" + energy_wh +
'}';
}
}
| true |
ef32e2940bb83175202db14d4861f7cc880204ea | Java | spyy26224574/testUpload | /app/src/com/example/ipcamera/domain/Address.java | UTF-8 | 865 | 2.4375 | 2 | [] | no_license | package com.example.ipcamera.domain;
/*
* 地址的数据结构
*/
public class Address {
private String name;
private String address;
private String collect_longitude;
private String collect_latitude;
public void setName(String nameAddress){
this.name = nameAddress;
}
public String getName(){
return name;
}
public void setAddress(String addAddress){
this.address = addAddress;
}
public String getAddress(){
return address;
}
public void setCollectLongitude(String collect_longitude) {
this.collect_longitude = collect_longitude;
}
public String getCollectLongitude() {
return collect_longitude;
}
public void setCollectLatitude(String collect_latitude) {
this.collect_latitude = collect_latitude;
}
public String getCollectLatitude() {
return collect_latitude;
}
}
| true |
dff59657ae9f31c1f5b22823e97e45c7290f2498 | Java | wushanghui/java-code-example | /src/base/io/zip/ZipOutputStreamTest.java | UTF-8 | 1,514 | 2.828125 | 3 | [] | no_license | package base.io.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author wsh
* @date 2021/1/6 9:58
*/
public class ZipOutputStreamTest {
public static void main(String[] args) {
try {
String zipPath = "D:\\ideacode\\java-code-example\\src\\base\\io\\zip";
String zipName = "test.zip";
String filesPath = "D:\\ideacode\\java-code-example\\src\\base\\io\\zip\\test";
File f = new File(filesPath);
FileOutputStream fout = new FileOutputStream(zipPath + File.separator + zipName);
ZipOutputStream zout = new ZipOutputStream(fout);
if (f.isDirectory()) {
File[] files = f.listFiles();
for (File file : files) {
System.out.println(file.getAbsolutePath());
ZipEntry ze = new ZipEntry(file.getName());
zout.putNextEntry(ze);
FileInputStream in = new FileInputStream(file);
int b;
while ((b = in.read()) != -1) {
zout.write(b);
}
in.close();
zout.closeEntry();
}
zout.close();
fout.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
8399db39633168ab2b53608a3bd41510bf8a5198 | Java | sobkoNick/DesignPatterns | /src/main/java/com/epam/lab/patterns/factoryMethod/DroidFactory.java | UTF-8 | 480 | 2.765625 | 3 | [] | no_license | package com.epam.lab.patterns.factoryMethod;
/**
*
*/
public class DroidFactory {
public Droid getDroid(String type) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("b1")) {
return new B1Droid();
} else if (type.equalsIgnoreCase("b2")) {
return new B2Droid();
} else if (type.equalsIgnoreCase("droideka")) {
return new Droideka();
}
return null;
}
}
| true |
e3ff7fbd1266f86929a2902134159b6785bc5f7a | Java | abtt-decompiled/abtracetogether_1.0.0.apk_disassembled | /sources\com\worklight\wlclient\api\WLProcedureInvocationResponse.java | UTF-8 | 629 | 1.859375 | 2 | [] | no_license | package com.worklight.wlclient.api;
import com.worklight.common.Logger;
import org.json.JSONException;
import org.json.JSONObject;
@Deprecated
public class WLProcedureInvocationResponse extends WLProcedureInvocationResult {
@Deprecated
public WLProcedureInvocationResponse(WLResponse wLResponse) {
super(wLResponse);
}
@Deprecated
public JSONObject getJSONResult() throws JSONException {
String str = "getJSONResult";
Logger.enter(getClass().getSimpleName(), str);
Logger.exit(getClass().getSimpleName(), str);
return super.getResult();
}
}
| true |
a661dd8e78682f486c1563725893d367b4cc4283 | Java | aryan47/rapt-society-dashboard | /riteshProject-Dashboard/src/main/java/com/project/ritesh/dashboard/service/IndexService.java | UTF-8 | 539 | 1.828125 | 2 | [] | no_license | package com.project.ritesh.dashboard.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.ritesh.dashboard.JpaRepository.BookConfirmDetailsJpaRepository;
import com.project.ritesh.dashboard.entity.BookConfirmDetails;
@Service
public class IndexService {
@Autowired
private BookConfirmDetailsJpaRepository bookRepo;
public List<BookConfirmDetails> getBookDetails() {
return bookRepo.findAll();
}
}
| true |
16adeadc945213ad920135da7794b44f05d38a18 | Java | lautalb/EjerciciosJAVA | /Bicicleteria/src/bicicleteria/LocalBicicleteria.java | UTF-8 | 2,276 | 3.015625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bicicleteria;
/**
*
* @author lauta
*/
public class LocalBicicleteria {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Bicicleta bici1=new Bicicleta("1234", "Street", 2015);
Bicicleta bici2=new Bicicleta("5678", "Racer", 2016);
Bicicleteria nuevaBicicleteria= new Bicicleteria();
nuevaBicicleteria.addBicicleta(bici1);
nuevaBicicleteria.addBicicleta(bici2);
//para testear el metodo buscarBicicleta
System.out.println(nuevaBicicleteria.buscarBicicleta("56789"));
/*Ejercicio 4
A- Entre las tablas Bicicleteria y =Falso
Bicicleta existe una relación 1 a 1
B- Entre las tablas Bicicleteria y =Verdadero
Bicicleta existe una relación 1 a N
C- Entre las tablas Bicicleteria y = Falso
Bicicleta existe una relación N a N
D- La clave primaria de la tabla =Verdadero
Bicicleta es nroDeSerie
E- La clave foránea de la tabla =Falso
Bicicleta es nroDeSerie
F- La tabla Bicicleteria no tiene =Falso
clave primaria
G- La tabla Bicicleteria no tiene =Verdadero
clave foránea
*/
/* Ejercicio 5
Dado el diagrama de entidad-relación presentado en el ejercicio anterior, escriba una consulta SQL
que liste la cantidad de ventas y los números de serie de las bicicletas en venta de la bicicletería
cuyo idBicicleteria = 1. Ordene los resultados de acuerdo a la cantidad de ventas en forma
descendente.
SELECT b.cantVentas, bic.nroDeSerie
FROM Bicicleteria as b
INNER JOIN Bicicleta as bic on bic.Bicicleteria_idBicicleteria=b.idBicicleteria
WHERE b.idBicicleteria = 1
ORDER BY (b.cantVentas) DESC
*/
}
}
| true |
7d64b9d5afe9801d947feb2cb884fd92345e2b8c | Java | ent-project/ent | /dev/src/main/java/org/ent/dev/unit/combine/SourceSup.java | UTF-8 | 532 | 2.265625 | 2 | [
"MIT"
] | permissive | package org.ent.dev.unit.combine;
import org.ent.dev.unit.Req;
import org.ent.dev.unit.Sup;
import org.ent.dev.unit.data.Data;
import org.ent.dev.unit.local.Source;
public class SourceSup implements Sup {
private Req downstream;
private final Source delegate;
public SourceSup(Source delegate) {
this.delegate = delegate;
}
@Override
public void setDownstream(Req downstream) {
this.downstream = downstream;
}
@Override
public void requestNext() {
Data next = delegate.get();
downstream.deliver(next);
}
}
| true |
c44188fcdd0beb7fcb39d24186bb63b4ac828d74 | Java | TalesOfArboria/NucleusFramework | /src/com/jcwhatever/nucleus/managed/items/floating/IFloatingItemManager.java | UTF-8 | 3,719 | 2.1875 | 2 | [
"MIT"
] | permissive | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* 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 com.jcwhatever.nucleus.managed.items.floating;
import com.jcwhatever.nucleus.Nucleus;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Manages floating items.
*
* @see Nucleus#getFloatingItems
*/
public interface IFloatingItemManager {
/**
* Add a new floating item.
*
* @param plugin The items owning plugin.
* @param name The name of the item.
* @param itemStack The {@link org.bukkit.inventory.ItemStack}.
*
* @return The created {@link IFloatingItem} or null if the name already exists.
*/
@Nullable
IFloatingItem add(Plugin plugin, String name, ItemStack itemStack);
/**
* Add a new floating item.
*
* @param plugin The items owning plugin.
* @param name The name of the item.
* @param itemStack The {@link org.bukkit.inventory.ItemStack}.
* @param location Optional initial location to set.
*
* @return The created {@link IFloatingItem} or null if the name already exists.
*/
@Nullable
IFloatingItem add(Plugin plugin, String name, ItemStack itemStack,
@Nullable Location location);
/**
* Determine if the manager contains an item.
*
* @param plugin The items owning plugin.
* @param name The name of the item.
*/
boolean contains(Plugin plugin, String name);
/**
* Get an item by name.
*
* @param plugin The items owning plugin.
* @param name The name of the item.
*
* @return The item or null if not found.
*/
@Nullable
IFloatingItem get(Plugin plugin, String name);
/**
* Get all items owned by the specified plugin.
*
* @param plugin The owning plugin.
*/
Collection<IFloatingItem> getAll(Plugin plugin);
/**
* Get all items owned by the specified plugin.
*
* @param plugin The owning plugin.
* @param output The output collection to place results into.
*
* @return The output collection.
*/
<T extends Collection<IFloatingItem>> T getAll(Plugin plugin, T output);
/**
* Remove an item.
*
* @param plugin The items owning plugin.
* @param name The name of the item.
*
* @return True if found and removed, otherwise false.
*/
boolean remove(Plugin plugin, String name);
}
| true |
14699c451fcf8252683fe321d44e31c410b67b96 | Java | sqpsk/virtual-diagonal | /zplot/src/main/java/zplot/plotpanel/PlotAxis.java | UTF-8 | 8,695 | 2.4375 | 2 | [] | no_license | package zplot.plotpanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Stroke;
import zplot.utility.Interval2D;
import zplot.utility.SwingUtils;
import zplot.utility.ZGraphics2D;
import zplot.utility.ZMath;
public class PlotAxis {
// Line
// Tick
// gap
// Label
// gap
// title
// gap
public void setDrawGridLines(boolean b) {
drawGridLines = b;
}
public void setAxisColor(Color c) {
axisColor = c;
}
public void setGridLineColor(Color c) {
gridLineColor = c;
}
public void setGridLineStroke(Stroke s) {
gridLineStroke = s;
}
public PlotAxisSupport getXAxisSupport() {
return xSupport;
}
public void setXAxisSupport(PlotAxisSupport supp) {
xSupport = supp;
}
public void setXAxisRoundTickOffset(boolean b) {
xData.roundTickOffset = b;
}
public void setXAxisTitle(String title) {
xData.title = title;
clearAxisSize();
}
public void setXAxisUnits(String units) {
xSupport.setUnits(units);
}
public PlotAxisSupport getYAxisSupport() {
return ySupport;
}
public void setYAxisSupport(PlotAxisSupport supp) {
ySupport = supp;
}
public void setYAxisRoundTickOffset(boolean b) {
yData.roundTickOffset = b;
}
public void setYAxisTitle(String title) {
yData.title = title;
clearAxisSize();
}
public void setYAxisUnits(String units) {
ySupport.setUnits(units);
}
void setAxisRange(Interval2D axisRange) {
this.axisRangeHz = axisRange;
}
void clearAxisSize() {
xAxisHeightPx = -1;
yAxisWidthPx = -1;
}
int xAxisHeightPx(Graphics2D g) {
if (xAxisHeightPx < 0) {
xAxisHeightPx = calculateXaxisHeight(g);
assert xAxisHeightPx > 0;
}
return xAxisHeightPx;
}
int yAxisWidthPx(Graphics2D g, int height) {
if (yAxisWidthPx < 0) {
yAxisWidthPx = calculateYaxisWidth(g, height);
assert yAxisWidthPx > 0;
}
return yAxisWidthPx;
}
void paintComponent(ZGraphics2D g, Interval2D canvas) {
paintComponent(g, (int) canvas.x().begin(), (int) canvas.x().end(), (int) canvas.y().begin(), (int) canvas.y().end());
}
void paintComponent(ZGraphics2D g, int xBegin, int xEnd, int yBegin, int yEnd) {
assert xAxisHeightPx > 0;
assert yAxisWidthPx > 0;
final int width = xEnd - xBegin;
final int height = yEnd - yBegin;
// Draw from the bottom up - this way we do not have to pre calculate the height
xSupport.init(g, width - yAxisWidthPx, axisRangeHz.x());
g.setColor(axisColor);
drawXaxis(g, xBegin, xEnd, yBegin, yEnd, xSupport);
if (xData.title != null) {
String s = xSupport.formatTitle(xData.title);
Rectangle titleBounds = SwingUtils.getStringBounds(g, s);
// Drawing letters with a tail (y) can get cut off
g.drawString(s, (xBegin + xEnd - titleBounds.width) / 2, yEnd - gapPx);
}
ySupport.init(g, height - xAxisHeightPx, axisRangeHz.y());
drawYaxis(g, xBegin, xEnd, yBegin, yEnd, ySupport);
if (yData.title != null) {
String s = ySupport.formatTitle(yData.title);
Rectangle titleBounds = SwingUtils.getStringBounds(g, s);
int x = xBegin + gapPx + titleBounds.height - 3;
int y = (yEnd + titleBounds.width) / 2;
SwingUtils.drawVerticalString(g, s, x, y);
}
}
private int calculateXaxisHeight(Graphics2D g) {
int sum = tickSizePx;
sum += gapPx;
int textHeight = SwingUtils.getStringBounds(g, "()").height;
sum += textHeight;
sum += gapPx;
if (xData.title != null) {
sum += textHeight;
sum += gapPx;
}
return sum;
}
private int calculateYaxisWidth(Graphics2D g, int height) {
ySupport.init(g, height - xAxisHeightPx, axisRangeHz.y());
int sumPx = tickSizePx;
sumPx += gapPx;
String minValue = ySupport.formatAxisLabel(axisRangeHz.y().begin());
Rectangle minLabelBounds = SwingUtils.getStringBounds(g, minValue);
String maxValue = ySupport.formatAxisLabel(axisRangeHz.y().end());
Rectangle maxLabelBounds = SwingUtils.getStringBounds(g, maxValue);
sumPx += Math.max(minLabelBounds.width, maxLabelBounds.width);
sumPx += gapPx;
if (yData.title != null) {
Rectangle titleBounds = SwingUtils.getStringBounds(g, "()");
sumPx += titleBounds.height;
sumPx += gapPx;
}
return sumPx;
}
private void drawXaxis(ZGraphics2D g, int xBegin, int xEnd, int yBegin, int yEnd, PlotAxisSupport supp) {
final Stroke axisStroke = g.getStroke();
final double tickStepHz = supp.tickStepHz();
final int yTickBegin = yEnd - xAxisHeightPx;
final int yTickBack = yTickBegin + tickSizePx - 1;
// Draw the axis
g.drawLine(xBegin + yAxisWidthPx, yTickBegin, xEnd - 1, yTickBegin);
double value;
if (axisRangeHz.x().size() != 0.0 && xData.roundTickOffset) {
value = Math.ceil(axisRangeHz.x().begin() / supp.firstTickMultipleHz()) * supp.firstTickMultipleHz();
} else {
value = axisRangeHz.x().begin();
}
final int axisWidthPx = xEnd - xBegin - yAxisWidthPx;
final double majorTickStepPx;
double x;
if (axisRangeHz.x().size() != 0.0) {
majorTickStepPx = tickStepHz * axisWidthPx / axisRangeHz.x().size();
x = xBegin + yAxisWidthPx - 1 + ((value - axisRangeHz.x().begin()) * axisWidthPx / axisRangeHz.x().size());
} else {
majorTickStepPx = xEnd - xBegin;
x = (xBegin + xEnd + this.yAxisWidthPx) / 2;
}
int labelEnd = -1;
while (x < xEnd) {
int xInt = ZMath.roundPositive(x);
if (drawGridLines) {
g.setColor(gridLineColor);
g.setStroke(gridLineStroke);
g.drawLine(xInt, yBegin, xInt, yTickBegin);
g.setColor(axisColor);
g.setStroke(axisStroke);
}
g.drawLine(xInt, yTickBegin, xInt, yTickBack);
labelEnd = drawXLabel(g, supp.formatAxisLabel(value), labelEnd, xInt, yTickBack + 1 + gapPx, 3);
value += tickStepHz;
x += majorTickStepPx;
}
}
private void drawYaxis(ZGraphics2D g, int xBegin, int xEnd, int yBegin, int yEnd, PlotAxisSupport supp) {
final Stroke axisStroke = g.getStroke();
final double tickStepHz = supp.tickStepHz();
final int xTickBegin = xBegin + yAxisWidthPx - tickSizePx;
final int xTickBack = xTickBegin + tickSizePx - 1;
// Draw axis
g.drawLine(xTickBack, yBegin, xTickBack, yEnd - this.xAxisHeightPx);
double value;
if (axisRangeHz.y().size() != 0.0 && yData.roundTickOffset) {
value = Math.ceil(axisRangeHz.y().begin() / supp.firstTickMultipleHz()) * supp.firstTickMultipleHz();
} else {
value = axisRangeHz.y().begin();
}
final int axisWidth = yEnd - yBegin - xAxisHeightPx;
final double majorTickStepPx;
double y;
if (axisRangeHz.y().size() != 0.0) {
majorTickStepPx = tickStepHz * axisWidth / axisRangeHz.y().size();
y = yEnd - xAxisHeightPx - ((value - axisRangeHz.y().begin()) * axisWidth / axisRangeHz.y().size());
} else {
majorTickStepPx = yEnd - yBegin;
y = (yBegin + yEnd - this.xAxisHeightPx) / 2;
}
while (y >= yBegin) {
int yInt = ZMath.roundPositive(y);
if (drawGridLines) {
g.setColor(gridLineColor);
g.setStroke(gridLineStroke);
g.drawLine(xTickBack + 1, (int) yInt, xEnd - 1, yInt);
g.setColor(axisColor);
g.setStroke(axisStroke);
}
// Tick mark
g.drawLine(xTickBegin, yInt, xTickBack, yInt);
// Label
drawYLabel(g, supp.formatAxisLabel(value), xTickBegin - gapPx, yInt);
value += tickStepHz;
y -= majorTickStepPx;
}
}
private static int drawXLabel(Graphics2D g, String label, int prevEnd, int x, int y, int gap) {
Rectangle labelBounds = SwingUtils.getStringBounds(g, label);
// labelBounds is one past bounding rectangle so subtract 1
if (prevEnd + gap < x - (labelBounds.width / 2)) {
g.drawString(label, x - labelBounds.width / 2, y + labelBounds.height - 1);
return x + (labelBounds.width / 2);
} else {
return prevEnd;
}
}
private static void drawYLabel(Graphics2D g, String label, int x, int y) {
Rectangle labelBounds = SwingUtils.getStringBounds(g, label);
g.drawString(label, x - labelBounds.width - 1, y + labelBounds.height / 2);
}
private static class AxisData {
String title = null;
boolean roundTickOffset = true;
}
private static final int tickSizePx = 6; // Must be > 0
private static final int gapPx = 3;
private final AxisData xData = new AxisData();
private final AxisData yData = new AxisData();
private Color axisColor = Color.BLACK;
private Color gridLineColor = Color.GRAY.brighter();
private Stroke gridLineStroke = new BasicStroke(1);
private boolean drawGridLines = true;
private PlotAxisSupport xSupport = new AxisSiSupport();
private PlotAxisSupport ySupport = new AxisSiSupport();
// The numbers on the axis. axisRangeHz must contain dataEnvelopeHz.
private Interval2D axisRangeHz = new Interval2D(-1.0, 1.0, -1.0, 1.0);
private int xAxisHeightPx = -1;
private int yAxisWidthPx = -1;
}
| true |
28fd7e8b2363fe88e534ab1c20c84523ce412977 | Java | landolsijasser/Jeu-du-Taquin | /src/taquin/ScoreModel.java | UTF-8 | 3,929 | 2.84375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | package taquin;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
public class ScoreModel extends AbstractTableModel{
/**
*
*/
private static final long serialVersionUID = 1L;
//l'ent�te du JTable
private final String[] entete;
//les donn�es du JTable
private ArrayList<Joueur> list;
//le constructeur
public ScoreModel(){
entete=new String[]{"Joueur","Score","Type de Jeu","Date"};
//lecture � partir du fichier score.dat
String ligne=null;
String[] elements=null;
list=new ArrayList<Joueur>();
//lire � partir d'un fichier
BufferedReader in=null;
try{
in=new BufferedReader(new FileReader("Ressources/Data/score.dat"));
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
return;
}
try{
while((ligne=in.readLine())!=null){
elements=ligne.split(";");
list.add(new Joueur(elements[0],elements[1],elements[2],elements[3]));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
}
//fermer le buffer
try {
in.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
}
//
//trier la liste des joueur
Collections.sort(list);
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public int getColumnCount() {
return entete.length;
}
@Override
public String getColumnName(int columnIndex) {
return entete[columnIndex];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex){
case 0:
return list.get(rowIndex).getNom();
case 1:
return list.get(rowIndex).getScore();
case 2:
return list.get(rowIndex).getTypeJeu();
case 3:
return list.get(rowIndex).getDateJeu();
default:
return null;
}
}
//supprimer un joueur
public void viderListeJoueur(){
int indice=list.size();
list.clear();
fireTableRowsDeleted(0,indice-1);
//l'�criture dans le fichier
PrintWriter out=null;
try{
out=new PrintWriter(new FileWriter("Ressources/Data/score.dat"));
out.print("");
out.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
}//
}
//get List
public ArrayList<Joueur> getList(){
return list;
}
//la classe Joueur
class Joueur implements Comparable<Joueur>{
private String nom;
private String score;
private String typeJeu;
private String dateJeu;
public Joueur(String nom,String score,String typeJeu,String dateJeu) {
this.nom=nom;
this.score=score;
this.typeJeu=typeJeu;
this.dateJeu=dateJeu;
}
public String getNom(){
return this.nom;
}
public String getScore(){
return this.score;
}
public String getTypeJeu(){
return this.typeJeu;
}
public String getDateJeu(){
return this.dateJeu;
}
@Override
public int compareTo(Joueur o) {
SimpleDateFormat formater=new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateO1 = null,dateO2 = null;
try {
dateO1=formater.parse(this.getDateJeu());
dateO2=formater.parse(o.getDateJeu());
} catch (ParseException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
}
if(dateO1.compareTo(dateO2)==-1)
return 1;
else if(dateO1.compareTo(dateO2)==1)
return -1;
else
return 0;
}
}
//
} | true |
c4668764661615a3a4ee384a722003378dea2397 | Java | lestephane/coursera-nand2tetris | /06/src/main/java/Parser.java | UTF-8 | 2,021 | 3.109375 | 3 | [] | no_license | public class Parser {
private final BufferedReader input;
private String currentLine;
private Parser(BufferedReader r) {
this.input = r;
this.advance();
}
public boolean hasMoreCommands() {
return this.currentLine != null;
}
public void advance() {
try {
this.currentLine = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public Commands.Command command() {
if (currentLine == null) return null;
final String line = trimOfWhitespaceAndComments(currentLine);
if (line.startsWith("//") || line.isEmpty()) {
return Commands.comment();
} else if (line.startsWith("@")) {
return Commands.ainst(line);
} else if (line.startsWith("(") && line.endsWith(")")) {
return Commands.label(line);
} else {
return Commands.cinst(line);
}
}
private String trimOfWhitespaceAndComments(final String line) {
int pos = line.indexOf("//");
if (pos != -1) {
return line.substring(0, pos).trim();
} else {
return line.trim();
}
}
public interface Source {
Parser makeParser();
}
public static class StringSource implements Source {
private final String input;
public StringSource(String input) {
this.input = input;
}
public Parser makeParser() {
return new Parser(new BufferedReader(new StringReader(input)));
}
}
public static class FileSource implements Source {
private final File input;
public FileSource(File input) {
this.input = input;
}
public Parser makeParser() {
try {
return new Parser(new BufferedReader(new FileReader(input)));
} catch (FileNotFoundException e) {
throw new ParseException(e);
}
}
}
} | true |
f524933d59c35fc8de2d0c67739ea097c47bda72 | Java | GZRJ2525/WorkAssistant | /app/src/main/java/com/gzrijing/workassistant/view/ReturnMachineActivity.java | UTF-8 | 4,356 | 1.953125 | 2 | [] | no_license | package com.gzrijing.workassistant.view;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.gzrijing.workassistant.R;
import com.gzrijing.workassistant.adapter.ReturnMachineAdapter;
import com.gzrijing.workassistant.entity.ReturnMachine;
import com.gzrijing.workassistant.listener.HttpCallbackListener;
import com.gzrijing.workassistant.util.HttpUtils;
import com.gzrijing.workassistant.util.JsonParseUtils;
import com.gzrijing.workassistant.util.ToastUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class ReturnMachineActivity extends AppCompatActivity {
private String userNo;
private ListView lv_list;
private List<ReturnMachine> returnMachineList = new ArrayList<ReturnMachine>();
private ReturnMachineAdapter adapter;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_machine);
initData();
initViews();
}
private void initData() {
SharedPreferences app = getSharedPreferences(
"saveUser", MODE_PRIVATE);
userNo = app.getString("userNo", "");
getReturnMachine();
IntentFilter intentFilter = new IntentFilter("action.com.gzrijing.workassistant.SendMachine");
registerReceiver(mBroadcastReceiver, intentFilter);
}
private void getReturnMachine() {
String url = null;
try {
url = "?cmd=getneedsendmachinelist&userno=" + URLEncoder.encode(userNo, "UTF-8")
+ "&billtype=" + URLEncoder.encode("退还", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpUtils.sendHttpGetRequest(url, new HttpCallbackListener() {
@Override
public void onFinish(final String response) {
Log.e("response", response);
handler.post(new Runnable() {
@Override
public void run() {
List<ReturnMachine> list = JsonParseUtils.getReturnMachine(response);
returnMachineList.clear();
returnMachineList.addAll(list);
adapter.notifyDataSetChanged();
}
});
}
@Override
public void onError(Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
ToastUtil.showToast(ReturnMachineActivity.this, "与服务器断开连接", Toast.LENGTH_SHORT);
}
});
}
});
}
private void initViews() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lv_list = (ListView) findViewById(R.id.return_machine_lv);
adapter = new ReturnMachineAdapter(this, returnMachineList);
lv_list.setAdapter(adapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("action.com.gzrijing.workassistant.SendMachine")) {
getReturnMachine();
}
}
};
@Override
protected void onDestroy() {
unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}
| true |
d966e726debf3fdf7739c75c6dfd9a62e038af37 | Java | aremarss/java-2.2.1 | /src/BonusMilesService.java | UTF-8 | 178 | 2.75 | 3 | [] | no_license | public class BonusMilesService {
public int calculate(int ticketPrice, int bonusMiles) {
int totalMiles = ticketPrice / bonusMiles;
return totalMiles;
}
} | true |
673c8d22f7407687da1ef330473638ce572e7f4b | Java | ahmed-baz/ERP-System-Of-Medical-Equipment-Factory | /MedicalDevicesFactoryWebApp/MedicalDevicesViewController/src/oracle/medical/app/beans/products/SelectedProductBean.java | UTF-8 | 5,856 | 1.929688 | 2 | [] | no_license | package oracle.medical.app.beans.products;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import oracle.adf.controller.ControllerContext;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;
import oracle.jbo.domain.BlobDomain;
import oracle.jbo.domain.Number;
import org.apache.myfaces.trinidad.model.UploadedFile;
public class SelectedProductBean {
private UploadedFile myFile;
public void setDeleteProductpopup(RichPopup deleteProductpopup) {
this.deleteProductpopup = deleteProductpopup;
}
public RichPopup getDeleteProductpopup() {
return deleteProductpopup;
}
public void setUpdatedProductpopup(RichPopup updatedProductpopup) {
this.updatedProductpopup = updatedProductpopup;
}
public RichPopup getUpdatedProductpopup() {
return updatedProductpopup;
}
public void setSavedIcon(RichPopup savedIcon) {
this.savedIcon = savedIcon;
}
public RichPopup getSavedIcon() {
return savedIcon;
}
private RichPopup deleteProductpopup;
private RichPopup updatedProductpopup;
private RichPopup savedIcon;
public String cancelUpdatepopup() {
// Add event code here...
updatedProductpopup.cancel();
return null;
}
public String confirmDeleteActionBTN() {
// Add event code here...
BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
AttributeBinding ProductIdAttribute = (AttributeBinding) bindingContainer.get("ProductId");
Number ProductId = (Number) ProductIdAttribute.getInputValue();
OperationBinding deleteChildOperation = bindingContainer.getOperationBinding("deleteChild");
deleteChildOperation.getParamsMap().put("productId", ProductId);
deleteChildOperation.execute();
OperationBinding deleteOperation = bindingContainer.getOperationBinding("Delete");
deleteOperation.execute();
OperationBinding commitOperation = bindingContainer.getOperationBinding("Commit");
commitOperation.execute();
ControllerContext ccontext = ControllerContext.getInstance();
String viewId = "Products";
ccontext.getCurrentViewPort().setViewId(viewId);
return null;
}
public String cancelDeleteMessage() {
// Add event code here...
deleteProductpopup.cancel();
return null;
}
public String uploadingFile() {
if (myFile != null) {
if (myFile.getFilename().toUpperCase().endsWith(".JPG") ||
myFile.getFilename().toUpperCase().endsWith(".PNG")) {
//Access Attribute for update
BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
AttributeBinding attributeName = (AttributeBinding) bindingContainer.get("Image");
attributeName.setInputValue(createBlobDomain(myFile));
// Access Iterator Binding for Commit
// BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding commitDCBinding = (DCIteratorBinding) bindingContainer.get("MainProducts1Iterator");
commitDCBinding.getDataControl().commitTransaction();
//this.refreshPage();
} else {
FacesMessage mesg =
new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error !", "Error while uploading image file !");
FacesContext.getCurrentInstance().addMessage(null, mesg);
}
}
refreshPage();
return null;
}
private void refreshPage() {
FacesContext fctx = FacesContext.getCurrentInstance();
String refreshpage = fctx.getViewRoot().getViewId();
ViewHandler ViewH = fctx.getApplication().getViewHandler();
UIViewRoot UIV = ViewH.createView(fctx, refreshpage);
UIV.setViewId(refreshpage);
fctx.setViewRoot(UIV);
}
public void setMyFile(UploadedFile myFile) {
this.myFile = myFile;
}
public UploadedFile getMyFile() {
return myFile;
}
private BlobDomain createBlobDomain(UploadedFile file) {
InputStream in = null;
BlobDomain blobDomain = null;
OutputStream out = null;
try {
in = file.getInputStream();
blobDomain = new BlobDomain();
out = blobDomain.getBinaryOutputStream();
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.fillInStackTrace();
}
return blobDomain;
}
public String saveUpdatedProductBTN() {
// Add event code here...
uploadingFile();
BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding commitOperation = bindingContainer.getOperationBinding("Commit");
commitOperation.execute();
updatedProductpopup.cancel();
RichPopup.PopupHints hint = new RichPopup.PopupHints();
savedIcon.show(hint);
return null;
}
}
| true |
f6d8827b56365703d5304a62ab238f49c842ea36 | Java | DavinderSinghKharoud/AlgorithmsAndDataStructures | /LeetCode/MergeSortedArrays.java | UTF-8 | 860 | 3.421875 | 3 | [] | no_license | package LeetCode;
public class MergeSortedArrays {
public static void merge(int[] nums1, int m, int[] nums2, int n) {
m--;
n--;
int index = nums1.length - 1;
while ( index >= 0 ){
if (m < 0) {
nums1[index] = nums2[n--];
} else if (n < 0) {
nums1[index] = nums1[m--];
} else {
if (nums1[m] > nums2[n]) {
nums1[index] = nums1[m--];
} else {
nums1[index] = nums2[n--];
}
}
index--;
}
}
public static void main(String[] args) {
int[] m = new int[]{1, 2, 3, 0, 0, 0};
int[] n = new int[]{2, 5, 6};
merge(m, 3, n, 3);
for (int num : m) {
System.out.println(num);
}
}
}
| true |
68406feb24a42970dec9b820b4ac6aa88015448a | Java | jclaessens97/School-Portfolio | /Software Architecture/code/ride-service/src/main/java/be/kdg/rideservice/controllers/receiver/impl/LocationMessageReceiver.java | UTF-8 | 1,985 | 2.296875 | 2 | [
"MIT"
] | permissive | package be.kdg.rideservice.controllers.receiver.impl;
import be.kdg.rideservice.controllers.receiver.Receiver;
import be.kdg.rideservice.dto.LocationDto;
import be.kdg.rideservice.service.RideService;
import be.kdg.rideservice.service.VehicleService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class LocationMessageReceiver implements Receiver {
private static final Logger LOGGER = LoggerFactory.getLogger(LocationMessageReceiver.class);
private final ObjectMapper objectMapper;
private final GeometryFactory gf;
private final VehicleService vehicleService;
private final RideService rideService;
@Autowired
public LocationMessageReceiver(ObjectMapper objectMapper, GeometryFactory geometryFactory, VehicleService vehicleService, RideService rideService) {
this.objectMapper = objectMapper;
this.gf = geometryFactory;
this.vehicleService = vehicleService;
this.rideService = rideService;
}
@RabbitListener(queues = "locationQueue")
public void receive(Message msg) {
try {
LocationDto locationDto = objectMapper.readValue(msg.getBody(), LocationDto.class);
Point point = gf.createPoint(new Coordinate(locationDto.getXCoord(), locationDto.getYCoord()));
vehicleService.saveLocation(point, locationDto.getVehicleId());
rideService.saveLocation(locationDto);
} catch (IOException ex) {
LOGGER.error("Failed to deserialize message" + msg);
}
}
}
| true |
8d88e9a2ee9527e017038c6828000e1c421d87bb | Java | HemanthKasireddy/HemanthWorkSpace | /DataStructures/UnOrderedList.java | UTF-8 | 6,306 | 3.921875 | 4 | [] | no_license | /**
*
* @author Hemanth
* Desc -> Read the Text from a file, split it into words and arrange it as Linked List.
* Take a user input to search a Word in the List. If the Word is not found then add it to the list,
* and if it found then remove the word from the List. In the end save the list into a file
* I/P -> Read from file the list of Words and take user input to search a Text
* O/P -> The List of Words to a File.
*
*/
package com.bridgeit.datastrucers.Programs;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.Scanner;
class UnOrderLinkedList {
// creating a file object using file path
File file=new File("/home/bridgeit/Desktop/Hemanth_WorkSpace/WordsSearchFile");
//creating linked list object
LinkedList<String> linkedList=new LinkedList<String>();
//creating required class objects and initializing with null
BufferedWriter bufferedWriter=null;
BufferedReader bufferedReader=null;
FileWriter fileWriter=null;
FileReader fileReader=null;
private String []wordsArray=null;
private String userSearch;
//allocating data to object using constructor
public UnOrderLinkedList(String userSearch) {
this.userSearch=userSearch;
}
/**
* this method for reading file data
* by using of file reader reading data from file putting in to the buffer reader
* and reading line by line data from buffer reader
* and splitting data by space and putting into the Words array
*/
public void readingDataFromFile() {
try{
//checking file is exist or not
if (file.exists()) {
// checking file can have read permission or not
if(file.canRead()) {
//creating file reader object with parameter of file object
fileReader=new FileReader(file);
// creating bufferedReader object of BufferedReader
//reading entire data of file into bufferedReader
bufferedReader=new BufferedReader(fileReader);
String s;
//reading line by line data of bufferedReader and storing into string
// splitting with space and storing into words array
while((s=bufferedReader.readLine())!=null){
wordsArray=s.trim().split(" ");
}
} else {
System.out.println("you can't read this file");
}
} else {
System.out.println("File not exists");
}
} catch(Exception ex){
System.out.println("The \" "+ex+" \" Exception is raised");
ex.printStackTrace();
}
}
/**
* This method for creating linked list
* and adding elements form words array to linked list
* by using add method
*/
public void addingWordsArrayElementsToLinkedList() {
//System.out.println(words.length);
// adding data from words array to liked list object
for(String word:wordsArray){
linkedList.add(word);
}
}
/**
* this method for checking the user entry is present in the linked list
* if user entry present in the linked list removing that element from list
* if element is not there adding that element to linked list
* and overwriting previous data on file with linked list data
* by using file writer and buffer writer
*/
// method for searching user entry is present or not
public void userEntrySearching() {
try{
//checking the user entry is present in the linked list
// if exist removing element from linked list
//if it's not there adding to linked list
if(linkedList.indexOf(userSearch)>=0){
linkedList.remove(userSearch);
//System.out.println(linkedList.size());
System.out.println("\" "+userSearch+" \" Element was removed from file");
}else {
linkedList.add(userSearch);
//System.out.println(linkedList.size());
System.out.println("\" "+userSearch+" \" Element was added to file");
}
//taking all the liked list data as a string
String string="";
for(String word:linkedList){
string=string+" "+word;
}
//string re writing into the file
fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(string);
bufferedWriter.flush();
bufferedWriter.close();
}catch(Exception ex){
System.out.println("The \" "+ex+" \" Exception is raised");
ex.printStackTrace();
}
}
/**
* this method for displaying file data to user screen
* by using of file reader reading a data from file putting in to the buffer reader
* and reading line by line data from buffer reader
*/
public void displayingListWords() {
try{
if(file.canRead()) {
fileReader=new FileReader(file);
bufferedReader=new BufferedReader(fileReader);
String s;
while((s=bufferedReader.readLine())!=null){
System.out.println(s);
}
} else {
System.out.println("you can't read this file");
}
}catch(Exception ex){
System.out.println("The \" "+ex+" \" Exception is raised");
ex.printStackTrace();
}
finally{
try{
fileReader.close();
bufferedReader.close();
fileWriter.close();
bufferedWriter.close();
}catch(Exception ex){
System.out.println("The \" "+ex+" \" Exception is raised");
ex.printStackTrace();
}
}
}
}
public class UnOrderedList {
public static void main (String []args){
Scanner scanner=new Scanner(System.in);
try{
System.out.println("Enter the string you want to search");
String userSearch=scanner.nextLine();
// creating object UnOrderLinkedList class
UnOrderLinkedList unOrderLinkedList=new UnOrderLinkedList(userSearch);
// using object of UnOrderLinkedList calling UnOrderLinkedList objects
unOrderLinkedList.readingDataFromFile();
unOrderLinkedList.addingWordsArrayElementsToLinkedList();
unOrderLinkedList.userEntrySearching();
unOrderLinkedList.displayingListWords();
}catch(Exception ex){
System.out.println("The \" "+ex+" \" Exception is raised");
ex.printStackTrace();
} finally{
scanner.close();
}
}
} | true |
4156f1fa550e7f77f85a8e9a8d5636376658c172 | Java | bradchao/III_Java202106 | /Java@中壢/src/tw/brad/java/Brad02.java | UTF-8 | 198 | 2.875 | 3 | [] | no_license | package tw.brad.java;
public class Brad02 {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a / b); // byte, short, int =>
System.out.println(a % b);
}
}
| true |
144a3acd5ef2105c89f47e4b226ae1d601be2f76 | Java | santialur/shared-rides | /Shared-Rides/src/main/java/com/shared/rides/domain/User.java | UTF-8 | 4,680 | 2.375 | 2 | [] | no_license | package com.shared.rides.domain;
/*
Clase que representa un usuario genérico. Esta clase en particular tiene por un lado
el oid que es un autoincremental que representa de forma única a ese usuario; y por
otro lado, el personalId que es lo que diferencia a esa persona de otra de la misma
organizacion (por ejemplo, la clave de cada alumno en la UCC)
*/
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
@Entity
@Table(name = "User")
@Inheritance(strategy=InheritanceType.JOINED)
public class User implements Serializable{
private long userId;
private String personalId;
private String pw;
private String name;
private String surname;
private Address address;
private Organization organization;
private List<Association> associations;
private long phoneNumber;
private String email;
private Shift shift;
private String picture;
private Pedestrian pedestrian;
private Driver driver;
private Date lastLoginDate;
//-----------CONSTRUCTOR
public User(){
}
public User(long id){
this.userId = id;
}
//-----------GETTERS & SETTERS
@Id
@GeneratedValue
@Column(name="id")
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
@Column(name="personalID")
public String getPersonalId() {
return personalId;
}
public void setPersonalId(String personalId) {
this.personalId = personalId;
}
@Column(name="phoneNumber")
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="surname")
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
@Column(name="password")
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "addressID")
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@OneToOne
@JoinColumn(name = "organizationID")
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
@Column(name="email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Enumerated(EnumType.STRING)
@Column(name="shift")
public Shift getShift() {
return shift;
}
public void setShift(Shift shift) {
this.shift = shift;
}
@Column(name="picture")
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@OneToMany(cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name="User_Assoc", joinColumns = @JoinColumn(name="userID"),
inverseJoinColumns = @JoinColumn(name="associationID"))
public List<Association> getAssociations() {
return associations;
}
public void setAssociations(List<Association> associations) {
this.associations = associations;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name="User_Pedestrian", joinColumns = @JoinColumn(name="userID"),
inverseJoinColumns = @JoinColumn(name="pedestrianID"))
public Pedestrian getPedestrian() {
return pedestrian;
}
public void setPedestrian(Pedestrian pedestrian) {
this.pedestrian = pedestrian;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name="User_Driver", joinColumns = @JoinColumn(name="userID"),
inverseJoinColumns = @JoinColumn(name="driverID"))
public Driver getDriver() {
return driver;
}
public void setDriver(Driver driver) {
this.driver = driver;
}
@Column(name="lastLoginDate")
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
//-------------------------------
}
| true |
28a7b7e4a600e3709b400122e5cd886dff3087bd | Java | a1r1n1e/NotASet | /app/src/main/java/ru/whobuys/vovch/notaset/LauncherActivity.java | UTF-8 | 1,647 | 2.078125 | 2 | [] | no_license | package ru.whobuys.vovch.notaset;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class LauncherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher_actitvity);
TextView singleButton = (TextView) findViewById(R.id.singleplayer);
singleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LauncherActivity.this, SingleActivity.class);
LauncherActivity.this.startActivity(intent);
}
});
TextView oneFourButton = (TextView) findViewById(R.id.four_players);
oneFourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LauncherActivity.this, OneFourActivity.class);
LauncherActivity.this.startActivity(intent);
}
});
TextView multiplayerButton = (TextView) findViewById(R.id.network);
multiplayerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LauncherActivity.this, MultiplayerActivity.class);
LauncherActivity.this.startActivity(intent);
}
});
}
}
| true |
51db5e8b1ca259459c6b194bf1c79f2821c58897 | Java | james1416/Electronic-business-platform | /src/main/java/com/electronicwallet/model/ElectronicWalletDAO_interface.java | UTF-8 | 879 | 1.851563 | 2 | [] | no_license | package com.electronicwallet.model;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.List;
public interface ElectronicWalletDAO_interface {
public List<ElectronicWalletVO> getAll(Integer ele_memid);
public void insertNewPayment(Integer ele_memid, Timestamp ele_time, String ele_rec, Integer ele_mon);
public void walUpdatedByTranOnSmem(Integer od_smemid, Timestamp ele_time, Integer od_price, Connection con);
public void walUpdatedByTranOnBmem(Integer od_bmemid, Timestamp ele_time, Integer od_price, Connection con);
public void refund(Integer od_smemid, Timestamp ele_time, Integer od_price, Connection con);
public Integer findTotalCount(Integer ele_memid);
public List<ElectronicWalletVO> findByPage(Integer ele_memid, Integer start, Integer pageSize);
public ElectronicWalletVO getOneLog(Integer ele_memid, Integer ele_id);
}
| true |
db41086c3b2baba23c09f08c94e0c147c4a71f34 | Java | StephenFerrari14/slack-arenabot-java | /src/main/java/com/slack/headdesk/arenabots/SlackMessageParser.java | UTF-8 | 1,725 | 2.671875 | 3 | [] | no_license | package com.slack.headdesk.arenabots;
import com.slack.headdesk.arenabots.entities.SlackEntity;
import com.slack.headdesk.arenabots.rules.*;
import java.util.ArrayList;
/**
* First idea at a rule based slack framework
* Think it might be better to make an interface like hubot
*/
class SlackMessageParser {
private SlackEntity entity;
SlackMessageParser(SlackEntity entity) {
this.entity = entity;
}
String parse() {
// It works so move these out at some point to a configuration
ArrayList<BaseRule> rules = new ArrayList<BaseRule>();
rules.add(new ChallengeRule(this.entity));
rules.add(new SelfRule(this.entity));
rules.add(new PingRule(this.entity));
rules.add(new HelpRule(this.entity));
rules.add(new CreateRobotRule(this.entity));
rules.add(new DeleteRobotRule(this.entity));
rules.add(new GetProfileRule(this.entity));
rules.add(new GetRobotRule(this.entity));
rules.add(new BattleChallengeRule(this.entity));
rules.add(new AcceptChallengeRule(this.entity));
rules.add(new MissedRule(this.entity));
for (BaseRule rule : rules) {
System.out.println(String.format("Running rule: %s", rule.getClass().getName()));
rule.run();
if (rule.ruleCaught) {
System.out.println(String.format("Rule caught for: %s", rule.getClass().getName()));
if (!rule.result.equals("")) {
return rule.result;
}
return String.format("Rule caught for: %s", rule.getClass().getName());
}
}
return "I do not know how to do that. Please try again.";
}
}
| true |
3b6f2fdb8b5eeb8d947fd09a895b7ae02eab4659 | Java | gaoxiang114/parkingarea | /src/main/java/com/parkarea/common/util/SpringUtil.java | UTF-8 | 594 | 2.28125 | 2 | [] | no_license | package com.parkarea.common.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 按bean的id获取实例
* @author gaoxiang_nad
*
*/
public class SpringUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtil.applicationContext = applicationContext;
}
public static Object getBean(String serviceName) {
return applicationContext.getBean(serviceName);
}
}
| true |
c9e86f1bb3adff59b1637129eb0cc344197cbc03 | Java | xingpenghui/SelfCoding1 | /SelfCoding_Common/src/main/java/com/feri/common/poi/PoiExcel_Main.java | UTF-8 | 3,373 | 2.796875 | 3 | [] | no_license | package com.feri.common.poi;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
/**
*@Author feri
*@Date Created in 2019/1/19 15:34
*/
public class PoiExcel_Main {
public static void main(String[] args) throws IOException {
// String[] strings={"序号","姓名","成绩"};
// exportExcel(strings);
System.out.println(importExcel("成绩.xls"));
}
//导出 生成数据
public static void exportExcel(String[] titles) throws IOException {
//1、创建表格对象
HSSFWorkbook workbook=new HSSFWorkbook();
//2、创建Sheet
HSSFSheet sheet=workbook.createSheet("周考成绩表");
//3、创建第一行
HSSFRow row=sheet.createRow(0);
//4、设置第一行的内容
//单元格的样式
HSSFCellStyle cellStyle=workbook.createCellStyle();
//设置对齐方式
cellStyle.setAlignment(HorizontalAlignment.CENTER);
HSSFFont font=workbook.createFont();
font.setBold(true);
font.setColor(HSSFFont.COLOR_RED);
font.setFontHeightInPoints((short) 30);
cellStyle.setFont(font);
//设置字符个数
sheet.setDefaultColumnWidth(30);
for(int i=0;i<titles.length;i++){
HSSFCell cell=row.createCell(i);
cell.setCellStyle(cellStyle);
cell.setCellValue(titles[i]);
}
HSSFCellStyle cellStyle1=workbook.createCellStyle();
//设置对齐方式
cellStyle1.setAlignment(HorizontalAlignment.LEFT);
HSSFFont font1=workbook.createFont();
font1.setColor(HSSFFont.COLOR_NORMAL);
cellStyle1.setFont(font1);
//5、设置写出的内容
for(int i=1;i<101;i++){
HSSFRow row1=sheet.createRow(i);
setValeu(row1.createCell(0),cellStyle1,i+"");
setValeu(row1.createCell(1),cellStyle1,"洪利"+i);
setValeu(row1.createCell(2),cellStyle1,(new Random().nextInt(100)+1)+"");
}
//6、写出
workbook.write(new File("成绩.xls"));
}
//导出 生成数据
public static LinkedHashMap<Integer,List<String>> importExcel(String fn) throws IOException {
//1、创建表格对象
HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(fn));
//2、创建Sheet
HSSFSheet sheet=workbook.getSheet("周考成绩表");
//3、
LinkedHashMap<Integer,List<String>> map=new LinkedHashMap<>();
int start=sheet.getFirstRowNum();
int total=sheet.getLastRowNum();
for(int i=start;i<=total;i++){
HSSFRow row=sheet.getRow(i);
//
map.put(i,new ArrayList<>());
int s1=row.getFirstCellNum();
int t1=row.getLastCellNum();
for(int j=s1;j<t1;j++){
HSSFCell cell=row.getCell(j);
map.get(i).add(cell.getStringCellValue());
}
}
return map;
}
private static void setValeu(HSSFCell cell,HSSFCellStyle cellStyle,String v){
cell.setCellValue(v);
cell.setCellStyle(cellStyle);
}
}
| true |
f294cc8728f506ba39553e2d9ae341d46892de57 | Java | Renzo21/Educativo | /src/java/Controladores/SancionesControlador.java | UTF-8 | 6,559 | 2.328125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controladores;
import Modelos.Sanciones;
import Modelos.Tiposfaltas;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import utiles.Conexion;
import utiles.Utiles;
/**
*
* @author ALUMNO
*/
public class SancionesControlador {
public static Sanciones buscarId(int id) {
Sanciones sancion = null;
if (Conexion.conectar()) {
try {
String sql = "select * from sanciones sa, tipos_faltas tf"
+ " where sa.id_tipofalta=tf.id_tipofalta and "
+ "id_sancion=?";
try (PreparedStatement ps = Conexion.getConn().prepareStatement(sql)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
sancion = new Sanciones();
sancion.setId_sancion(rs.getInt("id_sancion"));
sancion.setObs_sancion(rs.getString("obs_sancion"));
Tiposfaltas tipofalta = new Tiposfaltas();
tipofalta.setId_tipofalta(rs.getInt("id_tipofalta"));
tipofalta.setDescripcion_tipofalta(rs.getString("descripcion_tipofalta"));
sancion.setTipofalta(tipofalta);
}
ps.close();
}
} catch (SQLException ex) {
System.out.println("--> " + ex.getLocalizedMessage());
}
}
Conexion.cerrar();
return sancion;
}
public static String buscarNombre(String nombre, int pagina) {
int offset = (pagina - 1) * Utiles.REGISTRO_PAGINA;
String valor = "";
if (Conexion.conectar()) {
try {
String sql = "select * from sanciones sa, tipos_faltas tf "
+ "where sa.id_tipofalta=tf.id_tipofalta and "
+ " upper(obs_sancion) like '%"
+ nombre.toUpperCase()
+ "%' "
+ "order by id_sancion "
+ "offset " + offset + " limit " + Utiles.REGISTRO_PAGINA;
System.out.println("--> " + sql);
try (PreparedStatement ps = Conexion.getConn().prepareStatement(sql)) {
ResultSet rs = ps.executeQuery();
String tabla = "";
while (rs.next()) {
tabla += "<tr>"
+ "<td>" + rs.getString("id_sancion") + "</td>"
+ "<td>" + rs.getString("descripcion_tipofalta") + "</td>"
+ "<td>" + rs.getString("obs_sancion") + "</td>"
+ "</tr>";
}
if (tabla.equals("")) {
tabla = "<tr><td colspan=5>No existen registros ...</td></tr>";
}
ps.close();
valor = tabla;
}
} catch (SQLException ex) {
System.out.println("--> " + ex.getLocalizedMessage());
}
}
Conexion.cerrar();
return valor;
}
public static boolean agregar(Sanciones sancion) {
boolean valor = false;
if (Conexion.conectar()) {
int v1 = sancion.getTipofalta().getId_tipofalta();
String v2 = sancion.getObs_sancion();
String sql = "insert into sanciones(id_tipofalta, obs_sancion) "
+ "values('" + v1 + "','" + v2 + "')";
System.out.println("--> " + sql);
try {
Conexion.getSt().executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keyset = Conexion.getSt().getGeneratedKeys();
if (keyset.next()) {
int id_sancion = keyset.getInt(1);
sancion.setId_sancion(id_sancion);
Conexion.getConn().setAutoCommit(false);
}
valor = true;
} catch (SQLException ex) {
System.out.println("--> " + ex.getLocalizedMessage());
}
Conexion.cerrar();
}
return valor;
}
public static boolean modificar(Sanciones sancion) {
boolean valor = false;
if (Conexion.conectar()) {
String sql = "update sanciones set id_tipofalta=?, obs_sancion=? "
+ "where id_sancion=?";
try (PreparedStatement ps = Conexion.getConn().prepareStatement(sql)) {
ps.setInt(1, sancion.getTipofalta().getId_tipofalta());
ps.setString(2, sancion.getObs_sancion());
ps.setInt(3, sancion.getId_sancion());
ps.executeUpdate();
ps.close();
Conexion.getConn().setAutoCommit(false);
System.out.println("--> Grabado");
valor = true;
} catch (SQLException ex) {
System.out.println("--> " + ex.getLocalizedMessage());
try {
Conexion.getConn().rollback();
} catch (SQLException ex1) {
System.out.println("--> " + ex1.getLocalizedMessage());
}
}
}
Conexion.cerrar();
return valor;
}
public static boolean eliminar(Sanciones sancion) {
boolean valor = false;
if (Conexion.conectar()) {
String sql = "delete from sanciones where id_sancion=?";
try (PreparedStatement ps = Conexion.getConn().prepareStatement(sql)) {
ps.setInt(1, sancion.getId_sancion());
ps.executeUpdate();
ps.close();
Conexion.getConn().setAutoCommit(false);
valor = true;
} catch (SQLException ex) {
System.out.println("--> " + ex.getLocalizedMessage());
try {
Conexion.getConn().rollback();
} catch (SQLException ex1) {
System.out.println("--> " + ex1.getLocalizedMessage());
}
}
}
Conexion.cerrar();
return valor;
}
} | true |
336f95cb9308a53f55e572870cf86869ea2548f4 | Java | milyami/StreamToView | /src/jvm/view/grouped/Max.java | UTF-8 | 10,382 | 2.03125 | 2 | [] | no_license | package view.grouped;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import table.tableupdate.TableRowDeleteUpd;
import table.tableupdate.TableRowPutUpd;
import table.tableupdate.TableRowUpd;
import table.value.Value;
import view.Const;
import view.ViewField;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by milya on 07.01.16.
*/
public class Max extends Aggregate {
private static Logger LOG = LoggerFactory.getLogger(Max.class);
public ViewField MAX_ROW_PK;
public ViewField MAX;
public Max() {
super();
initFields();
}
public Max(ViewField field) {
super(field);
initFields();
}
public Max(ViewField field, ViewField groupBy) {
super(field, groupBy);
LOG.error(LOG_STRING + super.toString());
initFields();
}
private void initFields() {
LOG_STRING = "====== Max GROUP BY: ";
VIEW_TYPE = "maxGroupBy";
VIEW_ID = getId();
VIEW_TABLE_NAME = "vt_" + VIEW_ID;
MAX_ROW_PK = new ViewField(VIEW_ID, Const.AGGREGATE_VIEW_TABLE_COLUMN_PK, Const.AGGREGATE_VIEW_TABLE_COLUMN_FAMILY, Value.TYPE.STRING);
MAX = new ViewField(VIEW_ID, Const.MAX_VIEW_TABLE_COLUMN_MAX, Const.AGGREGATE_VIEW_TABLE_COLUMN_FAMILY, Value.TYPE.INTEGER);
FIELD_TO_SELECTION = new ViewField(field.getTableName(), VIEW_TYPE + field.getColumnName(), field.getFamilyName(), Value.TYPE.INTEGER);
}
@Override
public ArrayList<TableRowUpd> processAggregateUpdate(TableRowUpd update, String viewName, HashMap<ViewField, Object> historyEntry) {
LOG.error(LOG_STRING + " got update: " + update);
ArrayList<TableRowUpd> selectionUpdates = new ArrayList<>();
try {
if (!update.areViewFieldsUpdated(Lists.newArrayList(field, groupBy))) return null;
String pk = update.getPk();
String baseTable = update.getTableName();
Integer updateField = (Integer) update.getUpdatedValueByField(field);
Integer prevField = (Integer) historyEntry.get(HISTORY_PREV_VERSION_FIELD);
String prevAggrKey = (String) historyEntry.get(HISTORY_PREV_VERSION_AGGREGATE);
if (groupBy == null) {
if (update instanceof TableRowPutUpd) {
String currentMaxPk = getCurrentMaxPk(null);// updateAggrKey=prevAggrKey
if (pk.equals(currentMaxPk))
selectionUpdates.add(updateMax(baseTable, null));
else
selectionUpdates.add(setMax(baseTable, updateField, pk, null));
} else if (update instanceof TableRowDeleteUpd) {
if (update.areViewFieldsUpdated(Lists.newArrayList(field, groupBy))) {
String currentMaxPk = getCurrentMaxPk(null);
if (pk.equals(currentMaxPk)) {
deleteViewValueByAggrKey(null);
TableRowUpd selectionUpdate = updateMax(baseTable, null);
if (selectionUpdate != null)
selectionUpdates.add(selectionUpdate);
else
selectionUpdates.add(new TableRowDeleteUpd(baseTable, pk, FIELD_TO_SELECTION));
}
}
}
if (!selectionUpdates.isEmpty()) return selectionUpdates;
return null;
}
String updateAggrKey = prevAggrKey;
if (update.areViewFieldsUpdated(groupBy))
if (update instanceof TableRowDeleteUpd)
updateAggrKey = null;
else
updateAggrKey = (String) update.getUpdatedValueByField(groupBy);
if (update instanceof TableRowPutUpd) {
if (prevAggrKey == null) {
if (!isFieldUpdated(update, groupBy, prevAggrKey)) return null;
else {
if (!isFieldUpdated(update, field, prevField))
updateField = prevField;
if (updateField == null) return null;
selectionUpdates.add(setMax(baseTable, updateField, pk, updateAggrKey));
}
} else { // prevAggrKey!=null
if (!isFieldUpdated(update, groupBy, prevAggrKey)) {
if (isFieldUpdated(update, field, prevField)) {
String currentMaxPk = getCurrentMaxPk(prevAggrKey);
if (pk.equals(currentMaxPk))
selectionUpdates.add(updateMax(baseTable, prevAggrKey));
else
selectionUpdates.add(setMax(baseTable, updateField, pk, prevAggrKey));
} else {
if (updateField != null) { // prevField == null
String currentMaxPk = getCurrentMaxPk(prevAggrKey);
if (currentMaxPk == null) {
selectionUpdates.add(setMax(baseTable, prevField, pk, prevAggrKey));
}
return null;
}
}
} else { //aggrKey is updated
selectionUpdates.add(updateMax(baseTable, prevAggrKey));
if (!isFieldUpdated(update, field, prevField))
updateField = prevField;
if (updateField == null) return null;
selectionUpdates.add(setMax(baseTable, updateField, pk, updateAggrKey));
}
}
} else if (update instanceof TableRowDeleteUpd) {
if (update.areViewFieldsUpdated(Lists.newArrayList(field, groupBy))) {
String currentMaxPk = getCurrentMaxPk(prevAggrKey);
if (pk.equals(currentMaxPk)) {
deleteViewValueByAggrKey(prevAggrKey);
selectionUpdates.add(new TableRowDeleteUpd(baseTable, prevAggrKey, FIELD_TO_SELECTION));
selectionUpdates.add(updateMax(baseTable, prevAggrKey));
}
}
}
if (!selectionUpdates.isEmpty()) return selectionUpdates;
return null;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private HashMap<ViewField, Object> getCurrentMax(String aggrKeyValue) throws IOException {
HashMap<ViewField, Object> currentMax = conn.getFieldsByPk(VIEW_TABLE_NAME, VIEW_ID + aggrKeyValue, Lists.newArrayList(MAX, MAX_ROW_PK));
return currentMax;
}
private String getCurrentMaxPk(String aggrKey) throws IOException {
if (aggrKey == null) aggrKey = Const.AGGREGATE_KEY;
HashMap<ViewField, Object> currentMaxRow = getCurrentMax(aggrKey);
if (currentMaxRow.size() == 0) return null;
String currentMaxPk = (String) currentMaxRow.get(MAX_ROW_PK);
return currentMaxPk;
}
private TableRowUpd updateMax(String tableName, String aggrKey) throws IOException {
if (aggrKey == null) aggrKey = Const.AGGREGATE_KEY;
HashMap<ViewField, Object> newMaxRow = scanNewMax(aggrKey);
if (newMaxRow == null) {
deleteViewValueByAggrKey(aggrKey);
return new TableRowDeleteUpd(tableName, aggrKey, FIELD_TO_SELECTION);
}
String newMaxPk = (String) newMaxRow.get(MAX_ROW_PK);
Integer newMax = (Integer) newMaxRow.get(MAX);
deleteViewValueByAggrKey(aggrKey);
if (newMax != null) {
return setMax(tableName, newMax, newMaxPk, aggrKey);
} else return new TableRowDeleteUpd(tableName, aggrKey, FIELD_TO_SELECTION);
}
private TableRowUpd setMax(String tableName, Integer newValue, String pk, String aggrKey) throws IOException {
if (newValue == null) return null;
if (aggrKey == null) aggrKey = Const.AGGREGATE_KEY;
HashMap<ViewField, Object> currentMaxRow = getCurrentMax(aggrKey);
Integer currentMax = (Integer) currentMaxRow.get(MAX);
String currentMaxPk = (String) currentMaxRow.get(MAX_ROW_PK);
if (pk.equals(currentMaxPk) || currentMax == null || currentMax < newValue) {
HashMap<ViewField, Object> newMaxRow = new HashMap<>();
newMaxRow.put(MAX, newValue);
newMaxRow.put(MAX_ROW_PK, pk);
conn.putFieldsByPk(VIEW_TABLE_NAME, VIEW_ID + aggrKey, newMaxRow);
return new TableRowPutUpd(tableName, aggrKey, FIELD_TO_SELECTION, newValue);
}
return null;
}
private HashMap<ViewField, Object> scanNewMax(String aggrKey) throws IOException {
HashMap<String, HashMap<ViewField, Object>> rows = conn.scanTableFields(HISTORY_TABLE_NAME, Lists.newArrayList(HISTORY_PREV_VERSION_FIELD,
HISTORY_PREV_VERSION_AGGREGATE));
if (!rows.isEmpty()) {
String newMaxPk = null;
Integer newMax = null;
for (Map.Entry<String, HashMap<ViewField, Object>> row : rows.entrySet()) {
HashMap<ViewField, Object> rowFields = row.getValue();
if (aggrKey.equals(Const.AGGREGATE_KEY) || aggrKey.equals(rowFields.get(HISTORY_PREV_VERSION_AGGREGATE))) {
Integer fieldValue = (Integer) rowFields.get(HISTORY_PREV_VERSION_FIELD);
if (fieldValue == null) continue;
if (newMax == null || fieldValue > newMax) {
newMax = fieldValue;
newMaxPk = row.getKey();
}
}
}
if (newMax != null) {
HashMap<ViewField, Object> newMaxRow = new HashMap<>();
newMaxRow.put(MAX, newMax);
newMaxRow.put(MAX_ROW_PK, newMaxPk);
return newMaxRow;
}
}
return null;
}
@Override
public String toString() {
return "Max{" + super.toString() + "}";
}
}
| true |
4f762a3a825834944827397495a3ec4c8c475986 | Java | Akashkansal065/FirstFrameWork | /src/main/java/com/magic/base/Provider.java | UTF-8 | 4,581 | 2.390625 | 2 | [] | no_license | package com.magic.base;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.testng.Reporter;
import org.testng.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.magic.utilities.ExcelReader;
import com.magic.utilities.ExtentTestManager;
import com.magic.utilities.GoogleSheet;
import com.relevantcodes.extentreports.LogStatus;
public class Provider{
@DataProvider
public Object[][] insert(Method m)
{
System.out.println("Data Provider Executing method name:-"+m.getName());
Class<? extends Object> className = m.getDeclaringClass();
/*System.out.println(className.getSimpleName());
Method[] meth =className.getDeclaredMethods();
for (Method method : meth) {
System.out.println(method.getName());
}*/
ExcelReader excel = new ExcelReader(System.getProperty("user.dir")+"//src//test//resources//excel//"+className.getSimpleName()+".xlsx");
//excel = new ExcelReader(System.getProperty("user.dir")+"//src//test//resources//excel//TestClssSecond.xlsx");
String sheetname ="Sheet1";
int rows = excel.getRowCount(sheetname);
int column = excel.getColumnCount(sheetname);
Map<String,List<Map<String,String>>> allData = new LinkedHashMap<>();
for(int i=1;i<=rows;i++)
{
HashMap<String,String> map = new HashMap<>();
for(int j=1;j<column;j++)
{
//System.out.println(excel.getCellData(0, j,sheetname)+" : "+excel.getCellData(i, j,sheetname));
map.put(excel.getCellData(0, j,sheetname),excel.getCellData(i, j,sheetname));
}
String methodName = excel.getCellData(i, 0,sheetname);
if(allData.get(methodName) == null) {
allData.put(methodName, new ArrayList<Map<String,String>>());
}
allData.get(methodName).add(map);
}
if(!allData.containsKey(m.getName()))
{
Reporter.log("Test start onTestStart:- "+m.getName());
Test test = m.getAnnotation(Test.class);
ExtentTestManager.startTest(className.getSimpleName()+"."+m.getName().toUpperCase(),test.description());
ExtentTestManager.getTest().assignCategory(className.getSimpleName());
ExtentTestManager.getTest().log(LogStatus.INFO,"Test Going to be skipped",m.getName());
throw new SkipException("Test Case Skipped as not present in "+className.getSimpleName()+".xlsx"+" Excel");
}
Object [][] arr = new Object [allData.get(m.getName()).size()][1];
for(int i=0;i<arr.length;i++) //No. of Rows should be -1 as starting to fetch value from Second row.
{
arr[i][0] = allData.get(m.getName()).get(i);
System.out.println(i+": "+arr[i][0].toString());
}
return arr;
}
@DataProvider
public String[][] gInsert()
{
String spreadsheetId="14-7PNS2RzGrdvvx5VMBvRlZoyX_oHJ_JJtiPidrgbEs";
String range="'Sprint 20'";
GoogleSheet sheetAPI = new GoogleSheet();
List<List<Object>> values = null;
try {
values = sheetAPI.getSpreadSheetRecords(spreadsheetId, range);
} catch (IOException e) {e.printStackTrace();}
String arr[][] = new String[1][];
for(int i=0;i<1;i++)
{
arr[i] = new String[3];
for(int j=0;j<3;j++)
{
System.out.print(values.get(i).get(j).toString()+",");
arr[i][j]= values.get(i).get(j).toString().trim();
}
}
return arr;
}
public Map<String,Map<String,List<List<String>>>> restData()
{
//System.out.println("Rest Excel");
ExcelReader excel = new ExcelReader(System.getProperty("user.dir")+"//src//test//resources//excel//Rest.xlsx");
String sheetname ="Sheet1";
int rows = excel.getRowCount(sheetname);
int columnCount = excel.getColumnCount(sheetname);
Map<String,Map<String,List<List<String>>>> allData = new LinkedHashMap<>();
for(int rowIdx = 1; rowIdx <= rows; rowIdx++) {
String agicKey = excel.getCellData(rowIdx, 0,sheetname); // get first key
if(allData.get(agicKey) == null) {
//allData.put(agicKey, new LinkedHashMap<>());
}
Map<String,List<List<String>>> secondMap = allData.get(agicKey); // get second key
String mobilKey = excel.getCellData(rowIdx, 1,sheetname);
if(secondMap.get(mobilKey) == null) {
//secondMap.put(mobilKey, new ArrayList<>());
}
List<List<String>> dataList = secondMap.get(mobilKey);
List<String> dataValueList = new ArrayList<>();
for(int colIdx = 2; colIdx < columnCount; colIdx++) {
dataValueList.add(excel.getCellData(rowIdx, colIdx,sheetname));
}
dataList.add(dataValueList);
}
return allData;
}
} | true |
0e48920d8f6ae7f95e6edb9394e253bc58c1b9b1 | Java | dvmoran1/Equipo-A | /urlbasics/src/main/java/com/mycompany/urlbasics/Main.java | UTF-8 | 2,545 | 2.875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.urlbasics;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class Main extends JFrame {
static JLabel mylabel;
public Main () {
setTitle ("HTTP URL Connection");
setSize (new Dimension (800, 600));
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
mylabel = new JLabel();
JScrollPane panel = new JScrollPane (mylabel);
setContentPane (panel);
setVisible (true);
}
public static void main (String [] args) throws MalformedURLException, IOException {
Main m = new Main ();
URL url = new URL ("http://www.uv.mx:8080/usuarios.html?q=any&filename=book.pdf");
System.out.println ("protocol = " + url.getProtocol ());
System.out.println("authority = " + url.getAuthority ());
System.out.println("host = " + url.getHost ());
System.out.println("port = " + url.getPort ());
System.out.println("path = " + url.getPath ());
System.out.println("query = " + url.getQuery ());
System.out.println("filename = " + url.getFile ());
System.out.println("ref = " + url.getRef ());
URL loremURL = new URL ("https://pbs.twimg.com/media/D4y8BOaW0AM74Gj.jpg");
URLConnection urlConn = loremURL.openConnection ();
HttpURLConnection httpUrlConn = (HttpURLConnection) urlConn;
httpUrlConn.connect ();
if (httpUrlConn.getResponseCode () == HttpURLConnection.HTTP_OK) {
InputStream in = httpUrlConn.getInputStream (); //bytes crudos
BufferedImage image=null;
image=ImageIO.read(in);
ImageIcon icono=new ImageIcon(image);
in.close ();
mylabel.setIcon(icono);
}
httpUrlConn.disconnect ();
}
} | true |
ad5d871466ac5d66dbd7457f76042ff67cb41487 | Java | oguzkurtcebe/Resteasy-WebServis | /src/main/java/com/mycompany/restfulwebservice/client/ClientClassPost.java | UTF-8 | 2,600 | 2.71875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.restfulwebservice.client;
import com.mycompany.restfulwebservice.pojo.PersonClass;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
/**
*
* @author bmogu
*/
public class ClientClassPost {
public static void main(String[] args) {
ClientClassPost ccp = new ClientClassPost();
ccp.postValueInJson();
ccp.postValueInXml();
}
public void postValueInJson() {
PersonClass person = new PersonClass();
person.setName("hakan");
person.setSurName("aslan");
person.setCity("kocaeli");
person.setPhoneNumber("05xxxxxxxxx");
String link = "http://localhost:8080/RestfulWebService/webservice/postjson/postAvalueJson";
Client client = ClientBuilder.newClient();
WebTarget target = client.target(link);
Response response = target.request().post(Entity.entity(person, MediaType.APPLICATION_JSON));
if (response.getStatus() == 200) {
System.out.println("işlem başarılı");
System.out.println(response.readEntity(String.class));
} else {
System.out.println("Post işlemi başarısız");
System.out.println(response.readEntity(String.class));
}
}
public void postValueInXml(){
PersonClass person=new PersonClass();
person.setName("oguz");
person.setSurName("kurtcebe");
person.setPhoneNumber("05xxxxxxxxx");
person.setCity("Van");
Entity entity=Entity.xml(person);
String link="http://localhost:8080/RestfulWebService/webservice/postxml/postAvalueXml";
ResteasyClient restEasyClient=new ResteasyClientBuilder().build();
ResteasyWebTarget target=restEasyClient.target(link);
Response response=target.request().post(entity);
if(response.getStatus()==200){
System.out.println("İşlem başarılı:"+response.readEntity(String.class));
}
else{
System.out.println("işlem Başarısız:"+response.readEntity(String.class));
}
}
}
| true |
bef4b4dbb621095f12e698d303f286c45aa08714 | Java | shrey4796/College-Festival-Android-App | /OASIS/src/bits/dvm/oasis/Event_Update_Item.java | UTF-8 | 785 | 2.53125 | 3 | [] | no_license | package bits.dvm.oasis;
public class Event_Update_Item {
private int id,show_notification;
private String update;
//simple constructor
public Event_Update_Item(){
}
//parameterised constructor
public Event_Update_Item(int id, String update, int show_notification) {
this.id = id;
this.update = update;
this.show_notification = show_notification;
}
//getters and setters
public String getupdate() {
return update;
}
public void setupdate(String update) {
this.update = update;
}
public int isshow_notification() {
return show_notification;
}
public void setshow_notification(int show_notification) {
this.show_notification = show_notification;
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
}
| true |
983fc40b19e4d212296cf0070dd42026219d1522 | Java | bmsjarbas/currency_exchange_rates | /src/main/java/ie/britoj/currencyexchangerates/web/controllers/SignUpController.java | UTF-8 | 1,657 | 2.171875 | 2 | [] | no_license | package ie.britoj.currencyexchangerates.web.controllers;
import ie.britoj.currencyexchangerates.services.UserManager;
import ie.britoj.currencyexchangerates.web.validators.SignUpValidator;
import ie.britoj.currencyexchangerates.web.viewmodels.SignUpViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
@Controller
@RequestMapping("/signup")
@Transactional
public class SignUpController {
@Autowired
UserManager userManager;
@Autowired
SignUpValidator signUpValidator;
@GetMapping()
public ModelAndView getSignUp(){
SignUpViewModel signUpViewModel = new SignUpViewModel();
return new ModelAndView("signup-form", "signUp", signUpViewModel);
}
@PostMapping
public String postSignUp(@ModelAttribute("signUp") SignUpViewModel signUp,
BindingResult bindingResult){
signUpValidator.validate(signUp, bindingResult);
if(bindingResult.hasErrors()){
return "signup-form";
}
userManager.create(signUp.createUser());
return "redirect:/signin?userCreated";
}
} | true |
21cf50c01aae15963fde7e2ecb2a84fdb4ef2c2f | Java | uw-loci/4d-software-suite | /4dview/TiffWriter.java | UTF-8 | 10,594 | 2.5625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | //Some code modified from Wayne Rasband's freeware application ImageJ
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
class TiffWriter extends ImageWriter
{
//***** TIFF HEADER CONSTANTS
static final int BPS_DATA_SIZE = 6;
static final int HEADER_SIZE = 8;
static final int NUM_ENTRIES = 9;
static final int IFD_SIZE = 2 + (NUM_ENTRIES * 12) + 4; // num_entries + ImageFileDirectory entries + next_IFD
static final int OFFSET_TO_IMAGE_DATA = 768;
static final int NEW_SUBFILE_TYPE = 254;
static final int IMAGE_WIDTH = 256;
static final int IMAGE_LENGTH = 257;
static final int BITS_PER_SAMPLE = 258;
static final int COMPRESSION = 259;
static final int PHOTO_INTERP = 262;
static final int STRIP_OFFSETS = 273;
static final int SAMPLES_PER_PIXEL = 277;
static final int ROWS_PER_STRIP = 278;
static final int STRIP_BYTE_COUNT = 279;
static final int X_RESOLUTION = 282;
static final int Y_RESOLUTION = 283;
static final int PLANAR_CONFIGURATION = 284;
static final int RESOLUTION_UNIT = 296;
static final int COLOR_MAP = 320;
static final int IMAGE_HDR = -22222; //43314
boolean invert;
//******************************************************************************
//* I N I T
//******************************************************************************
public TiffWriter(String file_name, int width, int height) throws Exception
{
super(file_name, width, height);
invert = false;
return;
}// end of init()
//******************************************************************************
//* C R E A T E S T A C K
//******************************************************************************
void createStack (int n_slices) throws Exception
{
int image_data_size = 0, image_size_in_bytes = 0;
int next_IFD = 0;
if (n_slices < 1)
throw (new Exception("Need at least one slice in a stack."));
this.num_slices = n_slices;
image_size_in_bytes = getImageSizeInBytes(image_width, image_height);
image_data_size = image_size_in_bytes * num_slices;
if (num_slices > 1)
next_IFD = OFFSET_TO_IMAGE_DATA + image_data_size;
else
next_IFD = 0;
writeTiffHeader(next_IFD);
return;
}// end of createStack
//******************************************************************************
//* S A V E I M A G E
//******************************************************************************
void saveImage (Image img) throws Exception
{
int bps_size = 0;
byte[] filler = null;
int next_IFD = 0;
try
{
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
if (img == null)
return;
writeTiffHeader(next_IFD);
writeImageSlice(img);
os.close();
ok_to_write = false;
}
catch (Exception e)
{
os.close();
throw(e);
}
return;
}// end of saveImage()
//******************************************************************************
//* S A V E S T A C K
//* image_array contains the individual java.awt.image objects
//******************************************************************************
void saveStack (Vector image_array) throws Exception
{
int i = 0;
int image_data_size = 0, image_size_in_bytes = 0;
int next_IFD = 0;
try
{
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
if (image_array == null)
return;
if (image_array.size() <= 1)
throw (new Exception("File is not a TIFF stack."));
//***** Get variable info
num_slices = image_array.size();
image_size_in_bytes = getImageSizeInBytes(image_width, image_height);
image_data_size = image_size_in_bytes * num_slices;
next_IFD = OFFSET_TO_IMAGE_DATA + image_data_size;
writeTiffHeader(next_IFD);
writeImageSlices(image_array);
writeStackFooter();
os.close();
ok_to_write = false;
}
catch (Exception e)
{
os.close();
throw(e);
}
return;
}// end of saveStack()
//*****************************************************************
//* W R I T E T I F F H E A D E R
//*****************************************************************
private void writeTiffHeader(int next_IFD) throws Exception
{
int bps_size = 0;
byte[] filler = null;
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
writeTiffIdentifier();
writeTiffImageFileDirectory(OFFSET_TO_IMAGE_DATA, next_IFD);
if (output_file_type == RGB_IMAGE)
{
writeBitsPerPixel();
bps_size = BPS_DATA_SIZE;
}
filler = new byte[OFFSET_TO_IMAGE_DATA - (HEADER_SIZE + IFD_SIZE + bps_size)]; // create an empty buffer to pad out the header to 768 bytes
os.write(filler);
return;
}// end of writeTiffHeader()
//******************************************************************************
//* W R I T E I M A G E S L I C E
//* Writes an image as a slice of a tiff stack
//******************************************************************************
void writeImageSlice(Image img) throws Exception
{
super.writeImageSlice(img);
}// end of writeImageSlice()
//******************************************************************************
//* C L O S E S T A C K
//******************************************************************************
public void closeStack() throws Exception
{
writeStackFooter();
os.close();
ok_to_write = false;
}// end of closeStack()
//*****************************************************************
//* W R I T E S T A C K F O O T E R
//*****************************************************************
private void writeStackFooter() throws Exception
{
int i = 0, image_size = 0, image_data_size = 0;
int image_offset = OFFSET_TO_IMAGE_DATA;
int next_IFD = 0;
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
image_size = getImageSizeInBytes(image_width, image_height);
image_data_size = image_size * num_slices;
next_IFD = OFFSET_TO_IMAGE_DATA + image_data_size;
//***** Write the footer info to the file, basically the IFDs for slices 2 through n
for (i = 2; i <= num_slices; i++)
{
if (i == num_slices)
next_IFD = 0;
else
next_IFD += IFD_SIZE;
image_offset += image_size;
writeTiffImageFileDirectory(image_offset, next_IFD);
}// for each image after the first
return;
}// end of writeStackFooter()
//******************************************************************************
//* W R I T E T I F F I D E N T I F I E R
//******************************************************************************
private void writeTiffIdentifier() throws Exception
{
try
{
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
byte[] hdr = new byte[8];
hdr[0] = 77; // "MM" (Motorola byte order)
hdr[1] = 77;
hdr[2] = 0; // 42 (magic number)
hdr[3] = 42;
hdr[4] = 0; // 8 (offset to first ImageFileDirectory)
hdr[5] = 0;
hdr[6] = 0;
hdr[7] = 8;
os.write(hdr);
}
catch (Exception e)
{
throw(e);
}
return;
}// end of writeTiffIdentifier()
//******************************************************************************
//* W R I T E T I F F E N T R Y
//******************************************************************************
private void writeTiffEntry(int tag, int field_type, int count, int value) throws Exception
{
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
os.writeShort(tag);
os.writeShort(field_type);
os.writeInt(count);
if (count== 1 && field_type == 3)
value <<= 16;
os.writeInt(value);
return;
}// end of writeTiffEntry()
//***********************************************************************************
//* W R I T E T I F F I M A G E F I L E D I R E C T O R Y
//*
//* An IFD provides information about a specific image such as height, width
//* bit depth, etc. image_offset is the offset in bytes from the start of the
//* file to the beginning of the image for which the IFD is supplying information
//* next_IFD is the offset in bytes from the end of the current IFD to the
//* beginning of the next IFD
//************************************************************************************
private void writeTiffImageFileDirectory(int image_offset, int next_IFD) throws Exception
{
int bits_per_sample = 8, photo_interp = 0;
int bytes_per_pixel = 1, samples_per_pixel = 1;
int image_size_in_bytes = 0;
int tag_data_offset = 0;
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
switch (Settings.output_file_type)
{
case GRAY_8_BIT_IMAGE:
bits_per_sample = 8;
photo_interp = invert?0:1;
break;
case GRAY_16_BIT_IMAGE:
bits_per_sample = 16;
photo_interp = invert?0:1;
bytes_per_pixel = 2;
break;
case RGB_IMAGE:
photo_interp = 2;
bytes_per_pixel = 3;
samples_per_pixel = 3;
break;
default:
throw (new Exception("Can't save this format as TIFF file!"));
}// end of switch
image_size_in_bytes = getImageSizeInBytes(image_width, image_height);
tag_data_offset = HEADER_SIZE + IFD_SIZE;
try
{
os.writeShort(NUM_ENTRIES);
writeTiffEntry(NEW_SUBFILE_TYPE, 4, 1, 0);
writeTiffEntry(IMAGE_WIDTH, 3, 1, image_width);
writeTiffEntry(IMAGE_LENGTH, 3, 1, image_height);
if (Settings.output_file_type == RGB_IMAGE)
{
writeTiffEntry(BITS_PER_SAMPLE, 3, 3, tag_data_offset);
tag_data_offset += BPS_DATA_SIZE;
}
else
writeTiffEntry(BITS_PER_SAMPLE, 3, 1, bits_per_sample);
writeTiffEntry(PHOTO_INTERP, 3, 1, photo_interp);
writeTiffEntry(STRIP_OFFSETS, 4, 1, image_offset);
writeTiffEntry(SAMPLES_PER_PIXEL,3, 1, bytes_per_pixel);
writeTiffEntry(ROWS_PER_STRIP, 3, 1, image_height);
writeTiffEntry(STRIP_BYTE_COUNT, 4, 1, image_size_in_bytes);
//***** Write the offset to the next IFD, this will be 0 for the last IFD
os.writeInt(next_IFD);
}
catch (Exception e)
{
throw (e);
}
return;
}// end of writeTiffImageFileDirectory
//*****************************************************************
//* W R I T E B I T S P E R P I X E L
//*****************************************************************
void writeBitsPerPixel() throws Exception
{
if (!ok_to_write)
throw (new Exception("Output Stream is not open."));
os.writeShort(8);
os.writeShort(8);
os.writeShort(8);
return;
}// end of writeBitsPerPixel()
} // end of TiffWriter
| true |
e3b8e1cbd51247d2c692e601c4f5740149b6f832 | Java | thy00/Selling | /src/test/java/cn/thyonline/dao/OrderDetailRepositoryTest.java | UTF-8 | 1,403 | 2.09375 | 2 | [] | no_license | package cn.thyonline.dao;
import cn.thyonline.dataobject.OrderDetail;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
import static org.junit.Assert.*;
/**
* @Description:
* @Author: Created by thy
* @Date: 2018/6/20 20:23
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderDetailRepositoryTest {
@Autowired
private OrderDetailRepository repository;
@Test
public void saveTest(){
OrderDetail detail=new OrderDetail();
detail.setDetailId("1232");
detail.setOrderId("12323");
detail.setProductIcon(String.valueOf(43));
detail.setProductId("2342");
detail.setProductName("咖啡");
detail.setProductPrice(BigDecimal.valueOf(8989));
detail.setProductQuantity(2);
OrderDetail save = repository.save(detail);
Assert.assertNotNull(save);
}
@Test
public void findByOrOrderId() {
PageRequest request=new PageRequest(0,2);
List<OrderDetail> details = repository.findByOrderId("12323");
Assert.assertNotEquals(0,details.size());
}
} | true |
d0191e9c3cb03fe64182f1a7e24355f2f65d3a45 | Java | bekirberksenel/PandemicAssessmentOfTurkey | /spring-boot/src/main/java/com/mongodb/starter/controllers/CoronaCaseController.java | UTF-8 | 3,997 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | package com.mongodb.starter.controllers;
import com.mongodb.starter.HaberParser;
import com.mongodb.starter.models.CaseSummary;
import com.mongodb.starter.models.CoronaCase;
import com.mongodb.starter.repositories.CoronaCaseRepository;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/api")
public class CoronaCaseController {
private final static Logger LOGGER = LoggerFactory.getLogger(CoronaCaseController.class);
private final CoronaCaseRepository coronaCaseRepository;
public CoronaCaseController(CoronaCaseRepository coronaCaseRepository) {
this.coronaCaseRepository = coronaCaseRepository;
}
//Declaring rooting for method
@PostMapping("insertCase")
@ResponseStatus(HttpStatus.CREATED)
//ALLOW react to access method
@CrossOrigin(origins = "http://localhost:3000")
public CoronaCase postCase(@RequestBody String haber) {
HaberParser parser = new HaberParser(haber);
try{
//try to parse corona news
CoronaCase c = parser.getCase();
if(c == null){
c = new CoronaCase();
return c;
};
// save to db if valid new
return coronaCaseRepository.save(c);
}catch (Exception e){
System.out.println(e);
e.printStackTrace();
CoronaCase c = new CoronaCase();
return c;
}
}
@PostMapping("caseSummary")
@ResponseStatus(HttpStatus.CREATED)
@CrossOrigin(origins = "http://localhost:3000")
public ArrayList<CaseSummary> getSummary(@RequestBody String sehir) {
try{
HashMap<String,CaseSummary> summaries = new HashMap<String,CaseSummary>();
List<CoronaCase> cases;
// find corona cases from db
if(sehir .equals("TÜM ŞEHİRLER"))
cases = coronaCaseRepository.findAll();
else
cases = coronaCaseRepository.findAll(sehir);
//CALCULATE SUMMARY FOR ALL CASE DATES
for(int a=0;a<cases.size();a++){
// ıf summary for date exist, add to it
if(summaries.containsKey(cases.get(a).getDate().toString())){
CaseSummary s = summaries.get(cases.get(a).getDate().toString());
s.toplamTaburcu += cases.get(a).getTaburcuSayisi();
s.toplamVaka += cases.get(a).getVakaSayisi();
s.toplamVefat += cases.get(a).getVefatSayisi();
}else{
// create new summary if not exist for date
CaseSummary s = new CaseSummary(sehir,cases.get(a).getDate());
s.toplamTaburcu += cases.get(a).getTaburcuSayisi();
s.toplamVaka += cases.get(a).getVakaSayisi();
s.toplamVefat += cases.get(a).getVefatSayisi();
summaries.put(cases.get(a).getDate().toString(),s);
}
}
// GET SUMMARRİES AND SOORT
ArrayList<CaseSummary> listOfKeys
= new ArrayList<CaseSummary>(summaries.values());
listOfKeys.sort((o1, o2) -> o1.date.compareTo(o2.date));
return listOfKeys;
}catch (Exception e){
System.out.println(e);
e.printStackTrace();
return null;
}
}
@GetMapping("cases")
public List<CoronaCase> getCases() {
return coronaCaseRepository.findAll();
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public final Exception handleAllExceptions(RuntimeException e) {
LOGGER.error("Internal server error.", e);
return e;
}
}
| true |
7c1b3655402a2f4efa17caff625a479fc4353c8e | Java | kingdzdz/FanweLive1 | /fanweHybridLive/src/main/java/com/fanwe/baimei/appview/BMDailyTasksEntranceView.java | UTF-8 | 4,863 | 2.234375 | 2 | [] | no_license | package com.fanwe.baimei.appview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.View;
import com.fanwe.baimei.dialog.BMDailyTasksDialog;
import com.fanwe.live.R;
import com.fanwe.live.appview.BaseAppView;
/**
* 包名: com.fanwe.baimei.appview
* 描述: 每日任务列表入口
* 作者: Su
* 创建时间: 2017/5/31 17:04
**/
public class BMDailyTasksEntranceView extends BaseAppView
{
private static final long DURATION_ALARM = 1000;
private BMDailyTasksDialog mTasksDialog;
private AnimatorSet mAlarmAnimatorSet;
private Handler mDelayHandler;
private Runnable mAlarmRunnable;
public BMDailyTasksEntranceView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
initBMDailyTaskEntranceView(context);
}
public BMDailyTasksEntranceView(Context context, AttributeSet attrs)
{
super(context, attrs);
initBMDailyTaskEntranceView(context);
}
public BMDailyTasksEntranceView(Context context)
{
super(context);
initBMDailyTaskEntranceView(context);
}
private void initBMDailyTaskEntranceView(Context context)
{
setContentView(R.layout.bm_view_daily_tasks_entrance);
setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
getTasksDialog().show();
stopAlarm();
}
});
}
private Handler getDelayHandler()
{
if (mDelayHandler == null)
{
mDelayHandler = new Handler(Looper.getMainLooper());
}
return mDelayHandler;
}
private Runnable getAlarmRunnable()
{
if (mAlarmRunnable == null)
{
mAlarmRunnable = new Runnable()
{
@Override
public void run()
{
stopAlarm();
getAlarmAnimatorSet().start();
}
};
}
return mAlarmRunnable;
}
private BMDailyTasksDialog getTasksDialog()
{
if (mTasksDialog == null)
{
mTasksDialog = new BMDailyTasksDialog(getActivity());
}
return mTasksDialog;
}
@Override
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
stopAlarm();
}
/**
* 开始提醒动画
*/
public void startAlarm()
{
startAlarm(0);
}
/**
* 指定毫秒后开始提醒动画
* @param delayMills
*/
public void startAlarm(long delayMills)
{
stopAlarm();
getDelayHandler().postDelayed(getAlarmRunnable(), delayMills);
}
/**
* 结束提醒动画
*/
public void stopAlarm()
{
if (getAlarmAnimatorSet().isRunning())
{
getAlarmAnimatorSet().cancel();
getDelayHandler().removeCallbacks(getAlarmRunnable());
}
}
private AnimatorSet getAlarmAnimatorSet()
{
if (mAlarmAnimatorSet == null)
{
mAlarmAnimatorSet = new AnimatorSet();
ObjectAnimator oa1 = ObjectAnimator.ofFloat(BMDailyTasksEntranceView.this, "scaleX", 1, 0.9f, 0.9f, 1.1f, 1.1f, 1.1f, 1.1f, 1.1f, 1.1f, 1);
ObjectAnimator oa2 = ObjectAnimator.ofFloat(BMDailyTasksEntranceView.this, "scaleY", 1, 0.9f, 0.9f, 1.1f, 1.1f, 1.1f, 1.1f, 1.1f, 1.1f, 1);
ObjectAnimator oa3 = ObjectAnimator.ofFloat(BMDailyTasksEntranceView.this, "rotation", 0, -5, -5, 5, -5, 5, -5, 5, -5, 0);
oa1.setRepeatCount(Integer.MAX_VALUE);
oa2.setRepeatCount(Integer.MAX_VALUE);
oa3.setRepeatCount(Integer.MAX_VALUE);
oa1.setRepeatMode(ValueAnimator.RESTART);
oa2.setRepeatMode(ValueAnimator.RESTART);
oa3.setRepeatMode(ValueAnimator.RESTART);
mAlarmAnimatorSet.playTogether(oa1, oa2, oa3);
mAlarmAnimatorSet.setDuration(DURATION_ALARM);
mAlarmAnimatorSet.addListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationCancel(Animator animation)
{
super.onAnimationCancel(animation);
BMDailyTasksEntranceView.this.setScaleX(1.0f);
BMDailyTasksEntranceView.this.setScaleY(1.0f);
BMDailyTasksEntranceView.this.setRotation(0);
}
});
}
return mAlarmAnimatorSet;
}
}
| true |
e6cd1029bee59f66fc0dbd2eeeed1383f69c6289 | Java | Atarikir/java_basics | /15_NoSQL/Students/src/main/java/Main.java | UTF-8 | 2,790 | 3.015625 | 3 | [] | no_license | import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.BsonDocument;
import org.bson.Document;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("studentsDb");
MongoCollection<Document> collection = database.getCollection("students");
collection.drop();
String csvFile = "15_NoSQL/Students/src/main/resources/mongo.csv";
collection.insertMany(parseMongoCsv(csvFile));
System.out.println("Общее количество студентов: " + collection.countDocuments());
BsonDocument query = BsonDocument.parse("{age: {$gt: 40}}");
System.out.println("Количество студентов старше 40 лет: " + collection.countDocuments(query));
query = BsonDocument.parse("{age: 1}");
System.out.println("Имя самого молодого студента: " + Objects.requireNonNull(collection.find().sort(query)
.limit(1).first()).get("name")
);
query = BsonDocument.parse("{age: -1}");
Document oldestStudent = collection.find().sort(query).first();
assert oldestStudent != null;
System.out.println("Список курсов самого старого студента: " + oldestStudent.get("name") + "\nКурсы: ");
oldestStudent.values().stream().skip(3).forEach(System.out::println);
}
private static List<Document> parseMongoCsv(String csvFile) {
List<Document> listStudents = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(csvFile))) {
String defaultSeparator = ",";
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] columns = line.split(defaultSeparator, 3);
String[] courses = columns[2].split(defaultSeparator);
listStudents.add(new Document()
.append("name", columns[0])
.append("age", Integer.valueOf(columns[1]))
.append("courses", Arrays.asList(courses))
);
}
} catch (FileNotFoundException e) {
System.out.println("Wrong path to file or folder!");
} catch (IOException e) {
e.printStackTrace();
}
return listStudents;
}
}
| true |
c643a6bfc119fe7f4277393b2bd30cc6e44a85f7 | Java | dyhpoon/Fo.dex | /app/src/main/java/com/dyhpoon/fodex/view/PleaseInstallToast.java | UTF-8 | 844 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package com.dyhpoon.fodex.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.dyhpoon.fodex.R;
/**
* Created by darrenpoon on 17/3/15.
*/
public class PleaseInstallToast extends Toast {
private PleaseInstallToast(Context context) {
super(context);
}
@TargetApi(21)
public static Toast make(Context context, String text) {
Resources res = context.getResources();
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.ic_cross_fit_15);
return CustomToast.make(
context,
text,
res.getColor(R.color.red),
drawable);
}
}
| true |
3bb0e99bfdccadbbf8e524bde3cabe6db4c371e6 | Java | syanima/boot-camp | /src/kingdom_of_Balloria/balls/ReadOnlyBalls.java | UTF-8 | 390 | 2.9375 | 3 | [] | no_license | package kingdom_of_Balloria.balls;
import kingdom_of_Balloria.Color;
import kingdom_of_Balloria.balls.Balls;
public class ReadOnlyBalls {
private final Balls balls;
public ReadOnlyBalls(Balls balls) {
this.balls = balls;
}
public int size() {
return balls.size();
}
public int countOf(Color color) {
return balls.countOf(color);
}
} | true |
19390db52a4a981a033fe062b59d6fd1e4ba69ac | Java | caihaitao/shiro | /myShiroTest/src/main/java/mytest/myShiroTest/ShiroHelloWord.java | UTF-8 | 1,283 | 2.140625 | 2 | [] | no_license | /*******************************************************************************
* Created on 2016年4月13日 上午9:24:41
* Copyright (c) 2014 深圳市小牛电子商务有限公司版权所有. 粤ICP备13089339号
* 注意:本内容仅限于深圳市小牛电子商务有限公司内部传阅,禁止外泄以及用于其他商业目的!
******************************************************************************/
package mytest.myShiroTest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
/**
* @author caihaitao 2016年4月13日 上午9:24:41
*/
public class ShiroHelloWord {
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager manager = factory.getInstance();
SecurityUtils.setSecurityManager(manager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
subject.login(token);
System.out.println(subject.isAuthenticated());
}
}
| true |
e4f765203f8e95dee12dd2a8e8aa99d5a02e6d74 | Java | rheeeujin/pension | /psproject/src/common/Pagination.java | UTF-8 | 1,252 | 2.796875 | 3 | [] | no_license | package common;
import lombok.Data;
@Data
public class Pagination {
private int ppv; // page per view = 12
private int pageRange; // 한페이지에 보여줄 페이징범위
private int totalCnt; // 총 게시글 수
private int currPage; // 현재 페이지 번호
//계산 이후 결과값
private int pageCnt; // 페이지 수
private boolean firstRange; // 첫번째 페이지 범위 인가
private boolean lastRange; // 마지막 페이지 범위 인가
private int from; // 쿼리 사용시 시작 위치
private int to; // 쿼리 사용시 종료 위치
private int fromPage; // 화면 표시에 사용될 시작 페이지 번호
private int toPage; // 화면 표시에 사용될 종료 페이지 번호
public Pagination(int ppv, int pageRange, int totalCnt, int currPage) {
this.ppv = ppv;
this.pageRange = pageRange;
this.totalCnt = totalCnt;
this.currPage = currPage;
pageCnt = (totalCnt-1) / ppv + 1;
to = ppv * currPage;
from = to - ppv + 1;
toPage = ((currPage -1) / pageRange + 1) * pageRange;
fromPage = toPage - pageRange + 1;
toPage = toPage > pageCnt ? pageCnt : toPage;
firstRange = fromPage != 1;
lastRange = toPage != pageCnt;
}
}
| true |
4e75212bd3e3cb1174ab75ea2ff69113f8e2db94 | Java | michaelansel/slogo-team1-dukecs108 | /slogo/src/util/parser/rule/SequenceRule.java | UTF-8 | 1,994 | 2.578125 | 3 | [] | no_license | package util.parser.rule;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import util.parser.AbstractParserRule;
import util.parser.MatchFailedException;
import util.parser.ParserException;
import util.parser.ParserResult;
import util.parser.TokenManager;
public class SequenceRule extends AbstractParserRule
{
private List<AbstractParserRule> myRules =
new ArrayList<AbstractParserRule>();
public SequenceRule (Object[] objects)
{
for (Object o : objects)
myRules.add(ExactlyOneRule.create(o));
}
public ParserResult evaluate (TokenManager tokenManager)
throws ParserException
{
ParserResult result = new ParserResult();
if (logger.isLoggable(Level.FINER)) logger.finer(myRules.toString());
for (AbstractParserRule rule : myRules)
{
try
{
result.merge(rule.evaluate(tokenManager));
}
catch (MatchFailedException e)
{
throw new MatchFailedException(/*
* String.format(
* "Sequence rule failed while parsing %s.\nRemaining Tokens: %s"
* , rule.toString(),
* myTokens.toString())
*/"Sequence rule match failure.", e);
}
}
if (logger.isLoggable(Level.FINER)) logger.finer("Sequence returning: " +
result.toString());
return processResult(result);
}
@Override
public void setRule (AbstractParserRule rule)
{
throw new UnsupportedOperationException();
}
@Override
public String toString ()
{
return "SequenceRule";
}
}
| true |
1db8ba5566b00ceec4cd07e07b6d125ada4a67aa | Java | jacking1008/toures-balon | /services/Mocks/espectaculos/src/main/java/com/tuboleta/espectaculos/service/RestPartido.java | UTF-8 | 4,403 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.tuboleta.espectaculos.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.tuboleta.espectaculos.vo.RequestRest;
import com.tuboleta.espectaculos.vo.Response;
import com.tuboleta.espectaculos.vo.VOPartido;
@RestController
@RequestMapping(path = "/servicesREST/TUBOLETA")
public class RestPartido {
private List<VOPartido> partidos = createListPartidos();
@RequestMapping(method = RequestMethod.POST, path = "/consultarEventos", consumes = "application/json", produces = "application/json")
public @ResponseBody List<VOPartido> consultarEventos(@RequestBody RequestRest request) throws Exception {
System.out.println("Clasificacion Evento: " + request.getClasificacionEvento());
try {
if (request.getClasificacionEvento().equals("Deportes")) {
return partidos;
}
return null;
} catch (Exception ex) {
return null;
}
}
@RequestMapping(method = RequestMethod.PUT, path = "/reservarEvento", consumes = "application/json", produces = "application/json")
public @ResponseBody Response reservarEvento(@RequestBody RequestRest request) {
System.out.println("Nombre del evento: " + request.getNombreEvento());
System.out.println("Numero de Reserva: " + request.getNumReserva());
System.out.println("Nombre Cliente: " + request.getNombre());
System.out.println("Identificacion Cliente: " + request.getIdentificacion());
Integer numReserva = getRandomNumberUsingInts(1,100000);
String mensaje = "Reserva realizada Exitosamente";
if (numReserva < 20000) {
numReserva = 0;
mensaje = "No se pudo realizar la reserva solicitada";
}
return new Response(numReserva, mensaje);
}
@RequestMapping(method = RequestMethod.PUT, path = "/pagarEvento", consumes = "application/json", produces = "application/json")
public @ResponseBody Response pagarEvento(@RequestBody RequestRest request) {
System.out.println("Numero de reserva: " + request.getNumReserva());
System.out.println("Valor: " + request.getValor());
return new Response(request.getNumReserva(), "Reserva Pagada Exitosamente por valor de: "+request.getValor());
}
public int getRandomNumberUsingInts(int min, int max) {
Random random = new Random();
return random.ints(min, max)
.findFirst()
.getAsInt();
}
private static List<VOPartido> createListPartidos() {
List<VOPartido> tempPartidos = new ArrayList<>();
VOPartido partido1 = new VOPartido();
partido1.setNombreEvento("ELIMINATORIAS QATAR 2022");
partido1.setClasificacion("Deportes");
partido1.setFechaHora("jueves 3 septiembre 2020 15:30");
partido1.setLugar("Estadio Metropolitano (Barranquilla)");
partido1.setPrecio(new Random().nextDouble() * 100000);
partido1.setUbicacion("OCCIDENTAL BAJA");
VOPartido partido2 = new VOPartido();
partido2.setNombreEvento("ELIMINATORIAS QATAR 2022");
partido2.setClasificacion("Deportes");
partido2.setFechaHora("jueves 3 septiembre 2020 15:30");
partido2.setLugar("Estadio Metropolitano (Barranquilla)");
partido2.setPrecio(new Random().nextDouble() * 100000);
partido2.setUbicacion("OCCIDENTAL ALTA");
VOPartido partido3 = new VOPartido();
partido3.setNombreEvento("ELIMINATORIAS QATAR 2022");
partido3.setClasificacion("Deportes");
partido3.setFechaHora("jueves 3 septiembre 2020 15:30");
partido3.setLugar("Estadio Metropolitano (Barranquilla)");
partido3.setPrecio(new Random().nextDouble() * 100000);
partido3.setUbicacion("ORIENTAL ALTA");
VOPartido partido4 = new VOPartido();
partido4.setNombreEvento("ELIMINATORIAS QATAR 2022");
partido4.setClasificacion("Deportes");
partido4.setFechaHora("jueves 3 septiembre 2020 15:30");
partido4.setLugar("Estadio Metropolitano (Barranquilla)");
partido4.setPrecio(new Random().nextDouble() * 100000);
partido4.setUbicacion("ORIENTAL BAJA");
tempPartidos.add(partido1);
tempPartidos.add(partido2);
tempPartidos.add(partido3);
tempPartidos.add(partido4);
return tempPartidos;
}
} | true |
2b897fb4f3fbb3fdd734602d6401916299c221d0 | Java | kuilaoda5/MsCrowd | /mscrowdfunding01-admin-parent/mscrowdfunding03-admin-component/src/main/java/cn/melonseed/crowd/service/api/RoleService.java | UTF-8 | 778 | 1.992188 | 2 | [] | no_license | /**
* Title: RoleService.java
* Description:
* @author MelonSeed
* @date 2021年5月29日
* @version 1.0
*/
package cn.melonseed.crowd.service.api;
import java.util.List;
import com.github.pagehelper.PageInfo;
import cn.melonseed.crowd.entity.Role;
/**
* Title: RoleService
* Description:
* @author MelonSeed
* @date 2021年5月29日
*/
public interface RoleService {
PageInfo<Role> getPageInfo(int pageNum, int pageSize, String keyword);
void saveRole(Role role);
void updateRole(Role role);
void removeById(List<Integer> roleIdList);
// 根据adminId查询已分配的角色
List<Role> queryUnAssignedRoleList(Integer adminId);
List<Role> queryAssignedRoleList(Integer adminId);
}
| true |
46f72e5e03b7c85ed9f746bb652ed5744b917fba | Java | resonancellc/RemoteDebugServer | /src/com/app2/banana/ServerThread.java | UTF-8 | 4,276 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package com.app2.banana;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import com.app2.manager.ChatConnection;
import com.app2.manager.Configuration;
import com.app2.manager.KryoNetServer;
import com.esotericsoftware.kryonet.Connection;
public class ServerThread extends BThread {
public static final String TAG = "ServerThread";
private ServerSocket mServerSocket = null;
private List<AdbProxy> hostList = new ArrayList<AdbProxy>();
private List<AdbProxy> slaveList = new ArrayList<AdbProxy>();
private List<Session> sessionList = new ArrayList<Session>();
KryoNetServer mKryoNetServer = null;
private void startManagerServer() {
if (null == mKryoNetServer) {
mKryoNetServer = new KryoNetServer();
mKryoNetServer.start();
Log.d(TAG, "startManagerServer");
}
}
private void startAdbServer() {
try {
mServerSocket = new ServerSocket(Configuration.ADB_SERVER_PORT);
Log.d(TAG, "startAdbServer");
} catch (IOException e) {
e.printStackTrace();
}
}
public ServerThread() {
super();
}
public ServerThread(String name) {
super(name);
}
@Override
public void run() {
super.run();
startManagerServer();
startAdbServer();
while (true) {
Socket adbSocket = null;
try {
adbSocket = mServerSocket.accept();
Log.d(TAG, "adbSocket is " + adbSocket.toString());
} catch (IOException e) {
e.printStackTrace();
}
BlockingQueue<Data> responseStreamQueue = new LinkedBlockingQueue<Data>();
BlockingQueue<Data> requestStreamQueue = new LinkedBlockingQueue<Data>();
AdbProxy adbProxy = new AdbProxy("adbProxy", adbSocket,
responseStreamQueue, requestStreamQueue);
// List<Connection> connections = mKryoNetServer
// .getDeviceByType(Configuration.TYPE_INT_PC_TERMINAL);
List<Connection> connections = mKryoNetServer.getConnections();
Log.d(TAG, "connections size is " + connections.size());
int size = connections.size();
if (size > 0) {
// to do choice connection
ChatConnection c = null;
String address = null;
boolean find = false;
for (int i = 0; i < size; i++) {
c = (ChatConnection) connections.get(i);
Log.d(TAG, "connected phone adb client address is "
+ address + " name is " + c);
//Log.d(TAG, "connect pc adb client address is "
// + adbSocket.getInetAddress().toString());
if (null != c.mIp
&& c.mIp.trim().contains(
adbSocket.getInetAddress().toString())) {
find = true;
break;
}
}
Log.d(TAG, "11 find = " + find + " connection " + c);
if (find && null != c) {
if (null != c.mDestDevice) {
ChatConnection tempC = null;
connections = mKryoNetServer
.getConnectedDevicesByType(Configuration.TYPE_INT_PHONE_CLIENT);
size = connections.size();
Log.d(TAG, "22 connections size is " + size);
find = false;
for (int i = 0; i < size; i++) {
tempC = (ChatConnection) connections.get(i);
Log.d(TAG, "22 connection is " + tempC);
Log.d(TAG, "22 mDestDevice is " + c.mDestDevice);
if (tempC.name.equals(c.mDestDevice)) {
find = true;
break;
}
}
Log.d(TAG, "22 find = " + find + " connection " + tempC);
if (find && null != tempC) {
Session session = new Session(adbProxy, tempC,
requestStreamQueue, responseStreamQueue);
session.start();
hostList.add(adbProxy);
adbProxy.run();
tempC.mSession = session;
sessionList.add(session);
Log.d(TAG,
"sessionList size is " + sessionList.size());
} else {
System.out.println("dst device is not online!");
}
} else {
System.out.println("not set dest device error!!!");
}
} else {
System.out.println("please config first!");
}
}
}
// long timeout = System.currentTimeMillis() + 1000000;
// while (timeout > System.currentTimeMillis()) {
// try {
// sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// Log.d(TAG, "ServerThread run out");
}
}
| true |
b287fd270e030d96c0cf0b35c8e361f59e30657a | Java | blackducksoftware/blackduck-alert | /channel-jira-cloud/src/test/java/com/synopsys/integration/alert/channel/jira/cloud/model/TestDoneStatusDetailsComponent.java | UTF-8 | 586 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | package com.synopsys.integration.alert.channel.jira.cloud.model;
import com.synopsys.integration.jira.common.model.components.StatusCategory;
import com.synopsys.integration.jira.common.model.components.StatusDetailsComponent;
public class TestDoneStatusDetailsComponent extends StatusDetailsComponent {
@Override
public String getName() {
return "done";
}
@Override
public String getId() {
return "1";
}
@Override
public StatusCategory getStatusCategory() {
return new StatusCategory(null, 1, "done", null, "done");
}
}
| true |
c70fdad08a64ff06ab5b3840b0db938056ff1dad | Java | Fu-Yilei/Calculator | /src/calcultator.java | UTF-8 | 4,738 | 2.9375 | 3 | [] | no_license | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class calcultator extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public JTextArea jt = new JTextArea();
public calcultator(){
int j = 0;
int height = 150;
setTitle("calculator");
getContentPane().setLayout(null);
Container c = getContentPane();
setSize(440,500);
for(int i = 0; i < 9; i++){
if(j % 3 == 0){
height += 60;
j = 0;
}
JButton bl = new JButton("" + (i + 1));
bl.setFont(new Font("Californian FB", Font.BOLD, 24));
bl.setFont(UIManager.getFont("Button.font"));
c.add(bl);
bl.setBounds(10 + 60 * j, height , 50, 50);
bl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jt.append(bl.getText());
}
});
j++;
}
JButton bl =new JButton("0");
bl.setFont(new Font("Californian FB", Font.BOLD, 24));
bl.setFont(UIManager.getFont("Button.font"));
bl.setBounds(70, 390, 50, 50);
c.add(bl);
bl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jt.append(bl.getText());
}
});
JButton b0 = new JButton(".");
b0.setFont(new Font("Californian FB", Font.BOLD, 24));
b0.setBounds(130, 390, 50, 50);
c.add(b0);
b0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(b0.getText());
}
});
JButton b1 = new JButton("+");
b1.setFont(new Font("Californian FB", Font.BOLD, 24));
b1.setBounds(300, 210, 50, 50);
c.add(b1);
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(" " + b1.getText() + " ");
}
});
JButton b2 = new JButton("-");
b2.setFont(new Font("Californian FB", Font.BOLD, 24));
b2.setFont(UIManager.getFont("Button.font"));
b2.setBounds(360, 210, 50, 50);
c.add(b2);
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(" " + b2.getText() + " ");
}
});
JButton b3 = new JButton("*");
b3.setFont(new Font("Californian FB", Font.BOLD, 24));
b3.setFont(UIManager.getFont("Button.font"));
b3.setBounds(300, 270, 50, 50);
c.add(b3);
b3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(" " + b3.getText() + " ");
}
});
JButton b4 = new JButton("/");
b4.setFont(new Font("Californian FB", Font.BOLD, 24));
b4.setFont(UIManager.getFont("Button.font"));
b4.setBounds(360, 270, 50, 50);
c.add(b4);
b4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(" " + b4.getText() + " ");
}
});
JButton b5 = new JButton("=");
b5.setFont(new Font("Californian FB", Font.BOLD, 24));
b5.setFont(UIManager.getFont("Button.font"));
b5.setBounds(300, 330, 50, 50);
c.add(b5);
b5.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jt.append(" ");
float num = transfer(jt.getText());
jt.append("\n" + num);
}
});
JButton b6 = new JButton("AC");
b6.setFont(new Font("Californian FB", Font.BOLD, 24));
b6.setFont(UIManager.getFont("Button.font"));
b6.setBounds(360, 330, 50, 50);
c.add(b6);
b6.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jt.setText("");
}
});
jt.setBounds(10, 10, 400, 172);
c.add(jt);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public float transfer(String a){
try{
int i, count = 0, j= 0;
float num1 = 0, num2 = 0, result = 0;
char ch = ' ';
for(i = 0; i < a.length(); i++){
if(a.charAt(i) == ' '){
count++;
switch(count){
case 1:
num1 = Float.parseFloat(a.substring(0, i));
break;
case 2:
ch = a.charAt(i - 1);
j = i;
break;
case 3:
num2 = Float.parseFloat(a.substring(j + 1, i));
break;
}
switch(ch){
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
}
}
return result;
}
catch(Exception e){
jt.setText("Error, please tap \"AC\".");
}
return 0;
}
public static void main(String arg[]){
new calcultator();
}
}
| true |
9667828d66e37e87b55d92e2dcf6ca3bcac0be3c | Java | AirspanNetworks/SWITModules | /airspan.netspan/src/main/java/Netspan/NBI_16_5/Lte/CbsdDetails.java | UTF-8 | 17,206 | 1.625 | 2 | [] | no_license |
package Netspan.NBI_16_5.Lte;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CbsdDetails complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CbsdDetails">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="FccId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CallSign" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Category" type="{http://Airspan.Netspan.WebServices}CbsdCategory" minOccurs="0"/>
* <element name="CbsdGroupType" type="{http://Airspan.Netspan.WebServices}CbsdGroupTypes" minOccurs="0"/>
* <element name="CbsdGroupId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="IsInstallParams" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="IsCpiSignatureData" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="HorizontalAccuracy" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="VerticalAccuracy" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="IndoorDeployment" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="AntennaAzimuth" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="AntennaDowntilt" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="AntennaGain" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="AntennaBeamwidth" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="AntennaModel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CpiDetails" type="{http://Airspan.Netspan.WebServices}CpiDetails" minOccurs="0"/>
* <element name="IsMeasurementCapability" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="MeasurementReportType" type="{http://Airspan.Netspan.WebServices}CbsdMeasReportTypes" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CbsdDetails", propOrder = {
"fccId",
"callSign",
"category",
"cbsdGroupType",
"cbsdGroupId",
"isInstallParams",
"isCpiSignatureData",
"horizontalAccuracy",
"verticalAccuracy",
"indoorDeployment",
"antennaAzimuth",
"antennaDowntilt",
"antennaGain",
"antennaBeamwidth",
"antennaModel",
"cpiDetails",
"isMeasurementCapability",
"measurementReportType"
})
public class CbsdDetails {
@XmlElement(name = "FccId")
protected String fccId;
@XmlElement(name = "CallSign")
protected String callSign;
@XmlElementRef(name = "Category", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<CbsdCategory> category;
@XmlElementRef(name = "CbsdGroupType", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<CbsdGroupTypes> cbsdGroupType;
@XmlElement(name = "CbsdGroupId")
protected String cbsdGroupId;
@XmlElementRef(name = "IsInstallParams", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Boolean> isInstallParams;
@XmlElementRef(name = "IsCpiSignatureData", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Boolean> isCpiSignatureData;
@XmlElementRef(name = "HorizontalAccuracy", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> horizontalAccuracy;
@XmlElementRef(name = "VerticalAccuracy", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> verticalAccuracy;
@XmlElementRef(name = "IndoorDeployment", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Boolean> indoorDeployment;
@XmlElementRef(name = "AntennaAzimuth", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> antennaAzimuth;
@XmlElementRef(name = "AntennaDowntilt", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> antennaDowntilt;
@XmlElementRef(name = "AntennaGain", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> antennaGain;
@XmlElementRef(name = "AntennaBeamwidth", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> antennaBeamwidth;
@XmlElement(name = "AntennaModel")
protected String antennaModel;
@XmlElement(name = "CpiDetails")
protected CpiDetails cpiDetails;
@XmlElementRef(name = "IsMeasurementCapability", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<Boolean> isMeasurementCapability;
@XmlElementRef(name = "MeasurementReportType", namespace = "http://Airspan.Netspan.WebServices", type = JAXBElement.class, required = false)
protected JAXBElement<CbsdMeasReportTypes> measurementReportType;
/**
* Gets the value of the fccId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFccId() {
return fccId;
}
/**
* Sets the value of the fccId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFccId(String value) {
this.fccId = value;
}
/**
* Gets the value of the callSign property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCallSign() {
return callSign;
}
/**
* Sets the value of the callSign property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCallSign(String value) {
this.callSign = value;
}
/**
* Gets the value of the category property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link CbsdCategory }{@code >}
*
*/
public JAXBElement<CbsdCategory> getCategory() {
return category;
}
/**
* Sets the value of the category property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link CbsdCategory }{@code >}
*
*/
public void setCategory(JAXBElement<CbsdCategory> value) {
this.category = value;
}
/**
* Gets the value of the cbsdGroupType property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link CbsdGroupTypes }{@code >}
*
*/
public JAXBElement<CbsdGroupTypes> getCbsdGroupType() {
return cbsdGroupType;
}
/**
* Sets the value of the cbsdGroupType property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link CbsdGroupTypes }{@code >}
*
*/
public void setCbsdGroupType(JAXBElement<CbsdGroupTypes> value) {
this.cbsdGroupType = value;
}
/**
* Gets the value of the cbsdGroupId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCbsdGroupId() {
return cbsdGroupId;
}
/**
* Sets the value of the cbsdGroupId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCbsdGroupId(String value) {
this.cbsdGroupId = value;
}
/**
* Gets the value of the isInstallParams property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public JAXBElement<Boolean> getIsInstallParams() {
return isInstallParams;
}
/**
* Sets the value of the isInstallParams property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public void setIsInstallParams(JAXBElement<Boolean> value) {
this.isInstallParams = value;
}
/**
* Gets the value of the isCpiSignatureData property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public JAXBElement<Boolean> getIsCpiSignatureData() {
return isCpiSignatureData;
}
/**
* Sets the value of the isCpiSignatureData property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public void setIsCpiSignatureData(JAXBElement<Boolean> value) {
this.isCpiSignatureData = value;
}
/**
* Gets the value of the horizontalAccuracy property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getHorizontalAccuracy() {
return horizontalAccuracy;
}
/**
* Sets the value of the horizontalAccuracy property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setHorizontalAccuracy(JAXBElement<Integer> value) {
this.horizontalAccuracy = value;
}
/**
* Gets the value of the verticalAccuracy property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getVerticalAccuracy() {
return verticalAccuracy;
}
/**
* Sets the value of the verticalAccuracy property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setVerticalAccuracy(JAXBElement<Integer> value) {
this.verticalAccuracy = value;
}
/**
* Gets the value of the indoorDeployment property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public JAXBElement<Boolean> getIndoorDeployment() {
return indoorDeployment;
}
/**
* Sets the value of the indoorDeployment property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public void setIndoorDeployment(JAXBElement<Boolean> value) {
this.indoorDeployment = value;
}
/**
* Gets the value of the antennaAzimuth property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getAntennaAzimuth() {
return antennaAzimuth;
}
/**
* Sets the value of the antennaAzimuth property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setAntennaAzimuth(JAXBElement<Integer> value) {
this.antennaAzimuth = value;
}
/**
* Gets the value of the antennaDowntilt property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getAntennaDowntilt() {
return antennaDowntilt;
}
/**
* Sets the value of the antennaDowntilt property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setAntennaDowntilt(JAXBElement<Integer> value) {
this.antennaDowntilt = value;
}
/**
* Gets the value of the antennaGain property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getAntennaGain() {
return antennaGain;
}
/**
* Sets the value of the antennaGain property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setAntennaGain(JAXBElement<Integer> value) {
this.antennaGain = value;
}
/**
* Gets the value of the antennaBeamwidth property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getAntennaBeamwidth() {
return antennaBeamwidth;
}
/**
* Sets the value of the antennaBeamwidth property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setAntennaBeamwidth(JAXBElement<Integer> value) {
this.antennaBeamwidth = value;
}
/**
* Gets the value of the antennaModel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAntennaModel() {
return antennaModel;
}
/**
* Sets the value of the antennaModel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAntennaModel(String value) {
this.antennaModel = value;
}
/**
* Gets the value of the cpiDetails property.
*
* @return
* possible object is
* {@link CpiDetails }
*
*/
public CpiDetails getCpiDetails() {
return cpiDetails;
}
/**
* Sets the value of the cpiDetails property.
*
* @param value
* allowed object is
* {@link CpiDetails }
*
*/
public void setCpiDetails(CpiDetails value) {
this.cpiDetails = value;
}
/**
* Gets the value of the isMeasurementCapability property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public JAXBElement<Boolean> getIsMeasurementCapability() {
return isMeasurementCapability;
}
/**
* Sets the value of the isMeasurementCapability property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*/
public void setIsMeasurementCapability(JAXBElement<Boolean> value) {
this.isMeasurementCapability = value;
}
/**
* Gets the value of the measurementReportType property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link CbsdMeasReportTypes }{@code >}
*
*/
public JAXBElement<CbsdMeasReportTypes> getMeasurementReportType() {
return measurementReportType;
}
/**
* Sets the value of the measurementReportType property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link CbsdMeasReportTypes }{@code >}
*
*/
public void setMeasurementReportType(JAXBElement<CbsdMeasReportTypes> value) {
this.measurementReportType = value;
}
}
| true |
4cb9a05c57a3665c6137df09fcdd9e226e0d92db | Java | mhenriquedev/cliente-api | /src/main/java/com/desafio/mirante/model/Cliente.java | UTF-8 | 2,238 | 1.960938 | 2 | [] | no_license | package com.desafio.mirante.model;
import java.util.Collection;
import java.util.List;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Classe Cliente
*
* @author mateus henrique
*
*/
@Entity
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String cpf;
@Embedded
private Endereco endereco;
private String username;
private String passwordHash;
private String role;
@OneToMany(fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private List<Telefone> telefone;
@OneToMany(fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private List<Email> email;
public Cliente() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public List<Telefone> getTelefone() {
return telefone;
}
public void setTelefone(List<Telefone> telefone) {
this.telefone = telefone;
}
public List<Email> getEmail() {
return email;
}
public void setEmail(List<Email> email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| true |
64403508157e07d951f1b190d49f86c6d88e766c | Java | q85064972/AopspringbootDemo | /msgsend/src/main/java/com/sms/msgsend/mapper/core/Mapper.java | UTF-8 | 1,821 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | package com.sms.msgsend.mapper.core;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.common.ConditionMapper;
import tk.mybatis.mapper.common.IdsMapper;
import tk.mybatis.mapper.common.special.InsertListMapper;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* 定制版MyBatis Mapper插件接口,如需其他接口参考官方文档自行添加。
*/
public interface Mapper<T>
extends
BaseMapper<T>,
ConditionMapper<T>,
IdsMapper<T>,
InsertListMapper<T> {
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> wrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
int updateById(@Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
| true |
d2c48e7d27bbfef461f33fff627d246c087df386 | Java | fanweijin521/JTechMod | /app/src/main/java/com/JTechMod/adapter/base/ViewPagerAdapter.java | UTF-8 | 1,168 | 2.390625 | 2 | [] | no_license | package com.JTechMod.adapter.base;
import java.util.ArrayList;
import com.JTechMod.fragment.base.BaseFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
/**
* viewpager适配器
*
* @author wuxubaiyang
*
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<BaseFragment> fragmentBases = new ArrayList<BaseFragment>();;
public void setFragmentBases(ArrayList<BaseFragment> fragmentBases) {
this.fragmentBases = fragmentBases;
}
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public ViewPagerAdapter(FragmentManager fragmentManager, ArrayList<BaseFragment> fragmentBases) {
super(fragmentManager);
this.fragmentBases = fragmentBases;
}
@Override
public Fragment getItem(int position) {
return fragmentBases.get(position);
}
@Override
public int getCount() {
return fragmentBases.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
}
} | true |
f544991ec56192afaa4c1c9202bcf1fa4642ffe6 | Java | DavidCrgh/Act05Creacionales | /src/Caso3/Producto/Combo.java | UTF-8 | 263 | 2.609375 | 3 | [] | no_license | package Caso3.Producto;
import java.util.ArrayList;
public class Combo {
private ArrayList<Alimento> items;
public Combo() {
items = new ArrayList<>();
}
public void addAlimento(Alimento alimento){
items.add(alimento);
}
}
| true |
ef917c066ad8809a856f1e04f3b9a1d48fce095c | Java | Cangyunzhuixue/oop | /src/elemOfopp/day5/Test.java | UTF-8 | 1,063 | 3.125 | 3 | [] | no_license | package elemOfopp.day5;
import java.util.Vector;
import java.util.Scanner;;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Vector<Double> vector = new Vector<Double>();
double score;
double maxNum = 0;
do {
score = scanner.nextDouble();
Double score2 = score;
vector.addElement(score2);
} while (score >= 0);
System.out.println(vector.size());
for (int i = 0; i < vector.size(); i++) {
double d2 = vector.elementAt(i).doubleValue();
maxNum = (maxNum > d2) ? maxNum : d2;
}
for (int i = 0; i < vector.size(); i++) {
double d3 = vector.elementAt(i).doubleValue();
if (d3 >= 0) {
if (maxNum - d3 <= 10) {
System.out.println(d3 + " :A");
} else if (maxNum - d3 <= 20) {
System.out.println(d3 + " :B");
} else if (maxNum - d3 <= 30) {
System.out.println(d3 + " :C");
} else {
System.out.println(d3 + " :D");
}
}
}
System.out.println(maxNum);
scanner.close();
}
}
| true |
46275f3e904ed6a1ad515d074c9658b6f00da782 | Java | vjaydeshmukh/Food-ordering | /app/src/main/java/com/library/apple/food/CartFragment.java | UTF-8 | 20,734 | 1.867188 | 2 | [
"MIT"
] | permissive | package com.library.apple.food;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CartFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
private List<CartItem> cartList;
TextView btn_coupon;
Button btn_empty;
boolean status = true;
TextView cart_tot_discount;
EditText et_coupon;
Button btn_proceed;
String auth_token;
private String cart_url = "https://www.hungermela.com/api/v1/cart/";
TextView cart_res_name,cart_item_price,cart_tot_price,cart_del_price;
View myView;
String final_price;
public void getAddress(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginToken",Context.MODE_PRIVATE);
auth_token = sharedPreferences.getString("token","error");
String url_address = "https://www.hungermela.com/api/v1/address/";
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.GET, url_address,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if(jsonObject1.getBoolean("selected")==true){
String line_1 = jsonObject1.getString("line_1");
String phone_number = jsonObject1.getString("phone_number");
String final_address = line_1+", "+phone_number;
TextView complete_address = (TextView)myView.findViewById(R.id.tv2);
complete_address.setText(final_address);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Token " + auth_token);
return params;
}
};
queue.add(postRequest);
}
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_cart,container,false);
getAddress();
cart_res_name = (TextView)myView.findViewById(R.id.cart_res_name);
cart_item_price = (TextView)myView.findViewById(R.id.cart_item_price);
cart_tot_price = (TextView)myView.findViewById(R.id.cart_tot_price);
cart_del_price = (TextView)myView.findViewById(R.id.cart_del_price);
cart_tot_discount = (TextView)myView.findViewById(R.id.cart_tot_discount);
btn_coupon = (TextView) myView.findViewById(R.id.btn_coupon);
et_coupon = (EditText)myView.findViewById(R.id.et_coupon);
btn_empty = (Button)myView.findViewById(R.id.btn_empty);
TextView address11112 = (TextView)myView.findViewById(R.id.editde7);
address11112.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),Address.class);
startActivity(intent);
}
});
btn_proceed = (Button)myView.findViewById(R.id.btn_proceed);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginToken",Context.MODE_PRIVATE);
auth_token = sharedPreferences.getString("token","error");
cartList = new ArrayList<>();
recyclerView = (RecyclerView)myView.findViewById(R.id.rv_cart);
adapter = new CartAdapter(getActivity(),cartList,auth_token,recyclerView);
recyclerView.setAdapter(adapter);
btn_proceed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
// if(Integer.parseInt(final_price)<100){
//
// Toast.makeText(getActivity(),"Minimum order value must be more than Rs 100",Toast.LENGTH_LONG).show();
// }
// else{
// }
checkOut(et_coupon.getText().toString().trim());
}
});
// TextView tv1 = (TextView)myView.findViewById(R.id.tv1);
//// tv1.setOnClickListener(new View.OnClickListener() {
//// @Override
//// public void onClick(View view) {
////
//// BottomSheetAddress1 bottomSheetAddress = new BottomSheetAddress1();
//// bottomSheetAddress.show(getActivity().getSupportFragmentManager(),"bottomSheetAddress");
////
////
////
//// }
//// });
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
getData();
getData1();
btn_empty.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
empty_cart(view);
}
});
btn_coupon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(status == true){
String coup = et_coupon.getText().toString().trim();
if(!(coup.isEmpty())){
applyCoupon(coup);
et_coupon.setEnabled(false);
btn_coupon.setText("REMOVE");
btn_coupon.setTextColor(Color.RED);
status = false;
Toast.makeText(getActivity(),"Coupon Applied",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getActivity(),"Apply coupon first",Toast.LENGTH_LONG).show();
}
}
else if(status == false){
et_coupon.setEnabled(true);
btn_coupon.setText("APPLY");
status = true;
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new CartFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
}
}
});
return myView;
}
private void applyCoupon(final String coupoun){
String coupon_url = "https://www.hungermela.com/api/v1/final-price/";
RequestQueue queue2 = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.POST, coupon_url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
try {
JSONObject js = new JSONObject(response);
String cart_total_without_dis = js.getString("total_cart_without_discount");
String price_item_tot1 = getActivity().getString(R.string.price,cart_total_without_dis);
cart_tot_price.setText(price_item_tot1);
String del_charge = js.getString("delivery_charge");
String del_charge1 = getActivity().getString(R.string.price,del_charge);
cart_del_price.setText(del_charge1);
String discount_price = js.getString("discount_price");
String discount_price1 = getActivity().getString(R.string.dis_price,discount_price);
cart_tot_discount.setText(discount_price1);
final_price = js.getString("final_price");
String final_price1 = getActivity().getString(R.string.proceed_to_pay,final_price);
btn_proceed.setText(final_price1);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("count",Context.MODE_PRIVATE);
String name = sharedPreferences.getString("count1","0");
String sub_title = getActivity().getString(R.string.price1,name,final_price);
cart_item_price.setText(sub_title);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token "+auth_token);
return params;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("code", coupoun);
return params;
}
};
queue2.add(postRequest);
}
public void getData1(){
RequestQueue queue1 = Volley.newRequestQueue(getActivity());
String url_final = "https://www.hungermela.com/api/v1/final-price/";
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, url_final, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String price_item_tot = response.getString("total_cart");
String del_charge = response.getString("delivery_charge");
final_price = response.getString("final_price");
String price_item_tot1 = getActivity().getString(R.string.price,price_item_tot);
cart_tot_price.setText(price_item_tot1);
String del_charge1 = getActivity().getString(R.string.price,del_charge);
cart_del_price.setText(del_charge1);
String final_price1 = getActivity().getString(R.string.proceed_to_pay,final_price);
btn_proceed.setText(final_price1);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("count",Context.MODE_PRIVATE);
String name = sharedPreferences.getString("count1","0");
String sub_title = getActivity().getString(R.string.price1,name,final_price);
cart_item_price.setText(sub_title);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token "+auth_token);
return params;
}
};
queue1.add(jsonObjectRequest1);
}
private void empty_cart(final View view){
String url_empty = "https://www.hungermela.com/api/v1/empty-cart/";
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.POST, url_empty,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
getData();
getData1();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new CartFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token "+auth_token);
return params;
}
};
queue.add(postRequest);
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, cart_url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String count = response.getString("count");
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("count", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("count1",count);
editor.commit();
String total = response.getString("total");
JSONArray items = response.getJSONArray("items");
for(int i=0; i < response.length(); i++){
JSONObject jsonObject = items.getJSONObject(i);
CartItem cartItem = new CartItem();
cartItem.setId_id(jsonObject.getString("id"));
JSONObject item = jsonObject.getJSONObject("item");
cartItem.setCart_item_id(item.getString("id"));
cartItem.setVegnon_cart(item.getBoolean("veg"));
cartItem.setTitle_cart(item.getString("name"));
cartItem.setNo_cart(jsonObject.getString("quantity"));
cartItem.setPrice_cart(jsonObject.getString("price"));
cartList.add(cartItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token "+auth_token);
return params;
}
};
queue.add(jsonObjectRequest);
}
private void checkOut(final String coupoun){
String checkout_url = "https://www.hungermela.com/api/v1/checkout/";
RequestQueue queue2 = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.POST, checkout_url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
try {
JSONObject js = new JSONObject(response);
Intent intent = new Intent(getActivity(),success.class);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token "+auth_token);
return params;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("code", coupoun);
return params;
}
};
queue2.add(postRequest);
}
}
| true |
d0d30bd7226441e70ddb530ca28f355f1cb783d6 | Java | angelicamarmolejo28/logica-programacion-college | /src/college/People.java | UTF-8 | 833 | 2.78125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package college;
/**
*
* @author angelica
*/
public class People {
public String name;
public String lastname;
int id;
public String maritalstatus;
public People (String name, String lastname, int id, String maritalStatus){
try {
if(id <= 0){
throw new ArithmeticException("The ID is not valid");
}
this.id=id;
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
this.name=name;
this.lastname=lastname;
this.maritalstatus=maritalStatus;
}
public void setMaritalStatus (String maritalStatus) {
this.maritalstatus=maritalStatus;
}
}
| true |
3ebb3337f3d89844d5263516c30a5665967cd5e2 | Java | bjblack/anathema_3e | /Hero_Sheet/src/main/java/net/sf/anathema/hero/sheet/pdf/PortraitSimpleExaltSheetReport.java | UTF-8 | 3,781 | 1.921875 | 2 | [] | no_license | package net.sf.anathema.hero.sheet.pdf;
import net.sf.anathema.framework.reporting.pdf.AbstractPdfReport;
import net.sf.anathema.framework.reporting.pdf.PageSize;
import net.sf.anathema.hero.environment.HeroEnvironment;
import net.sf.anathema.hero.environment.report.ReportException;
import net.sf.anathema.hero.individual.model.Hero;
import net.sf.anathema.hero.sheet.pdf.content.ReportContentRegistry;
import net.sf.anathema.hero.sheet.pdf.encoder.boxes.EncoderRegistry;
import net.sf.anathema.hero.sheet.pdf.encoder.graphics.SheetGraphics;
import net.sf.anathema.hero.sheet.pdf.page.PageConfiguration;
import net.sf.anathema.hero.sheet.pdf.page.PageEncoder;
import net.sf.anathema.hero.sheet.pdf.page.PageRegistry;
import net.sf.anathema.hero.sheet.pdf.page.layout.Sheet;
import net.sf.anathema.hero.sheet.pdf.page.layout.simple.FirstPageEncoder;
import net.sf.anathema.hero.sheet.pdf.page.layout.simple.SecondPageEncoder;
import net.sf.anathema.hero.sheet.pdf.session.ReportSession;
import net.sf.anathema.hero.sheet.preferences.PageSizePreference;
import net.sf.anathema.library.resources.Resources;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.ArrayList;
import java.util.List;
public class PortraitSimpleExaltSheetReport extends AbstractPdfReport
{
private final Resources resources;
private final PageSizePreference pageSizePreference;
private HeroReportingRegistries moduleObject;
public PortraitSimpleExaltSheetReport (HeroEnvironment environment, PageSizePreference pageSizePreference)
{
this.resources = environment.getResources ();
this.pageSizePreference = pageSizePreference;
this.moduleObject = new HeroReportingRegistries (environment.getObjectFactory (), resources);
}
@Override
public String toString ()
{
return resources.getString ("CharacterModule.Reporting.Sheet.Name");
}
@Override
public void performPrint (Hero hero, Document document, PdfWriter writer) throws ReportException
{
PageSize pageSize = pageSizePreference.getPageSize ();
PdfContentByte directContent = writer.getDirectContent ();
PageConfiguration configuration = PageConfiguration.ForPortrait (pageSize);
try
{
List<PageEncoder> encoderList = new ArrayList<> ();
encoderList.add (new FirstPageEncoder (configuration));
ReportSession session = new ReportSession (getContentRegistry (), hero);
encoderList.addAll (findAdditionalPages (pageSize, session));
encoderList.add (new SecondPageEncoder ());
Sheet sheet = new Sheet (document, getEncoderRegistry (), resources, pageSize);
for (PageEncoder encoder : encoderList)
{
SheetGraphics graphics = SheetGraphics.WithHelvetica (directContent);
encoder.encode (sheet, graphics, session);
}
}
catch (Exception e)
{
throw new ReportException (e);
}
}
private List<PageEncoder> findAdditionalPages (PageSize pageSize, ReportSession session)
{
PageRegistry additionalPageRegistry = getReportingModuleObject ().getAdditionalPageRegistry ();
return additionalPageRegistry.createEncoders (pageSize, getEncoderRegistry (), resources, session);
}
private EncoderRegistry getEncoderRegistry ()
{
return getReportingModuleObject ().getEncoderRegistry ();
}
private HeroReportingRegistries getReportingModuleObject ()
{
return moduleObject;
}
private ReportContentRegistry getContentRegistry ()
{
HeroReportingRegistries moduleObject = getReportingModuleObject ();
return moduleObject.getContentRegistry ();
}
@Override
public boolean supports (Hero hero)
{
return hero.getSplat ().getTemplateType ().getHeroType ().isEssenceUser ();
}
}
| true |
542e47426959b90e7df0dc19c4d1533d69caa3cc | Java | KajanM/SpringIntegration | /helloworld/src/main/java/com/k4j4n/helloworld/service/HelloServiceImpl.java | UTF-8 | 516 | 2.328125 | 2 | [] | no_license | package com.k4j4n.helloworld.service;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Service;
/**
* Created by k4j4n on 10/30/17.
*/
@Service("helloService")
public class HelloServiceImpl implements HelloService {
@Override
@ServiceActivator(inputChannel = "name")
//@Gateway(requestChannel = "name")
public void sayHello(String name) {
System.out.println("Hello " + name + " :)");
}
}
| true |
a531b4790bb64f07eb77b39402fe238a45f47a95 | Java | sergiovictoria/bpm-portal | /dto/src/main/java/br/com/seta/processo/dto/Compra.java | UTF-8 | 1,172 | 2.140625 | 2 | [] | no_license | package br.com.seta.processo.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class Compra implements Serializable {
private static final long serialVersionUID = 1L;
private BigDecimal nrorequisicao;
private String status;
private java.util.Date dtacompra;
private java.util.Date dataExecucao;
public Compra( ) {
}
public Compra(BigDecimal nrorequisicao, String status, Date dtacompra) {
this.nrorequisicao = nrorequisicao;
this.status = status;
this.dtacompra = dtacompra;
}
public BigDecimal getNrorequisicao() {
return nrorequisicao;
}
public void setNrorequisicao(BigDecimal nrorequisicao) {
this.nrorequisicao = nrorequisicao;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public java.util.Date getDtacompra() {
return dtacompra;
}
public void setDtacompra(java.util.Date dtacompra) {
this.dtacompra = dtacompra;
}
public java.util.Date getDataExecucao() {
return dataExecucao;
}
public void setDataExecucao(java.util.Date dataExecucao) {
this.dataExecucao = dataExecucao;
}
}
| true |
44a9f5825b8d2dc1ece199d800ec94e74671fe59 | Java | travel-cloud/Cheddar | /cheddar/cheddar-integration-mocks/src/test/java/com/clicktravel/infrastructure/persistence/inmemory/filestore/InMemoryInternetFileStoreTest.java | UTF-8 | 2,541 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 Click Travel Ltd
*
* 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.clicktravel.infrastructure.persistence.inmemory.filestore;
import static com.clicktravel.infrastructure.persistence.inmemory.filestore.RandomFileStoreHelper.randomFileItem;
import static com.clicktravel.infrastructure.persistence.inmemory.filestore.RandomFileStoreHelper.randomFilePath;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.net.URL;
import org.junit.Test;
import com.clicktravel.cheddar.infrastructure.persistence.database.exception.NonExistentItemException;
import com.clicktravel.cheddar.infrastructure.persistence.filestore.FileItem;
import com.clicktravel.cheddar.infrastructure.persistence.filestore.FilePath;
public class InMemoryInternetFileStoreTest {
@Test
public void shouldGeneratePublicUrl_withFilePath() throws Exception {
// Given
final FilePath filePath = randomFilePath();
final FileItem expectedFileItem = randomFileItem();
final InMemoryInternetFileStore fileStore = new InMemoryInternetFileStore();
fileStore.write(filePath, expectedFileItem);
// When
final URL publicUrl = fileStore.publicUrlForFilePath(filePath);
// Then
assertThat(publicUrl,
is(new URL("http://" + filePath.directory() + "localhost/" + expectedFileItem.filename())));
}
@Test
public void shouldNotGeneratePublicUrl_withIncorrectFilePath() throws Exception {
// Given
final FilePath filePath = randomFilePath();
final InMemoryInternetFileStore fileStore = new InMemoryInternetFileStore();
// When
NonExistentItemException actualException = null;
try {
fileStore.publicUrlForFilePath(filePath);
} catch (final NonExistentItemException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
}
| true |
c3f57bd1372afc5d536471055d12e1381b0b2286 | Java | DuyTran1811/Homework-Java-Basic | /src/BaiTap1String/BT3.java | UTF-8 | 309 | 2.625 | 3 | [] | no_license | package BaiTap1String;
import java.util.Scanner;
public class BT3 {
public static void main(String[] args) {
Scanner sw = new Scanner(System.in);
System.out.println("Nhap vao 1 chuoi");
String str = sw.nextLine();
System.out.println(str.replaceAll("\\s+"," * "));
}
}
| true |
2b7d90445132a627017ad514b8200e9113dfb05b | Java | lrmymycn/befun | /j2ee/befun-dao/src/main/java/com/befun/dao/profile/impl/DepartmentDaoImpl.java | UTF-8 | 349 | 1.664063 | 2 | [] | no_license | package com.befun.dao.profile.impl;
import org.springframework.stereotype.Repository;
import com.befun.dao.BaseHibernateDao;
import com.befun.dao.profile.DepartmentDao;
import com.befun.domain.profile.Department;
@Repository("DepartmentDao")
public class DepartmentDaoImpl extends BaseHibernateDao<Department, Long> implements DepartmentDao {
}
| true |
e68d28fbd4b9333322638497d287f05623bfcd0f | Java | reymont/DPModel | /src/dp/work9/Movie.java | UTF-8 | 293 | 2.828125 | 3 | [] | no_license | package work9;
class Movie {
private static Movie s = null;
private Movie(){}
public static Movie getInstance(Boolean isSee){
if(isSee){
if( s == null){
synchronized(Movie.class){
if( s == null ){
s = new Movie();
}
}
}
}
return s;
}
} | true |
022c1182fbec3ce6c6ce109659492a666625273c | Java | KavvamMunireddy/SBME | /src/com/muni/reddy/AlphabeticPyramid.java | UTF-8 | 530 | 3.515625 | 4 | [] | no_license | package com.muni.reddy;
import java.util.Scanner;
public class AlphabeticPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the uppercase character you want to print in last row:: ");
String rows = scanner.next();
char alphabet = 'A';
char alphabet1 = rows.charAt(0);
for (int i = 1; i <= (alphabet1 - 'A' + 1); i++) {
for (int j = 1; j <= i; j++) {
System.out.print(alphabet + " ");
}
++alphabet;
System.out.print("\n");
}
}
}
| true |
4bb2476b87f1ca25c259b265d722bb3f427f0b08 | Java | SebastianWeetabix/fred-maven | /src/main/java/freenet/clients/http/StatisticsToadlet.java | UTF-8 | 80,913 | 1.78125 | 2 | [] | no_license | package freenet.clients.http;
import java.io.IOException;
import java.net.URI;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import freenet.client.HighLevelSimpleClient;
import freenet.config.SubConfig;
import freenet.io.comm.IncomingPacketFilterImpl;
import freenet.io.xfer.BlockReceiver;
import freenet.io.xfer.BlockTransmitter;
import freenet.l10n.NodeL10n;
import freenet.node.FNPPacketMangler;
import freenet.node.Location;
import freenet.node.Node;
import freenet.node.NodeClientCore;
import freenet.node.NodeStarter;
import freenet.node.NodeStats;
import freenet.node.OpennetManager;
import freenet.node.PeerManager;
import freenet.node.PeerNodeStatus;
import freenet.node.RequestStarterGroup;
import freenet.node.Version;
import freenet.node.stats.DataStoreInstanceType;
import freenet.node.stats.DataStoreStats;
import freenet.node.stats.StatsNotAvailableException;
import freenet.node.stats.StoreAccessStats;
import freenet.support.BandwidthStatsContainer;
import freenet.support.HTMLNode;
import freenet.support.SizeUtil;
import freenet.support.TimeUtil;
import freenet.support.api.HTTPRequest;
import freenet.support.io.NativeThread;
public class StatisticsToadlet extends Toadlet {
static final NumberFormat thousandPoint = NumberFormat.getInstance();
private static class STMessageCount {
public String messageName;
public int messageCount;
STMessageCount( String messageName, int messageCount ) {
this.messageName = messageName;
this.messageCount = messageCount;
}
}
private final Node node;
private final NodeClientCore core;
private final NodeStats stats;
private final PeerManager peers;
private final DecimalFormat fix1p1 = new DecimalFormat("0.0");
private final DecimalFormat fix1p2 = new DecimalFormat("0.00");
private final DecimalFormat fix1p4 = new DecimalFormat("0.0000");
private final DecimalFormat fix1p6sci = new DecimalFormat("0.######E0");
private final DecimalFormat fix3p1pct = new DecimalFormat("##0.0%");
private final DecimalFormat fix3p1US = new DecimalFormat("##0.0", new DecimalFormatSymbols(Locale.US));
private final DecimalFormat fix3pctUS = new DecimalFormat("##0%", new DecimalFormatSymbols(Locale.US));
private final DecimalFormat fix6p6 = new DecimalFormat("#####0.0#####");
protected StatisticsToadlet(Node n, NodeClientCore core, HighLevelSimpleClient client) {
super(client);
this.node = n;
this.core = core;
stats = node.nodeStats;
peers = node.peers;
}
/**
* Counts the peers in <code>peerNodes</code> that have the specified
* status.
* @param peerNodeStatuses The peer nodes' statuses
* @param status The status to count
* @return The number of peers that have the specified status.
*/
private int getPeerStatusCount(PeerNodeStatus[] peerNodeStatuses, int status) {
int count = 0;
for (int peerIndex = 0, peerCount = peerNodeStatuses.length; peerIndex < peerCount; peerIndex++) {
if(!peerNodeStatuses[peerIndex].recordStatus())
continue;
if (peerNodeStatuses[peerIndex].getStatusValue() == status) {
count++;
}
}
return count;
}
private int getCountSeedServers(PeerNodeStatus[] peerNodeStatuses) {
int count = 0;
for(int peerIndex = 0; peerIndex < peerNodeStatuses.length; peerIndex++) {
if(peerNodeStatuses[peerIndex].isSeedServer()) count++;
}
return count;
}
private int getCountSeedClients(PeerNodeStatus[] peerNodeStatuses) {
int count = 0;
for(int peerIndex = 0; peerIndex < peerNodeStatuses.length; peerIndex++) {
if(peerNodeStatuses[peerIndex].isSeedClient()) count++;
}
return count;
}
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException {
if(!ctx.isAllowedFullAccess()) {
super.sendErrorPage(ctx, 403, NodeL10n.getBase().getString("Toadlet.unauthorizedTitle"), NodeL10n.getBase().getString("Toadlet.unauthorized"));
return;
}
final SubConfig nodeConfig = node.config.get("node");
node.clientCore.bandwidthStatsPutter.updateData();
HTMLNode pageNode;
// Synchronize to avoid problems with DecimalFormat.
synchronized(this) {
/* gather connection statistics */
PeerNodeStatus[] peerNodeStatuses = peers.getPeerNodeStatuses(true);
Arrays.sort(peerNodeStatuses, new Comparator<PeerNodeStatus>() {
public int compare(PeerNodeStatus firstNode, PeerNodeStatus secondNode) {
int statusDifference = firstNode.getStatusValue() - secondNode.getStatusValue();
if (statusDifference != 0) {
return statusDifference;
}
return 0;
}
});
int numberOfConnected = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_CONNECTED);
int numberOfRoutingBackedOff = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_ROUTING_BACKED_OFF);
int numberOfTooNew = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_TOO_NEW);
int numberOfTooOld = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_TOO_OLD);
int numberOfDisconnected = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_DISCONNECTED);
int numberOfNeverConnected = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_NEVER_CONNECTED);
int numberOfDisabled = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_DISABLED);
int numberOfBursting = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_BURSTING);
int numberOfListening = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_LISTENING);
int numberOfListenOnly = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_LISTEN_ONLY);
int numberOfSeedServers = getCountSeedServers(peerNodeStatuses);
int numberOfSeedClients = getCountSeedClients(peerNodeStatuses);
int numberOfRoutingDisabled = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_ROUTING_DISABLED);
int numberOfClockProblem = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_CLOCK_PROBLEM);
int numberOfConnError = getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_CONN_ERROR);
int numberOfDisconnecting = PeerNodeStatus.getPeerStatusCount(peerNodeStatuses, PeerManager.PEER_NODE_STATUS_DISCONNECTING);
final int mode = ctx.getPageMaker().parseMode(request, container);
PageNode page = ctx.getPageMaker().getPageNode(l10n("fullTitle", new String[] { "name" }, new String[] { node.getMyName() }), ctx);
pageNode = page.outer;
HTMLNode contentNode = page.content;
// FIXME! We need some nice images
final long now = System.currentTimeMillis();
double myLocation = node.getLocation();
final long nodeUptimeSeconds = (now - node.startupTime) / 1000;
if(ctx.isAllowedFullAccess())
contentNode.addChild(core.alerts.createSummary());
double swaps = node.getSwaps();
double noSwaps = node.getNoSwaps();
HTMLNode overviewTable = contentNode.addChild("table", "class", "column");
HTMLNode overviewTableRow = overviewTable.addChild("tr");
HTMLNode nextTableCell = overviewTableRow.addChild("td", "class", "first");
// node version information box
HTMLNode versionInfobox = nextTableCell.addChild("div", "class", "infobox");
drawNodeVersionBox(versionInfobox);
// jvm stats box
HTMLNode jvmStatsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawJVMStatsBox(jvmStatsInfobox);
// Statistic gathering box
HTMLNode statGatheringContent = ctx.getPageMaker().getInfobox("#", l10n("statisticGatheringTitle"), nextTableCell, "statistics-generating", true);
// Generate a Thread-Dump
if(node.isUsingWrapper()){
HTMLNode threadDumpForm = ctx.addFormChild(statGatheringContent, "/", "threadDumpForm");
threadDumpForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "getThreadDump", l10n("threadDumpButton")});
}
// Get logs
HTMLNode logsList = statGatheringContent.addChild("ul");
if(nodeConfig.config.get("logger").getBoolean("enabled"))
logsList.addChild("li").addChild("a", new String[]{ "href", "target"}, new String[]{ "/?latestlog", "_blank"}, l10n("getLogs"));
logsList.addChild("li").addChild("a", "href", TranslationToadlet.TOADLET_URL+"?getOverrideTranlationFile").addChild("#", NodeL10n.getBase().getString("TranslationToadlet.downloadTranslationsFile"));
if(mode >= PageMaker.MODE_ADVANCED) {
// store size box
//HTMLNode storeSizeInfobox = nextTableCell.addChild("div", "class", "infobox");
HTMLNode storeSizeInfobox = contentNode.addChild("div","class", "infobox");
drawStoreSizeBox(storeSizeInfobox, myLocation, nodeUptimeSeconds);
if(numberOfConnected + numberOfRoutingBackedOff > 0) {
HTMLNode loadStatsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawLoadBalancingBox(loadStatsInfobox, false);
loadStatsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawLoadBalancingBox(loadStatsInfobox, true);
// Psuccess box
HTMLNode successRateBox = nextTableCell.addChild("div", "class", "infobox");
successRateBox.addChild("div", "class", "infobox-header", l10n("successRate"));
HTMLNode successRateContent = successRateBox.addChild("div", "class", "infobox-content");
stats.fillSuccessRateBox(successRateContent);
HTMLNode timeDetailBox = nextTableCell.addChild("div", "class", "infobox");
timeDetailBox.addChild("div", "class", "infobox-header", l10n("chkDetailTiming"));
HTMLNode timingsContent = timeDetailBox.addChild("div", "class", "infobox-content");
stats.fillDetailedTimingsBox(timingsContent);
HTMLNode byHTLBox = nextTableCell.addChild("div", "class", "infobox");
byHTLBox.addChild("div", "class", "infobox-header", l10n("successByHTLBulk"));
HTMLNode byHTLContent = byHTLBox.addChild("div", "class", "infobox-content");
stats.fillRemoteRequestHTLsBox(byHTLContent, false);
byHTLBox = nextTableCell.addChild("div", "class", "infobox");
byHTLBox.addChild("div", "class", "infobox-header", l10n("successByHTLRT"));
byHTLContent = byHTLBox.addChild("div", "class", "infobox-content");
stats.fillRemoteRequestHTLsBox(byHTLContent, true);
}
}
if(mode >= PageMaker.MODE_ADVANCED || numberOfConnected + numberOfRoutingBackedOff > 0) {
// Activity box
nextTableCell = overviewTableRow.addChild("td", "class", "last");
HTMLNode activityInfobox = nextTableCell.addChild("div", "class", "infobox");
drawActivityBox(activityInfobox, mode >= PageMaker.MODE_ADVANCED);
/* node status overview box */
if(mode >= PageMaker.MODE_ADVANCED) {
HTMLNode overviewInfobox = nextTableCell.addChild("div", "class", "infobox");
drawOverviewBox(overviewInfobox, nodeUptimeSeconds, node.clientCore.bandwidthStatsPutter.getLatestUptimeData().totalUptime, now, swaps, noSwaps);
}
// Peer statistics box
HTMLNode peerStatsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawPeerStatsBox(peerStatsInfobox, mode >= PageMaker.MODE_ADVANCED, numberOfConnected, numberOfRoutingBackedOff,
numberOfTooNew, numberOfTooOld, numberOfDisconnected, numberOfNeverConnected, numberOfDisabled,
numberOfBursting, numberOfListening, numberOfListenOnly, numberOfSeedServers, numberOfSeedClients,
numberOfRoutingDisabled, numberOfClockProblem, numberOfConnError, numberOfDisconnecting, node);
// Bandwidth box
HTMLNode bandwidthInfobox = nextTableCell.addChild("div", "class", "infobox");
drawBandwidthBox(bandwidthInfobox, nodeUptimeSeconds, mode >= PageMaker.MODE_ADVANCED);
}
if(mode >= PageMaker.MODE_ADVANCED) {
// Peer routing backoff reason box
HTMLNode backoffReasonInfobox = nextTableCell.addChild("div", "class", "infobox");
backoffReasonInfobox.addChild("div", "class", "infobox-header", "Peer Backoff");
HTMLNode backoffReasonContent = backoffReasonInfobox.addChild("div", "class", "infobox-content");
HTMLNode curBackoffReasonInfobox = backoffReasonContent.addChild("div", "class", "infobox");
curBackoffReasonInfobox.addChild("div", "class", "infobox-header", "Current backoff reasons (bulk)");
HTMLNode curBackoffReasonContent = curBackoffReasonInfobox.addChild("div", "class", "infobox-content");
String [] routingBackoffReasons = peers.getPeerNodeRoutingBackoffReasons(false);
if(routingBackoffReasons.length == 0) {
curBackoffReasonContent.addChild("#", l10n("notBackedOff"));
} else {
HTMLNode reasonList = curBackoffReasonContent.addChild("ul");
for(int i=0;i<routingBackoffReasons.length;i++) {
int reasonCount = peers.getPeerNodeRoutingBackoffReasonSize(routingBackoffReasons[i], false);
if(reasonCount > 0) {
reasonList.addChild("li", routingBackoffReasons[i] + '\u00a0' + reasonCount);
}
}
}
curBackoffReasonInfobox = backoffReasonContent.addChild("div", "class", "infobox");
curBackoffReasonInfobox.addChild("div", "class", "infobox-header", "Current backoff reasons (realtime)");
curBackoffReasonContent = curBackoffReasonInfobox.addChild("div", "class", "infobox-content");
routingBackoffReasons = peers.getPeerNodeRoutingBackoffReasons(true);
if(routingBackoffReasons.length == 0) {
curBackoffReasonContent.addChild("#", l10n("notBackedOff"));
} else {
HTMLNode reasonList = curBackoffReasonContent.addChild("ul");
for(int i=0;i<routingBackoffReasons.length;i++) {
int reasonCount = peers.getPeerNodeRoutingBackoffReasonSize(routingBackoffReasons[i], true);
if(reasonCount > 0) {
reasonList.addChild("li", routingBackoffReasons[i] + '\u00a0' + reasonCount);
}
}
}
// Per backoff-type count and avg backoff lengths
// Routing Backoff bulk
HTMLNode routingBackoffStatisticsTableBulk = backoffReasonInfobox.addChild("table", "border", "0");
HTMLNode row = routingBackoffStatisticsTableBulk.addChild("tr");
row.addChild("th", l10n("routingBackoffReason") + " (bulk)");
row.addChild("th", l10n("count"));
row.addChild("th", l10n("avgTime"));
row.addChild("th", l10n("totalTime"));
for(NodeStats.TimedStats entry : stats.getRoutingBackoffStatistics(false)) {
row = routingBackoffStatisticsTableBulk.addChild("tr");
row.addChild("td", entry.keyStr);
row.addChild("td", Long.toString(entry.count));
row.addChild("td", TimeUtil.formatTime(entry.avgTime, 2, true));
row.addChild("td", TimeUtil.formatTime(entry.totalTime, 2, true));
}
// Routing Backoff realtime
HTMLNode routingBackoffStatisticsTableRT = backoffReasonInfobox.addChild("table", "border", "0");
row = routingBackoffStatisticsTableRT.addChild("tr");
row.addChild("th", l10n("routingBackoffReason") + " (realtime)");
row.addChild("th", l10n("count"));
row.addChild("th", l10n("avgTime"));
row.addChild("th", l10n("totalTime"));
for(NodeStats.TimedStats entry : stats.getRoutingBackoffStatistics(true)) {
row = routingBackoffStatisticsTableRT.addChild("tr");
row.addChild("td", entry.keyStr);
row.addChild("td", Long.toString(entry.count));
row.addChild("td", TimeUtil.formatTime(entry.avgTime, 2, true));
row.addChild("td", TimeUtil.formatTime(entry.totalTime, 2, true));
}
// Transfer Backoff bulk
HTMLNode transferBackoffStatisticsTableBulk = backoffReasonInfobox.addChild("table", "border", "0");
row = transferBackoffStatisticsTableBulk.addChild("tr");
row.addChild("th", l10n("transferBackoffReason") + " (bulk)");
row.addChild("th", l10n("count"));
row.addChild("th", l10n("avgTime"));
row.addChild("th", l10n("totalTime"));
for(NodeStats.TimedStats entry : stats.getTransferBackoffStatistics(false)) {
row = transferBackoffStatisticsTableBulk.addChild("tr");
row.addChild("td", entry.keyStr);
row.addChild("td", Long.toString(entry.count));
row.addChild("td", TimeUtil.formatTime(entry.avgTime, 2, true));
row.addChild("td", TimeUtil.formatTime(entry.totalTime, 2, true));
}
// Transfer Backoff realtime
HTMLNode transferBackoffStatisticsTableRT = backoffReasonInfobox.addChild("table", "border", "0");
row = transferBackoffStatisticsTableRT.addChild("tr");
row.addChild("th", l10n("transferBackoffReason") + " (realtime)");
row.addChild("th", l10n("count"));
row.addChild("th", l10n("avgTime"));
row.addChild("th", l10n("totalTime"));
for(NodeStats.TimedStats entry : stats.getTransferBackoffStatistics(true)) {
row = transferBackoffStatisticsTableRT.addChild("tr");
row.addChild("td", entry.keyStr);
row.addChild("td", Long.toString(entry.count));
row.addChild("td", TimeUtil.formatTime(entry.avgTime, 2, true));
row.addChild("td", TimeUtil.formatTime(entry.totalTime, 2, true));
}
//Swap statistics box
HTMLNode locationSwapInfobox = nextTableCell.addChild("div", "class", "infobox");
drawSwapStatsBox(locationSwapInfobox, myLocation, nodeUptimeSeconds, swaps, noSwaps);
// unclaimedFIFOMessageCounts box
HTMLNode unclaimedFIFOMessageCountsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawUnclaimedFIFOMessageCountsBox(unclaimedFIFOMessageCountsInfobox);
HTMLNode threadsPriorityInfobox = nextTableCell.addChild("div", "class", "infobox");
drawThreadPriorityStatsBox(threadsPriorityInfobox);
nextTableCell = overviewTableRow.addChild("td");
// thread usage box
HTMLNode threadUsageInfobox = nextTableCell.addChild("div", "class", "infobox");
threadUsageInfobox.addChild("div", "class", "infobox-header", "Thread usage");
HTMLNode threadUsageContent = threadUsageInfobox.addChild("div", "class", "infobox-content");
HTMLNode threadUsageList = threadUsageContent.addChild("ul");
getThreadNames(threadUsageList);
// rejection reasons box
drawRejectReasonsBox(nextTableCell, false);
drawRejectReasonsBox(nextTableCell, true);
// database thread jobs box
HTMLNode databaseJobsInfobox = nextTableCell.addChild("div", "class", "infobox");
drawDatabaseJobsBox(databaseJobsInfobox);
OpennetManager om = node.getOpennet();
if(om != null) {
// opennet stats box
drawOpennetStatsBox(nextTableCell.addChild("div", "class", "infobox"), om);
if(node.isSeednode())
drawSeedStatsBox(nextTableCell.addChild("div", "class", "infobox"), om);
}
// peer distribution box
overviewTableRow = overviewTable.addChild("tr");
nextTableCell = overviewTableRow.addChild("td", "class", "first");
HTMLNode peerCircleInfobox = nextTableCell.addChild("div", "class", "infobox");
peerCircleInfobox.addChild("div", "class", "infobox-header", "Peer\u00a0Location\u00a0Distribution (w/pReject)");
HTMLNode peerCircleTable = peerCircleInfobox.addChild("div", "class", "infobox-content").addChild("table");
addPeerCircle(peerCircleTable, peerNodeStatuses, myLocation);
nextTableCell = overviewTableRow.addChild("td");
// node distribution box
HTMLNode nodeCircleInfobox = nextTableCell.addChild("div", "class", "infobox");
nodeCircleInfobox.addChild("div", "class", "infobox-header", "Node\u00a0Location\u00a0Distribution (w/Swap\u00a0Age)");
HTMLNode nodeCircleTable = nodeCircleInfobox.addChild("div", "class", "infobox-content").addChild("table");
addNodeCircle(nodeCircleTable, myLocation);
overviewTableRow = overviewTable.addChild("tr");
nextTableCell = overviewTableRow.addChild("td", "class", "first");
// specialisation box
int[] incomingRequestCountArray = new int[1];
int[] incomingRequestLocation = stats.getIncomingRequestLocation(incomingRequestCountArray);
int incomingRequestsCount = incomingRequestCountArray[0];
if(incomingRequestsCount > 0) {
HTMLNode nodeSpecialisationInfobox = nextTableCell.addChild("div", "class", "infobox");
nodeSpecialisationInfobox.addChild("div", "class", "infobox-header", "Incoming\u00a0Request\u00a0Distribution");
HTMLNode nodeSpecialisationTable = nodeSpecialisationInfobox.addChild("div", "class", "infobox-content").addChild("table");
addSpecialisation(nodeSpecialisationTable, myLocation, incomingRequestsCount, incomingRequestLocation);
}
nextTableCell = overviewTableRow.addChild("td");
int[] outgoingLocalRequestCountArray = new int[1];
int[] outgoingLocalRequestLocation = stats.getOutgoingLocalRequestLocation(outgoingLocalRequestCountArray);
int outgoingLocalRequestsCount = outgoingLocalRequestCountArray[0];
int[] outgoingRequestCountArray = new int[1];
int[] outgoingRequestLocation = stats.getOutgoingRequestLocation(outgoingRequestCountArray);
int outgoingRequestsCount = outgoingRequestCountArray[0];
if(outgoingLocalRequestsCount > 0 && outgoingRequestsCount > 0) {
HTMLNode nodeSpecialisationInfobox = nextTableCell.addChild("div", "class", "infobox");
nodeSpecialisationInfobox.addChild("div", "class", "infobox-header", "Outgoing\u00a0Request\u00a0Distribution");
HTMLNode nodeSpecialisationTable = nodeSpecialisationInfobox.addChild("div", "class", "infobox-content").addChild("table");
addCombinedSpecialisation(nodeSpecialisationTable, myLocation, outgoingLocalRequestsCount, outgoingLocalRequestLocation, outgoingRequestsCount, outgoingRequestLocation);
}
overviewTableRow = overviewTable.addChild("tr");
nextTableCell = overviewTableRow.addChild("td", "class", "first");
// success rate per location
int[] locationSuccessRatesArray = stats.chkSuccessRatesByLocation.getPercentageArray(1000);
{
HTMLNode nodeSpecialisationInfobox = nextTableCell.addChild("div", "class", "infobox");
nodeSpecialisationInfobox.addChild("div", "class", "infobox-header", "Local\u00a0CHK\u00a0Success\u00a0Rates\u00a0By\u00a0Location");
HTMLNode nodeSpecialisationTable = nodeSpecialisationInfobox.addChild("div", "class", "infobox-content").addChild("table");
addSpecialisation(nodeSpecialisationTable, myLocation, 1000, locationSuccessRatesArray);
}
}
}
this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
}
private void drawLoadBalancingBox(HTMLNode loadStatsInfobox, boolean realTime) {
// Load balancing box
// Include overall window, and RTTs for each
loadStatsInfobox.addChild("div", "class", "infobox-header", "Load limiting "+(realTime ? "RealTime" : "Bulk"));
HTMLNode loadStatsContent = loadStatsInfobox.addChild("div", "class", "infobox-content");
RequestStarterGroup starters = core.requestStarters;
double window = starters.getWindow(realTime);
double realWindow = starters.getRealWindow(realTime);
HTMLNode loadStatsList = loadStatsContent.addChild("ul");
loadStatsList.addChild("li", l10n("globalWindow")+": "+window);
loadStatsList.addChild("li", l10n("realGlobalWindow")+": "+realWindow);
loadStatsList.addChild("li", starters.statsPageLine(false, false, realTime));
loadStatsList.addChild("li", starters.statsPageLine(true, false, realTime));
loadStatsList.addChild("li", starters.statsPageLine(false, true, realTime));
loadStatsList.addChild("li", starters.statsPageLine(true, true, realTime));
loadStatsList.addChild("li", starters.diagnosticThrottlesLine(false));
loadStatsList.addChild("li", starters.diagnosticThrottlesLine(true));
}
private void drawRejectReasonsBox(HTMLNode nextTableCell, boolean local) {
HTMLNode rejectReasonsTable = new HTMLNode("table");
NodeStats stats = node.nodeStats;
boolean success = local ? stats.getLocalRejectReasonsTable(rejectReasonsTable) :
stats.getRejectReasonsTable(rejectReasonsTable);
if(!success)
return;
HTMLNode rejectReasonsInfobox = nextTableCell.addChild("div", "class", "infobox");
rejectReasonsInfobox.addChild("div", "class", "infobox-header", (local ? "Local " : "")+"Preemptive Rejection Reasons");
rejectReasonsInfobox.addChild("div", "class", "infobox-content").addChild(rejectReasonsTable);
}
private void drawNodeVersionBox(HTMLNode versionInfobox) {
versionInfobox.addChild("div", "class", "infobox-header", l10n("versionTitle"));
HTMLNode versionInfoboxContent = versionInfobox.addChild("div", "class", "infobox-content");
HTMLNode versionInfoboxList = versionInfoboxContent.addChild("ul");
versionInfoboxList.addChild("li", NodeL10n.getBase().getString("WelcomeToadlet.version", new String[] { "fullVersion", "build", "rev" },
new String[] { Version.publicVersion(), Integer.toString(Version.buildNumber()), Version.cvsRevision() }));
if(NodeStarter.extBuildNumber < NodeStarter.RECOMMENDED_EXT_BUILD_NUMBER)
versionInfoboxList.addChild("li", NodeL10n.getBase().getString("WelcomeToadlet.extVersionWithRecommended",
new String[] { "build", "recbuild", "rev" },
new String[] { Integer.toString(NodeStarter.extBuildNumber), Integer.toString(NodeStarter.RECOMMENDED_EXT_BUILD_NUMBER), NodeStarter.extRevisionNumber }));
else
versionInfoboxList.addChild("li", NodeL10n.getBase().getString("WelcomeToadlet.extVersion", new String[] { "build", "rev" },
new String[] { Integer.toString(NodeStarter.extBuildNumber), NodeStarter.extRevisionNumber }));
}
private void drawJVMStatsBox(HTMLNode jvmStatsInfobox) {
jvmStatsInfobox.addChild("div", "class", "infobox-header", l10n("jvmInfoTitle"));
HTMLNode jvmStatsInfoboxContent = jvmStatsInfobox.addChild("div", "class", "infobox-content");
HTMLNode jvmStatsList = jvmStatsInfoboxContent.addChild("ul");
Runtime rt = Runtime.getRuntime();
long freeMemory = rt.freeMemory();
long totalMemory = rt.totalMemory();
long maxMemory = rt.maxMemory();
long usedJavaMem = totalMemory - freeMemory;
long allocatedJavaMem = totalMemory;
long maxJavaMem = maxMemory;
int availableCpus = rt.availableProcessors();
int threadCount = stats.getActiveThreadCount();
jvmStatsList.addChild("li", l10n("usedMemory", "memory", SizeUtil.formatSize(usedJavaMem, true)));
jvmStatsList.addChild("li", l10n("allocMemory", "memory", SizeUtil.formatSize(allocatedJavaMem, true)));
jvmStatsList.addChild("li", l10n("maxMemory", "memory", SizeUtil.formatSize(maxJavaMem, true)));
jvmStatsList.addChild("li", l10n("threads", new String[] { "running", "max" },
new String[] { thousandPoint.format(threadCount), Integer.toString(stats.getThreadLimit()) }));
jvmStatsList.addChild("li", l10n("cpus", "count", Integer.toString(availableCpus)));
jvmStatsList.addChild("li", l10n("javaVersion", "version", System.getProperty("java.version")));
jvmStatsList.addChild("li", l10n("jvmVendor", "vendor", System.getProperty("java.vendor")));
jvmStatsList.addChild("li", l10n("jvmName", "name", System.getProperty("java.vm.name")));
jvmStatsList.addChild("li", l10n("jvmVersion", "version", System.getProperty("java.vm.version")));
jvmStatsList.addChild("li", l10n("osName", "name", System.getProperty("os.name")));
jvmStatsList.addChild("li", l10n("osVersion", "version", System.getProperty("os.version")));
jvmStatsList.addChild("li", l10n("osArch", "arch", System.getProperty("os.arch")));
}
private void drawThreadPriorityStatsBox(HTMLNode node) {
node.addChild("div", "class", "infobox-header", l10n("threadsByPriority"));
HTMLNode threadsInfoboxContent = node.addChild("div", "class", "infobox-content");
int[] activeThreadsByPriority = stats.getActiveThreadsByPriority();
int[] waitingThreadsByPriority = stats.getWaitingThreadsByPriority();
HTMLNode threadsByPriorityTable = threadsInfoboxContent.addChild("table", "border", "0");
HTMLNode row = threadsByPriorityTable.addChild("tr");
row.addChild("th", l10n("priority"));
row.addChild("th", l10n("running"));
row.addChild("th", l10n("waiting"));
for(int i=0; i<activeThreadsByPriority.length; i++) {
row = threadsByPriorityTable.addChild("tr");
row.addChild("td", String.valueOf(i+1));
row.addChild("td", String.valueOf(activeThreadsByPriority[i]));
row.addChild("td", String.valueOf(waitingThreadsByPriority[i]));
}
}
private void drawDatabaseJobsBox(HTMLNode node) {
// Job count by priority
node.addChild("div", "class", "infobox-header", l10n("databaseJobsByPriority"));
HTMLNode threadsInfoboxContent = node.addChild("div", "class", "infobox-content");
int[] jobsByPriority = core.clientDatabaseExecutor.getQueuedJobsCountByPriority();
HTMLNode threadsByPriorityTable = threadsInfoboxContent.addChild("table", "border", "0");
HTMLNode row = threadsByPriorityTable.addChild("tr");
row.addChild("th", l10n("priority"));
row.addChild("th", l10n("waiting"));
for(int i=0; i<jobsByPriority.length; i++) {
row = threadsByPriorityTable.addChild("tr");
row.addChild("td", String.valueOf(i));
row.addChild("td", String.valueOf(jobsByPriority[i]));
}
// Per job-type execution count and avg execution time
HTMLNode executionTimeStatisticsTable = threadsInfoboxContent.addChild("table", "border", "0");
row = executionTimeStatisticsTable .addChild("tr");
row.addChild("th", l10n("jobType"));
row.addChild("th", l10n("count"));
row.addChild("th", l10n("avgTime"));
row.addChild("th", l10n("totalTime"));
for(NodeStats.TimedStats entry : stats.getDatabaseJobExecutionStatistics()) {
row = executionTimeStatisticsTable.addChild("tr");
row.addChild("td", entry.keyStr);
row.addChild("td", Long.toString(entry.count));
row.addChild("td", TimeUtil.formatTime(entry.avgTime, 2, true));
row.addChild("td", TimeUtil.formatTime(entry.totalTime, 2, true));
}
HTMLNode jobQueueStatistics = threadsInfoboxContent.addChild("table", "border", "0");
row = jobQueueStatistics .addChild("tr");
row.addChild("th", l10n("queuedCount"));
row.addChild("th", l10n("jobType"));
stats.getDatabaseJobQueueStatistics().toTableRows(jobQueueStatistics);
}
private void drawOpennetStatsBox(HTMLNode box, OpennetManager om) {
box.addChild("div", "class", "infobox-header", l10n("opennetStats"));
HTMLNode opennetStatsContent = box.addChild("div", "class", "infobox-content");
om.drawOpennetStatsBox(opennetStatsContent);
}
private void drawSeedStatsBox(HTMLNode box, OpennetManager om) {
box.addChild("div", "class", "infobox-header", l10n("seedStats"));
HTMLNode opennetStatsContent = box.addChild("div", "class", "infobox-content");
om.drawSeedStatsBox(opennetStatsContent);
}
private void drawStoreSizeBox(HTMLNode storeSizeInfobox, double loc, long nodeUptimeSeconds) {
storeSizeInfobox.addChild("div", "class", "infobox-header", l10n("datastore"));
HTMLNode storeSizeInfoboxContent = storeSizeInfobox.addChild("div", "class", "infobox-content");
HTMLNode scrollDiv = storeSizeInfoboxContent.addChild("div", "style", "overflow:scr");
HTMLNode storeSizeTable = scrollDiv.addChild("table", "border", "0");
HTMLNode row = storeSizeTable.addChild("tr");
//FIXME - Non-breaking space? "Stat-name"?
row.addChild("th", "");
row.addChild("th", l10n("keys"));
row.addChild("th", l10n("capacity"));
row.addChild("th", l10n("datasize"));
row.addChild("th", l10n("utilization"));
row.addChild("th", l10n("readRequests"));
row.addChild("th", l10n("successfulReads"));
row.addChild("th", l10n("successRate"));
row.addChild("th", l10n("writes"));
row.addChild("th", l10n("accessRate"));
row.addChild("th", l10n("writeRate"));
row.addChild("th", l10n("falsePos"));
row.addChild("th", l10n("avgLocation"));
row.addChild("th", l10n("avgSuccessLoc"));
row.addChild("th", l10n("furthestSuccess"));
row.addChild("th", l10n("avgDist"));
row.addChild("th", l10n("distanceStats"));
Map<DataStoreInstanceType, DataStoreStats> storeStats = node.getDataStoreStats();
for (Map.Entry<DataStoreInstanceType, DataStoreStats> entry : storeStats.entrySet()) {
DataStoreInstanceType instance = entry.getKey();
DataStoreStats stats = entry.getValue();
StoreAccessStats sessionAccess = stats.getSessionAccessStats();
StoreAccessStats totalAccess;
long totalUptimeSeconds = 0;
try {
totalAccess = stats.getTotalAccessStats();
// FIXME this is not necessarily the same as the datastore's uptime if we've switched.
// Ideally we'd track uptime there too.
totalUptimeSeconds =
node.clientCore.bandwidthStatsPutter.getLatestUptimeData().totalUptime;
} catch (StatsNotAvailableException e) {
totalAccess = null;
}
row = storeSizeTable.addChild("tr");
row.addChild("th", l10n(instance.store.name()) + "\n" + " (" + l10n(instance.key.name()) + ")");
row.addChild("td", thousandPoint.format(stats.keys()));
row.addChild("td", thousandPoint.format(stats.capacity()));
row.addChild("td", SizeUtil.formatSize(stats.dataSize()));
row.addChild("td", fix3p1pct.format(stats.utilization()));
row.addChild("td", thousandPoint.format(sessionAccess.readRequests()) +
(totalAccess == null ? "" : (" ("+thousandPoint.format(totalAccess.readRequests())+")")));
row.addChild("td", thousandPoint.format(sessionAccess.successfulReads()) +
(totalAccess == null ? "" : (" ("+thousandPoint.format(totalAccess.successfulReads())+")")));
try {
String rate = fix1p4.format(sessionAccess.successRate()) + "%";
if(totalAccess != null) {
try {
rate += " (" + fix1p4.format(totalAccess.successRate()) + "%)";
} catch (StatsNotAvailableException e) {
// Ignore
}
}
row.addChild("td", rate);
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
row.addChild("td", thousandPoint.format(sessionAccess.writes()) +
(totalAccess == null ? "" : (" ("+thousandPoint.format(totalAccess.writes())+")")));
String access = fix1p2.format(sessionAccess.accessRate(nodeUptimeSeconds)) + " /s";
if(totalAccess != null)
access += " (" + fix1p2.format(totalAccess.accessRate(totalUptimeSeconds)) + " /s)";
row.addChild("td", access);
access = fix1p2.format(sessionAccess.writeRate(nodeUptimeSeconds)) + " /s)";
if(totalAccess != null)
access += " (" + fix1p2.format(totalAccess.writeRate(totalUptimeSeconds)) + " /s)";
row.addChild("td", access);
row.addChild("td", thousandPoint.format(sessionAccess.falsePos()) +
(totalAccess == null ? "" : (" ("+thousandPoint.format(totalAccess.falsePos())+")")));
try {
row.addChild("td", fix1p4.format(stats.avgLocation()));
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
try {
row.addChild("td", fix1p4.format(stats.avgSuccess()));
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
try {
row.addChild("td", fix1p4.format(stats.furthestSuccess()));
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
try {
row.addChild("td", fix1p4.format(stats.avgDist()));
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
try {
row.addChild("td", fix3p1pct.format(stats.distanceStats()));
} catch (StatsNotAvailableException e) {
row.addChild("td", "N/A");
}
}
}
private void drawUnclaimedFIFOMessageCountsBox(HTMLNode unclaimedFIFOMessageCountsInfobox) {
unclaimedFIFOMessageCountsInfobox.addChild("div", "class", "infobox-header", "unclaimedFIFO Message Counts");
HTMLNode unclaimedFIFOMessageCountsInfoboxContent = unclaimedFIFOMessageCountsInfobox.addChild("div", "class", "infobox-content");
HTMLNode unclaimedFIFOMessageCountsList = unclaimedFIFOMessageCountsInfoboxContent.addChild("ul");
Map<String, Integer> unclaimedFIFOMessageCountsMap = node.getUSM().getUnclaimedFIFOMessageCounts();
STMessageCount[] unclaimedFIFOMessageCountsArray = new STMessageCount[unclaimedFIFOMessageCountsMap.size()];
int i = 0;
int totalCount = 0;
for (Map.Entry<String, Integer> e : unclaimedFIFOMessageCountsMap.entrySet()) {
String messageName = e.getKey();
int messageCount = e.getValue();
totalCount = totalCount + messageCount;
unclaimedFIFOMessageCountsArray[i++] = new STMessageCount( messageName, messageCount );
}
Arrays.sort(unclaimedFIFOMessageCountsArray, new Comparator<STMessageCount>() {
public int compare(STMessageCount firstCount, STMessageCount secondCount) {
return secondCount.messageCount - firstCount.messageCount; // sort in descending order
}
});
for (int countsArrayIndex = 0, countsArrayCount = unclaimedFIFOMessageCountsArray.length; countsArrayIndex < countsArrayCount; countsArrayIndex++) {
STMessageCount messageCountItem = unclaimedFIFOMessageCountsArray[countsArrayIndex];
int thisMessageCount = messageCountItem.messageCount;
double thisMessagePercentOfTotal = ((double) thisMessageCount) / ((double) totalCount);
unclaimedFIFOMessageCountsList.addChild("li", "" + messageCountItem.messageName + ":\u00a0" + thisMessageCount + "\u00a0(" + fix3p1pct.format(thisMessagePercentOfTotal) + ')');
}
unclaimedFIFOMessageCountsList.addChild("li", "Unclaimed Messages Considered:\u00a0" + totalCount);
}
private void drawSwapStatsBox(HTMLNode locationSwapInfobox, double location, long nodeUptimeSeconds, double swaps, double noSwaps) {
locationSwapInfobox.addChild("div", "class", "infobox-header", "Location swaps");
int startedSwaps = node.getStartedSwaps();
int swapsRejectedAlreadyLocked = node.getSwapsRejectedAlreadyLocked();
int swapsRejectedNowhereToGo = node.getSwapsRejectedNowhereToGo();
int swapsRejectedRateLimit = node.getSwapsRejectedRateLimit();
int swapsRejectedRecognizedID = node.getSwapsRejectedRecognizedID();
double locChangeSession = node.getLocationChangeSession();
int averageSwapTime = node.getAverageOutgoingSwapTime();
int sendSwapInterval = node.getSendSwapInterval();
HTMLNode locationSwapInfoboxContent = locationSwapInfobox.addChild("div", "class", "infobox-content");
HTMLNode locationSwapList = locationSwapInfoboxContent.addChild("ul");
locationSwapList.addChild("li", "location:\u00a0" + location);
if (swaps > 0.0) {
locationSwapList.addChild("li", "locChangeSession:\u00a0" + fix1p6sci.format(locChangeSession));
locationSwapList.addChild("li", "locChangePerSwap:\u00a0" + fix1p6sci.format(locChangeSession/swaps));
}
if ((swaps > 0.0) && (nodeUptimeSeconds >= 60)) {
locationSwapList.addChild("li", "locChangePerMinute:\u00a0" + fix1p6sci.format(locChangeSession/(nodeUptimeSeconds/60.0)));
}
if ((swaps > 0.0) && (nodeUptimeSeconds >= 60)) {
locationSwapList.addChild("li", "swapsPerMinute:\u00a0" + fix1p6sci.format(swaps/(nodeUptimeSeconds/60.0)));
}
if ((noSwaps > 0.0) && (nodeUptimeSeconds >= 60)) {
locationSwapList.addChild("li", "noSwapsPerMinute:\u00a0" + fix1p6sci.format(noSwaps/(nodeUptimeSeconds/60.0)));
}
if ((swaps > 0.0) && (noSwaps > 0.0)) {
locationSwapList.addChild("li", "swapsPerNoSwaps:\u00a0" + fix1p6sci.format(swaps/noSwaps));
}
if (swaps > 0.0) {
locationSwapList.addChild("li", "swaps:\u00a0" + (int)swaps);
}
if (noSwaps > 0.0) {
locationSwapList.addChild("li", "noSwaps:\u00a0" + (int)noSwaps);
}
if (startedSwaps > 0) {
locationSwapList.addChild("li", "startedSwaps:\u00a0" + startedSwaps);
}
if (swapsRejectedAlreadyLocked > 0) {
locationSwapList.addChild("li", "swapsRejectedAlreadyLocked:\u00a0" + swapsRejectedAlreadyLocked);
}
if (swapsRejectedNowhereToGo > 0) {
locationSwapList.addChild("li", "swapsRejectedNowhereToGo:\u00a0" + swapsRejectedNowhereToGo);
}
if (swapsRejectedRateLimit > 0) {
locationSwapList.addChild("li", "swapsRejectedRateLimit:\u00a0" + swapsRejectedRateLimit);
}
if (swapsRejectedRecognizedID > 0) {
locationSwapList.addChild("li", "swapsRejectedRecognizedID:\u00a0" + swapsRejectedRecognizedID);
}
locationSwapList.addChild("li", "averageSwapTime:\u00a0" + TimeUtil.formatTime(averageSwapTime, 2, true));
locationSwapList.addChild("li", "sendSwapInterval:\u00a0" + TimeUtil.formatTime(sendSwapInterval, 2, true));
}
protected static void drawPeerStatsBox(HTMLNode peerStatsInfobox, boolean advancedModeEnabled, int numberOfConnected,
int numberOfRoutingBackedOff, int numberOfTooNew, int numberOfTooOld, int numberOfDisconnected,
int numberOfNeverConnected, int numberOfDisabled, int numberOfBursting, int numberOfListening,
int numberOfListenOnly, int numberOfSeedServers, int numberOfSeedClients, int numberOfRoutingDisabled,
int numberOfClockProblem, int numberOfConnError, int numberOfDisconnecting, Node node) {
peerStatsInfobox.addChild("div", "class", "infobox-header", l10n("peerStatsTitle"));
HTMLNode peerStatsContent = peerStatsInfobox.addChild("div", "class", "infobox-content");
HTMLNode peerStatsList = peerStatsContent.addChild("ul");
if (numberOfConnected > 0) {
HTMLNode peerStatsConnectedListItem = peerStatsList.addChild("li").addChild("span");
peerStatsConnectedListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_connected", l10nDark("connected"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("connectedShort"));
peerStatsConnectedListItem.addChild("span", ":\u00a0" + numberOfConnected);
}
if (numberOfRoutingBackedOff > 0) {
HTMLNode peerStatsRoutingBackedOffListItem = peerStatsList.addChild("li").addChild("span");
peerStatsRoutingBackedOffListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_backed_off", l10nDark(advancedModeEnabled ? "backedOff" : "busy"),
"border-bottom: 1px dotted; cursor: help;" }, l10nDark((advancedModeEnabled ? "backedOff" : "busy")+"Short"));
peerStatsRoutingBackedOffListItem.addChild("span", ":\u00a0" + numberOfRoutingBackedOff);
}
if (numberOfTooNew > 0) {
HTMLNode peerStatsTooNewListItem = peerStatsList.addChild("li").addChild("span");
peerStatsTooNewListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_too_new", l10nDark("tooNew"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("tooNewShort"));
peerStatsTooNewListItem.addChild("span", ":\u00a0" + numberOfTooNew);
}
if (numberOfTooOld > 0) {
HTMLNode peerStatsTooOldListItem = peerStatsList.addChild("li").addChild("span");
peerStatsTooOldListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_too_old", l10nDark("tooOld"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("tooOldShort"));
peerStatsTooOldListItem.addChild("span", ":\u00a0" + numberOfTooOld);
}
if (numberOfDisconnected > 0) {
HTMLNode peerStatsDisconnectedListItem = peerStatsList.addChild("li").addChild("span");
peerStatsDisconnectedListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_disconnected", l10nDark("notConnected"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("notConnectedShort"));
peerStatsDisconnectedListItem.addChild("span", ":\u00a0" + numberOfDisconnected);
}
if (numberOfNeverConnected > 0) {
HTMLNode peerStatsNeverConnectedListItem = peerStatsList.addChild("li").addChild("span");
peerStatsNeverConnectedListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_never_connected", l10nDark("neverConnected"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("neverConnectedShort"));
peerStatsNeverConnectedListItem.addChild("span", ":\u00a0" + numberOfNeverConnected);
}
if (numberOfDisabled > 0) {
HTMLNode peerStatsDisabledListItem = peerStatsList.addChild("li").addChild("span");
peerStatsDisabledListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_disabled", l10nDark("disabled"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("disabledShort"));
peerStatsDisabledListItem.addChild("span", ":\u00a0" + numberOfDisabled);
}
if (numberOfBursting > 0) {
HTMLNode peerStatsBurstingListItem = peerStatsList.addChild("li").addChild("span");
peerStatsBurstingListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_bursting", l10nDark("bursting"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("burstingShort"));
peerStatsBurstingListItem.addChild("span", ":\u00a0" + numberOfBursting);
}
if (numberOfListening > 0) {
HTMLNode peerStatsListeningListItem = peerStatsList.addChild("li").addChild("span");
peerStatsListeningListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_listening", l10nDark("listening"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("listeningShort"));
peerStatsListeningListItem.addChild("span", ":\u00a0" + numberOfListening);
}
if (numberOfListenOnly > 0) {
HTMLNode peerStatsListenOnlyListItem = peerStatsList.addChild("li").addChild("span");
peerStatsListenOnlyListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_listen_only", l10nDark("listenOnly"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("listenOnlyShort"));
peerStatsListenOnlyListItem.addChild("span", ":\u00a0" + numberOfListenOnly);
}
if (numberOfClockProblem > 0) {
HTMLNode peerStatsRoutingDisabledListItem = peerStatsList.addChild("li").addChild("span");
peerStatsRoutingDisabledListItem.addChild("span", new String[] { "class", "title", "style" }, new String[] { "peer_clock_problem", l10nDark("clockProblem"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("clockProblemShort"));
peerStatsRoutingDisabledListItem.addChild("span", ":\u00a0" + numberOfClockProblem);
}
if (numberOfConnError > 0) {
HTMLNode peerStatsRoutingDisabledListItem = peerStatsList.addChild("li").addChild("span");
peerStatsRoutingDisabledListItem.addChild("span", new String[] { "class", "title", "style" }, new String[] { "peer_routing_disabled", l10nDark("connError"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("connErrorShort"));
peerStatsRoutingDisabledListItem.addChild("span", ":\u00a0" + numberOfClockProblem);
}
if (numberOfDisconnecting > 0) {
HTMLNode peerStatsListenOnlyListItem = peerStatsList.addChild("li").addChild("span");
peerStatsListenOnlyListItem.addChild("span", new String[] { "class", "title", "style" }, new String[] { "peer_disconnecting", l10nDark("disconnecting"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("disconnectingShort"));
peerStatsListenOnlyListItem.addChild("span", ":\u00a0" + numberOfDisconnecting);
}
if (numberOfSeedServers > 0) {
HTMLNode peerStatsSeedServersListItem = peerStatsList.addChild("li").addChild("span");
peerStatsSeedServersListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_listening" /* FIXME */, l10nDark("seedServers"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("seedServersShort"));
peerStatsSeedServersListItem.addChild("span", ":\u00a0" + numberOfSeedServers);
}
if (numberOfSeedClients > 0) {
HTMLNode peerStatsSeedClientsListItem = peerStatsList.addChild("li").addChild("span");
peerStatsSeedClientsListItem.addChild("span", new String[] { "class", "title", "style" },
new String[] { "peer_listening" /* FIXME */, l10nDark("seedClients"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("seedClientsShort"));
peerStatsSeedClientsListItem.addChild("span", ":\u00a0" + numberOfSeedClients);
}
if (numberOfRoutingDisabled > 0) {
HTMLNode peerStatsRoutingDisabledListItem = peerStatsList.addChild("li").addChild("span");
peerStatsRoutingDisabledListItem.addChild("span", new String[] { "class", "title", "style" }, new String[] { "peer_routing_disabled", l10nDark("routingDisabled"), "border-bottom: 1px dotted; cursor: help;" }, l10nDark("routingDisabledShort"));
peerStatsRoutingDisabledListItem.addChild("span", ":\u00a0" + numberOfRoutingDisabled);
}
OpennetManager om = node.getOpennet();
if(om != null) {
peerStatsList.addChild("li", l10n("maxTotalPeers")+": "+om.getNumberOfConnectedPeersToAimIncludingDarknet());
peerStatsList.addChild("li", l10n("maxOpennetPeers")+": "+om.getNumberOfConnectedPeersToAim());
}
}
private static String l10n(String key) {
return NodeL10n.getBase().getString("StatisticsToadlet."+key);
}
private static String l10nDark(String key) {
return NodeL10n.getBase().getString("DarknetConnectionsToadlet."+key);
}
private static String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("StatisticsToadlet."+key, new String[] { pattern }, new String[] { value });
}
private static String l10n(String key, String[] patterns, String[] values) {
return NodeL10n.getBase().getString("StatisticsToadlet."+key, patterns, values);
}
private void drawActivityBox(HTMLNode activityInfobox, boolean advancedModeEnabled) {
activityInfobox.addChild("div", "class", "infobox-header", l10nDark("activityTitle"));
HTMLNode activityInfoboxContent = activityInfobox.addChild("div", "class", "infobox-content");
HTMLNode activityList = drawActivity(activityInfoboxContent, node);
int numARKFetchers = node.getNumARKFetchers();
if (advancedModeEnabled && activityList != null) {
if (numARKFetchers > 0)
activityList.addChild("li", "ARK\u00a0Fetch\u00a0Requests:\u00a0" + numARKFetchers);
activityList.addChild("li", "BackgroundFetcherByUSKSize:\u00a0" + node.clientCore.uskManager.getBackgroundFetcherByUSKSize());
activityList.addChild("li", "temporaryBackgroundFetchersLRUSize:\u00a0" + node.clientCore.uskManager.getTemporaryBackgroundFetchersLRU());
}
}
static void drawBandwidth(HTMLNode activityList, Node node, long nodeUptimeSeconds, boolean isAdvancedModeEnabled) {
long[] total = node.collector.getTotalIO();
if(total[0] == 0 || total[1] == 0)
return;
long total_output_rate = (total[0]) / nodeUptimeSeconds;
long total_input_rate = (total[1]) / nodeUptimeSeconds;
long totalPayload = node.getTotalPayloadSent();
long total_payload_rate = totalPayload / nodeUptimeSeconds;
if(node.clientCore == null) throw new NullPointerException();
BandwidthStatsContainer stats = node.clientCore.bandwidthStatsPutter.getLatestBWData();
if(stats == null) throw new NullPointerException();
long overall_total_out = stats.totalBytesOut;
long overall_total_in = stats.totalBytesIn;
int percent = (int) (100 * totalPayload / total[0]);
long[] rate = node.nodeStats.getNodeIOStats();
long delta = (rate[5] - rate[2]) / 1000;
if(delta > 0) {
long output_rate = (rate[3] - rate[0]) / delta;
long input_rate = (rate[4] - rate[1]) / delta;
SubConfig nodeConfig = node.config.get("node");
int outputBandwidthLimit = nodeConfig.getInt("outputBandwidthLimit");
int inputBandwidthLimit = nodeConfig.getInt("inputBandwidthLimit");
if(inputBandwidthLimit == -1) {
inputBandwidthLimit = outputBandwidthLimit * 4;
}
activityList.addChild("li", l10n("inputRate", new String[] { "rate", "max" }, new String[] { SizeUtil.formatSize(input_rate, true), SizeUtil.formatSize(inputBandwidthLimit, true) }));
activityList.addChild("li", l10n("outputRate", new String[] { "rate", "max" }, new String[] { SizeUtil.formatSize(output_rate, true), SizeUtil.formatSize(outputBandwidthLimit, true) }));
}
activityList.addChild("li", l10n("totalInputSession", new String[] { "total", "rate" }, new String[] { SizeUtil.formatSize(total[1], true), SizeUtil.formatSize(total_input_rate, true) }));
activityList.addChild("li", l10n("totalOutputSession", new String[] { "total", "rate" }, new String[] { SizeUtil.formatSize(total[0], true), SizeUtil.formatSize(total_output_rate, true) } ));
activityList.addChild("li", l10n("payloadOutput", new String[] { "total", "rate", "percent" }, new String[] { SizeUtil.formatSize(totalPayload, true), SizeUtil.formatSize(total_payload_rate, true), Integer.toString(percent) } ));
activityList.addChild("li", l10n("totalInput", new String[] { "total" }, new String[] { SizeUtil.formatSize(overall_total_in, true) }));
activityList.addChild("li", l10n("totalOutput", new String[] { "total" }, new String[] { SizeUtil.formatSize(overall_total_out, true) } ));
if(isAdvancedModeEnabled) {
long totalBytesSentCHKRequests = node.nodeStats.getCHKRequestTotalBytesSent();
long totalBytesSentSSKRequests = node.nodeStats.getSSKRequestTotalBytesSent();
long totalBytesSentCHKInserts = node.nodeStats.getCHKInsertTotalBytesSent();
long totalBytesSentSSKInserts = node.nodeStats.getSSKInsertTotalBytesSent();
long totalBytesSentOfferedKeys = node.nodeStats.getOfferedKeysTotalBytesSent();
long totalBytesSendOffers = node.nodeStats.getOffersSentBytesSent();
long totalBytesSentSwapOutput = node.nodeStats.getSwappingTotalBytesSent();
long totalBytesSentAuth = node.nodeStats.getTotalAuthBytesSent();
long totalBytesSentAckOnly = node.nodeStats.getNotificationOnlyPacketsSentBytes();
long totalBytesSentResends = node.nodeStats.getResendBytesSent();
long totalBytesSentUOM = node.nodeStats.getUOMBytesSent();
long totalBytesSentAnnounce = node.nodeStats.getAnnounceBytesSent();
long totalBytesSentAnnouncePayload = node.nodeStats.getAnnounceBytesPayloadSent();
long totalBytesSentRoutingStatus = node.nodeStats.getRoutingStatusBytes();
long totalBytesSentNetworkColoring = node.nodeStats.getNetworkColoringSentBytes();
long totalBytesSentPing = node.nodeStats.getPingSentBytes();
long totalBytesSentProbeRequest = node.nodeStats.getProbeRequestSentBytes();
long totalBytesSentRouted = node.nodeStats.getRoutedMessageSentBytes();
long totalBytesSentDisconn = node.nodeStats.getDisconnBytesSent();
long totalBytesSentInitial = node.nodeStats.getInitialMessagesBytesSent();
long totalBytesSentChangedIP = node.nodeStats.getChangedIPBytesSent();
long totalBytesSentNodeToNode = node.nodeStats.getNodeToNodeBytesSent();
long totalBytesSentAllocationNotices = node.nodeStats.getAllocationNoticesBytesSent();
long totalBytesSentRemaining = total[0] -
(totalPayload + totalBytesSentCHKRequests + totalBytesSentSSKRequests +
totalBytesSentCHKInserts + totalBytesSentSSKInserts +
totalBytesSentOfferedKeys + totalBytesSendOffers + totalBytesSentSwapOutput +
totalBytesSentAuth + totalBytesSentAckOnly + totalBytesSentResends +
totalBytesSentUOM + totalBytesSentAnnounce +
totalBytesSentRoutingStatus + totalBytesSentNetworkColoring + totalBytesSentPing +
totalBytesSentProbeRequest + totalBytesSentRouted + totalBytesSentDisconn +
totalBytesSentInitial + totalBytesSentChangedIP + totalBytesSentNodeToNode + totalBytesSentAllocationNotices);
activityList.addChild("li", l10n("requestOutput", new String[] { "chk", "ssk" }, new String[] { SizeUtil.formatSize(totalBytesSentCHKRequests, true), SizeUtil.formatSize(totalBytesSentSSKRequests, true) }));
activityList.addChild("li", l10n("insertOutput", new String[] { "chk", "ssk" }, new String[] { SizeUtil.formatSize(totalBytesSentCHKInserts, true), SizeUtil.formatSize(totalBytesSentSSKInserts, true) }));
activityList.addChild("li", l10n("offeredKeyOutput", new String[] { "total", "offered" }, new String[] { SizeUtil.formatSize(totalBytesSentOfferedKeys, true), SizeUtil.formatSize(totalBytesSendOffers, true) }));
activityList.addChild("li", l10n("swapOutput", "total", SizeUtil.formatSize(totalBytesSentSwapOutput, true)));
activityList.addChild("li", l10n("authBytes", "total", SizeUtil.formatSize(totalBytesSentAuth, true)));
activityList.addChild("li", l10n("ackOnlyBytes", "total", SizeUtil.formatSize(totalBytesSentAckOnly, true)));
activityList.addChild("li", l10n("resendBytes", new String[] { "total", "percent" }, new String[] { SizeUtil.formatSize(totalBytesSentResends, true), Long.toString((long)(100 * totalBytesSentResends) / Math.max(1, total[0])) } ));
activityList.addChild("li", l10n("uomBytes", "total", SizeUtil.formatSize(totalBytesSentUOM, true)));
activityList.addChild("li", l10n("announceBytes", new String[] { "total", "payload" }, new String[] { SizeUtil.formatSize(totalBytesSentAnnounce, true), SizeUtil.formatSize(totalBytesSentAnnouncePayload, true) }));
activityList.addChild("li", l10n("adminBytes", new String[] { "routingStatus", "disconn", "initial", "changedIP" }, new String[] { SizeUtil.formatSize(totalBytesSentRoutingStatus, true), SizeUtil.formatSize(totalBytesSentDisconn, true), SizeUtil.formatSize(totalBytesSentInitial, true), SizeUtil.formatSize(totalBytesSentChangedIP, true) }));
activityList.addChild("li", l10n("debuggingBytes", new String[] { "netColoring", "ping", "probe", "routed" }, new String[] { SizeUtil.formatSize(totalBytesSentNetworkColoring, true), SizeUtil.formatSize(totalBytesSentPing, true), SizeUtil.formatSize(totalBytesSentProbeRequest, true), SizeUtil.formatSize(totalBytesSentRouted, true) } ));
activityList.addChild("li", l10n("nodeToNodeBytes", "total", SizeUtil.formatSize(totalBytesSentNodeToNode, true)));
activityList.addChild("li", l10n("loadAllocationNoticesBytes", "total", SizeUtil.formatSize(totalBytesSentAllocationNotices, true)));
activityList.addChild("li", l10n("unaccountedBytes", new String[] { "total", "percent" },
new String[] { SizeUtil.formatSize(totalBytesSentRemaining, true), Integer.toString((int)(totalBytesSentRemaining*100 / total[0])) }));
double sentOverheadPerSecond = node.nodeStats.getSentOverheadPerSecond();
activityList.addChild("li", l10n("totalOverhead", new String[] { "rate", "percent" },
new String[] { SizeUtil.formatSize((long)sentOverheadPerSecond), Integer.toString((int)((100 * sentOverheadPerSecond) / total_output_rate)) }));
}
}
static HTMLNode drawActivity(HTMLNode activityInfoboxContent, Node node) {
int numLocalCHKInserts = node.getNumLocalCHKInserts();
int numRemoteCHKInserts = node.getNumRemoteCHKInserts();
int numLocalSSKInserts = node.getNumLocalSSKInserts();
int numRemoteSSKInserts = node.getNumRemoteSSKInserts();
int numLocalCHKRequests = node.getNumLocalCHKRequests();
int numRemoteCHKRequests = node.getNumRemoteCHKRequests();
int numLocalSSKRequests = node.getNumLocalSSKRequests();
int numRemoteSSKRequests = node.getNumRemoteSSKRequests();
int numTransferringRequests = node.getNumTransferringRequestSenders();
int numTransferringRequestHandlers = node.getNumTransferringRequestHandlers();
int numCHKOfferReplys = node.getNumCHKOfferReplies();
int numSSKOfferReplys = node.getNumSSKOfferReplies();
int numCHKRequests = numLocalCHKRequests + numRemoteCHKRequests;
int numSSKRequests = numLocalSSKRequests + numRemoteSSKRequests;
int numCHKInserts = numLocalCHKInserts + numRemoteCHKInserts;
int numSSKInserts = numLocalSSKInserts + numRemoteSSKInserts;
if ((numTransferringRequests == 0) &&
(numCHKRequests == 0) && (numSSKRequests == 0) &&
(numCHKInserts == 0) && (numSSKInserts == 0) &&
(numTransferringRequestHandlers == 0) &&
(numCHKOfferReplys == 0) && (numSSKOfferReplys == 0)) {
activityInfoboxContent.addChild("#", l10n("noRequests"));
return null;
} else {
HTMLNode activityList = activityInfoboxContent.addChild("ul");
if (numCHKInserts > 0 || numSSKInserts > 0) {
activityList.addChild("li", NodeL10n.getBase().getString("StatisticsToadlet.activityInserts",
new String[] { "CHKhandlers", "SSKhandlers", "local" } ,
new String[] { Integer.toString(numCHKInserts), Integer.toString(numSSKInserts), Integer.toString(numLocalCHKInserts)+"/" + Integer.toString(numLocalSSKInserts)}));
}
if (numCHKRequests > 0 || numSSKRequests > 0) {
activityList.addChild("li", NodeL10n.getBase().getString("StatisticsToadlet.activityRequests",
new String[] { "CHKhandlers", "SSKhandlers", "local" } ,
new String[] { Integer.toString(numCHKRequests), Integer.toString(numSSKRequests), Integer.toString(numLocalCHKRequests)+"/" + Integer.toString(numLocalSSKRequests)}));
}
if (numTransferringRequests > 0 || numTransferringRequestHandlers > 0) {
activityList.addChild("li", NodeL10n.getBase().getString("StatisticsToadlet.transferringRequests",
new String[] { "senders", "receivers", "turtles" }, new String[] { Integer.toString(numTransferringRequests), Integer.toString(numTransferringRequestHandlers), "0"}));
}
if (numCHKOfferReplys > 0 || numSSKOfferReplys > 0) {
activityList.addChild("li", NodeL10n.getBase().getString("StatisticsToadlet.offerReplys",
new String[] { "chk", "ssk" }, new String[] { Integer.toString(numCHKOfferReplys), Integer.toString(numSSKOfferReplys) }));
}
activityList.addChild("li", NodeL10n.getBase().getString("StatisticsToadlet.runningBlockTransfers",
new String[] { "sends", "receives" }, new String[] { Integer.toString(BlockTransmitter.getRunningSends()), Integer.toString(BlockReceiver.getRunningReceives()) }));
return activityList;
}
}
private void drawOverviewBox(HTMLNode overviewInfobox, long nodeUptimeSeconds, long nodeUptimeTotal, long now, double swaps, double noSwaps) {
overviewInfobox.addChild("div", "class", "infobox-header", "Node status overview");
HTMLNode overviewInfoboxContent = overviewInfobox.addChild("div", "class", "infobox-content");
HTMLNode overviewList = overviewInfoboxContent.addChild("ul");
/* node status values */
int bwlimitDelayTime = (int) stats.getBwlimitDelayTime();
int bwlimitDelayTimeBulk = (int) stats.getBwlimitDelayTimeBulk();
int bwlimitDelayTimeRT = (int) stats.getBwlimitDelayTimeRT();
int nodeAveragePingTime = (int) stats.getNodeAveragePingTime();
double numberOfRemotePeerLocationsSeenInSwaps = node.getNumberOfRemotePeerLocationsSeenInSwaps();
// Darknet
int darknetSizeEstimateSession = stats.getDarknetSizeEstimate(-1);
int darknetSizeEstimate24h = 0;
int darknetSizeEstimate48h = 0;
if(nodeUptimeSeconds > (24*60*60)) { // 24 hours
darknetSizeEstimate24h = stats.getDarknetSizeEstimate(now - (24*60*60*1000)); // 48 hours
}
if(nodeUptimeSeconds > (48*60*60)) { // 48 hours
darknetSizeEstimate48h = stats.getDarknetSizeEstimate(now - (48*60*60*1000)); // 48 hours
}
// Opennet
int opennetSizeEstimateSession = stats.getOpennetSizeEstimate(-1);
int opennetSizeEstimate24h = 0;
int opennetSizeEstimate48h = 0;
if (nodeUptimeSeconds > (24 * 60 * 60)) { // 24 hours
opennetSizeEstimate24h = stats.getOpennetSizeEstimate(now - (24 * 60 * 60 * 1000)); // 48 hours
}
if (nodeUptimeSeconds > (48 * 60 * 60)) { // 48 hours
opennetSizeEstimate48h = stats.getOpennetSizeEstimate(now - (48 * 60 * 60 * 1000)); // 48 hours
}
double routingMissDistanceLocal = stats.routingMissDistanceLocal.currentValue();
double routingMissDistanceRemote = stats.routingMissDistanceRemote.currentValue();
double routingMissDistanceOverall = stats.routingMissDistanceOverall.currentValue();
double backedOffPercent = stats.backedOffPercent.currentValue();
overviewList.addChild("li", "bwlimitDelayTime:\u00a0" + bwlimitDelayTime + "ms");
overviewList.addChild("li", "bwlimitDelayTimeBulk:\u00a0" + bwlimitDelayTimeBulk + "ms");
overviewList.addChild("li", "bwlimitDelayTimeRT:\u00a0" + bwlimitDelayTimeRT + "ms");
overviewList.addChild("li", "nodeAveragePingTime:\u00a0" + nodeAveragePingTime + "ms");
overviewList.addChild("li", "darknetSizeEstimateSession:\u00a0" + darknetSizeEstimateSession + "\u00a0nodes");
if(nodeUptimeSeconds > (24*60*60)) { // 24 hours
overviewList.addChild("li", "darknetSizeEstimate24h:\u00a0" + darknetSizeEstimate24h + "\u00a0nodes");
}
if(nodeUptimeSeconds > (48*60*60)) { // 48 hours
overviewList.addChild("li", "darknetSizeEstimate48h:\u00a0" + darknetSizeEstimate48h + "\u00a0nodes");
}
overviewList.addChild("li", "opennetSizeEstimateSession:\u00a0" + opennetSizeEstimateSession + "\u00a0nodes");
if (nodeUptimeSeconds > (24 * 60 * 60)) { // 24 hours
overviewList.addChild("li", "opennetSizeEstimate24h:\u00a0" + opennetSizeEstimate24h + "\u00a0nodes");
}
if (nodeUptimeSeconds > (48 * 60 * 60)) { // 48 hours
overviewList.addChild("li", "opennetSizeEstimate48h:\u00a0" + opennetSizeEstimate48h + "\u00a0nodes");
}
if ((numberOfRemotePeerLocationsSeenInSwaps > 0.0) && ((swaps > 0.0) || (noSwaps > 0.0))) {
overviewList.addChild("li", "avrConnPeersPerNode:\u00a0" + fix6p6.format(numberOfRemotePeerLocationsSeenInSwaps/(swaps+noSwaps)) + "\u00a0peers");
}
overviewList.addChild("li", "nodeUptimeSession:\u00a0" + TimeUtil.formatTime(nodeUptimeSeconds * 1000));
overviewList.addChild("li", "nodeUptimeTotal:\u00a0" + TimeUtil.formatTime(nodeUptimeTotal));
overviewList.addChild("li", "routingMissDistanceLocal:\u00a0" + fix1p4.format(routingMissDistanceLocal));
overviewList.addChild("li", "routingMissDistanceRemote:\u00a0" + fix1p4.format(routingMissDistanceRemote));
overviewList.addChild("li", "routingMissDistanceOverall:\u00a0" + fix1p4.format(routingMissDistanceOverall));
overviewList.addChild("li", "backedOffPercent:\u00a0" + fix3p1pct.format(backedOffPercent));
overviewList.addChild("li", "pInstantReject:\u00a0" + fix3p1pct.format(stats.pRejectIncomingInstantly()));
overviewList.addChild("li", "unclaimedFIFOSize:\u00a0" + node.getUnclaimedFIFOSize());
overviewList.addChild("li", "RAMBucketPoolSize:\u00a0" + SizeUtil.formatSize(core.tempBucketFactory.getRamUsed())+ " / "+ SizeUtil.formatSize(core.tempBucketFactory.getMaxRamUsed()));
overviewList.addChild("li", "uptimeAverage:\u00a0" + fix3p1pct.format(node.uptime.getUptime()));
long[] decoded = IncomingPacketFilterImpl.getDecodedPackets();
if(decoded != null) {
overviewList.addChild("li", "packetsDecoded:\u00a0"+fix3p1pct.format(((double)decoded[0])/((double)decoded[1]))+"\u00a0("+decoded[1]+")");
}
}
private void drawBandwidthBox(HTMLNode bandwidthInfobox, long nodeUptimeSeconds, boolean isAdvancedModeEnabled) {
bandwidthInfobox.addChild("div", "class", "infobox-header", l10n("bandwidthTitle"));
HTMLNode bandwidthInfoboxContent = bandwidthInfobox.addChild("div", "class", "infobox-content");
HTMLNode bandwidthList = bandwidthInfoboxContent.addChild("ul");
drawBandwidth(bandwidthList, node, nodeUptimeSeconds, isAdvancedModeEnabled);
}
// FIXME this should probably be moved to nodestats so it can be used by FCP??? would have to make ThreadBunch public :<
private void getThreadNames(HTMLNode threadUsageList) {
Thread[] threads = stats.getThreads();
LinkedHashMap<String, ThreadBunch> map = new LinkedHashMap<String, ThreadBunch>();
int totalCount = 0;
for(int i=0;i<threads.length;i++) {
if(threads[i] == null) break;
String name = NativeThread.normalizeName(threads[i].getName());
ThreadBunch bunch = map.get(name);
if(bunch != null) {
bunch.count++;
} else {
map.put(name, new ThreadBunch(name, 1));
}
totalCount++;
}
ThreadBunch[] bunches = map.values().toArray(new ThreadBunch[map.size()]);
Arrays.sort(bunches, new Comparator<ThreadBunch>() {
public int compare(ThreadBunch b0, ThreadBunch b1) {
if(b0.count > b1.count) return -1;
if(b0.count < b1.count) return 1;
return b0.name.compareTo(b1.name);
}
});
double thisThreadPercentOfTotal;
for(int i=0; i<bunches.length; i++) {
thisThreadPercentOfTotal = ((double) bunches[i].count) / ((double) totalCount);
threadUsageList.addChild("li", "" + bunches[i].name + ":\u00a0" + Integer.toString(bunches[i].count) + "\u00a0(" + fix3p1pct.format(thisThreadPercentOfTotal) + ')');
}
}
private static class ThreadBunch {
public ThreadBunch(String name2, int i) {
this.name = name2;
this.count = i;
}
String name;
int count;
}
private final static int PEER_CIRCLE_RADIUS = 100;
private final static int PEER_CIRCLE_INNER_RADIUS = 60;
private final static int PEER_CIRCLE_ADDITIONAL_FREE_SPACE = 10;
private final static long MAX_CIRCLE_AGE_THRESHOLD = 24l*60*60*1000; // 24 hours
private final static int HISTOGRAM_LENGTH = 10;
private void addNodeCircle (HTMLNode circleTable, double myLocation) {
int[] histogram = new int[HISTOGRAM_LENGTH];
for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
histogram[i] = 0;
}
HTMLNode nodeCircleTableRow = circleTable.addChild("tr");
HTMLNode nodeHistogramLegendTableRow = circleTable.addChild("tr");
HTMLNode nodeHistogramGraphTableRow = circleTable.addChild("tr");
HTMLNode nodeCircleTableCell = nodeCircleTableRow.addChild("td", new String[] { "class", "colspan" }, new String[] {"first", "10"});
HTMLNode nodeHistogramLegendCell;
HTMLNode nodeHistogramGraphCell;
HTMLNode nodeCircleInfoboxContent = nodeCircleTableCell.addChild("div", new String[] { "style", "class" }, new String[] {"position: relative; height: " + ((PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) * 2) + "px; width: " + ((PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) * 2) + "px", "peercircle" });
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0, false, 1.0), "mark" }, "|");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.125, false, 1.0), "mark" }, "+");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.25, false, 1.0), "mark" }, "--");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.375, false, 1.0), "mark" }, "+");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.5, false, 1.0), "mark" }, "|");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.625, false, 1.0), "mark" }, "+");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.75, false, 1.0), "mark" }, "--");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.875, false, 1.0), "mark" }, "+");
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { "position: absolute; top: " + PEER_CIRCLE_RADIUS + "px; left: " + (PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) + "px", "mark" }, "+");
final Object[] knownLocsCopy = stats.getKnownLocations(-1);
final Double[] locations = (Double[])knownLocsCopy[0];
final Long[] timestamps = (Long[])knownLocsCopy[1];
Double location;
Long locationTime;
double strength = 1.0;
long now = System.currentTimeMillis();
long age = 1;
int histogramIndex;
int nodeCount = 0;
for(int i=0; i<locations.length; i++){
nodeCount += 1;
location = locations[i];
locationTime = timestamps[i];
age = now - locationTime.longValue();
if( age > MAX_CIRCLE_AGE_THRESHOLD ) {
age = MAX_CIRCLE_AGE_THRESHOLD;
}
strength = 1 - ((double) age / MAX_CIRCLE_AGE_THRESHOLD );
histogramIndex = (int) (Math.floor(location.doubleValue() * HISTOGRAM_LENGTH));
histogram[histogramIndex]++;
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(location.doubleValue(), false, strength), "connected" }, "x");
}
nodeCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(myLocation, true, 1.0), "me" }, "x");
//
double histogramPercent;
for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
nodeHistogramLegendCell = nodeHistogramLegendTableRow.addChild("td");
nodeHistogramGraphCell = nodeHistogramGraphTableRow.addChild("td", "style", "height: 100px;");
nodeHistogramLegendCell.addChild("div", "class", "histogramLabel").addChild("#", fix1p1.format(((double) i) / HISTOGRAM_LENGTH ));
histogramPercent = nodeCount==0 ? 0 : ((double)histogram[ i ] / nodeCount);
// Don't use HTMLNode here to speed things up
nodeHistogramGraphCell.addChild("%", "<div class=\"histogramConnected\" style=\"height: " + fix3pctUS.format(histogramPercent) + "; width: 100%;\">\u00a0</div>");
}
}
private void addSpecialisation(HTMLNode table, double peerLocation, int incomingRequestsCount, int[] incomingRequestLocation) {
HTMLNode nodeHistogramLegendTableRow = table.addChild("tr");
HTMLNode nodeHistogramGraphTableRow = table.addChild("tr");
int myIndex = (int)(peerLocation * incomingRequestLocation.length);
for (int i = 0; i<incomingRequestLocation.length; i++) {
HTMLNode nodeHistogramLegendCell = nodeHistogramLegendTableRow.addChild("td");
HTMLNode nodeHistogramGraphCell = nodeHistogramGraphTableRow.addChild("td", "style", "height: 100px;");
HTMLNode nodeHistogramGraphCell2 = nodeHistogramLegendCell.addChild("div", "class", "histogramLabel");
if(i == myIndex)
nodeHistogramGraphCell2 = nodeHistogramGraphCell2.addChild("span", "class", "me");
nodeHistogramGraphCell2.addChild("#", fix1p1.format(((double) i) / incomingRequestLocation.length ));
nodeHistogramGraphCell.addChild("div", new String[] { "class", "style" }, new String[] { "histogramConnected", "height: " + fix3pctUS.format(((double)incomingRequestLocation[i]) / incomingRequestsCount) + "; width: 100%;" }, "\u00a0");
}
}
private void addCombinedSpecialisation(HTMLNode table, double peerLocation, int locallyOriginatingRequestsCount, int[] locallyOriginatingRequests, int remotelyOriginatingRequestsCount, int[] remotelyOriginatingRequests) {
assert(locallyOriginatingRequests.length == remotelyOriginatingRequests.length);
HTMLNode nodeHistogramLegendTableRow = table.addChild("tr");
HTMLNode nodeHistogramGraphTableRow = table.addChild("tr");
int myIndex = (int)(peerLocation * locallyOriginatingRequests.length);
for (int i = 0; i<locallyOriginatingRequests.length; i++) {
HTMLNode nodeHistogramLegendCell = nodeHistogramLegendTableRow.addChild("td");
HTMLNode nodeHistogramGraphCell = nodeHistogramGraphTableRow.addChild("td", "style", "height: 100px;");
HTMLNode nodeHistogramGraphCell2 = nodeHistogramLegendCell.addChild("div", "class", "histogramLabel");
if(i == myIndex)
nodeHistogramGraphCell2 = nodeHistogramGraphCell2.addChild("span", "class", "me");
nodeHistogramGraphCell2.addChild("#", fix1p1.format(((double) i) / locallyOriginatingRequests.length ));
nodeHistogramGraphCell.addChild("div",
new String[] { "class", "style" },
new String[] { "histogramConnected", "height: " +
fix3pctUS.format(((double)locallyOriginatingRequests[i]) / locallyOriginatingRequestsCount) +
"; width: 100%;" },
"\u00a0");
nodeHistogramGraphCell.addChild("div",
new String[] { "class", "style" },
new String[] { "histogramDisconnected", "height: " +
fix3pctUS.format(((double)remotelyOriginatingRequests[i]) / remotelyOriginatingRequestsCount) +
"; width: 100%;" },
"\u00a0");
}
}
private void addPeerCircle (HTMLNode circleTable, PeerNodeStatus[] peerNodeStatuses, double myLocation) {
int[] histogramConnected = new int[HISTOGRAM_LENGTH];
int[] histogramDisconnected = new int[HISTOGRAM_LENGTH];
for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
histogramConnected[i] = 0;
histogramDisconnected[i] = 0;
}
HTMLNode peerCircleTableRow = circleTable.addChild("tr");
HTMLNode peerHistogramLegendTableRow = circleTable.addChild("tr");
HTMLNode peerHistogramGraphTableRow = circleTable.addChild("tr");
HTMLNode peerCircleTableCell = peerCircleTableRow.addChild("td", new String[] { "class", "colspan" }, new String[] {"first", "10"});
HTMLNode peerHistogramLegendCell;
HTMLNode peerHistogramGraphCell;
HTMLNode peerCircleInfoboxContent = peerCircleTableCell.addChild("div", new String[] { "style", "class" }, new String[] {"position: relative; height: " + ((PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) * 2) + "px; width: " + ((PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) * 2) + "px", "peercircle" });
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0, false, 1.0), "mark" }, "|");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.125, false, 1.0), "mark" }, "+");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.25, false, 1.0), "mark" }, "--");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.375, false, 1.0), "mark" }, "+");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.5, false, 1.0), "mark" }, "|");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.625, false, 1.0), "mark" }, "+");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.75, false, 1.0), "mark" }, "--");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(0.875, false, 1.0), "mark" }, "+");
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { "position: absolute; top: " + PEER_CIRCLE_RADIUS + "px; left: " + (PEER_CIRCLE_RADIUS + PEER_CIRCLE_ADDITIONAL_FREE_SPACE) + "px", "mark" }, "+");
PeerNodeStatus peerNodeStatus;
double peerLocation;
double peerDistance;
int histogramIndex;
int peerCount = peerNodeStatuses.length;
int newPeerCount = 0;
for (int peerIndex = 0; peerIndex < peerCount; peerIndex++) {
peerNodeStatus = peerNodeStatuses[peerIndex];
peerLocation = peerNodeStatus.getLocation();
if(!peerNodeStatus.isSearchable()) continue;
if(peerLocation < 0.0 || peerLocation > 1.0) continue;
double[] foafLocations=peerNodeStatus.getPeersLocation();
if (foafLocations!=null && peerNodeStatus.isRoutable()) {
for (double foafLocation : foafLocations) {
//one grey dot for each "Friend-of-a-friend"
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(foafLocation, false, 0.9), "disconnected" }, ".");
}
}
newPeerCount++;
peerDistance = Location.distance( myLocation, peerLocation );
histogramIndex = (int) (Math.floor(peerDistance * HISTOGRAM_LENGTH * 2));
if (peerNodeStatus.isConnected()) {
histogramConnected[histogramIndex]++;
} else {
histogramDisconnected[histogramIndex]++;
}
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(peerLocation, false, (1.0 - peerNodeStatus.getPReject())), ((peerNodeStatus.isConnected())?"connected":"disconnected") }, ((peerNodeStatus.isOpennet())?"o":"x"));
}
peerCircleInfoboxContent.addChild("span", new String[] { "style", "class" }, new String[] { generatePeerCircleStyleString(myLocation, true, 1.0), "me" }, "x");
//
double histogramPercent;
for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
peerHistogramLegendCell = peerHistogramLegendTableRow.addChild("td");
peerHistogramGraphCell = peerHistogramGraphTableRow.addChild("td", "style", "height: 100px;");
peerHistogramLegendCell.addChild("div", "class", "histogramLabel").addChild("#", fix1p2.format(((double) i) / ( HISTOGRAM_LENGTH * 2 )));
//
histogramPercent = ((double) histogramConnected[ i ] ) / newPeerCount;
peerHistogramGraphCell.addChild("div", new String[] { "class", "style" }, new String[] { "histogramConnected", "height: " + fix3pctUS.format(histogramPercent) + "; width: 100%;" }, "\u00a0");
//
histogramPercent = ((double) histogramDisconnected[ i ] ) / newPeerCount;
peerHistogramGraphCell.addChild("div", new String[] { "class", "style" }, new String[] { "histogramDisconnected", "height: " + fix3pctUS.format(histogramPercent) + "; width: 100%;" }, "\u00a0");
}
}
private String generatePeerCircleStyleString (double peerLocation, boolean offsetMe, double strength) {
peerLocation *= Math.PI * 2;
//
int offset = 0;
if( offsetMe ) {
// Make our own peer stand out from the crowd better so we can see it easier
offset = -10;
} else {
offset = (int) (PEER_CIRCLE_INNER_RADIUS * (1.0 - strength));
}
double x = PEER_CIRCLE_ADDITIONAL_FREE_SPACE + PEER_CIRCLE_RADIUS + Math.sin(peerLocation) * (PEER_CIRCLE_RADIUS - offset);
double y = PEER_CIRCLE_RADIUS - Math.cos(peerLocation) * (PEER_CIRCLE_RADIUS - offset); // no PEER_CIRCLE_ADDITIONAL_FREE_SPACE for y-disposition
//
return "position: absolute; top: " + fix3p1US.format(y) + "px; left: " + fix3p1US.format(x) + "px";
}
@Override
public String path() {
return "/stats/";
}
}
| true |
54200d1727fa582d1700cfa9e1cc4df1e9e03b59 | Java | vivekchopra/books | /Beginning_JavaServer_Pages_2nd_ed/ch18/ch18-spring-base/src/begjsp/ch18/spring/TestFormController.java | UTF-8 | 331 | 2.03125 | 2 | [] | no_license | package begjsp.ch18.spring;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class TestFormController extends SimpleFormController
{
public ModelAndView onSubmit(Object object)
{
return new ModelAndView("success");
}
}
| true |
c9120cd9db7b6faf93e61a9ee7ede2514e89bbef | Java | q315099997/test-platform | /TestPlatform/src/com/ztemt/test/platform/OutputService.java | UTF-8 | 3,515 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package com.ztemt.test.platform;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.ztemt.test.platform.util.DeviceUtils;
import com.ztemt.test.platform.util.FileUtils;
import com.ztemt.test.platform.util.HttpPost;
import com.ztemt.test.platform.util.HttpPost.ProgressListener;
public class OutputService extends IntentService implements ProgressListener {
private static final String TAG = "OutputService";
private NotificationCompat.Builder mBuilder;
private NotificationManager mNM;
public OutputService() {
super("output");
}
@Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
protected void onHandleIntent(Intent intent) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(
CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI
&& info.getState() == NetworkInfo.State.CONNECTED) {
mBuilder = createProgressNotificationBuilder();
mNM.notify(R.string.upload, mBuilder.build());
for (File file : FileUtils.listFile(OutputManager.OUTPUT)) {
if (upload(file)) {
file.delete();
} else {
Log.w(TAG, "upload " + file.getName() + " failed");
}
}
mNM.cancel(R.string.upload);
} else {
Log.d(TAG, "wifi is not active");
}
stopSelf();
}
@Override
public void onProgressUpdate(int progress) {
mBuilder.setProgress(100, progress, false);
mNM.notify(R.string.upload, mBuilder.build());
}
private boolean upload(File file) {
String task = file.getName().split("-")[0];
Map<String, String> params = new HashMap<String, String>();
params.put("address", DeviceUtils.getWifiMacAddress(this));
params.put("model", Build.MODEL);
params.put("display", Build.DISPLAY);
params.put("buildDate", DeviceUtils.getBuildDate2());
params.put("task", task);
String result = "failure";
try {
result = HttpPost.post(getString(R.string.upload_url), params, file, this);
} catch (IOException e) {
Log.e(TAG, "upload", e);
}
return "success".equals(result);
}
private NotificationCompat.Builder createProgressNotificationBuilder() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(getString(R.string.file_upload_title));
builder.setContentText(getString(R.string.file_upload_text));
builder.setAutoCancel(false);
builder.setOnlyAlertOnce(true);
builder.setOngoing(true);
builder.setDefaults(Notification.DEFAULT_SOUND);
return builder;
}
}
| true |
f24e99c2b9c88a2e19dbfa250fc22825b459dce2 | Java | harrinry/ddp-study-manager | /src/main/java/org/broadinstitute/dsm/model/BSPKit.java | UTF-8 | 8,970 | 1.898438 | 2 | [
"BSD-3-Clause"
] | permissive | package org.broadinstitute.dsm.model;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.broadinstitute.ddp.db.TransactionWrapper;
import org.broadinstitute.dsm.db.DDPInstance;
import org.broadinstitute.dsm.db.InstanceSettings;
import org.broadinstitute.dsm.db.dao.ddp.kitrequest.KitRequestDao;
import org.broadinstitute.dsm.db.dao.kit.BSPKitDao;
import org.broadinstitute.dsm.db.dto.kit.BSPKitDto;
import org.broadinstitute.dsm.db.dto.settings.InstanceSettingsDto;
import org.broadinstitute.dsm.model.bsp.BSPKitInfo;
import org.broadinstitute.dsm.model.bsp.BSPKitStatus;
import org.broadinstitute.dsm.statics.ApplicationConfigConstants;
import org.broadinstitute.dsm.statics.ESObjectConstants;
import org.broadinstitute.dsm.util.ElasticSearchDataUtil;
import org.broadinstitute.dsm.util.ElasticSearchUtil;
import org.broadinstitute.dsm.util.EventUtil;
import org.broadinstitute.dsm.util.NotificationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class BSPKit {
private static Logger logger = LoggerFactory.getLogger(BSPKit.class);
public Optional<BSPKitStatus> getKitStatus(@NonNull String kitLabel, NotificationUtil notificationUtil) {
logger.info("Checking label " + kitLabel);
BSPKitDao bspKitDao = new BSPKitDao();
Optional<BSPKitDto> bspKitQueryResult = bspKitDao.getBSPKitQueryResult(kitLabel);
Optional<BSPKitStatus> result = Optional.empty();
if (bspKitQueryResult.isEmpty()) {
logger.info("No kit w/ label " + kitLabel + " found");
}
else {
BSPKitDto maybeBspKitQueryResult = bspKitQueryResult.get();
if (StringUtils.isNotBlank(maybeBspKitQueryResult.getParticipantExitId())) {
String message = "Kit of exited participant " + maybeBspKitQueryResult.getBspParticipantId() + " was received by GP.<br>";
notificationUtil.sentNotification(maybeBspKitQueryResult.getNotificationRecipient(), message, NotificationUtil.DSM_SUBJECT);
result = Optional.of(new BSPKitStatus(BSPKitStatus.EXITED));
}
else if (StringUtils.isNotBlank(maybeBspKitQueryResult.getDeactivationDate())) {
result = Optional.of(new BSPKitStatus(BSPKitStatus.DEACTIVATED));
}
}
return result;
}
public boolean canReceiveKit(@NonNull String kitLabel) {
BSPKitDao bspKitDao = new BSPKitDao();
Optional<BSPKitDto> bspKitQueryResult = bspKitDao.getBSPKitQueryResult(kitLabel);
if (bspKitQueryResult.isEmpty()) {
logger.info("No kit w/ label " + kitLabel + " found");
return false;
}
else {
BSPKitDto maybeBspKitQueryResult = bspKitQueryResult.get();
if (StringUtils.isNotBlank(maybeBspKitQueryResult.getParticipantExitId()) || StringUtils.isNotBlank(maybeBspKitQueryResult.getDeactivationDate())) {
logger.info("Kit can not be received.");
return false;
}
}
return true;
}
public Optional<BSPKitInfo> receiveBSPKit(String kitLabel, NotificationUtil notificationUtil) {
logger.info("Trying to receive kit " + kitLabel);
BSPKitDao bspKitDao = new BSPKitDao();
Optional<BSPKitDto> bspKitQueryResult = bspKitDao.getBSPKitQueryResult(kitLabel);
if (bspKitQueryResult.isEmpty()) {
logger.warn("returning empty object for "+kitLabel);
return Optional.empty();
}
BSPKitDto maybeBspKitQueryResult = bspKitQueryResult.get();
if (StringUtils.isBlank(maybeBspKitQueryResult.getDdpParticipantId())) {
throw new RuntimeException("No participant id for " + kitLabel + " from " + maybeBspKitQueryResult.getInstanceName());
}
logger.info("particpant id is " + maybeBspKitQueryResult.getDdpParticipantId());
DDPInstance ddpInstance = DDPInstance.getDDPInstance(maybeBspKitQueryResult.getInstanceName());
InstanceSettings instanceSettings = new InstanceSettings();
InstanceSettingsDto instanceSettingsDto = instanceSettings.getInstanceSettings(maybeBspKitQueryResult.getInstanceName());
instanceSettingsDto.getKitBehaviorChange()
.flatMap(kitBehavior -> kitBehavior.stream().filter(o -> o.getName().equals(InstanceSettings.INSTANCE_SETTING_RECEIVED)).findFirst())
.ifPresentOrElse(received -> {
Map<String, Map<String, Object>> participants = ElasticSearchUtil.getFilteredDDPParticipantsFromES(ddpInstance,
ElasticSearchUtil.BY_GUID + maybeBspKitQueryResult.getDdpParticipantId());
writeSampleReceivedToES(ddpInstance, maybeBspKitQueryResult);
Map<String, Object> participant = participants.get(maybeBspKitQueryResult.getDdpParticipantId());
if (participant != null) {
boolean triggerDDP = true;
boolean specialBehavior = InstanceSettings.shouldKitBehaveDifferently(participant, received);
if (specialBehavior) {
//don't trigger ddp to sent out email, only email to study staff
triggerDDP = false;
if (InstanceSettings.TYPE_NOTIFICATION.equals(received.getType())) {
String message = "Kit of participant " + maybeBspKitQueryResult.getBspParticipantId() + " was received by GP. <br> " +
"CollaboratorSampleId: " + maybeBspKitQueryResult.getBspSampleId() + " <br> " +
received.getValue();
notificationUtil.sentNotification(maybeBspKitQueryResult.getNotificationRecipient(), message, NotificationUtil.UNIVERSAL_NOTIFICATION_TEMPLATE, NotificationUtil.DSM_SUBJECT);
}
else {
logger.error("Instance settings behavior for kit was not known " + received.getType());
}
}
bspKitDao.setKitReceivedAndTriggerDDP(kitLabel, triggerDDP, maybeBspKitQueryResult);
}
}, () -> {
bspKitDao.setKitReceivedAndTriggerDDP(kitLabel, true, maybeBspKitQueryResult);
});
String bspParticipantId = maybeBspKitQueryResult.getBspParticipantId();
String bspSampleId = maybeBspKitQueryResult.getBspSampleId();
String bspMaterialType = maybeBspKitQueryResult.getBspMaterialType();
String bspReceptacleType = maybeBspKitQueryResult.getBspReceptacleType();
int bspOrganism;
try {
bspOrganism = Integer.parseInt(maybeBspKitQueryResult.getBspOrganism());
}
catch (NumberFormatException e) {
throw new RuntimeException("Organism " + maybeBspKitQueryResult.getBspOrganism() + " can't be parsed to integer", e);
}
logger.info("Returning info for kit w/ label " + kitLabel + " for " + maybeBspKitQueryResult.getInstanceName());
logger.info("Kit returned has sample id " + bspSampleId);
return Optional.of(new BSPKitInfo(maybeBspKitQueryResult.getBspCollection(),
bspOrganism,
"U",
bspParticipantId,
bspSampleId,
bspMaterialType,
bspReceptacleType));
}
private void writeSampleReceivedToES(DDPInstance ddpInstance, BSPKitDto bspKitInfo) {
String kitRequestId = new KitRequestDao().getKitRequestIdByBSPParticipantId(bspKitInfo.getBspParticipantId());
Map<String, Object> nameValuesMap = new HashMap<>();
ElasticSearchDataUtil.setCurrentStrictYearMonthDay(nameValuesMap, ESObjectConstants.RECEIVED);
ElasticSearchUtil.writeSample(ddpInstance, kitRequestId, bspKitInfo.getDdpParticipantId(), ESObjectConstants.SAMPLES,
ESObjectConstants.KIT_REQUEST_ID, nameValuesMap);
}
public void triggerDDP(Connection conn, @NonNull BSPKitDto bspKitInfo, boolean firstTimeReceived, String kitLabel) {
try {
if (bspKitInfo.isHasParticipantNotifications() && firstTimeReceived) {
KitDDPNotification kitDDPNotification = KitDDPNotification.getKitDDPNotification(TransactionWrapper.getSqlFromConfig(ApplicationConfigConstants.GET_RECEIVED_KIT_INFORMATION_FOR_NOTIFICATION_EMAIL), kitLabel, 1);
if (kitDDPNotification != null) {
EventUtil.triggerDDP(conn, kitDDPNotification);
}
}
}
catch (Exception e) {
logger.error("Failed doing DSM internal received things for kit w/ label " + kitLabel, e);
}
}
}
| true |
652d8d313f155976527300fa755d61ebb4a21cf0 | Java | klg0705/fl_core | /src/test/java/fl/core/service/impl/TestFightServiceImpl.java | UTF-8 | 1,072 | 2.34375 | 2 | [] | no_license | package fl.core.service.impl;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import fl.core.domain.Fighter;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-test.xml" })
public class TestFightServiceImpl {
@Resource
FightServiceImpl service;
@Test
public final void test() {
List<Fighter> list = new ArrayList<Fighter>();
Fighter a = new Fighter();
a.setAttack(10);
a.setDefence(10);
a.setHp(50);
list.add(a);
Fighter b = new Fighter();
b.setAttack(16);
b.setDefence(20);
b.setHp(40);
list.add(b);
list = service.fight(list);
assertEquals(-4, list.get(0).getHp());
assertEquals(31, list.get(1).getHp());
}
}
| true |
91ac073f0d256c0438c9787bcdaf226569dd9a00 | Java | AinurAglyamov/HortsmannExamples | /src/main/java/chapter6/EmployeeSortTest.java | UTF-8 | 576 | 3.171875 | 3 | [] | no_license | package chapter6;
import java.util.Arrays;
public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staff = new Employee[5];
staff[0] = new Employee("Vitya", 35000.00);
staff[1] = new Employee("Albus Dambldor", 36000.00);
staff[2] = new Employee("Ainur", 45000.00);
staff[3] = new Employee("Gwerman", 15000.00);
staff[4] = new Employee("Vitya", 36000.00);
System.out.println(Arrays.toString(staff));
Arrays.sort(staff);
System.out.println(Arrays.toString(staff));
}
}
| true |
6966a128909284aae5b2de16d3deb5a484a55781 | Java | 44755c1wan/QuickSdk | /quicksdklib/src/main/java/com/ledi/bean/MsgProcessor.java | UTF-8 | 373 | 1.84375 | 2 | [] | no_license | package com.ledi.bean;
public class MsgProcessor {
/**
* 处理超时的消息
* @param index
*/
public void dealOverTimeMsg(int index){
// switch (index) {
// case 0:
// loginOverTimeHandler(index);
// break;
//
//// default:
// break;
// }
}
// private void loginOverTimeHandler(index){
//这里写处理方法
}
// }
| true |
ebbce89c85520ef5cd39e81d98cce3d2e75c8224 | Java | fromzer/GiftCertificates | /web/src/main/java/com/epam/esm/hateoas/GiftOrderResource.java | UTF-8 | 814 | 2.078125 | 2 | [] | no_license | package com.epam.esm.hateoas;
import com.epam.esm.controller.UserController;
import com.epam.esm.model.GiftOrder;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@Component
public class GiftOrderResource implements RepresentationModelAssembler<GiftOrder, EntityModel<GiftOrder>> {
@Override
public EntityModel<GiftOrder> toModel(GiftOrder entity) {
return EntityModel.of(entity, linkTo(methodOn(UserController.class)
.getUserOrder(entity.getUser().getId(), entity.getId())).withSelfRel());
}
}
| true |
4420fd6286f265a6f13a1570152e1e4721ae4a7e | Java | dengshunshun/spring-data-chapter | /chapter2/src/main/java/com/mtcarpenter/repository/UserPagingRepository.java | UTF-8 | 756 | 2.09375 | 2 | [] | no_license | package com.mtcarpenter.repository;
import com.mtcarpenter.entity.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
* @author 山间木匠
* @Date 2020/2/29
*/
public interface UserPagingRepository extends PagingAndSortingRepository<User, Long> {
// 通过姓名查找
List<User> findByName(String name);
// 通过姓名查找
List<User> queryByName(String name);
// 通过姓名或者邮箱查找
List<User> findByNameOrEmail(String name,String email);
// 计算某一个 age 的数量
int countByAge(int age);
// 通过姓名条件查询
List<User> findByName(String name, Pageable pageable);
}
| true |
eaa203f7a422f2bfe4ce31dd83bfd8107d883c8a | Java | chudooder/BeltMaster | /core/src/org/chu/game/objects/Boxapult.java | UTF-8 | 2,508 | 2.671875 | 3 | [] | no_license | package org.chu.game.objects;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import org.chu.game.BeltMaster;
import org.chu.game.Constants;
import org.chu.game.render.RenderQueue;
import org.chu.game.render.SpriteSheet;
/**
* Created by Chudooder on 9/22/2017.
*/
public class Boxapult extends Entity {
private static final int DELTA_H = 32;
private static final float DEPTH = 0.1f;
private static TextureRegion base;
private static TextureRegion top;
private final float vx;
private final float vy;
private final float x0;
private final float y0;
private final float flyTime;
private double animTimer;
public static void setupAnimations(BeltMaster game) {
SpriteSheet sheet = game.getSpriteSheet("game-objects");
base = sheet.getRegion(0, 8, 2, 2);
top = sheet.getRegion(2, 8, 2, 2);
}
public Boxapult(int x, int y, int destX, int destY) {
super(x, y);
// position of the launched block
this.x0 = x;
this.y0 = y + 10;
float h; // vertical distance between launch position and peak, should be negative
if(destY > y0) { // destination is above launch position
h = destY - y0 + DELTA_H;
} else {
h = DELTA_H;
}
// calculate initial y velocity
this.vy = (float) Math.sqrt(-2f * Constants.GRAVITY * h);
// calculate time t to complete arc
flyTime = (float) (-vy - Math.sqrt(Math.pow(vy, 2) - 2 * Constants.GRAVITY * (y0 - destY)))
/ Constants.GRAVITY;
// calculate initial x velocity
this.vx = (destX - x0) / flyTime;
// System.out.printf("(%f, %f) to (%d, %d): vx = %f, vy = %f, t = %f", x0, y0, destX, destY, vx, vy, flyTime);
this.hitbox = new Rectangle(x, y, 32, 32);
this.animTimer = 0.0f;
}
public float getVx() { return vx; }
public float getVy() { return vy; }
public float getX0() { return x0; }
public float getY0() { return y0; }
public float getFlyTime() { return flyTime; }
public void collideWithBlock() {
animTimer = 1.0;
}
@Override
public void update(double dt) {
animTimer = Math.max(0.0, animTimer - dt);
}
@Override
public void render(float time, RenderQueue queue) {
queue.draw(base, x, y, DEPTH);
queue.draw(top, x, y-5, DEPTH);
}
}
| true |
44fb0293e87c45de0c2bcf5cb40cb02f81874a24 | Java | saulgalaviz/dataStructures_and_Algorithms | /SortingAlgorithms/MergeSort.java | UTF-8 | 921 | 3.515625 | 4 | [] | no_license | package SortingAlgorithms;
public class MergeSort
{
private int[] sortedList, secondList;
public MergeSort(int[] list)
{
sortedList = list;
secondList = new int[list.length - 1];
}
public void MergeSort(int low, int high)
{
if(low < high)
{
int mid = (low + high) / 2;
MergeSort(low, mid);
MergeSort(mid + 1, high);
merge(low, mid, high);
}
else
return;
}
public void merge(int low, int mid, int high)
{
int l1, l2, i;
for(l1 = low, l2 = mid, i = low; l1 <= mid && l2 <= high; i++)
{
if(sortedList[l1] <= sortedList[l2])
secondList[i] = sortedList[l1++];
else
secondList[i] = sortedList[l2++];
}
while(l1 <= mid)
secondList[i++] = sortedList[l1++];
while(l2 <= high)
secondList[i++] = sortedList[l2++];
for(i = low; i <= high; i++)
sortedList[i] = secondList[i];
}
public int[] returnList()
{
return sortedList;
}
}
| true |
f4e7a81289098326daaa87f71af747bd5850e5b9 | Java | hyb1234hi/reverse-wechat | /weixin6519android1140/src/sourcecode/com/google/android/gms/auth/api/signin/FacebookSignInConfig.java | UTF-8 | 1,132 | 1.882813 | 2 | [] | no_license | package com.google.android.gms.auth.api.signin;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import java.util.ArrayList;
public class FacebookSignInConfig
implements SafeParcelable
{
public static final Parcelable.Creator<FacebookSignInConfig> CREATOR = new b();
Intent Jt;
final ArrayList<String> agr;
final int versionCode;
public FacebookSignInConfig()
{
this(1, null, new ArrayList());
}
FacebookSignInConfig(int paramInt, Intent paramIntent, ArrayList<String> paramArrayList)
{
this.versionCode = paramInt;
this.Jt = paramIntent;
this.agr = paramArrayList;
}
public int describeContents()
{
return 0;
}
public void writeToParcel(Parcel paramParcel, int paramInt)
{
b.a(this, paramParcel, paramInt);
}
}
/* Location: D:\tools\apktool\weixin6519android1140\jar\classes4-dex2jar.jar!\com\google\android\gms\auth\api\signin\FacebookSignInConfig.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
e5970a1e755f7448d44153531c302c9c18f85a7c | Java | krishna-gara/BBH_UI | /app/controllers/User.java | UTF-8 | 1,464 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package controllers;
/**
* Created by sunny.singh on 5/9/2017.
*/
public class User {
private String user_id;
private String customer_Id;
private String first_name;
private String last_name;
private String email;
private String user_name;
private String password;
private String is_disabled;
// private String role;
public String getUserId() {
return user_id;
}
public String getCustomerId() {
return customer_Id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public String getUserName() {
return user_name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getIsDisable() {
return is_disabled;
}
public void setUserId(String user_id) {
this.user_id = user_id;
}
public void setFirstName(String first_name) {
this.first_name = first_name;
}
public void setLastName(String last_name) {
this.last_name = last_name;
}
public void setCustomerId(String customer_Id) {
this.customer_Id = customer_Id;
}
public void setUserName(String user_name) {
this.user_name = user_name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public void setIsDisable(String is_disabled) {
this.is_disabled = is_disabled;
}
}
| true |
2d6701f1aa6869d93bf87ba25c30d7df571f2f69 | Java | ynbz/framework | /framework/src/main/java/com/suredy/security/entity/Role2PermissionEntity.java | UTF-8 | 1,595 | 2.15625 | 2 | [
"MIT"
] | permissive | /**
* Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
* @author ZhangMaoren
* @since 2015年4月27日
* @version 0.1
*/
package com.suredy.security.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.suredy.core.model.BaseModel;
import com.suredy.security.model.Role2Permission;
/**
* @author ZhangMaoren
*
*/
@Entity
@Table(name = "T_SECURITY_ROLE2PERMISSION")
public class Role2PermissionEntity extends BaseModel {
/**
*
*/
private static final long serialVersionUID = -4529646227556472193L;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "ROLEID")
private RoleEntity role;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "PERMISSIONID")
private PermissionEntity permission;
/**
* @return the role
*/
public RoleEntity getRole() {
return role;
}
/**
* @param role the role to set
*/
public void setRole(RoleEntity role) {
this.role = role;
}
/**
* @return the permission
*/
public PermissionEntity getPermission() {
return permission;
}
/**
* @param permission the permission to set
*/
public void setPermission(PermissionEntity permission) {
this.permission = permission;
}
@Transient
public Role2Permission toVO(){
Role2Permission vo = new Role2Permission();
vo.setId(id);
vo.setPermissionId(permission.getId());
vo.setRoleId(role.getId());
return vo;
}
}
| true |
5206548d0b94b793a0038a98b37b596954386aab | Java | hhtqaq/booksmate | /api_common/src/main/java/com/ecjtu/hht/booksmate/common/CommonApplication.java | UTF-8 | 381 | 1.695313 | 2 | [] | no_license | package com.ecjtu.hht.booksmate.common;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author hht
* @date 2019/9/29 16:01
*/
@SpringBootApplication
public class CommonApplication {
public static void main(String[] args) {
SpringApplication.run(CommonApplication.class, args);
}
}
| true |
00cc8b1bcd9b3338462ac31039ddf984a71983a1 | Java | STAMP-project/dspot-experiments | /benchmark/training/org/jboss/as/test/integration/ejb/interceptor/inject/InterceptorInjectionUnitTestCase.java | UTF-8 | 2,488 | 1.78125 | 2 | [] | no_license | /**
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ejb.interceptor.inject;
import java.util.ArrayList;
import javax.naming.InitialContext;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Migration test from EJB Testsuite (interceptors, 2061) to AS7 [JIRA JBQA-5483].
* <p>
* Interceptor injection test.
* Bill Burke, Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class InterceptorInjectionUnitTestCase {
@ArquillianResource
InitialContext ctx;
static boolean deployed = false;
static int test = 0;
@Test
public void testInterceptAndInjection() throws Exception {
MySessionRemote test = ((MySessionRemote) (ctx.lookup(("java:module/" + (MySessionBean.class.getSimpleName())))));
ArrayList list = test.doit();
Assert.assertEquals("MyBaseInterceptor", list.get(0));
Assert.assertEquals("MyInterceptor", list.get(1));
}
/**
* Tests that the {@link SimpleStatelessBean} and its interceptor class {@link SimpleInterceptor}
* have all the expected fields/methods injected
*
* @throws Exception
*
*/
@Test
public void testInjection() throws Exception {
InjectionTester bean = ((InjectionTester) (ctx.lookup(("java:module/" + (SimpleStatelessBean.class.getSimpleName())))));
bean.assertAllInjectionsDone();
}
}
| true |
61dcd1bb5bc7459a130bdaaa106490e00cd52752 | Java | 09101204/my_hotel | /src/com/hotel/entity/Room.java | UTF-8 | 1,021 | 2.09375 | 2 | [] | no_license | package com.hotel.entity;
public class Room {
private int r_id;
private String r_name;
private String inStorey;
private int r_style_id;
private int pic_id;
private String r_state;
private int h_id;
public int getR_id() {
return r_id;
}
public int getPic_id() {
return pic_id;
}
public void setPic_id(int pic_id) {
this.pic_id = pic_id;
}
public void setR_id(int r_id) {
this.r_id = r_id;
}
public String getR_name() {
return r_name;
}
public void setR_name(String r_name) {
this.r_name = r_name;
}
public String getInStorey() {
return inStorey;
}
public void setInStorey(String inStorey) {
this.inStorey = inStorey;
}
public int getR_style_id() {
return r_style_id;
}
public void setR_style_id(int r_style_id) {
this.r_style_id = r_style_id;
}
public String getR_state() {
return r_state;
}
public void setR_state(String r_state) {
this.r_state = r_state;
}
public int getH_id() {
return h_id;
}
public void setH_id(int h_id) {
this.h_id = h_id;
}
}
| true |
d167b87252ad9f7922a4b10190de0eb38f831ffe | Java | InaEterovic/SoftArchitectureREDO | /Stack/src/test/refactoringgolf/stack/StackTest.java | UTF-8 | 2,716 | 3.34375 | 3 | [] | no_license | package refactoringgolf.stack;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class StackTest {
private Stack stack;
@Before
public void setup()
{
stack = new Stack();
}
@Test
public void emptyWhenCreated()
{
assertTrue(stack.isEmpty());
}
@Test
public void returnTheNumberOfItems()
{
stack.pushElement("1");
stack.pushElement("2");
assertEquals(2, stack.getSize());
}
@Test
public void emptyWhenPushAndPopOneItem()
{
stack.pushElement("1");
stack.popLastElement();
assertTrue(stack.isEmpty());
}
@Test
public void notEmptyWhenPush()
{
stack.pushElement("1");
assertFalse(stack.isEmpty());
}
@Test
public void pushAndPopOneItem()
{
stack.pushElement("1");
assertEquals("1", stack.popLastElement());
}
@Test
public void popTheLastWhenTwoItems()
{
stack.pushElement("1");
stack.pushElement("2");
assertEquals("2", stack.popLastElement());
}
@Test
public void pushAndPopTwoItems()
{
stack.pushElement("1");
stack.pushElement("2");
stack.popLastElement();
assertEquals("1", stack.popLastElement());
}
@Test
public void returnOneItemWithoutRemovingIt()
{
stack.pushElement("1");
stack.peekElement();
assertEquals("1", stack.peekElement());
}
@Test
public void returnThePositionWhereAnItemExits() {
stack.pushElement("1");
stack.pushElement("2");
stack.pushElement("3");
stack.pushElement("4");
assertEquals(3, stack.searchElement("2"));
}
@Test
public void returnMinusOneWhenItemDoesntExits()
{
assertEquals(-1, stack.searchElement("1"));
}
@Test
public void containAndItemAlreadyPushed()
{
stack.pushElement("1");
assertTrue(stack.isElementInStack("1"));
}
@Test
public void notContainAnItemNotPushed()
{
assertFalse(stack.isElementInStack("1"));
}
@Test
public void replaceTheValueOfAnElement()
{
stack.pushElement("6");
stack.pushElement("2");
stack.pushElement("6");
stack.replaceAll("6", "1");
assertEquals("1", stack.popLastElement());
stack.popLastElement();
assertEquals("1", stack.popLastElement());
}
@Test
public void throwExceptionWhenEmptyAndPop()
{
try
{
stack.popLastElement();
fail();
}
catch (IllegalStateException e)
{
}
}
}
| true |
be56025c485d234f3791ce2ad0da1fc0212db6d2 | Java | gitter-badger/cukedoctor | /cukedoctor-reporter/src/main/java/com/github/cukedoctor/api/ScenarioResults.java | UTF-8 | 857 | 2.46875 | 2 | [] | no_license | package com.github.cukedoctor.api;
import com.github.cukedoctor.api.model.Element;
import java.util.List;
/**
* Created by pestano on 04/06/15.
*/
public class ScenarioResults {
List<Element> passedScenarios;
List<Element> failedScenarios;
public ScenarioResults(List<Element> passedScenarios, List<Element> failedScenarios) {
this.passedScenarios = passedScenarios;
this.failedScenarios = failedScenarios;
}
public Integer getNumberOfScenariosPassed() {
return passedScenarios.size();
}
public Integer getNumberOfScenariosFailed() {
return failedScenarios.size();
}
public List<Element> getPassedScenarios() {
return passedScenarios;
}
public List<Element> getFailedScenarios() {
return failedScenarios;
}
public Object getNumberOfScenarios() {
return getNumberOfScenariosFailed() + getNumberOfScenariosPassed();
}
}
| true |
fcc8152b225661e2a8fa3c6713b98cfc22d646c1 | Java | asestes1/AcrpRepository | /BanditGDPSimulator/src/state_criteria/TmiRateCriteria.java | UTF-8 | 1,597 | 2.671875 | 3 | [] | no_license | package state_criteria;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import model.GdpAction;
import state_representation.DefaultState;
public class TmiRateCriteria<T extends DefaultState> implements StateCriteria<T>{
private final GdpAction gdpAction;
private final CircularFifoQueue<Boolean> history;
private final int historyLength;
public GdpAction getGdpAction() {
return gdpAction;
}
public TmiRateCriteria(GdpAction gdpAction, CircularFifoQueue<Boolean> history, int historyLength) {
super();
this.gdpAction = gdpAction;
this.history = new CircularFifoQueue<Boolean>(history);
this.historyLength = historyLength;
}
public TmiRateCriteria(GdpAction gdpAction, Integer historyLength) {
super();
this.gdpAction = gdpAction;
this.history = new CircularFifoQueue<Boolean>();
this.historyLength = historyLength;
}
@Override
public boolean isSatisfied(T state) {
if(historyLength < history.size()){
return false;
}
for(Boolean observation: history){
if(!observation){
return false;
}
}
return true;
}
@Override
public StateCriteria<T> updateHistory(T state) {
CircularFifoQueue<Boolean> newHistory = new CircularFifoQueue<Boolean>(history);
if(!state.getCurrentTime().isBefore(gdpAction.getGdpInterval().getStart())){
Integer gdpRate = gdpAction.getPaars().get(state.getCurrentTime());
Integer stateRate = state.getCapacity();
newHistory.add(gdpRate <= stateRate);
}
return new TmiRateCriteria<T>(gdpAction, newHistory, historyLength);
}
}
| true |
d9ee8a32a9343b6a39eaa379f3da75628949c704 | Java | Deepu206/Core-java | /variables_5/LocalVariableDemo5.java | UTF-8 | 290 | 2.859375 | 3 | [] | no_license | package variables_5;
public class LocalVariableDemo5 {
public static void main(String[] args) {
int x;
if (args.length>0) {
x=10;
// System.out.println(x);
}
/*System.out.println(x);*/ //The local variable x may not have been initialized
}
}
| true |
654f6389f6fcefda04de05118713de24736d8556 | Java | 2ndStack/2ndHotel | /src/latief/hotel/swing/JMainFrame.java | UTF-8 | 58,654 | 1.929688 | 2 | [] | no_license | /*
* created : Jun 18, 2011
* by : Latief
*/
/*
* JMainFrame.java
*
* Created on Jun 18, 2011, 10:24:31 AM
*/
package latief.hotel.swing;
import java.awt.CardLayout;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import latief.hotel.controller.HotelController;
import latief.hotel.model.Kamar;
import latief.hotel.model.Tamu;
import org.prambananswing.swing.combobox.BeanComboBoxModel;
import org.prambananswing.swing.table.BeanTableModel;
/**
*
* @author Latief
*/
public class JMainFrame extends javax.swing.JFrame {
/** Creates new form JMainFrame */
public JMainFrame() {
initComponents();
jScrollPaneDaftarTamu.getViewport().setOpaque(false);
jScrollPaneTagihan.getViewport().setOpaque(false);
hotelController = new HotelController();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanelCheckIn = new javax.swing.JPanel();
jLabelCheckInTitle = new javax.swing.JLabel();
jLabelCheckInNoIdentitas = new javax.swing.JLabel();
jLabelCheckInName = new javax.swing.JLabel();
jLabelCheckInDateIn = new javax.swing.JLabel();
jLabelCheckInDateOut = new javax.swing.JLabel();
jLabelCheckInKamar = new javax.swing.JLabel();
jLabelCheckInTotalCost = new javax.swing.JLabel();
jTextFieldCheckInNoIdentitas = new javax.swing.JTextField();
jTextFieldCheckInNama = new javax.swing.JTextField();
jDateChooserCheckInIn = new com.toedter.calendar.JDateChooser();
jDateChooserCheckInOut = new com.toedter.calendar.JDateChooser();
jComboBoxCheckInRoom = new javax.swing.JComboBox();
jTextFieldCheckInTotalBiaya = new javax.swing.JTextField();
jLabelCheckInSubmit = new javax.swing.JButton();
jPanelCheckOut = new javax.swing.JPanel();
jLabelCheckOutTitle = new javax.swing.JLabel();
jLabelCheckOutKamar = new javax.swing.JLabel();
jLabelCheckOutNoIdentitas = new javax.swing.JLabel();
jLabelCheckOutName = new javax.swing.JLabel();
jLabelCheckOutDateIn = new javax.swing.JLabel();
jLabelCheckOutDateOut = new javax.swing.JLabel();
jLabelCheckOutTotalCost = new javax.swing.JLabel();
jComboBoxCheckOutRoom = new javax.swing.JComboBox();
jTextFieldCheckOutNoIdentitas = new javax.swing.JTextField();
jTextFieldCheckOutNama = new javax.swing.JTextField();
jDateChooserCheckOutIn = new com.toedter.calendar.JDateChooser();
jDateChooserCheckOutOut = new com.toedter.calendar.JDateChooser();
jTextFieldCheckOutTotalBiaya = new javax.swing.JTextField();
jLabelCheckOutSubmit = new javax.swing.JButton();
jPanelDaftarTamu = new javax.swing.JPanel();
jLabelDaftarTamuTitle = new javax.swing.JLabel();
jScrollPaneDaftarTamu = new javax.swing.JScrollPane();
jTableDaftarTamu = new org.prambananswing.swing.table.JPTable();
jPanelTagihan = new javax.swing.JPanel();
jLabelTagihan = new javax.swing.JLabel();
jScrollPaneTagihan = new javax.swing.JScrollPane();
jTableDaftarTagihan = new org.prambananswing.swing.table.JPTable();
jPanelCariTamu = new javax.swing.JPanel();
jLabelCariTamu = new javax.swing.JLabel();
jLabelCariTamuNama = new javax.swing.JLabel();
jLabelCariTamuMetode = new javax.swing.JLabel();
jTextFieldCariTamuNama = new javax.swing.JTextField();
jComboBoxCariTamuMetode = new javax.swing.JComboBox();
jLabelCariTamuSubmit = new javax.swing.JButton();
jLabelCariNoIdentitas = new javax.swing.JLabel();
jLabelCariName = new javax.swing.JLabel();
jLabelCariDateIn = new javax.swing.JLabel();
jLabelCariDateOut = new javax.swing.JLabel();
jLabelCariKamar = new javax.swing.JLabel();
jLabelCariTotalCost = new javax.swing.JLabel();
jTextFieldCariNoIdentitas = new javax.swing.JTextField();
jTextFieldCariNama = new javax.swing.JTextField();
jDateChooserCariIn = new com.toedter.calendar.JDateChooser();
jDateChooserCariOut = new com.toedter.calendar.JDateChooser();
jTextFieldCariKamar = new javax.swing.JTextField();
jTextFieldCariTotalBiaya = new javax.swing.JTextField();
jBackground = new org.prambananswing.swing.panel.JPPanel();
jPanelCard = new org.prambananswing.swing.panel.JPPanel();
jPanelWelcome = new javax.swing.JPanel();
jPanelMenu = new org.prambananswing.swing.panel.JPPanel();
labelCheckIn = new javax.swing.JLabel();
labelCheckOut = new javax.swing.JLabel();
labelDaftarTamu = new javax.swing.JLabel();
labelTagihan = new javax.swing.JLabel();
labelCari = new javax.swing.JLabel();
jPanelCheckIn.setOpaque(false);
jLabelCheckInTitle.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInTitle.setText("Check In");
jLabelCheckInNoIdentitas.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInNoIdentitas.setText("No Identitas");
jLabelCheckInName.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInName.setText("Nama");
jLabelCheckInDateIn.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInDateIn.setText("Tanggal Check In");
jLabelCheckInDateOut.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInDateOut.setText("Tanggal Check Out");
jLabelCheckInKamar.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInKamar.setText("Kamar");
jLabelCheckInTotalCost.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckInTotalCost.setText("Total Biaya");
jDateChooserCheckInIn.setOpaque(false);
jDateChooserCheckInOut.setOpaque(false);
jComboBoxCheckInRoom.setOpaque(false);
jComboBoxCheckInRoom.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxCheckInRoomItemStateChanged(evt);
}
});
jTextFieldCheckInTotalBiaya.setEditable(false);
jLabelCheckInSubmit.setText("check in");
jLabelCheckInSubmit.setOpaque(false);
jLabelCheckInSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jLabelCheckInSubmitActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelCheckInLayout = new javax.swing.GroupLayout(jPanelCheckIn);
jPanelCheckIn.setLayout(jPanelCheckInLayout);
jPanelCheckInLayout.setHorizontalGroup(
jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCheckInLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCheckInTitle)
.addGroup(jPanelCheckInLayout.createSequentialGroup()
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCheckInDateIn)
.addComponent(jLabelCheckInNoIdentitas)
.addComponent(jLabelCheckInName)
.addComponent(jLabelCheckInDateOut)
.addComponent(jLabelCheckInKamar)
.addComponent(jLabelCheckInTotalCost))
.addGap(11, 11, 11)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldCheckInNama, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCheckInNoIdentitas, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jComboBoxCheckInRoom, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDateChooserCheckInOut, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDateChooserCheckInIn, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldCheckInTotalBiaya, javax.swing.GroupLayout.Alignment.LEADING))))
.addComponent(jLabelCheckInSubmit))
.addContainerGap(176, Short.MAX_VALUE))
);
jPanelCheckInLayout.setVerticalGroup(
jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCheckInLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelCheckInTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCheckInNoIdentitas)
.addComponent(jTextFieldCheckInNoIdentitas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCheckInName)
.addComponent(jTextFieldCheckInNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCheckInLayout.createSequentialGroup()
.addComponent(jDateChooserCheckInIn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jDateChooserCheckInOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCheckInLayout.createSequentialGroup()
.addComponent(jLabelCheckInDateIn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelCheckInDateOut)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxCheckInRoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCheckInKamar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckInLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldCheckInTotalBiaya, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCheckInTotalCost))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelCheckInSubmit)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelCheckOut.setOpaque(false);
jLabelCheckOutTitle.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutTitle.setText("Check Out");
jLabelCheckOutKamar.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutKamar.setText("Kamar");
jLabelCheckOutNoIdentitas.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutNoIdentitas.setText("No Identitas");
jLabelCheckOutName.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutName.setText("Nama");
jLabelCheckOutDateIn.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutDateIn.setText("Tanggal Check In");
jLabelCheckOutDateOut.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutDateOut.setText("Tanggal Check Out");
jLabelCheckOutTotalCost.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCheckOutTotalCost.setText("Total Biaya");
jComboBoxCheckOutRoom.setOpaque(false);
jComboBoxCheckOutRoom.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxCheckOutRoomItemStateChanged(evt);
}
});
jTextFieldCheckOutNoIdentitas.setEditable(false);
jTextFieldCheckOutNama.setEditable(false);
jDateChooserCheckOutIn.setEnabled(false);
jDateChooserCheckOutIn.setOpaque(false);
jDateChooserCheckOutOut.setEnabled(false);
jDateChooserCheckOutOut.setOpaque(false);
jTextFieldCheckOutTotalBiaya.setEditable(false);
jLabelCheckOutSubmit.setText("check out");
jLabelCheckOutSubmit.setOpaque(false);
jLabelCheckOutSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jLabelCheckOutSubmitActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelCheckOutLayout = new javax.swing.GroupLayout(jPanelCheckOut);
jPanelCheckOut.setLayout(jPanelCheckOutLayout);
jPanelCheckOutLayout.setHorizontalGroup(
jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCheckOutLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCheckOutTitle)
.addGroup(jPanelCheckOutLayout.createSequentialGroup()
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCheckOutDateIn)
.addComponent(jLabelCheckOutNoIdentitas)
.addComponent(jLabelCheckOutName)
.addComponent(jLabelCheckOutDateOut)
.addComponent(jLabelCheckOutKamar)
.addComponent(jLabelCheckOutTotalCost))
.addGap(11, 11, 11)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldCheckOutNama, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCheckOutNoIdentitas, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jDateChooserCheckOutOut, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDateChooserCheckOutIn, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldCheckOutTotalBiaya, javax.swing.GroupLayout.Alignment.LEADING))
.addComponent(jComboBoxCheckOutRoom, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabelCheckOutSubmit))
.addContainerGap(176, Short.MAX_VALUE))
);
jPanelCheckOutLayout.setVerticalGroup(
jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCheckOutLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelCheckOutTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCheckOutKamar)
.addComponent(jComboBoxCheckOutRoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCheckOutNoIdentitas)
.addComponent(jTextFieldCheckOutNoIdentitas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCheckOutName)
.addComponent(jTextFieldCheckOutNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCheckOutLayout.createSequentialGroup()
.addComponent(jDateChooserCheckOutIn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jDateChooserCheckOutOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCheckOutLayout.createSequentialGroup()
.addComponent(jLabelCheckOutDateIn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelCheckOutDateOut)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCheckOutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldCheckOutTotalBiaya, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCheckOutTotalCost))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelCheckOutSubmit)
.addContainerGap(87, Short.MAX_VALUE))
);
jPanelDaftarTamu.setOpaque(false);
jLabelDaftarTamuTitle.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelDaftarTamuTitle.setText("Daftar Tamu");
jScrollPaneDaftarTamu.setOpaque(false);
jTableDaftarTamu.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTableDaftarTamu.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jTableDaftarTamu.setOpaque(false);
jScrollPaneDaftarTamu.setViewportView(jTableDaftarTamu);
javax.swing.GroupLayout jPanelDaftarTamuLayout = new javax.swing.GroupLayout(jPanelDaftarTamu);
jPanelDaftarTamu.setLayout(jPanelDaftarTamuLayout);
jPanelDaftarTamuLayout.setHorizontalGroup(
jPanelDaftarTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDaftarTamuLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelDaftarTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneDaftarTamu, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
.addComponent(jLabelDaftarTamuTitle))
.addContainerGap())
);
jPanelDaftarTamuLayout.setVerticalGroup(
jPanelDaftarTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDaftarTamuLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelDaftarTamuTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPaneDaftarTamu, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
.addContainerGap())
);
jPanelTagihan.setOpaque(false);
jLabelTagihan.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelTagihan.setText("Tagihan");
jScrollPaneTagihan.setOpaque(false);
jTableDaftarTagihan.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTableDaftarTagihan.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jTableDaftarTagihan.setOpaque(false);
jScrollPaneTagihan.setViewportView(jTableDaftarTagihan);
javax.swing.GroupLayout jPanelTagihanLayout = new javax.swing.GroupLayout(jPanelTagihan);
jPanelTagihan.setLayout(jPanelTagihanLayout);
jPanelTagihanLayout.setHorizontalGroup(
jPanelTagihanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTagihanLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelTagihanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneTagihan, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
.addComponent(jLabelTagihan))
.addContainerGap())
);
jPanelTagihanLayout.setVerticalGroup(
jPanelTagihanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTagihanLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelTagihan)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPaneTagihan, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
.addContainerGap())
);
jPanelCariTamu.setOpaque(false);
jLabelCariTamu.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariTamu.setText("Pencarian Tamu");
jLabelCariTamuNama.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariTamuNama.setText("Nama");
jLabelCariTamuMetode.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariTamuMetode.setText("Metode");
jComboBoxCariTamuMetode.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Sequence", "Binary Iteration", "Binary Recursion" }));
jComboBoxCariTamuMetode.setOpaque(false);
jLabelCariTamuSubmit.setText("Cari");
jLabelCariTamuSubmit.setOpaque(false);
jLabelCariTamuSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jLabelCariTamuSubmitActionPerformed(evt);
}
});
jLabelCariNoIdentitas.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariNoIdentitas.setText("No Identitas");
jLabelCariName.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariName.setText("Nama");
jLabelCariDateIn.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariDateIn.setText("Tanggal Check In");
jLabelCariDateOut.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariDateOut.setText("Tanggal Check Out");
jLabelCariKamar.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariKamar.setText("Kamar");
jLabelCariTotalCost.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
jLabelCariTotalCost.setText("Total Biaya");
jTextFieldCariNoIdentitas.setEditable(false);
jTextFieldCariNama.setEditable(false);
jDateChooserCariIn.setEnabled(false);
jDateChooserCariIn.setOpaque(false);
jDateChooserCariOut.setEnabled(false);
jDateChooserCariOut.setOpaque(false);
jTextFieldCariKamar.setEditable(false);
jTextFieldCariTotalBiaya.setEditable(false);
javax.swing.GroupLayout jPanelCariTamuLayout = new javax.swing.GroupLayout(jPanelCariTamu);
jPanelCariTamu.setLayout(jPanelCariTamuLayout);
jPanelCariTamuLayout.setHorizontalGroup(
jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCariTamu)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCariTamuLayout.createSequentialGroup()
.addComponent(jLabelCariTamuMetode)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBoxCariTamuMetode, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCariTamuLayout.createSequentialGroup()
.addComponent(jLabelCariTamuNama)
.addGap(18, 18, 18)
.addComponent(jTextFieldCariTamuNama, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelCariTamuSubmit))
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCariDateIn)
.addComponent(jLabelCariName)
.addComponent(jLabelCariNoIdentitas))
.addGap(18, 18, 18)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextFieldCariNama, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
.addComponent(jDateChooserCariIn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCariNoIdentitas)))
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelCariDateOut)
.addComponent(jLabelCariKamar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jDateChooserCariOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCariKamar, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
.addComponent(jTextFieldCariTotalBiaya))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jLabelCariTotalCost))
.addGap(1, 1, 1)))
.addGap(127, 127, 127))
);
jPanelCariTamuLayout.setVerticalGroup(
jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelCariTamu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariTamuNama)
.addComponent(jTextFieldCariTamuNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariTamuMetode)
.addComponent(jComboBoxCariTamuMetode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCariTamuSubmit))
.addGap(18, 18, 18)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelCariTamuLayout.createSequentialGroup()
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariNoIdentitas)
.addComponent(jTextFieldCariNoIdentitas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariName)
.addComponent(jTextFieldCariNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addComponent(jLabelCariDateIn))
.addComponent(jDateChooserCariIn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDateChooserCariOut, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCariDateOut, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariKamar)
.addComponent(jTextFieldCariKamar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelCariTamuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelCariTotalCost)
.addComponent(jTextFieldCariTotalBiaya, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(47, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hotel");
jPanelCard.setBackground(new java.awt.Color(255, 255, 255));
jPanelCard.setIcon(null);
jPanelCard.setOpaque(false);
jPanelCard.setLayout(new java.awt.CardLayout());
jPanelWelcome.setOpaque(false);
javax.swing.GroupLayout jPanelWelcomeLayout = new javax.swing.GroupLayout(jPanelWelcome);
jPanelWelcome.setLayout(jPanelWelcomeLayout);
jPanelWelcomeLayout.setHorizontalGroup(
jPanelWelcomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 428, Short.MAX_VALUE)
);
jPanelWelcomeLayout.setVerticalGroup(
jPanelWelcomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 458, Short.MAX_VALUE)
);
jPanelCard.add(jPanelWelcome, "card2");
jPanelMenu.setBackground(new java.awt.Color(255, 255, 255));
jPanelMenu.setIcon(null);
jPanelMenu.setOpaque(false);
labelCheckIn.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
labelCheckIn.setText("Check In");
labelCheckIn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelCheckIn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelCheckInMouseClicked(evt);
}
});
labelCheckOut.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
labelCheckOut.setText("Check Out");
labelCheckOut.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelCheckOut.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelCheckOutMouseClicked(evt);
}
});
labelDaftarTamu.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
labelDaftarTamu.setText("Daftar Tamu");
labelDaftarTamu.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelDaftarTamu.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelDaftarTamuMouseClicked(evt);
}
});
labelTagihan.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
labelTagihan.setText("Tagihan");
labelTagihan.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelTagihan.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelTagihanMouseClicked(evt);
}
});
labelCari.setFont(new java.awt.Font("Comic Sans MS", 0, 11));
labelCari.setText("Pencarian");
labelCari.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelCari.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelCariMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelMenuLayout = new javax.swing.GroupLayout(jPanelMenu);
jPanelMenu.setLayout(jPanelMenuLayout);
jPanelMenuLayout.setHorizontalGroup(
jPanelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMenuLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelCheckIn, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(labelCheckOut, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(labelDaftarTamu, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(labelTagihan, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(labelCari, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE))
.addContainerGap())
);
jPanelMenuLayout.setVerticalGroup(
jPanelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMenuLayout.createSequentialGroup()
.addContainerGap()
.addComponent(labelCheckIn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelCheckOut)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelDaftarTamu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelTagihan)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelCari)
.addContainerGap(338, Short.MAX_VALUE))
);
javax.swing.GroupLayout jBackgroundLayout = new javax.swing.GroupLayout(jBackground);
jBackground.setLayout(jBackgroundLayout);
jBackgroundLayout.setHorizontalGroup(
jBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jBackgroundLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelCard, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
.addContainerGap())
);
jBackgroundLayout.setVerticalGroup(
jBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jBackgroundLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanelCard, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
.addComponent(jPanelMenu, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jBackground, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jBackground, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-616)/2, (screenSize.height-518)/2, 616, 518);
}// </editor-fold>//GEN-END:initComponents
private void labelCheckInMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCheckInMouseClicked
showPanelCheckIn();
}//GEN-LAST:event_labelCheckInMouseClicked
private void labelCheckOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCheckOutMouseClicked
showPanelCheckOut();
}//GEN-LAST:event_labelCheckOutMouseClicked
private void labelDaftarTamuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelDaftarTamuMouseClicked
showPanelDaftarTamu();
}//GEN-LAST:event_labelDaftarTamuMouseClicked
private void labelTagihanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelTagihanMouseClicked
showPanelTagihan();
}//GEN-LAST:event_labelTagihanMouseClicked
private void jLabelCheckInSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLabelCheckInSubmitActionPerformed
submitCheckIn();
}//GEN-LAST:event_jLabelCheckInSubmitActionPerformed
private void jComboBoxCheckInRoomItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxCheckInRoomItemStateChanged
showCost();
}//GEN-LAST:event_jComboBoxCheckInRoomItemStateChanged
private void jComboBoxCheckOutRoomItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxCheckOutRoomItemStateChanged
showTamuCheckOut();
}//GEN-LAST:event_jComboBoxCheckOutRoomItemStateChanged
private void jLabelCheckOutSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLabelCheckOutSubmitActionPerformed
submitCheckOut();
}//GEN-LAST:event_jLabelCheckOutSubmitActionPerformed
private void jLabelCariTamuSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLabelCariTamuSubmitActionPerformed
submitCari();
}//GEN-LAST:event_jLabelCariTamuSubmitActionPerformed
private void labelCariMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCariMouseClicked
showPanelCari();
}//GEN-LAST:event_labelCariMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.prambananswing.swing.panel.JPPanel jBackground;
private javax.swing.JComboBox jComboBoxCariTamuMetode;
private javax.swing.JComboBox jComboBoxCheckInRoom;
private javax.swing.JComboBox jComboBoxCheckOutRoom;
private com.toedter.calendar.JDateChooser jDateChooserCariIn;
private com.toedter.calendar.JDateChooser jDateChooserCariOut;
private com.toedter.calendar.JDateChooser jDateChooserCheckInIn;
private com.toedter.calendar.JDateChooser jDateChooserCheckInOut;
private com.toedter.calendar.JDateChooser jDateChooserCheckOutIn;
private com.toedter.calendar.JDateChooser jDateChooserCheckOutOut;
private javax.swing.JLabel jLabelCariDateIn;
private javax.swing.JLabel jLabelCariDateOut;
private javax.swing.JLabel jLabelCariKamar;
private javax.swing.JLabel jLabelCariName;
private javax.swing.JLabel jLabelCariNoIdentitas;
private javax.swing.JLabel jLabelCariTamu;
private javax.swing.JLabel jLabelCariTamuMetode;
private javax.swing.JLabel jLabelCariTamuNama;
private javax.swing.JButton jLabelCariTamuSubmit;
private javax.swing.JLabel jLabelCariTotalCost;
private javax.swing.JLabel jLabelCheckInDateIn;
private javax.swing.JLabel jLabelCheckInDateOut;
private javax.swing.JLabel jLabelCheckInKamar;
private javax.swing.JLabel jLabelCheckInName;
private javax.swing.JLabel jLabelCheckInNoIdentitas;
private javax.swing.JButton jLabelCheckInSubmit;
private javax.swing.JLabel jLabelCheckInTitle;
private javax.swing.JLabel jLabelCheckInTotalCost;
private javax.swing.JLabel jLabelCheckOutDateIn;
private javax.swing.JLabel jLabelCheckOutDateOut;
private javax.swing.JLabel jLabelCheckOutKamar;
private javax.swing.JLabel jLabelCheckOutName;
private javax.swing.JLabel jLabelCheckOutNoIdentitas;
private javax.swing.JButton jLabelCheckOutSubmit;
private javax.swing.JLabel jLabelCheckOutTitle;
private javax.swing.JLabel jLabelCheckOutTotalCost;
private javax.swing.JLabel jLabelDaftarTamuTitle;
private javax.swing.JLabel jLabelTagihan;
private org.prambananswing.swing.panel.JPPanel jPanelCard;
private javax.swing.JPanel jPanelCariTamu;
private javax.swing.JPanel jPanelCheckIn;
private javax.swing.JPanel jPanelCheckOut;
private javax.swing.JPanel jPanelDaftarTamu;
private org.prambananswing.swing.panel.JPPanel jPanelMenu;
private javax.swing.JPanel jPanelTagihan;
private javax.swing.JPanel jPanelWelcome;
private javax.swing.JScrollPane jScrollPaneDaftarTamu;
private javax.swing.JScrollPane jScrollPaneTagihan;
private org.prambananswing.swing.table.JPTable jTableDaftarTagihan;
private org.prambananswing.swing.table.JPTable jTableDaftarTamu;
private javax.swing.JTextField jTextFieldCariKamar;
private javax.swing.JTextField jTextFieldCariNama;
private javax.swing.JTextField jTextFieldCariNoIdentitas;
private javax.swing.JTextField jTextFieldCariTamuNama;
private javax.swing.JTextField jTextFieldCariTotalBiaya;
private javax.swing.JTextField jTextFieldCheckInNama;
private javax.swing.JTextField jTextFieldCheckInNoIdentitas;
private javax.swing.JTextField jTextFieldCheckInTotalBiaya;
private javax.swing.JTextField jTextFieldCheckOutNama;
private javax.swing.JTextField jTextFieldCheckOutNoIdentitas;
private javax.swing.JTextField jTextFieldCheckOutTotalBiaya;
private javax.swing.JLabel labelCari;
private javax.swing.JLabel labelCheckIn;
private javax.swing.JLabel labelCheckOut;
private javax.swing.JLabel labelDaftarTamu;
private javax.swing.JLabel labelTagihan;
// End of variables declaration//GEN-END:variables
/**
* Class untuk operasi logic dan perhitungan.
*/
private HotelController hotelController;
/**
*
* Tampilkan AbstractComponentCardLayout di layar
*
* @param componentCardLayout AbstractComponentCardLayout yang akan ditampilkan
*/
private void showCardLayout(JPanel componentCardLayout, String cardName){
jPanelCard.removeAll();
jPanelCard.add(componentCardLayout, cardName);
((CardLayout)jPanelCard.getLayout()).first(jPanelCard);
}
/**
* Tampilkan PanelCheckIn
*/
private void showPanelCheckIn(){
clearInputCheckIn();
reModelComboBoxKamarCheckIn();
showCardLayout(jPanelCheckIn, "cardCheckIn");
}
/**
* Tampilkan PanelCheckOut
*/
private void showPanelCheckOut(){
clearOutputCheckOut();
reModelComboBoxKamarCheckOut();
showCardLayout(jPanelCheckOut, "cardCheckOut");
}
/**
* Tampilkan PanelDaftarTamu
*/
private void showPanelDaftarTamu(){
showDaftarTamu();
showCardLayout(jPanelDaftarTamu, "cardDaftarTamu");
}
/**
* Tampilkan PanelTagihan
*/
private void showPanelTagihan(){
showTagihan();
showCardLayout(jPanelTagihan, "cardTagihan");
}
/**
* Tampilkan PanelCari
*/
private void showPanelCari(){
//showTagihan();
showCardLayout(jPanelCariTamu, "cardCari");
}
/**
* Kejadian ketika tombol CheckIn ditekan. Ketika ditekan maka Kamars tertentu
* akan tercatat telah dipesan oleh Tamu.
*/
private void submitCheckIn(){
//Jika tidak ada ruangan yang dipilih, abaikan proses selanjutnya.
if(jComboBoxCheckInRoom.getSelectedIndex() < 0){
clearInputCheckIn();
return;
}
//Jika tanggal check out lebih awal dari check in, abaikan proses selanjutnya
if(jDateChooserCheckInIn.getCalendar().getTimeInMillis() > jDateChooserCheckInOut.getCalendar().getTimeInMillis()){
jTextFieldCheckInTotalBiaya.setText("");
return;
}
//Ambil Kamar yang dipilih
Kamar kamarSelected = hotelController.findKamar(Integer.parseInt((jComboBoxCheckInRoom.getSelectedItem() + "").substring(0, 3)));
//Catat tamunya
Tamu tamu = new Tamu();
tamu.setNoIdentitas(jTextFieldCheckInNoIdentitas.getText().trim());
tamu.setNama(jTextFieldCheckInNama.getText().trim());
tamu.setCheckIn(jDateChooserCheckInIn.getCalendar());
tamu.setCheckOut(jDateChooserCheckInOut.getCalendar());
tamu.setKamar(kamarSelected);
tamu.setTotalBiaya(hotelController.calculateCost(kamarSelected, tamu.getCheckIn(), tamu.getCheckOut()));
//Tambah ke daftar tamu
hotelController.addTamu(tamu);
reModelComboBoxKamarCheckIn();
clearInputCheckIn();
}
/**
* Kejadian ketika tombol check out ditekan. Ketika check out maka Kamar
* tertentu akan kosong dan Tamu berkurang jumlahnya.
*/
private void submitCheckOut(){
//Jika tidak ada kamar yang dipilih, abaikan proses selanjutnya.
if(jComboBoxCheckOutRoom.getSelectedIndex() < 0){
clearOutputCheckOut();
return;
}
//Ambil kamar mana yang dipilih
Kamar kamarSelected = hotelController.findKamar(Integer.parseInt((jComboBoxCheckOutRoom.getSelectedItem() + "").substring(0, 3)));
//Hapus Tamu yang check out dari daftar Tamu
hotelController.removeTamu(kamarSelected);
reModelComboBoxKamarCheckOut();
clearOutputCheckOut();
}
/**
* Kejadian tombol cari ditekan.
*/
private void submitCari(){
clearOutputCari();
if(jTextFieldCariTamuNama.getText().trim().isEmpty()){
return;
}
String nama = jTextFieldCariTamuNama.getText().trim();
Tamu tamu = hotelController.search(nama, jComboBoxCariTamuMetode.getSelectedIndex());
if(tamu == null){
JOptionPane.showConfirmDialog(this, "Tamu tidak ditemukan", "Tidak Ditemukan", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE);
return;
}
jTextFieldCariNoIdentitas.setText(tamu.getNoIdentitas());
jTextFieldCariNama.setText(tamu.getNama());
jDateChooserCariIn.setCalendar(tamu.getCheckIn());
jDateChooserCariOut.setCalendar(tamu.getCheckOut());
jTextFieldCariKamar.setText(tamu.getKamar().toString());
jTextFieldCariTotalBiaya.setText(tamu.getTotalBiaya() + "");
}
/**
* Tampilkan Daftar Tamu ke dalam jTableDaftarTamu
*/
private void showDaftarTamu(){
String [] columnNames = {"No Identitas", "Nama", "Check In", "Check Out", "Kamar", "Total Biaya"};
boolean [] columnVisible = {true,true,true,true,true,true};
setTableModel(jTableDaftarTamu, hotelController.getTamus(), columnNames, columnVisible);
}
/**
* Tampilkan Daftar Tagihan ke dalam jTableDaftarTagihan
*/
private void showTagihan(){
String [] columnNames = {"No Kamar","Jenis Kamar", "No Identitas", "Nama", "Check In", "Check Out","Total Biaya"};
boolean [] columnVisible = {true,true,true,true,true,true,true};
setTableModel(jTableDaftarTagihan, hotelController.getTagihans(), columnNames, columnVisible);
}
/**
* Tampilkan Total biaya ketika ada Kamar yang dipilih.
*/
private void showCost(){
//Jika ada Kamar/CheckIn/CheckOut yang dipilih, abaikan proses selanjutnya.
if(jComboBoxCheckInRoom.getSelectedIndex() < 0
&& jDateChooserCheckInIn.getCalendar() == null
&& jDateChooserCheckInOut.getCalendar() == null){
jTextFieldCheckInTotalBiaya.setText("");
return;
}
//Jika tanggal check out lebih awal dari check in, abaikan proses selanjutnya
if(jDateChooserCheckInIn.getCalendar().getTimeInMillis() > jDateChooserCheckInOut.getCalendar().getTimeInMillis()){
jTextFieldCheckInTotalBiaya.setText("");
return;
}
//Ambil Kamar yang dipilih
Kamar kamarSelected = hotelController.findKamar(Integer.parseInt((jComboBoxCheckInRoom.getSelectedItem() + "").substring(0, 3)));
//Hitung biaya, kemudian tampilkan.
int cost = hotelController.calculateCost(kamarSelected, jDateChooserCheckInIn.getCalendar(), jDateChooserCheckInOut.getCalendar());
jTextFieldCheckInTotalBiaya.setText("" + cost);
}
/**
* Tampilkan data Tamu yang akan di-check out di PanelCheckOut.
*/
private void showTamuCheckOut(){
//Jika tidak ada Kamar yang akan di checkout, abaikan proses selanjutnya.
if(jComboBoxCheckOutRoom.getSelectedIndex() < 0){
return;
}
//Ambil Kamar yang akan di check out.
Kamar kamarSelected = hotelController.findKamar(Integer.parseInt((jComboBoxCheckOutRoom.getSelectedItem() + "").substring(0, 3)));
//Tampilakn data Tamu yang akan di check out di Component Output PanelCheckOut
Tamu tamu = hotelController.findTamu(kamarSelected);
jTextFieldCheckOutNoIdentitas.setText(tamu.getNoIdentitas());
jTextFieldCheckOutNama.setText(tamu.getNama());
jDateChooserCheckOutIn.setCalendar(tamu.getCheckIn());
jDateChooserCheckOutOut.setCalendar(tamu.getCheckOut());
jTextFieldCheckOutTotalBiaya.setText(tamu.getTotalBiaya() + "");
}
/**
* Bersihkan Component input pada PanelCheckIn
*/
private void clearInputCheckIn(){
jTextFieldCheckInNoIdentitas.setText("");
jTextFieldCheckInNama.setText("");
jDateChooserCheckInIn.setCalendar(null);
jDateChooserCheckInOut.setCalendar(null);
jComboBoxCheckInRoom.setSelectedIndex(-1);
jTextFieldCheckInTotalBiaya.setText("");
}
/**
* Bersihkan Component output pada Panel CheckOut
*/
private void clearOutputCheckOut(){
jTextFieldCheckOutNoIdentitas.setText("");
jTextFieldCheckOutNama.setText("");
jDateChooserCheckOutIn.setCalendar(null);
jDateChooserCheckOutOut.setCalendar(null);
jComboBoxCheckOutRoom.setSelectedIndex(-1);
jTextFieldCheckOutTotalBiaya.setText("");
}
/**
* Bersihkan Component input pada PanelCheckIn
*/
private void clearOutputCari(){
jTextFieldCariNoIdentitas.setText("");
jTextFieldCariNama.setText("");
jDateChooserCariIn.setCalendar(null);
jDateChooserCariOut.setCalendar(null);
jTextFieldCariKamar.setText("");
jTextFieldCariTotalBiaya.setText("");
}
/**
* Di modelin ulang untuk jComboBoxCheckInRoom agar menampilkan data kamar yang kosong.
*/
private void reModelComboBoxKamarCheckIn(){
setComboBoxModelKamar(jComboBoxCheckInRoom, hotelController.findEmptyKamars());
}
/**
* Di modelin ulang untuk jComboBoxCheckOutRoom agar menampilkan data kamar yang isi.
*/
private void reModelComboBoxKamarCheckOut(){
setComboBoxModelKamar(jComboBoxCheckOutRoom, hotelController.findFullKamars());
}
/**
* Set JComboBox dengan daftar Kamar.
* @param comboBox
* @param kamars
*/
private void setComboBoxModelKamar(JComboBox comboBox, List<Kamar> kamars){
boolean [] fieldVisible = {true,false,true};
BeanComboBoxModel model = new BeanComboBoxModel(kamars, fieldVisible, " - ");
comboBox.setModel(model);
}
/**
* Menampilkan Daftar data ke dalam JTable.
* @param table
* @param data
* @param columnNames
* @param columnVisible
*/
private void setTableModel(JTable table, List data, String [] columnNames, boolean [] columnVisible){
BeanTableModel model = new BeanTableModel(data, columnNames);
model.setColumnVisible(columnVisible);
table.setModel(model);
}
}
| true |
a6c67a075af82d0c2f07536e1fbf65d31d57b006 | Java | shy942/EGITrepoOnlineVersion | /QueryReformulation-master 2/data/processed/SessionPerspective.java | UTF-8 | 696 | 2.15625 | 2 | [] | no_license | /***/
package org.eclipse.ui.tests.api;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
/**
* This class tests the persistance of a perspective.
*/
public class SessionPerspective implements IPerspectiveFactory {
public static String ID = "org.eclipse.ui.tests.api.SessionPerspective";
/**
* @see IPerspectiveFactory#createInitialLayout(IPageLayout)
*/
@Override
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
layout.addView(SessionView.VIEW_ID, IPageLayout.LEFT, 0.33f, editorArea);
layout.addPlaceholder(MockViewPart.ID4, IPageLayout.RIGHT, .033f, editorArea);
}
}
| true |
7bd9194f65ff75818a55f517ecfb46aedfcdb5af | Java | michalPrzepiorka/lotto-api | /src/main/java/com/example/lotto/lottoPlus/LottoPlusController.java | UTF-8 | 2,251 | 2.390625 | 2 | [] | no_license | package com.example.lotto.lottoPlus;
import com.example.lotto.mainLotto.LottoDateHelper;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author Y510p
* @project lotto
* @date 17.01.2020
**/
@RestController
@RequestMapping("/lottoPlus")
public class LottoPlusController {
private LottoPlusRepository lottoPlusRepository;
public LottoPlusController(LottoPlusRepository lottoPlusRepository) {
this.lottoPlusRepository = lottoPlusRepository;
}
@GetMapping
public Iterable<LottoPlusData> findAllLottoDraw() {
Iterable<LottoPlusData> dbResult = lottoPlusRepository.findAll();
List<LottoPlusData> result = new ArrayList<>();
dbResult.forEach(result::add);
result.sort(Comparator.comparing(o -> getDate(o.getDate())));
Collections.reverse(result);
return result;
}
private Date getDate(String str) {
try {
return new SimpleDateFormat("dd-MM-yyyy").parse(str);
} catch (ParseException e) {
return null;
}
}
@GetMapping("/{id}")
public Optional<LottoPlusData> findByLottoDrawId(@PathVariable String id) {
return lottoPlusRepository.findById(id);
}
@GetMapping("/search")
public LottoPlusData getLottoDrawByDate(@RequestParam(required = false) String date) {
if (date == null) {
return lottoPlusRepository.findAll().iterator().next();
} else {
return lottoPlusRepository.findFirstByDate(date);
}
}
@PostMapping("/check")
public LottoDateHelper getLotteryNumbers(@RequestBody LottoDateHelper date) {
LottoPlusData firstByDate = lottoPlusRepository.findFirstByDate(date.getDate());
if (firstByDate == null) {
return null;
}
LottoDateHelper result = new LottoDateHelper(date.getDate());
String[] split = firstByDate.getNumbers().split(" ");
for (String s : split) {
int number = Integer.parseInt(s);
if (date.getNumbers().contains(number)) {
result.getNumbers().add(number);
}
}
return result;
}
}
| true |
68a778d82da63619c3ecc66abce2eba0786e552b | Java | Marat311/Spring2020_JavaPractice | /src/day41_Inheritance/Task02/SavingAccount.java | UTF-8 | 315 | 2.203125 | 2 | [] | no_license | package day41_Inheritance.Task02;
/*
create sub class of BankAccount and name it SavingAccount
variables: accountNumber, accountHolder, balance, interestRate
methods: deposit, showBalance
*/
public class CheckingAccount {
/*
accountNumber
accountHolder
Balance
interestRate
*/
}
| true |