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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
47730a1d5d2a635654c404a5105ddf46b2749237 | Java | wezdenko/hermes-java | /src/database/classes/Position.java | UTF-8 | 1,352 | 3.359375 | 3 | [] | no_license | package database.classes;
public class Position {
private int id;
private String name;
private float maxSalary;
private float minSalary;
public Position() {}
public Position(int id, String name, float minSalary, float maxSalary) {
setId(id);
setName(name);
setMinSalary(minSalary);
setMaxSalary(maxSalary);
}
/// Setters ///
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
// check name length limit
this.name = name;
}
public void setMaxSalary(float maxSalary) {
this.maxSalary = Math.round(maxSalary * 100) / 100;
}
public void setMinSalary(float minSalary) {
this.minSalary = Math.round(minSalary * 100) / 100;
}
/// Getters ///
public int getId() {
return this.id;
}
public String getId_S() {
return Converter.IntToString(this.id);
}
public String getName() {
return this.name;
}
public float getMaxSalary() {
return this.maxSalary;
}
public String getMaxSalary_S() {
return Converter.DoubleToString(this.maxSalary);
}
public float getMinSalary() {
return this.minSalary;
}
public String getMinSalary_S() {
return Converter.DoubleToString(this.minSalary);
}
} | true |
5256b5733b186b410408d96ec03827c2dbe18dcb | Java | appleshow/monitor | /src/main/java/com/aps/monitor/service/impl/MenuConfigServiceImpl.java | UTF-8 | 2,908 | 2.03125 | 2 | [] | no_license | package com.aps.monitor.service.impl;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import com.aps.monitor.comm.*;
import org.springframework.stereotype.Service;
import com.aps.monitor.dao.ComFormMapper;
import com.aps.monitor.dao.ComMenuMapper;
import com.aps.monitor.model.ComForm;
import com.aps.monitor.model.ComMenu;
import com.aps.monitor.service.IMenuConfigService;
@Service
public class MenuConfigServiceImpl implements IMenuConfigService {
@Resource
private ComFormMapper comFormMapper;
@Resource
private ComMenuMapper comMenuMapper;
/**
*
* @param httpSession
* @param requestRefPar
* @param responseData
*/
@Override
public void referMenu(HttpSession httpSession, RequestRefPar requestRefPar, ResponseData responseData) {
ComMenu comMenu = new ComMenu();
List<ComMenu> comMenus;
comMenu.setFarMenuId(requestRefPar.getIntegerPar("farMenuId"));
comMenu.setMenuName(requestRefPar.getStringPar("menuName"));
comMenus = comMenuMapper.selectByCondition(comMenu);
responseData.setData(comMenus);
}
/**
*
* @param httpSession
* @param requestMdyPar
* @param responseData
*/
@Override
public void modifyMenu(HttpSession httpSession, RequestMdyPar requestMdyPar, ResponseData responseData) {
int personId;
boolean jsonParseException = false;
String type;
Date now = new Date();
Map<String, String> rowData;
ComMenu comMenu;
for (int row = 0; row < requestMdyPar.getParCount(); row++) {
rowData = requestMdyPar.getInPar().get(row);
type = requestMdyPar.getType(rowData);
comMenu = (ComMenu) JsonUtil.readValueAsObject(rowData, ComMenu.class);
if (null != comMenu) {
personId = requestMdyPar.getPersonId(httpSession, now, rowData);
switch (type) {
case CommUtil.MODIFY_TYPE_INSERT:
comMenu.setItime(now);
comMenu.setIperson(personId);
comMenu.setUtime(now);
comMenu.setUperson(personId);
comMenuMapper.insertSelective(comMenu);
break;
case CommUtil.MODIFY_TYPE_UPDATE:
comMenuMapper.updateByPrimaryKeySelective(comMenu);
break;
case CommUtil.MODIFY_TYPE_DELETE:
comMenuMapper.deleteByPrimaryKey(comMenu.getMenuId());
break;
default:
break;
}
} else {
jsonParseException = true;
break;
}
}
if (jsonParseException) {
responseData.setCode(-108);
responseData.setMessage("数据处理异常,请检查输入数据!");
} else {
responseData.setCode(0);
}
}
/**
*
* @param httpSession
* @param requestRefPar
* @param responseData
*/
@Override
public void referAllForms(HttpSession httpSession, RequestRefPar requestRefPar, ResponseData responseData) {
ComForm comForm = new ComForm();
List<ComForm> comForms;
comForms = comFormMapper.selectCombData(comForm);
responseData.setData(comForms);
}
}
| true |
afb712ab0da033bf08298255946402ca5806c703 | Java | VipJayce/FileShare | /test/test/gap/warning/comparator/MyTest.java | UTF-8 | 2,543 | 2.125 | 2 | [] | no_license | /**
* 字段名称:MyTest
*/
package test.gap.warning.comparator;
import junit.framework.TestCase;
/*************************************
* @(C)Copyright 北京瑞友科技股份有限公司上海分公司. 2013
* @作者: 谭彦军
* @创建时间:2013-6-24 上午02:14:16
* @文件名:MyTest.java
* @描述:
*************************************/
public class MyTest extends TestCase {
public void test(){
StringBuilder GET_AGENT_BILLITEM_BY_BILLID = new StringBuilder()
.append("with lp as (select * from agent_fin_bill_item_mod modv where modv.BILLID = ? ) ")
.append("select emp_id, emp_name, bill_id, service_year_month, emp_post_id, emp_code, ")
.append("LISTAGG(product_id || '~' || product_name || '~' || product_type || '~' || ")
.append("nvl(to_char(e_base, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(amount, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(p_ratio, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(p_money, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(e_ratio, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(e_money, 'FM9999999.0099'), '^') || '~' || ")
.append("nvl(to_char(0), '^') || '~' || nvl(to_char(city_name), '^') || '~' || ")
.append("nvl(to_char(is_sum), '^'), ")
.append(" '~') WITHIN GROUP(ORDER BY product_type, serial_no) pro ")
.append("from (select alluser.*, t3.e_base, t3.amount, t3.p_ratio, t3.p_money,t3.e_ratio, t3.e_money, t3.is_sum, t3.city_name ")
.append("from (select distinct emp_id, emp_name, emp_code, service_year_month, product_type, product_id, product_name, serial_no, billid bill_id, emp_post_id from lp) alluser ")
.append("left join (select t4.*, sp2.city_name from lp t4 left join (select sp.*, pb.city_name from pb_security_product sp ")
.append("left join pb_city pb on pb.id = sp.city_id) sp2 on sp2.id = t4.security_product_id) t3 ")
.append("on alluser.emp_id = t3.emp_id ")
.append("and alluser.emp_post_id = t3.emp_post_id and alluser.product_id = t3.product_id ")
.append("and alluser.service_year_month = t3.service_year_month ")
.append(" ) where is_sum !='0' group by emp_id, emp_name, emp_code, service_year_month, bill_id, emp_post_id");
System.out.println(GET_AGENT_BILLITEM_BY_BILLID.toString());
}
}
| true |
fba280e2eccec9725b3844a70b4850512150b4dc | Java | thuurzz/Java | /Impacta/Tarefas/IDE/POO/POO_CC3A/src/main/java/Aula_02_Decisao/Ex_02_Ordena3Num.java | UTF-8 | 1,388 | 3.8125 | 4 | [
"MIT"
] | permissive | /*
* 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 Aula_02_Decisao;
import java.util.Scanner;
/**
*
* @author megazord
*/
public class Ex_02_Ordena3Num {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Digite um número inteiro n1: ");
int n1 = entrada.nextInt();
System.out.println("Digite um número inteiro n2: ");
int n2 = entrada.nextInt();
System.out.println("Digite um número inteiro n3: ");
int n3 = entrada.nextInt();
int aux;
// Colocar o meor de todos em n1
if (n1 > n2 || n1 > n3){
if (n2 < n3){
// trocar n1 com n2
aux = n1;
n1 = n2;
n2 = aux;
} else {
// trocar n1 com n3
aux = n1;
n1 = n3;
n3 = aux;
}
}
// Intermediário em n2 é o mairo de todos em n3
if (n2 > n3) {
// trocar n1 com n2
aux = n2;
n2 = n3;
n3 = aux;
}
// Exibe resultado
System.out.printf("%d, %d, %d", n1, n2, n3);
}
}
| true |
287dc70d1af1469224a3969026cd60cfc322dffc | Java | solq360/chat | /app/src/main/java/org/son/chat/core/FileAudio.java | UTF-8 | 2,863 | 2.65625 | 3 | [] | no_license | package org.son.chat.core;
import org.son.chat.util.SDCardUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* 文件处理语音
* Created by luojie on 15/4/22.
*/
public class FileAudio extends AbstractAudio {
private String fileName = SDCardUtil.getPath("/a.pcm");
@Override
public void record() {
if (this.recordRun) {
return;
}
createRecord();
audioRecord.startRecording();
this.recordRun = true;
new Thread(new Runnable() {
@Override
public void run() {
byte[] buf = new byte[1024 * 4];
File file = new File(fileName);
DataOutputStream ds = null;
try {
ds = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
while (recordRun) {
int len = audioRecord.read(buf, 0, buf.length);
// write
ds.write(buf, 0, len);
}
ds.flush();
ds.close();
closeRecord();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void play() {
if (!this.recordRun) {
return;
}
createPlay();
audioTrack.play();
this.recordRun = false;
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(fileName);
DataInputStream is = null;
try {
is = new DataInputStream(new BufferedInputStream(new FileInputStream(file), 1024 * 8));
int i = 0;
final int len = 1024 * 512;
byte[] pBuf = new byte[len];
System.out.println("play len :" + pBuf.length);
System.out.println("file len :" + file.length());
while (is.available() > 0) {
pBuf[i] = (byte) is.readByte();
i++;
if (i >= len) {
audioTrack.write(pBuf, 0, i - 1);
i = 0;
}
}
is.close();
if (i > 0) {
audioTrack.write(pBuf, 0, i - 1);
}
closePlay();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
| true |
055122c437806787cc8e5883d7b2cfdb9647db3c | Java | trieu/leo-cdp | /core-leo-cms/src/test/java/test/crawler/pending/tikiVn_ProductJsoupDocToProductItem.java | UTF-8 | 3,943 | 2.0625 | 2 | [] | no_license | package test.crawler.pending;
import java.util.List;
import java.util.stream.Collectors;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import leotech.cdp.model.business.ProductItem;
import leotech.crawler.util.JsoupParserUtil;
import rfx.core.util.HttpClientUtil;
import rfx.core.util.StringUtil;
import test.crawler.ProductJsoupDocToProductItem;
public class tikiVn_ProductJsoupDocToProductItem implements ProductJsoupDocToProductItem{
public boolean parse(Document srcDoc, ProductItem dstProductItem) throws Exception {
String ogType = JsoupParserUtil.getAttr(srcDoc, "meta[property='og:type']", "content").toLowerCase();
if( ! "website".equals(ogType) ) {
//skip if not a product
return false;
}
// start common parser for Open Graph
String title = JsoupParserUtil.getAttr(srcDoc, "meta[property='og:title']", "content");
if (StringUtil.isEmpty(title)) {
title = JsoupParserUtil.getText(srcDoc, "title");
}
String description = JsoupParserUtil.getAttr(srcDoc, "meta[property='og:description']", "content");
String productImage = JsoupParserUtil.getAttr(srcDoc, "meta[property='og:image']", "content").replace("http:","https:");
String salePrice = JsoupParserUtil.getAttr(srcDoc, "div.summary meta[itemprop='price']", "content");
String priceCurrency = JsoupParserUtil.getAttr(srcDoc, "div.summary meta[itemprop='priceCurrency']", "content");
String fullUrl = JsoupParserUtil.getAttr(srcDoc, "div.summary meta[itemprop='url']", "content");
String siteName = JsoupParserUtil.getAttr(srcDoc, "meta[property='og:site_name']", "content");
// No itemCondition property
// String itemCondition = JsoupParserUtil.getAttr(doc, "link[itemprop='itemCondition']", "href");
String availability = JsoupParserUtil.getAttr(srcDoc, "link[itemprop='availability']", "href");
String brand = JsoupParserUtil.getAttr(srcDoc, "div.brand meta[itemprop='name']", "content");
List<String> categories = JsoupParserUtil.getTexts(srcDoc, "a[class='Breadcrumb__Item-sc-1a3qw0s-1 hjpGLl']:gt(0):not(a[href='#'])");
String sku = JsoupParserUtil.getText(srcDoc, "span[itemprop='sku']");
String originalPrice = JsoupParserUtil.getText(srcDoc, "p[class='original-price']").replace("Giá thị trư�ng:", "").replace("₫", "")
.replace(".", "").trim();
String sellerName = JsoupParserUtil.getText(srcDoc, "a[class='seller-name']");
List<String> promoCodes = JsoupParserUtil.getTexts(srcDoc, "div.coupon span[class='coupon-code']");
dstProductItem.setPromoCodes(promoCodes);
List<Double> promoPrices = JsoupParserUtil.getTexts(srcDoc, "div.coupon span[class='coupon-price']").stream()
.map(priceStr -> Double.valueOf(priceStr.replace("â‚«", "").replace(".", "").trim()))
.collect(Collectors.toList());
dstProductItem.setPromoPrices(promoPrices);
dstProductItem.setSku(sku);
dstProductItem.setName(title);
dstProductItem.setDescription(description);
dstProductItem.setImage(productImage);
dstProductItem.setSalePrice(salePrice);
dstProductItem.setPriceCurrency(priceCurrency);
dstProductItem.setFullUrl(fullUrl);
dstProductItem.setSiteName(siteName);
// dstProductItem.setItemCondition(itemCondition);
dstProductItem.setAvailability(availability);
dstProductItem.setOriginalPrice(originalPrice);
dstProductItem.setCategories(categories);
dstProductItem.setBrand(brand);
dstProductItem.setSellerName(sellerName);
return true;
}
public static void main(String[] args) throws Exception {
ProductJsoupDocToProductItem test = new tikiVn_ProductJsoupDocToProductItem();
String url = "https://tiki.vn/man-hinh-dell-u2419h-24inch-fullhd-8ms-60hz-ips-hang-chinh-hang-p7986170.html?spid=7986171&src=home-deal-hot";
ProductItem p = new ProductItem("");
p.setSiteDomain("tiki.vn");
if( test.parse(Jsoup.connect(url).get(), p) && !p.isEmpty()) {
System.out.println(p);
}
}
}
| true |
c71f19dc0c315b9af9dc15cd2e6006e8a6bd8d43 | Java | stalkerpnv/CharacterStreams | /src/oopexample/Cat.java | UTF-8 | 209 | 3.015625 | 3 | [] | no_license | package oopexample;
public class Cat extends Animal {
Cat(String name, String color, int age) {
super(name, color, age);
}
public void swim(){
System.out.println("swim");
}
}
| true |
3df35701861ed10f6438d402f7c855e6205871f1 | Java | reeceyang/AP-Computer-Science | /src/U6A3/U6A3.java | UTF-8 | 2,583 | 3.328125 | 3 | [] | no_license | // Reece Yang
//
// This Java project (applet) will compare the Sequential Search to the
// Binary Search.
package U6A3;
import javax.swing.JApplet;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.Container;
public class U6A3 extends JApplet
{
private int[] array = new int[300];
private int[] targets = {2, 2629, 11176, 27032, 43661};
public void init()
{
setSize(1250, 750);
JTextArea out = new JTextArea();
out.setFont(new Font("Monospaced", Font.BOLD, 16));
out.append("The Array\n\n");
BuildArray();
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 15; j++)
{
out.append(array[i * 15 + j] + "\t");
}
out.append("\n");
}
out.append("\n\n");
out.append(
"Search Comparisons using the # of visits to the Array\n\n");
out.append("Number\tSequential\tBinary\n");
out.append("------\t----------\t------\n");
int numberOfTargets = targets.length;
for (int i = 0; i < numberOfTargets; i++)
{
int target = targets[i];
int sequentialVisits = Sequential(target);
int binaryVisits = Binary(target);
out.append(target
+ "\t"
+ (sequentialVisits == -1 ? "Not Found" : sequentialVisits + "\t")
+ "\t"
+ (binaryVisits == -1 ? "Not Found" : binaryVisits) + "\n");
}
Container container = getContentPane();
container.add(out);
}
public void BuildArray()
{
for (int i = 0; i < 300; i++)
{
array[i] = (int) (i * i * 0.5 + i * 0.5 + 1);
}
}
public int Sequential(int target)
{
int length = array.length;
for (int i = 0; i < length; i++)
{
if (array[i] == target)
{
return i + 1;
}
}
return -1;
}
public int Binary(int target)
{
int low = 0;
int high = array.length - 1;
int mid, dif, count = 0;
while (low <= high)
{
count++;
mid = (low + high) / 2;
dif = array[mid] - target;
if (dif == 0)
{
return count;
}
else if (dif < 0)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
}
| true |
c8e1f295d32d2307e860b92dba84742182c97ca8 | Java | bellmit/zycami-ded | /src/main/java/com/xiaomi/clientreport/data/PerfClientReport.java | UTF-8 | 1,563 | 1.71875 | 2 | [] | no_license | /*
* Decompiled with CFR 0.151.
*
* Could not load the following classes:
* org.json.JSONException
* org.json.JSONObject
*/
package com.xiaomi.clientreport.data;
import com.xiaomi.channel.commonutils.logger.b;
import com.xiaomi.clientreport.data.a;
import org.json.JSONException;
import org.json.JSONObject;
public class PerfClientReport
extends a {
private static final long DEFAULT_VALUE = 255L;
public int code;
public long perfCounts;
public long perfLatencies;
public PerfClientReport() {
long l10;
this.perfCounts = l10 = (long)-1;
this.perfLatencies = l10;
}
public static PerfClientReport getBlankInstance() {
PerfClientReport perfClientReport = new PerfClientReport();
return perfClientReport;
}
public JSONObject toJson() {
String string2;
JSONObject jSONObject;
try {
jSONObject = super.toJson();
if (jSONObject == null) {
return null;
}
string2 = "code";
}
catch (JSONException jSONException) {
b.a(jSONException);
return null;
}
int n10 = this.code;
jSONObject.put(string2, n10);
string2 = "perfCounts";
long l10 = this.perfCounts;
jSONObject.put(string2, l10);
string2 = "perfLatencies";
l10 = this.perfLatencies;
jSONObject.put(string2, l10);
return jSONObject;
}
public String toJsonString() {
return super.toJsonString();
}
}
| true |
3211fa1335f98c2cf08a796e3e69e9de9cf1c5d9 | Java | fayyua/onetwo | /modules/orm/src/main/java/org/onetwo/common/fish/JFishSQLSymbolManagerImpl.java | UTF-8 | 1,742 | 2.28125 | 2 | [] | no_license | package org.onetwo.common.fish;
import java.util.Map;
import org.onetwo.common.db.ExtQuery;
import org.onetwo.common.db.sqlext.DefaultSQLDialetImpl;
import org.onetwo.common.db.sqlext.DefaultSQLSymbolManagerImpl;
import org.onetwo.common.db.sqlext.SQLDialet;
import org.onetwo.common.db.sqlext.SQLSymbolManager;
import org.onetwo.common.fish.orm.DBDialect;
import org.onetwo.common.fish.orm.JFishMappedEntry;
import org.onetwo.common.fish.orm.MappedEntryManager;
public class JFishSQLSymbolManagerImpl extends DefaultSQLSymbolManagerImpl {
public static final SQLSymbolManager SQL_SYMBOL_MANAGER = create();
public static JFishSQLSymbolManagerImpl create(){
SQLDialet sqlDialet = new DefaultSQLDialetImpl();
JFishSQLSymbolManagerImpl newSqlSymbolManager = new JFishSQLSymbolManagerImpl(sqlDialet);
return newSqlSymbolManager;
}
private DBDialect dialect;
private MappedEntryManager mappedEntryManager;
public JFishSQLSymbolManagerImpl(SQLDialet sqlDialet) {
super(sqlDialet);
}
@Override
public ExtQuery createQuery(Class<?> entityClass, String alias, Map<Object, Object> properties) {
JFishMappedEntry entry = null;
if(mappedEntryManager!=null){
entry = this.mappedEntryManager.getEntry(entityClass);
}
ExtQuery q = new JFishExtQueryImpl(entry, entityClass, alias, properties, this);
return q;
}
public DBDialect getDialect() {
return dialect;
}
public void setDialect(DBDialect dialect) {
this.dialect = dialect;
}
public MappedEntryManager getMappedEntryManager() {
return mappedEntryManager;
}
public void setMappedEntryManager(MappedEntryManager mappedEntryManager) {
this.mappedEntryManager = mappedEntryManager;
}
}
| true |
caf745e4630b2f284154007d7b4bc11b594f5f00 | Java | katt999/JAVA_IT_PARK_3 | /Tasks/Homework/Task8/src/Main.java | UTF-8 | 1,905 | 3.84375 | 4 | [] | no_license | /**
* Created by EVZabinskaya on 18.10.2017.
*/
public class Main {
public static void main(String[] args) {
Human Kate = new Human("Kate", 34, 168, 51);
Human Irina = new Human("Irina", 30, 165, 53);
AgeHumanComparator ageHumanComparator = new AgeHumanComparator();
HeightHumanComparator heightHumanComparator = new HeightHumanComparator();
WidthHumanComparator widthHumanComparator = new WidthHumanComparator();
int ageDifference = ageHumanComparator.compare(Kate,Irina);
int heightDifference = heightHumanComparator.compare(Kate,Irina);
int widthDifference = widthHumanComparator.compare(Kate,Irina);
System.out.println("Разница в возрасте людей: " + ageDifference);
System.out.println("Разница в росте людей: " + heightDifference);
System.out.println("Разница в весе людей: " + widthDifference);
Human[] humans = new Human[2];
humans[0] = Kate;
humans[1] = Irina;
HumanComparator ageComparator = new AgeHumanComparator();
HumanComparator widthComparator = new WidthHumanComparator();
HumanComparator heightComporator = new HeightHumanComparator();
SorterBubble sorterBubbles = new SorterBubble();
SorterSelect sorterSelects = new SorterSelect();
sorterBubbles.sort(ageComparator,humans);
//sorterBubbles.sort(widthComparator,humans);
// sorterBubbles.sort(heightComporator,humans);
// sorterSelects.sort(ageComparator,humans);
//sorterSelects.sort(widthComparator,humans);
// sorterSelects.sort(heightComporator,humans);
for (int j = 0; j < humans.length; j++) {
System.out.println(humans[j].getName()+ " - рост " + humans[j].getAge() + "см.");
}
}
}
| true |
7e08862f13bb2b2cd7528e77717316f7eee4207c | Java | mizanxali/java-interimsem | /AbstractTest1.java | UTF-8 | 652 | 3.90625 | 4 | [] | no_license | //Concept of abstract class where object of abstract base class holding reference of sub-class.
abstract class Vehicle
{
public abstract void engine(); // abstract method
}
class Car extends Vehicle {
public void engine() //method overridden
{
System.out.println("Car engine");
// car engine implementation
}
}
class Bus extends Vehicle {
public void engine() {
System.out.println("Bus engine");
}
}
public class AbstractTest1 {
public static void main(String[] args)
{
Vehicle v = new Car();
v.engine();
Vehicle v1 = new Bus();
v1.engine();
}
}
| true |
68379aff823b2dc342a4629a4f421b8c3b898c80 | Java | joseseie/PraticaJava2e-08hProject | /src/e/correcoes/e8/oo/e1/Teste.java | UTF-8 | 743 | 2.640625 | 3 | [
"MIT"
] | permissive |
package e.correcoes.e8.oo.e1;
/**
*
* @author joseseie
*/
public class Teste {
public static void main(String[] args) {
Lampada lampada1 = new Lampada("Vermelha", true, "Fluorescente", 45, (byte) 95);
Lampada lampada2 = new Lampada("Vermelha", true, "Fluorescente", 45, (byte) 95);
lampada1.toString();
lampada2.toString();
lampada1.ligar();
lampada2.desligar();
lampada1.temMesmaVoltagem(lampada2);
lampada1.saoIguais(lampada2);
lampada1.aumentarOuReduzirLuminosidade('+');
lampada1.aumentarOuReduzirLuminosidade('+');
lampada1.aumentarOuReduzirLuminosidade('+');
}
}
| true |
fde032c8e5bf34bb17f54aa8d1a08cafb43c6330 | Java | Ruanjiahui/Project | /HTTP_SDK/src/main/java/com/example/administrator/Resource/HttpConnectionString.java | UTF-8 | 2,876 | 2.875 | 3 | [] | no_license | package com.example.administrator.Resource;
import android.util.Log;
import com.example.administrator.Abstract.HttpRequest;
import com.example.administrator.HttpCode;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Administrator on 2016/2/15.
* <p/>
* 这个一个网络链接的类
* <p/>
* 下面是HTTP请求的POST与GET请求的方法
*/
public class HttpConnectionString extends HttpRequest {
private HttpConnectSource httpConnectSource = null;
private HttpReadSource httpReadSource = null;
private HttpURLConnection connection = null;
/**
* 下面是 HTTP GET请求的方法
*
* @param uri
* @return
*/
@Override
public String GET(String uri) {
String result = null;
try {
URL url = new URL(uri);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 将默认设置请求方式POST改成GET
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setReadTimeout(20000);//设置请求时间
// connection.connect();//发送请求链接
if (httpURLConnection.getResponseCode() == 200) {
httpReadSource = new HttpReadSource(httpURLConnection);
return httpReadSource.getResult();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 这个是HTTP POST请求的方法
*
* @param uri
* @param data
* @return
*/
@Override
public String POST(String uri, byte[] data) {
String result = null;
try {
httpConnectSource = new HttpConnectSource(uri);
httpConnectSource.setUseCaches(false); //不使用缓存
connection = httpConnectSource.getHttpURLConnection();
//创建输出字节对象z
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data);
outputStream.flush();
outputStream.close();
connection.connect();//发送请求链接
//判断如果请求码 等于200 则说明请求成功在下面获取返回来的数据
//如果请求码 不等于200 则说明请求不成功
if (connection.getResponseCode() == 200) {
httpReadSource = new HttpReadSource(connection);
return httpReadSource.getResult();
}
} catch (java.io.IOException e) {
return HttpCode.TIMEOUT + "";
}
return result;
}
/**
* 取消下载链接
*/
@Override
public void disConnection() {
connection.disconnect();
}
}
| true |
6189769c580d3c0da9d39a0ffbd546b6bd8fb33e | Java | extraskittles/zzr-mall | /mall-admin/src/main/java/com/zzr/mall/controller/ProductImageController.java | UTF-8 | 2,078 | 2.046875 | 2 | [] | no_license | package com.zzr.mall.controller;
import com.zzr.mall.dto.ProductImageAddParam;
import com.zzr.mall.model.ProductImage;
import com.zzr.mall.result.CommonPage;
import com.zzr.mall.result.CommonResult;
import com.zzr.mall.service.ProductImageService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@ResponseBody
@Api(tags = "商品图片管理")
public class ProductImageController {
@Autowired
ProductImageService productImageService;
@GetMapping("selectProductImages")
public CommonResult selectProductImages(int productId, int pageNum, int pageSize){
List<ProductImage> productImages = productImageService.selectByProductId(productId, pageNum, pageSize);
if(productImages!=null){
return CommonResult.success(CommonPage.getPage(productImages));
}else {
return CommonResult.failed();
}
}
@PostMapping("/deleteProductImage")
public CommonResult deleteProductImage(int productImageId){
int i = productImageService.delete(productImageId);
if(i>0){
return CommonResult.success();
}else {
return CommonResult.failed();
}
}
@PostMapping("/addProductImage")
public CommonResult addProductImage(ProductImageAddParam param){
int i = productImageService.insert(param);
if(i>0){
return CommonResult.success();
}else {
return CommonResult.failed();
}
}
@PostMapping("/updateProductImage")
public CommonResult updateProductImage(ProductImage productImage){
int i = productImageService.update(productImage);
if(i>0){
return CommonResult.success();
}else {
return CommonResult.failed();
}
}
}
| true |
e0ace383be9c15406beb82c2ab15cd53dc6e6475 | Java | CandiceDeng/Algorithm | /TopQs/Array/MedianofTwoSortedArray.java | UTF-8 | 1,796 | 3.828125 | 4 | [] | no_license | // Median of Two Sorted Arrays
// There are two sorted arrays nums1 and nums2 of size m and n respectively.
// Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
// You may assume nums1 and nums2 cannot be both empty.
// Example 1:
// nums1 = [1, 3]
// nums2 = [2]
// The median is 2.0
// Example 2:
// nums1 = [1, 2]
// nums2 = [3, 4]
// The median is (2 + 3)/2 = 2.5
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length+nums2.length;
//Kth element's index is k-1
if (n%2==0){
return (findKthinArray(nums1,nums2,0,0,n/2+1)+
findKthinArray(nums1,nums2,0,0,n/2))/2.0;
}
return findKthinArray(nums1,nums2,0,0,n/2+1);
}
private int findKthinArray(int[] nums1,int[] nums2,
int start1,int start2,int k){
//If length of each array is equal to zero, directly return the Kth element of the other array
if (start1>=nums1.length){
return nums2[start2+k-1];
}
if (start2>=nums2.length){
return nums1[start1+k-1];
}
if (k==1){
return Math.min(nums1[start1],nums2[start2]);
}
//Find the subarray(length=k/2) with less value and eliminate it
int halfKth1 = start1+k/2-1 < nums1.length?
nums1[start1+k/2-1] : Integer.MAX_VALUE;
int halfKth2 = start2+k/2-1 < nums2.length?
nums2[start2+k/2-1] : Integer.MAX_VALUE;
if (halfKth1<halfKth2){
return findKthinArray(nums1,nums2,start1+k/2,start2,k-k/2);
}else{
return findKthinArray(nums1,nums2,start1,start2+k/2,k-k/2);
}
}
} | true |
8b0f6993b4e86cf1bcf9e4838f114f332f51a6e3 | Java | chinezu57/SpringTutorial | /src/main/java/spring/tutorial/dto/Identifiable.java | UTF-8 | 126 | 1.835938 | 2 | [] | no_license | package spring.tutorial.dto;
/**
* Created by Robert on 10/11/2015.
*/
public interface Identifiable {
Long getId();
}
| true |
93fa88c8d665b577c1d49e2e20a646ce2dcb0968 | Java | zhongxingyu/Seer | /Diff-Raw-Data/18/18_efec819959ae2f6e3746ebb91d0ac8b0ff8e4430/AggregationExisting/18_efec819959ae2f6e3746ebb91d0ac8b0ff8e4430_AggregationExisting_s.java | UTF-8 | 7,788 | 1.828125 | 2 | [] | no_license | // $Id: $
/*
* Copyright 1997-2006 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* support@unidata.ucar.edu.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ucar.nc2.ncml;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.VariableDS;
import ucar.nc2.util.CancelTask;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Date;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import org.jdom.Element;
/**
* JoinExisting Aggregation.
*
* @author caron
*/
public class AggregationExisting extends Aggregation {
public AggregationExisting(NetcdfDataset ncd, String dimName, String recheckS) {
super( ncd, dimName, Aggregation.Type.JOIN_EXISTING, recheckS);
}
protected void buildDataset(boolean isNew, CancelTask cancelTask) throws IOException {
buildCoords(cancelTask);
// open a "typical" nested dataset and copy it to newds
Dataset typicalDataset = getTypicalDataset();
NetcdfFile typical = typicalDataset.acquireFile(null);
NcMLReader.transferDataset(typical, ncDataset, isNew ? null : new MyReplaceVariableCheck());
// create aggregation dimension
String dimName = getDimensionName();
Dimension aggDim = new Dimension(dimName, getTotalCoords(), true);
ncDataset.removeDimension(null, dimName); // remove previous declaration, if any
ncDataset.addDimension(null, aggDim);
// now we can create the real aggExisting variables
// all variables with the named aggregation dimension
List vars = typical.getVariables();
for (int i = 0; i < vars.size(); i++) {
Variable v = (Variable) vars.get(i);
if (v.getRank() < 1)
continue;
Dimension d = v.getDimension(0);
if (!dimName.equals(d.getName()))
continue;
VariableDS vagg = new VariableDS(ncDataset, null, null, v.getShortName(), v.getDataType(),
v.getDimensionsString(), null, null);
vagg.setProxyReader(this);
NcMLReader.transferVariableAttributes(v, vagg);
ncDataset.removeVariable(null, v.getShortName());
ncDataset.addVariable(null, vagg);
if (cancelTask != null && cancelTask.isCancel()) return;
}
ncDataset.finish();
makeProxies(typicalDataset, ncDataset);
typical.close();
}
/**
* Persist info (nccords, coorValues) from joinExisting, since that can be expensive to recreate.
* @throws IOException
*/
public void persist() throws IOException {
if (diskCache2 == null)
return;
FileChannel channel = null;
try {
String cacheName = getCacheName();
if (cacheName == null) return;
File cacheFile = diskCache2.getCacheFile(cacheName);
boolean exists = cacheFile.exists();
if (!exists) {
File dir = cacheFile.getParentFile();
dir.mkdirs();
}
// only write out if something changed after the cache file was last written
if (!wasChanged)
return;
// Get a file channel for the file
FileOutputStream fos = new FileOutputStream(cacheFile);
channel = fos.getChannel();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock;
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
return; // give up
}
if (lock == null) return;
PrintStream out = new PrintStream(fos);
out.print("<?xml version='1.0' encoding='UTF-8'?>\n");
out.print("<aggregation xmlns='http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2' ");
out.print("type='" + type + "' ");
if (dimName != null)
out.print("dimName='" + dimName + "' ");
if (recheck != null)
out.print("recheckEvery='" + recheck + "' ");
out.print(">\n");
for (int i = 0; i < nestedDatasets.size(); i++) {
Dataset dataset = (Dataset) nestedDatasets.get(i);
out.print(" <netcdf location='" + dataset.getLocation() + "' ");
out.print("ncoords='" + dataset.getNcoords(null) + "' ");
if (dataset.coordValue != null)
out.print("coordValue='" + dataset.coordValue + "' ");
out.print("/>\n");
}
out.print("</aggregation>\n");
out.close(); // this also closes the channel and releases the lock
cacheFile.setLastModified(lastChecked);
wasChanged = false;
if (debug)
System.out.println("Aggregation persisted = " + cacheFile.getPath() + " lastModified= " + new Date(lastChecked));
} finally {
if (channel != null)
channel.close();
}
}
// read info from the persistent XML file, if it exists
protected void persistRead() {
String cacheName = getCacheName();
if (cacheName == null) return;
File cacheFile = diskCache2.getCacheFile(cacheName);
if (!cacheFile.exists())
return;
if (debug) System.out.println(" *Read cache " + cacheFile.getPath());
Element aggElem;
try {
aggElem = NcMLReader.readAggregation(cacheFile.getPath());
} catch (IOException e) {
return;
}
List ncList = aggElem.getChildren("netcdf", NcMLReader.ncNS);
for (int j = 0; j < ncList.size(); j++) {
Element netcdfElemNested = (Element) ncList.get(j);
String location = netcdfElemNested.getAttributeValue("location");
Dataset ds = findDataset(location);
if ((null != ds) && (ds.ncoord == 0)) {
if (debugCacheDetail) System.out.println(" use cache for " + location);
String ncoordsS = netcdfElemNested.getAttributeValue("ncoords");
try {
ds.ncoord = Integer.parseInt(ncoordsS);
} catch (NumberFormatException e) {
} // ignore
String coordValue = netcdfElemNested.getAttributeValue("coordValue");
if (coordValue != null) {
ds.coordValue = coordValue;
}
}
}
}
// find a dataset in the nestedDatasets by location
private Dataset findDataset(String location) {
for (int i = 0; i < nestedDatasets.size(); i++) {
Dataset ds = (Dataset) nestedDatasets.get(i);
if (location.equals(ds.getLocation()))
return ds;
}
return null;
}
// name to use in the DiskCache2 for the persistent XML info.
// Document root is aggregation
// has the name getCacheName()
private String getCacheName() {
String cacheName = ncDataset.getLocation();
if (cacheName == null) cacheName = ncDataset.getCacheName();
return cacheName;
}
}
| true |
73da8eb37bd91eaae5ddfca794d6fe5d1173d21b | Java | librairy/survey-api | /src/test/java/org/librairy/survey/questions/QuestionTemplate.java | UTF-8 | 2,938 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package org.librairy.survey.questions;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import io.swagger.model.Question;
import org.librairy.survey.bb.data.PairCandidate;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*/
public class QuestionTemplate {
private final PairCandidate pair;
private final Escaper escaper = Escapers.builder()
.addEscape('\'',"")
.addEscape('\"',"")
.addEscape('('," ")
.addEscape(')'," ")
.addEscape('['," ")
.addEscape(']'," ")
.build();
public QuestionTemplate(PairCandidate candidate){
this.pair = candidate;
}
public Question getQuestion() {
String key = new StringBuilder()
.append(this.pair.getItem1().getId()).append("#").append(this.pair.getItem2().getId()).toString();
String b1 = escaper.escape(this.pair.getItem1().getName());
String b2 = escaper.escape(this.pair.getItem2().getName());
String url1 = "#";
try {
url1 = "https://www.google.com/search?q="+URLEncoder.encode(b1,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url2 = "#";
try {
url2 = "https://www.google.com/search?q="+URLEncoder.encode(b2,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new Question(key, "{\n" +
" \"type\": \"panel\",\n" +
" \"innerIndent\": 1,\n" +
" \"name\": \"p"+key+"\",\n" +
" \"title\": \"Q"+key+"\",\n" +
" \"elements\": [\n" +
" {\n" +
" \"type\": \"html\",\n" +
" \"name\": \"h"+key+"\",\n" +
" \"html\": \"<table><body><row><td><img src='http://bit.ly/2zMxn2P' width='100px' /></td><td style='padding:20px'><a href='"+url1+"' target='_blank'>'"+b1+"'</a></td><td><img src='http://bit.ly/2A6nX30' width='100px' /></td><td style='padding:20px'><a href='"+url2+"' target='_blank'>'"+b2+"'</a></td></row></body></table>\"\n" +
" },\n" +
" {\n" +
" \"type\": \"radiogroup\",\n" +
" \"name\": \""+key+"\",\n" +
" \"title\": \"Are these books related?\",\n" +
" \"isRequired\": true,\n" +
" \"colCount\": 1,\n" +
" \"choices\": [\n" +
" \"yes\",\n" +
" \"no\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }");
}
}
| true |
638d6847a8ce7c9e2ad72c7b80bc7d1e9eb1c919 | Java | TsvetomirN1/Spring-Fundamentals | /pathfinder/src/main/java/com/example/pathfinder/service/impl/UserServiceImpl.java | UTF-8 | 2,656 | 2.359375 | 2 | [
"MIT"
] | permissive | package com.example.pathfinder.service.impl;
import com.example.pathfinder.model.entity.Role;
import com.example.pathfinder.model.entity.User;
import com.example.pathfinder.model.enums.LevelEnum;
import com.example.pathfinder.model.enums.RoleEnum;
import com.example.pathfinder.model.service.UserServiceModel;
import com.example.pathfinder.repository.RoleRepository;
import com.example.pathfinder.repository.UserRepository;
import com.example.pathfinder.service.UserService;
import com.example.pathfinder.util.CurrentUser;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final ModelMapper modelMapper;
private final RoleRepository roleRepository;
private final CurrentUser currentUser;
public UserServiceImpl(UserRepository userRepository, ModelMapper modelMapper, RoleRepository roleRepository, CurrentUser currentUser) {
this.userRepository = userRepository;
this.modelMapper = modelMapper;
this.roleRepository = roleRepository;
this.currentUser = currentUser;
}
@Override
public void registerUser(UserServiceModel userServiceModel) {
Role userRole = roleRepository.findByRole(RoleEnum.USER);
User user = modelMapper.map(userServiceModel, User.class);
user.setLevel(LevelEnum.BEGINNER);
user.setRoles(Set.of(userRole));
System.out.println();
userRepository.save(user);
}
@Override
public UserServiceModel findUserByUsernameAndPassword(String username, String password) {
return userRepository
.findByUsernameAndPassword(username, password)
.map(user -> modelMapper.map(user, UserServiceModel.class))
.orElse(null);
}
@Override
public void loginUser(Long id, String username) {
currentUser.setUsername(username);
currentUser.setId(id);
}
@Override
public void logoutUser() {
currentUser.setUsername(null);
currentUser.setId(null);
}
@Override
public UserServiceModel findById(Long id) {
return userRepository.findById(id)
.map(user -> modelMapper.map(user, UserServiceModel.class))
.orElse(null);
}
@Override
public boolean isNameExist(String username) {
return userRepository.findByUsername(username).isPresent();
}
@Override
public User findCurrentUser() {
return userRepository.findById(currentUser.getId()).orElse(null);
}
}
| true |
6a5a5b99f7bd47adc302570fe516d8490ddab609 | Java | NadinZeitoune/School_Apps | /Android/24_12_2018_BroadcastReceiver/app/src/main/java/com/company/hackeru/a24_12_2018_broadcastreceiver/SecondActivity.java | UTF-8 | 577 | 2.171875 | 2 | [] | no_license | package com.company.hackeru.a24_12_2018_broadcastreceiver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_second);
int param1 = getIntent().getIntExtra("param1", 0);
param1++;
Intent data = new Intent();
data.putExtra("result",param1);
setResult(RESULT_OK, data);
finish();
}
}
| true |
9cbf211249f617d9158ee8e1f9159ce11dfa216d | Java | mengxiangpei/xiaozuxiangmu | /src/main/java/com/jk/dao/SysUserInfoMapper.java | UTF-8 | 526 | 1.757813 | 2 | [] | no_license | package com.jk.dao;
import com.jk.pojo.SysUserInfo;
public interface SysUserInfoMapper {
int deleteByPrimaryKey(String sysuserId);
int insert(SysUserInfo record);
int insertSelective(SysUserInfo record);
SysUserInfo selectByPrimaryKey(String sysuserId);
int updateByPrimaryKeySelective(SysUserInfo record);
int updateByPrimaryKey(SysUserInfo record);
SysUserInfo checkSysUserInfo(SysUserInfo user);
void saveSysUser(SysUserInfo user);
SysUserInfo checkSysUser(SysUserInfo user);
} | true |
33d24f673ad387313b10a9313d22fcfc47ec6da0 | Java | debezium/debezium | /debezium-connector-oracle/src/main/java/io/debezium/connector/oracle/logminer/processor/AbstractTransaction.java | UTF-8 | 2,270 | 2.328125 | 2 | [
"MIT",
"Apache-2.0",
"Artistic-1.0-Perl",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"LGPL-2.1-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-1.1",
"GPL-3.0-only",
"GPL-2.0-only",
"Artisti... | permissive | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.oracle.logminer.processor;
import java.time.Instant;
import java.util.Objects;
import io.debezium.connector.oracle.Scn;
/**
* An abstract implementation of an Oracle {@link Transaction}.
*
* @author Chris Cranford
*/
public abstract class AbstractTransaction implements Transaction {
private static final String UNKNOWN = "UNKNOWN";
private final String transactionId;
private final Scn startScn;
private final Instant changeTime;
private final String userName;
private final Integer redoThreadId;
public AbstractTransaction(String transactionId, Scn startScn, Instant changeTime, String userName, Integer redoThreadId) {
this.transactionId = transactionId;
this.startScn = startScn;
this.changeTime = changeTime;
this.userName = !UNKNOWN.equalsIgnoreCase(userName) ? userName : null;
this.redoThreadId = redoThreadId;
}
@Override
public String getTransactionId() {
return transactionId;
}
@Override
public Scn getStartScn() {
return startScn;
}
@Override
public Instant getChangeTime() {
return changeTime;
}
@Override
public String getUserName() {
return userName;
}
@Override
public int getRedoThreadId() {
return redoThreadId == null ? -1 : redoThreadId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractTransaction that = (AbstractTransaction) o;
return Objects.equals(transactionId, that.transactionId);
}
@Override
public int hashCode() {
return Objects.hash(transactionId);
}
@Override
public String toString() {
return "AbstractTransaction{" +
"transactionId='" + transactionId + '\'' +
", startScn=" + startScn +
", changeTime=" + changeTime +
", userName='" + userName + '\'' +
'}';
}
}
| true |
7b060e4325f6439290e80c3d0c5aaab285cd540d | Java | koval-xxj/NaviPark | /app/src/main/java/com/valpiok/NaviPark/payment/ResourceProvider.java | UTF-8 | 1,009 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | package com.valpiok.NaviPark.payment;
/**
* Created by SERHIO on 14.09.2017.
*/
import android.content.Context;
import com.valpiok.NaviPark.R;
import ch.datatrans.payment.android.IResourceProvider;
public class ResourceProvider implements IResourceProvider {
@Override
public String getNWErrorButtonCancelText(Context context) {
return context.getString(R.string.nw_error_button_cancel);
}
@Override
public String getNWErrorButtonRetryText(Context context) {
return context.getString(R.string.nw_error_button_retry);
}
@Override
public String getNWErrorDialogMessageText(Context context) {
return context.getString(R.string.nw_error_message);
}
@Override
public String getNWErrorDialogTitleText(Context context) {
return context.getString(R.string.nw_error_title);
}
@Override
public String getNWIndicatorMessageText(Context context) {
return context.getString(R.string.nw_indicator_message);
}
} | true |
f0b11d4b208638cf67930c4fe09900308ef2a030 | Java | 8secz-johndpope/snapchat-re | /jadx-snap-new/sources/com/snap/composer/foundation/Cancelable.java | UTF-8 | 2,439 | 2.015625 | 2 | [] | no_license | package com.snap.composer.foundation;
import com.snap.composer.actions.ComposerRunnableAction;
import com.snap.composer.exceptions.AttributeError;
import com.snap.composer.utils.JSConversions;
import com.snapchat.client.composer.utils.ComposerJsConvertible;
import defpackage.ajxw;
import defpackage.akbl;
import defpackage.akcr;
import defpackage.akcs;
import java.util.LinkedHashMap;
import java.util.Map;
public interface Cancelable extends ComposerJsConvertible {
public static final Companion Companion = Companion.a;
public static final class Companion {
static final /* synthetic */ Companion a = new Companion();
static final class a extends akcs implements akbl<Object[], ajxw> {
private /* synthetic */ Cancelable a;
a(Cancelable cancelable) {
this.a = cancelable;
super(1);
}
public final /* synthetic */ Object invoke(Object obj) {
akcr.b((Object[]) obj, "_params");
this.a.cancel();
return ajxw.a;
}
}
private Companion() {
}
public final Cancelable fromJavaScript(Object obj) {
if (obj instanceof Map) {
obj = JSConversions.INSTANCE.unwrapNativeInstance(((Map) obj).get("$nativeInstance"));
}
Cancelable cancelable = (Cancelable) (!(obj instanceof Cancelable) ? null : obj);
if (cancelable != null) {
return cancelable;
}
StringBuilder stringBuilder = new StringBuilder("Cannot cast ");
stringBuilder.append(obj);
stringBuilder.append(" to Cancelable");
throw new AttributeError(stringBuilder.toString());
}
public final Map<String, Object> toJavaScript(Cancelable cancelable) {
akcr.b(cancelable, "instance");
Map linkedHashMap = new LinkedHashMap();
linkedHashMap.put("cancel", new ComposerRunnableAction(new a(cancelable)));
linkedHashMap.put("$nativeInstance", JSConversions.INSTANCE.wrapNativeInstance(cancelable));
return linkedHashMap;
}
}
public static final class DefaultImpls {
public static Object toJavaScript(Cancelable cancelable) {
return Cancelable.Companion.toJavaScript(cancelable);
}
}
void cancel();
Object toJavaScript();
}
| true |
778acd396f94342822f47cfeaa0691b0298cca68 | Java | nhduy163/Karaoke | /Source code/src/BUS/TaiKhoanBUS.java | UTF-8 | 2,459 | 2.359375 | 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 BUS;
import DAO.TaiKhoanDAO;
import DTO.NhanVienDTO;
import DTO.TaiKhoanDTO;
import java.util.ArrayList;
import javax.swing.JTextField;
/**
*
* @author Hainguyen
*/
public class TaiKhoanBUS {
public static ArrayList<TaiKhoanDTO> TaiKhoanAll() {
return TaiKhoanDAO.TaiKHoanAll();
}
public static TaiKhoanDTO getTaiKhoan(int MaTK) {
return TaiKhoanDAO.getTaiKhoan(MaTK);
}
public static int getMaNV(String TenTK) {
ArrayList<TaiKhoanDTO> arr = TaiKhoanBUS.TaiKhoanAll();
TaiKhoanDTO tk;
int i = 0;
while (i < arr.size()) {
tk = arr.get(i);
if (TenTK.equals(tk.getTenTK())) {
return tk.getMaNV();
} else {
i++;
}
}
return 0;
}
public static int getSoTK() {
return TaiKhoanDAO.getSoTK();
}
public static boolean checkTenTaikhoan(JTextField tf) {
ArrayList<TaiKhoanDTO> arr = TaiKhoanBUS.TaiKhoanAll();
TaiKhoanDTO tk;
String taikhoan = tf.getText();
int i = 0;
while (i < arr.size()) {
tk = arr.get(i);
if (tk.getTenTK().equals(taikhoan)) {
return false;
} else {
i++;
}
}
return true;
}
public static boolean checkMatKhau(JTextField tf) {
return !"".equals(tf.getText());
}
public static boolean checkTaikhoan(JTextField tf) {
return !"".equals(tf.getText());
}
public static boolean checkDangNhap(JTextField tf1, JTextField tf2) {
ArrayList<TaiKhoanDTO> arr = TaiKhoanBUS.TaiKhoanAll();
TaiKhoanDTO tk;
String taikhoan = tf1.getText();
String matkhau = tf2.getText();
int i = 0;
while (i < arr.size()) {
tk = arr.get(i);
if (taikhoan.equals(tk.getTenTK()) && matkhau.equals(tk.getMatKhau())) {
return true;
} else {
i++;
}
}
return false;
}
public static boolean checkTinhTrang(NhanVienDTO nv) {
return nv.getTinhTrang() == 1;
}
}
| true |
5a5aaa71504bf3a5a839e6e6f39e77a176ff3ed7 | Java | cuba-platform/workflow-thesis | /modules/core/src/com/haulmont/workflow/core/timer/MainAssignmentTimerAction.java | UTF-8 | 3,819 | 1.945313 | 2 | [] | no_license | /*
* Copyright (c) 2008-2016 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/commercial-software-license for details.
*/
package com.haulmont.workflow.core.timer;
import com.haulmont.cuba.core.EntityManager;
import com.haulmont.cuba.core.Persistence;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.Scripting;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.workflow.core.WfHelper;
import com.haulmont.workflow.core.app.WfMailWorker;
import com.haulmont.workflow.core.entity.CardInfo;
import com.haulmont.workflow.core.entity.Proc;
import groovy.lang.Binding;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.Execution;
import java.util.HashMap;
import java.util.Map;
public class MainAssignmentTimerAction extends AssignmentTimerAction {
private Log log = LogFactory.getLog(getClass());
private boolean makesSense(TimerActionContext context) {
Execution execution = WfHelper.getExecutionService().findExecutionById(context.getJbpmExecutionId());
if (execution == null) {
log.debug("Execution not found, do nothing");
return false;
}
if (!execution.isActive(context.getActivity())) {
log.debug("Execution is not in " + context.getActivity() + ", do nothing");
return false;
}
return true;
}
protected CardInfo createCardInfo(TimerActionContext context, User user, int type, String subject) {
Metadata metadata = AppBeans.get(Metadata.NAME);
CardInfo ci = metadata.create(CardInfo.class);
ci.setCard(context.getCard());
ci.setType(type);
ci.setUser(user);
ci.setJbpmExecutionId(context.getJbpmExecutionId());
ci.setActivity(context.getActivity());
ci.setDescription(subject);
EntityManager em = AppBeans.get(Persistence.class).getEntityManager();
em.persist(ci);
return ci;
}
protected void sendEmail(User user, String subject, String body) {
WfMailWorker wfMailWorker = AppBeans.get(WfMailWorker.NAME);
try {
wfMailWorker.sendEmail(user, subject, body);
} catch (Exception e) {
log.error("Unable to send email to " + user.getEmail(), e);
}
}
@Override
protected void execute(TimerActionContext context, User user) {
if (!makesSense(context)) return;
String script = context.getCard().getProc().getProcessPath() + "/OverdueAssignmentNotification.groovy";
String subject;
String body;
try {
Map<String, Object> bindingParams = new HashMap<>();
bindingParams.put("card", context.getCard());
bindingParams.put("dueDate", context.getDueDate());
bindingParams.put("activity", context.getActivity());
bindingParams.put("user", user);
Binding binding = new Binding(bindingParams);
AppBeans.get(Scripting.class).runGroovyScript(script, binding);
subject = binding.getVariable("subject").toString();
body = binding.getVariable("body").toString();
} catch (Exception e) {
log.error("Unable to evaluate groovy script " + script, e);
Proc proc = context.getCard().getProc();
String procStr = proc == null ? null : " of process " + proc.getName();
subject = "Stage " + context.getActivity() + procStr + " is overdue";
body = "Stage " + context.getActivity() + procStr + " is overdue";
}
createCardInfo(context, user, CardInfo.TYPE_OVERDUE, subject);
sendEmail(user, subject, body);
}
} | true |
c3bb66f6a44a35d6bd9f8f006b71102109239124 | Java | SmellyCat44/2020shortlab_takeoutAssistant | /src/cn/edu/zucc/takeoutassist/model/BeanManager.java | UTF-8 | 523 | 1.984375 | 2 | [] | no_license | package cn.edu.zucc.takeoutassist.model;
public class BeanManager {
private String mng_id;
private String mng_name;
private String mng_pwd;
public String getMng_id() {
return mng_id;
}
public void setMng_id(String mng_id) {
this.mng_id = mng_id;
}
public String getMng_name() {
return mng_name;
}
public void setMng_name(String mng_name) {
this.mng_name = mng_name;
}
public String getMng_pwd() {
return mng_pwd;
}
public void setMng_pwd(String mng_pwd) {
this.mng_pwd = mng_pwd;
}
}
| true |
a6ddbeb6c5c2721cbc0f12840ecac74ea6372505 | Java | diazdaniel0526/monopofast | /src/byui/cit260/monopofastPro/model/IngredientOrder.java | UTF-8 | 1,670 | 2.65625 | 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 byui.cit260.monopofastPro.model;
import java.io.Serializable;
import java.util.Objects;
/**
*
* @author ellisoverson
*/
public class IngredientOrder implements Serializable{
//class instance variables
private String order;
private FoodItem foodItem;
private Ingredients ingredient;
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public FoodItem getFoodItem() {
return foodItem;
}
public void setFoodItem(FoodItem foodItem) {
this.foodItem = foodItem;
}
public Ingredients getIngredient() {
return ingredient;
}
public void setIngredient(Ingredients ingredient) {
this.ingredient = ingredient;
}
public IngredientOrder() {
}
@Override
public String toString() {
return "IngredientOrder{" + "order=" + order + '}';
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.order);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IngredientOrder other = (IngredientOrder) obj;
if (!Objects.equals(this.order, other.order)) {
return false;
}
return true;
}
}
| true |
ca58f42e8d0cc7926d446fed39ffd1f3db99f779 | Java | subham5230/shoppr_ecommerce | /ShopprWebParent/ShopprBackend/src/test/java/com/shoppr/admin/setting/state/StateRepositoryTests.java | UTF-8 | 2,806 | 2.1875 | 2 | [] | no_license | package com.shoppr.admin.setting.state;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
import com.shoppr.common.entity.Country;
import com.shoppr.common.entity.State;
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Rollback(false)
public class StateRepositoryTests {
@Autowired private StateRepository repo;
@Autowired private TestEntityManager entityManager;
@Test
public void testCreateStatesInIndia() {
Integer countryId = 1;
Country country = entityManager.find(Country.class, countryId);
// State state = repo.save(new State("Karnataka", country));
// State state = repo.save(new State("Punjab", country));
// State state = repo.save(new State("Uttar Pradesh", country));
State state = repo.save(new State("West Bengal", country));
assertThat(state).isNotNull();
assertThat(state.getId()).isGreaterThan(0);
}
@Test
public void testCreateStatesInUS() {
Integer countryId = 2;
Country country = entityManager.find(Country.class, countryId);
// State state = repo.save(new State("California", country));
// State state = repo.save(new State("Texas", country));
// State state = repo.save(new State("New York", country));
State state = repo.save(new State("Washington", country));
assertThat(state).isNotNull();
assertThat(state.getId()).isGreaterThan(0);
}
@Test
public void testListStatesByCountry() {
Integer countryId = 1;
Country country = entityManager.find(Country.class, countryId);
List<State> listStates = repo.findByCountryOrderByNameAsc(country);
listStates.forEach(System.out::println);
assertThat(listStates.size()).isGreaterThan(0);
}
@Test
public void testUpdateState() {
Integer stateId = 3;
String stateName = "Tamil Nadu";
State state = repo.findById(stateId).get();
state.setName(stateName);
State updatedState = repo.save(state);
assertThat(updatedState.getName()).isEqualTo(stateName);
}
@Test
public void testGetState() {
Integer stateId = 1;
Optional<State> findById = repo.findById(stateId);
assertThat(findById.isPresent());
}
@Test
public void testDeleteState() {
Integer stateId = 8;
repo.deleteById(stateId);
Optional<State> findById = repo.findById(stateId);
assertThat(findById.isEmpty());
}
}
| true |
f1d37db11e22c2fbab96d53d5f24404534fc5002 | Java | wks1222/mobius-source | /java/lineage2/gameserver/model/instances/DecoyInstance.java | UTF-8 | 6,846 | 2.234375 | 2 | [] | no_license | /*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package lineage2.gameserver.model.instances;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import lineage2.commons.lang.reference.HardReference;
import lineage2.commons.threading.RunnableImpl;
import lineage2.gameserver.ThreadPoolManager;
import lineage2.gameserver.data.xml.holder.NpcHolder;
import lineage2.gameserver.model.Creature;
import lineage2.gameserver.model.Player;
import lineage2.gameserver.model.Skill;
import lineage2.gameserver.network.serverpackets.AutoAttackStart;
import lineage2.gameserver.network.serverpackets.CharInfo;
import lineage2.gameserver.network.serverpackets.L2GameServerPacket;
import lineage2.gameserver.tables.SkillTable;
import lineage2.gameserver.templates.npc.NpcTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Mobius
* @version $Revision: 1.0 $
*/
public class DecoyInstance extends NpcInstance
{
@SuppressWarnings("unused")
private static final Logger _log = LoggerFactory.getLogger(DecoyInstance.class);
private final HardReference<Player> _playerRef;
private int _lifeTime, _timeRemaining;
private ScheduledFuture<?> _decoyLifeTask, _hateSpam;
/**
* Constructor for DecoyInstance.
* @param objectId int
* @param template NpcTemplate
* @param owner Player
* @param lifeTime int
*/
public DecoyInstance(int objectId, NpcTemplate template, Player owner, int lifeTime)
{
super(objectId, template);
_playerRef = owner.getRef();
_lifeTime = lifeTime;
_timeRemaining = _lifeTime;
int skilllevel = getId() < 13257 ? getId() - 13070 : getId() - 13250;
_decoyLifeTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new DecoyLifetime(), 1000, 1000);
_hateSpam = ThreadPoolManager.getInstance().scheduleAtFixedRate(new HateSpam(SkillTable.getInstance().getInfo(5272, skilllevel)), 1000, 3000);
}
/**
* Method onDeath.
* @param killer Creature
*/
@Override
protected void onDeath(Creature killer)
{
super.onDeath(killer);
if (_hateSpam != null)
{
_hateSpam.cancel(false);
_hateSpam = null;
}
_lifeTime = 0;
}
/**
* @author Mobius
*/
class DecoyLifetime extends RunnableImpl
{
/**
* Method runImpl.
*/
@Override
public void runImpl()
{
try
{
double newTimeRemaining;
decTimeRemaining(1000);
newTimeRemaining = getTimeRemaining();
if (newTimeRemaining < 0)
{
unSummon();
}
}
catch (Exception e)
{
_log.error("", e);
}
}
}
/**
* @author Mobius
*/
class HateSpam extends RunnableImpl
{
private final Skill _skill;
/**
* Constructor for HateSpam.
* @param skill Skill
*/
HateSpam(Skill skill)
{
_skill = skill;
}
/**
* Method runImpl.
*/
@Override
public void runImpl()
{
try
{
setTarget(DecoyInstance.this);
doCast(_skill, DecoyInstance.this, true);
}
catch (Exception e)
{
_log.error("", e);
}
}
}
/**
* Method unSummon.
*/
public void unSummon()
{
if (_decoyLifeTask != null)
{
_decoyLifeTask.cancel(false);
_decoyLifeTask = null;
}
if (_hateSpam != null)
{
_hateSpam.cancel(false);
_hateSpam = null;
}
deleteMe();
}
/**
* Method decTimeRemaining.
* @param value int
*/
public void decTimeRemaining(int value)
{
_timeRemaining -= value;
}
/**
* Method getTimeRemaining.
* @return int
*/
public int getTimeRemaining()
{
return _timeRemaining;
}
/**
* Method getLifeTime.
* @return int
*/
public int getLifeTime()
{
return _lifeTime;
}
/**
* Method getPlayer.
* @return Player
*/
@Override
public Player getPlayer()
{
return _playerRef.get();
}
/**
* Method isAutoAttackable.
* @param attacker Creature
* @return boolean
*/
@Override
public boolean isAutoAttackable(Creature attacker)
{
Player owner = getPlayer();
return (owner != null) && owner.isAutoAttackable(attacker);
}
/**
* Method isAttackable.
* @param attacker Creature
* @return boolean
*/
@Override
public boolean isAttackable(Creature attacker)
{
Player owner = getPlayer();
return (owner != null) && owner.isAttackable(attacker);
}
/**
* Method onDelete.
*/
@Override
protected void onDelete()
{
Player owner = getPlayer();
if (owner != null)
{
owner.setDecoy(null);
}
super.onDelete();
}
/**
* Method getColRadius.
* @return double
*/
@Override
public double getColRadius()
{
Player player = getPlayer();
if (player == null)
{
return 0;
}
if ((player.getTransformation() != 0) && (player.getTransformationTemplate() != 0))
{
return NpcHolder.getInstance().getTemplate(player.getTransformationTemplate()).getCollisionRadius();
}
return player.getTemplate().getCollisionRadius();
}
/**
* Method getColHeight.
* @return double
*/
@Override
public double getColHeight()
{
Player player = getPlayer();
if (player == null)
{
return 0;
}
if ((player.getTransformation() != 0) && (player.getTransformationTemplate() != 0))
{
return NpcHolder.getInstance().getTemplate(player.getTransformationTemplate()).getCollisionHeight();
}
return player.getTemplate().getCollisionHeight();
}
/**
* Method addPacketList.
* @param forPlayer Player
* @param dropper Creature
* @return List<L2GameServerPacket>
*/
@Override
public List<L2GameServerPacket> addPacketList(Player forPlayer, Creature dropper)
{
if (!isInCombat())
{
return Collections.<L2GameServerPacket> singletonList(new CharInfo(this));
}
List<L2GameServerPacket> list = new ArrayList<>(2);
list.add(new CharInfo(this));
list.add(new AutoAttackStart(objectId));
return list;
}
/**
* Method isInvul.
* @return boolean
*/
@Override
public boolean isInvul()
{
return _isInvul;
}
}
| true |
360e479f8c70b4cbeabb938e729d714be844ea80 | Java | MPSong/csebud | /csebud/src/buddy/student/Course.java | UTF-8 | 2,125 | 2.65625 | 3 | [] | no_license | package buddy.student;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Course {
@Id
String studentId; // 강의를 수강한 학생의 학번
String lectureCode; // 해당되는 강의의 학수번호
String lectureName; // 해당되는 강의의 강의명
String professor; // 해당되는 강의의 교수명
String credit; // 해당되는 강의의 학점
String grade; // 해당되는 강의의 등급
int isEnglishCourse;// 해당되는 강의의 영어강의 유무
/**
* @return the studentId
*/
public String getStudentId(){
return studentId;
}
/**
* @param studentId the studentId to set
*/
public void setStudentId(String studentId){
this.studentId = studentId;
}
/**
* @return the lectureCode
*/
public String getLectureCode(){
return lectureCode;
}
/**
* @param lectureCode the lectureCode to set
*/
public void setLectureCode(String lectureCode){
this.lectureCode = lectureCode;
}
/**
* @return the lectureName
*/
public String getLectureName(){
return lectureName;
}
/**
* @param lectureName the lectureName to set
*/
public void setLectureName(String lectureName){
this.lectureName = lectureName;
}
/**
* @return the professor
*/
public String getProfessor(){
return professor;
}
/**
* @param professor the professor to set
*/
public void setProfessor(String professor){
this.professor = professor;
}
/**
* @return the credit
*/
public String getCredit(){
return credit;
}
/**
* @param credit the credit to set
*/
public void setCredit(String credit){
this.credit = credit;
}
/**
* @return the grade
*/
public String getGrade(){
return grade;
}
/**
* @param grade the grade to set
*/
public void setGrade(String grade){
this.grade = grade;
}
/**
* @return the isEnglishCourse
*/
public int getIsEnglishCourse(){
return isEnglishCourse;
}
/**
* @param isEnglishCourse the isEnglishCourse to set
*/
public void setIsEnglishCourse(int isEnglishCourse){
this.isEnglishCourse = isEnglishCourse;
}
} | true |
a344171e48968fd1575ed4dd00baa50ef5ba3e82 | Java | DmytroKataryna/WideWeather | /app/src/main/java/kataryna/dmytro/wideweather/helpers/Utils.java | UTF-8 | 888 | 2.6875 | 3 | [] | no_license | package kataryna.dmytro.wideweather.helpers;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created by dmytroKataryna on 25.01.16.
*/
public class Utils {
public static String getCountryName(String isoCode) {
return new Locale("", isoCode).getDisplayCountry(Locale.ENGLISH);
}
public static String getTime(long unixTime) {
Date d = new Date(unixTime * 1000);
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy, HH:mm", Locale.ENGLISH);
f.setTimeZone(TimeZone.getDefault());
return f.format(d);
}
public static String getForecastTime(long unixTime) {
Date d = new Date(unixTime * 1000);
SimpleDateFormat f = new SimpleDateFormat("E dd", Locale.ENGLISH);
f.setTimeZone(TimeZone.getDefault());
return f.format(d);
}
}
| true |
6344b3eb4c5027f5378a71ab86ff3bddd3e43c64 | Java | GULNURKIRCAER/ZEROBANK | /src/test/java/com/zerobank/step_definitions/AddNewPayeeDefs.java | UTF-8 | 2,257 | 2.453125 | 2 | [] | no_license | package com.zerobank.step_definitions;
import com.zerobank.pages.LoginPage;
import com.zerobank.utilities.BrowserUtils;
import com.zerobank.utilities.ConfigurationReader;
import com.zerobank.utilities.Driver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.junit.Assert;
import org.openqa.selenium.By;
import java.util.Map;
public class AddNewPayeeDefs {
@Given("Add New Payee tab")
public void add_New_Payee_tab() {
String url = ConfigurationReader.get("url");
Driver.get().get(url);
LoginPage loginPage = new LoginPage();
loginPage.signIn.click();
BrowserUtils.waitFor(2);
Driver.get().findElement(By.id("user_login")).sendKeys("username");
Driver.get().findElement(By.id("user_password")).sendKeys("password");
if(loginPage.userName.getAttribute("value").equals("username") || loginPage.password.getAttribute("value").equals("password")) {
Driver.get().findElement(By.name("submit")).click();
}else if(!loginPage.userName.getAttribute("value").equals("username") || !loginPage.password.getAttribute("value").equals("password")){
Assert.assertTrue(loginPage.alert.isDisplayed());
}
Driver.get().findElement(By.xpath("//a[text()='Pay Bills']")).click();
Driver.get().findElement(By.xpath("//a[text()='Add New Payee']")).click();
}
@Given("creates new payee using following information")
public void creates_new_payee_using_following_information(Map<String,String> userInfo) {
BrowserUtils.waitFor(1);
new LoginPage().NewPayee(userInfo.get("Payee Name"),userInfo.get("Payee Address"));
new LoginPage().NewPayee2(userInfo.get("Account"),userInfo.get("Payee details"));
}
@Then("message The new payee The Law Offices of Hyde,Price & Scharks was successfully created. should be displayed")
public void message_The_new_payee_The_Law_Offices_of_Hyde_Price_Scharks_was_successfully_created_should_be_displayed() {
BrowserUtils.waitFor(1);
Assert.assertEquals("The new payee The Law Offices of Hyde,Price & Scharks was successfully created.",Driver.get().findElement(By.id("alert_content")).getText());
}
}
| true |
e603104e217af36a283e4010bab9223e426e1817 | Java | jwpiotrowski/blogwatch | /src/test/java/com/baeldung/selenium/page/HomePageUITest.java | UTF-8 | 3,344 | 2.234375 | 2 | [] | no_license | package com.baeldung.selenium.page;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.logging.Level;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.common.GlobalConstants;
import com.baeldung.selenium.common.BaseUISeleniumTest;
import com.baeldung.site.HomePageDriver;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
public final class HomePageUITest extends BaseUISeleniumTest {
@Autowired
private HomePageDriver homePageDriver;
@Test
@Tag(GlobalConstants.TAG_DAILY)
public final void givenOnTheHomePage_whenPageLoads_thenJavaWeeklyLinksMatchWithTheLinkText() {
homePageDriver.loadUrl();
List<WebElement> javaWeeklyElements = this.homePageDriver.getAllJavaWeeklyIssueLinkElements();
String expectedLink;
String issueNumber;
for (WebElement webElement : javaWeeklyElements) {
issueNumber = webElement.getText().replaceAll("\\D+", "");
if (issueNumber.length() > 0) {
expectedLink = (this.homePageDriver.getUrl() + "/java-weekly-") + issueNumber;
logger.debug("expectedLink-->" + expectedLink);
logger.debug("actual Link-->" + webElement.getAttribute("href"));
assertTrue(expectedLink.equals(webElement.getAttribute("href").toString()));
}
}
}
@Test
@Tag(GlobalConstants.TAG_DAILY)
public final void givenOnTheHomePage_whenPageLoads_thenItContainsCategoriesInTheFooterMenu() {
homePageDriver.loadUrl();
assertTrue(homePageDriver.findCategoriesContainerInThePageFooter().isDisplayed());
}
@Test
@Tag(GlobalConstants.TAG_DAILY)
public final void givenOnTheHomePage_whenHomePageLoaded_thenNoSevereMessagesInBrowserLog() {
homePageDriver.loadUrl();
LogEntries browserLogentries = homePageDriver.getWebDriver().manage().logs().get(LogType.BROWSER);
for (LogEntry logEntry : browserLogentries) {
if (logEntry.getLevel().equals(Level.SEVERE)) {
fail("Error with Severe Level-->" + logEntry.getMessage());
}
}
}
@Test
@Tag(GlobalConstants.TAG_DAILY)
public final void givenOnTheHomePageUrlWithoutWWWPrefix_whenUrlIsHit_thenItRedirectsToWWW() {
Response response = RestAssured.given().redirects().follow(false).head(GlobalConstants.BAELDUNG_HOME_PAGE_URL_WITHOUT_WWW_PREFIX);
assertEquals(301, response.getStatusCode());
assertEquals(GlobalConstants.BAELDUNG_HOME_PAGE_URL_WITH_WWW_PREFIX, response.getHeader("Location").replaceAll("/$", ""));
}
@Test
@Tag(GlobalConstants.TAG_DAILY)
public final void givenOnTheHomePage_whenPageLoads_thenItHasOneAboutMenuInTheFooter() {
homePageDriver.loadUrl();
assertTrue(homePageDriver.findAboutMenuInThePageFooter().size() == 1);
}
}
| true |
95b8da06a0a660aaff9067613a14245815605654 | Java | CodeShagee/distributer_x | /src/GUI/ViewEnteredPOfrmCustomers.java | UTF-8 | 14,705 | 2.140625 | 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 GUI;
import Domain.PO;
import Domain.SalesOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Shiyanrox
*/
public class ViewEnteredPOfrmCustomers extends javax.swing.JFrame {
/**
* Creates new form ViewEnteredPOfrmCustomers
*/
public ViewEnteredPOfrmCustomers() {
initComponents();
loadTable();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtPOCfind = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
dcFrom = new com.toedter.calendar.JDateChooser();
dcTo = new com.toedter.calendar.JDateChooser();
btnPOVVFind = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblPOVC = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("DistributerX: Purchasing Order from Customer View");
jPanel1.setBackground(new java.awt.Color(0, 153, 153));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("View Entered PO from Customers"));
jLabel1.setText("Name");
jLabel2.setText("From");
jLabel3.setText("To");
btnPOVVFind.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG/FontAwesome_f002(0)_24.png"))); // NOI18N
btnPOVVFind.setText("Find");
btnPOVVFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPOVVFindActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtPOCfind, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dcFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dcTo, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPOVVFind)
.addContainerGap(18, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(dcFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dcTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPOCfind, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addComponent(jLabel1)
.addComponent(jLabel3))
.addContainerGap(24, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnPOVVFind)
.addGap(0, 0, Short.MAX_VALUE))
);
tblPOVC.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null}
},
new String [] {
"#", "Ref.Code", "PO No", "Customer Name", "Issued date", "Status"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
false, true, false, false, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblPOVC.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
tblPOVCMouseReleased(evt);
}
});
jScrollPane1.setViewportView(tblPOVC);
if (tblPOVC.getColumnModel().getColumnCount() > 0) {
tblPOVC.getColumnModel().getColumn(0).setMaxWidth(40);
tblPOVC.getColumnModel().getColumn(1).setMaxWidth(70);
tblPOVC.getColumnModel().getColumn(2).setMaxWidth(70);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnPOVVFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPOVVFindActionPerformed
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String fDate=null;
String tDate=null;
Date FromDate = dcFrom.getDate();
Date ToDate = dcTo.getDate();
if (FromDate != null & ToDate != null) {
int comp = FromDate.compareTo(ToDate);
if (comp <= 0) {
fDate = df.format(FromDate);
tDate = df.format(ToDate);
} else {
JOptionPane.showMessageDialog(rootPane, "From Date is Higher than To Date!", "Oops", JOptionPane.INFORMATION_MESSAGE);
}
} else if (FromDate != null) {
fDate = df.format(FromDate);
} else if (ToDate != null) {
tDate = df.format(ToDate);
}
this.findSalesOrderByFilter(txtPOCfind.getText(), fDate, tDate);
}//GEN-LAST:event_btnPOVVFindActionPerformed
private void tblPOVCMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPOVCMouseReleased
DefaultTableModel dtm = (DefaultTableModel) tblPOVC.getModel();
int Status;
if(Boolean.parseBoolean(dtm.getValueAt(tblPOVC.getSelectedRow(), 4).toString())){Status=1;}
else
{
Status=0;
}
SalesOrder obj=new SalesOrder();
obj.setRefCode(Integer.parseInt(dtm.getValueAt(tblPOVC.getSelectedRow(), 1).toString()));
obj.setStatus(Status);
boolean result = new SalesOrder().updateSalesOrder(obj);
if (result) {
if (Status==1) {
JOptionPane.showMessageDialog(rootPane, "SalesOrder Activated Successfully", "Oparation Complete", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(rootPane, "SalesOrder Canceled Successfully", "Oparation Incomplete", JOptionPane.INFORMATION_MESSAGE);
} } else {
JOptionPane.showMessageDialog(rootPane, "Error in Oparation", "Oparation Incomplete", JOptionPane.ERROR);
}
}//GEN-LAST:event_tblPOVCMouseReleased
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ViewEnteredPOfrmCustomers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewEnteredPOfrmCustomers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewEnteredPOfrmCustomers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewEnteredPOfrmCustomers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ViewEnteredPOfrmCustomers().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnPOVVFind;
private com.toedter.calendar.JDateChooser dcFrom;
private com.toedter.calendar.JDateChooser dcTo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblPOVC;
private javax.swing.JTextField txtPOCfind;
// End of variables declaration//GEN-END:variables
private void loadTable() {
SalesOrder POobj = new SalesOrder();
ArrayList<SalesOrder> POList = POobj.loadSalesOrder();
if (POList.isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Sorry ! No PO Found.");
} else {
DefaultTableModel dtm = (DefaultTableModel) tblPOVC.getModel();
dtm.setRowCount(0);
int count = 0;
while (POList.size() > count) {
Vector v = new Vector();
SalesOrder po = new SalesOrder();
po = POList.get(count);
v.add(count + 1);
v.add(po.getRefCode());
v.add(po.getPoNo());
v.add(po.getCustomer());
v.add(po.getDate());
if(po.getStatus()==1) {v.add(true);} else {v.add(false);}
dtm.addRow(v);
count++;
}
}
}
private void findSalesOrderByFilter(String customer,String fDate,String tDate) {
SalesOrder POobj = new SalesOrder();
ArrayList<SalesOrder> POList = POobj.searchSalesOrderByFilter(customer, fDate, tDate);
if (POList.isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Sorry ! No Sales Order Found.");
} else {
DefaultTableModel dtm = (DefaultTableModel) tblPOVC.getModel();
dtm.setRowCount(0);
int count = 0;
while (POList.size() > count) {
Vector v = new Vector();
SalesOrder po = new SalesOrder();
po = POList.get(count);
v.add(count + 1);
v.add(po.getRefCode());
v.add(po.getPoNo());
v.add(po.getCustomer());
v.add(po.getDate());
if(po.getStatus()==1) {v.add(true);} else {v.add(false);}
dtm.addRow(v);
count++;
}
}
}
}
| true |
c6597b8680799413da32e2a47b35bd143e3c2694 | Java | jeonhyungseop/hyungseop | /src/main/java/kr/or/ddit/cfms/head/changeatt/dao/IHeadChangeAttDAO.java | UTF-8 | 1,286 | 1.828125 | 2 | [] | no_license | package kr.or.ddit.cfms.head.changeatt.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import kr.or.ddit.cfms.commons.vo.PagingVO;
import kr.or.ddit.cfms.head.changeatt.vo.ChangeAttendanceListVO;
import kr.or.ddit.cfms.head.commute.vo.DclzVO;
/**
* @author 진예은
* @since 2021. 6. 7
* @version 1.0
* @see javax.servlet.http.HttpServlet
* <pre>
* [[개정이력(Modification Information)]]
* 수정일 수정자 수정내용
* -------- -------- ----------------------
* 2021. 6. 11 진예은 수정요청관리
* 2021, 6. 14 진예은 수정요청 반려
* Copyright (c) 2021 by DDIT All right reserved
* </pre>
*/
@Repository
public interface IHeadChangeAttDAO {
//수정요청관리
public List<DclzVO> selectChangeAtt(PagingVO<DclzVO> pagingVO);
//수정요청관리 COUNT
public int selectChangeAttCount(PagingVO<DclzVO> pagingVO);
//수정요청 승인
public int ChangeOKUpdate(DclzVO dclzVO);
//수정요청 승인
public int ChangeOKBeforeUpdate(DclzVO dclzVO);
//수정요청 반려
public int ChangeRejectUpdate(int seq);
//수정 일괄승인
public int ChangeAllUpdate(ChangeAttendanceListVO changeAttendanceListVO);
}
| true |
4417eb942f2dbb91b53e0d9c20aa3776b9c745f8 | Java | wh0amis/caex | /hotdog-after-end-master/hotdog-contract/contract-common/src/main/java/com/contract/dao/CWalletHitstoryMapper.java | UTF-8 | 2,974 | 1.835938 | 2 | [] | no_license | package com.contract.dao;
import com.contract.entity.CWalletHitstory;
import com.contract.entity.CWalletHitstoryExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface CWalletHitstoryMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int countByExample(CWalletHitstoryExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int deleteByExample(CWalletHitstoryExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int deleteByPrimaryKey(@Param("id") Integer id, @Param("cid") Integer cid, @Param("type") String type);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int insert(CWalletHitstory record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int insertSelective(CWalletHitstory record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
List<CWalletHitstory> selectByExample(CWalletHitstoryExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
CWalletHitstory selectByPrimaryKey(@Param("id") Integer id, @Param("cid") Integer cid, @Param("type") String type);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int updateByExampleSelective(@Param("record") CWalletHitstory record, @Param("example") CWalletHitstoryExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int updateByExample(@Param("record") CWalletHitstory record, @Param("example") CWalletHitstoryExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(CWalletHitstory record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table c_wallet_hitstory
*
* @mbggenerated
*/
int updateByPrimaryKey(CWalletHitstory record);
} | true |
e80b8895dc199776a75fe7dfe9b87b382190ad4f | Java | vvshuai/vvs-coupon | /vvs-coupon-service/coupon-distribution/src/main/java/org/vvs/coupon/entity/Coupon.java | UTF-8 | 2,325 | 2.21875 | 2 | [] | no_license | package org.vvs.coupon.entity;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.vvs.coupon.constant.CouponStatus;
import org.vvs.coupon.converter.CouponStatusConverter;
import org.vvs.coupon.serialization.CouponSerialize;
import org.vvs.coupon.vo.CouponTemplateSDK;
import javax.persistence.*;
import java.util.Date;
/**
* @Author: vvshuai
* @Description: 优惠券 用户领取的实体表
* @Date: Created in 21:51 2020/12/2
* @Modified By:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "coupon")
@JsonSerialize(using = CouponSerialize.class)
public class Coupon {
/** 自增主键 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Integer id;
/** 关联优惠券模板主键(逻辑外键)*/
@Column(name = "template_id", nullable = false)
private Integer templateId;
/** 领取用户 */
@Column(name = "user_id", nullable = false)
private Long userId;
/** 优惠券码 */
@Column(name = "coupon_code", nullable = false)
private String couponCode;
/** 领取时间 */
@CreatedDate
@Column(name = "assign_time", nullable = false)
private Date assignTime;
/** 优惠券状态 */
@Basic
@Column(name = "status", nullable = false)
@Convert(converter = CouponStatusConverter.class)
private CouponStatus status;
/** 用户优惠券 模板信息 */
@Transient
private CouponTemplateSDK templateSDK;
/**
* @Description: 返回一个无效的coupon对象
* @return: org.vvs.coupon.entity.Coupon
*/
public static Coupon invalidCoupon() {
Coupon coupon = new Coupon();
coupon.setId(-1);
return coupon;
}
/**
* @Description:
* @return:
*/
public Coupon(Integer templateId, Long userId, String couponCode,
CouponStatus status) {
this.templateId = templateId;
this.userId = userId;
this.couponCode = couponCode;
this.status = status;
}
}
| true |
727678011193ec993522c95b5f2cf21aaa31dab1 | Java | Cyebukayire/devops-junit-testing | /src/main/java/com/example/classbjunit/controller/ItemController.java | UTF-8 | 541 | 1.9375 | 2 | [] | no_license | package com.example.classbjunit.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.classbjunit.model.Item;
import com.example.classbjunit.service.ItemService;
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
@GetMapping("/all-items")
public List<Item> getAll(){
return itemService.getAll();
}
}
| true |
7f71ef88cb8f6eb5981d2f622237a0b7b7d0eace | Java | hakanorak21/Java-Interview | /ersin/CharFrequency.java | UTF-8 | 495 | 3.046875 | 3 | [] | no_license | package ersin;
public class CharFrequency {
public static void main(String[] args) {
String str = "AAABBCDD";
System.out.print("method 1: ");
m1(str);
}
public static String m1(String str) {
String nstr = "";
while (str.length()!=0) {
int size = str.length();
String temp = str.substring(0,1);
str = str.replace(temp, "");
int freq = size - str.length();
nstr += temp + freq;
}
System.out.println(nstr);
return nstr;
}
}
| true |
a3176184dd76635e5db98fa6a1213984b1b064c5 | Java | jgomezpe/uniltiranyu | /java/uniltiranyu/examples/games/sokoban/SokobanBoardDrawer.java | UTF-8 | 3,171 | 2.765625 | 3 | [] | no_license | package uniltiranyu.examples.games.sokoban;
import java.awt.Color;
import java.awt.Graphics;
import uniltiranyu.simulate.SimulatedAgent;
import uniltiranyu.simulate.gui.Drawer;
public class SokobanBoardDrawer extends Drawer {
public static int DIMENSION = 15;
public static int DRAW_AREA_SIZE = 400;
public static int CELL_SIZE = 20;
public static int MARGIN = 10;
public static int SHAPE_SIZE = 1;
protected int getCanvasValue( int val ){
return val*CELL_SIZE+MARGIN;
}
@Override
public void paint(Graphics g) {
if( environment != null && ((SokobanEnvironment)environment).board != null ){
SokobanEnvironment env = (SokobanEnvironment)environment;
SokobanBoard b = env.board;
int n = b.rows();
int m = b.columns();
DIMENSION = Math.max(n, m);
CELL_SIZE = DRAW_AREA_SIZE / (DIMENSION+1);
MARGIN = CELL_SIZE / 2;
g.setColor( Color.lightGray );
int GRID_SIZE = CELL_SIZE * DIMENSION;
for (int i = 0; i <= n; i++) {
int j = getCanvasValue( i );
g.drawLine( j, GRID_SIZE + MARGIN, j, MARGIN );
g.drawLine( GRID_SIZE + MARGIN, j, MARGIN, j );
}
for (int i = 0; i < n; i++) {
int X = getCanvasValue(i);
for (int j = 0; j < m; j++) {
int Y=getCanvasValue(j);
int v = b.get(i, j);
if((v&SokobanBoard.WALL)==SokobanBoard.WALL){
g.setColor( Color.gray );
g.fillRect(X+1, Y+1, CELL_SIZE-2, CELL_SIZE-2);
}
if((v&SokobanBoard.GRASS)==SokobanBoard.GRASS){
g.setColor( Color.green );
g.fillRect(X+1, Y+1, CELL_SIZE-2, CELL_SIZE-2);
}
if((v&SokobanBoard.MARK)==SokobanBoard.MARK){
g.setColor( Color.yellow );
g.fillRect(X+CELL_SIZE/4, Y+CELL_SIZE/4, CELL_SIZE/2, CELL_SIZE/2);
}
if((v&SokobanBoard.BLOCK)==SokobanBoard.BLOCK){
if((v&SokobanBoard.MARK)==SokobanBoard.MARK) g.setColor( Color.cyan );
else g.setColor( Color.pink );
g.fillRect(X+2, Y+2, CELL_SIZE-4, CELL_SIZE-4);
}
}
}
SimulatedAgent a = (SimulatedAgent)env.agent();
int direction = ((Integer) a.getAttribute(SokobanEnvironment.D)).intValue();
int x = ((Integer) a.getAttribute(SokobanEnvironment.X)).intValue();
int y = ((Integer) a.getAttribute(SokobanEnvironment.Y)).intValue();
boolean play_mode = ((Boolean) a.getAttribute(SokobanUtil.MODE)).booleanValue();
if( play_mode) g.setColor( Color.black ); else g.setColor(Color.lightGray);
int X = getCanvasValue( x );
int Y = getCanvasValue( y );
int EYE_SIZE = 6;
g.drawOval( X + EYE_SIZE/2, Y + EYE_SIZE/2, CELL_SIZE - EYE_SIZE, CELL_SIZE - EYE_SIZE );
switch( direction ){
case 0: g.drawOval( X + CELL_SIZE/2 - EYE_SIZE/2, Y , EYE_SIZE, EYE_SIZE); break;
case 1: g.drawOval( X + CELL_SIZE - EYE_SIZE, Y + CELL_SIZE/2 - EYE_SIZE/2, EYE_SIZE, EYE_SIZE); break;
case 2: g.drawOval( X + CELL_SIZE/2 - EYE_SIZE/2, Y + CELL_SIZE - EYE_SIZE, EYE_SIZE, EYE_SIZE); break;
case 3: g.drawOval( X, Y + CELL_SIZE/2 - EYE_SIZE/2, EYE_SIZE, EYE_SIZE); break;
}
}
}
@Override
public void setDimension(int width, int height) {
DRAW_AREA_SIZE = Math.min(width,height);
}
} | true |
3944a65c3a37989120c2325b313b006cd3345882 | Java | xuanqizi/TicketPurchase | /ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/SignUpBody.java | UTF-8 | 720 | 1.984375 | 2 | [
"MIT"
] | permissive | package com.ruoyi.common.core.domain.model;
/**
* 用户注册对象
*
* @author Zhenxi Chen
* @date 2021/6/3
*/
public class SignUpBody {
private String phone; // 手机号
private String password; // 密码
private String username; // 用户名
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
| true |
6c0266cdc2a7d760bbd386e27ff268f7001d32e4 | Java | tapakkur/hello-spring-boot | /src/main/java/ApplicationRun.java | UTF-8 | 899 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
/**
* @author tapakkur
* @ProjectName hello-spring-boot
* @Date 2019/4/7 12:19
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.tapakkur.demo_springboot"})
public class ApplicationRun implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(ApplicationRun.class);
public static void main(String[] args) {
SpringApplication.run(ApplicationRun.class,args);
}
public void run(String... args) throws Exception {
logger.info("The service has been started ...");
}
}
| true |
fd5ea310998058e6b00e213d016bf0e627db04c9 | Java | Jigiang/distributed-lock | /distributed-lock-spring-boot-starter/src/main/java/com/github/zhuobinchan/distributed/lock/spring/configuration/DistributedLockProperties.java | UTF-8 | 1,708 | 1.929688 | 2 | [
"Apache-2.0"
] | permissive | package com.github.zhuobinchan.distributed.lock.spring.configuration;
import com.github.zhuobinchan.distributed.lock.core.config.DistributedLockConfig;
import com.github.zhuobinchan.distributed.lock.core.config.RedissonConfig;
import com.github.zhuobinchan.distributed.lock.core.config.ZookeeperConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author zhuobin chan on 2020-12-22 15:28
*/
@Component
@ConfigurationProperties(
prefix = "spring.distributed.lock", ignoreInvalidFields = true
)
public class DistributedLockProperties {
private boolean enable;
private LockType lockType;
private DistributedLockConfig config;
private RedissonConfig redissonConfig;
private ZookeeperConfig zookeeperConfig;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public LockType getLockType() {
return lockType;
}
public void setLockType(LockType lockType) {
this.lockType = lockType;
}
public DistributedLockConfig getConfig() {
return config;
}
public void setConfig(DistributedLockConfig config) {
this.config = config;
}
public RedissonConfig getRedissonConfig() {
return redissonConfig;
}
public void setRedissonConfig(RedissonConfig redissonConfig) {
this.redissonConfig = redissonConfig;
}
public ZookeeperConfig getZookeeperConfig() {
return zookeeperConfig;
}
public void setZookeeperConfig(ZookeeperConfig zookeeperConfig) {
this.zookeeperConfig = zookeeperConfig;
}
}
| true |
122346636b182b1e2d18b551c70a350de3285288 | Java | nyutopia/toutiao | /src/main/java/com/ny/toutiao/service/UserService.java | UTF-8 | 3,313 | 2.25 | 2 | [] | no_license | package com.ny.toutiao.service;
import com.ny.toutiao.dao.LoginTicketDAO;
import com.ny.toutiao.dao.UserDAO;
import com.ny.toutiao.model.LoginTicket;
import com.ny.toutiao.model.User;
import com.ny.toutiao.util.ToutiaoUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* Created by ny on 2017/8/1.
*/
@Service
public class UserService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
private UserDAO userDAO;
@Autowired
private LoginTicketDAO loginTicketDAO;
public Map<String,Object> register(String username, String password){
Map<String,Object> map = new HashMap<>();
if(StringUtils.isBlank(username)){
map.put("msgname","用户名不能为空");
return map;
}
if(StringUtils.isBlank(password)){
map.put("msgpwd","密码不能为空");
return map;
}
User user = userDAO.selectaByName(username);
if(user!=null){
map.put("masgname","用户名已经被注册");
return map;
}
user = new User();
user.setName(username);
// user.setPassword(password);
user.setSalt(UUID.randomUUID().toString().substring(0,5));
user.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
user.setPassword(ToutiaoUtil.MD5(password+user.getSalt()));
userDAO.addUser(user);
//登录
String ticket = addLoginTicket(user.getId());
map.put("ticket",ticket);
return map;
}
public Map<String,Object> login(String username, String password){
Map<String,Object> map = new HashMap<>();
if(StringUtils.isBlank(username)){
map.put("msgname","用户名不能为空");
return map;
}
if(StringUtils.isBlank(password)){
map.put("msgpwd","密码不能为空");
return map;
}
User user = userDAO.selectaByName(username);
if(user==null){
map.put("msgname","用户名不存在");
return map;
}
if(!ToutiaoUtil.MD5(password+user.getSalt()).equals(user.getPassword())){
map.put("msgpwd","密码不正确");
return map;
}
map.put("userId",user.getId());
//ticket
String ticket = addLoginTicket(user.getId());
map.put("ticket",ticket);
return map;
}
private String addLoginTicket(int userId){
LoginTicket ticket = new LoginTicket();
ticket.setUserId(userId);
Date date = new Date();
//5天的有效期
date.setTime(date.getTime()+1000*3600*24*5);
ticket.setExpired(date);
ticket.setStatus(0);
ticket.setTicket(UUID.randomUUID().toString().replaceAll("-",""));
loginTicketDAO.addTicket(ticket);
return ticket.getTicket();
}
public User getUser(int id){
return userDAO.selectaById(id);
}
public void logout(String ticket){
loginTicketDAO.updateStatus(ticket,1);
}
}
| true |
0df1bbff3c5f6823f66332daefa9053bc9ccb3b1 | Java | abcijkxyz/jump-pilot | /plug-ins/de.soldin.jump/trunk/src/org/dinopolis/gpstool/GPSTool.java | UTF-8 | 33,013 | 1.53125 | 2 | [] | no_license | /***********************************************************************
* @(#)$RCSfile: GPSTool.java,v $ $Revision: 1.5 $ $Date: 2006/10/23 08:15:38 $
*
* Copyright (c) 2001 IICM, Graz University of Technology
* Copyright (c) 2001-2003 Sandra Brueckler, Stefan Feitl
* Written during an XPG-Project at the IICM of the TU-Graz, Austria
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
package org.dinopolis.gpstool;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.imageio.ImageIO;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.dinopolis.gpstool.gpsinput.GPSDataProcessor;
import org.dinopolis.gpstool.gpsinput.GPSDevice;
import org.dinopolis.gpstool.gpsinput.GPSException;
import org.dinopolis.gpstool.gpsinput.GPSFileDevice;
import org.dinopolis.gpstool.gpsinput.GPSPosition;
import org.dinopolis.gpstool.gpsinput.GPSRawDataFileLogger;
import org.dinopolis.gpstool.gpsinput.GPSRawDataListener;
import org.dinopolis.gpstool.gpsinput.GPSRoute;
import org.dinopolis.gpstool.gpsinput.GPSSerialDevice;
import org.dinopolis.gpstool.gpsinput.GPSTrack;
import org.dinopolis.gpstool.gpsinput.GPSWaypoint;
import org.dinopolis.gpstool.gpsinput.SatelliteInfo;
import org.dinopolis.gpstool.gpsinput.garmin.GPSGarminDataProcessor;
import org.dinopolis.gpstool.gpsinput.nmea.GPSNmeaDataProcessor;
import org.dinopolis.gpstool.gpsinput.sirf.GPSSirfDataProcessor;
import org.dinopolis.gpstool.gpx.ReadGPX;
import org.dinopolis.util.ProgressListener;
import org.dinopolis.util.commandarguments.CommandArgumentException;
import org.dinopolis.util.commandarguments.CommandArguments;
import org.dinopolis.util.text.OneArgumentMessageFormat;
//----------------------------------------------------------------------
/**
* Demo application to show the usage of the org.dinopolis.gpstool.gpsinput package (read and
* interpret gps data from various devices (serial, file, ...). <p>
* It uses a velocity (http://jakarta.apache.org/velocity) template to
* print the downloaded tracks, routes, and waypoints. See the help
* output for details about the usable variables.
*
* @author Christof Dallermassl, Stefan Feitl
* @version $Revision: 1.5 $
*/
public class GPSTool implements PropertyChangeListener, ProgressListener
{
protected boolean gui_ = true;
protected GPSDataProcessor gps_processor_;
public final static String DEFAULT_TEMPLATE =
"<?xml version=\"1.0\"?>"
+"$dateformatter.applyPattern(\"yyyy-MM-dd'T'HH:mm:ss'Z'\")"
+"$longitudeformatter.applyPattern(\"0.000000\")"
+"$latitudeformatter.applyPattern(\"0.000000\")"
+"$altitudeformatter.applyPattern(\"0\")\n"
+"<gpx"
+" version=\"1.0\"\n"
+" creator=\"$author\"\n"
+" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+" xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
+" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n"
+" <time>$dateformatter.format($creation_date)</time>\n"
+" <bounds minlat=\"$min_latitude\" minlon=\"$min_longitude\"\n"
+" maxlat=\"$max_latitude\" maxlon=\"$max_longitude\"/>\n"
+"\n"
+"## print all waypoints that are available:\n"
+"#if($printwaypoints)\n"
+"#foreach( $point in $waypoints )\n"
+" <wpt lat=\"$latitudeformatter.format($point.Latitude)\" lon=\"$longitudeformatter.format($point.Longitude)\">\n"
+"#if($point.hasValidAltitude())\n"
+" <ele>$altitudeformatter.format($point.Altitude)</ele>\n"
+"#end\n"
+" <name>$!point.Identification</name>\n"
+"#if($point.getComment().length() > 0)\n"
+" <desc>![CDATA[$!point.Comment]]</desc>\n"
+"#end\n"
+"#if($point.getSymbolName())\n"
+" <sym>$point.getSymbolName()</sym>\n"
+"#end\n"
+" </wpt>\n"
+"#end\n"
+"#end\n"
+"## print all routes that are available:\n"
+"#if($printroutes)\n"
+"#foreach( $route in $routes )\n"
+" <rte>\n"
+" <name>$!route.Identification</name>\n"
+"#if($route.getComment().length() > 0)\n"
+" <desc>![CDATA[$!route.Comment]]</desc>\n"
+"#end\n"
+" <number>$velocityCount</number>\n"
+"#set ($points = $route.getWaypoints())\n"
+"#foreach ($point in $points)\n"
+" <rtept lat=\"$latitudeformatter.format($point.Latitude)\" lon=\"$longitudeformatter.format($point.Longitude)\">\n"
+"#if($point.hasValidAltitude())\n"
+" <ele>$altitudeformatter.format($point.Altitude)</ele>\n"
+"#end\n"
+"#if($point.getIdentification().length() > 0)\n"
+" <name>![CDATA[$!point.Identification]]</name>\n"
+"#end\n"
+"#if($point.getComment().length() > 0)\n"
+" <desc>![CDATA[$!point.Comment]]</desc>\n"
+"#end\n"
+" </rtept>\n"
+"#end\n"
+" </rte>\n"
+"#end\n"
+"#end\n"
+"## print all tracks that are available:\n"
+"#if($printtracks)\n"
+"#foreach( $track in $tracks )\n"
+"#set($close_segment = false)\n"
+" <trk>\n"
+" <name>$!track.Identification</name>\n"
+"#if($point.getComment().length() > 0)\n"
+" <desc>![CDATA[$!point.Comment]]</desc>\n"
+"#end\n"
+"## <number>$velocityCount</number>\n"
+"#set ($points = $track.getWaypoints())##\n"
+"#foreach ($point in $points)##\n"
+"#if($point.isNewTrack())\n"
+"#if($close_segment)## close trkseg, if not the first occurence\n"
+" </trkseg>\n"
+"#end\n"
+" <trkseg>\n"
+"#set($close_segment = true)\n"
+"#end\n"
+" <trkpt lat=\"$latitudeformatter.format($point.Latitude)\" lon=\"$longitudeformatter.format($point.Longitude)\">\n"
+"#if($point.hasValidAltitude())\n"
+" <ele>$altitudeformatter.format($point.Altitude)</ele>\n"
+"#end\n"
+"#if($point.getDate())## only if there is a time set! \n"
+" <time>$dateformatter.format($point.getDate())</time>\n"
+"#end\n"
+" </trkpt>\n"
+"#end\n"
+"#if($close_segment)\n"
+" </trkseg>\n"
+"#end\n"
+" </trk>\n"
+"#end\n"
+"#end\n"
+"</gpx>\n";
//----------------------------------------------------------------------
/**
* Default constructor
*/
public GPSTool()
{
}
//----------------------------------------------------------------------
/**
* Initialize the gps device, the gps data processor and handle all
* command line arguments.
* @param arguments the command line arguments
*/
public void init(String[] arguments)
{
if(arguments.length < 1)
{
printHelp();
return;
}
String[] valid_args =
new String[] {"device*","d*","help","h","speed#","s#","file*","f*",
"nmea","n","garmin","g","sirf","i","rawdata","downloadtracks",
"downloadwaypoints","downloadroutes","deviceinfo","printposonce",
"printpos","p","printalt","printspeed","printheading","printsat",
"template*","outfile*","screenshot*", "printdefaulttemplate",
"helptemplate","nmealogfile*","l","uploadtracks","uploadroutes",
"uploadwaypoints","infile*"};
// Check command arguments
// Throw exception if arguments are invalid
CommandArguments args = null;
try
{
args = new CommandArguments(arguments,valid_args);
}
catch(CommandArgumentException cae)
{
System.err.println("Invalid arguments: "+cae.getMessage());
printHelp();
return;
}
// Set default values
String filename = null;
String serial_port_name = null;
int serial_port_speed = -1;
GPSDataProcessor gps_data_processor;
String nmea_log_file = null;
// Handle given command arguments
if (args.isSet("help") || (args.isSet("h")))
{
printHelp();
return;
}
if(args.isSet("helptemplate"))
{
printHelpTemplate();
}
if (args.isSet("printdefaulttemplate"))
{
System.out.println(DEFAULT_TEMPLATE);
}
if (args.isSet("device"))
{
serial_port_name = (String)args.getValue("device");
}
else
if (args.isSet("d"))
{
serial_port_name = (String)args.getValue("d");
}
if (args.isSet("speed"))
{
serial_port_speed = ((Integer)args.getValue("speed")).intValue();
}
else
if (args.isSet("s"))
{
serial_port_speed = ((Integer)args.getValue("s")).intValue();
}
if (args.isSet("file"))
{
filename = (String)args.getValue("file");
}
else
if (args.isSet("f"))
{
filename = (String)args.getValue("f");
}
if (args.isSet("garmin") || args.isSet("g"))
{
gps_data_processor = new GPSGarminDataProcessor();
serial_port_speed = 9600;
if(filename != null)
{
System.err.println("ERROR: Cannot read garmin data from file, only serial port supported!");
return;
}
}
else
if (args.isSet("sirf") || args.isSet("i"))
{
gps_data_processor = new GPSSirfDataProcessor();
serial_port_speed = 19200;
if(filename != null)
{
System.err.println("ERROR: Cannot read sirf data from file, only serial port supported!");
return;
}
}
else
// default: if (args.isSet("nmea") || args.isSet("n"))
{
gps_data_processor = new GPSNmeaDataProcessor();
serial_port_speed = 4800;
}
if (args.isSet("nmealogfile") || (args.isSet("l")))
{
if(args.isSet("nmealogfile"))
nmea_log_file = args.getStringValue("nmealogfile");
else
nmea_log_file = args.getStringValue("l");
}
if (args.isSet("rawdata"))
{
gps_data_processor.addGPSRawDataListener(
new GPSRawDataListener()
{
public void gpsRawDataReceived(char[] data, int offset, int length)
{
System.out.println("RAWLOG: "+new String(data,offset,length));
}
});
}
// Define device to read data from
GPSDevice gps_device;
Hashtable environment = new Hashtable();
if (filename != null)
{
environment.put(GPSFileDevice.PATH_NAME_KEY,filename);
gps_device = new GPSFileDevice();
}
else
{
if (serial_port_name != null)
environment.put(GPSSerialDevice.PORT_NAME_KEY,serial_port_name);
if (serial_port_speed > -1)
environment.put(GPSSerialDevice.PORT_SPEED_KEY,new Integer(serial_port_speed));
gps_device = new GPSSerialDevice();
}
try
{
// set params needed to open device (file,serial, ...):
gps_device.init(environment);
// connect device and data processor:
gps_data_processor.setGPSDevice(gps_device);
gps_data_processor.open();
// use progress listener to be informed about the number
// of packages to download
gps_data_processor.addProgressListener(this);
// raw data logger (to file):
if((nmea_log_file != null) && (nmea_log_file.length() > 0))
{
gps_data_processor.addGPSRawDataListener(new GPSRawDataFileLogger(nmea_log_file));
}
// check, what to do:
if(args.isSet("deviceinfo"))
{
System.out.println("GPSInfo:");
String[] infos = gps_data_processor.getGPSInfo();
for(int index=0; index < infos.length; index++)
{
System.out.println(infos[index]);
}
}
if(args.isSet("screenshot"))
{
FileOutputStream out = new FileOutputStream((String)args.getValue("screenshot"));
BufferedImage image = gps_data_processor.getScreenShot();
ImageIO.write(image,"PNG",out);
}
boolean print_waypoints = args.isSet("downloadwaypoints");
boolean print_routes = args.isSet("downloadroutes");
boolean print_tracks = args.isSet("downloadtracks");
if(print_waypoints || print_routes || print_tracks)
{
// create context for template printing:
VelocityContext context = new VelocityContext();
if(print_waypoints)
{
List waypoints = gps_data_processor.getWaypoints();
if(waypoints != null)
context.put("waypoints",waypoints);
else
print_waypoints = false;
// System.out.println(waypoints);
}
if(print_tracks)
{
List tracks = gps_data_processor.getTracks();
if(tracks != null)
context.put("tracks",tracks);
else
print_tracks = false;
// System.out.println(tracks);
}
if(print_routes)
{
List routes = gps_data_processor.getRoutes();
if(routes != null)
context.put("routes",routes);
else
print_routes = false;
// System.out.println(routes);
}
// download finished, prepare context:
context.put("printwaypoints",new Boolean(print_waypoints));
context.put("printtracks",new Boolean(print_tracks));
context.put("printroutes",new Boolean(print_routes));
Writer writer;
Reader reader;
if(args.isSet("template"))
{
String template_file = (String)args.getValue("template");
reader = new FileReader(template_file);
}
else
{
reader = new StringReader(DEFAULT_TEMPLATE);
}
if(args.isSet("outfile"))
writer = new FileWriter((String)args.getValue("outfile"));
else
writer = new OutputStreamWriter(System.out);
addDefaultValuesToContext(context);
boolean result = printTemplate(context,reader,writer);
}
boolean read_waypoints = (args.isSet("uploadwaypoints") && args.isSet("infile"));
boolean read_routes = (args.isSet("uploadroutes") && args.isSet("infile"));
boolean read_tracks = (args.isSet("uploadtracks") && args.isSet("infile"));
if(read_waypoints || read_routes || read_tracks)
{
// Create GPX file parser
ReadGPX reader = new ReadGPX();
String in_file = (String)args.getValue("infile");
// Parse given input file
reader.parseFile(in_file);
// Upload read data to attached gps device
if (read_waypoints)
gps_data_processor.setWaypoints(reader.getWaypoints());
if (read_routes)
gps_data_processor.setRoutes(reader.getRoutes());
if (read_tracks)
gps_data_processor.setTracks(reader.getTracks());
}
if(args.isSet("printposonce"))
{
GPSPosition pos = gps_data_processor.getGPSPosition();
System.out.println("Current Position: "+pos);
}
// register as listener to be informed about the chosen events
if(args.isSet("printpos") || args.isSet("p"))
{
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.LOCATION,this);
}
if(args.isSet("printalt"))
{
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE,this);
}
if(args.isSet("printspeed"))
{
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SPEED,this);
}
if(args.isSet("printheading"))
{
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.HEADING,this);
}
if(args.isSet("printsat"))
{
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES,this);
gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO,this);
}
if(args.isSet("printpos") || args.isSet("p") || args.isSet("printalt")
|| args.isSet("printsat") || args.isSet("printspeed") || args.isSet("printheading"))
{
// tell gps processor to send curren position once every second:
gps_data_processor.startSendPositionPeriodically(1000L);
try
{
// wait for user pressing enter:
System.in.read();
}
catch(IOException ignore) {}
}
// close device and processor:
//gps_data_processor.close();
}
catch(GPSException e)
{
e.printStackTrace();
}
catch(FileNotFoundException fnfe)
{
System.err.println("ERROR: File not found: "+fnfe.getMessage());
}
catch(IOException ioe)
{
System.err.println("ERROR: I/O Error: "+ioe.getMessage());
}
}
//----------------------------------------------------------------------
/**
* Adds some important values to the velocity context (e.g. date, ...).
*
* @param context the velocity context holding all the data
*/
public void addDefaultValuesToContext(VelocityContext context)
{
DecimalFormat latitude_formatter = (DecimalFormat)NumberFormat.getInstance(Locale.US);
latitude_formatter.applyPattern("0.0000000");
DecimalFormat longitude_formatter = (DecimalFormat)NumberFormat.getInstance(Locale.US);
longitude_formatter.applyPattern("0.0000000");
DecimalFormat altitude_formatter = (DecimalFormat)NumberFormat.getInstance(Locale.US);
altitude_formatter.applyPattern("000000");
OneArgumentMessageFormat string_formatter = new OneArgumentMessageFormat("{0}",Locale.US);
context.put("dateformatter",new SimpleDateFormat());
context.put("latitudeformatter", latitude_formatter);
context.put("longitudeformatter", longitude_formatter);
context.put("altitudeformatter", altitude_formatter);
context.put("stringformatter", string_formatter);
// current time, date
Calendar now = Calendar.getInstance();
context.put("creation_date",now.getTime());
// int day = now.get(Calendar.DAY_OF_MONTH);
// int month = now.get(Calendar.MONTH);
// int year = now.get(Calendar.YEAR);
// int hour = now.get(Calendar.HOUR_OF_DAY);
// int minute = now.get(Calendar.MINUTE);
// int second = now.get(Calendar.SECOND);
// DecimalFormat two_digit_formatter = new DecimalFormat("00");
// context.put("date_day",two_digit_formatter.format((long)day));
// context.put("date_month",two_digit_formatter.format((long)month));
// context.put("date_year",Integer.toString(year));
// context.put("date_hour",two_digit_formatter.format((long)hour));
// context.put("date_minute",two_digit_formatter.format((long)minute));
// context.put("date_second",two_digit_formatter.format((long)second));
// author
context.put("author",System.getProperty("user.name"));
// extent of waypoint, routes and tracks:
double min_latitude = 90.0;
double min_longitude = 180.0;
double max_latitude = -90.0;
double max_longitude = -180.0;
List routes = (List)context.get("routes");
GPSRoute route;
if(routes != null)
{
Iterator route_iterator = routes.iterator();
while(route_iterator.hasNext())
{
route = (GPSRoute)route_iterator.next();
min_longitude = route.getMinLongitude();
max_longitude = route.getMaxLongitude();
min_latitude = route.getMinLatitude();
max_latitude = route.getMaxLatitude();
}
}
List tracks = (List)context.get("tracks");
GPSTrack track;
if(tracks != null)
{
Iterator track_iterator = tracks.iterator();
while(track_iterator.hasNext())
{
track = (GPSTrack)track_iterator.next();
min_longitude = Math.min(min_longitude,track.getMinLongitude());
max_longitude = Math.max(max_longitude,track.getMaxLongitude());
min_latitude = Math.min(min_latitude,track.getMinLatitude());
max_latitude = Math.max(max_latitude,track.getMaxLatitude());
}
}
List waypoints = (List)context.get("waypoints");
GPSWaypoint waypoint;
if(waypoints != null)
{
Iterator waypoint_iterator = waypoints.iterator();
while(waypoint_iterator.hasNext())
{
waypoint = (GPSWaypoint)waypoint_iterator.next();
min_longitude = Math.min(min_longitude,waypoint.getLongitude());
max_longitude = Math.max(max_longitude,waypoint.getLongitude());
min_latitude = Math.min(min_latitude,waypoint.getLatitude());
max_latitude = Math.max(max_latitude,waypoint.getLatitude());
}
}
context.put("min_latitude",new Double(min_latitude));
context.put("min_longitude",new Double(min_longitude));
context.put("max_latitude",new Double(max_latitude));
context.put("max_longitude",new Double(max_longitude));
}
//----------------------------------------------------------------------
/**
* Prints the given context with the given velocity template to the
* given output writer.
*
* @param context the velocity context holding all the data
* @param template the reader providing the template to use
* @param out the writer to write the result to.
* @return true if successfull, false otherwise (see velocity log for
* details then).
* @throws IOException if an error occurs
*/
public boolean printTemplate(VelocityContext context,Reader template, Writer out)
throws IOException
{
boolean result = false;
try
{
Velocity.init();
result = Velocity.evaluate(context,out,"gpstool",template);
out.flush();
out.close();
}
catch(ParseErrorException pee)
{
pee.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
return(result);
}
// public void registerListener()
// {
// System.out.println("------------------------------------------------------------");
// System.out.println("------------------------------------------------------------");
// System.out.println("------------------------------------------------------------");
// try
// {
// // JFrame frame = null;
// // if(gui_)
// // {
// // GPSInfoPanel panel = new GPSInfoPanel();
// // frame = new JFrame("GPS Info");
// // frame.getContentPane().add(panel);
// // frame.pack();
// // frame.setVisible(true);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.LOCATION,panel);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.HEADING,panel);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE,panel);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.SPEED,panel);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES,panel);
// // gps_processor_.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO,panel);
// // }
// System.in.read();
// if(gui_)
// {
// frame.setVisible(false);
// frame.dispose();
// }
// // try
// // {
// // Thread.sleep(200000);
// // }
// // catch(InterruptedException ie)
// // {}
// // gps_processor_.close();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// }
//----------------------------------------------------------------------
/**
* Returns the default template used to print data from the gps device.
*
* @return the default template.
*/
public static String getDefaultTEmplate()
{
return(DEFAULT_TEMPLATE);
}
//----------------------------------------------------------------------
// Callback method for PropertyChangeListener
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/**
* Callback for any changes of the gps data (position, heading, speed,
* etc.).
* @param event the event holding the information.
*/
public void propertyChange(PropertyChangeEvent event)
{
Object value = event.getNewValue();
String name = event.getPropertyName();
if(name.equals(GPSDataProcessor.SATELLITE_INFO))
{
SatelliteInfo[] infos = (SatelliteInfo[])value;
SatelliteInfo info;
for(int count=0; count < infos.length; count++)
{
info = infos[count];
System.out.println("sat "+info.getPRN()+": elev="+info.getElevation()
+ " azim="+info.getAzimuth()+" dB="+info.getSNR());
}
}
else
System.out.println(event.getPropertyName()+": "+event.getNewValue());
}
//----------------------------------------------------------------------
// Callback methods for ProgressListener
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/**
* Callback to inform listeners about an action to start.
*
* @param action_id the id of the action that is started. This id may
* be used to display a message for the user.
* @param min_value the minimum value of the progress counter.
* @param max_value the maximum value of the progress counter. If the
* max value is unknown, max_value is set to <code>Integer.NaN</code>.
*/
public void actionStart(String action_id, int min_value, int max_value)
{
System.err.println("Starting '"+action_id+"' ("+max_value+" packages): ");
}
//----------------------------------------------------------------------
/**
* Callback to inform listeners about progress going on. It is not
* guaranteed that this method is called on every change of current
* value (e.g. only call this method on every 10th change).
*
* @param action_id the id of the action that is started. This id may
* be used to display a message for the user.
* @param current_value the current value
*/
public void actionProgress(String action_id, int current_value)
{
System.err.print("\r"+current_value);
}
//----------------------------------------------------------------------
/**
* Callback to inform listeners about the end of the action.
*
* @param action_id the id of the action that is started. This id may
* be used to display a message for the user.
*/
public void actionEnd(String action_id)
{
System.err.println("\nfinished");
}
//----------------------------------------------------------------------
/**
* Prints the help message for writing templates.
*/
public static void printHelpTemplate()
{
System.out.println("GPSTool is able to write tracks, routes, and waypoints in various");
System.out.println("formats. It uses a velocity template for this. Please see");
System.out.println("http://jakarta.apache.org/velocity for details. GPSTool provides");
System.out.println("the following objects to be used in the template (the type is");
System.out.println("included in parentheses):");
System.out.println(" $waypoints (List of GPSWaypoint objects): the waypoints from the gps device");
System.out.println(" $routes (List of GPSRoute objects): the routes from the gps device");
System.out.println(" $tracks (List of GPSTrack objects) the tracks from the gps device");
System.out.println(" $printwaypoints (Boolean): true, if the user decided to download waypoints");
System.out.println(" $printtracks (Boolean): true, if the user decided to download tracks");
System.out.println(" $printroutes (Boolean): true, if the user decided to download routes");
System.out.println(" $creation_date (java.util.Date): the creation date (now)");
System.out.println(" $author (String): the system property 'user.name'");
System.out.println(" $min_latitude (Double): the minimum latitude of all downloaded data");
System.out.println(" $max_latitude (Double): the maximum latitude of all downloaded data");
System.out.println(" $min_longitude (Double): the minimum longitude of all downloaded data");
System.out.println(" $min_longitude (Double): the maximum longitude of all downloaded data");
System.out.println(" $dateformatter (java.text.SimpleDateFormat): helper object to format dates");
System.out.println("For an example use the commandline switch '--printdefaulttemplate'.");
}
//----------------------------------------------------------------------
/**
* Prints the help messages
*/
public static void printHelp()
{
System.out.println("GPSTool 0.5.2 - Communication between GPS-Devices and Computers via serial port");
System.out.println("(c) 2000-2006 Christof Dallermassl\n");
System.out.println("Usage: java org.dinopolis.gpstool.GPSTool [options]\n");
System.out.println("Options:");
System.out.println("--device, -d <device>, e.g. -d /dev/ttyS0 or COM1 (defaults depending on OS).");
System.out.println("--speed, -s <speed>, e.g. -s 4800 (default for nmea, 9600 for garmin, 19200 for sirf).");
System.out.println("--file, -f <filename>, the gps data is read from the given file.");
System.out.println("--nmea, -n, the gps data is interpreted as NMEA data (default).");
System.out.println("--garmin, -g, the gps data is interpreted as garmin data.");
System.out.println("--sirf, -i, the gps data is interpreted as sirf data.");
System.out.println("--nmealogfile, -l <filename>, the gps data is logged into this file.");
System.out.println("--rawdata, the raw (nmea or garmin) gps data is printed to stdout.");
// System.out.println("--nogui, no frame is opened.\n");
System.out.println("--printposonce, prints the current position and exits again.");
System.out.println("--printpos, -p, prints the current position and any changes.");
System.out.println(" Loops until the user presses 'enter'.");
System.out.println("--printalt, prints the current altitude and any changes.");
System.out.println("--printsat, prints the current satellite info altitude and any changes.");
System.out.println("--printspeed, prints the current speed and any changes.");
System.out.println("--printheading, prints the current heading and any changes.");
System.out.println("--deviceinfo, prints some information about the gps device (if available)");
System.out.println("--screenshot <filename>, saves a screenshot of the gps device in PNG format.");
System.out.println("--downloadtracks, print tracks stored in the gps device.");
System.out.println("--downloadwaypoints, print waypoints stored in the gps device.");
System.out.println("--downloadroutes, print routes stored in the gpsdevice .");
System.out.println("--outfile <filename>, the file to print the tracks, routes and waypoints to, stdout is default");
System.out.println("--template <filename>, the velocity template to use for printing routes, tracks and waypoints");
System.out.println("--printdefaulttemplate, prints the default template used to print routes, waypoints, and tracks.");
System.out.println("--uploadtracks, reads track information from the file given at the infile\n"
+" parameter and uploads it to the gps device.");
System.out.println("--uploadroutes, reads route information from the file given at the infile\n"
+" parameter and uploads it to the gps device.");
System.out.println("--uploadwaypoints, reads waypoint information from the file given at the infile\n"
+" parameter and uploads it to the gps device.");
System.out.println("--infile <filename>, the GPX file to read the tracks, routes and waypoints from");
System.out.println("--helptemplate, prints some more information on how to write a template.");
System.out.println("--help -h, shows this page");
System.out.println("Java Version: " + System.getProperty("java.version"));
System.out.println("OS: " + System.getProperty("os.name") + "/" + System.getProperty("os.arch"));
}
//----------------------------------------------------------------------
/**
* Main method
* @param arguments the command line arguments
*/
public static void main (String[] arguments)
{
new GPSTool().init(arguments);
}
}
| true |
4c614868e00ce3e41c54a3112c5e268bd6828f14 | Java | ChaoSBYNN/HRMS | /HRMS/src/com/zxc/dao/EmpContactInfoDao.java | UTF-8 | 2,635 | 2.328125 | 2 | [
"MIT"
] | permissive | package com.zxc.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.zxc.entity.EmpContactInfo;
import com.zxc.mapper.EmpContactInfoMapper;
import com.zxc.util.MyBatisUtil;
public class EmpContactInfoDao {
static SqlSessionFactory sqlSessionFactory = null;
static {
sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
}
public EmpContactInfo selectEmpContactInfo(EmpContactInfo EmpContactInfo) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmpContactInfoMapper EmpContactInfoMapper = sqlSession.getMapper(EmpContactInfoMapper.class);
EmpContactInfo = EmpContactInfoMapper.selectEmpContactInfo(EmpContactInfo);
} finally {
sqlSession.close();
}
return EmpContactInfo;
}
public List<EmpContactInfo> selectEmpContactInfos() {
SqlSession session = sqlSessionFactory.openSession();
List<EmpContactInfo> EmpContactInfos = null;
try {
EmpContactInfoMapper mapper = session.getMapper(EmpContactInfoMapper.class);
EmpContactInfos = (List<EmpContactInfo>) mapper.selectEmpContactInfos();
for (EmpContactInfo EmpContactInfo : EmpContactInfos) {
System.out.println(EmpContactInfo.getMobilePhone());
}
} finally {
session.close();
}
return EmpContactInfos;
}
public Integer insertEmpContactInfo(EmpContactInfo EmpContactInfo){
SqlSession session = sqlSessionFactory.openSession();
int count= 0;
try {
EmpContactInfoMapper mapper = session.getMapper(EmpContactInfoMapper.class);
count = mapper.insertEmpContactInfo(EmpContactInfo);
session.commit();
} finally {
session.close();
}
return count;
}
public Integer updateEmpContactInfo(EmpContactInfo EmpContactInfo){
SqlSession session = sqlSessionFactory.openSession();
int count= 0;
try {
EmpContactInfoMapper mapper = session.getMapper(EmpContactInfoMapper.class);
count = mapper.updateEmpContactInfo(EmpContactInfo);
//*
session.commit();
} finally {
session.close();
}
return count;
}
public Integer deleteEmpContactInfo(EmpContactInfo EmpContactInfo){
SqlSession session = sqlSessionFactory.openSession();
int count= 0;
try {
EmpContactInfoMapper mapper = session.getMapper(EmpContactInfoMapper.class);
count = mapper.deleteEmpContactInfo(EmpContactInfo);
//*
session.commit();
} finally {
session.close();
}
return count;
}
} | true |
229b2ddc5e4fd1ea9e5a7bc8fd0400e392e6ec4b | Java | GuruKrishnaPanda/APIFramework | /PCRAPIFramework/src/test/java/baseTest/BaseTest.java | UTF-8 | 1,795 | 2.03125 | 2 | [] | no_license | package baseTest;
import java.lang.reflect.Method;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import UtilFiles.GenericXLSXReader;
import UtilFiles.TestDataBuilder;
import apiSession.APISession;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
public class BaseTest {
public APISession session;
public String currentTestcase=null;
public RequestSpecification req;
public ResponseSpecification res;
public Response response;
public TestDataBuilder data = new TestDataBuilder();
public String testName=null;
//public GenericXLSXReader xls = new GenericXLSXReader(System.getProperty("user.dir")+"//input//Data.xlsx");
/*
@BeforeMethod
public void init(ITestResult result) {
System.out.println("@BeforeMethod");
testName = result.getMethod().getMethodName().toUpperCase();
System.out.println(testName);
session= new APISession();
session.init(testName);
}*/
@BeforeMethod
public void init(ITestResult result) {
System.out.println("@BeforeMethod");
testName = result.getMethod().getMethodName().toUpperCase();
System.out.println(testName);
session.createChildNode(testName);
}
@BeforeClass
public void init() {
System.out.println("@BeforeClass");
session= new APISession();
testName = this.getClass().getSimpleName();
session.init(testName);
}
@AfterMethod
public void quit() {
//session.getCon().quit();
}
@AfterClass
public void quit1() {
//session.getCon().quit();
session.generateReports();
}
}
| true |
158cdf7189b3a8ee256d2704a43818825bbdb851 | Java | JohanJoergensen/MasterThesisUSEF | /ri.usef.energy-master/usef-build/usef-hoogdalem/usef-workflow-hd/usef-hd-agr1/src/main/java/nl/energieprojecthoogdalem/messageservice/scheduleservice/tasks/ShiftTask.java | UTF-8 | 2,465 | 2.234375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2014-2016 BePowered BVBA http://www.bepowered.be/
*
* Software is subject to the following conditions:
*
* The above copyright 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 nl.energieprojecthoogdalem.messageservice.scheduleservice.tasks;
import nl.energieprojecthoogdalem.messageservice.scheduleservice.MessageScheduler;
import nl.energieprojecthoogdalem.messageservice.transportservice.MqttConnection;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
/**
* a task that converts a shift request device message from USEF RI to hoogdalem mqtt topics
* */
public class ShiftTask implements Runnable
{
@Inject
private MqttConnection connection;
@Inject
private MessageScheduler scheduler;
private final Logger LOGGER = LoggerFactory.getLogger(ShiftTask.class);
private String endpoint;
private DateTime date;
/**
* class initialisation with following arguments
* @param endpoint the endpoint or cgate serial to send to ex (MZ29EBX000)
* @param date the day and time this task will be executed
* */
public void init(String endpoint, DateTime date)
{
this.endpoint = endpoint;
this.date = date;
}
/**
* sends the value for normal operation to the cqate over mqtt
* removes the task from the memory map in the scheduler
* */
@Override
public void run()
{
LOGGER.info("Executing shift task for endpoint {} on {}", endpoint ,date);
if(connection.isConnected() )
{
LOGGER.info("Publishing shift message for endpoint {} on {} ", endpoint ,date);
connection.publish(endpoint + "/BatMode", "SetDefault");
}
else
LOGGER.warn("Dropping shift message for endpoint {} on {}", endpoint, date);
scheduler.removeTask(endpoint, date, MessageScheduler.SHIFT_SUFFIX);
}
}
| true |
a5e3f0ec179609c5e15f434df047bdeaaffe2a00 | Java | skykying/bundle | /IDE/debug/com.lembed.lite.studio.debug.gdbjtag/src/com/lembed/lite/studio/debug/gdbjtag/services/IPeripheralMemoryService.java | UTF-8 | 2,495 | 1.804688 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2014 Liviu Ionescu.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Liviu Ionescu - initial version
*******************************************************************************/
package com.lembed.lite.studio.debug.gdbjtag.services;
import org.eclipse.cdt.core.IAddress;
import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.debug.service.IMemory.IMemoryDMContext;
import org.eclipse.cdt.dsf.service.IDsfService;
import org.eclipse.debug.core.model.MemoryByte;
/**
* The Interface IPeripheralMemoryService.
*/
public interface IPeripheralMemoryService extends IDsfService {
// ------------------------------------------------------------------------
/**
* Initialize memory data.
*
* @param memContext the mem context
* @param rm the rm
*/
public abstract void initializeMemoryData(final IMemoryDMContext memContext, RequestMonitor rm);
/**
* Checks if is big endian.
*
* @param context the context
* @return true, if is big endian
*/
public abstract boolean isBigEndian(IMemoryDMContext context);
/**
* Gets the address size.
*
* @param context the context
* @return the address size
*/
public abstract int getAddressSize(IMemoryDMContext context);
/**
* Gets the memory.
*
* @param memoryDMC the memory DMC
* @param address the address
* @param offset the offset
* @param word_size the word size
* @param word_count the word count
* @param drm the DataRequestMonitor
*/
public abstract void getMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size,
int word_count, DataRequestMonitor<MemoryByte[]> drm);
/**
* Sets the memory.
*
* @param memoryDMC the memory DMC
* @param address the address
* @param offset the offset
* @param word_size the word size
* @param word_count the word count
* @param buffer the buffer
* @param rm the rm
*/
public abstract void setMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size,
int word_count, byte[] buffer, RequestMonitor rm);
// ------------------------------------------------------------------------
}
| true |
ec19db2cb0e1b8dc186c57de91bc919ebf237165 | Java | loicdesrosiers/ecoLogic | /android/ecoLogicv2/app/src/main/java/info/iut/ecologic/AppDataBase.java | UTF-8 | 506 | 1.953125 | 2 | [] | no_license | package info.iut.ecologic;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.RoomDatabase;
import java.io.Serializable;
import DAOs.QCMUniqueSolutionDAO;
import DAOs.UserDAO;
import Entites.QCMUniqueSolution;
import Entites.User;
@Database(entities = {User.class, QCMUniqueSolution.class}, version = 3)
public abstract class AppDataBase extends RoomDatabase{
public abstract UserDAO userDAO();
public abstract QCMUniqueSolutionDAO qcmUniqueSolutionDAO();
}
| true |
f3aee3d835a69b8607c374453d0a84acb6178a56 | Java | kangarooxin/demo-swagger | /src/main/java/com/justfun/common/support/swagger/JsonParamReader.java | UTF-8 | 3,683 | 2.03125 | 2 | [] | no_license | package com.justfun.common.support.swagger;
import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Optional;
import com.justfun.common.support.swagger.annotations.ApiJsonParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.ModelReference;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.service.ResolvedMethodParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.contexts.ModelContext;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;
import static springfox.documentation.schema.Collections.*;
import static springfox.documentation.service.Parameter.DEFAULT_PRECEDENCE;
import static springfox.documentation.spi.schema.contexts.ModelContext.inputParam;
/**
* @author kangarooxin
*/
@Component
@Order
public class JsonParamReader implements ParameterBuilderPlugin {
@Autowired
private TypeNameExtractor typeNameExtractor;
@Autowired
private TypeResolver typeResolver;
@Override
public void apply(ParameterContext context) {
ResolvedMethodParameter methodParameter = context.resolvedMethodParameter();
Optional<ApiJsonParam> optional = methodParameter.findAnnotation(ApiJsonParam.class); //根据参数上的ApiJsonObject注解中的参数动态生成Class
if (!optional.isPresent()) {
return;
}
ApiJsonParam anno = optional.get();
ModelReference itemModel = null;
String name = anno.name();
if ("".equals(name)) {
name = methodParameter.defaultName().orNull();
}
ResolvedType modelType;
if(anno.dataTypeClass().isAssignableFrom(Void.class)) {
modelType = methodParameter.getParameterType();
} else {
modelType = typeResolver.resolve(anno.dataTypeClass(), anno.dataTypeParametersClass());
}
String typeName;
if (isContainerType(modelType)) {
ResolvedType elementType = collectionElementType(modelType);
String itemTypeName = typeNameFor(context, elementType);
typeName = containerType(modelType);
itemModel = new ModelRef(itemTypeName);
} else {
typeName = typeNameFor(context, modelType);
}
context.parameterBuilder()
.name(name)
.description(anno.value())
.defaultValue(null)
.required(anno.require())
.allowMultiple(isContainerType(modelType))
.type(modelType)
.modelRef(new ModelRef(typeName, itemModel))
.parameterType(anno.type())
.order(DEFAULT_PRECEDENCE)
.parameterAccess(null);
}
private String typeNameFor(ParameterContext context, ResolvedType parameterType) {
ModelContext modelContext = inputParam(
context.getGroupName(),
parameterType,
context.getDocumentationType(),
context.getAlternateTypeProvider(),
context.getGenericNamingStrategy(),
context.getIgnorableParameterTypes());
return typeNameExtractor.typeName(modelContext);
}
@Override
public boolean supports(DocumentationType documentationType) {
return true;
}
}
| true |
3a6bbaed3750b712dd57b850dde0c2bb4332761b | Java | shmilovt/Final_Project_Client | /app/src/main/java/com/example/final_project_client/Presentation/Report/CostReportFragment.java | UTF-8 | 2,380 | 2.109375 | 2 | [] | no_license | package com.example.final_project_client.Presentation.Report;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.example.final_project_client.R;
import com.google.gson.Gson;
public class CostReportFragment extends Fragment implements ReportFragment {
private View mView;
private EditText editTextCost;
public CostReportFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_cost_report, container, false);
editTextCost = mView.findViewById(R.id.editTextCost);
editTextCost.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Integer buidingNumberContentInteger;
try {
buidingNumberContentInteger = Integer.parseInt(s.toString());
if (buidingNumberContentInteger == 0)
editTextCost.setText("");
} catch (NumberFormatException e) {
}
}
});
return mView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private Integer getCost() {
Integer cost;
try {
cost = Integer.parseInt(editTextCost.getText().toString());
} catch (NumberFormatException e) {
cost = null;
}
return cost;
}
@Override
public String getContent() {
Integer cost = getCost();
if (cost != null)
return new Gson().toJson(cost);
else{
return null;
}
}
}
| true |
3fe0b98ac21581b6e09da7ca0647d5e657ccda63 | Java | mounirzz/StaterManagement | /src/main/java/com/micro/demo/controllers/UserController.java | UTF-8 | 11,538 | 1.875 | 2 | [] | no_license | package com.micro.demo.controllers;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.mail.Multipart;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.yaml.snakeyaml.emitter.ScalarAnalysis;
import com.micro.demo.adapters.AppConfig;
import com.micro.demo.models.Remember;
import com.micro.demo.models.User;
import com.micro.demo.repositories.RememberRepository;
import com.micro.demo.repositories.UserRepository;
import com.micro.demo.services.MailService;
import com.micro.demo.services.RememberService;
import com.micro.demo.services.UserService;
import com.micro.demo.util.CookieUtil;
import com.micro.demo.util.UserUtil;
@Controller
@RequestMapping("/user")
public class UserController {
private Logger log = LoggerFactory.getLogger(UserController.class);
@Value("${Spring-stater.user.verification}")
private boolean requireActivation;
@Value("{Spring-stater.user.root}")
private String userRoot;
@Autowired
private AppConfig appConfig ;
@Autowired
private UserRepository userRepository ;
@Autowired
private AuthenticationManager authenticationManager ;
@Autowired
private UserService userservice ;
@Autowired
private MailService mailservice ;
@Autowired
private RememberService rememberService ;
@RequestMapping(method = RequestMethod.GET)
public String index() {
return "user/index";
}
@RequestMapping("/user/list")
public String list(ModelMap map) {
Iterable<User> users = this.userRepository.findAll();
map.addAttribute("users",users);
return "user/list";
}
@RequestMapping(value="/user/register",method = RequestMethod.GET)
public String registerPost(@Valid User user,BindingResult result) {
if (result.hasErrors()) {
return "user/register";
}
User registeredUser = userservice.register(user);
if (registeredUser != null) {
mailservice.sendNewRegistration(user.getEmail(), registeredUser.getToken());
if (!requireActivation) {
userservice.autoLogin(user.getUserName());
return "redirect:/";
}
return "user/register-success";
}else {
log.error("User already exists :" + user.getUserName());
result.rejectValue("email", "error.alreadyExists", "This username or email al ready exists, please try to reset password instead.");
return "user/register";
}
}
@RequestMapping(value = "/user/reset-password")
public String resetPasswordEmail(User user) {
return "user/reset-password";
}
@RequestMapping(value = "/user/reset-password",method = RequestMethod.POST)
public String resetPasswordEmailPost(User user, BindingResult result) {
User u = userRepository.findOneByEmail(user.getEmail());
if (u == null) {
result.rejectValue("email", "eroor.doesntExist","We could not find this email in our database");
return "user/resert-password";
}else {
String resetToken = userservice.createResetPasswordToken(u, true);
mailservice.sendResetPassword(user.getEmail(), resetToken);
}
return "user/reset-password-sent";
}
@RequestMapping(value = "/user/reset-password-change")
public String resetPasswordChange(User user , BindingResult result,Model model) {
User u = userRepository.findOneByToken(user.getToken());
if (user.getToken().equals("1") || u == null) {
result.rejectValue("activation", "error.doesntExist","We could not find this reset password request.");
}else {
model.addAttribute("username" , u.getUserName());
}
return "user/reset-password-change";
}
@RequestMapping(value="/user/reset-password-change", method = RequestMethod.POST)
public ModelAndView resetPasswordChangePost(User user , BindingResult result) {
boolean isChanged = userservice.resetPassword(user);
if (isChanged) {
userservice.autoLogin(user.getUserName());
return new ModelAndView("redirect:/");
}else {
return new ModelAndView("user/rest-password-change","error" , "Password could not be changed");
}
}
@RequestMapping("/user/activation-send")
public ModelAndView activationSend(User user) {
return new ModelAndView("/user/activation-send");
}
@RequestMapping(value = "/user/activation-send", method = RequestMethod.POST)
public ModelAndView activationSendPost(User user, BindingResult result) {
User u = userservice.resetActivation(user.getEmail());
if (u != null) {
mailservice.sendNewActivationRequest(u.getEmail(), u.getToken());
return new ModelAndView("/user/activation-sent");
}else {
result.rejectValue("email", "error.doesntExist","We could not find this email in our database");
return new ModelAndView("/user/activation-send");
}
}
@RequestMapping("/user/delete")
public String delete(Long id) {
userservice.delete(id);
return "redirect:/user/list";
}
@RequestMapping("/user/activate")
public String activate(String activation) {
User u = userservice.activate(activation);
if (u != null) {
userservice.autoLogin(u);
return "redirect:/";
}
return "redirect:/error?message=Could not activate with this activation code, please contact support";
}
@RequestMapping("/user/autologin")
public String autologin(User user) {
userservice.autoLogin(user.getUserName());
return "redirect:/";
}
@RequestMapping(value = "login" , method = RequestMethod.GET)
public String loginFrom(HttpServletRequest request , HttpSession session) {
String uuid;
if ((uuid = CookieUtil.getCookieValue(request, appConfig.USER_COOKIE_NAME)) != null) {
Remember remember = rememberService.findById(uuid);
if (remember != null && remember.getUser() != null) {
if (userservice.checkLogin(remember.getUser())) {
UserUtil.saveUserToSession(session, remember.getUser());
log.info("L'utilisateur [{}] s'est connecté avec succés avec les cookies.", remember.getUser().getUserName());
return "redirect:/";
}
}
}
return "user/userlogin";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(User user, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
if (userservice.checkLogin(user)) {
user = userservice.findOneByUsernameandPassword(user.getUserName(), user.getPassword());
com.micro.demo.util.UserUtil.saveUserToSession(session, user);
log.info("Rappelez-vous s'il faut se connecter à l'utilisateur:" + request.getParameter("remember"));
if ("on".equals(request.getParameter("remember"))) {
String uuid = UUID.randomUUID().toString();
Remember remember = new Remember();
remember.setId(uuid);
remember.setUser(user);
remember.setAddTime(new Date());
rememberService.add(remember);
CookieUtil.addCookie(response, appConfig.USER_COOKIE_NAME, uuid, appConfig.USER_COOKIE_AGE);
} else {
CookieUtil.removeCookie(response, appConfig.USER_COOKIE_NAME);
}
log.info("Utilisateur[" + user.getUserName() + "]Atterrissage réussi");
return "redirect:/";
}
return "redirect:/user/login?errorPwd=true";
}
@RequestMapping(value="/logout" ,method = RequestMethod.GET)
public String profile(HttpSession session,HttpServletResponse response) {
UserUtil.deleteUserFromSession(session);
CookieUtil.removeCookie(response, appConfig.USER_COOKIE_NAME);
return "redirect:/";
}
@RequestMapping("/user/edit/{id}")
public String edit(@PathVariable("id") Long id , User user) {
User u ;
User loggedInUser = userservice.getLoggedInUser();
if (id == 0) {
id = loggedInUser.getId();
}
if (loggedInUser.getId() != id && !loggedInUser.isAdmin()) {
return "user/permission-denied";
}else if(loggedInUser.isAdmin()) {
u = userRepository.findOne(id);
} else {
u = loggedInUser;
}
user.setId(u.getId());
user.setUserName(u.getUserName());
user.setAddress(u.getAddress());
user.setCompanyName(u.getCompanyName());
user.setEmail(u.getEmail());
user.setFirstname(u.getFirstname());
user.setLastname(u.getLastname());
return "/user/edit";
}
@RequestMapping(value= "/user/edit", method = RequestMethod.POST)
public String editPost(@Valid User user,BindingResult result) {
if (result.hasFieldErrors("email")) {
return "/user/edit";
}
if (userservice.getLoggedInUser().isAdmin()) {
userservice.updateUser(user);
}else {
userservice.updateUser(userservice.getLoggedInUser().getUserName(),user);
}
if (userservice.getLoggedInUser().getId().equals(user.getId())) {
userservice.getLoggedInUser(true);
}
return "redirect:/user/edit/" +user.getId() + "?updated";
}
@RequestMapping(value="/user/update", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
String fileName = formatter.format(Calendar.getInstance().getTime())+ "_thumbnail.jpg";
User user = userservice.getLoggedInUser();
if(!file.isEmpty()){
try {
String saveDirectory = userRoot + File.separator + user.getId() + File.separator;
File test = new File(saveDirectory);
if (!test.exists()) {
test.mkdirs();
}
byte[] bytes = file.getBytes();
ByteArrayInputStream imageInputStream = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(imageInputStream);
//BufferedImage thumbnail = scalr.resize(image, 200);
File thumbnailOut = new File(saveDirectory + fileName);
ImageIO.write(null, "png", thumbnailOut);
userservice.updateProfilePicture(user, fileName);
userservice.getLoggedInUser(true); //Force refresh of cached User
System.out.println("image Saved::: "+ fileName);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return "redirect:/user/edit/" +user.getId();
}
@RequestMapping(value="/user/profile-picture", method = RequestMethod.GET)
public @ResponseBody byte[] profilePicture() throws IOException {
User u = userservice.getLoggedInUser();
String profilePicture = userRoot = File.separator + u.getId() + File.separator + u.getProfilePicture();
if (new File(profilePicture).exists()) {
return IOUtils.toByteArray(new FileInputStream(profilePicture));
}else {
return null;
}
}
}
| true |
42634e9775c01e577b83c3b9fc3f00b94ff47a3c | Java | ruhibhandari21/ScrapyKartCustomer | /app/src/main/java/com/app/scrapykart/order/PendingAdapter.java | UTF-8 | 3,031 | 2.21875 | 2 | [] | no_license | package com.app.scrapykart.order;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.app.scrapykart.R;
import java.util.ArrayList;
/**
* Created by shadaf on 13/1/18.
*/
public class PendingAdapter extends RecyclerView.Adapter<PendingAdapter.ViewHolder> {
ArrayList<OrderSetter> orderSetters = null;
PendingFragment pendingFragment;
boolean selection = false;
public class ViewHolder extends RecyclerView.ViewHolder {
Button btCancel, btPositive;
TextView tvItem, tvDate, tvCountValue, tvPriceValue, tvIdValue;
RatingBar ratingBar;
public ViewHolder(View view) {
super(view);
/* tvItem = (TextView) view.findViewById(R.id.tvItem);
tvDate = (TextView) view.findViewById(R.id.tvDate);
tvCountValue = (TextView) view.findViewById(R.id.tvCountValue);
tvPriceValue = (TextView) view.findViewById(R.id.tvPriceValue);
tvIdValue = (TextView) view.findViewById(R.id.tvIdValue);
*/
btCancel = (Button) view.findViewById(R.id.btCancel);
btPositive = (Button) view.findViewById(R.id.btPositive);
}
}
public PendingAdapter(PendingFragment pendingFragment, ArrayList<OrderSetter> orderSetters) {
this.pendingFragment = pendingFragment;
this.orderSetters = orderSetters;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pending_order_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
/*OrderSetter setter = orderSetters.get(position);
holder.tvItem.setText(setter.getVendorName());
holder.tvDate.setText(setter.getOrderDate());
holder.tvCountValue.setText(setter.getQuantity()+" Items");
holder.tvPriceValue.setText("Rs. "+setter.getPrice());
holder.tvIdValue.setText(setter.getOrderId());
*/
holder.btCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(pendingFragment.getContext(), "Under development",
Toast.LENGTH_SHORT).show();
}
});
holder.btPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(pendingFragment.getContext(), "Under development",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return orderSetters.size();
}
}
| true |
278ac9c0b7198f5f9d5b3e286b12c03e16af8c41 | Java | haxsscker/abc.parent | /abc.service/src/main/java/com/autoserve/abc/service/biz/intf/sys/SysLinkInfoService.java | UTF-8 | 1,391 | 2.09375 | 2 | [] | no_license | package com.autoserve.abc.service.biz.intf.sys;
import com.autoserve.abc.dao.common.PageCondition;
import com.autoserve.abc.dao.dataobject.SysLinkInfoDO;
import com.autoserve.abc.service.biz.result.BaseResult;
import com.autoserve.abc.service.biz.result.ListResult;
import com.autoserve.abc.service.biz.result.PageResult;
import com.autoserve.abc.service.biz.result.PlainResult;
/**
* 类SysLinkInfo.java的实现描述:TODO 类实现描述
*
* @author liuwei 2014年11月27日 下午5:03:20
*/
public interface SysLinkInfoService {
/**
* 添加友情链接
*
* @param pojo
* @return BaseResult
*/
BaseResult createSyslinkInfo(SysLinkInfoDO pojo);
/**
* 删除友情链接
*
* @param id
* @return
*/
BaseResult removeSyslinkInfo(int id);
/**
* 修改友情链接
*
* @param pojo
* @return BaseResult
*/
BaseResult modifySyslinkInfo(SysLinkInfoDO pojo);
/**
* 查询单条友情链接
*
* @param id
* @return
*/
PlainResult<SysLinkInfoDO> queryById(int id);
/**
* 分页查询友情链接
*
* @param id
* @return
*/
PageResult<SysLinkInfoDO> queryListByParam(PageCondition pageCondition);
/**
* 查询所有的友情链接
* @return
*/
ListResult<SysLinkInfoDO> queryAllList();
}
| true |
1e429870f725e5a941e1e62455c05df936bcd26d | Java | X00LA/dtlTraders | /src/main/java/net/dandielo/core/items/serialize/core/GenericSpeed.java | UTF-8 | 1,932 | 2.40625 | 2 | [] | no_license | package net.dandielo.core.items.serialize.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.dandielo.core.bukkit.NBTUtils;
import net.dandielo.core.items.dItem;
import net.dandielo.core.items.serialize.Attribute;
import net.dandielo.core.items.serialize.ItemAttribute;
import org.bukkit.inventory.ItemStack;
@Attribute(
name = "GenericSpeed",
key = "g",
sub = {"speed"},
priority = 5
)
public class GenericSpeed extends ItemAttribute {
private static String ATTRIBUTE = "generic.movementSpeed";
private List modifiers = new ArrayList();
public GenericSpeed(dItem item, String key, String sub) {
super(item, key, sub);
}
public boolean deserialize(String data) {
String[] mods = data.split(";");
String[] var3 = mods;
int var4 = mods.length;
for(int var5 = 0; var5 < var4; ++var5) {
String mod = var3[var5];
this.modifiers.add(new NBTUtils.Modifier(mod.split("/")));
}
return true;
}
public String serialize() {
String result = "";
NBTUtils.Modifier mod;
for(Iterator var2 = this.modifiers.iterator(); var2.hasNext(); result = result + ";" + mod.toString()) {
mod = (NBTUtils.Modifier)var2.next();
}
return result.substring(1);
}
public boolean onRefactor(ItemStack item) {
List mods = NBTUtils.getModifiers(item, ATTRIBUTE);
if(mods != null && !mods.isEmpty()) {
this.modifiers.addAll(mods);
return true;
} else {
return false;
}
}
public ItemStack onNativeAssign(ItemStack item, boolean endItem) {
NBTUtils.Modifier mod;
for(Iterator var3 = this.modifiers.iterator(); var3.hasNext(); item = NBTUtils.setModifier(item, mod.getName(), ATTRIBUTE, mod.getValue(), mod.getOperation())) {
mod = (NBTUtils.Modifier)var3.next();
}
return item;
}
}
| true |
954223ac85e568df8195754833e6e1ced3136950 | Java | code-lab-org/sipg | /src/main/java/edu/mit/sipg/core/social/population/TableLookupModel.java | UTF-8 | 2,468 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | /******************************************************************************
* Copyright 2020 Paul T. Grogan
*
* 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 edu.mit.sipg.core.social.population;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* A population model implementation that looks up values from a table.
*
* @author Roi Guinto
* @author Paul T. Grogan
*/
public class TableLookupModel implements PopulationModel {
private long time, nextTime;
private final Map<Long, Long> populationMap;
/**
* Instantiates a new table lookup model.
*/
protected TableLookupModel() {
this(new TreeMap<Long, Long>());
}
/**
* Instantiates a new table lookup model.
*
* @param initialTime the initial time
* @param timeStep the time step
* @param populationValues the population values
*/
public TableLookupModel(int initialTime, int timeStep, long[] populationValues) {
this.populationMap = new HashMap<Long, Long>();
for(int i = initialTime; i < populationValues.length; i += timeStep) {
populationMap.put(new Long(i), populationValues[i]);
}
}
/**
* Instantiates a new table lookup model.
*
* @param populationMap the population map
*/
public TableLookupModel(Map<Long, Long> populationMap) {
this.populationMap = Collections.unmodifiableMap(
new TreeMap<Long, Long>(populationMap));
}
@Override
public long getPopulation() {
Long populationValue = populationMap.get(time);
if(populationValue == null) {
return 0;
} else {
return populationValue.longValue();
}
}
@Override
public void initialize(long time) {
this.time = time;
}
@Override
public void tick() {
nextTime = time + 1;
}
@Override
public void tock() {
time = nextTime;
}
}
| true |
924054064006f4e91ca7354fa2a0d75ff2ab1fa9 | Java | bxbxbx/nabaztag-source-code | /server/OS/net/violet/platform/applets/js/JsClassLoader.java | UTF-8 | 5,460 | 2.1875 | 2 | [
"MIT"
] | permissive | package net.violet.platform.applets.js;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.violet.platform.api.exceptions.APIException;
import net.violet.platform.applets.AppResourcesLoader;
import net.violet.platform.applets.js.helpers.JSClassCompiler;
import net.violet.platform.applets.tools.SourceClassLoader;
import net.violet.platform.util.Constantes;
import org.apache.log4j.Logger;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.GeneratedClassLoader;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.optimizer.ClassCompiler;
/**
* A ClassLoader that compile JavaScript source into Java classes The
* ClassLoader can store the compiled classes
*
* @author christophe - Violet
*/
public class JsClassLoader extends ClassLoader implements SourceClassLoader {
private static final Logger LOGGER = Logger.getLogger(JsClassLoader.class);
String mApiSource;
File mCompileDir; // temporary directory to compile the files
ScriptableObject mScope; // ImporterTopLevel
Class[] mInterfaces = { Scriptable.class }; // javascript applications will at least implement the Scriptable interface.. -------------------------------------------------------------------------80
/**
* Create a ClassLoader for the provided JavaScript API and implemented
* interfaces
*
* @param apiSource the source of the application player library (or
* JavaSCript API)
* @param additionalInterfaces Rhino Scriptable will be added by default
* @throws IOException
*/
public JsClassLoader(String apiSource, List<Class> additionalInterfaces) {
// FIXME: use our own classloader as parent
super(JsClassLoader.class.getClassLoader());
this.mCompileDir = new File(Constantes.JS_COMPILED_CLASSES_PATH);
if (!this.mCompileDir.exists()) {
this.mCompileDir = null; // FileUtils.forceMkdir(this.mCompileDir);
}
this.mApiSource = (apiSource == null) ? net.violet.common.StringShop.EMPTY_STRING : apiSource;
if (additionalInterfaces != null) {
final List<Class> interfaces = new ArrayList<Class>(1 + additionalInterfaces.size());
interfaces.add(Scriptable.class);
interfaces.addAll(additionalInterfaces);
this.mInterfaces = interfaces.toArray(this.mInterfaces);
}
// create a new global scope level
final Context cx = Context.enter();
this.mScope = new ImporterTopLevel(cx);
Context.exit();
}
/**
* Find and load a java class implemented in JavaScript.
*
* @param appPublicKey (serve as the class name for this application)
* @return the class
* @throws ClassNotFoundException
* @throws JavaScriptException
* @see ClassLoader#loadClass(String)
*/
@Override
protected Class<?> findClass(String appPublicKey) throws ClassNotFoundException {
try {
final String appSrc = getApplicationSources(appPublicKey);
if (appSrc == null) {
throw new ClassNotFoundException("Sources for application " + appPublicKey + " couldn't be found !");
}
return loadFromSource(appPublicKey, appSrc);
} catch (final Exception e) {
final String strErrMsg = "Unable to load class for JavaScript application " + appPublicKey;
JsClassLoader.LOGGER.error(strErrMsg, e);
throw new ClassNotFoundException(strErrMsg, e);
} finally {
Context.exit();
}
}
/**
* @param inClassName the class name (use the application api_key)
* @param inAppSource the JavaScript source of the application (will be
* concatened with the JavaScript API library)
* @return aldo la classe
*/
public Class loadFromSource(String inClassName, String inAppSource) {
// init a rhino context
final Context cx = Context.enter();
try {
final CompilerEnvirons compEnv = new CompilerEnvirons();
compEnv.initFromContext(cx);
final ClassCompiler compiler = new ClassCompiler(compEnv);
compiler.setTargetImplements(this.mInterfaces);
// an array of generated classnames with their bytecodes
final Object[] byteCodes = compiler.compileToClassFiles(this.mApiSource + inAppSource, inClassName + ".js", 1, inClassName);
// optionally store the compiled classes
if (this.mCompileDir != null) {
try {
JSClassCompiler.saveClassFiles(byteCodes, this.mCompileDir);
} catch (final IOException e) {
JsClassLoader.LOGGER.error("Compiled class files couldn't be saved !", e);
}
}
// define the Java classes from generated byte code
final GeneratedClassLoader loader = cx.createClassLoader(cx.getApplicationClassLoader());
Class aldo = null; // the one we must return
for (int i = 0; i < byteCodes.length; i += 2) {
final Class classe = loader.defineClass((String) byteCodes[i], (byte[]) byteCodes[i + 1]);
loader.linkClass(classe);
if (i == 0) {
aldo = classe;
}
}
return aldo;
} finally {
Context.exit();
}
}
/**
* Find the javascript source file for this class name
*
* @param appPublicKey the name of the class we're looking for
* @return the javascript source file
*/
private String getApplicationSources(String appPublicKey) throws APIException {
final String appSrc = AppResourcesLoader.LOADER.getApplicationSources(appPublicKey);
return this.mApiSource + appSrc;
}
}
| true |
ed75e77719f095ebc5c94e0a097d81cbfd249f01 | Java | jsjs0730/UTBC | /NewsProject2/src/main/java/tk/utbc/controller/MemberController.java | UTF-8 | 7,157 | 2.03125 | 2 | [] | no_license | /**
*
*/
package tk.utbc.controller;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import tk.utbc.service.MailService;
import tk.utbc.service.MemberService;
import tk.utbc.vo.MemberVO;
/**
* @author KEN
* Park Jong-hyun
*/
@Controller
@RequestMapping("/member/*")
public class MemberController {
private static final Logger logger =LoggerFactory.getLogger(MemberController.class);
@SuppressWarnings("unused")
@Autowired
private BCryptPasswordEncoder passwordEncoder;
//form data 전송시 datetype 에러가 생긴다
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
@Inject
private MemberService service;
@SuppressWarnings("unused")
@Inject
private MailService mailService;
@RequestMapping("/terms")
public String terms() throws Exception{
return "/member/terms";
}
@RequestMapping(value="/signup", method=RequestMethod.GET)
public String createUserGET() throws Exception{
logger.info("회원 등록을 시도함.....get");
return "/member/signup";
}
@RequestMapping(value="/signup", method=RequestMethod.POST)
public String createUserPOST(MemberVO vo) throws Exception{
vo.setUpw(BCrypt.hashpw(vo.getPassword(), BCrypt.gensalt(10)));
logger.info("회원 등록을 시도함.....post");
logger.info(vo.toString());
//트랜잭션을 사용해도 무관
//회원정보
service.createUser(vo);
//아이디 : 권한
service.createAuthority(vo.getUid(), vo.getAuth());
//회원포인트 테이블
service.createUserPoint(vo.getUid());
return "redirect:/";
}
//닉 또는 아이디 중복 검사
@ResponseBody
@RequestMapping(value="/chkUser")
public String checkUser(MemberVO vo) throws Exception {
int cnt = service.chkUser(vo);
return String.valueOf(cnt);
}
/*@RequestMapping(value="/passwordEncoder", method= {RequestMethod.GET, RequestMethod.POST})
public String passwordEncoder(@RequestParam(value="targetStr", required=false, defaultValue="") String targetStr, Model model){
if(StringUtils.hasText(targetStr)) {
//암호화 작업
String bCryptString = passwordEncoder.encode(targetStr);
model.addAttribute("targetStr", targetStr);
model.addAttribute("bCryptString", bCryptString);
}
return "/common/showBCryptString";
}*/
@ResponseBody
@RequestMapping(value="/{uname}", method=RequestMethod.GET)
public Map<String, Object> userStat(@PathVariable("uname") String uname) throws Exception{
Map<String, Object> ult = service.getStat(uname);
Map<String, Object> result = new HashMap<>();
result.put("stat", ult);
return result;
}
@ResponseBody
@RequestMapping(value="/{uname}", method=RequestMethod.DELETE)
public Map<String, Object> userDropout(@PathVariable("uname") String uname) throws Exception{
service.dropout(uname);
Map<String, Object> result = new HashMap<>();
result.put("code", "success");
return result;
}
@RequestMapping(value="/find", method=RequestMethod.GET)
public String find() {
return "/member/find";
}
@RequestMapping(value="/find/id", method=RequestMethod.POST)
public String findMyIdPOST(@RequestParam String email, RedirectAttributes rttr) throws Exception{
logger.info("email 검사 : "+email);
Map<String,Object> result = new HashMap<>();
String id = service.findMyId(email);
if(id != null) {
String title = "UTBC 아이디 찾기 안내 메일 입니다.";
StringBuilder sb = new StringBuilder();
sb.append("귀하의 아이디는 " + id + " 입니다.");
mailService.send(title, sb.toString(), "bakamono56789@yahoo.co.jp", email, null);
result.put("code", "success");
result.put("message", "귀하의 이메일 주소로 아이디가 전송될 것입니다.");
}else {
result.put("code", "danger");
result.put("message", "입력하신 이메일의 가입된 아이디가 존재하지 않습니다.");
}
rttr.addFlashAttribute("result", result);
return "redirect:/member/find";
}
@RequestMapping(value="/find/password", method=RequestMethod.POST)
public String findMyPasswordPOST(@RequestParam String uid, @RequestParam String email, RedirectAttributes rttr) throws Exception{
logger.info("uid : " + uid + "// email : " + email);
Map<String,Object> result = new HashMap<>();
String id = service.findMyPwd(uid, email); //간단한 ID, 이메일 검증
if(id != null) {
int ran = new Random().nextInt(500000) + 10000; //10000 ~ 499999
String newPwd = String.valueOf(ran);//일종의 rawPwd 생성
String encodePwd = BCrypt.hashpw(newPwd, BCrypt.gensalt(10)); //DB에 저장할 때는 encode
service.updatePwd(id, encodePwd); //DB
String title = "UTBC 임시 비밀번호 안내 메일 입니다.";
StringBuilder sb = new StringBuilder();
sb.append("귀하의 임시비밀번호 : " + newPwd);
sb.append("\n <주의>반드시 비밀번호를 변경하십시오.");
mailService.send(title, sb.toString(), "bakamono56789@yahoo.co.jp", email, null);
result.put("code", "success");
result.put("message", "귀하의 이메일 주소로 임시 비밀번호가 전송될 것입니다.");
}else {
result.put("code", "danger");
result.put("message", "입력하신 아이디 또는 이메일 정보로 가입된 아이디가 존재하지 않습니다.");
}
rttr.addFlashAttribute("result", result);
return "redirect:/member/find";
}
@RequestMapping(value="/editProfile", method=RequestMethod.GET)
public String editMyProfileGET() {
return "/member/editProfile";
}
@RequestMapping(value="/editProfile", method=RequestMethod.POST)
public String editMyProfilePOST(MemberVO vo, RedirectAttributes rttr) throws Exception {
vo.setUpw(BCrypt.hashpw(vo.getPassword(), BCrypt.gensalt(10)));
service.updateUserProfile(vo);
rttr.addFlashAttribute("message", "회원정보가 수정 되었습니다. 재로그인 해주세요.");
return "redirect:/";
}
}
| true |
a1b0e60796839988a7a2b9f5c41b228463596b64 | Java | kinanpermata/PBO-Jobsheets | /Jobsheet6/Tugas/Laptop.java | UTF-8 | 707 | 2.59375 | 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 Jobsheet6.Tugas;
/**
*
* @author ASUS
*/
public class Laptop extends Komputer{
public String jnsBaterai;
public Laptop(){
}
public Laptop(String merk, int kecProcessor, int sizeMemory,
String jnsProcessor, String jnsBaterai){
super(merk, kecProcessor, sizeMemory, jnsProcessor);
this.jnsBaterai = jnsBaterai;
}
public void tampilLaptop(){
super.tampilData();
System.out.println("Jenis Baterai: " +jnsBaterai);
}
} | true |
a25d74bf892edaa3fae3543d64e020934c01c4e9 | Java | nareshmiriyala/ConcurrentApp | /ConcurrentApp/src/main/java/com/dellnaresh/concurrentapp/Start.java | UTF-8 | 812 | 2.15625 | 2 | [] | no_license | package com.dellnaresh.concurrentapp;
import com.dellnaresh.entity.Trans;
import com.dellnaresh.jpa.TransJpaController;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import java.util.Map;
/**
*
* @author nareshm
*/
public class Start {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory=Persistence.createEntityManagerFactory("com.dellnaresh_ConcurrentApp_jar_1.0-SNAPSHOTPU");
TransJpaController transJpaController=new TransJpaController(entityManagerFactory);
// transJpaController.create(new Trans());
System.out.println(transJpaController.getTransCount());
}
}
| true |
cbb5ecd293e7ad1035f9b8438ecf6f35c9a09792 | Java | pxson001/facebook-app | /classes9.dex_source_from_JADX/com/facebook/pager/RenderInfo.java | UTF-8 | 2,708 | 2.046875 | 2 | [] | no_license | package com.facebook.pager;
import com.facebook.common.objectpool.ObjectPool;
import com.facebook.common.objectpool.ObjectPool.Allocator;
import com.facebook.common.time.AwakeTimeSinceBootClock;
import com.google.common.base.Objects;
/* compiled from: ccu_invalid_contact_id_event */
public class RenderInfo<T, S> {
private static final ObjectPool<RenderInfo> f18415a = new ObjectPool(RenderInfo.class, 0, 100, 1, 500, new C21291(), AwakeTimeSinceBootClock.INSTANCE);
public T f18416b;
public S f18417c;
public int f18418d = Integer.MIN_VALUE;
public int f18419e = Integer.MAX_VALUE;
public float f18420f = Float.MIN_VALUE;
public float f18421g = Float.MIN_VALUE;
public float f18422h = Float.MIN_VALUE;
/* compiled from: ccu_invalid_contact_id_event */
final class C21291 implements Allocator<RenderInfo> {
C21291() {
}
public final void m18402a(Object obj) {
RenderInfo renderInfo = (RenderInfo) obj;
renderInfo.f18416b = null;
renderInfo.f18417c = null;
renderInfo.f18418d = Integer.MIN_VALUE;
renderInfo.f18419e = Integer.MIN_VALUE;
renderInfo.f18420f = Float.MIN_VALUE;
renderInfo.f18421g = Float.MIN_VALUE;
renderInfo.f18422h = Float.MIN_VALUE;
}
public final Object m18401a() {
return new RenderInfo();
}
}
public static <X, Y> RenderInfo<X, Y> m18403a() {
return (RenderInfo) f18415a.a();
}
public final void m18404b() {
f18415a.a(this);
}
public final T m18405d() {
return this.f18416b;
}
public final int m18406f() {
return this.f18419e;
}
public final int m18407g() {
return this.f18418d;
}
public final float m18408h() {
return this.f18421g;
}
public final float m18409i() {
return this.f18422h;
}
public final float m18410j() {
return this.f18420f;
}
public String toString() {
return "object:" + this.f18416b + " position:" + this.f18418d + " width:" + this.f18421g + " height:" + this.f18422h + " offset:" + this.f18420f;
}
public int hashCode() {
return Objects.hashCode(new Object[]{this.f18416b, Integer.valueOf(this.f18418d)});
}
public boolean equals(Object obj) {
if (!(obj instanceof RenderInfo)) {
return false;
}
RenderInfo renderInfo = (RenderInfo) obj;
if (Objects.equal(this.f18416b, renderInfo.f18416b) && Objects.equal(Integer.valueOf(this.f18418d), Integer.valueOf(renderInfo.f18418d))) {
return true;
}
return false;
}
}
| true |
7270d1d7303b981e776c11a04aa5d1bd286c22bc | Java | ksu-m16/iTracker | /src/itracker/collect/strategy/IStrategy.java | UTF-8 | 342 | 2.015625 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package itracker.collect.strategy;
import itracker.util.ILocation;
/**
*
* @author KerneL
*/
public interface IStrategy {
void reset();
boolean isReady();
void update(ILocation loc);
String getName();
}
| true |
26be9a05d117b681693b105248a236f28826f7cf | Java | OxideMC/kiln | /src/main/java/com/github/glassmc/kiln/common/SystemUtil.java | UTF-8 | 967 | 2.90625 | 3 | [
"MIT"
] | permissive | package com.github.glassmc.kiln.common;
import java.util.Locale;
public class SystemUtil {
public static OSType getOSType() {
String osName = System.getProperty("os.name").toLowerCase();
if(osName.contains("win")) {
return OSType.WINDOWS;
}
if(osName.contains("mac")) {
return OSType.MAC;
}
if(osName.contains("nux")) {
return OSType.LINUX;
}
return OSType.UNKNOWN;
}
public static Architecture getArchitecture() {
String osArch = System.getProperty("os.arch");
if(osArch.equals("32")) {
return Architecture.X32;
}
if(osArch.equals("64")) {
return Architecture.X64;
}
return Architecture.UNKNOWN;
}
public enum OSType {
WINDOWS,
MAC,
LINUX,
UNKNOWN
}
public enum Architecture {
X32,
X64,
UNKNOWN
}
}
| true |
7c4b324e3b38480067a787f170229d80e7a4757f | Java | GoogleCloudPlatform/spring-cloud-gcp | /spring-cloud-gcp-autoconfigure/src/main/java/com/google/cloud/spring/autoconfigure/config/GcpConfigProperties.java | UTF-8 | 3,407 | 1.765625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.google.cloud.spring.autoconfigure.config;
import com.google.cloud.spring.core.Credentials;
import com.google.cloud.spring.core.CredentialsSupplier;
import com.google.cloud.spring.core.GcpScope;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
/**
* Configuration for {@link GoogleConfigPropertySourceLocator}.
*
* @since 1.1
*/
@ConfigurationProperties("spring.cloud.gcp.config")
public class GcpConfigProperties implements CredentialsSupplier, EnvironmentAware {
/** Enables Spring Cloud GCP Config. */
private boolean enabled;
/** Name of the application. */
@Value("${spring.application.name:application}")
private String name;
/**
* Comma-delimited string of profiles under which the app is running. Gets its default value from
* the {@code spring.profiles.active} property, falling back on the {@code
* spring.profiles.default} property.
*/
private String profile;
/** Timeout for Google Runtime Configuration API calls. */
private int timeoutMillis = 60000;
/** Overrides the GCP project ID specified in the Core module. */
private String projectId;
/** Overrides the GCP OAuth2 credentials specified in the Core module. */
@NestedConfigurationProperty
private final Credentials credentials = new Credentials(GcpScope.RUNTIME_CONFIG_SCOPE.getUrl());
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return this.enabled;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getProfile() {
return this.profile;
}
public void setTimeoutMillis(int timeoutMillis) {
this.timeoutMillis = timeoutMillis;
}
public int getTimeoutMillis() {
return this.timeoutMillis;
}
public String getProjectId() {
return this.projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public Credentials getCredentials() {
return this.credentials;
}
@Override
public void setEnvironment(Environment environment) {
if (this.profile == null) {
String[] profiles = environment.getActiveProfiles();
if (profiles.length == 0) {
profiles = environment.getDefaultProfiles();
}
if (profiles.length > 0) {
this.profile = profiles[profiles.length - 1];
} else {
this.profile = "default";
}
}
}
}
| true |
0054489de2add1abb91a4e81eec147a1028af65f | Java | paurav11/Java | /src/ControlStatements/Loops.java | UTF-8 | 1,460 | 4.28125 | 4 | [] | no_license | package ControlStatements;
public class Loops {
public static void main(String[] args) {
/* loops are used to execute a set of instructions/functions repeatedly
when some conditions become true.
*/
// for loop (Entry controlled)
for (int i=1; i<10; i++) {
if (i>5) {
continue; // continue keyword is used to skip the statements below it
}
System.out.println(i);
}
// Nested for loops
for (int i=1; i<5; i++) {
for (int j=i; j<4; j++) {
System.out.println("i = " + i + " j = " + j);
}
}
int i=0;
// while loop (Entry controlled)
System.out.println("while loop...");
while (i!=10) {
System.out.println("hello " + i);
i++;
}
// Infinite while loop
System.out.println("infinite while loop...");
while (true) {
int j = (int)(Math.random()*(10-1) + 1);
System.out.println(j);
if (j==5) {
System.out.println("loop terminated.");
break; // break keyword helps to exit any loop anytime
}
}
int z = 10;
// do-while loop (Executed at least once) (Exit controlled)
System.out.println("do while...");
do {
System.out.println(z);
z--;
} while (z!=3);
}
}
| true |
bdfb7356b99c2c333df561690b5f0a984a74dc99 | Java | sdgdsffdsfff/biz-parameter | /biz-parameter-api/src/main/java/com/mysoft/b2b/bizsupport/api/QualificationBasicRelation.java | UTF-8 | 1,083 | 2.109375 | 2 | [] | no_license | package com.mysoft.b2b.bizsupport.api;
import java.io.Serializable;
/**
* 资质与基础分类服务关联模型类
* @author pengym
*
*/
public class QualificationBasicRelation implements Serializable{
private static final long serialVersionUID = 2406775613593500998L;
/**
* 主键id
*/
private String id;
/**
* 资质码
*/
private String qualificationCode;
/**
* 基础分类服务码
*/
private String categoryCode;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getQualificationCode() {
return qualificationCode;
}
public void setQualificationCode(String qualificationCode) {
this.qualificationCode = qualificationCode;
}
public String getCategoryCode() {
return categoryCode;
}
public void setCategoryCode(String categoryCode) {
this.categoryCode = categoryCode;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "QualificationBasicRelation{id="+id+",qualificationCode="+qualificationCode+
",categoryCode="+categoryCode+"}";
}
}
| true |
f135e04d30d58f7b40288a176422a3cc6bf217f0 | Java | JoseSM8/SpringRepository | /WazuWeb/src/test/java/com/wazuweb/WazuWebApplicationTests.java | UTF-8 | 930 | 2.125 | 2 | [] | no_license | package com.wazuweb;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import com.wazuweb.model.UsuarioSecurity;
import com.wazuweb.repo.IUsuarioLog;
@RunWith (SpringRunner.class)
@SpringBootTest
class WazuWebApplicationTests {
@Autowired
private BCryptPasswordEncoder encoder;
@Autowired
private IUsuarioLog log;
@Test
public void crearUsuarioTest() {
UsuarioSecurity us = new UsuarioSecurity();
us.setId(5);
us.setNombre("Profe");
us.setClave(encoder.encode("12345"));
UsuarioSecurity retorno = log.save(us);
assertTrue(retorno.getClave().equalsIgnoreCase(us.getClave()));
}
}
| true |
9c4ade9bda8b64330da1a39014fff222bc7e4687 | Java | kafun18/O2O | /src/main/java/com/imooc/o2o/util/PathUtil.java | UTF-8 | 713 | 2.109375 | 2 | [] | no_license | package com.imooc.o2o.util;
//import org.apache.jasper.tagplugins.jstl.core.If;
public class PathUtil {
private static String seperator=System.getProperty("file.separator");
public static String getImgBasePath(){
String os = System.getProperty("os.name");
String basePath = "";
if(os.toLowerCase().startsWith("win")){
basePath="C:/Users/kafun/Desktop/image/1/";
}else {
basePath="C:/Users/kafun/Desktop/image/2/";
}
basePath=basePath.replace("/",seperator);
return basePath;
}
public static String getShopImagePath(Long shopId){
String imagePath="C:/Users/kafun/Desktop/image/3/";
return imagePath.replace("/", seperator);
//return imagePath;
}
}
| true |
a46cb3340f384e593e2d0775f666a2734cbff0c9 | Java | caotingting2017/automationTesting | /androidUITest/src/test/java/com/arisan1000/utils/ReadXmlFileUtils.java | UTF-8 | 5,714 | 2.8125 | 3 | [] | no_license | package com.arisan1000.utils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Text;
import org.jdom2.input.SAXBuilder;
public class ReadXmlFileUtils {
private static Map<String, Object> element = new HashMap<String, Object>();
File classpathRoot = new File(System.getProperty("user.dir"));
File XmlDir = new File(classpathRoot, "elementsXmlFiles");
/**
* 读取文档的要元素节点
* @param filename
* @param id
* @return
* @throws Exception
*/
public Element getRootElement(String filename) throws Exception{
File xmlFile = new File(XmlDir, filename);
// 读取文件
SAXBuilder saxBuilder = new SAXBuilder();
Document document;
document = saxBuilder.build(xmlFile);
Element classElement = document.getRootElement();
return classElement;
}
/**
* 获取filename文档中的,class标签的name值为id的结构体中的所有子节点
*
* @param filename
* @param id:
* element标签属性name的值,参考<element name="start"> ,id 为 "start"
* @return Map<tag, value> 存在所有子节点的Map对象
* @throws Exception
*/
public Map<String, Object> getElement(String filename, String id) throws Exception {
// File xmlFile = new File(XmlDir, filename);
//
// // 读取文件
// SAXBuilder saxBuilder = new SAXBuilder();
// Document document;
// document = saxBuilder.build(xmlFile);
//
// Element classElement = document.getRootElement();
Element classElement = getRootElement(filename);
List<Element> elementIndex = classElement.getChildren("element");
if (!elementIndex.isEmpty()) {
for (Element elt : elementIndex) {
if(!id.equals(elt.getAttribute("name").getValue())){
continue;
}
// if (id.equals(elt.getAttribute("name").getValue())) {// 查找name值为id的index标签
List<Element> children = elt.getChildren();
for (Element child : children) {
if (child.getChildren().isEmpty()) {
element.put(child.getName(), child.getText());
} else {
Map<String, String> childrenElement = new HashMap<String, String>();
for (Element childrenChild : child.getChildren()) {
childrenElement.put(childrenChild.getAttribute("name").getValue(),
childrenChild.getText());
}
element.put(child.getName(), childrenElement);
}
}
break;
// }
}
}
return element;
}
/**
* 获取定位标识相同的一组元素
* @param elementName
* @param filename
* @return
* @throws Exception
*/
public Element getListElemts(String elementName,String filename) throws Exception{
Element desElement = null;
Element classElement = getRootElement(filename);
List<Element> elementsList = classElement.getChildren("elements");
if (!elementsList.isEmpty()) {
// 找出elementName匹配的elements元素块
for (Element elt : elementsList) {
if (elementName.equals(elt.getAttribute("name").getValue())) {
desElement = elt;
break;
}
}
}
return desElement;
}
public Map<String, Object> getListElementChild(String listElementName,String filename,String index) throws Exception{
//TODO
System.out.println("index:"+index);
Element elements = getListElemts(listElementName,filename);//找到符合条件的<elements>
List<Element> childrenOfElements = elements.getChildren();
// if (childrenOfElements.isEmpty()) {
// return element;
// }
if(!childrenOfElements.isEmpty()){//有子结点
for(Element childElements :childrenOfElements ){
System.out.println("index.equals(childElements.getAttributeValue(\"index\")):true or false:"+index.equals(childElements.getAttributeValue("index")));
if(index.equals(childElements.getAttributeValue("index"))){//找到index匹配的<element>
if (!childElements.getChildren().isEmpty()) {
List<Element> childrenOfElement = childElements.getChildren();//<description><text>标签
for(Element childOfElement:childrenOfElement){
if(childrenOfElement.isEmpty()){//<description>标签没有子标签
element.put(childOfElement.getName(), childOfElement.getText());
}else {//遍历<text>标签,将子标签放入Map中
Map<String, String> grandChildrenElement = new HashMap<String, String>();
for (Element grandChildrenChild : childOfElement.getChildren()) {
grandChildrenElement.put(grandChildrenChild.getAttribute("name").getValue(),
grandChildrenChild.getText());
}
element.put(childOfElement.getName(), grandChildrenElement);
}
}
}
break;
}
else{
continue;
}
}
}else{
System.out.println("标签下没有子元素");
}
return element;
}
/**
* 查找命名为elementName的一批元素
*
* @param filename
* @param elementName
* @return
* @throws Exception
*/
public String getElementsAccessibility( String elementName,String filename) throws Exception {
// String accessbilityId = null;
// Element classElement = getRootElement(filename);
// List<Element> elementsList = classElement.getChildren("elements");
// if (!elementsList.isEmpty()) {
// // 找出id匹配的elements元素块
// for (Element elt : elementsList) {
// if (elementName.equals(elt.getAttribute("name").getValue())) {
// accessbilityId = elt.getAttributeValue("id");//获取定位标识
// break;
// }
//
// }
//
// }else{
// System.err.println("无此元素");
// }
//
//
return getListElemts(elementName,filename).getAttributeValue("id");
}
}
| true |
8cc7a76d72670e18e6115bb4e76f2e7fa1b0b338 | Java | yygood1000/ph_project | /driver/src/main/java/com/topjet/crediblenumber/goods/view/fragment/ListenOrderView.java | UTF-8 | 669 | 1.6875 | 2 | [] | no_license | package com.topjet.crediblenumber.goods.view.fragment;
import com.topjet.common.base.view.activity.IView;
import com.topjet.common.order_detail.modle.extra.CityAndLocationExtra;
/**
* Created by yy on 2017/9/11.
* 听单View
*/
public interface ListenOrderView extends IView {
void setStartText(String text, boolean isNull, boolean isNeeedLocation);
void setEndText(String text);
/**
* 设置popup中的地址
*/
void setPopAddress(CityAndLocationExtra extra);
void showOrHidePermissionsFail(boolean show); // 显示或隐藏无法获得定位权限
void requestOverlayPermission(); // 申请悬浮窗权限
}
| true |
aa00b3459973607fabded98176309b4a99f0d16d | Java | imurvai/brickcontroller | /app/src/main/java/com/scn/devicemanagement/DeviceManager.java | UTF-8 | 13,517 | 2.203125 | 2 | [] | no_license | package com.scn.devicemanagement;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import com.scn.common.StateChange;
import com.scn.logger.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by steve on 2017. 09. 06..
*/
@Singleton
public final class DeviceManager implements DeviceFactory {
//
// Constants
//
private static final String TAG = DeviceManager.class.getSimpleName();
private static final int SCAN_INTERVAL_SECS = 10;
public enum State {
OK,
LOADING,
REMOVING,
UPDATING,
SCANNING
}
//
// Private members
//
private final DeviceRepository deviceRepository;
private final BluetoothDeviceManager bluetoothDeviceManager;
private final InfraRedDeviceManager infraRedDeviceManager;
private final MutableLiveData<StateChange<DeviceManager.State>> stateChangeLiveData = new MutableLiveData<>();
private final List<Device.DeviceType> supportedDeviceTypes = Arrays.asList(
Device.DeviceType.INFRARED,
Device.DeviceType.SBRICK,
Device.DeviceType.BUWIZZ,
Device.DeviceType.BUWIZZ2
);
//
// Constructor
//
@Inject
public DeviceManager(@NonNull DeviceRepository deviceRepository,
@NonNull BluetoothDeviceManager bluetoothDeviceManager,
@NonNull InfraRedDeviceManager infraRedDeviceManager) {
Logger.i(TAG, "constructor...");
this.deviceRepository = deviceRepository;
this.bluetoothDeviceManager = bluetoothDeviceManager;
this.infraRedDeviceManager = infraRedDeviceManager;
stateChangeLiveData.setValue(new StateChange(State.OK, State.OK, false));
}
//
// DeviceFactory methods
//
public Device createDevice(Device.DeviceType type, @NonNull String name, @NonNull String address, @NonNull String deviceSpecificDataJSon) {
Logger.i(TAG, "createDevice - type: " + type.toString() + ", name: " + name + ", address: " + address + ", device specific data: " + deviceSpecificDataJSon);
Device device = null;
switch (type) {
case INFRARED:
device = infraRedDeviceManager.createDevice(type, name, address, deviceSpecificDataJSon);
break;
case BUWIZZ:
case BUWIZZ2:
case SBRICK:
device = bluetoothDeviceManager.createDevice(type, name, address, deviceSpecificDataJSon);
break;
}
return device;
}
//
// API
//
public List<Device.DeviceType> getSupportedDeviceTypes() {
return supportedDeviceTypes;
}
@MainThread
public boolean isBluetoothLESupported() {
Logger.i(TAG, "isBluetoothLESupported...");
return bluetoothDeviceManager.isBluetoothLESupported();
}
@MainThread
public boolean isBluetoothOn() {
Logger.i(TAG, "isBluetoothOn...");
return bluetoothDeviceManager.isBluetoothOn();
}
@MainThread
public boolean isInfraSupported() {
Logger.i(TAG, "isInfraSupported...");
return infraRedDeviceManager.isInfraRedSupported();
}
@MainThread
public LiveData<StateChange<DeviceManager.State>> getStateChangeLiveData() {
Logger.i(TAG, "getStateChangeLiveData...");
return stateChangeLiveData;
}
@MainThread
public boolean loadDevicesAsync(boolean forceLoad) {
Logger.i(TAG, "loadDevicesAsync...");
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState().toString());
return false;
}
setState(State.LOADING, false);
Single.fromCallable(() -> {
deviceRepository.loadDevices(this, forceLoad);
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
x -> {
Logger.i(TAG, "Load devices onSuccess...");
setState(State.OK, false);
},
error -> {
Logger.e(TAG, "Load devices onError...", error);
setState(State.OK, true);
});
return true;
}
@MainThread
public boolean startDeviceScan() {
Logger.i(TAG, "startDeviceScan...");
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState().toString());
return false;
}
Observable<Device> bluetoothDeviceObservable = bluetoothDeviceManager.startScan();
Observable<Device> infraredDeviceObservable = infraRedDeviceManager.startScan();
List<Observable<Device>> deviceScanObservables = new ArrayList<>();
if (bluetoothDeviceObservable != null) deviceScanObservables.add(bluetoothDeviceObservable);
if (infraredDeviceObservable != null) deviceScanObservables.add(infraredDeviceObservable);
if (deviceScanObservables.size() > 0) {
setState(State.SCANNING, false, new ScanProgress(0));
final Disposable timerDisposable = Observable.interval(1, TimeUnit.SECONDS)
.take(SCAN_INTERVAL_SECS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
time -> {
int intTime = time.intValue();
Logger.i(TAG, "Device timer scan onNext - " + intTime);
setState(State.SCANNING, false, new ScanProgress(intTime));
},
error -> {
Logger.e(TAG, "Device timer scan onError...", error);
stopDeviceScan();
},
() -> {
Logger.i(TAG, "Device timer scan onComplete...");
stopDeviceScan();
}
);
Observable.merge(deviceScanObservables)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.doOnNext(deviceRepository::storeDevice)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
device -> {
Logger.i(TAG, "Device scan onNext - " + device);
},
error -> {
Logger.e(TAG, "Device scan onError...", error);
timerDisposable.dispose();
stopDeviceScan();
setState(State.OK, true);
},
() -> {
Logger.i(TAG, "Device scan onComplete...");
timerDisposable.dispose();
setState(State.OK, false);
});
return true;
}
return false;
}
@MainThread
public void stopDeviceScan() {
Logger.i(TAG, "stopDeviceScan...");
if (getCurrentState() != State.SCANNING) {
Logger.w(TAG, " wrong state - " + getCurrentState());
return;
}
bluetoothDeviceManager.stopScan();
infraRedDeviceManager.stopScan();
}
@MainThread
public LiveData<List<Device>> getDeviceListLiveData() {
Logger.i(TAG, "getDeviceListLiveData...");
return deviceRepository.getDeviceListLiveData();
}
public Device getDevice(@NonNull String deviceId) {
Logger.i(TAG, "getDevice - " + deviceId);
return deviceRepository.getDevice(deviceId);
}
public boolean removeDeviceAsync(@NonNull final Device device) {
Logger.i(TAG, "removeDeviceAsync - " + device);
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState());
return false;
}
setState(State.REMOVING, false);
Single.fromCallable(() -> {
deviceRepository.deleteDevice(device);
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
x -> {
Logger.i(TAG, "deleteDevice onSuccess.");
setState(State.OK, false);
},
e -> {
Logger.e(TAG, "deleteDevice onError", e);
setState(State.OK, true);
});
return true;
}
@MainThread
public boolean removeAllDevicesAsync() {
Logger.i(TAG, "removeAllDevicesAsync...");
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState());
return false;
}
setState(State.REMOVING, false);
Single.fromCallable(() -> {
deviceRepository.deleteAllDevices();
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
x -> {
Logger.i(TAG, "removeAllDevice onSuccess.");
setState(State.OK, false);
},
e -> {
Logger.e(TAG, "removeAllDevice onError.", e);
setState(State.OK, true);
});
return true;
}
@MainThread
public boolean updateDeviceNameAsync(@NonNull final Device device, @NonNull final String newName) {
Logger.i(TAG, "updateDeviceNameAsync - " + device);
Logger.i(TAG, " new name: " + newName);
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState());
return false;
}
setState(State.UPDATING, false);
Single.fromCallable(() -> {
deviceRepository.updateDeviceName(device, newName);
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
x -> {
Logger.i(TAG, "updateDeviceNameAsync onSuccess - " + device);
setState(State.OK, false);
},
e -> {
Logger.e(TAG, "updateDeviceNameAsync onError - " + device, e);
setState(State.OK, true);
});
return true;
}
@MainThread
public boolean updateDeviceSpecificDataAsync(@NonNull final Device device, @NonNull final String deviceSpecificDataJSon) {
Logger.i(TAG, "updateDeviceSpecificDataAsync - " + device);
Logger.i(TAG, " new device specific data: " + deviceSpecificDataJSon);
if (getCurrentState() != State.OK) {
Logger.w(TAG, " wrong state - " + getCurrentState());
return false;
}
setState(State.UPDATING, false);
Single.fromCallable(() -> {
deviceRepository.updateDeviceSpecificData(device, deviceSpecificDataJSon);
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
x -> {
Logger.i(TAG, "updateDeviceSpecificDataAsync onSuccess - " + device);
setState(State.OK, false);
},
e -> {
Logger.e(TAG, "updateDeviceSpecificDataAsync onError - " + device, e);
setState(State.OK, true);
});
return true;
}
//
// Private methods
//
@MainThread
private State getCurrentState() {
return stateChangeLiveData.getValue().getCurrentState();
}
@MainThread
private void setState(State newState, boolean isError) {
Logger.i(TAG, "setState - " + getCurrentState() + " -> " + newState);
State currentState = getCurrentState();
stateChangeLiveData.setValue(new StateChange(currentState, newState, isError));
}
@MainThread
private void setState(State newState, boolean isError, Object data) {
Logger.i(TAG, "setState with data - " + getCurrentState() + " -> " + newState);
State currentState = getCurrentState();
stateChangeLiveData.setValue(new StateChange(currentState, newState, isError, data));
}
//
// ScanProgress
//
public static class ScanProgress {
public int maxProgress;
public int progress;
public ScanProgress(int progress) {
this.maxProgress = SCAN_INTERVAL_SECS;
this.progress = progress;
}
}
}
| true |
ab89a0c9ba465efd2fd93dab180b20b38b019a54 | Java | GithubWangXiaoXi/Hospital-master | /src/main/java/com/ming/hospital/dao/MedicineMapper.java | UTF-8 | 482 | 1.929688 | 2 | [] | no_license | package com.ming.hospital.dao;
import com.ming.hospital.pojo.Medicine;
import java.util.List;
public interface MedicineMapper {
public Medicine queryMedicineByMno(String mno);
public List<Medicine> queryAllMedicine();
public void saveMedicine(Medicine medicine);
public void deleteMedicineByMno(String mno);
public void modifyMedicine(Medicine medicine);
public List<Medicine> queryMultiMedicine(Medicine medicine);
Medicine queryMedicineByMname(String mname);
}
| true |
e066a86153287b194eb8dc2068cd45749fe51710 | Java | jcamiloif6/ST0245-032 | /talleres/taller09/punto1.java | UTF-8 | 463 | 3 | 3 | [] | no_license | import java.util.HashMap;
public class punto1 {
HashMap <String, Integer> people = new HashMap<String, Integer>();
public void insertar(String nombre, int numero) {
people.put(nombre, numero);
}
public void mostrar(){
for (String i : people.keySet()) {
System.out.println( i + ": " + people.get(i));
}
}
public void buscar(String nombre){
System.out.println(people.get(nombre));
}
}
| true |
b2d3a79d9e289ced07e75ec06d1779202b325b27 | Java | UjjwalPandey/InterviewBit-Solution---Java | /src/TwoPointers/CountOfRectanglesWithAreaLessThanTheGivenNumber.java | UTF-8 | 1,818 | 3.75 | 4 | [] | no_license | /* Count of rectangles with area less than the given number
Given a sorted array of distinct integers A and an integer B,
find and return how many rectangles with distinct configurations can be created using elements of this array as length and breadth
whose area is lesser than B.
(Note that a rectangle of 2 x 3 is different from 3 x 2 if we take configuration into view)
For example:
A = [2 3 5], B = 15
Answer = 6 (2 x 2, 2 x 3, 2 x 5, 3 x 2, 3 x 3, 5 x 2)
Note: As the answer may be large return the answer modulo (10^9 + 7).
Input Format
The first argument given is the integer array A.
The second argument given is integer B.
Output Format
Return the number of rectangles with distinct configurations with area less than B modulo (10^9 + 7).
Constraints
1 <= length of the array <= 100000
1 <= A[i] <= 10^9
1 <= B <= 10^9
For Example
Input 1:
A = [1, 2, 3, 4, 5]
B = 5
Output 1:
8
Input 2:
A = [5, 10, 20, 100, 105]
B = 110
Output 2:
6
*/
package TwoPointers;
import java.util.Arrays;
public class CountOfRectanglesWithAreaLessThanTheGivenNumber {
static int mod = 1000000007;
public static void main(String[] args) {
int[] A = {1, 2, 3, 4, 5};
int B = 5;
System.out.println(numberOfRectangles(A,B));
}
private static int numberOfRectangles(int[] A, int B) {
long ans = 0, mod = (long)(1e9 + 7);
int l = 0, r = A.length - 1;
while(l < A.length && r >= 0) {
if(1L * A[l] * A[r] < B) {
ans = (ans + r + 1) % mod;
l++;
} else r--;
}
return (int)ans;
}
}
| true |
a8b5716b8df123f65305af7712fe432f76d0a18f | Java | isabelh340/classwork | /Interview Questions/Reverse.java | UTF-8 | 447 | 3.328125 | 3 | [] | no_license | import java.util.*;
public class Reverse {
public static String reverseWords(String s) {
String[] words = s.split("\\s+");
StringBuilder ans = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
ans.append(words[i]).append(" ");
}
ans.delete(ans.length()-1, ans.length());
return ans.toString();
}
public static void main(String args[]) {
System.out.println(reverseWords(" a nb asdf"));
}
} | true |
305730d5267f0ba8a85e9a545f0b8b9f5f9ec0ee | Java | samirvikash/watson-data-api-clients | /java/src/main/java/com/ibm/watson/data/client/model/ConnectionMetadata.java | UTF-8 | 4,909 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.ibm.watson.data.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Objects;
/**
* Metadata about a connection asset
*/
public class ConnectionMetadata extends Metadata {
private String assetId;
private Date createTime;
private String creatorId;
private String projectId;
private String catalogId;
private ConnectionMetadataUsage usage;
public ConnectionMetadata assetId(String assetId) {
this.assetId = assetId;
return this;
}
@javax.annotation.Nullable
@JsonProperty("asset_id")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public String getAssetId() { return assetId; }
public void setAssetId(String assetId) { this.assetId = assetId; }
public ConnectionMetadata createTime(Date createTime) {
this.createTime = createTime;
return this;
}
@javax.annotation.Nullable
@JsonProperty("create_time")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; }
public ConnectionMetadata creatorId(String creatorId) {
this.creatorId = creatorId;
return this;
}
@javax.annotation.Nullable
@JsonProperty("creator_id")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public String getCreatorId() { return creatorId; }
public void setCreatorId(String creatorId) { this.creatorId = creatorId; }
public ConnectionMetadata projectId(String projectId) {
this.projectId = projectId;
return this;
}
@javax.annotation.Nullable
@JsonProperty("project_id")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public String getProjectId() { return projectId; }
public void setProjectId(String projectId) { this.projectId = projectId; }
public ConnectionMetadata catalogId(String catalogId) {
this.catalogId = catalogId;
return this;
}
@javax.annotation.Nullable
@JsonProperty("catalog_id")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public String getCatalogId() { return catalogId; }
public void setCatalogId(String catalogId) { this.catalogId = catalogId; }
public ConnectionMetadata usage(ConnectionMetadataUsage usage) {
this.usage = usage;
return this;
}
@javax.annotation.Nullable
@JsonProperty("usage")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public ConnectionMetadataUsage getUsage() { return usage; }
public void setUsage(ConnectionMetadataUsage usage) { this.usage = usage; }
@Override
public boolean equals(java.lang.Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
ConnectionMetadata that = (ConnectionMetadata)o;
return super.equals(o) &&
Objects.equals(this.assetId, that.assetId) &&
Objects.equals(this.createTime, that.createTime) &&
Objects.equals(this.creatorId, that.creatorId) &&
Objects.equals(this.projectId, that.projectId) &&
Objects.equals(this.catalogId, that.catalogId) &&
Objects.equals(this.usage, that.usage);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), assetId, createTime, creatorId, projectId, catalogId, usage);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ConnectionMetadata {\n");
super.toString(sb);
sb.append(" assetId: ").append(toIndentedString(assetId)).append("\n");
sb.append(" createTime: ").append(toIndentedString(createTime)).append("\n");
sb.append(" creatorId: ").append(toIndentedString(creatorId)).append("\n");
sb.append(" projectId: ").append(toIndentedString(projectId)).append("\n");
sb.append(" catalogId: ").append(toIndentedString(catalogId)).append("\n");
sb.append(" usage: ").append(toIndentedString(usage)).append("\n");
sb.append("}");
return sb.toString();
}
}
| true |
d63aea78776cd7451c833eeb4faf2efbbe949fe5 | Java | AGGADNABIL/xitneppa | /project-war/src/main/java/com/tyba/appentix/web/materiel/search/MaterielsSearch.java | UTF-8 | 2,106 | 2.125 | 2 | [] | no_license | package com.tyba.appentix.web.materiel.search;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.tyba.appentix.business.materiel.model.Materiels;
import com.tyba.appentix.business.materiel.service.MaterielService;
import com.tyba.appentix.business.materiel.vo.MaterielsVO;
import com.tyba.appentix.business.materiel.vo.transformer.MaterielsVOTransformer;
import com.tyba.technicalServices.spring.BeansLookuper;
import com.tyba.technicalServices.web.ISearchResultVO;
import com.tyba.technicalServices.web.ResultBean;
import com.tyba.technicalServices.web.SearchBase;
import com.tyba.technicalServices.web.SearchConfig;
import com.tyba.technicalServices.web.SearchResultBean;
public class MaterielsSearch extends SearchBase implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public SearchResultBean tranform(List<Object> resultQuery) {
SearchResultBean searchResultBean = new SearchResultBean();
ResultBean resultBean = new ResultBean();
searchResultBean.setResultBean(resultBean);
List<ISearchResultVO> listServicesSearchResultsVo = new ArrayList<ISearchResultVO>();
MaterielsVOTransformer servicesVOTransformer = new MaterielsVOTransformer();
for (Object o : resultQuery) {
Materiels srv = (Materiels) o;
listServicesSearchResultsVo.add((MaterielsVO) servicesVOTransformer.model2VO(srv));
}
resultBean.setRows(listServicesSearchResultsVo);
return searchResultBean;
}
@SuppressWarnings("unchecked")
public List specificExecute(Serializable searchBean,
SearchConfig configuration, String sortField, String sortOrder) {
MaterielsCriteria criteria = (MaterielsCriteria) searchBean;
MaterielService referentielService = (MaterielService) BeansLookuper
.lookup("materielService");
return referentielService.findMaterielsByCriteria(criteria.getReferenceMateriel(), criteria.getLibelleMateriel(), configuration, sortField, sortOrder);
}
@Override
public SearchResultBean precondition(Serializable searchBean) {
// TODO Auto-generated method stub
return null;
}
}
| true |
e2009c045370297db2e29cc72ba256582b77a049 | Java | cckmit/dubboProject | /qumiandan-web/src/main/java/cn/qumiandan/web/frontServer/file/entity/request/IndexFileVO.java | UTF-8 | 448 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | package cn.qumiandan.web.frontServer.file.entity.request;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import lombok.Data;
/**
* @description:首页轮播图参数对象
* @author:zhuyangyong
* @date: 2018/11/13 18:39
*/
@Data
public class IndexFileVO implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(message = "区域编号不能为空")
private String areaCode;
}
| true |
5a5c0e280e9dff82a584ae7c700d15ab30d3a665 | Java | tryge/cucumber-jvm | /java/src/main/java/cucumber/annotation/Advice.java | UTF-8 | 617 | 2.5 | 2 | [
"MIT"
] | permissive | package cucumber.annotation;
import java.lang.annotation.*;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Advice {
/**
* @return the pattern that is used to match a step with this advice
*/
String value();
/**
* @return the pointcut annotations (i.e. they have to be annotated with
* <code>Pointcut</code>) that this advice may advise.
*/
Class<? extends Annotation>[] pointcuts();
/**
* @return max amount of time this is allowed to run for. 0 (default) means no restriction.
*/
int timeout() default 0;
}
| true |
441df95120b44156b009995c71b1d19383b9f4b0 | Java | lijinlong2016/demo | /src/main/java/com/test/classload/MCFClassLoader.java | UTF-8 | 1,291 | 2.515625 | 3 | [] | no_license | package com.test.classload;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
public class MCFClassLoader extends URLClassLoader {
public MCFClassLoader(URL[] urls) {
super(urls);
}
public MCFClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public MCFClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
@SuppressWarnings("rawtypes")
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class c = findLoadedClass(name);
if (c == null) {
try {
c = findClass(name);
} catch (ClassNotFoundException e) {
return super.loadClass(name);
}
}
return c;
}
}
class AA {
public ClassLoader getDSClassLoader(String moudleName) {
URLClassLoader urlClassLoader = null;
try {
urlClassLoader = new MCFClassLoader(new URL[]{new URL("......xxx.jar"), new URL("......yyy.jar")}, this.getClass().getClassLoader());
} catch (Exception e) {
e.printStackTrace();
}
return urlClassLoader;
}
} | true |
3f3cda39f939e6d0bb46796e88fd228e7275a71b | Java | forrep/slidesolver-java | /src/jp/ne/raccoon/slidesolver/JavaSolver.java | UTF-8 | 4,138 | 3.015625 | 3 | [
"MIT"
] | permissive | package jp.ne.raccoon.slidesolver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import jp.ne.raccoon.slidesolver.Solver.Direction;
import jp.ne.raccoon.slidesolver.Solver.FieldOperation;
import jp.ne.raccoon.slidesolver.Solver.MoveLimit;
import jp.ne.raccoon.slidesolver.Solver.SolveWorker;
public class JavaSolver {
public static void main(String[] args) throws Exception {
Reader reader = new InputStreamReader(JavaSolver.class.getResourceAsStream("problems.txt"));
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("solved.txt")));
// 移動数制限
String[] limitsString = bufferedReader.readLine().split(" ");
MoveLimit moveLimit = new MoveLimit(Integer.parseInt(limitsString[0]), Integer.parseInt(limitsString[1]), Integer.parseInt(limitsString[2]), Integer.parseInt(limitsString[3]));
// 行数
int count = Integer.parseInt(bufferedReader.readLine());
ExecutorService executor = Executors.newFixedThreadPool(2);
@SuppressWarnings("unchecked")
Future<SolveWorker>[] futures = (Future<SolveWorker>[]) new Future[count];
int lineNumber = 0;
int solved = 0;
long start = System.currentTimeMillis();
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] params = line.split(",");
int width = Integer.parseInt(params[0]);
int height = Integer.parseInt(params[1]);
String fieldString = params[2];
futures[lineNumber] = executor.submit(new SolveWorker(width, height, fieldString, false));
++lineNumber;
}
lineNumber = 0;
List<Integer> unsolved = new ArrayList<>();
for (Future<SolveWorker> future : futures) {
++lineNumber;
if (future == null) { continue; }
SolveWorker worker = future.get();
System.out.println("#" + lineNumber);
System.out.println("Problem : " + worker.getWidth() + "," + worker.getHeight() + "," + worker.getFieldString());
System.out.flush();
FieldOperation answerField = worker.getField();
System.out.println("Operation : " + answerField.getOperations());
System.out.println("Count : " + answerField.getOperationCount());
System.out.println("Distance : " + answerField.getManhattanDistance());
if (answerField.isSolved()) {
++solved;
moveLimit.add(answerField.getOperations());
writer.write(answerField.getOperations());
}
else {
unsolved.add(lineNumber);
}
writer.write("\n");
long elapsed = System.currentTimeMillis() - start;
long remain = Math.max(elapsed * count / lineNumber - elapsed, 0);
System.out.println("Elapsed : " + (elapsed / 1000) + " sec");
System.out.println("Remain : " + (remain / 1000) + " sec");
System.out.println("Total : " + ((elapsed + remain) / 1000) + " sec");
System.out.println();
System.out.flush();
}
System.out.println("Number : " + count);
System.out.println("Solved : " + solved);
System.out.println("Elapsed : " + ((System.currentTimeMillis() - start) / 1000) + " sec");
System.out.println("Limits(L): " + moveLimit.moves[Direction.LEFT.code] + "/" + moveLimit.limits[Direction.LEFT.code]);
System.out.println("Limits(R): " + moveLimit.moves[Direction.RIGHT.code] + "/" + moveLimit.limits[Direction.RIGHT.code]);
System.out.println("Limits(U): " + moveLimit.moves[Direction.UP.code] + "/" + moveLimit.limits[Direction.UP.code]);
System.out.println("Limits(D): " + moveLimit.moves[Direction.DOWN.code] + "/" + moveLimit.limits[Direction.DOWN.code]);
System.out.println();
System.out.print("Unsolved: ");
for (int i = 0; i < unsolved.size(); ++i) {
if (i > 0) {
System.out.print(",");
}
System.out.print(unsolved.get(i));
}
System.out.println();
executor.shutdownNow();
writer.close();
reader.close();
}
}
| true |
e8b51119ff7cb07e863e62ff18cccfacb7ade7e4 | Java | weilanx/FTPProject | /FTP/src/command/PwdCommand.java | UTF-8 | 558 | 2.65625 | 3 | [] | no_license | package command;
import server.ClientDeal;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
public class PwdCommand implements Command {
@Override
public void deal(BufferedWriter writer, String data, ClientDeal client) {
try {
//当前工作目录
String path = client.getCurrentPath();
writer.write("212 current path: "+path+" \r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
b28130ebc96636e24679c507b3a304fcd79d18fc | Java | Jovtcho/JavaFundamentals | /Java Advanced/03.String-Processing-Exercises/P15ValidUsernames.java | UTF-8 | 1,540 | 3.171875 | 3 | [
"MIT"
] | permissive | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class P15ValidUsernames {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String regex = "\\b[A-Za-z]\\w{2,24}\\b";
String inputLine = bf.readLine();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputLine);
List<String> userNames = new ArrayList<>();
while (matcher.find()) {
userNames.add(matcher.group());
}
int maxSum = 0;
String firstUserName = "";
String secondUserName = "";
if (userNames.size() == 1) {
firstUserName = userNames.get(0);
System.out.println(firstUserName);
return;
}
for (int i = 0; i < userNames.size() - 1; i++) {
int currentUserNameLen = userNames.get(i).length();
int nextUserNameLen = userNames.get(i + 1).length();
int currentSum = currentUserNameLen + nextUserNameLen;
if (currentSum > maxSum) {
maxSum = currentSum;
firstUserName = userNames.get(i);
secondUserName = userNames.get(i + 1);
}
}
System.out.println(firstUserName);
System.out.println(secondUserName);
}
}
| true |
7e78cf866f2f8655eced0c3fa661098bc6da5730 | Java | sandeepdice/myhibernateproject | /src/com/roadrantz/dao/ItemListDao.java | UTF-8 | 185 | 1.710938 | 2 | [] | no_license | package com.roadrantz.dao;
import java.util.List;
import standalone.beans.Category;
import standalone.beans.Item;
public interface ItemListDao {
List<Item> getItemList();
} | true |
91899b8453893939acc0331edad46d5a6293193b | Java | guisenhan/istudy | /app/src/main/java/hise/hznu/istudy/widget/LoadView.java | UTF-8 | 6,209 | 2.140625 | 2 | [] | no_license | package hise.hznu.istudy.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import hise.hznu.istudy.R;
/**
* Created by Jacky on 15/10/29.
*/
public class LoadView extends FrameLayout {
private FrameLayout loadingLayout;
private FrameLayout netErrorLayout;
private FrameLayout noDataLayout;
private ImageView loadingImage;
private TextView loadingViewText;
private TextView noDataText;
private LoadViewStatus currentLoadViewStatus = LoadViewStatus.NONE;
private OnLoadViewListener onLoadViewListener;
public LoadView(Context context) {
super(context);
init();
}
public LoadView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LoadView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LoadView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
View.inflate(getContext(), R.layout.view_load, this);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
loadingLayout = (FrameLayout) findViewById(R.id.ll_load_loading);
loadingLayout.setVisibility(GONE);
netErrorLayout = (FrameLayout) findViewById(R.id.ll_load_net_error);
netErrorLayout.setVisibility(GONE);
noDataLayout = (FrameLayout) findViewById(R.id.ll_load_no_data);
noDataLayout.setVisibility(GONE);
// loadingImage = (ImageView)findViewById(R.id.loading_image);
loadingViewText = (TextView) findViewById(R.id.loading_view_text);
noDataText = (TextView)findViewById(R.id.loading_view_no_data_text);
}
public void showLoading() {
if (loadingLayout != null) {
loadingLayout.setVisibility(VISIBLE);
// AnimationDrawable animationDrawable = (AnimationDrawable)loadingImage.getDrawable();
// animationDrawable.start();
}
if (netErrorLayout != null) {
netErrorLayout.setVisibility(GONE);
netErrorLayout.setOnClickListener(null);
}
if (noDataLayout != null) {
noDataLayout.setVisibility(GONE);
}
currentLoadViewStatus = LoadViewStatus.LOADING;
}
public void showNetError() {
if (loadingLayout != null) {
loadingLayout.setVisibility(GONE);
// AnimationDrawable animationDrawable = (AnimationDrawable)loadingImage.getDrawable();
// animationDrawable.stop();
}
if (netErrorLayout != null) {
netErrorLayout.setVisibility(VISIBLE);
netErrorLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (currentLoadViewStatus.equals(LoadViewStatus.NET_ERROR) && onLoadViewListener != null) {
onLoadViewListener.onNetErrorReload();
}
}
});
}
if (noDataLayout != null) {
noDataLayout.setVisibility(GONE);
}
currentLoadViewStatus = LoadViewStatus.NET_ERROR;
}
public void setNoDataText(String str){
noDataText.setText(str);
}
public void showNoData() {
if (loadingLayout != null) {
loadingLayout.setVisibility(GONE);
// AnimationDrawable animationDrawable = (AnimationDrawable)loadingImage.getDrawable();
// animationDrawable.stop();
}
if (netErrorLayout != null) {
netErrorLayout.setVisibility(GONE);
netErrorLayout.setOnClickListener(null);
}
if (noDataLayout != null) {
noDataLayout.setVisibility(VISIBLE);
}
currentLoadViewStatus = LoadViewStatus.NO_DATA;
}
public void clearLoad() {
if (loadingLayout != null) {
loadingLayout.setVisibility(GONE);
// AnimationDrawable animationDrawable = (AnimationDrawable)loadingImage.getDrawable();
// animationDrawable.stop();
}
if (netErrorLayout != null) {
netErrorLayout.setVisibility(GONE);
}
if (noDataLayout != null) {
noDataLayout.setVisibility(GONE);
}
}
public void showTransparentLoading() {
if (loadingLayout != null) {
loadingLayout.setClickable(false);
loadingLayout.setVisibility(VISIBLE);
loadingLayout.setBackgroundColor(ContextCompat.getColor(getContext(),android.R.color.transparent));
// AnimationDrawable animationDrawable = (AnimationDrawable)loadingImage.getDrawable();
// animationDrawable.start();
}
if (netErrorLayout != null) {
netErrorLayout.setVisibility(GONE);
netErrorLayout.setOnClickListener(null);
}
if (noDataLayout != null) {
noDataLayout.setVisibility(GONE);
}
currentLoadViewStatus = LoadViewStatus.LOADING;
}
public void setLoadingViewText(String text) {
if (loadingViewText != null) {
loadingViewText.setText(text);
}
}
public void setLoadingViewText(int resid) {
if (loadingViewText != null) {
loadingViewText.setText(resid);
}
}
public void setLoadingViewText(CharSequence text) {
if (loadingViewText != null) {
loadingViewText.setText(text);
}
}
public void setOnLoadViewListener(OnLoadViewListener onLoadViewListener) {
this.onLoadViewListener = onLoadViewListener;
}
private enum LoadViewStatus {
NONE, LOADING, NET_ERROR, NO_DATA
}
public interface OnLoadViewListener {
void onNetErrorReload();
}
}
| true |
a663eb59dde1c1128dbd537644c443ceb423d85a | Java | n9/MusicPlayerRemote | /app/src/main/java/net/prezz/mpr/service/PlaybackService.java | UTF-8 | 19,093 | 1.625 | 2 | [] | no_license | package net.prezz.mpr.service;
import java.util.Arrays;
import net.prezz.mpr.Utils;
import net.prezz.mpr.model.PlayerState;
import net.prezz.mpr.model.PlayerStatus;
import net.prezz.mpr.model.PlaylistEntity;
import net.prezz.mpr.model.ResponseReceiver;
import net.prezz.mpr.model.ResponseResult;
import net.prezz.mpr.model.StatusListener;
import net.prezz.mpr.model.TaskHandle;
import net.prezz.mpr.model.UriEntity;
import net.prezz.mpr.model.command.Command;
import net.prezz.mpr.model.command.NextCommand;
import net.prezz.mpr.model.command.PlayPauseCommand;
import net.prezz.mpr.model.command.PreviousCommand;
import net.prezz.mpr.model.command.VolumeDownCommand;
import net.prezz.mpr.model.command.VolumeUpCommand;
import net.prezz.mpr.model.external.CoverReceiver;
import net.prezz.mpr.model.external.ExternalInformationService;
import net.prezz.mpr.mpd.MpdPlayer;
import net.prezz.mpr.ui.ApplicationActivator;
import net.prezz.mpr.ui.helpers.VolumeButtonsHelper;
import net.prezz.mpr.ui.mpd.MpdPlayerSettings;
import net.prezz.mpr.ui.player.PlayerActivity;
import net.prezz.mpr.R;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
public class PlaybackService extends Service {
private static final String CMD_VOL_DOWN = "net.prezz.mpr.service.PlaybackService.CMD_VOL_DOWN";
private static final String CMD_VOL_UP = "net.prezz.mpr.service.PlaybackService.CMD_VOL_UP";
private static final String CMD_PREV = "net.prezz.mpr.service.PlaybackService.CMD_PREV";
private static final String CMD_PLAY_PAUSE = "net.prezz.mpr.service.PlaybackService.CMD_PLAY_PAUSE";
private static final String CMD_NEXT = "net.prezz.mpr.service.PlaybackService.CMD_NEXT";
private static final int NOTIFICATION_ID = 64545;
private static final Object lock = new Object();
private static boolean started = false;
private boolean isForegroundService;
private MpdPlayer player;
private PlayerStatus playerStatus;
private PlaylistEntity playlistEntity;
private Bitmap cover;
private PlayerInfoRefreshListener playerInfoRefreshListener;
private TaskHandle updatePlaylistHandle;
private TaskHandle updateCoverHandle;
private ControlBroadcastReceiver broadcastReceiver;
private int coverSize;
public static void start() {
synchronized (lock) {
Context context = ApplicationActivator.getContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Resources resources = context.getResources();
boolean enabled = sharedPreferences.getBoolean(resources.getString(R.string.settings_behavior_show_notification_key), false);
if (enabled && !started) {
started = true;
context.startService(new Intent(context, PlaybackService.class));
}
}
}
public static void stop() {
synchronized (lock) {
Context context = ApplicationActivator.getContext();
context.stopService(new Intent(context, PlaybackService.class));
started = false;
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
updatePlaylistHandle = TaskHandle.NULL_HANDLE;
updateCoverHandle = TaskHandle.NULL_HANDLE;
coverSize = (int) (getResources().getDisplayMetrics().density * 64);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
started = true; // if the service gets killed and restarted we need to set it to true
isForegroundService = false;
playlistEntity = null;
MpdPlayerSettings settings = MpdPlayerSettings.create(this);
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
broadcastReceiver = new ControlBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(CMD_VOL_DOWN);
filter.addAction(CMD_VOL_UP);
filter.addAction(CMD_PREV);
filter.addAction(CMD_PLAY_PAUSE);
filter.addAction(CMD_NEXT);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(broadcastReceiver, filter);
if (player != null) {
updateCoverHandle.cancelTask();
updatePlaylistHandle.cancelTask();
player.dispose();
}
updateNotification(isForegroundService);
player = new MpdPlayer(settings);
playerStatus = new PlayerStatus(false);
playerInfoRefreshListener = new PlayerInfoRefreshListener();
player.setStatusListener(playerInfoRefreshListener);
return START_STICKY;
}
@Override
public void onDestroy() {
updateCoverHandle.cancelTask();
updatePlaylistHandle.cancelTask();
if (player != null) {
player.dispose();
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
started = false;
super.onDestroy();
}
private void updateNotification(boolean sticky) {
String artistText = null;
String titleText = null;
if (playlistEntity != null) {
String artist = playlistEntity.getArtist();
if (artist != null) {
artistText = artist;
} else {
String name = playlistEntity.getName();
if (name != null) {
artistText = name;
} else {
artistText = "";
}
}
Integer track = playlistEntity.getTrack();
String title = playlistEntity.getTitle();
if (track != null && title != null) {
titleText = String.format("%s - %s", track, title);
} else if (title != null) {
titleText = title;
} else {
UriEntity uri = playlistEntity.getUriEntity();
if (uri != null) {
titleText = uri.getUriFilname();
} else {
titleText = "";
}
}
} else {
artistText = "";
titleText = getString(R.string.player_playing_info_none);
}
String volumeText = "";
int volume = (playerStatus != null) ? playerStatus.getVolume() : -1;
if (volume != -1) {
volumeText = getString(R.string.general_volume_text_format, volume);
} else {
volumeText = getString(R.string.general_volume_text_no_mixer);
}
PlayerState playerState = (playerStatus != null) ? playerStatus.getState() : PlayerState.STOP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
updateMediaNotificationM(artistText, titleText, volumeText, playerState, sticky);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
updateMediaNotificationL(artistText, titleText, volumeText, playerState);
} else {
updateBasicNotification(artistText, titleText, volumeText, playerState);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void updateMediaNotificationM(String artist, String title, String volume, PlayerState playerState, boolean sticky) {
Intent volDownIntent = new Intent(CMD_VOL_DOWN);
Intent volUpIntent = new Intent(CMD_VOL_UP);
Intent prevIntent = new Intent(CMD_PREV);
Intent playPauseIntent = new Intent(CMD_PLAY_PAUSE);
Intent nextIntent = new Intent(CMD_NEXT);
Intent launchIntent = new Intent(this, PlayerActivity.class);
int ic_play = (playerState == PlayerState.PLAY) ? R.drawable.ic_pause_w : (playerState == PlayerState.PAUSE) ? R.drawable.ic_paused_w : R.drawable.ic_play_w;
Notification.Builder notificationBuilder = new Notification.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_notification)
.setShowWhen(false)
.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_volume_down_w), "", PendingIntent.getBroadcast(this, 0, volDownIntent, 0)).build()) // #0
.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_volume_up_w), "", PendingIntent.getBroadcast(this, 0, volUpIntent, 0)).build()) // #1
.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_previous_w), "", PendingIntent.getBroadcast(this, 0, prevIntent, 0)).build()) // #2
.addAction(new Notification.Action.Builder(Icon.createWithResource(this, ic_play), "", PendingIntent.getBroadcast(this, 0, playPauseIntent, 0)).build()) // #3
.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_next_w), "", PendingIntent.getBroadcast(this, 0, nextIntent, 0)).build()) // #4
.setStyle(new Notification.MediaStyle().setShowActionsInCompactView(3)) // #3 play toggle button
.setContentTitle(title)
.setContentText(artist)
.setSubText(volume)
.setLargeIcon(cover)
.setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
.setAutoCancel(false)
.setOngoing(sticky);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getString(R.string.notification_media_player_channel_id);
NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
if (channel == null) {
channel = new NotificationChannel(channelId, getString(R.string.notification_media_player_channel_name), NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(channel);
}
notificationBuilder.setChannelId(channelId);
}
Notification notification = notificationBuilder.build();
if (sticky) {
startForeground(NOTIFICATION_ID, notification);
isForegroundService = true;
} else {
if (isForegroundService) {
stopForeground(false);
}
notificationManager.notify(NOTIFICATION_ID, notification);
isForegroundService = false;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void updateMediaNotificationL(String artist, String title, String volume, PlayerState playerState) {
Intent volDownIntent = new Intent(CMD_VOL_DOWN);
Intent volUpIntent = new Intent(CMD_VOL_UP);
Intent prevIntent = new Intent(CMD_PREV);
Intent playPauseIntent = new Intent(CMD_PLAY_PAUSE);
Intent nextIntent = new Intent(CMD_NEXT);
Intent launchIntent = new Intent(this, PlayerActivity.class);
int ic_play = (playerState == PlayerState.PLAY) ? R.drawable.ic_pause_w : (playerState == PlayerState.PAUSE) ? R.drawable.ic_paused_w : R.drawable.ic_play_w;
Notification notification = new Notification.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_notification)
.setShowWhen(false)
.addAction(R.drawable.ic_volume_down_w, "", PendingIntent.getBroadcast(this, 0, volDownIntent, 0)) // #0
.addAction(R.drawable.ic_volume_up_w, "", PendingIntent.getBroadcast(this, 0, volUpIntent, 0)) // #1
.addAction(R.drawable.ic_previous_w, "", PendingIntent.getBroadcast(this, 0, prevIntent, 0)) // #2
.addAction(ic_play, "", PendingIntent.getBroadcast(this, 0, playPauseIntent, 0)) // #3
.addAction(R.drawable.ic_next_w, "", PendingIntent.getBroadcast(this, 0, nextIntent, 0)) // #4
.setStyle(new Notification.MediaStyle().setShowActionsInCompactView(3)) // #3 play toggle button
.setContentTitle(title)
.setContentText(artist)
.setSubText(volume)
.setLargeIcon(cover)
.setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
.setAutoCancel(false)
.setOngoing(true)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private void updateBasicNotification(String artist, String title, String volume, PlayerState playerState) {
Intent volDownIntent = new Intent(CMD_VOL_DOWN);
Intent volUpIntent = new Intent(CMD_VOL_UP);
Intent playPauseIntent = new Intent(CMD_PLAY_PAUSE);
Intent launchIntent = new Intent(this, PlayerActivity.class);
int ic_play = (playerState == PlayerState.PLAY) ? R.drawable.ic_pause_w : (playerState == PlayerState.PAUSE) ? R.drawable.ic_paused_w : R.drawable.ic_play_w;
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setShowWhen(false)
.addAction(R.drawable.ic_volume_down_w, "", PendingIntent.getBroadcast(this, 0, volDownIntent, 0)) // #0
.addAction(R.drawable.ic_volume_up_w, "", PendingIntent.getBroadcast(this, 0, volUpIntent, 0)) // #1
.addAction(ic_play, "", PendingIntent.getBroadcast(this, 0, playPauseIntent, 0)) // #2
.setContentTitle(title)
.setContentText(artist)
.setSubText(volume)
.setLargeIcon(cover)
.setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
.setAutoCancel(false)
.setOngoing(true)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private class PlayerInfoRefreshListener extends ResponseReceiver<PlaylistEntity> implements StatusListener {
@Override
public void statusUpdated(PlayerStatus status) {
if (!status.isConnected() || status.getState() == PlayerState.STOP) {
PlaybackService.stop();
} else {
boolean updateState = (playerStatus.getState() != status.getState() || playerStatus.getVolume() != status.getVolume());
boolean updatePlaying = (playlistEntity == null || playerStatus.getPlaylistVersion() != status.getPlaylistVersion() || playerStatus.getCurrentSong() != status.getCurrentSong());
playerStatus = status;
if (updateState) {
updateNotification(status.getState() == PlayerState.PLAY);
}
if (updatePlaying) {
int position = Math.max(0, status.getCurrentSong());
updatePlaylistHandle.cancelTask();
updatePlaylistHandle = player.getPlaylistEntity(position, this);
}
}
}
@Override
public void receiveResponse(PlaylistEntity response) {
boolean updateCover = false;
if (response != null && playlistEntity == null) {
updateCover = true;
} else if (response == null && playlistEntity != null) {
updateCover = true;
} else if (response != null && playlistEntity != null) {
updateCover = !Utils.equals(response.getArtist(), playlistEntity.getArtist()) || !Utils.equals(response.getAlbum(), playlistEntity.getAlbum());
}
playlistEntity = response;
if (updateCover) {
cover = null;
}
updateNotification(isForegroundService);
if (updateCover && response != null) {
updateCoverHandle.cancelTask();
updateCoverHandle = ExternalInformationService.getCover(response.getArtist(), response.getAlbum(), coverSize, new CoverReceiver() {
@Override
public void receiveCover(Bitmap bitmap) {
cover = bitmap;
updateNotification(isForegroundService);
}
});
}
}
}
private class ControlBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (CMD_VOL_DOWN.equals(action)) {
sendControlCommand(new VolumeDownCommand(VolumeButtonsHelper.getVolumeAmount(context)));
} else if (CMD_VOL_UP.equals(action)) {
sendControlCommand(new VolumeUpCommand(VolumeButtonsHelper.getVolumeAmount(context)));
} else if (CMD_PREV.equals(action)) {
sendControlCommand(new PreviousCommand());
} else if (CMD_PLAY_PAUSE.equals(action)) {
sendControlCommand(new PlayPauseCommand());
} else if (CMD_NEXT.equals(action)) {
sendControlCommand(new NextCommand());
} else if (Intent.ACTION_SCREEN_ON.equals(action)) {
player.setStatusListener(playerInfoRefreshListener);
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
player.setStatusListener(null);
}
}
private void sendControlCommand(Command command) {
player.sendControlCommands(Arrays.asList(command), new ResponseReceiver<ResponseResult>() {
@Override
public void receiveResponse(ResponseResult response) {
}
});
}
}
}
| true |
d35e3fecb5e3123821faca8ebef01fdec1a26913 | Java | kongzhidea/jdk-source | /demo/src/main/java/demo/javafx_samples/src/Ensemble8/src/samples/java/ensemble/samples/graphics2d/stopwatch/DigitalClock.java | UTF-8 | 4,652 | 2.453125 | 2 | [
"BSD-3-Clause"
] | permissive | package demo.javafx_samples.src.Ensemble8.src.samples.java.ensemble.samples.graphics2d.stopwatch;
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.effect.Lighting;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class DigitalClock extends Parent {
private final HBox hBox = new HBox();
public final Font FONT = new Font(16);
private Text[] digits = new Text[8];
private Group[] digitsGroup = new Group[8];
private int[] numbers = {0, 1, 3, 4, 6, 7};
DigitalClock() {
configureDigits();
configureDots();
configureHbox();
getChildren().addAll(hBox);
}
private void configureDigits() {
for (int i : numbers) {
digits[i] = new Text("0");
digits[i].setFont(FONT);
digits[i].setTextOrigin(VPos.TOP);
digits[i].setLayoutX(2.3);
digits[i].setLayoutY(-1);
Rectangle background;
if (i < 6) {
background = createBackground(Color.web("#a39f91"), Color.web("#FFFFFF"));
digits[i].setFill(Color.web("#000000"));
} else {
background = createBackground(Color.web("#bdbeb3"), Color.web("#FF0000"));
digits[i].setFill(Color.web("#FFFFFF"));
}
digitsGroup[i] = new Group(background, digits[i]);
}
}
private void configureDots() {
digits[2] = createDot(":");
digitsGroup[2] = new Group(createDotBackground(), digits[2]);
digits[5] = createDot(".");
digitsGroup[5] = new Group(createDotBackground(), digits[5]);
}
private Rectangle createDotBackground() {
Rectangle background = new Rectangle(8, 17, Color.TRANSPARENT);
background.setStroke(Color.TRANSPARENT);
background.setStrokeWidth(2);
return background;
}
private Text createDot(String string) {
Text text = new Text(string);
text.setFill(Color.web("#000000"));
text.setFont(FONT);
text.setTextOrigin(VPos.TOP);
text.setLayoutX(1);
text.setLayoutY(-4);
return text;
}
private Rectangle createBackground(Color stroke, Color fill) {
Rectangle background = new Rectangle(14, 17, fill);
background.setStroke(stroke);
background.setStrokeWidth(2);
background.setEffect(new Lighting());
background.setCache(true);
return background;
}
private void configureHbox() {
hBox.getChildren().addAll(digitsGroup);
hBox.setSpacing(1);
}
public void refreshDigits(String time) { //expecting time in format "xx:xx:xx"
for (int i = 0; i < digits.length; i++) {
digits[i].setText(time.substring(i, i + 1));
}
}
}
| true |
09fa20afe55dc6f4579d1613375dfdf6230fee52 | Java | mail-vishalgarg/JavaPractice | /src/com/java/IO/StandardInput.java | UTF-8 | 427 | 3.265625 | 3 | [] | no_license | package com.oracle.IO;
import java.io.IOException;
public class StandardInput {
public static void main(String[] args) throws IOException {
/*System.out.println("Enter any character");
int y=System.in.read();
System.out.println((char)y);*/
char[] ary={'a','b','j'};
for(int i=0; i<ary.length;i++){
System.out.println((char)ary[i]);
}
int x=65;
System.out.println((char)x);
}
}
| true |
28b5a0eb0b977070169c4adfb135906bc7e1cf14 | Java | NandiniDR29/regression-test | /ren-automation-ui/src/main/java/com/exigen/ren/rest/claim/model/common/claimbody/claim/PaidToDateInfoEntityModel.java | UTF-8 | 1,546 | 2.21875 | 2 | [] | no_license | package com.exigen.ren.rest.claim.model.common.claimbody.claim;
import com.exigen.ipb.eisa.ws.rest.model.Model;
import java.util.Objects;
public class PaidToDateInfoEntityModel extends Model {
private String gracePeriod;
private String paidToDateWithGracePeriod;
private String paidToDate;
public String getGracePeriod() {
return gracePeriod;
}
public void setGracePeriod(String gracePeriod) {
this.gracePeriod = gracePeriod;
}
public String getPaidToDateWithGracePeriod() {
return paidToDateWithGracePeriod;
}
public void setPaidToDateWithGracePeriod(String paidToDateWithGracePeriod) {
this.paidToDateWithGracePeriod = paidToDateWithGracePeriod;
}
public String getPaidToDate() {
return paidToDate;
}
public void setPaidToDate(String paidToDate) {
this.paidToDate = paidToDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
PaidToDateInfoEntityModel that = (PaidToDateInfoEntityModel) o;
return Objects.equals(gracePeriod, that.gracePeriod) &&
Objects.equals(paidToDateWithGracePeriod, that.paidToDateWithGracePeriod) &&
Objects.equals(paidToDate, that.paidToDate);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), gracePeriod, paidToDateWithGracePeriod, paidToDate);
}
}
| true |
842a90218c0870b24e3d8ef707d3bcae24be6fd9 | Java | bnreplah/Sac2020 | /CMPR112/module11/module11/src/lecture11tempatureconvert/extraCredit.java | UTF-8 | 4,319 | 3.546875 | 4 | [] | no_license | /**
*Ticket : 86713
*Course : CMPR 112
*Student : Ben Halpern
*Instructor : Professor Kirscher
*Environment: Win 10 NetBeans
*Project Title :
*
*
*Assignment details:
*/
/*
* 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 lecture11tempatureconvert;
import java.util.Scanner;
import java.util.Random;
/**
*
* @author benha
*/
public class extraCredit {
static void homeworkHeader(String title){ //this method is overloaded, takes in a string value for the title
//homeworkHeader function which when called will produce the homework header
System.out.println("Homework Header");
System.out.println();//blank line for visibility
System.out.println("Ticket : 86713");
System.out.println( "Course : CMPR 112 ");
System.out.println( "Student : Ben Halpern ");
System.out.println( "Instructor : Joel Kirscher");
System.out.println( "Environment: Win 10 NetBeans ");
System.out.println( "Project Title : " + title); //the input from the user is printed out to the screen here
System.out.println("\n\n");
//end homework header outputs
}//end homeworkHeader method
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//Scanner input = new Scanner(System.in);
homeworkHeader("Extra Credit");
//System.out.println("please enter the number of tests, and the number of people:");
report(100);
report(1000);
}
/**
* returns a number 1/365
* @return
*/
public static int getBirthday(){
Random rand = new Random();
return rand.nextInt(365) + 1;
}//end getBirthday
public static double runTests(int numberOfPeople, int testNumbers){
int birthdays[] = new int[numberOfPeople];
int sameBirthday = 0;
//int birthdaysCreated = 0;
for(int testNum = 0; testNum <= testNumbers ; testNum++){
popBirthdays(birthdays);
if(match(numberOfPeople, birthdays))
sameBirthday++;
}//endfor
return (double)sameBirthday/(double)(testNumbers);
}//end runTests
public static boolean match(int numPeople, int birthdays[]){
int cases = 0;
for(int i = 0; i < birthdays.length/2 ; i++){
for(int k = birthdays.length/2; k < birthdays.length; k++ )
if(birthdays[i] == birthdays[k]){
cases++;
}//end if
}//end for
return (cases >=1);
}//end match
public static void popBirthdays(int birthdays[]){
for(int j = 0; j < birthdays.length; j++)
birthdays[j] = getBirthday();
}//end popBirthdays
public static void report(int testCases){
final int MAXPEOPLE = 80;
System.out.printf("%20s %20s %10s %20s %n","Tests Cases","Number of People","","Percentage sharing a birthday");
for(int tests = testCases,people = 2; people < MAXPEOPLE; people += 5){
System.out.printf("%20d %20d %20.2f %% %n",tests, people ,runTests(people, tests)*100 );
}//end for
System.out.println();//blank line for visibility
}
}
//Discussion Questions
/*
Did you expect to see these results? After running these simulations is it a big deal when in a small group ( perhaps 12 people) two people have the same birthday?
I don't really know what I expected. I kind of expected to see the results shown, knowing that the more comparisons the more likely there are those who share a birthday out of 1/365.
When 2 people have the same birthday in a small group it is a big deal since that is a 100% match out of the whole in that group. However the percentage is calculated more on liklihood of a mathch in a group not
how many match in a group. Therefore
What was easy? Did you find breaking it up into functions helped? Is that comfortable now?
Was there an unexpected difficult/challenging portion of the assignment? What data structure did you use? Did you consider a different solution?
*/ | true |
1577719ba36a837afbd90409db1505b11f47065a | Java | ArharbiOumkaltoum/-Travel-agency-jee | /src/agence/voyage/panier/Panier.java | UTF-8 | 615 | 2.203125 | 2 | [] | no_license | package agence.voyage.panier;
public class Panier {
private int id_panier;
private String destination;
private String prix;
private String duree;
public int getId_panier() {
return id_panier;
}
public void setId_panier(int id_panier) {
this.id_panier = id_panier;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getPrix() {
return prix;
}
public void setPrix(String prix) {
this.prix = prix;
}
public String getDuree() {
return duree;
}
public void setDuree(String duree) {
this.duree = duree;
}
}
| true |
7ccb4e6206c580f25aa14899a556d01669a9a901 | Java | benw1916/Shipping-Simulator | /src/main/java/Depricated/ShipStatus.java | UTF-8 | 1,051 | 2.515625 | 3 | [] | no_license | package main.java.Depricated;
public class ShipStatus{
/*public ShipStatus(Boat playerObject){
Abstract.RotateOptions(MenuDisplays.GetShoreOptionMenu()); //"Check Weather Report", "Check Ship Status", "Refuel Ship", "Check Port Prices", "Go Back"
System.out.println("Beet test");
ParseShoreOptions(Abstract.ScannerInt(), playerObject);
}
public ShipStatus(Boat playerObject, boolean UpgradeOrFuel){
if(UpgradeOrFuel == true){
// UpgradeShip(playerObject);
} else {
// shipFuel(playerObject);
}
}
//"Check Weather Report", "Check Ship Status", "Refuel Ship", "Check Port Prices", "Go Back"
private void ParseShoreOptions(int userInput, Boat playerObject){
if(userInput == 1){
;
}
if(userInput == 2){
UpgradeShip(playerObject);
}
if(userInput == 3){
System.out.println("Beep boop");
shipFuel(playerObject);
}
if(userInput == 4){
new SeaWeather().FormattedWeatherAndTemperature(playerObject, 30);
}
}
public void shipDamage(){
}*/
} | true |
187a58eb2e6d9002cf6d2bb87289500facbc2266 | Java | SapanShiv/bookstore-application | /src/main/java/com/bookstore/model/ErrorResponseTO.java | UTF-8 | 586 | 2.1875 | 2 | [] | no_license | package com.bookstore.model;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Error Response TO.
*
* @author shivanimalhotra
*
*/
@Data
@NoArgsConstructor
public class ErrorResponseTO {
/**
* @param message
* @param details
*/
public ErrorResponseTO(String message, List<Error> details) {
super();
this.message = message;
this.errorDetails = details;
}
/**
* The message.
*/
private String message;
/**
* The error.
*/
private boolean error;
/**
* The Error details.
*/
private List<Error> errorDetails;
}
| true |
9df90cb8a69ef066124f6d40274e6044dde1c8bd | Java | FeridQuluzade/teazy-coffee-shop-backend | /src/main/java/com/sale/teazy/domain/Sale.java | UTF-8 | 966 | 2.109375 | 2 | [] | no_license | package com.sale.teazy.domain;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Data
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "sales")
public class Sale {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "productId")
private Product productId;
private Long amount;
private Double price;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private SaleType saleType;
private String saleTypeValue;
private Double commissionPrice;
@CreationTimestamp
@Column(updatable = false, nullable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
}
| true |
a696b644f42425864474ea9ac82c63d4897d81e2 | Java | Sushantbhardwaj83/Test | /Practice/src/AverageOfN.java | UTF-8 | 265 | 2.953125 | 3 | [] | no_license | import java.util.Scanner;
public class AverageOfN {
double average(double n){
double avg=0;
while(n>=1)
{
avg=(avg+n)/n;
n--;
}
return avg;
}
public static void main(String[] args) {
int x=0x123;
System.out.println(x);
System.out.println(45/10/2);
}
}
| true |
732c1f2c0de19c08dd7c42285b899c2f341a5e0e | Java | DendiProject/ui-service | /src/main/java/com/netcracker/ui/service/graf/component/GrafState.java | UTF-8 | 565 | 1.648438 | 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 com.netcracker.ui.service.graf.component;
import com.vaadin.shared.ui.JavaScriptComponentState;
import java.util.ArrayList;
/**
*
* @author Artem
*/
public class GrafState extends JavaScriptComponentState{
public String eventStateInJSONFormat;
public String event;
public int nodesId;
public ArrayList<Node> nodes;
public ArrayList<Edge> edges;
}
| true |
49f0807af2ea0f338987d60db96cc3582de9ab2b | Java | ZoroSpace/LeetCode | /138CopyListwithRandomPointer.java | UTF-8 | 917 | 3.3125 | 3 | [] | no_license | /**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode cur1 = head,s2 = new RandomListNode(0), cur2 = s2;;
Map<RandomListNode,RandomListNode> map = new HashMap<>();
while(cur1 != null) {
cur2.next = new RandomListNode(cur1.label);
cur2 = cur2.next;
cur2.random = cur1.random;
map.put(cur1,cur2);
cur1 = cur1.next;
}
cur1 = head;
cur2 = s2.next;
while(cur1 != null) {
if(cur2.random != null) cur2.random = map.get(cur2.random);
cur1 = cur1.next;
cur2 = cur2.next;
}
return s2.next;
}
}
| true |