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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e3829316413126e7157d23af7805307c958aa4f2 | Java | PANU10/ElTallerDeCostura | /src/com/company/Cesta.java | UTF-8 | 1,096 | 3.109375 | 3 | [] | no_license | package com.company;
public class Cesta {
private int numPieza;
private final int maxCapa;
private boolean pieza;
private boolean ocupado;
public Cesta(int maxCapa) {
this.maxCapa = maxCapa;
}
public synchronized void aniyadirPieza(){
try {
while(ocupado) wait();
ocupado = true;
if (numPieza < maxCapa) {
this.numPieza +=1;
pieza = true;
}
ocupado = false;
notifyAll();
Thread.sleep(3000);
} catch (Exception e) {
e.getStackTrace();
}
}
public synchronized void cogerPieza(){
try {
while(ocupado || !pieza) wait();
ocupado = true;
if (numPieza > 0) {
numPieza--;
}
if(numPieza <= 0) pieza = false;
ocupado = false;
notifyAll();
} catch (Exception e) {
e.getStackTrace();
}
}
public synchronized int getNumPieza() {
return numPieza;
}
}
| true |
05be52044e86bd55cee77aac06c0eb7e81ea1800 | Java | dan-avram-selab/Laborator3_C | /src/ro/mta/facc/selab/RandomOutTask.java | UTF-8 | 299 | 2.640625 | 3 | [] | no_license | package ro.mta.facc.selab;
import java.util.Random;
public class RandomOutTask implements Task {
private int nr;
public RandomOutTask() {
this.nr = new Random().nextInt();
}
@Override
public void execute() {
System.out.println("The number is " + nr);
}
}
| true |
870741ade1bfb9f8f2f58d300eff5d5e0d5948a4 | Java | gabriel-ma/Digimon-API | /src/main/java/com/gabriel/digimonapi/service/AboutService.java | UTF-8 | 298 | 1.96875 | 2 | [] | no_license | package com.gabriel.digimonapi.service;
import com.gabriel.digimonapi.About.About;
import org.springframework.stereotype.Service;
@Service
public class AboutService {
public About retrieveApplicationInformation() {
return new About("This is the version 1 of the Digimon Api", "1.0");
}
}
| true |
d4a7e49fd452a953ad01c733f8539e869d8dc654 | Java | hedgehog-zowie/dp-parent | /dp-persist/src/main/java/com/iuni/dp/persist/datastat/dao/impl/MallPvuvDailyStatDaoImpl.java | UTF-8 | 13,145 | 2.09375 | 2 | [] | no_license | package com.iuni.dp.persist.datastat.dao.impl;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.iuni.dp.persist.common.dao.impl.BaseDaoImpl;
import com.iuni.dp.persist.datastat.dao.MallPvuvDailyStatDao;
import com.iuni.dp.persist.datastat.model.MallPvuvDailyStat;
/**
* 商城PV/UV基础数据日统计DAO实现类
* @author CaiKe
* @version dp-persist-1.0.0
*/
@Repository("mallPvuvDailyStatDao")
public class MallPvuvDailyStatDaoImpl extends BaseDaoImpl<MallPvuvDailyStat, Serializable> implements MallPvuvDailyStatDao {
private static final Logger logger = LoggerFactory.getLogger(MallPvuvDailyStatDaoImpl.class);
private static final BigDecimal ZERO_NUM = new BigDecimal("0.00");
@Override
public MallPvuvDailyStat selectMallPvuvDailyStatById(Integer id) {
logger.debug("MallPvuvDailyStatDaoImpl.selectMallPvuvDailyStatById(Integer) entry: id={}",
new Object[] { id });
long stime = System.currentTimeMillis();
MallPvuvDailyStat mallPvuvDailyStat = (MallPvuvDailyStat) getById(MallPvuvDailyStat.class.getSimpleName()+ ".selectMallPvuvDailyStatById"
, id);
logger.debug("MallPvuvDailyStatDaoImpl.selectMallPvuvDailyStatById(Integer) success: mallPvuvDailyStat={}, costTime={}ms",
new Object[] { mallPvuvDailyStat.toString(), System.currentTimeMillis() - stime });
return mallPvuvDailyStat;
}
@Override
public List<MallPvuvDailyStat> selectAllByExample(Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectAllByExample(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<MallPvuvDailyStat> mallPvuvDailyStats = findAllObjectsByPage(MallPvuvDailyStat.class.getSimpleName() + ".selectAllByExample", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectAllByExample(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return mallPvuvDailyStats;
}
@Override
public List<MallPvuvDailyStat> selectMallPvuvDailyStatByPage(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectMallPvuvDailyStatByPage(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<MallPvuvDailyStat> mallPvuvDailyStats = findAllObjectsByPage(MallPvuvDailyStat.class.getSimpleName() + ".selectMallPvuvDailyStatByPage", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectMallPvuvDailyStatByPage(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return mallPvuvDailyStats;
}
@Override
public Integer selectTotalCountByExample(Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectTotalCountByExample(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
Integer count = (Integer) getObjectByProperty(MallPvuvDailyStat.class.getSimpleName() + ".selectTotalCountByExample", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectTotalCountByExample(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return count;
}
@Override
public List<Map<String, Object>> selectMallDailyBaseStatByExample(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatByExample(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectMallDailyBaseStatByExample", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal orderNum = (BigDecimal) data.get("orderNum");
BigDecimal payNum = (BigDecimal) data.get("payNum");
BigDecimal visitDepth = ZERO_NUM;
BigDecimal payRate = ZERO_NUM;
BigDecimal orderRate = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
orderRate = orderNum.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
if(orderNum.compareTo(BigDecimal.ZERO) == 1) {
payRate = payNum.divide(orderNum, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
data.put("payRate", payRate);
data.put("orderRate", orderRate);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatByExample(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public List<Map<String, Object>> selectMallDailyBaseStatByPage(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatByPage(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectMallDailyBaseStatByPage", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal orderNum = (BigDecimal) data.get("orderNum");
BigDecimal payNum = (BigDecimal) data.get("payNum");
BigDecimal visitDepth = ZERO_NUM;
BigDecimal payRate = ZERO_NUM;
BigDecimal orderRate = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
orderRate = orderNum.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
if(orderNum.compareTo(BigDecimal.ZERO) == 1) {
payRate = payNum.divide(orderNum, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
data.put("payRate", payRate);
data.put("orderRate", orderRate);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatByPage(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public Integer selectMallDailyBaseStatCount(Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatCount(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
Integer count = (Integer) getObjectByProperty(MallPvuvDailyStat.class.getSimpleName() + ".selectMallDailyBaseStatCount", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectMallDailyBaseStatCount(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return count;
}
@Override
public List<Map<String, Object>> selectWjqDailyBaseStatByExample(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatByExample(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqDailyBaseStatByExample", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal visitDepth = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatByExample(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public List<Map<String, Object>> selectWjqDailyBaseStatByPage(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatByPage(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqDailyBaseStatByPage", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal visitDepth = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatByPage(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public Integer selectWjqDailyBaseStatCount(Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatCount(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
Integer count = (Integer) getObjectByProperty(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqDailyBaseStatCount", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqDailyBaseStatCount(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return count;
}
@Override
public List<Map<String, Object>> selectWjqMonthlyBaseStatByExample(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatByExample(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqMonthlyBaseStatByExample", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal visitDepth = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatByExample(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public List<Map<String, Object>> selectWjqMonthlyBaseStatByPage(
Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatByPage(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
List<Map<String, Object>> list = findAllObjectsByPage2(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqMonthlyBaseStatByPage", params);
if(CollectionUtils.isNotEmpty(list)) {
for(Map<String, Object> data : list) {
BigDecimal pv = (BigDecimal) data.get("pv");
BigDecimal uv = (BigDecimal) data.get("uv");
BigDecimal visitDepth = ZERO_NUM;
if(uv.compareTo(BigDecimal.ZERO) == 1) {
visitDepth = pv.divide(uv, 5, BigDecimal.ROUND_HALF_UP);
}
data.put("visitDepth", visitDepth);
}
}
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatByPage(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return list;
}
@Override
public Integer selectWjqMonthlyBaseStatCount(Map<String, Object> params) {
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatCount(Map<String, Object>) invoke");
Long stime = System.currentTimeMillis();
Integer count = (Integer) getObjectByProperty(MallPvuvDailyStat.class.getSimpleName() + ".selectWjqMonthlyBaseStatCount", params);
logger.debug("MallPvuvDailyStatDaoImpl.selectWjqMonthlyBaseStatCount(Map<String, Object>) success: costTime={}ms",
new Object[] { System.currentTimeMillis() - stime });
return count;
}
@Override
public Integer insertMallPvuvDailyStat(MallPvuvDailyStat mallPvuvDailyStat) {
logger.debug("MallPvuvDailyStatDaoImpl.insertMallPvuvDailyStat(StatScheme) entry: mallPvuvDailyStat={}",
new Object[] { mallPvuvDailyStat.toString() });
long stime = System.currentTimeMillis();
Integer insertIndex = (Integer) insert(mallPvuvDailyStat, MallPvuvDailyStat.class.getSimpleName() + ".insertMallPvuvDailyStat");
logger.debug("MallPvuvDailyStatDaoImpl.insertMallPvuvDailyStat(StatScheme) success: insertIndex={}, costTime={}ms",
new Object[] { insertIndex, System.currentTimeMillis() - stime });
return insertIndex;
}
@Override
public Integer deleteMallPvuvDailyStatById(Integer id) {
logger.debug("MallPvuvDailyStatDaoImpl.deleteMallPvuvDailyStatById(Integer) entry: id={}",
new Object[] { id });
long stime = System.currentTimeMillis();
Integer execCount = 0;
execCount = delete(id, MallPvuvDailyStat.class.getSimpleName() + ".deleteMallPvuvDailyStatById");
logger.debug("MallPvuvDailyStatDaoImpl.deleteMallPvuvDailyStatById(Integer) success: execCount={}, costTime={}ms",
new Object[] { execCount, System.currentTimeMillis() - stime });
return execCount;
}
}
| true |
40506adfe382b500b27fcbddca111ea040583b67 | Java | byp5303628/leetcode | /src/main/java/com/sapphire/leetcode/algorithm/question283/MoveZeros.java | UTF-8 | 374 | 2.765625 | 3 | [] | no_license | package com.sapphire.leetcode.algorithm.question283;
/**
* Author: 柏云鹏
* Date: 2019/6/16.
*/
public class MoveZeros {
public void moveZeroes(int[] nums) {
int i = nums.length - 1;
int j = nums.length - 1;
while (j >= 0) {
if (nums[j] == 0) {
j--;
continue;
}
}
}
}
| true |
616864aa298754ca9dd1b8d10afa31f8f8a33729 | Java | MichalGuz/java-basics | /src/main/java/tb_composition_room/Table.java | UTF-8 | 1,185 | 3.15625 | 3 | [] | no_license | package tb_composition_room;
public class Table extends FurnitureItem{
private int numberOfLegs;
public Table(double height, double width, double length, String color, String material, int numberOfLegs) {
super("table", height, width, length, color, material);
this.numberOfLegs = numberOfLegs;
}
public Table(String name, double height, double width, double length, String color, String material) {
super(name, height, width, length, color, material);
}
public void coverTheTable() {
System.out.println("Table was covered");
}
public int getNumberOfLegs() {
return numberOfLegs;
}
@Override
public String getName() {
return super.getName();
}
@Override
public double getHeight() {
return super.getHeight();
}
@Override
public double getWidth() {
return super.getWidth();
}
@Override
public double getLength() {
return super.getLength();
}
@Override
public String getColor() {
return super.getColor();
}
@Override
public String getMaterial() {
return super.getMaterial();
}
}
| true |
5f9f4d8f937c864bfeecb6f5cf9f34f374ff7bc0 | Java | ArfanR/Jeopardy | /Jeopardy/src/action_factory/ClockAnimationAction.java | UTF-8 | 491 | 1.875 | 2 | [] | no_license | package action_factory;
import frames.MainGUINetworked;
import game_logic.ServerGameData;
import messages.Message;
import other_gui.QuestionGUIElementNetworked;
import other_gui.TeamGUIComponents;
import server.Client;
public class ClockAnimationAction extends Action {
private QuestionGUIElementNetworked currentQuestion;
private TeamGUIComponents currentTeam;
public void executeAction(MainGUINetworked mainGUI, ServerGameData gameData, Message message,
Client client) {
}
}
| true |
f864c6b617009c2fd8ef3d1889ebecc31374638b | Java | nvanhoeck/NovaPolitica | /src/main/java/tools/dataconstants/PartiesConstants.java | UTF-8 | 518 | 1.773438 | 2 | [] | no_license | package tools.dataconstants;
public class PartiesConstants {
public static int id = 0;
public static int name = 1;
public static int shortname = 2;
public static int primaryColor = 3;
public static int secundaryColor = 4;
public static int budget = 5;
public static int popularity = 6;
public static int trust = 7;
public static int amountOfFederalSeats = 8;
public static int amountOfRegionalSeats = 9;
public static int country = 10;
public static int region = 11;
}
| true |
cc8737ca27bae30bc05d6a80f19f2e9ca2e245a4 | Java | moutainhigh/manfenjiayuan | /mfh-framework-business/src/main/java/org/century/schemas/DataType.java | UTF-8 | 2,692 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | package org.century.schemas;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable;
import java.util.Hashtable;
/**
* 商品属性 Goods Property
* <p>
* The maps between property ID and its meaning as follows:
* Property ID Property Name Mark
<ul>
<li>
1--Code of merchandise.店内码(商品编码)<br>
It’s a necessary property, and must be same as _goodscode field. It is the unique flag in the customer ’s retail system.
必须有,而且与_goodscode 相同。该信息是指客户零售系统中商品的唯一标 识(比如条形码)
</li>
<li>
2--Barcode.条形码
Unnecessary.非必须
</li>
</ul>
* </p>
*
* Created by bingshanguxue on 4/21/16.
*/
public class DataType implements KvmSerializable, Serializable {
public static final String NAMESPACE = "http://schemas.datacontract.org/2004/07/CENTURY_ESL.EntityEX";
public static final String _Text = "Text";
public static final String _Blob = "Blob";
public static final String _Numeric = "Numeric";
public static final String _DataTime = "DataTime";
public static final String _ImageDescriptionIndex = "ImageDescriptionIndex";
public static final DataType Text = new DataType(_Text);
public static final DataType Blob = new DataType(_Blob);
public static final DataType Numeric = new DataType(_Numeric);
public static final DataType DataTime = new DataType(_DataTime);
public static final DataType ImageDescriptionIndex = new DataType(_ImageDescriptionIndex);
public String value;
public DataType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public Object getProperty(int i) {
switch (i) {
case 0:
return getValue();
default:
return null;
}
}
@Override
public int getPropertyCount() {
return 1;
}
@Override
public void setProperty(int i, Object o) {
switch (i) {
case 0:
value = (String) o;
break;
default:
break;
}
}
@Override
public void getPropertyInfo(int i, Hashtable hashtable, PropertyInfo propertyInfo) {
switch (i) {
case 0:
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "value";
propertyInfo.namespace = NAMESPACE;
break;
default:
break;
}
}
}
| true |
0d055e92bd5b071f5aa2c718c4adddc5db30360e | Java | dontpanic42/Diss-O-Tron | /src/Structure/OntologyAnalyzer.java | UTF-8 | 5,378 | 2.21875 | 2 | [] | no_license | package Structure;
import Settings.InputSettings;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.ReasonerFactory;
import com.hp.hpl.jena.reasoner.ReasonerRegistry;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by daniel on 19.04.14.
*/
public class OntologyAnalyzer {
public interface AnalyzerEventHandler
{
public void onProgress(int current, int numClasses, String name);
public void onFinish(ArrayList<ClassInfo> classes, ArrayList<InstanceInfo> inst);
}
private OntModel model;
private ArrayList<OntClass> classes = null;
private ArrayList<Individual> individuals = null;
private InputSettings settings;
public OntologyAnalyzer(InputSettings settings)
{
OntDocumentManager dm = OntDocumentManager.getInstance();
OntModelSpec modelSpec = OntModelSpec.OWL_MEM_MICRO_RULE_INF; //OntModelSpec.OWL_MEM;
modelSpec.setDocumentManager(dm);
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.read(FileManager.get().open(settings.ontFilename), settings.ontFiletype);
this.settings = settings;
this.model = ontModel;
}
private ArrayList<Individual> getNamedIndividuals()
{
if(this.individuals != null)
{
return this.individuals;
}
ArrayList<Individual> list = new ArrayList<Individual>();
int counter = 0;
Individual i;
OntResource r;
for(OntClass o : model.listHierarchyRootClasses().toList())
{
ExtendedIterator<? extends OntResource> it = o.listInstances();
while(it.hasNext())
{
r = it.next();
if(!r.canAs(Individual.class))
{
continue;
}
i = r.as(Individual.class);
if(!i.isAnon() && i.getLocalName() != null)
{
if(counter++ >= settings.maxClasses)
{
System.err.println("Reached maximum individual count: " + settings.maxClasses + " - Ignoring rest.");
break;
}
System.out.println("Scanned individual " + counter);
list.add(i);
}
}
}
this.individuals = list;
return list;
}
private ArrayList<OntClass> getNamedClasses()
{
if(this.classes != null)
{
return this.classes;
}
ArrayList<OntClass> list = new ArrayList<OntClass>();
int counter = 0;
for(OntClass o : model.listClasses().toList())
{
if(!o.isAnon() && o.getLocalName() != null)
{
if(counter++ >= settings.maxClasses)
{
System.err.println("Reached maximum class count: " + settings.maxClasses + " - Ignoring rest.");
break;
}
list.add(o);
}
}
this.classes = list;
return list;
}
public int getNumNamedClasses()
{
return getNamedClasses().size();
}
public void analyze(InputSettings ips, AnalyzerEventHandler handler)
{
Analyzer a = new Analyzer(getNamedClasses(), getNamedIndividuals(), handler);
new Thread(a).start();
}
class Analyzer implements Runnable
{
AnalyzerEventHandler handler;
ArrayList<OntClass> classes;
ArrayList<Individual> individuals;
ClassAnalyzer ca = new ClassAnalyzer();
IndividualAnalyzer ia = new IndividualAnalyzer();
public Analyzer(ArrayList<OntClass> classes, ArrayList<Individual> individuals, AnalyzerEventHandler handler)
{
this.handler = handler;
this.classes = classes;
this.individuals = individuals;
}
public void run()
{
int counter = 0;
int max = classes.size() + individuals.size();
ArrayList<ClassInfo> info = new ArrayList<ClassInfo>();
ClassInfo classInfo;
for(OntClass o : classes)
{
//if(!o.getLocalName().equals("Kraftfahrer"))
// continue;
//System.out.println("Reading " + (++counter) + " von " + max);
classInfo = ca.analyze(o);//new ClassInfo(o);
info.add(classInfo);
handler.onProgress(++counter, max, "Klasse " + classInfo.getName());
}
ArrayList<InstanceInfo> indv = new ArrayList<InstanceInfo>();
InstanceInfo instanceInfo;
for(Individual i : individuals)
{
instanceInfo = ia.analyze(i);
indv.add(instanceInfo);
handler.onProgress(++counter, max, "Individual " + instanceInfo.getName());
}
handler.onFinish(info, indv);
}
}
}
| true |
9cb680d22acc72b980f5af7112b9ee9714af352a | Java | lcombs15/halloween-tower-defense | /src/test/java/mobs/MobTest.java | UTF-8 | 12,786 | 2.6875 | 3 | [
"MIT"
] | permissive | package mobs;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import projectiles.ChainLightning;
import projectiles.FireBlast;
import projectiles.IceBeam;
import projectiles.Projectile;
import utilities.Position;
import views.DriverView;
import java.awt.image.BufferedImage;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
public class MobTest {
private Mob sut_BasicMob;
private Mob sut_EvilPumpkinMob;
private Mob sut_FireImmuneMob;
private Mob sut_FrostImmuneMob;
private Mob sut_GiantPumpkinMob;
private Mob sut_LaughingPumpkinMob;
private Mob sut_LightningGolemMob;
private Mob sut_LightningImmuneMob;
private Mob sut_PumpkinMob;
private Mob sut_SpeedyMob;
private Mob sut_SpiderMob;
private Mob sut_TankMob;
private Mob sut_WitchMob;
private Mob sut_ZombieMob;
@Mock
private Projectile projectile;
@Mock
private IceBeam iceMock;
@Mock
private FireBlast fireMock;
@Mock
private ChainLightning chainMock;
@BeforeEach
public void init() {
sut_BasicMob = new BasicMob(1, 1, new Position(0, 0));
sut_EvilPumpkinMob = new EvilPumpkinMob(3, 3, new Position(0, 0));
sut_FireImmuneMob = new FireImmuneMob(1, 1, new Position(0, 0));
sut_FrostImmuneMob = new FrostImmuneMob(1, 1, new Position(0, 0));
sut_GiantPumpkinMob = new GiantPumpkinMob(1, 1, new Position(0, 0));
sut_LaughingPumpkinMob = new LaughingPumpkinMob(1, 1, new Position(0, 0));
sut_LightningGolemMob = new LightningGolemMob(1, 1, new Position(0, 0));
sut_LightningImmuneMob = new LightningImmuneMob(1, 1, new Position(0, 0));
sut_PumpkinMob = new PumpkinMob(1, 1, new Position(0, 0));
sut_SpeedyMob = new SpeedyMob(1, 1, new Position(0, 0));
sut_SpiderMob = new SpiderMob(1, 1, new Position(0, 0));
sut_TankMob = new TankMob(1, 1, new Position(0, 0));
sut_WitchMob = new WitchMob(1, 1, new Position(0, 0));
sut_ZombieMob = new ZombieMob(1, 1, new Position(0, 0));
MockitoAnnotations.initMocks(this);
}
@Test
public void givenBasicMob_WhenLevel1EasyDifficulty_ThenHealthBoost45() {
assertEquals(45, sut_BasicMob.getHealthBoost(1, 30, 1));
}
@Test
public void givenBasicMob_WhenLevel1EasyDifficulty_ThenHealth245() {
assertEquals(245, sut_BasicMob.getHealth());
}
@Test
public void givenEvilPumpkinMob_WhenLevel3HardDifficulty_ThenHealthBoost1350() {
assertEquals(1350, sut_EvilPumpkinMob.getHealthBoost(3, 60, 3));
}
@Test
public void givenMob_WhenSetNewPosition_ThenPositionX5() {
sut_FireImmuneMob.setPosition(new Position(5, 4));
assertEquals(5, sut_FireImmuneMob.getPosition().getXCord());
}
@Test
public void givenMob_WhenSetNewPosition_ThenPositionY4() {
sut_FrostImmuneMob.setPosition(5, 4);
assertEquals(4, sut_FrostImmuneMob.getPosition().getYCord());
}
@Test
public void givenFrostImmuneMob_WhenGetWidth_Then50() {
assertEquals(50, sut_FrostImmuneMob.getMobWidth());
}
@Test
public void givenFrostImmuneMob_WhenGetHeight_Then50() {
assertEquals(50, sut_FrostImmuneMob.getMobHeight());
}
@Test
public void givenMob_WhenSetDirectionL_ThenLeft() {
sut_GiantPumpkinMob.setDirection('l');
assertEquals('l', sut_GiantPumpkinMob.getDirection());
}
@Test
public void givenMob_WhenDirectionRSetToT_ThenR() {
sut_GiantPumpkinMob.setDirection('t');
assertNotEquals('t', sut_GiantPumpkinMob.getDirection());
}
@Test
public void givenMob_WhenGetUUID_ThenNotNull() {
assertNotNull(sut_LaughingPumpkinMob.getID());
}
@Test
public void givenLaughingPumpkinMob_WhenGetSpeedAndNoSlowdownAndEasy_Then5() {
assertEquals(5, sut_LaughingPumpkinMob.getSpeed());
}
@Test
public void givenLaughingPumpkinMob_WhenGetSlowPotency_Then0() {
assertEquals(0, sut_LaughingPumpkinMob.getSlowPotency());
}
@Test
public void givenLightningGolemMob_WhenGetRadius_Then30() {
assertEquals(30, sut_LightningGolemMob.getRadius());
}
@Test
public void givenMob_WhenTraveledDistance_Then1() {
sut_LightningGolemMob.traveledDistance();
assertEquals(1, sut_LightningGolemMob.getDistanceTraveled());
}
@Test
public void givenMob_WhenVisible_ThenTrue() {
assertTrue(sut_LightningGolemMob.isVisible());
}
@Test
public void givenMob_WhenVanished_ThenNotVisible() {
sut_LightningImmuneMob.vanishMob();
assertFalse(sut_LightningImmuneMob.isVisible());
}
@Test
public void givenMob_WhenActivated_ThenIsActive() {
sut_PumpkinMob.activate();
assertTrue(sut_PumpkinMob.isActive());
}
@Test
public void givenMob_WhenNotActivated_ThenNotActive() {
assertFalse(sut_LightningImmuneMob.isActive());
}
@Test
public void givenMob_WhenNotHitByIceBeam_ThenFalse() {
assertFalse(sut_SpeedyMob.isHitByIceBeam());
}
@Test
public void givenMob_WhenGetHashCode_ThenIDHashPlus31() {
assertEquals(sut_SpiderMob.getID().hashCode() + 31, sut_SpiderMob.hashCode());
}
@Test
public void givenTankMob_WhenWitchMob_ThenNotEquals() {
assertFalse(sut_TankMob.equals(sut_WitchMob));
}
@Test
public void givenZombieMob_WhenBasicMobTraveledLess_ThenNegative1() {
sut_ZombieMob.traveledDistance();
assertTrue(sut_ZombieMob.compareTo(sut_BasicMob) < 0);
}
@Test
public void givenZombieMob_WhenBasicMobTraveledSame_Then0() {
sut_ZombieMob.traveledDistance();
sut_BasicMob.traveledDistance();
assertEquals(0, sut_ZombieMob.compareTo(sut_BasicMob));
}
@Test
public void givenZombieMob_WhenBasicMobTraveledMore_ThenPositive1() {
sut_BasicMob.traveledDistance();
assertTrue(sut_ZombieMob.compareTo(sut_BasicMob) > 0);
}
@Test
public void givenBasicMob_WhenHitBy200DamageAndIsLevel1AndDifficulty1_ThenHealth45() {
when(projectile.getDamage()).thenReturn(200.0);
when(projectile.getDamageDuration()).thenReturn(1.0);
sut_BasicMob.activate();
sut_BasicMob.mobHitBy(projectile);
sut_BasicMob.mobDamageTick();
assertEquals(45, sut_BasicMob.getHealth());
}
@Test
public void givenBasicMob_WhenHitByIceBeam_ThenIsHitByIceBeam() {
sut_BasicMob.activate();
sut_BasicMob.mobHitBy(iceMock);
assertTrue(sut_BasicMob.isHitByIceBeam());
}
@Test
public void givenFrostImmuneMob_WhenHitByIceBeam_ThenNotHitByIceBeam() {
when(iceMock.isIce()).thenReturn(true);
sut_FrostImmuneMob.activate();
sut_FrostImmuneMob.mobHitBy(iceMock);
assertFalse(sut_FrostImmuneMob.isHitByIceBeam());
}
@Test
public void givenFireImmuneMob_WhenHitByFireBlastAndLevel1Difficulty1_ThenHealth245() {
when(fireMock.isFire()).thenReturn(true);
sut_FireImmuneMob.activate();
sut_FireImmuneMob.mobHitBy(fireMock);
sut_FireImmuneMob.mobDamageTick();
assertEquals(245, sut_FireImmuneMob.getHealth());
}
@Test
public void givenLightningImmuneMob_WhenHitByLightningAndLevel1Difficulty1_ThenHealth115() {
when(chainMock.isLightning()).thenReturn(true);
sut_LightningImmuneMob.activate();
sut_LightningImmuneMob.mobHitBy(chainMock);
sut_LightningImmuneMob.mobDamageTick();
assertEquals(115, sut_LightningImmuneMob.getHealth());
}
@Test
public void givenFrostImmuneMobJustCreated_WhenGetImage_ThenMatches() {
BufferedImage img1 = DriverView.getImage("GhostMobR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_FrostImmuneMob.getImage().getRGB(x, y));
}
@Test
public void givenFrostImmuneMobMovingLeft_WhenGetImage_ThenMatches() {
sut_FrostImmuneMob.movingLeft();
BufferedImage img1 = DriverView.getImage("GhostMob.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_FrostImmuneMob.getImage().getRGB(x, y));
}
@Test
public void givenFrostImmuneMobMovingRight_WhenGetImage_ThenMatches() {
sut_FrostImmuneMob.movingLeft();
sut_FrostImmuneMob.movingRight();
BufferedImage img1 = DriverView.getImage("GhostMobR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_FrostImmuneMob.getImage().getRGB(x, y));
}
@Test
public void givenLightningGolemMobMovingLeft_WhenGetImage_ThenMatches() {
sut_LightningGolemMob.movingLeft();
BufferedImage img1 = DriverView.getImage("LightningGolemMob.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_LightningGolemMob.getImage().getRGB(x, y));
}
@Test
public void givenLightningGolemMobMovingRight_WhenGetImage_ThenMatches() {
sut_LightningGolemMob.movingLeft();
sut_LightningGolemMob.movingRight();
BufferedImage img1 = DriverView.getImage("LightningGolemMobR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_LightningGolemMob.getImage().getRGB(x, y));
}
@Test
public void givenLightningImmuneMobMovingLeft_WhenGetImage_ThenMatches() {
sut_LightningImmuneMob.movingLeft();
BufferedImage img1 = DriverView.getImage("LightningGolemMob.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_LightningImmuneMob.getImage().getRGB(x, y));
}
@Test
public void givenLightningImmuneMobMovingRight_WhenGetImage_ThenMatches() {
sut_LightningImmuneMob.movingLeft();
sut_LightningImmuneMob.movingRight();
BufferedImage img1 = DriverView.getImage("LightningGolemMobR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_LightningImmuneMob.getImage().getRGB(x, y));
}
@Test
public void givenSpeedyMobMovingLeft_WhenGetImage_ThenMatches() {
sut_SpeedyMob.movingLeft();
BufferedImage img1 = DriverView.getImage("Bat.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_SpeedyMob.getImage().getRGB(x, y));
}
@Test
public void givenSpeedyMobMovingRight_WhenGetImage_ThenMatches() {
sut_SpeedyMob.movingLeft();
sut_SpeedyMob.movingRight();
BufferedImage img1 = DriverView.getImage("BatR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_SpeedyMob.getImage().getRGB(x, y));
}
@Test
public void givenTankMobMovingLeft_WhenGetImage_ThenMatches() {
sut_TankMob.movingLeft();
BufferedImage img1 = DriverView.getImage("ZombieMob.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_TankMob.getImage().getRGB(x, y));
}
@Test
public void givenTankMobMovingRight_WhenGetImage_ThenMatches() {
sut_TankMob.movingLeft();
sut_TankMob.movingRight();
BufferedImage img1 = DriverView.getImage("ZombieMobR.png", 50, 50);
for (int x = 0; x < img1.getWidth(); x++)
for (int y = 0; y < img1.getHeight(); y++)
assertEquals(img1.getRGB(x, y), sut_TankMob.getImage().getRGB(x, y));
}
@Test
public void givenWitchMob_WhenImmuneToLightning_ThenTrue() {
assertTrue(sut_WitchMob.immuneToLightning());
}
@Test
public void givenWitchMob_WhenImmuneToFire_ThenTrue() {
assertTrue(sut_WitchMob.immuneToFire());
}
@Test
public void givenWitchMob_WhenImmuneToIce_ThenTrue() {
assertTrue(sut_WitchMob.immuneToIce());
}
}
| true |
72d6f50ee0ce167f85136ac6c31ed95183974241 | Java | PavelMeld/hh-backend-homework | /backend/backend-src/src/main/test/java/hh/TestHelper.java | UTF-8 | 1,181 | 2.359375 | 2 | [] | no_license | package hh;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Stream;
public class TestHelper {
private static final Path SCRIPTS_DIR = Path.of("src","main", "resources");
public static void executeScript(SessionFactory streamFactory, String scriptFileName) {
Session session = streamFactory.openSession();
Transaction tx = session.beginTransaction();
splitToQueries(SCRIPTS_DIR.resolve(scriptFileName))
.forEach((query) -> {
session.createSQLQuery(query);
});
tx.commit();
session.close();
}
private static Stream<String> splitToQueries(Path path) {
try {
return Arrays.stream(Files.readString(path).split(";"));
} catch (IOException e) {
throw new RuntimeException("Can't read file " + path, e);
}
}
public static void initDb(SessionFactory factory) {
executeScript(factory, "db_init.sql");
}
}
| true |
e8e1862a364f306bd19eebc7441f2c5da7fa54d0 | Java | BrndBot/BrndBot_old | /bbproject/src/com/brndbot/servlets/SetSessionServlet.java | UTF-8 | 8,695 | 2.5625 | 3 | [] | no_license | /**
* CONFIDENTIAL
*
* All rights reserved by Brndbot, Ltd. 2014
*/
package com.brndbot.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.brndbot.block.ChannelEnum;
import com.brndbot.db.ImageType;
import com.brndbot.system.SessionUtils;
import com.brndbot.system.Utils;
/** How does managing the session from a servlet and serializing everything
* as JDOM make sense? Probably should delete this and replace it with
* sane session management. */
public class SetSessionServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final int TIMEOUT_PERIOD = 30 * 60; // 30 minutes, given in seconds
final static Logger logger = LoggerFactory.getLogger(SetSessionServlet.class);
private static int NEG_ONE = -1;
public SetSessionServlet ()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
/**
* Security cautions here. To avoid a bootstrapping issue, this can't use AuthenticationFilter.
* It's written so you can set only the image type without being logged in. I don't
* understand why, but I'll leave it that way.
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
logger.debug("--------Entering SetSessionServlet----------");
HttpSession session = request.getSession();
// Check if the duration has been set from the default. If not, set it.
int timeout = session.getMaxInactiveInterval();
if (timeout < TIMEOUT_PERIOD) {
session.setMaxInactiveInterval (TIMEOUT_PERIOD);
}
String action = Utils.getStringParameter(request, "action").toLowerCase();
logger.debug("Session ACTION: " + action);
if (action.equals(SessionUtils.TEST)) {
// Check if the session is active. Return OK if it is, unauthorized if it isn't.
int user_id = SessionUtils.getIntSession(session, SessionUtils.USER_ID);
if (user_id == 0) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
else {
response.setStatus(HttpServletResponse.SC_OK);
}
return;
}
if (action.equals(SessionUtils.IMAGE))
{
// Set the image type into the session
int image_id = Utils.getIntParameter(request, SessionUtils.IMAGE_ID_KEY);
if (image_id < 1)
{
session.removeAttribute(SessionUtils.IMAGE_ID_KEY);
}
else
{
ImageType image_type = ImageType.getByItemNumber(image_id);
if (image_type == null)
{
logger.debug("Invalid image_type: " + image_id);
throw new RuntimeException("Invalid image_type: " + image_id);
}
session.setAttribute(SessionUtils.IMAGE_ID_KEY, "" + image_id);
}
// Send an empty json reply
JSONObject json_obj = new JSONObject();
try
{
json_obj.put(SessionUtils.IMAGE_ID_KEY, "" + image_id);
}
catch (JSONException e)
{
String s = "JSON error returning image_type: " + image_id + "\n" + e.getMessage();
logger.error(s);
throw new RuntimeException(s);
}
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
logger.debug("JSON: {}", json_obj.toString());
out.println(json_obj);
out.flush();
response.setStatus(HttpServletResponse.SC_OK);
return;
}
int user_id = SessionUtils.getIntSession(session, SessionUtils.USER_ID);
if (user_id == 0)
{
//logger.debug("USER NOT LOGGED IN, SENDING TO LOGIN PAGE");
//response.sendRedirect("index.jsp");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// See if we're setting the blocks into the session
if (action.equals(SessionUtils.BLOCKS))
{
String json_array = Utils.getStringParameter(request, "hiddenBlocks");
session.setAttribute(SessionUtils.BLOCKS, json_array);
JSONObject json_obj = new JSONObject();
try
{
// System.out.println(json_array);
json_obj.put(SessionUtils.BLOCKS, json_array);
}
catch (JSONException e)
{
logger.error("Json exception: {} ", e.getMessage());
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
finally
{
}
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(json_obj);
out.flush();
response.setStatus(HttpServletResponse.SC_OK);
return;
}
if (!action.equals(SessionUtils.SET) && !action.equals(SessionUtils.CLEAR)
&& !action.equals(SessionUtils.GET))
{
logger.debug("Invalid action: " + action);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
int channel = NEG_ONE;
String content = "";
int database_id = NEG_ONE;
boolean foundOne = false;
if (action.equals(SessionUtils.CLEAR))
{
// I don't think this makes any sense.
// System.out.println("CLEARING THE SESSION!");
session.setAttribute(SessionUtils.CHANNEL_KEY, "" + NEG_ONE);
session.setAttribute(SessionUtils.CONTENT_KEY, "");
session.setAttribute(SessionUtils.DATABASE_ID_KEY, "" + NEG_ONE);
// FUSED_IMAGE_ID_KEY is cleared here, but set directly to session in servlets
session.setAttribute(SessionUtils.FUSED_IMAGE_ID_KEY, "" + NEG_ONE);
}
else if (action.equals(SessionUtils.GET))
{
// Fall through but legal
}
else // Set
{
// Check channel
channel = Utils.getIntParameter(request, SessionUtils.CHANNEL_KEY);
if (channel > 0)
{
ChannelEnum ch_enum = ChannelEnum.getByValue(channel);
System.out.println("Set non-zero channel to: " + channel + ", " + ch_enum.getItemText());
if (ch_enum == ChannelEnum.CH_NONE)
{
logger.debug("Unexpected channel: " + channel);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
session.setAttribute(SessionUtils.CHANNEL_KEY, "" + channel);
foundOne = true;
}
else
{
channel = SessionUtils.getIntSession(session, SessionUtils.CHANNEL_KEY);
}
// Check content type. In the new world, this is a model name.
content = Utils.getStringParameter(request, SessionUtils.CONTENT_KEY);
if (content != null) {
session.setAttribute(SessionUtils.CONTENT_KEY, "" + content);
foundOne = true;
}
// else
// {
// content = Utils.getIntSession(session, SessionUtils.CONTENT_KEY);
// }
// Check database id
/**** THIS SOUNDS SERIOUSLY UNSAFE. DISABLE IT AND SEE WHAT HAPPENS. *****/
database_id = Utils.getIntParameter(request, SessionUtils.DATABASE_ID_KEY);
if (database_id > 0)
{
// session.setAttribute(SessionUtils.DATABASE_ID_KEY, "" + database_id);
foundOne = true;
}
else
{
// System.out.println("Not going to happen Joe, neg_one on the db id");
database_id = SessionUtils.getIntSession(session, SessionUtils.DATABASE_ID_KEY);
}
}
if (!foundOne && !action.equals(SessionUtils.CLEAR))
{
logger.error("Bad args*********\n channel: " + channel + ", content: " + content + ", database_id: " + database_id);
}
channel = SessionUtils.getIntSession(session, SessionUtils.CHANNEL_KEY);
// content = Utils.getIntSession(session, SessionUtils.CONTENT_KEY);
database_id = SessionUtils.getIntSession(session, SessionUtils.DATABASE_ID_KEY);
logger.debug("Get channel: " + channel);
logger.debug("Get content: " + content);
logger.debug("Get database_id: " + database_id);
JSONObject json_obj = new JSONObject();
try
{
json_obj.put(SessionUtils.CHANNEL_KEY, "" + channel);
json_obj.put(SessionUtils.CONTENT_KEY, "" + content);
// json_obj.put(SessionUtils.DATABASE_ID_KEY, "" + database_id);
}
catch (JSONException e)
{
logger.error("Json exception: " + e.getMessage());
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
finally
{
}
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(json_obj);
out.flush();
response.setStatus(HttpServletResponse.SC_OK);
return;
}
}
| true |
9b16d001c32a876dfb1536d2fea6c0c1038b13fb | Java | ZHANGyu352460702/No1 | /.svn/pristine/9b/9b16d001c32a876dfb1536d2fea6c0c1038b13fb.svn-base | UTF-8 | 1,532 | 2.21875 | 2 | [] | no_license | package products;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import session.HibernateSessionFactory;
public class ProductsService {
/*private SessionFactory factory;*/
private Session session;
private Transaction tx;
/*public void setFactory(SessionFactory factory) {
this.factory = factory;
}*/
public List queryProducts() {
this.session =HibernateSessionFactory.getSession();
Query query = session.createQuery("from Products");
List list = query.list();
return list;
}
public int count(String search) {
if(search==null){
search="";
}
this.session =HibernateSessionFactory.getSession();
Query query = session.createQuery("from Products where pname like ?");
query.setString(0, "%"+search+"%");
List list = query.list();
int count = list.size();
System.out.println(count);
return count;
}
public List queryFenye(String page,String current,String search) {
if(current==null){
current="0";
}
if(search==null){
search="";
}
int pageCount = Integer.valueOf(page);
int currentPage = Integer.valueOf(current)-1;
this.session =HibernateSessionFactory.getSession();
Query query=this.session.createQuery("from Products where pname like ?");
query.setString(0, "%"+search+"%");
query.setFirstResult(pageCount*currentPage);
query.setMaxResults(pageCount);
List list=query.list();
return list;
}
}
| true |
00c237f47ef000d6b2dd742ff19ebc856f70568d | Java | KnzHz/fpv_live | /src/main/java/com/dji/widget2/DJISwitch2.java | UTF-8 | 2,117 | 2.3125 | 2 | [] | no_license | package com.dji.widget2;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Switch;
public class DJISwitch2 extends Switch {
private static int STYLE_FPV = 1;
private static int STYLE_NORMAL = 0;
private float mStateAlpha = 0.3f;
private int mStyle = STYLE_NORMAL;
private View mView;
public DJISwitch2(Context context, AttributeSet attrs) {
super(context, attrs);
initWithStyle(context, attrs);
}
private void initWithStyle(Context context, AttributeSet attrs) {
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.DJISwitch2);
this.mStyle = attributes.getInt(R.styleable.DJISwitch2_switch_dji_style, this.mStyle);
attributes.recycle();
setMinWidth(context.getResources().getDimensionPixelSize(R.dimen.cirsw_width));
if (this.mStyle == STYLE_NORMAL) {
setTrackResource(R.drawable.cirsw_track);
setThumbResource(R.drawable.cirsw_thumb);
} else if (this.mStyle == STYLE_FPV) {
setTrackResource(R.drawable.cirsw_track_fpv);
setThumbResource(R.drawable.cirsw_thumb);
}
setTextOn("");
setTextOff("");
setThumbTextPadding(context.getResources().getDimensionPixelSize(R.dimen.cirsw_text_padding));
}
public void setRelativeStateView(View view) {
this.mView = view;
}
public void setRelativeStateView(View view, float stateAlpha) {
this.mView = view;
this.mStateAlpha = stateAlpha;
}
/* access modifiers changed from: protected */
public void drawableStateChanged() {
super.drawableStateChanged();
if (isFocused() || !isEnabled()) {
setAlpha(this.mStateAlpha);
if (this.mView != null) {
this.mView.setAlpha(this.mStateAlpha);
return;
}
return;
}
setAlpha(1.0f);
if (this.mView != null) {
this.mView.setAlpha(1.0f);
}
}
}
| true |
b15a1166aa50ff9f0f7304cf1bb6d80da84806a9 | Java | apache/flink | /flink-tests/src/test/java/org/apache/flink/test/util/DataSetUtilsITCase.java | UTF-8 | 10,284 | 2.09375 | 2 | [
"BSD-3-Clause",
"OFL-1.1",
"ISC",
"MIT",
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.test.util;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.Utils;
import org.apache.flink.api.java.summarize.BooleanColumnSummary;
import org.apache.flink.api.java.summarize.NumericColumnSummary;
import org.apache.flink.api.java.summarize.StringColumnSummary;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple8;
import org.apache.flink.api.java.utils.DataSetUtils;
import org.apache.flink.test.operators.util.CollectionDataSets;
import org.apache.flink.types.DoubleValue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** Integration tests for {@link DataSetUtils}. */
@RunWith(Parameterized.class)
public class DataSetUtilsITCase extends MultipleProgramsTestBase {
public DataSetUtilsITCase(TestExecutionMode mode) {
super(mode);
}
@Test
public void testCountElementsPerPartition() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
long expectedSize = 100L;
DataSet<Long> numbers = env.generateSequence(0, expectedSize - 1);
DataSet<Tuple2<Integer, Long>> ds = DataSetUtils.countElementsPerPartition(numbers);
Assert.assertEquals(env.getParallelism(), ds.count());
Assert.assertEquals(expectedSize, ds.sum(1).collect().get(0).f1.longValue());
}
@Test
public void testZipWithIndex() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
long expectedSize = 100L;
DataSet<Long> numbers = env.generateSequence(0, expectedSize - 1);
List<Tuple2<Long, Long>> result =
new ArrayList<>(DataSetUtils.zipWithIndex(numbers).collect());
Assert.assertEquals(expectedSize, result.size());
// sort result by created index
Collections.sort(
result,
new Comparator<Tuple2<Long, Long>>() {
@Override
public int compare(Tuple2<Long, Long> o1, Tuple2<Long, Long> o2) {
return o1.f0.compareTo(o2.f0);
}
});
// test if index is consecutive
for (int i = 0; i < expectedSize; i++) {
Assert.assertEquals(i, result.get(i).f0.longValue());
}
}
@Test
public void testZipWithUniqueId() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
long expectedSize = 100L;
DataSet<Long> numbers = env.generateSequence(1L, expectedSize);
DataSet<Long> ids =
DataSetUtils.zipWithUniqueId(numbers)
.map(
new MapFunction<Tuple2<Long, Long>, Long>() {
@Override
public Long map(Tuple2<Long, Long> value) throws Exception {
return value.f0;
}
});
Set<Long> result = new HashSet<>(ids.collect());
Assert.assertEquals(expectedSize, result.size());
}
@Test
public void testIntegerDataSetChecksumHashCode() throws Exception {
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Integer> ds = CollectionDataSets.getIntegerDataSet(env);
Utils.ChecksumHashCode checksum = DataSetUtils.checksumHashCode(ds);
Assert.assertEquals(checksum.getCount(), 15);
Assert.assertEquals(checksum.getChecksum(), 55);
}
@Test
public void testSummarize() throws Exception {
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
List<Tuple8<Short, Integer, Long, Float, Double, String, Boolean, DoubleValue>> data =
new ArrayList<>();
data.add(
new Tuple8<>(
(short) 1, 1, 100L, 0.1f, 1.012376, "hello", false, new DoubleValue(50.0)));
data.add(
new Tuple8<>(
(short) 2, 2, 1000L, 0.2f, 2.003453, "hello", true, new DoubleValue(50.0)));
data.add(
new Tuple8<>(
(short) 4,
10,
10000L,
0.2f,
75.00005,
"null",
true,
new DoubleValue(50.0)));
data.add(new Tuple8<>((short) 10, 4, 100L, 0.9f, 79.5, "", true, new DoubleValue(50.0)));
data.add(
new Tuple8<>(
(short) 5, 5, 1000L, 0.2f, 10.0000001, "a", false, new DoubleValue(50.0)));
data.add(
new Tuple8<>(
(short) 6,
6,
10L,
0.1f,
0.0000000000023,
"",
true,
new DoubleValue(100.0)));
data.add(
new Tuple8<>(
(short) 7,
7,
1L,
0.2f,
Double.POSITIVE_INFINITY,
"abcdefghijklmnop",
true,
new DoubleValue(100.0)));
data.add(
new Tuple8<>(
(short) 8,
8,
-100L,
0.001f,
Double.NaN,
"abcdefghi",
true,
new DoubleValue(100.0)));
Collections.shuffle(data);
DataSet<Tuple8<Short, Integer, Long, Float, Double, String, Boolean, DoubleValue>> ds =
env.fromCollection(data);
// call method under test
Tuple results = DataSetUtils.summarize(ds);
Assert.assertEquals(8, results.getArity());
NumericColumnSummary<Short> col0Summary = results.getField(0);
Assert.assertEquals(8, col0Summary.getNonMissingCount());
Assert.assertEquals(1, col0Summary.getMin().shortValue());
Assert.assertEquals(10, col0Summary.getMax().shortValue());
Assert.assertEquals(5.375, col0Summary.getMean().doubleValue(), 0.0);
NumericColumnSummary<Integer> col1Summary = results.getField(1);
Assert.assertEquals(1, col1Summary.getMin().intValue());
Assert.assertEquals(10, col1Summary.getMax().intValue());
Assert.assertEquals(5.375, col1Summary.getMean().doubleValue(), 0.0);
NumericColumnSummary<Long> col2Summary = results.getField(2);
Assert.assertEquals(-100L, col2Summary.getMin().longValue());
Assert.assertEquals(10000L, col2Summary.getMax().longValue());
NumericColumnSummary<Float> col3Summary = results.getField(3);
Assert.assertEquals(8, col3Summary.getTotalCount());
Assert.assertEquals(0.001000, col3Summary.getMin().doubleValue(), 0.0000001);
Assert.assertEquals(0.89999999, col3Summary.getMax().doubleValue(), 0.0000001);
Assert.assertEquals(
0.2376249988883501, col3Summary.getMean().doubleValue(), 0.000000000001);
Assert.assertEquals(
0.0768965488108089, col3Summary.getVariance().doubleValue(), 0.00000001);
Assert.assertEquals(
0.27730226975415995,
col3Summary.getStandardDeviation().doubleValue(),
0.000000000001);
NumericColumnSummary<Double> col4Summary = results.getField(4);
Assert.assertEquals(6, col4Summary.getNonMissingCount());
Assert.assertEquals(2, col4Summary.getMissingCount());
Assert.assertEquals(0.0000000000023, col4Summary.getMin().doubleValue(), 0.0);
Assert.assertEquals(79.5, col4Summary.getMax().doubleValue(), 0.000000000001);
StringColumnSummary col5Summary = results.getField(5);
Assert.assertEquals(8, col5Summary.getTotalCount());
Assert.assertEquals(0, col5Summary.getNullCount());
Assert.assertEquals(8, col5Summary.getNonNullCount());
Assert.assertEquals(2, col5Summary.getEmptyCount());
Assert.assertEquals(0, col5Summary.getMinLength().intValue());
Assert.assertEquals(16, col5Summary.getMaxLength().intValue());
Assert.assertEquals(5.0, col5Summary.getMeanLength().doubleValue(), 0.0001);
BooleanColumnSummary col6Summary = results.getField(6);
Assert.assertEquals(8, col6Summary.getTotalCount());
Assert.assertEquals(2, col6Summary.getFalseCount());
Assert.assertEquals(6, col6Summary.getTrueCount());
Assert.assertEquals(0, col6Summary.getNullCount());
NumericColumnSummary<Double> col7Summary = results.getField(7);
Assert.assertEquals(100.0, col7Summary.getMax().doubleValue(), 0.00001);
Assert.assertEquals(50.0, col7Summary.getMin().doubleValue(), 0.00001);
}
}
| true |
07bb34dc491f1b9bfb0481e81e6e373ecd033469 | Java | gumruyanzh/portal | /src/main/java/com/product/resources/ProductResource.java | UTF-8 | 1,396 | 2.109375 | 2 | [] | no_license | package com.product.resources;
import com.codahale.metrics.annotation.Timed;
import com.product.data.entity.Product;
import com.product.resources.model.ProductCreateModel;
import com.product.service.ProductService;
import com.product.service.dto.ProductCreateDto;
import com.product.service.dto.ProductSimpleDto;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Created by TCE\zhirayrg on 3/3/17.
*/
@Path("/products")
public class ProductResource {
private final ProductService productService;
public ProductResource(ProductService productService) {
this.productService = productService;
}
@GET
@Timed
@Produces(MediaType.APPLICATION_JSON)
public List<ProductSimpleDto> getProducts() {
return productService.findAll();
}
@POST
@Timed
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ProductSimpleDto createProduct(ProductCreateModel producModel) {
ProductCreateDto productCreateDto = new ProductCreateDto();
productCreateDto.setName(producModel.getName());
productCreateDto.setCategoryId(producModel.getCategoryId());
productCreateDto.setTagIds(Optional.ofNullable(producModel.getTagIds()));
return productService.create(productCreateDto);
}
}
| true |
9ed6d05e344816acff48ce69986241217faa15c7 | Java | aljacobs1021/Training-Projects | /HomeTour/src/game/RoomManager.java | UTF-8 | 5,791 | 3.0625 | 3 | [] | no_license | // CONTAINS: Room definitions, Room to exit assignments
// DOES: What kind of rooms exist
package src.game;
import src.fixtures.Room;
public class RoomManager {
Room startingRoom;
private Room rooms[] = new Room[8];
Room foy, kit, lib, lr, apoth, gar, bed, bath;
public void init() {
// specify deets
foy = new Room("The Foyer", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
kit = new Room("K", "a HUDGHDJ KITCHEN ",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
lib = new Room("L", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
lr = new Room("LR", "a smasdffer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
apoth = new Room("APOTH", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
gar = new Room("GAR", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
bed = new Room("bed", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
bath = new Room("BATH", "a small foyer",
"The small entryway of a neo-colonial house. A dining room is open to the south, where a large table can be seen."
+ "\n"
+ "The hardwood floor leads west into doorway, next to a staircase that leads up to a second floor."
+ "\n" + "To the north is a small room, where you can see a piano.");
// N = 0 E = 1 S = 2 W = 3
foy.setExits(lr, null, null, lib);
lr.setExits(gar, null, foy, kit);
gar.setExits(null, null, lr, null);
kit.setExits(bed, lr, lib, apoth);
bed.setExits(null, null, kit, bath);
bath.setExits(null, bed, null, null);
apoth.setExits(null, kit, null, null);
lib.setExits(kit, foy, null, null);
// add objects to startingRoom and Rooms
setSR(foy);
// create room objects
this.rooms[0] = foy;
this.rooms[1] = lr;
this.rooms[2] = gar;
this.rooms[3] = kit;
this.rooms[4] = bed;
this.rooms[5] = bath;
this.rooms[6] = apoth;
this.rooms[7] = lib;
}
public void setSR(Room startingRoom) {
this.startingRoom = startingRoom;
}
public Room getSR() {
return startingRoom;
}
public Room[] getRM() {
return rooms;
}
public void setRM(Room[] room) {
this.rooms = room;
}
}
| true |
6d62dca5ac93bab9255b31b2bdf398a0f66b98d6 | Java | abhi3047/javaCoding | /mooc-java-programming-i/part02-Part02_04.ComparingNumbers/src/main/java/ComparingNumbers.java | UTF-8 | 532 | 3.828125 | 4 | [] | no_license |
import java.util.Scanner;
public class ComparingNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int no1= Integer.valueOf(in.nextLine());
int no2=Integer.valueOf(in.nextLine());
if (no1> no2){
System.out.println(no1 + " is greater than "+no2 +".");
}else if(no1<no2){
System.out.println(no1 + " is smaller than "+no2 +".");
}else{
System.out.println(no1 + " is equal to "+no2 +".");
}
}
}
| true |
5dfad8ef9585f6a4eb705a284662bb9796c91cf7 | Java | AxesandGrinds/Hify-Old | /app/src/main/java/com/amsavarthan/hify/adapters/NotificationAdapter.java | UTF-8 | 3,707 | 2.046875 | 2 | [] | no_license | package com.amsavarthan.hify.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.amsavarthan.hify.R;
import com.amsavarthan.hify.models.Notification;
import com.amsavarthan.hify.ui.notification.NotificationActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by amsavarthan on 22/2/18.
*/
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder> {
private List<Notification> notificationList;
private Context context;
public NotificationAdapter(List<Notification> notificationList, Context context) {
this.notificationList = notificationList;
this.context = context;
}
@NonNull
@Override
public NotificationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_item_list,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final NotificationAdapter.ViewHolder holder, int position) {
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
holder.message.setText(notificationList.get(position).getMessage());
mFirestore.collection("Users").document(notificationList.get(position).getFrom()).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
final String name,image;
name=documentSnapshot.getString("name");
image=documentSnapshot.getString("image");
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.default_user_art_g_2))
.load(image)
.into(holder.image);
holder.from.setText(name);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(context, NotificationActivity.class);
intent.putExtra("from_id", notificationList.get(holder.getAdapterPosition()).getFrom());
intent.putExtra("message", notificationList.get(holder.getAdapterPosition()).getMessage());
intent.putExtra("image",image);
intent.putExtra("name",name);
context.startActivity(intent);
}
});
}
});
}
@Override
public int getItemCount() {
return notificationList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private CircleImageView image;
private TextView from,message;
public ViewHolder(View itemView) {
super(itemView);
mView=itemView;
image = mView.findViewById(R.id.image);
from = mView.findViewById(R.id.name);
message = mView.findViewById(R.id.message);
}
}
}
| true |
37ba39e4d89380cc71a8a42bac29371d4d4c02dc | Java | tramontaz/basePatterns | /src/behavioral/chain/EmailNotifier.java | UTF-8 | 274 | 2.78125 | 3 | [] | no_license | package behavioral.chain;
public class EmailNotifier extends Notifier {
EmailNotifier(int priority) {
super(priority);
}
@Override
public void write(String message) {
System.out.println("Notifying use email notifier: " + message);
}
}
| true |
2b7bae31fc7840006f8a6b2fb660c843d11bafbd | Java | zh735652914/java-training | /src/interview/Main.java | UTF-8 | 2,301 | 3.015625 | 3 | [] | no_license | package interview;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
char[][] matrix = new char[2][n];
for (int i = 0; i < 2; i++) {
String tmp = scanner.nextLine();
for (int j = 0; j < tmp.length(); j++) {
matrix[i][j] = tmp.charAt(j);
}
// System.out.println(tmp);
}
System.out.println(new Main().uniquePaths2(2, n, matrix));
}
// private int bacxktrack(char[][] matrix, int[][] dp,)
public int uniquePaths2(int m, int n, char[][] matrix) {
int[][] dp = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0) {
dp[j][i] = j == 0 ? 1 : 0;
} else {
if (matrix[j][i] == 'X') {
dp[j][i] = 0;
continue;
}
if (j == 0) {
dp[j][i] = dp[j][i - 1] + dp[j + 1][i - 1];
} else {
dp[j][i] = dp[j][i - 1] + dp[j - 1][i - 1];
}
// dp[j][i] = dp[j][i - 1] + j == 0 ? dp[j + 1][i - 1] : dp[j - 1][i - 1];
}
}
}
return dp[m - 1][n - 1] == 0 ? -1 : dp[m - 1][n - 1];
}
public int uniquePaths(int m, int n, char[][] matrix) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
dp[i][j] = 1;
} else if (matrix[i][j] == 'X') {
dp[i][j] = -1;
} else {
// if (i == 0)
if (j == 0) continue;
if (i == 0) {
dp[i][j] = dp[i][j - 1] + dp[i + 1][j - 1];
} else if (i == 1) {
dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1];
}
// dp[i][j] = dp[i - 1][j] + dp[i - 1][j + 1] + dp[i - 1][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
}
| true |
3fbd07a633b14998b51fbc6732edf7afca58ad85 | Java | jtransc/jtransc-examples | /stress/src/main/java/com/stress/sub1/sub1/sub8/Class3341.java | UTF-8 | 394 | 2.1875 | 2 | [] | no_license | package com.stress.sub1.sub1.sub8;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class3341 {
public static final String static_const_3341_0 = "Hi, my num is 3341 0";
static int static_field_3341_0;
int member_3341_0;
public void method3341()
{
System.out.println(static_const_3341_0);
}
public void method3341_1(int p0, String p1)
{
System.out.println(p1);
}
}
| true |
ad76703e3dd82a54a4e68ea689daaab071a1261b | Java | officialprosingh/RavenEarn | /app/src/main/java/online/propaans/ravenearn/ravenearn/SignActivity.java | UTF-8 | 4,594 | 2.203125 | 2 | [] | no_license | package online.propaans.ravenearn.ravenearn;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import rest.Constants;
public class SignActivity extends AppCompatActivity {
private EditText username_sign_up , password_sign_up ;
private Button login_signup_button , signup;
private ProgressBar signup_progress ;
private FirebaseAuth mAuth;
DatabaseReference amount_firebase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign);
mAuth = FirebaseAuth.getInstance();
amount_firebase = FirebaseDatabase.getInstance().getReference("Users");
username_sign_up = (EditText) findViewById(R.id.username_sign_up);
password_sign_up = (EditText) findViewById(R.id.password_sign_up);
signup_progress = (ProgressBar) findViewById(R.id.sign_up_progress);
login_signup_button = (Button) findViewById(R.id.login_sign_up);
login_signup_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignActivity.this, LoginActivity.class));
}
});
signup = (Button) findViewById(R.id.sign_up);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = username_sign_up.getText().toString().trim();
String password = password_sign_up.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
username_sign_up.setError("Please Enter a Valid Email");
username_sign_up.requestFocus();
return;
}
if (email.isEmpty()){
username_sign_up.setError("Email is Required");
username_sign_up.requestFocus();
return;
}
if (password.isEmpty()){
password_sign_up.setError("Password is Required");
password_sign_up.requestFocus();
return;
}
if (password.length()<6){
password_sign_up.setError("Maximum Length of Password Should be 6");
password_sign_up.requestFocus();
return;
}
signup_progress.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
signup_progress.setVisibility(View.GONE);
if (task.isSuccessful()){
String amount = Constants.amount ;
String id = amount_firebase.push().getKey();
amount_firebase.child(id).setValue(amount);
Intent intent = new Intent(SignActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
else {
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(getApplicationContext(), "Email is Already Registered ", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
});
}
}
| true |
165adb87613aafb5dda875206c72e65a4201aee0 | Java | robert0801/Java.EPAM | /src/Exception/main/Group.java | UTF-8 | 2,002 | 3.265625 | 3 | [] | no_license | package Exception.main;
import Exception.exception.*;
import java.util.ArrayList;
import java.util.Map;
public class Group extends Faculty{
private String nameGroup;
private ArrayList<Student> studentsInGroup;
private int sumOnSubjectInGroup = 0;
private int countMarkInGroup = 0;
private Subject subject;
public void addStudentInGroup(String nameGroup, ArrayList<Student> studentsInGroup) throws ExceptionClass {
if (studentsInGroup.isEmpty()) throw new ExceptionClass("В группе " + nameGroup + " нет студентов");
this.nameGroup = nameGroup;
this.studentsInGroup = studentsInGroup;
}
public double averageMarkOnSubjectInGroup(Subject subject) throws ExceptionClass {
if (studentsInGroup.isEmpty()) throw new ExceptionClass("В группе " + getNameGroup() + " нет студетов");
for (Student student : studentsInGroup){
for (Map.Entry<Subject, Integer> studentIterator : student.getRating().entrySet()){
if (studentIterator.getKey().equals(subject)){
this.sumOnSubjectInGroup += studentIterator.getValue();
this.countMarkInGroup++;
}
}
}
return (double)sumOnSubjectInGroup / countMarkInGroup;
}
public void printAverageMarkOnSubjectInGroup(Subject subject) throws ExceptionClass {
this.averageMarkOnSubjectInGroup(subject);
if (sumOnSubjectInGroup == 0) throw new ExceptionClass("В группе " + getNameGroup() + " нет учеников, изучающих " + subject);
else System.out.println("В группе " + getNameGroup() + " по предмету " + subject +
" средний балл " + (double) sumOnSubjectInGroup / countMarkInGroup);
}
public String getNameGroup() {
return nameGroup;
}
public ArrayList<Student> getStudentsInGroup() {
return studentsInGroup;
}
}
| true |
3dd053161f34fa80ead0ebd782ef6ff8c3c00c6c | Java | weiyien/security_jwt | /src/main/java/top/coolidea/security/demo/controller/BaseController.java | UTF-8 | 3,666 | 2.5 | 2 | [] | no_license | package top.coolidea.security.demo.controller;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import top.coolidea.security.demo.common.RedisUtils;
import top.coolidea.security.demo.error.CommonStatusCode;
import top.coolidea.security.demo.error.ErrorCodeException;
import top.coolidea.security.demo.result.ResultDTO;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* @author: 魏薏恩
* @date: 2019/3/5 11:47
* @description:
*/
public class BaseController {
@Autowired
RedisUtils redisUtils;
@Autowired
private HttpServletRequest request;
private static final String SERIALVERSIONUID = "serialVersionUID";
/**
* 获取token中携带的用户名信息
*
* @return 用户名字符串
*/
protected String getLoginUserName() {
return request.getAttribute("username").toString();
}
/**
* 获取token中携带的用户id信息
*
* @return 用户id
*/
protected int getLoginUserId() {
return Integer.parseInt(request.getAttribute("userid").toString());
}
/**
* 获取请求中带的appId
*
* @return appId
*/
protected Integer getCurrentRequestAppId() {
Integer appId = Integer.parseInt(request.getParameter("appid"));
if (appId <= 0) {
return null;
}
return appId;
}
/**
* 增删改结果返回
*
* @param result 数据库操作结果
* @return 通用返回类型
*/
protected ResultDTO judgeResult(int result) {
if (result > 0) {
return ResultDTO.successed(result);
}
return ResultDTO.failed(CommonStatusCode.NO_DATA);
}
/**
* 检查是否通过jsr303参数验证
*
* @param bindingResult jsr303验证结果
*/
protected void validParam(BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
List<FieldError> ls = bindingResult.getFieldErrors();
List<Object> errorMsg = new ArrayList<>();
ls.stream().forEach(objectError -> errorMsg.add(objectError.getField() + "[" + objectError.getDefaultMessage() + "]"));
throw new ErrorCodeException(CommonStatusCode.REQUEST_ERROR, this.getClass(), errorMsg);
}
}
/**
* 检查传入对象的值是否都为空
*
* @param object
*/
protected void validParamObject(Object object) {
if (checkObjectAllFieldsIsNull(object)) {
List<Object> extraMessage = new ArrayList<>();
extraMessage.add(object.toString());
throw new ErrorCodeException(CommonStatusCode.REQUEST_ERROR, this.getClass(), extraMessage);
}
}
/**
* 检查传入的对象属性是否全为空
*
* @param object 需要检查对象
* @return 检查结果
*/
protected boolean checkObjectAllFieldsIsNull(Object object) {
if (null == object) {
return true;
}
try {
for (Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(object) != null && !StrUtil.isEmptyIfStr(field.get(object).toString()) && !field.getName().equals(SERIALVERSIONUID)) {
return false;
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
}
| true |
254af858752fc17d2669054b5b2fdd1c2985ac6a | Java | vampirelxz/huoxuanProject | /webui-service/src/main/java/com/lxz/webui/controller/AccountController.java | UTF-8 | 6,721 | 2.171875 | 2 | [] | no_license | package com.lxz.webui.controller;/****************************************************
* 创建人: @author liuxuanzhi
* 创建时间: 2021/3/9/17:04
* 项目名称: HXAssistant
* 文件名称: com.lxz.webui.controller
* 文件描述: @Description: 账簿控制层
*
* All rights Reserved, Designed By 投资交易团队
* @Copyright:2016-2021
*
********************************************************/
import com.alibaba.fastjson.JSONArray;
import com.lxz.webui.consumer.api.feign.GatewayFeign;
import com.lxz.webui.entity.AccountBO;
import com.lxz.webui.entity.AccountMonthVO;
import com.lxz.webui.entity.AccountWeekVO;
import com.lxz.webui.entity.Data1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
/**
* 包名称: com.lxz.webui.controller
* 类名称:AccountController
* 类描述:账簿控制层
* 创建人:@author liuxuanzhi
* 创建时间:2021/3/9/17:04
*/
@Controller
public class AccountController {
@Autowired
UtilController utilController;
@Autowired
RestTemplate restTemplate;
@Autowired
GatewayFeign gatewayFeign;
@PostMapping("/insertSelfAccount")
@ResponseBody
public String insertSelfAccount(@RequestParam("createId") String createId,@RequestParam("type") String type,@RequestParam("time") String time,@RequestParam("remark") String remark,@RequestParam("money") String money,@RequestParam("token") String token){
try{
gatewayFeign.insertSelfAccount(createId, type, time, remark, money, token);
}catch (Exception e){
e.printStackTrace();
return "login.html";
}
return null;
}
@GetMapping("/account")
public String listAccount(@RequestParam("createId") int createId, Model model,@RequestParam("token") String token){
if (createId == 0) {
return null;
}
List<AccountBO> accountBOS;
try {
System.out.println("出错");
accountBOS = gatewayFeign.listAccount(createId, token);
}catch (Exception e){
e.printStackTrace();
return null;
}
model.addAttribute("account", accountBOS);
System.out.println(model.getAttribute("account"));
return "stock/account::account";
}
@GetMapping("/deleteAccount")
@ResponseBody
public void delete(@RequestParam("id") int id,@RequestParam("token") String token){
gatewayFeign.deleteAccount(id,token);
}
@GetMapping("/getMonthModel")
public String getMonthModel(@RequestParam("createId") int createId,Model model,@RequestParam("token") String token){
AccountMonthVO accountMonthVOS = gatewayFeign.getMonthModel(createId, token);
model.addAttribute("accordion", accountMonthVOS);
System.out.println(model.getAttribute("accordion"));
return "stock/account::accordion";
}
@GetMapping("/getWeekModel")
@ResponseBody
public String getWeekModel(int createId,Model model,@RequestParam("token") String token){
List<AccountWeekVO> accountWeekVOS = gatewayFeign.getWeekModel(createId, token);
String s="[{\"name\":\"暂无数据\",\"value\":1.0},{\"name\":\"暂无数据\",\"value\":1.0},{\"name\":\"暂无数据\",\"value\":1.0},{\"name\":\"暂无数据\",\"value\":1.0}]";
try {
List<Data1> data1s = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Data1 data1 = new Data1();
if (accountWeekVOS.get(i) != null) {
data1.setName(accountWeekVOS.get(i).getType());
data1.setValue(accountWeekVOS.get(i).getTypeAll());
data1s.add(data1);
}
}
s = JSONArray.toJSONString(data1s);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(s);
return s;
}
@GetMapping("/getThisWeekData")
@ResponseBody
public String getThisWeekData(@RequestParam("createId") int createId,@RequestParam("token") String token){
String[] thisWeekData = gatewayFeign.getThisWeekData(createId, token);
String body = JSONArray.toJSONString(thisWeekData);
System.out.println(body);
return body;
}
@GetMapping("/getLastWeekData")
@ResponseBody
public String getLastWeekData(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getLastWeekData(createId, token));
return body;
}
@GetMapping("/getThisMonthData")
@ResponseBody
public String getThisMonthData(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getThisMonthData(createId, token));
return body;
}
@GetMapping("/getLastMonthData")
@ResponseBody
public String getLastMonthData(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getLastMonthData(createId, token));
return body;
}
@GetMapping("/getMonthTypePie")
@ResponseBody
public String getMonthTypePie(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getMonthTypePie(createId, token));
return body;
}
@GetMapping("/getMonthValuePie")
@ResponseBody
public String getMonthValuePie(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getMonthValuePie(createId, token));
return body;
}
@GetMapping("/getYearTypePie")
@ResponseBody
public String getYearTypePie(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getYearTypePie(createId, token));
return body;
}
@GetMapping("/getYearValuePie")
@ResponseBody
public String getYearValuePie(@RequestParam("createId") int createId,@RequestParam("token") String token){
String body = JSONArray.toJSONString(gatewayFeign.getYearValuePie(createId, token));
return body;
}
}
| true |
23f24ef746ecb8d2803468ba635ea5726ce03c2f | Java | mbatchkarov/Plovdiv | /src/main/java/view/SimulationParametersPanel.java | UTF-8 | 12,380 | 2.296875 | 2 | [
"BSD-3-Clause"
] | 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 view;
import java.awt.event.ItemEvent;
import javax.swing.*;
import model.SimulationDynamics;
/**
* @author miroslavbatchkarov
*/
public class SimulationParametersPanel extends javax.swing.JPanel {
private Display d;
private double[] advancedRates;
private AdvancedSimulationSettingsFrame advancedSettingsFrame;
/**
* Creates new form SimulationParametersPanel
*/
public SimulationParametersPanel(Display d) {
this.d = d;
advancedRates = new double[9];
advancedSettingsFrame = new AdvancedSimulationSettingsFrame(this);
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
gamaLabel = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
more = new javax.swing.JButton();
transmissionRate = new javax.swing.JTextField();
recoveryRate = new javax.swing.JTextField();
timeStep = new javax.swing.JTextField();
dynamics = new javax.swing.JComboBox();
ok = new javax.swing.JButton();
jLabel1.setText("Dynamics");
jLabel2.setText("Transmission rate");
gamaLabel.setText("Recovery rate");
jLabel4.setText("Time step");
more.setText("More...");
more.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moreActionPerformed(evt);
}
});
transmissionRate.setText("2.0");
transmissionRate.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
transmissionRateKeyReleased(evt);
}
});
recoveryRate.setText("1.0");
recoveryRate.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
recoveryRateKeyReleased(evt);
}
});
timeStep.setText("0.1");
timeStep.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
timeStepKeyReleased(evt);
}
});
dynamics.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"SI", "SIS", "SIR"}));
dynamics.setSelectedIndex(1);
dynamics.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
dynamicsItemStateChanged(evt);
}
});
dynamics.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
dynamicsItemStateChanged(evt);
}
});
dynamics.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dynamicsActionPerformed(evt);
}
});
ok.setText("Apply");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(gamaLabel)
.addComponent(jLabel4)
.addComponent(more, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(timeStep, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(recoveryRate, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(transmissionRate, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(dynamics, javax.swing.GroupLayout.Alignment.LEADING, 0, 72, Short.MAX_VALUE))
.addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dynamics, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(transmissionRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(gamaLabel)
.addComponent(recoveryRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(timeStep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(more)
.addComponent(ok))
.addGap(0, 0, 0))
);
}// </editor-fold>//GEN-END:initComponents
private void dynamicsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_dynamicsItemStateChanged
JComboBox source = (JComboBox) evt.getItemSelectable();
if (evt.getStateChange() == ItemEvent.SELECTED) {
if (source.getSelectedItem().toString().equals("SI")) {
recoveryRate.setEnabled(false);
}
else{
recoveryRate.setEnabled(true);
}
parseSimulationParameters();
}
}//GEN-LAST:event_dynamicsItemStateChanged
public void storeAdvancedParams(double[] params) {
this.advancedRates = params;
}
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
parseSimulationParameters();
}//GEN-LAST:event_okActionPerformed
private void moreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moreActionPerformed
advancedSettingsFrame.setVisible(true);
}//GEN-LAST:event_moreActionPerformed
private void transmissionRateKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_transmissionRateKeyReleased
UIUtils.parseDoubleOrColourComponentOnError((javax.swing.JTextField) evt.getSource());
}//GEN-LAST:event_transmissionRateKeyReleased
private void recoveryRateKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_recoveryRateKeyReleased
UIUtils.parseDoubleOrColourComponentOnError((javax.swing.JTextField) evt.getSource());
}//GEN-LAST:event_recoveryRateKeyReleased
private void timeStepKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_timeStepKeyReleased
UIUtils.parseDoubleOrColourComponentOnError((javax.swing.JTextField) evt.getSource());
}//GEN-LAST:event_timeStepKeyReleased
private void dynamicsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dynamicsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_dynamicsActionPerformed
public void parseSimulationParameters() {
//check the current state of the fields
//parse the contents of the text field that should be active (based on the combos)
//and attach them to the graph as a Dynamics object
//attach the dynamics setting to the graph
try {
double transmissionRateVal = Double.parseDouble(transmissionRate.getText());
double recoveryRateVal = Double.parseDouble(recoveryRate.getText());
double timeStepVal = Double.parseDouble(timeStep.getText());
SimulationDynamics.DynamicsType type;
if (dynamics.getSelectedItem().toString().equals("SIR")) {
type = SimulationDynamics.DynamicsType.SIR;
} else if (dynamics.getSelectedItem().toString().equals("SIS")) {
type = SimulationDynamics.DynamicsType.SIS;
} else {
type = SimulationDynamics.DynamicsType.SI;
}
SimulationDynamics res = new SimulationDynamics(type,
transmissionRateVal,
recoveryRateVal,
timeStepVal,
advancedRates[0],
advancedRates[1],
advancedRates[2],
advancedRates[3],
advancedRates[4],
advancedRates[5],
advancedRates[6],
advancedRates[7],
advancedRates[8]
);
d.updateSimulationParameters(res);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid value entered");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox dynamics;
private javax.swing.JLabel gamaLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JButton more;
private javax.swing.JButton ok;
private javax.swing.JTextField recoveryRate;
private javax.swing.JTextField timeStep;
private javax.swing.JTextField transmissionRate;
// End of variables declaration//GEN-END:variables
}
| true |
88311b8146f662f7a056b6d509dd23f4d2295310 | Java | fcolling/back2back | /core/src/test/java/org/ogerardin/b2b/config/BackupSourceRepositoryTest.java | UTF-8 | 1,893 | 2.046875 | 2 | [] | no_license | package org.ogerardin.b2b.config;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ogerardin.b2b.domain.BackupSource;
import org.ogerardin.b2b.domain.FilesystemSource;
import org.ogerardin.b2b.domain.mongorepository.BackupSourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@DataMongoTest
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class BackupSourceRepositoryTest {
private static final String FILESET_RSC = "/fileset";
@Autowired
BackupSourceRepository backupSourceRepository;
@Test
public void test() throws URISyntaxException, IOException, InterruptedException {
backupSourceRepository.deleteAll();
List<BackupSource> sources = new ArrayList<>();
{
URL url = getClass().getResource(FILESET_RSC);
Path dir = Paths.get(url.toURI());
FilesystemSource fileSource = new FilesystemSource(dir);
sources.add(fileSource);
}
// sources.add(new FilesystemSource("C:\\Users\\oge\\Downloads"));
sources.forEach(s -> backupSourceRepository.insert(s));
List<BackupSource> fetchedSources = backupSourceRepository.findAll();
Assert.assertThat(fetchedSources, Matchers.equalTo(sources));
// Thread.sleep(100000);
}
} | true |
2ccbf68184c1b82d80753f0959c448febcc791d1 | Java | teaganstewart/chips-challenge-group-project | /src/nz/ac/vuw/ecs/swen225/a3/maze/Skeleton.java | UTF-8 | 1,240 | 3.03125 | 3 | [] | no_license | package nz.ac.vuw.ecs.swen225.a3.maze;
import javax.json.Json;
import javax.json.JsonObject;
import nz.ac.vuw.ecs.swen225.a3.persistence.Saveable;
/**
* A class that provides where skeletons are able to move and allows them
* to be saved.
*
* @author Teagan Stewart - 300407769
*
*/
public class Skeleton extends Moveable implements Saveable {
/**
* The constructor for a Skeleton object.
*
* @param coordinate Coordinate skeleton spawns at.
* @param start The direction skeleton moves in at start.
*/
public Skeleton(Coordinate coordinate, Direction start) {
super(coordinate);
super.setDirection(start);
}
@Override
public boolean canWalkOn(Entity entity) {
if (entity == null)
return true;
if(entity instanceof Key || entity instanceof Treasure ||
entity instanceof FireBoots || entity instanceof IceBoots)
return true;
return false;
}
/**
* Serialise a skeleton object to json object for the purpose of saving.
* @return Json object skeleton.
*/
@Override
public JsonObject toJSON() {
JsonObject jsonObject = Json.createObjectBuilder()
.add("coordinate", getCoordinate().toJSON())
.add("direction", getDirection().toString())
.build();
return jsonObject;
}
} | true |
718e3b4704da7d97f790a957258c6adfa6fd6aca | Java | trandaiduong1990/CACISISS_PADSS | /src/org/transinfo/cacis/action/batchprocess/SearchCardBatchAction.java | UTF-8 | 4,928 | 1.976563 | 2 | [] | no_license | package org.transinfo.cacis.action.batchprocess;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.transinfo.cacis.TPlusException;
import org.transinfo.cacis.action.BaseAction;
import org.transinfo.cacis.controller.batchprocess.CardBatchManager;
import org.transinfo.cacis.controller.settings.EMVProfileManager;
import org.transinfo.cacis.dto.batchprocess.InstantCardDto;
import org.transinfo.cacis.dto.batchprocess.SearchInstantCardDto;
import org.transinfo.cacis.dto.settings.EMVProfileSearchDto;
import org.transinfo.cacis.formbean.batchprocess.CardBatchSearchForm;
import org.transinfo.cacis.formbean.settings.EMVProfileSearchForm;
import org.transinfo.cacis.util.DateUtil;
public class SearchCardBatchAction extends BaseAction {
private Logger logger = Logger.getLogger(SearchCardBatchAction.class);
@SuppressWarnings("deprecation")
@Override
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException, TPlusException, Exception {
int pageNo = 0;
if (request.getParameter("mode") != null
&& ((String) request.getParameter("mode")).equals("NEXT")) {
if (request.getParameter("pageNo") != null) {
pageNo = Integer.parseInt((String) request
.getParameter("pageNo")) + 1;
}
}
if (request.getParameter("mode") != null
&& ((String) request.getParameter("mode")).equals("PREV")) {
if (request.getParameter("pageNo") != null) {
pageNo = Integer.parseInt((String) request
.getParameter("pageNo")) - 1;
}
}
CardBatchSearchForm objForm = (CardBatchSearchForm) form;
ActionErrors errors = objForm.validate(mapping, request);
if (request.getParameter("back") != null
&& request.getParameter("back").equals("true"))
objForm.setBatchName(null);
if (errors != null && !errors.isEmpty()) {
saveErrors(request, errors);
return mapping.getInputForward();
}
boolean hasFromDate = objForm.getFromDate() != null
&& objForm.getFromDate() != "";
boolean hasToDate = objForm.getToDate() != null
&& objForm.getToDate() != "";
if (hasFromDate || hasToDate) {
errors.add("Error", new ActionError("cardBatch.invalidFromDate"));
Date from = DateUtil.convertDateStringToDate(objForm.getFromDate());
Date to = DateUtil.convertDateStringToDate(objForm.getToDate());
if ((hasFromDate && from == null) || (hasToDate && to == null)
|| (from != null && to != null && from.compareTo(to) == 1)) {
errors = new ActionErrors();
if (hasFromDate && from == null)
errors.add("Error", new ActionError(
"cardBatch.invalidFromDate"));
if (hasToDate && to == null)
errors.add("Error", new ActionError(
"cardBatch.invalidToDate"));
if (from != null && to != null && from.compareTo(to) == 1)
errors.add("Error", new ActionError(
"cardBatch.fromGreaterThanTo"));
saveErrors(request, errors);
return mapping.getInputForward();
}
}
// Dto Creation
SearchInstantCardDto objDto = new SearchInstantCardDto();
try {
BeanUtils.copyProperties(objDto, objForm);
objDto.setScreenType(mapping.getParameter().equals("add") ? "='N' "
: mapping.getParameter().equals("auth") ? "in ('N','A') "
: "in ('P','A')");
objDto.setIssuerId((String) request.getSession(false).getAttribute(
"ISSUER"));
if(request.getParameter("showList")!=null){
objDto.setBatchName(null);
objForm.setBatchName(null);
}
} catch (Exception e) {
logger.error(e);
System.out
.println("Error converting to form bean in SearchCardBatchAction execute method: "
+ e.getMessage());
throw new TPlusException(
"Error converting to form bean in SearchCardBatchAction execute method: "
+ e);
}
// Action Execution
CardBatchManager objManager = new CardBatchManager();
Collection cardBatch = objManager.search(objDto, pageNo);
objForm.setTotal(objDto.getTotal());
boolean chkShowTotalRecs = (objForm.getBatchName() == "" || objForm
.getBatchName() == null)
&& (objForm.getFromDate() == "" || objForm.getFromDate() == null)
&& (objForm.getToDate() == "" || objForm.getToDate() == null);
// Success
request.setAttribute("SEARCHLIST", cardBatch);
if (!chkShowTotalRecs)
request.setAttribute("CHKTOTALRECS", "1");
request.setAttribute("PAGENO", new Integer(pageNo).toString());
return mapping.findForward("success");
}
}
| true |
a34ff3651e494e353ecb15f64da68e0813b95cb7 | Java | UniTime/unitime | /JavaSource/org/unitime/timetable/dataexchange/DataExchangeIntegrationHelper.java | UTF-8 | 4,154 | 2.015625 | 2 | [
"Apache-2.0",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"CC-BY-3.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-freemarker",
"LGPL-2.1-only",
"EPL-1.0",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-generic-cla",
... | permissive | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.dataexchange;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.logging.Log;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.util.queue.QueueMessage;
/**
* @author Tomas Muller
*/
@Service("dataExchangeHelper")
public class DataExchangeIntegrationHelper {
public Document file2document(File file) throws DocumentException {
return new SAXReader().read(file);
}
public String exception2message(Exception exception) throws IOException {
StringWriter out = new StringWriter();
exception.printStackTrace(new PrintWriter(out));
out.flush(); out.close();
return out.toString();
}
public String importDocument(Document document) throws Exception {
final StringBuffer log = new StringBuffer("<html><header><title>XML Import Log</title></header><body>\n");
Log logger = new Log() {
protected void log(QueueMessage.Level level, Object message, Throwable t) {
log.append(new QueueMessage(level, message, t).toHTML() + "<br>\n");
}
@Override
public void warn(Object message, Throwable t) {
log(QueueMessage.Level.WARN, message, t);
}
@Override
public void warn(Object message) {
log(QueueMessage.Level.WARN, message, null);
}
@Override
public void trace(Object message, Throwable t) {
log(QueueMessage.Level.TRACE, message, t);
}
@Override
public void trace(Object message) {
log(QueueMessage.Level.TRACE, message, null);
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isFatalEnabled() {
return true;
}
@Override
public boolean isErrorEnabled() {
return true;
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public void info(Object message, Throwable t) {
log(QueueMessage.Level.INFO, message, t);
}
@Override
public void info(Object message) {
log(QueueMessage.Level.INFO, message, null);
}
@Override
public void fatal(Object message, Throwable t) {
log(QueueMessage.Level.FATAL, message, t);
}
@Override
public void fatal(Object message) {
log(QueueMessage.Level.FATAL, message, null);
}
@Override
public void error(Object message, Throwable t) {
log(QueueMessage.Level.ERROR, message, t);
}
@Override
public void error(Object message) {
log(QueueMessage.Level.ERROR, message, null);
}
@Override
public void debug(Object message, Throwable t) {
log(QueueMessage.Level.DEBUG, message, t);
}
@Override
public void debug(Object message) {
log(QueueMessage.Level.DEBUG, message, null);
}
};
String manager = document.getRootElement().attributeValue("manager", ApplicationProperty.DataExchangeXmlManager.value());
DataExchangeHelper.importDocument(document, manager, logger);
log.append("</body></html>");
return log.toString();
}
}
| true |
6f21b5a2be43ca54dc4472f5fdd651dabf477ac3 | Java | matthew-sturgill/AndroidToDoList | /app/src/main/java/mattsturgill/tdl10/ToDoActivity.java | UTF-8 | 7,403 | 2.21875 | 2 | [] | no_license | package mattsturgill.tdl10;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
/**
* Created by matthewsturgill on 10/27/16.
*/
public class ToDoActivity extends AppCompatActivity {
private ListView tdList;
private ToDoArrayAdapter tdArrayAdapter;
private ArrayList<ToDoItem> tdArray;
private SharedPreferences tdPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
tdPrefs = getPreferences(Context.MODE_PRIVATE);
setupItem();
Collections.sort(tdArray);
tdList = (ListView) findViewById(R.id.listView);
tdArrayAdapter = new ToDoArrayAdapter(this, R.layout.list_item_to_do, tdArray);
tdList.setAdapter(tdArrayAdapter);
tdList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// if the element is clicked create the intent
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ToDoItem item = tdArray.get(position);
Intent intent = new Intent(ToDoActivity.this, ToDoDetailActivity.class);
intent.putExtra("Title", item.getTitle());
intent.putExtra("Text", item.getText());
// intent.putExtra("Category", item.getCategory());
intent.putExtra("Index", position);
startActivityForResult(intent, 1);
}
});
tdList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//what to do if the view gets a long click
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(ToDoActivity.this);
alertBuilder.setTitle("Delete");
alertBuilder.setMessage("Are you sure?");
alertBuilder.setNegativeButton("Cancel", null);
alertBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem note = tdArray.get(position);
deleteFile("##" + note.getTitle());
tdArray.remove(position);
tdArrayAdapter.updateAdapter(tdArray);
}
});
alertBuilder.create().show();
return true;
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
int index = data.getIntExtra("Index", -1);
ToDoItem item = new ToDoItem (data.getStringExtra("Title"),
data.getStringExtra("Text"), new Date());
if (index == -1) {
tdArray.add(item);
} else {
ToDoItem oldItem = tdArray.get(index);
tdArray.set(index, item);
// writeFile(note);
if (!oldItem.getTitle().equals(item.getTitle())) {
File oldFile = new File(this.getFilesDir(), "##" + oldItem.getTitle());
File newFile = new File(this.getFilesDir(), "##" + item.getTitle());
oldFile.renameTo(newFile);
}
}
Collections.sort(tdArray);
tdArrayAdapter.updateAdapter(tdArray);
}
}
private void setupItem() {
tdArray = new ArrayList<>();
if (tdPrefs.getBoolean("firstRun", true)) {
SharedPreferences.Editor editor = tdPrefs.edit();
editor.putBoolean("firstRun", false);
editor.apply();
ToDoItem item1 = new ToDoItem("Item 1", "", new Date());
tdArray.add(item1);
tdArray.add(new ToDoItem("Item 2", "", new Date()));
tdArray.add(new ToDoItem("Item 3", "", new Date()));
for (ToDoItem item : tdArray) {
writeFile(item);
}
} else {
File[] filesDir = this.getFilesDir().listFiles();
for (File file : filesDir) {
FileInputStream inputStream = null;
String title = file.getName();
if (!title.startsWith("##")) {
continue;
} else {
title = title.substring(2, title.length());
}
Date date = new Date(file.lastModified());
String text = "";
try {
inputStream = openFileInput("##" + title);
byte[] input = new byte[inputStream.available()];
while (inputStream.read(input) != -1) {
}
text += new String(input);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
tdArray.add(new ToDoItem(title, text, date));
}
}
}
private void writeFile(ToDoItem item) {
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput("##" + item.getTitle(), Context.MODE_PRIVATE);
outputStream.write(item.getText().getBytes());
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException ioe) {
} catch (NullPointerException npe) {
} catch (Exception e) {
}
}
}
//menu
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_to_do, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(ToDoActivity.this, ToDoDetailActivity.class);
intent.putExtra("Title", "");
intent.putExtra("Text", "");
startActivityForResult(intent, 1);
return true;
}
return super.onOptionsItemSelected(item);
}
} | true |
2a84a924ee70d282eb21bc572d32ce81f20cc902 | Java | hxj1225/websimplejava | /src/main/java/com/hxj/websimplejava/concurrent/jobconcurrency/JobExecutor.java | WINDOWS-1252 | 2,818 | 2.734375 | 3 | [] | no_license | package com.hxj.websimplejava.concurrent.jobconcurrency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class JobExecutor {
private ExecutorService executorService;
@Deprecated
Map<String, Future<JobResult>> resultMap = new HashMap<String, Future<JobResult>>();
Set<Job> jobSet = new HashSet<>();
public JobExecutor(int threadSize){
if (executorService == null) executorService = Executors.newFixedThreadPool(threadSize);
}
public JobExecutor(ExecutorService executorService){
this.executorService = executorService;
}
public void addJob(Job job) {
jobSet.add(job);
}
public Map<String, JobResult> executeJob() {
Map<String, JobResult> executeResult = new HashMap<>();
for (Job job : jobSet) {
Future<JobResult> future = executorService.submit(job);
JobResult jobResult = new JobResult();
try {
if (job.getTimeout() > 0) {
jobResult = future.get(job.getTimeout(), TimeUnit.MILLISECONDS);
} else {
jobResult = future.get();
}
} catch (TimeoutException e) {
// ʱ
jobResult.setJobStatus(JobStatus.TIMEOUT);
jobResult.setMessage("timeout");
} catch (InterruptedException | ExecutionException e1) {
// 쳣
jobResult.setJobStatus(JobStatus.FAILED);
jobResult.setMessage(e1.getMessage());
}
executeResult.put(job.getName(), jobResult);
}
jobSet.clear();
return executeResult;
}
public void destory() {
if (executorService != null) {
executorService.shutdown();
executorService = null;
}
}
@Deprecated
public void putJob(Job job) {
resultMap.put(job.getName(), executorService.submit(job));
}
@Deprecated
public Map<String, JobResult> getExecuteResult() {
Map<String, JobResult> executeResult = new HashMap<>();
for (Map.Entry<String, Future<JobResult>> entry : resultMap.entrySet()) {
try {
executeResult.put(entry.getKey(), entry.getValue().get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
resultMap.clear();
return executeResult;
}
}
| true |
631ef837f70268245fb60447f0e30266cfa28ef0 | Java | jmanuel34/11_formacion | /src/main/java/dto/DtoCurso.java | UTF-8 | 1,019 | 2.40625 | 2 | [] | no_license | package dto;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
public class DtoCurso {
private int idCurso;
@Temporal(TemporalType.DATE)
private Date fechaInicio;
private int duracion;
private String nombre;
public DtoCurso() {
super();
}
public DtoCurso(int idCurso, Date fechaInicio, int duracion, String nombre) {
super();
this.idCurso = idCurso;
this.fechaInicio = fechaInicio;
this.duracion = duracion;
this.nombre = nombre;
}
public int getIdCurso() {
return idCurso;
}
public void setIdCurso(int idCurso) {
this.idCurso = idCurso;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public int getDuracion() {
return duracion;
}
public void setDuracion(int duracion) {
this.duracion = duracion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| true |
6cc3a38f20d99e9695ac28a99bcfec9130281b2c | Java | MorganHolmes/Java-Gym | /src/Gym/Member.java | UTF-8 | 1,032 | 3.34375 | 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 Gym;
/**
*
* @author Morgan
*/
public class Member extends Person {
//Attributes
private int weight;
private double height;
private GymGoal goal;
//Constructors
public Member(String forename, String surname, int age, int weight, double height, GymGoal goal){
super(forename, surname, age);
this.weight = weight;
this.height = height;
this.goal = goal;
}
//Methods
public int getWeight(){
return weight;
}
public double getHeight(){
return height;
}
public GymGoal getGoal(){
return goal;
}
public void setWeight(int weight){
this.weight = weight;
}
public String toString(){
return super.toString() + "\nWeight: " + weight + "\nHeight: " + height + "\nGym Goal: " + goal;
}
}
| true |
efbb903ae1c6b3cbf457da2e1da0164f90c5ad24 | Java | cpberryman/BigJava4thEditionExerciseSolutions | /src/Chapter_6_Iteration/P6_1.java | UTF-8 | 795 | 3.8125 | 4 | [] | no_license | package Chapter_6_Iteration;
import java.util.Scanner;
/**
* Solution to exercise P6.1
*
* @author ChrisBerryman
*/
public class P6_1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter temperatures: ");
double highestValue = in.nextDouble();
int highestMonth = 1;
for (int currentMonth = 2; currentMonth <= 12; currentMonth++) {
double nextValue = in.nextDouble();
if (nextValue > highestValue) {
highestValue = nextValue;
highestMonth = currentMonth;
}
}
System.out.println("Month with highest temperature: " + highestMonth);
}
}
| true |
29efe61205c3e3c589e0507eb1998efb4c745add | Java | markovartur/OOP-Labs | /lab2/src/com/company/Point2d.java | UTF-8 | 1,380 | 3.375 | 3 | [] | no_license | package com.company;
public class Point2d {
/** координата X **/
private double xCoord;
/** координата Y **/
private double yCoord;
/** Конструктор инициализации **/
public Point2d ( double x, double y) {
xCoord = x;
yCoord = y;
}
/** Конструктор по умолчанию. **/
public Point2d () {
//Вызовите конструктор с двумя параметрами и определите источник.
this(0, 0);
}
/** Возвращение координаты X **/
public double getX () {return xCoord;}
/** Возвращение координаты Y **/
public double getY () { return yCoord; }
/** Установка значения координаты X. **/
public void setX ( double val) { xCoord = val; }
/** Установка значения координаты Y. **/
public void setY ( double val) { yCoord = val; }
public double distanceTo(Point2d point) {
//return Math.round(Math.abs((point.xCoord - xCoord)+(point.yCoord - yCoord)));
return Math.round(Math.sqrt(Math.pow(point.getX() - getX(), 2)+Math.pow(point.getY() - getY(), 2)));
}
///////////////////////////////
void print(){
System.out.println("{x="+xCoord+ ", {y="+yCoord);
}
}
| true |
6661267f2d560e8af2d25b91e13163b82e0193c6 | Java | liweihai12345/hotel-api | /src/main/java/com/platform/mapper/BlackListMapper.java | UTF-8 | 581 | 1.835938 | 2 | [] | no_license | package com.platform.mapper;
import com.platform.entity.BlackListDO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BlackListMapper extends BaseDao<BlackListDO> {
int check(@Param("myuid") Long myuid, @Param("uid") Long uid);
List<BlackListDO> selectList(@Param("uid") Long userId, @Param("start") Integer start, @Param("size") Integer size);
int delete(@Param("myuid") Long myuid, @Param("uid") Long uid);
List<Long> selectBlackMeIds(@Param("uid") Long uid);
List<Long> selectMyBlackList(@Param("uid") Long uid);
}
| true |
677d732a4a52d1a68e379a03b486e41ca8e0e701 | Java | mpgrantham/myabcdata | /src/main/java/com/canalbrewing/myabcdata/model/User.java | UTF-8 | 2,703 | 2.203125 | 2 | [] | no_license | package com.canalbrewing.myabcdata.model;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class User {
public static final String STATUS_ACTIVE = "ACTIVE";
public static final String STATUS_PENDING = "PENDING";
private int id;
private String userNm;
private String password;
private String email;
private byte[] salt;
private byte[] encryptedPassword;
private String startPage;
private String status;
private String sessionKey;
private String staySignedInKey;
private List<Observed> observed = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserNm() {
return userNm;
}
public void setUserNm(String userNm) {
this.userNm = userNm;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public byte[] getSalt() {
return salt;
}
public void setSalt(byte[] salt) {
this.salt = salt;
}
public byte[] getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(byte[] encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getStartPage() {
return startPage;
}
public void setStartPage(String startPage) {
this.startPage = startPage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
public String getStaySignedInKey() {
return staySignedInKey;
}
public void setStaySignedInKey(String staySignedInKey) {
this.staySignedInKey = staySignedInKey;
}
@Override
public String toString() {
return "User [email=" + email + ", encryptedPassword=" + Arrays.toString(encryptedPassword) + ", id=" + id
+ ", password=" + password + ", status=" + status + ", salt=" + Arrays.toString(salt) + ", sessionKey="
+ sessionKey + ", startPage=" + startPage + ", userNm=" + userNm + "]";
}
public List<Observed> getObserved() {
return observed;
}
public void setObserved(List<Observed> observed) {
this.observed = observed;
}
} | true |
ac4f59e2944f3c5f01828f6e2cd676c1255263e3 | Java | mjapon/smartfact | /src/smf/sv/print/gui/ListaImpresorasFrame.java | UTF-8 | 9,241 | 1.914063 | 2 | [] | no_license | /* */ package smf.sv.print.gui;
/* */
/* */ import smf.sv.print.util.Ctes;
/* */ import smf.sv.print.util.CtesImpresoras;
/* */ import java.awt.BorderLayout;
/* */ import java.awt.Component;
/* */ import java.awt.Dimension;
/* */ import java.awt.FlowLayout;
/* */ import java.awt.Font;
/* */ import java.awt.GridLayout;
/* */ import java.awt.Toolkit;
/* */ import java.awt.event.ActionEvent;
/* */ import java.awt.event.ActionListener;
/* */ import java.io.PrintStream;
/* */ import java.util.ArrayList;
/* */ import java.util.HashMap;
/* */ import java.util.List;
/* */ import java.util.Map;
/* */ import java.util.Map.Entry;
/* */ import java.util.Set;
/* */ import javax.swing.ImageIcon;
/* */ import javax.swing.JButton;
/* */ import javax.swing.JComboBox;
/* */ import javax.swing.JFrame;
/* */ import javax.swing.JLabel;
/* */ import javax.swing.JOptionPane;
/* */ import javax.swing.JPanel;
/* */
/* */
/* */ public class ListaImpresorasFrame
/* */ extends JFrame
/* */ {
/* */ private JComboBox<String> impresorasCmbox;
/* */ private JPanel mainPanel;
/* */ private JButton guardarBtn;
/* */ private JButton cerrarBtn;
/* */ private List<String> impresorasIsyplus;
/* */ private List<String> impresorasRegistrarIsyplus;
/* */ private Map<String, String> impresorasActualizarLocal;
/* */
/* */ public ListaImpresorasFrame( List<String> impresorasIsyplus)
/* */ {
/* 46 */ this.impresorasIsyplus = new ArrayList();
/* */
/* 48 */ this.impresorasRegistrarIsyplus = new ArrayList();
/* 49 */ this.impresorasActualizarLocal = new HashMap();
/* */
/* 51 */ this.impresorasIsyplus.add("0;Registrar nuevo");
/* 52 */ this.impresorasIsyplus.addAll(impresorasIsyplus);
/* 53 */ init();
/* */ }
/* */
/* */ public JComboBox<String> getNewJComboBox(String codigoImpresoraIsyplus)
/* */ {
/* 58 */ System.out.println("getNewJComboBox------>" + (codigoImpresoraIsyplus != null ? codigoImpresoraIsyplus : "null"));
/* */
/* 60 */ this.impresorasCmbox = new JComboBox();
/* 61 */ Ctes.LOAD_JCOMBO_BOX(this.impresorasCmbox, this.impresorasIsyplus);
/* */
/* 63 */ Integer index = Integer.valueOf(0);
/* */
/* 65 */ if (codigoImpresoraIsyplus != null) {
/* 66 */ for (String printerIsyplus : this.impresorasIsyplus) {
/* 67 */ System.out.println("--->Printer isyplus:" + printerIsyplus);
/* 68 */ String[] codname = printerIsyplus.split(";");
/* 69 */ String cod = codname[0];
/* 70 */ if (cod.equalsIgnoreCase(codigoImpresoraIsyplus)) {
/* 71 */ index = Integer.valueOf(this.impresorasIsyplus.indexOf(printerIsyplus));
/* */ }
/* */ }
/* */ }
/* */
/* 76 */ this.impresorasCmbox.setSelectedIndex(index.intValue() >= 0 ? index.intValue() : 0);
/* 77 */ return this.impresorasCmbox;
/* */ }
/* */
/* */ public void doGuardar() {
/* 81 */ this.impresorasRegistrarIsyplus = new ArrayList();
/* 82 */ this.impresorasActualizarLocal = new HashMap();
/* */
/* */
/* 85 */ Component[] componets = this.mainPanel.getComponents();
/* 86 */ JLabel lastLabel = null;
/* 87 */ Component[] arrayOfComponent1; int j = (arrayOfComponent1 = componets).length; for (int i = 0; i < j; i++) { Component component = arrayOfComponent1[i];
/* 88 */ System.out.println("Iterando por components ---->, class es:" + component.getClass().toString());
/* 89 */ if ((component instanceof JLabel)) {
/* 90 */ lastLabel = (JLabel)component;
/* 91 */ System.out.println("Last label text est:" + lastLabel.getText());
/* */ }
/* */
/* 94 */ if ((component instanceof JComboBox)) {
/* 95 */ System.out.println("Component instance of jcombobox");
/* 96 */ JComboBox<String> jcombo = (JComboBox)component;
/* 97 */ String item = String.valueOf(jcombo.getSelectedItem());
/* 98 */ if ("0;Registrar nuevo".equalsIgnoreCase(item)) {
/* 99 */ if (lastLabel != null) {
/* 100 */ String auxImp = lastLabel.getText();
/* 101 */ this.impresorasRegistrarIsyplus.add(auxImp);
/* 102 */ System.out.println("Se agrega nueva impresora ha listado de nuevo para registro:" + auxImp);
/* */ }
/* */
/* */ }
/* 106 */ else if (lastLabel != null) {
/* 107 */ String[] partes = item.split(";");
/* 108 */ String cod_impresora = partes[0];
/* 109 */ String nom_impresora = lastLabel.getText();
/* 110 */ this.impresorasActualizarLocal.put(cod_impresora, nom_impresora);
/* 111 */ System.out.println("Se agrega nueva impresora ha mapa para actualizar en local cod_impresora:" + cod_impresora + ", impresora:" + nom_impresora);
/* */ }
/* */ }
/* */ }
/* */
/* */
/* 117 */ System.out.println("Valor para impresoras actualizar local es:" + this.impresorasActualizarLocal.entrySet().size());
/* */
/* 119 */ CtesImpresoras.CHECK_FILE_EXIST();
/* 120 */ for (Map.Entry<String, String> e : this.impresorasActualizarLocal.entrySet()) {
/* 121 */ CtesImpresoras.SET_PROPERTY_VALUE((String)e.getKey(), (String)e.getValue());
/* */ }
/* */
/* 124 */ System.out.println("Longitud cadena de impresoras registrar isyplus es:" + this.impresorasRegistrarIsyplus.size());
/* */
/* 126 */ StringBuffer impresorasGuardarBuffer = new StringBuffer();
/* 127 */ for (String printer : this.impresorasRegistrarIsyplus) {
/* 128 */ impresorasGuardarBuffer.append(printer);
/* 129 */ impresorasGuardarBuffer.append(";");
/* */ }
/* */
/* 132 */ String impresorasGuardar = impresorasGuardarBuffer.toString();
/* 133 */ if (impresorasGuardarBuffer.length() > 0) {
/* 134 */ impresorasGuardar = impresorasGuardarBuffer.substring(0, impresorasGuardarBuffer.length() - 1);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* 142 */ String webSoccetMessage = "SAVEPRINT<>" + impresorasGuardar;
/* */
/* 145 */ JOptionPane.showMessageDialog(null, "Los cambios han sido registrados");
/* 146 */ setVisible(false);
/* */ }
/* */
/* */ public void init() {
/* 150 */ setLayout(new BorderLayout());
/* 151 */ setFont(new Font("Arial", 0, 12));
/* 152 */ setTitle("Isyplus: Configurar impresoras ISYPLUS");
/* 153 */ setSize(700, 400);
/* 154 */ setIconImage(new ImageIcon(Ctes.RUTA_ICONO_SYS, "omt").getImage());
/* */
/* 156 */ List<String> impresorasList = Ctes.GET_LISTA_IMPRESORAS();
/* 157 */ int numFilas = impresorasList.size();
/* */
/* 159 */ this.impresorasCmbox = new JComboBox();
/* 160 */ this.mainPanel = new JPanel(new GridLayout(numFilas, 2));
/* */
/* 162 */ for (String impresora : impresorasList) {
/* 163 */ this.mainPanel.add(new JLabel(impresora));
/* */
/* */
/* */
/* 167 */ String codigoImpresoraProp = CtesImpresoras.GET_PRINTER_COD(impresora);
/* */
/* 169 */ System.out.println("Se busca impresora:" + impresora + " en impresoras.properties");
/* 170 */ System.out.println("Valor en impresoras.properties es:" + (codigoImpresoraProp != null ? codigoImpresoraProp : "null"));
/* */
/* */
/* 173 */ JComboBox<String> comboImpresorasIsyplus = getNewJComboBox(codigoImpresoraProp);
/* */
/* 175 */ this.mainPanel.add(comboImpresorasIsyplus);
/* */ }
/* */
/* 178 */ add(this.mainPanel, "Center");
/* */
/* 180 */ this.guardarBtn = new JButton("Guardar");
/* 181 */ this.cerrarBtn = new JButton("Cerrar");
/* 182 */ this.guardarBtn.addActionListener(new ActionListener() {
/* */ public void actionPerformed(ActionEvent e) {
/* 184 */ ListaImpresorasFrame.this.doGuardar();
/* */ }
/* */
/* 187 */ });
/* 188 */ final JFrame thisframe = this;
/* 189 */ this.cerrarBtn.addActionListener(new ActionListener() {
/* */ public void actionPerformed(ActionEvent e) {
/* 191 */ thisframe.setVisible(false);
/* */ }
/* */
/* 194 */ });
/* 195 */ JPanel southPanel = new JPanel(new FlowLayout());
/* 196 */ southPanel.add(this.guardarBtn);
/* 197 */ southPanel.add(this.cerrarBtn);
/* 198 */ add(southPanel, "South");
/* */
/* 200 */ Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
/* 201 */ setLocation(dim.width / 2 - getSize().width / 2, dim.height / 2 - getSize().height / 2);
/* */ }
/* */ }
/* Location: /Users/mjapon/Documents/jarisyplusprint/IsyplusPrint/jar/printws.jar!/com/serviestudios/print/gui/ListaImpresorasFrame.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ | true |
80462a07b360139a4c16f2ef1f66b010afc7c1bb | Java | Fdgonzalez/ecomerce-api | /user-service/src/main/java/com/cloud/ecomerce/user/controller/UserController.java | UTF-8 | 5,019 | 2.390625 | 2 | [] | no_license | package com.cloud.ecomerce.user.controller;
import com.cloud.ecomerce.user.model.RoleName;
import com.cloud.ecomerce.user.model.User;
import com.cloud.ecomerce.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@EnableResourceServer
@RestController
public class UserController extends ResourceServerConfigurerAdapter {
@Autowired
UserRepository userRepository;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private static final String ROLE_ADMIN = "ROLE_ADMIN";
private static final String ROLE_USER = "ROLE_USER";
/**
* Get a user by its username
* @param username the username to look up
* @return an optional of User
*/
@Secured({ROLE_ADMIN})
@GetMapping("/name/{name}")
public Optional<User> getUserByUsername(@PathVariable(value = "name") String username){
return userRepository.findByUsername(username);
}
@Secured({ROLE_ADMIN})
@GetMapping("/all")
public List<User> getAllUsers(){
return userRepository.findAll();
}
/**
* Register a user on the database
* JSON Example:
* {"username":"USERNAME","password":"PASSWORD","name":"name","lastname":"lastname","email":"test@TESTEST.com"}
* @param user a user object
* @return ok (200) if successful badRequest if the user already exists (no overwrite)
*/
@PostMapping("/")
public ResponseEntity<?> createUser(@Valid @RequestBody User user){
if(!userRepository.findByUsername(user.getUsername()).isPresent()) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
userRepository.setRole(user.getId(), RoleName.ROLE_USER.ordinal()+1);
return ResponseEntity.ok().build();
}
else
return ResponseEntity.badRequest().build();
}
@GetMapping("/mail/{name}")
public String getUserEmail(@PathVariable(name = "name") String name){
Optional<User> user = userRepository.findByUsername(name);
if(user.isPresent()){
return user.get().getEmail();
}
return("NOTFOUND");
}
@Secured({ROLE_ADMIN})
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable(value = "id") int id){
Optional<User> user = userRepository.findById(id);
if(user.isPresent()){
userRepository.delete(user.get());
return ResponseEntity.ok().build();
}else{
return ResponseEntity.notFound().build();
}
}
@PostMapping("/{id}")
public ResponseEntity<?> updateUser(@PathVariable(name = "id") int id ,@Valid @RequestBody User user){
Optional<User> existingUser = userRepository.findById(id);
if(existingUser.isPresent()){
userRepository.deleteById(id);
User newUser = existingUser.get();
newUser.setEmail(user.getEmail());
newUser.setLastName(user.getLastName());
newUser.setName(user.getName());
newUser.setPassword(user.getPassword());
newUser.setUsername(user.getUsername());
userRepository.save(newUser);
}
return ResponseEntity.notFound().build();
}
/**
* Promote user to admin (add ROLE_ADMIN authority)
* @param username the user to be promoted's name
* @return notFound if the user was not found in the database, badRequest if the user is already an admin,
* ok if the operation was successful
*/
@Secured({ROLE_ADMIN})
@PostMapping("/makeAdmin/{user}")
public ResponseEntity<?> makeAdmin(@PathVariable(value = "user") String username){
Optional<User> user = userRepository.findByUsername(username);
if(!user.isPresent())
return ResponseEntity.notFound().build();
if(user.get().getRoles().stream().anyMatch(role -> role.getName().equals(RoleName.ROLE_ADMIN)))
return ResponseEntity.badRequest().build();
userRepository.setRole(user.get().getId(),RoleName.ROLE_ADMIN.ordinal()+1);
return ResponseEntity.ok().build();
}
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/register","/actuator/","/actuator/**","/v2/api-docs").permitAll()
.anyRequest().authenticated();
}
}
| true |
347cac7cccbcf2ca280d6c5e57f1d547c6874b71 | Java | pavel-pereguda/WicketCookBook | /1605_10_code_final/recipe1007/src/main/java/cookbook/HomePage.java | UTF-8 | 469 | 2.28125 | 2 | [] | no_license | package cookbook;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.PropertyModel;
public class HomePage extends WebPage {
private int counter = 0;
public HomePage() {
add(new Label("counter", new PropertyModel<Integer>(this, "counter")));
add(new Link<Void>("increment") {
public void onClick() {
counter++;
}
});
}
}
| true |
748e54fcdfb31381a77446cb00c68e1171d3d516 | Java | germinateplatform/germinate | /src/jhi/germinate/client/util/event/GroupCreationEvent.java | UTF-8 | 1,954 | 2.203125 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
* Copyright 2017 Information and Computational Sciences,
* The James Hutton Institute.
*
* 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 jhi.germinate.client.util.event;
import com.google.gwt.event.shared.*;
import jhi.germinate.client.util.*;
/**
* A {@link GroupCreationEvent} indicates that the user navigated to a new page.
*
* @author Sebastian Raubach
*/
public class GroupCreationEvent extends GwtEvent<GroupCreationEvent.GroupCreationEventHandler>
{
/**
* {@link GroupCreationEventHandler} is the {@link EventHandler} of {@link LogoutEvent}
*/
public interface GroupCreationEventHandler extends EventHandler
{
/**
* Called when a {@link LogoutEvent} has been fired
*
* @param event The {@link LogoutEvent}
*/
void onGroupCreated(GroupCreationEvent event);
}
public static final Type<GroupCreationEventHandler> TYPE = new Type<>();
private MarkedItemList.ItemType type;
private Long id;
/**
* Creates a new instance of {@link LogoutEvent}
*/
public GroupCreationEvent(MarkedItemList.ItemType type, Long id)
{
this.type = type;
this.id = id;
}
public MarkedItemList.ItemType getType()
{
return type;
}
public Long getId()
{
return id;
}
@Override
public Type<GroupCreationEventHandler> getAssociatedType()
{
return TYPE;
}
@Override
protected void dispatch(GroupCreationEventHandler handler)
{
handler.onGroupCreated(this);
}
}
| true |
27262396c6466dfa3e8e99ebf62d4f714295ce3a | Java | prajwalmw/Notification | /app/src/main/java/com/example/applicationfundamentals/App.java | UTF-8 | 1,145 | 2.546875 | 3 | [] | no_license | package com.example.applicationfundamentals;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
/**
* Created By: Prajwal Waingankar on 03-Jul-21
* Github: prajwalmw
* Email: prajwalwaingankar@gmail.com
*/
public class App extends Application {
public static final String CHANNEL_ID_1 = "channel_1";
public static final String CHANNEL_ID_2 = "channel_2";
@Override
public void onCreate() {
super.onCreate();
//Creating notification Channel...
createNotifiChannel();
}
private void createNotifiChannel() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Step 1...
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//Step 2...
NotificationChannel notificationChannel_1 = new NotificationChannel(
CHANNEL_ID_1, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel_1);
//notification channel is created...
}
}
}
| true |
5cb1eded025d40a41cded41ae5c9d81ecc9f4922 | Java | paing123/tiktopgym_managementsystem | /tiktopgymmanagement/src/main/java/com/tiktop/controller/PackageController.java | UTF-8 | 3,719 | 2.28125 | 2 | [] | no_license | package com.tiktop.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.tiktop.model.Package;
import com.tiktop.services.PackageService;
@Controller
public class PackageController {
@Autowired
private PackageService packageService;
@InitBinder
private void InitBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
@RequestMapping(value = {"/admin/package" }, method = RequestMethod.GET)
public String pack(Model model) {
Package pack = new Package();
model.addAttribute("pack", pack);
return "admin/package";
}
@RequestMapping(value = { "/admin/addPackage" }, method = RequestMethod.GET)
public String showPackagePage(Model model) {
Package pack = new Package();
model.addAttribute("pack", pack);
return "admin/addPackage";
}
@RequestMapping(value = { "/admin/addPackage" }, method = RequestMethod.POST)
public String savePackage(@Valid @ModelAttribute("pack") Package pack, BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
return "admin/addPackage";
}
packageService.save(pack);
Package pk = new Package();
List<Package> packs = packageService.findPackage(pk);
model.addAttribute("packs", packs);
model.addAttribute("pack",pk);
model.addAttribute("success","success");
return "admin/package";
}
@RequestMapping(value = { "/admin/searchPackage" }, method = RequestMethod.POST)
public String SearchPackage(@ModelAttribute("pack") Package pack, Model model) {
List<Package> packs = packageService.findPackage(pack);
model.addAttribute("packs", packs);
return "admin/package";
}
@GetMapping("/admin/deletePackage/{id}")
public ModelAndView deletePackage(@ModelAttribute("id") Integer id) {
Package pack = new Package();
ModelAndView mav = new ModelAndView("admin/package");
List<Package> packs = packageService.findPackage(pack);
mav.addObject("packs",packs);
mav.addObject("pack",pack);
try {
packageService.delete(id);
return mav;
} catch (Exception e) {
mav.addObject("error","error");
return mav;
}
}
@GetMapping("/admin/updatePackage/{id}")
public ModelAndView showUpdatePackageForm(@ModelAttribute("id") int id) {
Package pack = new Package();
pack.setPackageId(id);
List<Package> pack1 = packageService.findPackage(pack);
pack.setPackageName(pack1.get(0).getPackageName());
pack.setPackageDuration(pack1.get(0).getPackageDuration());
pack.setPackageFees(pack1.get(0).getPackageFees());
ModelAndView mav = new ModelAndView("admin/updatePackage");
mav.addObject("pack", pack);
return mav;
}
@RequestMapping(value = "/admin/updatePackage", method = RequestMethod.POST)
public ModelAndView UpdatePackage(@ModelAttribute("pack") Package pack) {
packageService.update(pack);
ModelAndView mav = new ModelAndView("admin/package");
Package pk = new Package();
List<Package> packs = packageService.findPackage(pk);
mav.addObject("packs", packs);
mav.addObject("pack",pk);
return mav;
}
}
| true |
38f10d751dda8c508ba91aa600c765bbdfd792f9 | Java | lam1998t/BT_Tuan2 | /tuan2/cau_2/src/Main.java | UTF-8 | 250 | 2.453125 | 2 | [] | no_license | public class Main {
public static void main(String[] args){
Fraction f1 = new Fraction(8, 3);
Fraction f2 = new Fraction(5, 13);
f1.add(f2);
f1.subtract(f2);
f1.multiply(f2);
f1.divide(f2);
}
}
| true |
1be4fc4a87a843f39803bec6034da51c0b793590 | Java | erolsafauzun/CarRentalSystem | /src/main/java/com/eroluzun/carrentalsystem/api/CharValController.java | UTF-8 | 1,753 | 2.28125 | 2 | [] | no_license | package com.eroluzun.carrentalsystem.api;
import com.eroluzun.carrentalsystem.dto.GnlCharValDto;
import com.eroluzun.carrentalsystem.service.impl.CharValServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/gnlcharval")
public class CharValController {
private CharValServiceImpl charValServiceImpl;
public CharValController(CharValServiceImpl charValServiceImpl){
this.charValServiceImpl = charValServiceImpl;
}
@GetMapping("/{gnlCharValId}")
public ResponseEntity<GnlCharValDto> getByGnlCharValId (@PathVariable(value = "gnlCharValId",required = true) Long gnlCharValId){
GnlCharValDto gnlCharValDto = charValServiceImpl.getByGnlCharValId(gnlCharValId);
return new ResponseEntity<>(gnlCharValDto, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<GnlCharValDto> createGnlCharVal(@Valid @RequestBody GnlCharValDto gnlCharVal){
return ResponseEntity.ok(charValServiceImpl.save(gnlCharVal));
}
@PutMapping("/{gnlCharValId}")
public ResponseEntity<GnlCharValDto> updateGnlCharVal (@PathVariable(value = "gnlCharValId",required = true) Long gnlCharValId,
@Valid @RequestBody GnlCharValDto gnlCharVal){
return ResponseEntity.ok(charValServiceImpl.update(gnlCharValId, gnlCharVal));
}
@DeleteMapping("/{gnlCharValId}")
public ResponseEntity<Boolean> delete (@PathVariable(value = "gnlCharValId",required = true) Long gnlCharValId){
return ResponseEntity.ok(charValServiceImpl.delete(gnlCharValId));
}
}
| true |
ad321af24ae64f07df046f1d7bb635542896a9e6 | Java | ScheduleAppTeam/ScheduleProjectApp | /ScheduleProjectApp/src/main/java/com/example/scheduleprojectapp/LoginActivity.java | UTF-8 | 6,501 | 2.359375 | 2 | [] | no_license | package com.example.scheduleprojectapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.concurrent.ExecutionException;
import static com.example.scheduleprojectapp.NecessaryFunctions.isOnline;
@SuppressWarnings("ALL")
public class LoginActivity extends Activity {
private SigninActivity mt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public Object onRetainNonConfigurationInstance() {
return mt;
}
public void RegistrationButtonClick(View v)
{
if (isOnline(getApplicationContext())){
Intent intent = new Intent(getApplicationContext(), RegistrationActivity.class);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Нет интернет соединения", Toast.LENGTH_LONG).show();
}
}
public Boolean FieldsNonEmpty(String email, String password){
return ((!(email.isEmpty())) && (!(password.isEmpty())));
}
public void LoginButtonClick(View v){
final EditText EmailET;
EmailET = (EditText)findViewById(R.id.EmailET);
final EditText PasswordET;
PasswordET = (EditText)findViewById(R.id.PasswordET);
final String email = EmailET.getText().toString();
final String password = PasswordET.getText().toString();
if (FieldsNonEmpty(email, password)){
mt = (SigninActivity)getLastNonConfigurationInstance();
if (mt == null) {
new SigninActivity(this).execute(email, password);
}
}
else{
Toast.makeText(this.getApplicationContext(), "Введите данные", Toast.LENGTH_LONG).show();
}
}
public class SigninActivity extends AsyncTask<String,Integer,String>{
private ProgressDialog pd;
private Activity activity;
private String login;
public SigninActivity(Activity _activity) {
activity = _activity;
}
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... arg0) {
try{
login = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://uppdemonstration.comoj.com/login.php";
String data = URLEncoder.encode("login", "UTF-8")
+ "=" + URLEncoder.encode(login, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String(Constants.NO_INTERNET_CONNECTION);
}
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result){
if (result.equals(Constants.AUTHORIZATION_ACCEPTED)){
UserInfoGettingTask ugt = new UserInfoGettingTask(activity);
ugt.execute(login);
String responseResult = null;
try {
responseResult = ugt.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String [] resultArray = responseResult.split(" ");
UserTableDataBaseHelper db = new UserTableDataBaseHelper(activity.getApplicationContext());
User user = new User(Constants.DEFAULT_USER_APP_ID, login, resultArray[0], resultArray[1], Integer.valueOf(resultArray[2]), Constants.DEFAULT_USER_PERMISSION);
db.dropDB();
db.addUser(user);
Toast.makeText(activity.getApplicationContext(), "Авторизация пройдена", Toast.LENGTH_LONG).show();
Intent in = new Intent(activity.getApplicationContext(), ScheduleRefreshService.class);
startService(in);
Intent i = new Intent(activity.getApplicationContext(), ScheduleLoginService.class);
startService(i);
Intent intent = new Intent(getApplicationContext(), ScheduleActivity.class);
startActivity(intent);
finish();
}else if (result.equals(Constants.INCORRECT_PASSWORD)){
Toast.makeText(activity.getApplicationContext(), "Неправильный пароль", Toast.LENGTH_LONG).show();
}else if (result.equals(Constants.INCORRECT_ALL)){
Toast.makeText(activity.getApplicationContext(), "Неправильный пароль и логин", Toast.LENGTH_LONG).show();
}else if (result.equals(Constants.NO_INTERNET_CONNECTION)){
Toast.makeText(activity.getApplicationContext(), "Отсутствует интернет соединение", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(activity.getApplicationContext(), "Что-то пошло не по-плану", Toast.LENGTH_LONG).show();
}
}
}
} | true |
dacd12e3fee3d368582c047052af8424d2ddd666 | Java | xongxong/kcvs | /web/src/main/java/com/kcvs/service/impl/VehStatusMonitorServiceImpl.java | UTF-8 | 1,827 | 2.359375 | 2 | [] | no_license | package com.kcvs.service.impl;
import com.kcvs.service.VehStatusMonitorService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
@Transactional
public class VehStatusMonitorServiceImpl implements VehStatusMonitorService {
private String vehNo;
private String ipAddress;
private int portNo;
private boolean serviceLife = true;
private Thread worker = null;
private Logger logger = LogManager.getLogger();
public VehStatusMonitorServiceImpl() {
}
public VehStatusMonitorServiceImpl(String vehNo, String ipAddress, int portNo) {
this.vehNo = vehNo;
this.ipAddress = ipAddress;
this.portNo = portNo;
}
public void setVehNo(String vehNo) {
this.vehNo = vehNo;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setPortNo(int portNo) {
this.portNo = portNo;
}
@Override
public void startService() {
serviceLife = true;
if (worker == null) {
worker = new Thread(new Service());
worker.start();
}
}
@Override
public void stopService() {
serviceLife = false;
if (worker != null) {
try {
worker.join();
worker = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class Service implements Runnable {
boolean invokeEnable=false;
@Override
public void run() {
while (serviceLife) {
logger.debug("VehStatusMonitorService" + System.currentTimeMillis());
}
}
}
}
| true |
2fd10926b4262b7074e7209bcc063d3703be3af8 | Java | Neffes1987/masterHelper2 | /app/src/main/java/com/masterhelper/global/db/repositories/common/contracts/GeneralColumn.java | UTF-8 | 1,639 | 2.671875 | 3 | [] | no_license | package com.masterhelper.global.db.repositories.common.contracts;
import com.masterhelper.global.db.repositories.utils.ContractsUtilities;
public class GeneralColumn {
private String columnTitle;
private void setColumnTitle(String columnTitle) { this.columnTitle = columnTitle; }
public String getColumnTitle() { return columnTitle; }
private String columnType;
private void setColumnType(String columnType) { this.columnType = columnType; }
public String getColumnType() { return columnType; }
private int length;
private void setLength(int length) { this.length = length; }
public int getLength() { return length; }
private String tableName;
private void setTableName(String tableName) { this.tableName = tableName; }
public String getTableName() { return tableName; }
public GeneralColumn(String tableName, String columnTitle, ColumnTypes columnType, int length, boolean isNull ){
setColumnTitle(columnTitle);
setTableName(tableName);
setLength(length);
switch (columnType){
case CharType:
setColumnType(ContractsUtilities.charProp(columnTitle, length, isNull));
break;
case TextTypes:
setColumnType(ContractsUtilities.textProp(columnTitle, isNull));
break;
case Integer:
setColumnType(ContractsUtilities.intProp(columnTitle, isNull));
break;
case Primary:
setColumnType(ContractsUtilities.PrimaryProp(columnTitle, length));
break;
default: throw new Error("wrong content type");
}
}
public enum ColumnTypes {
Preview,
Primary,
CharType,
TextTypes,
Integer
}
}
| true |
9829f8d07f7052047fb4453fb817a74835bf4fd1 | Java | sharlamov/dev | /Store/src/main/java/net/club/model/Goods.java | UTF-8 | 845 | 2.15625 | 2 | [] | no_license | package net.club.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "db_goods")
public class Goods extends AbstractModel {
private static final long serialVersionUID = 8393451241387195740L;
@Column
String code;
@Column
String name;
@Column
Double priceIn;
@Column
Double priceOut;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPriceIn() {
return priceIn;
}
public void setPriceIn(Double priceIn) {
this.priceIn = priceIn;
}
public Double getPriceOut() {
return priceOut;
}
public void setPriceOut(Double priceOut) {
this.priceOut = priceOut;
}
} | true |
e0367b125c4eec623656fba0b794806a81df3351 | Java | yashodeepv/moneytransferservice | /src/main/java/com/yasho/config/Routes.java | UTF-8 | 791 | 2.171875 | 2 | [] | no_license | package com.yasho.config;
import com.yasho.controller.AccountController;
import io.undertow.Handlers;
import io.undertow.server.RoutingHandler;
import io.undertow.util.Methods;
public class Routes {
private AccountController accountController;
public Routes(AccountController accountController) {
this.accountController = accountController;
}
public RoutingHandler getRoutes() {
return Handlers.routing()
.add(Methods.GET, "/accounts", accountController::getAllAccounts)
.add(Methods.GET, "/accounts/{accountid}", accountController::getAccount)
.add(Methods.POST, "/accounts", accountController::saveAccount)
.add(Methods.POST, "/accounts/transfer", accountController::transfer);
}
}
| true |
5f3fa7804b5f626a272f3723ead1ed6a60d1a8e0 | Java | ChanWooP/ChanWooP | /01JavaSE/javase_20190304/src/com/test024/Score.java | UTF-8 | 852 | 2.8125 | 3 | [] | no_license | package com.test024;
public class Score {
//구성항목 : 학번 과목1 과목2 과목3
//자료형 : 학번은 String / 과목1,2,3 int
//샘플자료 :
//"S001", 100, 100, 100
//"S002", 100, 100, 100
private String stuNum;
private String name;
private int sub1, sub2, sub3;
public String getStuNum() {
return stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
public int getSub1() {
return sub1;
}
public void setSub1(int sub1) {
this.sub1 = sub1;
}
public int getSub2() {
return sub2;
}
public void setSub2(int sub2) {
this.sub2 = sub2;
}
public int getSub3() {
return sub3;
}
public void setSub3(int sub3) {
this.sub3 = sub3;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
ec8156ee175c9791d1c9386344ceae1ecb5586fa | Java | qiuchili/ggnn_graph_classification | /program_data/JavaProgramData/101/10.java | UTF-8 | 1,907 | 2.84375 | 3 | [
"MIT"
] | permissive | package <missing>;
public class GlobalMembers
{
//**********************************************************
//*??????? *
//*? ????? *
//*? ??1000012806 *
//*?????2010.11.17. *
//**********************************************************
public static int Main()
{
int a;
int b;
int c;
int i;
int j;
int k;
int A;
int B;
int C;
for (i = 0; i <= 2; i++)
{
a = i;
for (j = 0; j <= 2; j++)
{
b = j;
if (b == a)
{
continue;
}
for (k = 0; k <= 2; k++)
{
c = k;
if (c == a || c == b)
{
continue;
}
A = (b > a) + (c == a);
B = (a > b) + (a > c);
C = (c > b) + (b > a);
if ((a + A) == 2 && (b + B) == 2 && (c + C) == 2)
{
if (a > b && b > c)
{
System.out.print("C");
System.out.print("B");
System.out.print("A");
System.out.print("\n");
}
if (a > c && c > b)
{
System.out.print("B");
System.out.print("C");
System.out.print("A");
System.out.print("\n");
}
if (b > a && a > c)
{
System.out.print("C");
System.out.print("A");
System.out.print("B");
System.out.print("\n");
}
if (b > c && c > a)
{
System.out.print("A");
System.out.print("C");
System.out.print("B");
System.out.print("\n");
}
if (c > a && a > b)
{
System.out.print("B");
System.out.print("A");
System.out.print("C");
System.out.print("\n");
}
if (c > b && b > a)
{
System.out.print("A");
System.out.print("B");
System.out.print("C");
System.out.print("\n");
}
}
}
}
}
return 0;
}
}
| true |
7bc25b86599febd9f5fc235733c1026ac3e19325 | Java | cristianflury/ApiRestOngAlkemy | /src/test/java/org/alkemy/somosmas/controller/TestimonialServiceUnitTests.java | UTF-8 | 2,984 | 2.203125 | 2 | [] | no_license | package org.alkemy.somosmas.controller;
import org.alkemy.somosmas.SomosMasUnitTests;
import org.alkemy.somosmas.model.Testimonial;
import org.alkemy.somosmas.repository.TestimonialRepository;
import org.alkemy.somosmas.service.impl.ImageHandlerServiceImpl;
import org.alkemy.somosmas.service.impl.TestimonialServiceImpl;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class TestimonialServiceUnitTests extends SomosMasUnitTests {
@InjectMocks
TestimonialServiceImpl testimonialService;
@Mock
TestimonialRepository testimonialRepository;
@Mock
ImageHandlerServiceImpl imageHandlerService;
@Test
void delete_testimonial_works() throws Exception {
Testimonial testimonial = new Testimonial();
testimonial.setImage("https://alkemy-ong.s3.amazonaws.com/2021-09-28T21:21:30.897470_image_user8b6b7de5-423d-4c3e-9e84-fbf4a33d87b5.jpg");
when(testimonialRepository.findById(5L))
.thenReturn(java.util.Optional.of(testimonial));
testimonialService.delete(5L);
verify(testimonialRepository,times(1)).delete(any());
verify(imageHandlerService,times(1)).deleteFileFromS3Bucket(any());
}
@Test
void delete_testimonial_that_does_not_exist_throws_exception() throws Exception {
assertThrows(NoSuchElementException.class,() -> {
testimonialService.delete(5L);
});
verify(testimonialRepository,never()).delete(any());
verify(imageHandlerService,never()).deleteFileFromS3Bucket(any());
}
@Test
void update_testimonial_works() throws Exception {
Testimonial oldTestimonial = new Testimonial();
oldTestimonial.setId(1L);
when(testimonialRepository.findById(1L))
.thenReturn(java.util.Optional.of(oldTestimonial));
Testimonial newTestimonial = new Testimonial();
newTestimonial.setImage("asdasdaaascasdafasf");
newTestimonial.setName("new name");
newTestimonial.setContent("new content");
Testimonial updatedTestimonial = testimonialService.update(1L,newTestimonial,"jpg");
assertEquals(updatedTestimonial.getName(),"new name");
assertEquals(updatedTestimonial.getContent(),"new content");
assertEquals(updatedTestimonial.getId(),1L);
verify(testimonialRepository,times(1)).save(any());
verify(imageHandlerService,times(1)).deleteFileFromS3Bucket(any());
verify(imageHandlerService,times(1)).decodeImageAndCreateUrl(any(),any());
}
@Test
void update_testimonial_that_does_not_exist_throws_exception() {
assertThrows(NoSuchElementException.class,() -> {
testimonialService.update(5L, new Testimonial(),".jpg");
});
verify(testimonialRepository,never()).save(any());
}
}
| true |
1098405346e5a8262abc8b3ad1d7017fb64c0404 | Java | zhaoy1992/xtbg-whtjy-new | /src/main/java/com/chinacreator/xtbg/core/subsystemmanage/entity/SubsysUseInfoBean.java | UTF-8 | 2,028 | 1.90625 | 2 | [] | no_license | package com.chinacreator.xtbg.core.subsystemmanage.entity;
import com.chinacreator.xtbg.core.common.dbbase.entity.XtDbBaseBean;
/**
*
*<p>Title:SubsysUseInfoBean.java</p>
*<p>Description:子系统使用信息bean</p>
*<p>Copyright:Copyright (c) 2013</p>
*<p>Company:湖南科创</p>
*@author 夏天
*@version 1.0
*2013-4-28
*/
public class SubsysUseInfoBean extends XtDbBaseBean{
public SubsysUseInfoBean() {
super("OA_SUBSYS_USEINFO", new String[]{"info_id"}, new String[]{"info_id"});
}
private String info_id; //信息主键
private String sys_id; //子系统主键
private String user_id; //用户id
private String sys_user_id; //子系统对应用户id
private String sys_user_password; //子系统对应用户密码
/**
*<b>Summary: 获取信息主键</b>
*/
public String getInfo_id() {
return info_id;
}
/**
*<b>Summary: 设置信息主键</b>
*/
public void setInfo_id(String info_id) {
this.info_id = info_id;
}
/**
*<b>Summary: 获取子系统主键</b>
*/
public String getSys_id() {
return sys_id;
}
/**
*<b>Summary: 设置子系统主键</b>
*/
public void setSys_id(String sys_id) {
this.sys_id = sys_id;
}
/**
*<b>Summary: 获取用户id</b>
*/
public String getUser_id() {
return user_id;
}
/**
*<b>Summary: 设置用户id</b>
*/
public void setUser_id(String user_id) {
this.user_id = user_id;
}
/**
*<b>Summary: 获取子系统对应用户id</b>
*/
public String getSys_user_id() {
return sys_user_id;
}
/**
*<b>Summary: 设置子系统对应用户id</b>
*/
public void setSys_user_id(String sys_user_id) {
this.sys_user_id = sys_user_id;
}
/**
*<b>Summary: 获取子系统对应用户密码</b>
*/
public String getSys_user_password() {
return sys_user_password;
}
/**
*<b>Summary: 设置子系统对应用户密码</b>
*/
public void setSys_user_password(String sys_user_password) {
this.sys_user_password = sys_user_password;
}
}
| true |
b74295ecae61ac361da901d1c4847128f9c92176 | Java | jgomezr/consulteca | /consulteca/Consulteca/app/src/main/java/org/grameenfoundation/consulteca/synchronization/SynchronizationManager.java | UTF-8 | 52,376 | 1.890625 | 2 | [] | no_license | package org.grameenfoundation.consulteca.synchronization;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import com.google.gson.*;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.message.BasicNameValuePair;
import org.grameenfoundation.consulteca.ApplicationRegistry;
import org.grameenfoundation.consulteca.R;
import org.grameenfoundation.consulteca.location.GpsManager;
import org.grameenfoundation.consulteca.model.Farmer;
import org.grameenfoundation.consulteca.model.SearchLog;
import org.grameenfoundation.consulteca.model.SearchMenu;
import org.grameenfoundation.consulteca.model.SearchMenuItem;
import org.grameenfoundation.consulteca.services.MenuItemService;
import org.grameenfoundation.consulteca.settings.SettingsConstants;
import org.grameenfoundation.consulteca.settings.SettingsManager;
import org.grameenfoundation.consulteca.storage.DatabaseHelperConstants;
import org.grameenfoundation.consulteca.utils.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
/**
* A Facade that handles synchronization of search menus and menu items.
* It abstracts the underlying synchronization protocol from the callers
* and provides methods to initiate the synchronization.
*/
public class SynchronizationManager {
private final static String XML_NAME_SPACE = "http://schemas.applab.org/2010/07/search";
private final static String REQUEST_ELEMENT_NAME = "GetKeywordsRequest";
private final static String VERSION_ELEMENT_NAME = "localKeywordsVersion";
private final static String IMAGES_VERSION_ELEMENT_NAME = "localImagesVersion";
private final static String CURRENT_MENU_IDS = "menuIds";
private final static String DEFAULT_KEYWORDS_VERSION = "2010-04-04 00:00:00";
private final static String DEFAULT_IMAGES_VERSION = "2010-04-04 00:00:00";
private final static String DEFAULT_FARMERS_VERSION = "2014-11-03 00:00:00";
private MenuItemService menuItemService = new MenuItemService();
private boolean synchronizing = false;
private static final SynchronizationManager INSTANCE = new SynchronizationManager();
private Context applicationContext;
private Map<String, SynchronizationListener> synchronizationListenerList =
new HashMap<String, SynchronizationListener>();
private static final int DEFAULT_NETWORK_TIMEOUT = 3 * 60 * 1000;
private SynchronizationManager() {
applicationContext = ApplicationRegistry.getApplicationContext();
}
public static SynchronizationManager getInstance() {
return INSTANCE;
}
/**
* called to initialize the synchronization manager.
*/
public synchronized void initialize() {
}
/**
* called to start the synchronization process in a new
* thread only if it's not running. The synchronization manager gives feedback through the
* synchronization listener events.
* <p/>
* This method is non-blocking and therefore returns immediately.
*
* @see #registerListener(SynchronizationListener)
*/
public synchronized void start() {
if (this.isSynchronizing())
return;
/*
starts a new thread to begin the synchronization. The synchronization manager
*/
new Thread(new Runnable() {
@Override
public void run() {
try {
notifySynchronizationListeners("synchronizationStart");
synchronizing = true;
int maxSynchronizationSteps = 5;
notifySynchronizationListeners("synchronizationUpdate", 1, maxSynchronizationSteps,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.country_code_download_msg), false);
downloadCountryCode();
notifySynchronizationListeners("synchronizationUpdate", 2, maxSynchronizationSteps,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.upload_search_logs_download_msg), false);
uploadBulkSearchLogs();
notifySynchronizationListeners("synchronizationUpdate", 3, maxSynchronizationSteps,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.keyword_download_msg), false);
downloadSearchMenus();
notifySynchronizationListeners("synchronizationUpdate", 4, maxSynchronizationSteps,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.farmer_download_msg), false);
downloadFarmers();
notifySynchronizationListeners("synchronizationUpdate", maxSynchronizationSteps,
maxSynchronizationSteps,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.synchronization_complete_msg), true);
notifySynchronizationListeners("synchronizationComplete");
} catch (Exception e) {
Log.e(SynchronizationManager.class.getName(), "IOException", e);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_connecting_to_server)));
} finally {
synchronizing = false;
}
}
}).start();
}
/**
* uploads multiple search logs to the server in one request.
*/
protected void uploadBulkSearchLogs() throws Exception {
List<SearchLog> searchLogs = menuItemService.getAllSearchLogs();
if(searchLogs.size() == 0){
return;
}
GpsManager.getInstance().update();
for(SearchLog log : searchLogs) {
log.setSubmissionLocation(GpsManager.getInstance().getLocationAsString());
}
SearchLogRequest request = new SearchLogRequest();
request.setRequest(SettingsConstants.REQUEST_UPLOAD_SEARCHLOGS);
request.setImei(DeviceMetadata.getDeviceImei(ApplicationRegistry.getApplicationContext()));
request.setSearchLogs(searchLogs);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
String jsonRequest = gson.toJson(request);
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER);
url = url.substring(0, url.lastIndexOf("/") + 1) + SettingsConstants.REQUEST_SUBMIT_SEARCHLOGS_PAGE;
int networkTimeout = 10 * 60 * 1000;
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_METHODNAME, SettingsConstants.REQUEST_UPLOAD_SEARCHLOGS));
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_DATA, jsonRequest));
InputStream inputStream = HttpHelpers.postFormRequestAndGetStream(url, new UrlEncodedFormEntity(params),
networkTimeout);
StringBuilder stringBuilder = HttpHelpers.getUncompressedResponseString(new BufferedReader(
new InputStreamReader(inputStream)));
try {
String responseJson = stringBuilder.toString();
SearchLogResponse response = new Gson().fromJson(responseJson, SearchLogResponse.class);
if (response != null && response.getResultCode().equals("0")) {
for (SearchLog searchLog : searchLogs) {
menuItemService.deleteSearchLog(searchLog);
notifySynchronizationListeners("synchronizationUpdate",
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.uploading_search_logs), true);
}
}
else {
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_uploading_searchlogs),
new Exception(responseJson)));
}
}catch (Exception ex){
Log.e(SynchronizationManager.class.getName(), "Error uploading search logs", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_uploading_searchlogs)));
}
}
/**
* uploads the given search log to the server.
*
* @param searchLog
*/
private void uploadSearchLog(SearchLog searchLog) throws Exception {
StringBuilder requestParameters = new StringBuilder();
requestParameters.append("?submissionTime=" +
URLEncoder.encode(DatabaseHelperConstants.DEFAULT_DATE_FORMAT.format(searchLog.getDateCreated()),
"UTF-8"));
requestParameters.append("&intervieweeId=" +
URLEncoder.encode(searchLog.getClientId() == null ? "" : searchLog.getClientId(), "UTF-8"));
requestParameters.append("&keyword=" + URLEncoder.encode(searchLog.getMenuItemId(), "UTF-8"));
requestParameters.append("&location=" + URLEncoder.encode(searchLog.getGpsLocation(), "UTF-8"));
if (!searchLog.isTestLog()) {
requestParameters.append("&log=true");
}
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER) +
ApplicationRegistry.getApplicationContext().getString(R.string.search_log_url_path);
String result = HttpHelpers.fetchContent(url + requestParameters.toString());
//delete the log record.
if (result != null) {
menuItemService.deleteSearchLog(searchLog);
}
}
protected void downloadSearchMenus() throws IOException {
try {
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER);
String keywordVersion =
SettingsManager.getInstance().getValue(SettingsConstants.KEY_KEYWORDS_VERSION,
DEFAULT_KEYWORDS_VERSION);
String imagesVersion =
SettingsManager.getInstance().getValue(SettingsConstants.KEY_IMAGES_VERSION,
DEFAULT_IMAGES_VERSION);
KeywordsRequestWrapper request = new KeywordsRequestWrapper();
request.setRequest(SettingsConstants.REQUEST_DOWNLOAD_KEYWORDS);
request.setImei(DeviceMetadata.getDeviceImei(ApplicationRegistry.getApplicationContext()));
request.setKeywordsVersion(keywordVersion);
request.setImagesLastUpdatedDate(imagesVersion);
List<SearchMenu> menus = menuItemService.getAllSearchMenus();
ArrayList<String> menuArr = new ArrayList();
for(int i=0; i<menus.size();i++){
menuArr.add(menus.get(i).getId());
}
request.setMenuIds(menuArr);
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
int networkTimeout = 10 * 60 * 1000;
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_METHODNAME,
SettingsConstants.REQUEST_DOWNLOAD_KEYWORDS));
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_DATA, jsonRequest));
InputStream inputStream = HttpHelpers.postFormRequestAndGetStream(url, new UrlEncodedFormEntity(params),
networkTimeout);
String searchCacheFile = ApplicationRegistry.getApplicationContext().getCacheDir() + "/keywords.cache";
File cacheFile = new File(searchCacheFile);
if (cacheFile.exists()) {
boolean deleted = cacheFile.delete();
if (deleted) {
Log.i(SynchronizationManager.class.getName(), "Cache File Deleted.");
}
}
boolean downloadComplete = writeStreamToTempFile(inputStream, searchCacheFile,
ApplicationRegistry.getApplicationContext().getResources().getString(R.string.keyword_download_msg));
FileInputStream fileInputStream = new FileInputStream(cacheFile);
try {
if (downloadComplete && fileInputStream != null) {
processKeywords(fileInputStream);
}
} finally {
fileInputStream.close();
inputStream.close();
}
} catch (IOException e) {
throw e;
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Error downloading keywords", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_downloading_keywords)));
}
}
/**
* Downloads farmer details for caching on local device
* @throws IOException
*/
protected void downloadFarmers() throws IOException {
try {
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER);
String farmersVersion =
SettingsManager.getInstance().getValue(SettingsConstants.KEY_FARMERS_VERSION,
DEFAULT_FARMERS_VERSION);
FarmersRequestWrapper request = new FarmersRequestWrapper();
request.setRequest(SettingsConstants.REQUEST_UPLOAD_SEARCHLOGS);
request.setImei(DeviceMetadata.getDeviceImei(ApplicationRegistry.getApplicationContext()));
request.setFarmersVersion(farmersVersion);
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
int networkTimeout = 10 * 60 * 1000;
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_METHODNAME,
SettingsConstants.REQUEST_DOWNLOAD_FARMERS));
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_DATA, jsonRequest));
InputStream inputStream = HttpHelpers.postJsonRequestAndGetStream(url, networkTimeout, params);
String searchFarmerCacheFile = ApplicationRegistry.getApplicationContext().getCacheDir() + "/farmers.cache";
File cacheFile = new File(searchFarmerCacheFile);
if (cacheFile.exists()) {
boolean deleted = cacheFile.delete();
if (deleted) {
Log.i(SynchronizationManager.class.getName(), "Farmers Cache File Deleted.");
}
}
boolean downloadComplete = writeStreamToTempFile(inputStream, searchFarmerCacheFile,
ApplicationRegistry.getApplicationContext().getResources().getString(R.string.farmer_download_msg));
FileInputStream fileInputStream = new FileInputStream(cacheFile);
try {
if (downloadComplete && fileInputStream != null) {
processFarmers(fileInputStream);
}
} finally {
fileInputStream.close();
inputStream.close();
}
} catch (IOException e) {
throw e;
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Error downloading farmers", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_downloading_farmers)));
}
}
public Boolean writeStreamToTempFile(InputStream inputStream, String filePath, String message) throws IOException {
File tempFile = new File(filePath);
FileOutputStream stream = new FileOutputStream(tempFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int read = 0;
byte[] bytes = new byte[2048];
while ((read = inputStream.read(bytes)) != -1) {
stream.write(bytes, 0, read);
notifySynchronizationListeners("synchronizationUpdate", message, true);
}
stream.flush();
stream.close();
reader.close();
return true;
}
private void processKeywords(InputStream inputStream) throws IOException, ParseException {
final List<SearchMenu> searchMenus = new ArrayList<SearchMenu>();
List<SearchMenu> oldSearchMenus = menuItemService.getAllSearchMenus();
final List<SearchMenuItem> searchMenuItems = new ArrayList<SearchMenuItem>();
final List<SearchMenuItem> deletedSearchMenuItems = new ArrayList<SearchMenuItem>();
final List<String> imageIdz = new ArrayList<String>();
final List<String> deleteImageIz = new ArrayList<String>();
final String[] keywordVersion = new String[1];
final String[] imagesVersion = new String[1];
final int[] keywordCount = new int[1];
try {
new JSONParser().parse(new InputStreamReader(inputStream), new JsonSimpleBaseParser() {
private Object keywordObject = null;
private String keywordType = "";
private int keywordCounter = 0;
@Override
public boolean primitive(Object value) throws ParseException {
if (null != key && value != null) {
if (key.equals("resultCode")) {
if(!value.toString().equals("0")){
return false;//request wasn't successfull
}
} else if (key.equals("resultMessage")) {
Log.i(SynchronizationManager.class.getName(), value.toString());
} else if (key.equals("total")) {
keywordCount[0] = Integer.parseInt(value.toString());
notifySynchronizationListeners("synchronizationUpdate", keywordCounter++, keywordCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_keywords_msg), true);
} else if (key.equals("version")) {
keywordVersion[0] = value.toString();
imagesVersion[0] = value.toString();
} else {
if (keywordObject instanceof SearchMenu) {
populateSearchMenu((SearchMenu) keywordObject, key, value.toString());
} else if (keywordObject instanceof SearchMenuItem) {
populateSearchMenuItem((SearchMenuItem) keywordObject, key, value.toString());
} else if ("id".equalsIgnoreCase(key) && keywordObject instanceof String
&& keywordType.equalsIgnoreCase("images")) {
keywordObject = value;
} else if ("id".equalsIgnoreCase(key) && keywordObject instanceof String
&& keywordType.equalsIgnoreCase("deletedImages")) {
keywordObject = value;
}
else{
Log.i(SynchronizationManager.class.getName(), "no implementation to process " + key);
}
}
}
key = null;
return true;
}
@Override
public boolean startArray() throws ParseException {
keywordType = key;
return true;
}
@Override
public boolean startObject() throws ParseException {
if ("menus".equalsIgnoreCase(keywordType)) {
keywordObject = new SearchMenu();
} else if ("menuItems".equalsIgnoreCase(keywordType)
|| "deletedMenuItems".equalsIgnoreCase(keywordType)) {
keywordObject = new SearchMenuItem();
} else if ("images".equalsIgnoreCase(keywordType)) {
keywordObject = new String();
} else if ("deletedImages".equalsIgnoreCase(keywordType)) {
keywordObject = new String();
}
return true;
}
@Override
public boolean endObject() throws ParseException {
if (keywordObject != null) {
if (keywordObject instanceof SearchMenu) {
searchMenus.add((SearchMenu) keywordObject);
menuItemService.save((SearchMenu) keywordObject);
} else if (keywordObject instanceof SearchMenuItem &&
keywordType.equalsIgnoreCase("menuItems")) {
//searchMenuItems.add((SearchMenuItem) keywordObject);
menuItemService.save((SearchMenuItem) keywordObject);
notifySynchronizationListeners("synchronizationUpdate", keywordCounter++, keywordCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_keywords_msg), true);
} else if (keywordObject instanceof SearchMenuItem &&
keywordType.equalsIgnoreCase("deletedMenuItems")) {
//deletedSearchMenuItems.add((SearchMenuItem) keywordObject);
notifySynchronizationListeners("synchronizationUpdate", 1, 1,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.removing_keywords_msg), true);
menuItemService.deleteSearchMenuItems((SearchMenuItem) keywordObject);
} else if (keywordObject instanceof String &&
keywordType.equalsIgnoreCase("images")) {
imageIdz.add((String) keywordObject);
} else if (keywordObject instanceof String &&
keywordType.equalsIgnoreCase("deletedImages")) {
deleteImageIz.add((String) keywordObject);
}
}
keywordObject = null;
return true;
}
});
deleteOldMenus(oldSearchMenus, searchMenus);
SettingsManager.getInstance().setValue(SettingsConstants.KEY_KEYWORDS_VERSION, keywordVersion[0]);
downloadImages(imageIdz, imagesVersion[0]);
deleteUnusedImages(deleteImageIz);
} catch (ParseException ex) {
Log.e(SynchronizationManager.class.getName(), "Parsing Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_processing_keywords)));
} catch (IOException ex) {
Log.e(SynchronizationManager.class.getName(), "IOException Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_connecting_to_server)));
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Exception", ex);
}
}
private void deleteUnusedImages(List<String> deleteImageIz) {
if (deleteImageIz != null) {
for (String imageId : deleteImageIz) {
if (imageId != null && imageId.trim().length() > 0) {
File file = new File(ImageUtils.IMAGE_ROOT, imageId + ".jpg");
ImageUtils.deleteFile(file);
}
}
}
}
private void downloadImages(List<String> imageIds, String imagesVersion) throws IOException, ParseException {
if (imageIds != null) {
int count = imageIds.size(), counter = 0;
boolean complete = true;
if (ImageUtils.storageReady() && ImageUtils.createRootFolder()) {
for (final String imageId : imageIds) {
notifySynchronizationListeners("synchronizationUpdate", counter++, count,
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.downloading_images_msg), true);
if (imageId != null || imageId.trim().length() > 0) {
// Only download image if image does not already exist!
if (!ImageUtils.imageExists(imageId.toLowerCase(), false)) {
Log.d("Image Download", "Getting " + imageId);
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER);
ImagesRequestWrapper request = new ImagesRequestWrapper();
request.setRequest(SettingsConstants.REQUEST_DOWNLOAD_IMAGES);
request.setImei(DeviceMetadata.getDeviceImei(ApplicationRegistry.getApplicationContext()));
List<String> ids = new ArrayList<String>();
ids.add(imageId.split("-")[1]);
request.setImageIds(ids);
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
int networkTimeout = 10 * 60 * 1000;
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_METHODNAME,
SettingsConstants.REQUEST_DOWNLOAD_IMAGES));
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_DATA, jsonRequest));
InputStream inputStream = HttpHelpers.postJsonRequestAndGetStream(url, networkTimeout, params);
String jsonResponse = new java.util.Scanner(inputStream).useDelimiter("\\A").next();
ImagesResponseWrapper res = gson.fromJson(jsonResponse, ImagesResponseWrapper.class);
FileOutputStream out = null;
try {
if (res != null && res.getResultCode().equals("0")) {
for (ImageData image : res.getImageResults()) {
byte[] arr = Base64.decode((image.getImageData()), Base64.DEFAULT);
Bitmap png = BitmapFactory.decodeByteArray(arr, 0, arr.length);
out = new FileOutputStream(new File(ImageUtils.IMAGE_ROOT, imageId + ".jpg"));
png.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
}
} catch (Exception ex) {
complete = false;
Log.e(SynchronizationManager.class.getName(), "Image parsing Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_downloading_images)));
} finally {
out.close();
inputStream.close();
}
}
}
}
if(complete){
SettingsManager.getInstance().setValue(SettingsConstants.KEY_IMAGES_VERSION, imagesVersion);
}
}
}
}
private void processImages(InputStream inputStream, final String imageId) throws IOException, ParseException {
final int[] imagesCount = new int[1];
try {
new JSONParser().parse(new InputStreamReader(inputStream), new JsonSimpleBaseParser() {
private Object imageObject = null;
private String imageType = "";
private int imageCounter = 0;
@Override
public boolean primitive(Object value) throws ParseException, IOException {
if (null != key && value != null) {
if (key.equals("resultCode")) {
if(!value.toString().equals("0")){
return false;//request wasn't successfull
}
} else if (key.equals("resultMessage")) {
Log.i(SynchronizationManager.class.getName(), value.toString());
} else if (key.equals("total")) {
imagesCount[0] = Integer.parseInt(value.toString());
notifySynchronizationListeners("synchronizationUpdate", imageCounter++, imagesCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_images_msg), true);
} else {
if (imageObject instanceof ImageData) {
populateImageData((ImageData) imageObject, key, value.toString());
} else if ("imageId".equalsIgnoreCase(key) && imageObject instanceof String
&& imageType.equalsIgnoreCase("imageResults")) {
imageObject = value;
} else if ("imageData".equalsIgnoreCase(key) && imageObject instanceof String
&& imageType.equalsIgnoreCase("imageResults")) {
imageObject = value;
}
else{
Log.i(SynchronizationManager.class.getName(), "no implementation to process " + key);
}
}
}
key = null;
return true;
}
@Override
public boolean startArray() throws ParseException {
imageType = key;
return true;
}
@Override
public boolean startObject() throws ParseException {
if ("imageResults".equalsIgnoreCase(imageType)) {
imageObject = new ImageData();
}
return true;
}
@Override
public boolean endObject() throws ParseException, IOException {
if (imageObject != null) {
if (imageObject instanceof ImageData &&
imageType.equalsIgnoreCase("imageResults")) {
try {
//saveImage((ImageData) imageObject, imageId);
//ImageUtils.writeFile(imageId + ".jpg", new ByteArrayInputStream(Base64.decode(((ImageData) imageObject).getImageData())));
notifySynchronizationListeners("synchronizationUpdate", imageCounter++, imagesCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_images_msg), true);
}catch (Exception ex){
new Throwable(applicationContext.getString(R.string.error_connecting_to_server), ex);
}
}
}
imageObject = null;
return true;
}
});
}
catch (ParseException ex) {
Log.e(SynchronizationManager.class.getName(), "Parsing Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_downloading_images)));
} catch (IOException ex) {
Log.e(SynchronizationManager.class.getName(), "IOException Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_connecting_to_server)));
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Exception", ex);
}
}
private void populateImageData(ImageData imageData, String property, String value) {
if ("imageId".equalsIgnoreCase(property)) {
imageData.setImageId(value);
} else if ("imageData".equalsIgnoreCase(property)) {
imageData.setImageData(value);
}
}
private void deleteOldMenus(List<SearchMenu> oldSearchMenus, List<SearchMenu> searchMenus) {
for (SearchMenu searchMenu : oldSearchMenus) {
boolean exists = false;
for (SearchMenu newSearchMenu : searchMenus) {
if (newSearchMenu.getId().equalsIgnoreCase(searchMenu.getId())) {
exists = true;
}
}
if (!exists) {
menuItemService.deleteSearchMenus(searchMenu);
menuItemService.deleteSearchMenuItems(searchMenu);
}
}
}
private void populateSearchMenuItem(SearchMenuItem searchMenuItem, String property, String value) {
if ("id".equalsIgnoreCase(property)) {
searchMenuItem.setId(value);
} else if ("position".equalsIgnoreCase(property)) {
searchMenuItem.setPosition(Integer.parseInt(value));
} else if ("parent_id".equalsIgnoreCase(property)) {
searchMenuItem.setParentId(value);
} else if ("menu_id".equalsIgnoreCase(property)) {
searchMenuItem.setMenuId(value);
} else if ("label".equalsIgnoreCase(property)) {
searchMenuItem.setLabel(value);
} else if ("content".equalsIgnoreCase(property)) {
searchMenuItem.setContent(value);
}
}
private void populateSearchMenu(SearchMenu searchMenu, String property, String value) {
if ("id".equalsIgnoreCase(property)) {
searchMenu.setId(value);
} else if ("label".equalsIgnoreCase(property)) {
searchMenu.setLabel(value);
}
}
private void processFarmers(InputStream inputStream) throws IOException, ParseException {
final String[] farmersVersion = new String[]{ "" };
final int[] farmersCount = new int[]{ 0 };
final List<Farmer> farmers = new ArrayList<Farmer>();
try {
new JSONParser().parse(new InputStreamReader(inputStream), new JsonSimpleBaseParser() {
private Object farmerObject = null;
private String keywordType = "";
private int farmersCounter = 0;
@Override
public boolean primitive(Object value) throws ParseException {
if (null != key && value != null) {
if (key.equals("resultCode")) {
if(!value.toString().equals("0")){
return false;//request wasn't successfull
}
} else if (key.equals("resultMessage")) {
Log.i(SynchronizationManager.class.getName(), value.toString());
} else if (key.equals("farmerVersion")) {
farmersVersion[0] = value.toString();
} else if (key.equals("farmerCount")) {
farmersCount[0] = Integer.parseInt(value.toString());
notifySynchronizationListeners("synchronizationUpdate", farmersCounter++, farmersCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_farmers_msg), true);
} else {
if (farmerObject instanceof Farmer) {
populateFarmer((Farmer) farmerObject, key, value.toString());
}
}
}
key = null;
return true;
}
@Override
public boolean startArray() throws ParseException {
keywordType = key;
return true;
}
@Override
public boolean startObject() throws ParseException {
if ("afarmerResults".equalsIgnoreCase(keywordType)) {
farmerObject = new Farmer();
}
return true;
}
@Override
public boolean endObject() throws ParseException {
if (farmerObject != null) {
if (farmerObject instanceof Farmer) {
farmers.add((Farmer) farmerObject);
menuItemService.save((Farmer) farmerObject);
notifySynchronizationListeners("synchronizationUpdate", farmersCounter++, farmersCount[0],
ApplicationRegistry.getApplicationContext().
getResources().getString(R.string.processing_farmers_msg), true);
}
}
farmerObject = null;
return true;
}
});
SettingsManager.getInstance().setValue(SettingsConstants.KEY_FARMERS_VERSION, farmersVersion[0]);
} catch (ParseException ex) {
Log.e(SynchronizationManager.class.getName(), "Parsing Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_processing_farmers)));
} catch (IOException ex) {
Log.e(SynchronizationManager.class.getName(), "IOException Error", ex);
notifySynchronizationListeners("onSynchronizationError",
new Throwable(applicationContext.getString(R.string.error_connecting_to_server)));
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Exception", ex);
}
}
private void populateFarmer(Farmer farmer, String property, String value) {
if ("farmerId".equalsIgnoreCase(property)) {
farmer.setId(value);
} else if ("firstName".equalsIgnoreCase(property)) {
farmer.setFirstName (value);
} else if ("lastName".equalsIgnoreCase(property)) {
farmer.setLastName (value);
} else if ("creationDate".equalsIgnoreCase(property)) {
farmer.setCreationDate (value);
} else if ("subcounty".equalsIgnoreCase(property)) {
farmer.setSubcounty (value);
} else if ("village".equalsIgnoreCase(property)) {
farmer.setVillage (value);
}
}
/**
* Sets the version in the update request entity Passes the keywords version, images version and current MenuIds
*
* @return XML request entity
* @throws UnsupportedEncodingException
*/
static AbstractHttpEntity getRequestEntity(Context context) throws UnsupportedEncodingException {
String keywordsVersion = SettingsManager.getInstance().getValue(SettingsConstants.KEY_KEYWORDS_VERSION,
DEFAULT_KEYWORDS_VERSION);
String imagesVersion = SettingsManager.getInstance().getValue(SettingsConstants.KEY_IMAGES_VERSION,
DEFAULT_IMAGES_VERSION);
XmlEntityBuilder xmlRequest = new XmlEntityBuilder();
xmlRequest.writeStartElement(REQUEST_ELEMENT_NAME, XML_NAME_SPACE);
xmlRequest.writeStartElement(VERSION_ELEMENT_NAME);
xmlRequest.writeText(keywordsVersion);
xmlRequest.writeEndElement();
xmlRequest.writeStartElement(IMAGES_VERSION_ELEMENT_NAME);
xmlRequest.writeText(imagesVersion);
xmlRequest.writeEndElement();
xmlRequest.writeStartElement(CURRENT_MENU_IDS);
xmlRequest.writeText(getMenuIds());
xmlRequest.writeEndElement();
xmlRequest.writeEndElement();
return xmlRequest.getEntity();
}
private static String getMenuIds() {
MenuItemService menuItemService = new MenuItemService();
List<SearchMenu> searchMenuList = menuItemService.getAllSearchMenus();
boolean first = true;
StringBuilder stringBuilder = new StringBuilder("");
for (SearchMenu searchMenu : searchMenuList) {
if (first) {
first = false;
} else {
stringBuilder.append(",");
}
stringBuilder.append(searchMenu.getId());
}
return stringBuilder.toString();
}
protected void downloadCountryCode() {
String countryCode = SettingsManager.getInstance().getValue(SettingsConstants.KEY_COUNTRY_CODE, "NONE");
if ("NONE".equalsIgnoreCase(countryCode)) {
String url = SettingsManager.getInstance().getValue(SettingsConstants.KEY_SERVER);
try {
GeneralRequestWrapper request = new GeneralRequestWrapper();
request.setRequest(SettingsConstants.REQUEST_GET_COUNTRY_CODE);
request.setImei(DeviceMetadata.getDeviceImei(ApplicationRegistry.getApplicationContext()));
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
int networkTimeout = 10 * 60 * 1000;
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_METHODNAME,
SettingsConstants.REQUEST_GET_COUNTRY_CODE));
params.add(new BasicNameValuePair(SettingsConstants.REQUEST_DATA, jsonRequest));
InputStream inputStream = HttpHelpers.postFormRequestAndGetStream(url, new UrlEncodedFormEntity(params),
networkTimeout);
if (inputStream != null) {
countryCode = parseCountryCode(inputStream);
SettingsManager.getInstance().setValue(SettingsConstants.KEY_COUNTRY_CODE, countryCode);
inputStream.close();
}
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(), "Error downloading country code", ex);
notifySynchronizationListeners("onSynchronizationError", new Throwable(ex));
}
}
}
/**
* parses the given json input stream and returns the country code.
*
* @param inputStream
* @return country code
* @throws Exception
*/
private String parseCountryCode(InputStream inputStream) throws Exception {
final String[] countryCodeHolder = new String[1];
new JSONParser().parse(new InputStreamReader(inputStream), new JsonSimpleBaseParser() {
@Override
public boolean primitive(Object value) throws ParseException, IOException {
if (null != key) {
if ("countryCode".equals(key)) {
if (value != null) {
Log.d(SynchronizationManager.class.getName(),
"The country code is: " + String.valueOf(value));
countryCodeHolder[0] = String.valueOf(value);
}
}
}
return true;
}
});
return countryCodeHolder[0];
}
private AbstractHttpEntity buildCountryCodeRequestEntity() throws UnsupportedEncodingException {
XmlEntityBuilder xmlRequest = new XmlEntityBuilder();
xmlRequest.writeStartElement(REQUEST_ELEMENT_NAME, XML_NAME_SPACE);
xmlRequest.writeEndElement();
return xmlRequest.getEntity();
}
protected void notifySynchronizationListeners(String methodName, Object... args) {
//synchronized (synchronizationListenerList) {
for (SynchronizationListener listener : synchronizationListenerList.values()) {
try {
Class[] argTypes = null;
if (args != null) {
argTypes = new Class[args.length];
for (int index = 0; index < args.length; index++) {
argTypes[index] = args[index].getClass();
}
}
SynchronizationListener.class.
getMethod(methodName, argTypes).invoke(listener, args);
} catch (Exception ex) {
Log.e(SynchronizationManager.class.getName(),
"Error executing listener method", ex);
}
}
//}
}
/**
* called to stop an on going synchronization process.
*/
public synchronized void stop() {
//TODO stop the synchronization process here.
}
/**
* registers the given synchronization listener and if the listener already exists, it
* will be replaced.
*
* @param listener
*/
public synchronized void registerListener(SynchronizationListener listener) {
synchronizationListenerList.put(listener.getClass().getName(), listener);
}
/**
* un registers the given synchronization listener
*
* @param listener
*/
public synchronized void unRegisterListener(SynchronizationListener listener) {
//synchronized (synchronizationListenerList) {
synchronizationListenerList.remove(listener.getClass().getName());
//}
}
/**
* get a value to determine whether the synchronization manager is in the process of
* performing a synchronization manager
*
* @return
*/
public boolean isSynchronizing() {
return synchronizing;
}
public class KeywordsRequestWrapper {
private String keywordsVersion;
private List<String> menuIds;
private String ImagesLastUpdatedDate;
private String request;
private String imei;
public void setRequest(String request) {
this.request = request;
}
public void setImei(String imei) {
this.imei = imei;
}
public void setKeywordsVersion(String keywordsVersion) {
this.keywordsVersion = keywordsVersion;
}
public void setMenuIds(List<String> menuIds) {
this.menuIds = menuIds;
}
public void setImagesLastUpdatedDate(String imagesLastUpdatedDate) {
ImagesLastUpdatedDate = imagesLastUpdatedDate;
}
public String getKeywordsVersion() {
return keywordsVersion;
}
public List<String> getMenuIds() {
return menuIds;
}
public String getImagesLastUpdatedDate() {
return ImagesLastUpdatedDate;
}
public String getRequest() {
return request;
}
public String getImei() {
return imei;
}
}
public class SearchLogRequest {
private String request;
private String imei;
private List<SearchLog> searchLogs;
public void setRequest(String request) {
this.request = request;
}
public void setImei(String imei) {
this.imei = imei;
}
public void setSearchLogs(List<SearchLog> searchLogs) {
this.searchLogs = searchLogs;
}
}
public class FarmersRequestWrapper {
private String farmersVersion;
private String request;
private String imei;
public void setRequest(String request) {
this.request = request;
}
public void setImei(String imei) {
this.imei = imei;
}
public void setFarmersVersion(String farmersVersion) {
this.farmersVersion = farmersVersion;
}
}
public class GeneralRequestWrapper {
private String request;
private String imei;
public void setRequest(String request) {
this.request = request;
}
public void setImei(String imei) {
this.imei = imei;
}
}
public class SearchLogResponse {
private String resultMessage;
private String resultCode;
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
}
public class ImagesRequestWrapper {
private String request;
private String imei;
private List<String> imageIds;
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public List<String> getImageIds() {
return imageIds;
}
public void setImageIds(List<String> imageIds) {
this.imageIds = imageIds;
}
}
public class ImagesResponseWrapper {
private String resultCode;
private String resultMassage;
private List<ImageData> imageResults;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMassage() {
return resultMassage;
}
public void setResultMassage(String resultMassage) {
this.resultMassage = resultMassage;
}
public List<ImageData> getImageResults() {
return imageResults;
}
public void setImageResults(List<ImageData> imageResults) {
this.imageResults = imageResults;
}
}
public class ImageData {
private String imageId;
private String imageData;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public String getImageData() {
return imageData;
}
public void setImageData(String imageData) {
this.imageData = imageData;
}
}
}
| true |
460a472c99731138e5e5593682973126cc314731 | Java | mayuba/Battleship | /src/fr/enseirb/battleship/Player.java | UTF-8 | 636 | 3.046875 | 3 | [] | no_license | package fr.enseirb.battleship;
public abstract class Player {
protected String name;
protected int score;
protected Grid grid;
public Player(String name) {
this.name = name;
this.score = 0;
}
public Grid getGrid() {
return grid;
}
public String getName() {
return name;
}
public boolean checkWin(String name){
if(this.getGrid().checkAllShipSunk()){
if(name.compareTo("human") == 0)
System.out.println("You win !");
else {
System.out.println(name + " win !");
System.out.println("You loose !");
}
return true;
}
return false;
}
abstract public boolean play(Player player);
}
| true |
92144c06ad4e89ce3fa0ac857e6205531758f54e | Java | mfarnoosh/occupy | /occupy-server/src/main/java/com/mcm/processors/EventProcessor.java | UTF-8 | 619 | 2.0625 | 2 | [] | no_license | package com.mcm.processors;
import com.mcm.entities.mongo.events.BaseEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Created by alirezaghias on 1/6/2017 AD.
*/
abstract class EventProcessor<T extends BaseEvent> implements Callable<Void> {
private List<T> batch;
EventProcessor(List<T> batch) {
this.batch = batch;
}
abstract void doJob(List<T> batch);
@Override
public Void call() throws Exception {
doJob(batch);
return null;
}
}
| true |
ea38879cb545b7a7f47e08765150373eadacfde8 | Java | fengwuxp/some-examples | /oak-organization/services/src/main/java/com/oak/organization/services/organization/info/OrganizationInfo.java | UTF-8 | 2,515 | 1.8125 | 2 | [] | no_license | package com.oak.organization.services.organization.info;
import com.levin.commons.service.domain.Desc;
import com.oak.organization.enums.ApprovalStatus;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 组织
* 2020-1-19 13:18:21
*/
@Schema(description = "组织")
@Data
@Accessors(chain = true)
@NoArgsConstructor
@EqualsAndHashCode(of = {"id"})
@ToString(exclude = {"parentInfo",})
public class OrganizationInfo implements Serializable {
private static final long serialVersionUID = 4146251376336548110L;
@Schema(description = "ID")
private Long id;
@Schema(description = "编号")
private String code;
@Schema(description = "审核状态")
private ApprovalStatus status;
@Schema(description = "联系人")
private String contacts;
@Schema(description = "联系电话")
private String contactMobilePhone;
@Schema(description = "LOGO")
private String logo;
@Schema(description = "区域ID")
private String areaId;
@Schema(description = "区域名称")
private String areaName;
@Schema(description = "详细地址")
private String address;
@Schema(description = "最后到期日期")
private Date lastAuthEndDate;
@Schema(description = "层级")
private Integer level;
@Schema(description = "层级路径")
private String levelPath;
@Schema(description = "机构拼音首字母")
private String pinyinInitials;
@Schema(description = "父ID")
private Long parentId;
@Desc(code = "parent")
@Schema(description = "上级组织")
private OrganizationInfo parentInfo;
@Schema(description = "类型")
private String type;
@Schema(description = "ID路径")
private String idPath;
@Schema(description = "名称")
private String name;
@Schema(description = "排序代码")
private Integer orderCode;
@Schema(description = "是否允许")
private Boolean enable;
@Schema(description = "是否可编辑")
private Boolean editable;
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "更新时间")
private Date lastUpdateTime;
@Schema(description = "备注")
private String remark;
@Schema(description = "创建者")
private Long creatorId;
}
| true |
f7af840c7079472b723e6c325806e19976f7bd49 | Java | Hanyauku123/Tarea_Laboratorio_4 | /src/AbstractFactory/Convertir/Binario.java | UTF-8 | 485 | 2.8125 | 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 AbstractFactory.Convertir;
/**
*
* @author soporte
*/
public class Binario implements Convertir{
@Override
public String Convertir(int resul2) {
String binario = "";
binario = Integer.toBinaryString(resul2);
return binario;
}
}
| true |
f6ff846b895bf0ec14c9e583c8244d8a48fce7a7 | Java | seijuro/java-common-lib | /src/main/java/com/github/seijuro/common/IJSONConvertable.java | UTF-8 | 141 | 1.75 | 2 | [] | no_license | package com.github.seijuro.common;
import org.json.simple.JSONObject;
public interface IJSONConvertable {
JSONObject toJSONObject();
}
| true |
cb9a5ba21bd48dc3b509c9ea501578eeb5694d8d | Java | kevinli194/voogasalad_BitsPlease | /src/engine/collision/objects/EnemyCollisionObject.java | UTF-8 | 928 | 2.421875 | 2 | [
"MIT"
] | permissive | package engine.collision.objects;
import engine.gameObject.GameObject;
/**
*
* @author Ben
*
*/
public class EnemyCollisionObject extends CollisionObject {
@Override
protected void handlePowerupCollisionObject(GameObject thisOne,
GameObject other) {
myCollision.reverseVelocites(thisOne, other);
}
@Override
protected void handleEnemyCollisionObject(GameObject thisOne,
GameObject other) {
myCollision.reverseVelocites(thisOne, other);
}
@Override
protected void handleFixedObjectCollisionObject(GameObject thisOne,
GameObject other) {
myCollision.fixedCollision(other, thisOne);
}
@Override
protected void handleHeroCollisionObject(GameObject thisOne,
GameObject other) {
// TODO Auto-generated method stub
}
@Override
public void handleCollision(GameObject thisOne, GameObject other) {
// TODO other.getCollisionObject.handleEnemyCollisionObject(other,
// thisOne);
}
}
| true |
c507741b988ed065498de586be50fa07dd8704e6 | Java | tcmhoang/FPT-Java-OOP | /LAB_Dump/PersManagement_File/src/Business/FileManagement.java | UTF-8 | 1,427 | 3.25 | 3 | [] | no_license | package Business;
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class FileManagement
{
//get new content
public static String getUpdates(String pathFileInput) throws FileNotFoundException
{
Set<String> newContent = new HashSet<>();
File file = new File(pathFileInput);
Scanner input = new Scanner(file);
int count = 0;
while (input.hasNext())
{
String word = input.next();
newContent.add(word + " ");
}
return String.join("", newContent);
}
//write new content to file
public static void writeNewContent(String pathFileOutput, String content) throws WriteAbortedException
{
FileWriter fileWriter = null;
File file = new File(pathFileOutput);
try
{
fileWriter = new FileWriter(file);
BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
bufferWriter.write(content);
bufferWriter.close();
} catch (IOException ex)
{
throw new WriteAbortedException("Can’t write file" ,ex);
} finally
{
try
{
assert fileWriter != null;
fileWriter.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
| true |
365ff7feb366da229e0f82a0d90ac34add52cc2e | Java | liveqmock/javalib | /ygsoft.finance.common/legacysrc/javax/sql/rowset/serial/SerialClob.java | GB18030 | 20,194 | 2.546875 | 3 | [] | no_license | /*
* @(#)SerialClob.java 1.11 04/08/10
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package javax.sql.rowset.serial;
import java.sql.*;
import java.io.*;
/**
* A serialized mapping in the Java programming language of an SQL <code>CLOB</code> value.
* <P>
* The <code>SerialClob</code> class provides a constructor for creating an instance from a <code>Clob</code> object.
* Note that the <code>Clob</code> object should have brought the SQL <code>CLOB</code> value's data over to the client
* before a <code>SerialClob</code> object is constructed from it. The data of an SQL <code>CLOB</code> value can be
* materialized on the client as a stream of Unicode characters.
* <P>
* <code>SerialClob</code> methods make it possible to get a substring from a <code>SerialClob</code> object or to
* locate the start of a pattern of characters.
*
* @author Jonathan Bruce
*/
public class SerialClob implements Clob, Serializable, Cloneable {
/**
* A serialized array of characters containing the data of the SQL <code>CLOB</code> value that this
* <code>SerialClob</code> object represents.
*
* @serial
*/
private char buf[];
/**
* Internal Clob representation if SerialClob is intialized with a Clob
*/
private Clob clob;
/**
* The length in characters of this <code>SerialClob</code> object's internal array of characters.
*
* @serial
*/
private long len;
/**
* The original length in characters of tgus <code>SerialClob</code> objects internal array of characters.
*
* @serial
*/
private long origLen;
/**
* Constructs a <code>SerialClob</code> object that is a serialized version of the given <code>char</code> array.
* <p>
* The new <code>SerialClob</code> object is initialized with the data from the <code>char</code> array, thus
* allowing disconnected <code>RowSet</code> objects to establish a serialized <code>Clob</code> object without
* touching the data source.
*
* @param ch
* the char array representing the <code>Clob</code> object to be serialized
* @throws SerialException
* if an error occurs during serialization
* @throws SQLException
* if a SQL error occurs
*/
public SerialClob(char ch[]) throws SerialException, SQLException {
// %%% JMB. Agreed. Add code here to throw a SQLException if no
// support is available for locatorsUpdateCopy=false
// Serializing locators is not supported.
len = ch.length;
buf = new char[(int) len];
for (int i = 0; i < len; i++) {
buf[i] = ch[i];
}
origLen = len;
}
/**
* Constructs a <code>SerialClob</code> object that is a serialized version of the given <code>Clob</code> object.
* <P>
* The new <code>SerialClob</code> object is initialized with the data from the <code>Clob</code> object; therefore,
* the <code>Clob</code> object should have previously brought the SQL <code>CLOB</code> value's data over to the
* client from the database. Otherwise, the new <code>SerialClob</code> object object will contain no data.
* <p>
* Note: The <code>Clob</code> object supplied to this constructor cannot return <code>null</code> for the
* <code>Clob.getCharacterStream()</code> and <code>Clob.getAsciiStream</code> methods. This <code>SerialClob</code>
* constructor cannot serialize a <code>Clob</code> object in this instance and will throw an
* <code>SQLException</code> object.
*
* @param clob
* the <code>Clob</code> object from which this <code>SerialClob</code> object is to be constructed;
* cannot be null
* @throws SerialException
* if an error occurs during serialization
* @throws SQLException
* if a SQL error occurs in capturing the CLOB; if the <code>Clob</code> object is a null; or if at
* least one of the <code>Clob.getCharacterStream()</code> and <code>Clob.getAsciiStream()</code>
* methods on the <code>Clob</code> return a null
* @see java.sql.Clob
*/
public SerialClob(Clob clob) throws SerialException, SQLException {
if (clob == null) {
throw new SQLException("Cannot instantiate a SerialClob " + "object with a null Clob object");
}
len = clob.length();
this.clob = clob;
buf = new char[(int) len];
int read = 0;
int offset = 0;
BufferedReader reader;
if (clob.getCharacterStream() == null || clob.getAsciiStream() == null) {
throw new SQLException("Invalid Clob object. Calls to getCharacterStream "
+ "or getAsciiStream return null which cannot be serialized.");
}
try {
reader = new BufferedReader(clob.getCharacterStream());
do {
read = reader.read(buf, offset, (int) (len - offset));
offset += read;
} while (read > 0);
} catch (java.io.IOException ex) {
throw new SerialException("SerialClob: " + ex.getMessage());
}
origLen = len;
}
/**
* Retrieves the number of characters in this <code>SerialClob</code> object's array of characters.
*
* @return a <code>long</code> indicating the length in characters of this <code>SerialClob</code> object's array of
* character
* @throws SerialException
* if an error occurs
*/
public long length() throws SerialException {
return len;
}
/**
* Returns this <code>SerialClob</code> object's data as a stream of Unicode characters. Unlike the related method,
* <code>getAsciiStream</code>, a stream is produced regardless of whether the <code>SerialClob</code> object was
* created with a <code>Clob</code> object or a <code>char</code> array.
*
* @return a <code>java.io.Reader</code> object containing this <code>SerialClob</code> object's data
* @throws SerialException
* if an error occurs
*/
public java.io.Reader getCharacterStream() throws SerialException {
return (java.io.Reader) new CharArrayReader(buf);
}
/**
* Retrieves the <code>CLOB</code> value designated by this <code>SerialClob</code> object as an ascii stream. This
* method forwards the <code>getAsciiStream</code> call to the underlying <code>Clob</code> object in the event that
* this <code>SerialClob</code> object is instantiated with a <code>Clob</code> object. If this
* <code>SerialClob</code> object is instantiated with a <code>char</code> array, a <code>SerialException</code>
* object is thrown.
*
* @return a <code>java.io.InputStream</code> object containing this <code>SerialClob</code> object's data
* @throws SerialException
* if this <code>SerialClob<code> object was not instantiated
* with a <code>Clob</code> object
* @throws SQLException
* if there is an error accessing the <code>CLOB</code> value represented by the <code>Clob</code>
* object that was used to create this <code>SerialClob</code> object
*/
public java.io.InputStream getAsciiStream() throws SerialException, SQLException {
if (this.clob != null) {
return this.clob.getAsciiStream();
} else {
throw new SerialException("Unsupported operation. SerialClob cannot "
+ "return a the CLOB value as an ascii stream, unless instantiated "
+ "with a fully implemented Clob object.");
}
}
/**
* Returns a copy of the substring contained in this <code>SerialClob</code> object, starting at the given position
* and continuing for the specified number or characters.
*
* @param pos
* the position of the first character in the substring to be copied; the first character of the
* <code>SerialClob</code> object is at position <code>1</code>; must not be less than <code>1</code>,
* and the sum of the starting position and the length of the substring must be less than the length of
* this <code>SerialClob</code> object
* @param length
* the number of characters in the substring to be returned; must not be greater than the length of this
* <code>SerialClob</code> object, and the sum of the starting position and the length of the substring
* must be less than the length of this <code>SerialClob</code> object
* @return a <code>String</code> object containing a substring of this <code>SerialClob</code> object beginning at
* the given position and containing the specified number of consecutive characters
* @throws SerialException
* if either of the arguments is out of bounds
*/
public String getSubString(long pos, int length) throws SerialException {
if (pos < 1 || pos > this.length()) {
throw new SerialException("Invalid position in BLOB object set");
}
if ((pos - 1) + length > this.length()) {
throw new SerialException("Invalid position and substring length");
}
try {
return new String(buf, (int) pos - 1, length);
} catch (StringIndexOutOfBoundsException e) {
throw new SerialException("StringIndexOutOfBoundsException: " + e.getMessage());
}
}
/**
* Returns the position in this <code>SerialClob</code> object where the given <code>String</code> object begins,
* starting the search at the specified position. This method returns <code>-1</code> if the pattern is not found.
*
* @param searchStr
* the <code>String</code> object for which to search
* @param start
* the position in this <code>SerialClob</code> object at which to start the search; the first position
* is <code>1</code>; must not be less than <code>1</code> nor greater than the length of this
* <code>SerialClob</code> object
* @return the position at which the given <code>String</code> object begins, starting the search at the specified
* position; <code>-1</code> if the given <code>String</code> object is not found or the starting position
* is out of bounds; position numbering for the return value starts at <code>1</code>
* @throws SerialException
* if an error occurs locating the String signature
* @throws SQLException
* if there is an error accessing the Blob value from the database.
*/
public long position(String searchStr, long start) throws SerialException, SQLException {
if (start < 1 || start > len) {
return -1;
}
char pattern[] = searchStr.toCharArray();
int pos = (int) start - 1;
int i = 0;
long patlen = pattern.length;
while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++;
pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) {
pos++; // increment pos only
}
}
return -1; // not found
}
/**
* Returns the position in this <code>SerialClob</code> object where the given <code>Clob</code> signature begins,
* starting the search at the specified position. This method returns <code>-1</code> if the pattern is not found.
*
* @param searchStr
* the <code>Clob</code> object for which to search
* @param start
* the position in this <code>SerialClob</code> object at which to begin the search; the first position
* is <code>1</code>; must not be less than <code>1</code> nor greater than the length of this
* <code>SerialClob</code> object
* @return the position at which the given <code>Clob</code> object begins in this <code>SerialClob</code> object,
* at or after the specified starting position
* @throws SerialException
* if an error occurs locating the Clob signature
* @throws SQLException
* if there is an error accessing the Blob value from the database
*/
public long position(Clob searchStr, long start) throws SerialException, SQLException {
char cPattern[] = null;
try {
java.io.Reader r = searchStr.getCharacterStream();
cPattern = new char[(int) searchStr.length()];
r.read(cPattern);
} catch (IOException e) {
throw new SerialException("Error streaming Clob search data");
}
return position(new String(cPattern), start);
}
/**
* Writes the given Java <code>String</code> to the <code>CLOB</code> value that this <code>SerialClob</code> object
* represents, at the position <code>pos</code>.
*
* @param pos
* the position at which to start writing to the <code>CLOB</code> value that this
* <code>SerialClob</code> object represents; the first position is <code>1</code>; must not be less than
* <code>1</code> nor greater than the length of this <code>SerialClob</code> object
* @param str
* the string to be written to the <code>CLOB</code> value that this <code>SerialClob</code> object
* represents
* @return the number of characters written
* @throws SerialException
* if there is an error accessing the <code>CLOB</code> value; if an invalid position is set; if an
* invalid offset value is set; if number of bytes to be written is greater than the
* <code>SerialClob</code> length; or the combined values of the length and offset is greater than the
* Clob buffer
*/
public int setString(long pos, String str) throws SerialException {
return (setString(pos, str, 0, str.length()));
}
/**
* Writes <code>len</code> characters of <code>str</code>, starting at character <code>offset</code>, to the
* <code>CLOB</code> value that this <code>Clob</code> represents.
*
* @param pos
* the position at which to start writing to the <code>CLOB</code> value that this
* <code>SerialClob</code> object represents; the first position is <code>1</code>; must not be less than
* <code>1</code> nor greater than the length of this <code>SerialClob</code> object
* @param str
* the string to be written to the <code>CLOB</code> value that this <code>Clob</code> object represents
* @param offset
* the offset into <code>str</code> to start reading the characters to be written
* @param length
* the number of characters to be written
* @return the number of characters written
* @throws SerialException
* if there is an error accessing the <code>CLOB</code> value; if an invalid position is set; if an
* invalid offset value is set; if number of bytes to be written is greater than the
* <code>SerialClob</code> length; or the combined values of the length and offset is greater than the
* Clob buffer
*/
public int setString(long pos, String str, int offset, int length) throws SerialException {
String temp = str.substring(offset);
char cPattern[] = temp.toCharArray();
if (offset < 0 || offset > str.length()) {
throw new SerialException("Invalid offset in byte array set");
}
if (pos < 1 || pos > this.length()) {
throw new SerialException("Invalid position in BLOB object set");
}
if ((long) (length) > origLen) {
throw new SerialException("Buffer is not sufficient to hold the value");
}
if ((length + offset) > str.length()) {
// need check to ensure length + offset !> bytes.length
throw new SerialException("Invalid OffSet. Cannot have combined offset "
+ " and length that is greater that the Blob buffer");
}
int i = 0;
pos--; // values in the array are at position one less
while (i < length || (offset + i + 1) < (str.length() - offset)) {
this.buf[(int) pos + i] = cPattern[offset + i];
i++;
}
return i;
}
/**
* Retrieves a stream to be used to write Ascii characters to the <code>CLOB</code> value that this
* <code>SerialClob</code> object represents, starting at position <code>pos</code>. This method forwards the
* <code>setAsciiStream()</code> call to the underlying <code>Clob</code> object in the event that this
* <code>SerialClob</code> object is instantiated with a <code>Clob</code> object. If this <code>SerialClob</code>
* object is instantiated with a <code>char</code> array, a <code>SerialException</code> object is thrown.
*
* @param pos
* the position at which to start writing to the <code>CLOB</code> object
* @return the stream to which ASCII encoded characters can be written
* @throws SerialException
* if SerialClob is not instantiated with a Clob object that supports <code>setAsciiStream</code>
* @throws SQLException
* if there is an error accessing the <code>CLOB</code> value
* @see #getAsciiStream
*/
public java.io.OutputStream setAsciiStream(long pos) throws SerialException, SQLException {
if (this.clob.setAsciiStream(pos) != null) {
return this.clob.setAsciiStream(pos);
} else {
throw new SerialException("Unsupported operation. SerialClob cannot "
+ "return a writable ascii stream\n unless instantiated with a Clob object "
+ "that has a setAsciiStream() implementation");
}
}
/**
* Retrieves a stream to be used to write a stream of Unicode characters to the <code>CLOB</code> value that this
* <code>SerialClob</code> object represents, at position <code>pos</code>. This method forwards the
* <code>setCharacterStream()</code> call to the underlying <code>Clob</code> object in the event that this
* <code>SerialClob</code> object is instantiated with a <code>Clob</code> object. If this <code>SerialClob</code>
* object is instantiated with a <code>char</code> array, a <code>SerialException</code> is thrown.
*
* @param pos
* the position at which to start writing to the <code>CLOB</code> value
*
* @return a stream to which Unicode encoded characters can be written
* @throws SerialException
* if the SerialClob is not instantiated with a Clob object that supports
* <code>setCharacterStream</code>
* @throws SQLException
* if there is an error accessing the <code>CLOB</code> value
* @see #getCharacterStream
*/
public java.io.Writer setCharacterStream(long pos) throws SerialException, SQLException {
if (this.clob.setCharacterStream(pos) != null) {
return this.clob.setCharacterStream(pos);
} else {
throw new SerialException("Unsupported operation. SerialClob cannot "
+ "return a writable character stream\n unless instantiated with a Clob object "
+ "that has a setCharacterStream implementation");
}
}
/**
* Truncates the <code>CLOB</code> value that this <code>SerialClob</code> object represents so that it has a length
* of <code>len</code> characters.
* <p>
* Truncating a <code>SerialClob</code> object to length 0 has the effect of clearing its contents.
*
* @param length
* the length, in bytes, to which the <code>CLOB</code> value should be truncated
* @throws SQLException
* if there is an error accessing the <code>CLOB</code> value
*/
public void truncate(long length) throws SerialException {
if (length > len) {
throw new SerialException("Length more than what can be truncated");
} else {
len = length;
// re-size the buffer
if (len == 0) {
buf = new char[] {};
} else {
buf = (this.getSubString(1, (int) len)).toCharArray();
}
}
}
/**
* The identifier that assists in the serialization of this <code>SerialClob</code> object.
*/
static final long serialVersionUID = -1662519690087375313L;
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
public String toString() {
return getString();
}
/**
* ַ.
*
* @return ַ
*/
public String getString() {
return new String(buf);
}
/**
* һֵַ.
*
* @param value
* ֵַ
*/
public void setString(final String value) {
if (value == null) {
try {
truncate(0);
} catch (SerialException e) {
throw new RuntimeException(e);
}
} else {
buf = value.toCharArray();
len = buf.length;
}
}
public void free() throws SQLException {
// TODO Auto-generated method stub
}
public Reader getCharacterStream(long pos, long length) throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
| true |
1765726cccdde6556ec6c05d8874d4cb3c69055a | Java | L1j-Kiyoshi/kys8.1 | /src/l1j/server/server/serverpackets/S_HPMeter.java | UTF-8 | 1,284 | 2.359375 | 2 | [] | no_license | package l1j.server.server.serverpackets;
import l1j.server.server.Opcodes;
import l1j.server.server.model.L1Character;
public class S_HPMeter extends ServerBasePacket {
private static final String _typeString = "[S] S_HPMeter";
private byte[] _byte = null;
public S_HPMeter(int objId, int hpRatio, int mpRatio) {
buildPacket(objId, hpRatio, mpRatio);
}
public S_HPMeter(L1Character cha) {
int objId = cha.getId();
int hpRatio = 100;
int mpRatio = 100;
if (0 < cha.getMaxHp())
hpRatio = 100 * cha.getCurrentHp() / cha.getMaxHp();
if (0 < cha.getMaxMp())
mpRatio = 100 * cha.getCurrentMp() / cha.getMaxMp();
buildPacket(objId, hpRatio, mpRatio);
}
private void buildPacket(int objId, int hpRatio, int mpRatio) {
// 43 04 5d 91 05 00 00 93 1b
writeC(Opcodes.S_HIT_RATIO);
writeD(objId);
writeC(hpRatio);
writeC(mpRatio);
writeH(0);
}
@Override
public byte[] getContent() {
if (_byte == null) {
_byte = _bao.toByteArray();
}
return _byte;
}
@Override
public String getType() {
return _typeString;
}
}
| true |
79a8214e9a379deb3f1c93264ad710e97e8b9c20 | Java | psm7047/springframework | /src/main/java/com/mycompany/webapp/service/BoardsService2.java | UTF-8 | 1,073 | 2.03125 | 2 | [] | no_license | package com.mycompany.webapp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mycompany.webapp.dao.BoardsDao2;
import com.mycompany.webapp.dto.Board;
import com.mycompany.webapp.dto.Pager;
@Service
public class BoardsService2 {
@Autowired
private BoardsDao2 boardsDao2;
public List<Board> getBoardList() {
List<Board> list = boardsDao2.selectAll();
return list;
}
public List<Board> getBoardList(Pager pager) {
List<Board> list = boardsDao2.selectByPage(pager);
return list;
}
public Board getBoard(int bno) {
Board board = boardsDao2.selectByBno(bno);
return board;
}
public void updateBoard(Board board) {
boardsDao2.update(board);
}
public void saveBoard(Board board) {
boardsDao2.insert(board);
}
public void deleteBoards(int bno) {
boardsDao2.deleteByBno(bno);
}
public void addHitcount(int bno) {
boardsDao2.updateBhitcount(bno);
}
public int getTotalRows() {
int rows = boardsDao2.count();
return rows;
}
}
| true |
c24116786c3c896c4ad06cfb821b994e73b0e87f | Java | hnteam/bubuka_android | /app/src/main/java/ru/espepe/bubuka/player/service/sync/SyncProgressReport.java | UTF-8 | 711 | 2.03125 | 2 | [] | no_license | package ru.espepe.bubuka.player.service.sync;
import java.util.List;
/**
* Created by wolong on 27/08/14.
*/
public class SyncProgressReport {
private String type;
//public int filesTotal;
//public int filesComplete;
private List<SyncFileProgressReport> filesInProgress;
public SyncProgressReport(String type, List<SyncFileProgressReport> filesInProgress) {
this.type = type;
//this.filesTotal = filesTotal;
//this.filesComplete = filesComplete;
this.filesInProgress = filesInProgress;
}
public String getType() {
return type;
}
public List<SyncFileProgressReport> getFilesInProgress() {
return filesInProgress;
}
}
| true |
fc50fbd8b7813fc2014a92f3a3a2dcdade002547 | Java | bellmit/ecology | /src/main/java/ecustom/entities/HrmResource.java | UTF-8 | 1,443 | 2.09375 | 2 | [] | no_license | package ecustom.entities;
public class HrmResource {
private Integer id;
private String lastName;
private String loginId;
private String password;
private Integer subCompanyId;
private Integer departmentId;
private Integer jobTitle;
private String workCode;
private String email;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public Integer getSubCompanyId() {
return subCompanyId;
}
public void setSubCompanyId(Integer subCompanyId) {
this.subCompanyId = subCompanyId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public Integer getJobTitle() {
return jobTitle;
}
public void setJobTitle(Integer jobTitle) {
this.jobTitle = jobTitle;
}
public String getWorkCode() {
return workCode;
}
public void setWorkCode(String workCode) {
this.workCode = workCode;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| true |
d33a7633118b319e17994de57ef7ab15f5226c21 | Java | n01111786/movietuvi-master | /app/src/main/java/com/example/anubhavchoudhary/movietuvi/AboutUS.java | UTF-8 | 1,789 | 2.1875 | 2 | [] | no_license | package com.example.anubhavchoudhary.movietuvi;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class AboutUS extends AppCompatActivity {
private TextView first,second, third;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
first = findViewById(R.id.linkedin1);
second = findViewById(R.id.pin1);
third = findViewById(R.id.linkedin2);
first.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url1 = "https://www.linkedin.com/in/anubhav-choudhary-a30512146";
Intent ihelp = new Intent(Intent.ACTION_VIEW);
ihelp.setData(Uri.parse(url1));
startActivity(ihelp);
}
});
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "https://www.pinterest.ca/malinlomax/";
Intent ihelp = new Intent(Intent.ACTION_VIEW);
ihelp.setData(Uri.parse(url));
startActivity(ihelp);
}
});
third.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "https://www.pinterest.ca/malinlomax/";
Intent ihelp = new Intent(Intent.ACTION_VIEW);
ihelp.setData(Uri.parse(url));
startActivity(ihelp);
}
});
}
}
| true |
fd5302751a5b216e8553a517f2c151a3b2e29e16 | Java | huanglongf/enterprise_project | /service-impl-wms/src/main/java/com/jumbo/wms/manager/task/jd/JdOrderTaskImpl.java | UTF-8 | 3,239 | 1.90625 | 2 | [] | no_license | package com.jumbo.wms.manager.task.jd;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import com.baozun.task.annotation.SingleTaskLock;
import com.jumbo.dao.warehouse.BiChannelDao;
import com.jumbo.dao.warehouse.StockTransApplicationDao;
import com.jumbo.dao.warehouse.WhTransProvideNoDao;
import com.jumbo.wms.daemon.JdOrderTask;
import com.jumbo.wms.manager.BaseManagerImpl;
import com.jumbo.wms.manager.expressDelivery.TransOlManager;
import com.jumbo.wms.model.baseinfo.Transportator;
import com.jumbo.wms.model.warehouse.StockTransApplicationStatus;
public class JdOrderTaskImpl extends BaseManagerImpl implements JdOrderTask{
/**
*
*/
private static final long serialVersionUID = 2781749352292243948L;
@Autowired
private JdOrderManager jdOrderManager;
@Autowired
private StockTransApplicationDao staDao;
@Autowired
private BiChannelDao biChannelDao;
@Autowired
private WhTransProvideNoDao transProvideNoDao;
@Autowired
private TransOlManager transOlManager;
@SingleTaskLock(timeout = TASK_LOCK_TIMEOUT, value = TASK_LOCK_VALUE)
public void toHubGetJdTransNo() {
log.debug("获取运单号开始");
jdOrderManager.jdTransOnlineNo();
}
// 设置JD单据号
@SingleTaskLock(timeout = TASK_LOCK_TIMEOUT, value = TASK_LOCK_VALUE)
public void jdInterfaceByWarehouse() {
log.debug("设置运单号开始");
Long count = transProvideNoDao.getTranNoNumberByLpCode(Transportator.JD, null, new SingleColumnRowMapper<Long>(Long.class));
if (count > 0) {
List<String> idList = biChannelDao.getAllJDbIcHannel(new SingleColumnRowMapper<String>(String.class));
for (String owner : idList) {
try {
Boolean flag = true;
while (flag) {
List<String> lpList = new ArrayList<String>();
lpList.add("JD");
lpList.add("JDCOD");
List<Long> staList = staDao.findStaByOwnerAndStatus(owner, lpList, StockTransApplicationStatus.CREATED.getValue(), new SingleColumnRowMapper<Long>(Long.class));
if (staList.size() < 100) {
flag = false;
}
for (Long staId : staList) {
// JD下单
try {
// 设置JD单据号
transOlManager.matchingTransNo(staId);
} catch (Exception e) {
log.error("", e);
}
}
}
} catch (Exception e) {
log.error("", e);
}
}
}
// jdOrderManager.jdInterfaceByWarehouse();
}
@SingleTaskLock(timeout = TASK_LOCK_TIMEOUT, value = TASK_LOCK_VALUE)
public void jdReceiveOrder() {
log.debug("同步运单号开始");
jdOrderManager.createJdOlTransOrder();
}
}
| true |
12d27a87eb229b4a4b9da4c5d2f9214c562eda3b | Java | Piochat/Tarea_Restful_Java | /src/main/java/negocio/DibujanteJson.java | UTF-8 | 3,275 | 2.578125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package negocio;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import database.ConsultasDibujante;
import java.util.List;
import modelo.Autor;
/**
*
* @author georg
*/
public class DibujanteJson {
public String datosDibujantes() {
ObjectMapper mapper = new ObjectMapper();
String retorno = "Error";
ConsultasDibujante consulta = new ConsultasDibujante();
List<Autor> editoriales = consulta.selecDibujante("");
try {
retorno = mapper.writeValueAsString(editoriales);
} catch (JsonProcessingException e) {
System.err.println("Dibujante Json " + e.getMessage());
System.err.println(e.toString());
}
return retorno;
}
public String addDibujante(Autor ed) {
ObjectMapper mapper = new ObjectMapper();
String retorno = "";
ConsultasDibujante consulta = new ConsultasDibujante();
try {
if (consulta.insertarDibujante(ed).equals("Insert Exitoso")) {
retorno = "Isnertado";
}
} catch (Exception e) {
System.err.println("Dibujante Json " + e.getMessage());
System.err.println(e.toString());
retorno = "Error";
}
return retorno;
}
public String dibujanteById(String id) {
ObjectMapper mapper = new ObjectMapper();
String retorno = "Error";
ConsultasDibujante consulta = new ConsultasDibujante();
List<Autor> editoriales = consulta.selecDibujante("id_dibujante=" + id);
try {
retorno = mapper.writeValueAsString(editoriales);
} catch (JsonProcessingException e) {
System.err.println("Dibujante Json " + e.getMessage());
System.err.println(e.toString());
}
return retorno;
}
public String modDibujante(Autor ed) {
ObjectMapper mapper = new ObjectMapper();
String retorno = "";
ConsultasDibujante consulta = new ConsultasDibujante();
try {
if (consulta.updateDibujante(ed).equals("Update Exitoso")) {
retorno = "Actualizado";
}
} catch (Exception e) {
System.err.println("Dibujante Json " + e.getMessage());
System.err.println(e.toString());
retorno = "Error";
}
return retorno;
}
public String delDibujante(Autor ed) {
ObjectMapper mapper = new ObjectMapper();
String retorno = "";
ConsultasDibujante consulta = new ConsultasDibujante();
try {
if (consulta.deleteDibujante(ed).equals("Delete Exitoso")) {
retorno = "Borrado";
}
} catch (Exception e) {
System.err.println("Dibujante Json " + e.getMessage());
System.err.println(e.toString());
retorno = "Error";
}
return retorno;
}
}
| true |
999ae018745d0c66c9a8225242594d771d03866f | Java | adgadhiya/MyFirstProjects | /app/src/main/java/info/androidhive/slidingmenu/Data_receiver_Fragment.java | UTF-8 | 885 | 2.25 | 2 | [] | no_license | package info.androidhive.slidingmenu;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Data_receiver_Fragment extends Fragment {
TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_data_receiver_, container, false);
textView = (TextView)view.findViewById(R.id.received_data);
textView.setVisibility(View.GONE);
return view;
}
public void updateInfo(String name){
textView.setText("Welcome " +name);
textView.setVisibility(View.VISIBLE);
}
}
| true |
ee1d6bfc3660794420826c29f4e7ebc96f072028 | Java | Hameleon80/FinalProject | /src/ua/nure/ahtirskiy/finalProject/tests/FlightTest.java | UTF-8 | 763 | 2.671875 | 3 | [] | no_license | package ua.nure.ahtirskiy.finalProject.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import ua.nure.ahtirskiy.finalProject.entity.Flight;
/**
* Testing method isEmpty() from class Flight.
*
* @author Y.Ahtirskiy
**/
public class FlightTest {
Flight flight;
Flight flightNotEmpty;
@Before
public void init() {
flight = new Flight();
flightNotEmpty = new Flight();
flightNotEmpty.setName("Test");
}
@After
public void after() {
flight = null;
}
@Test
public void testFlightIsEmptyTrue() {
assertEquals(true, flight.isEmpty());
}
@Test
public void testFlightIsEmptyFalse() {
assertEquals(false, flightNotEmpty.isEmpty());
}
}
| true |
fe20a938390a0ce8ea5f606298e834cb2afdb21c | Java | johnaohara/hqlParsing | /src/orm_5/java/org/jboss/perf/ORM5HQLParser.java | UTF-8 | 879 | 1.976563 | 2 | [] | no_license | package org.jboss.perf;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.collections.AST;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.hql.internal.ast.HqlParser;
/**
* Created by johara on 25/01/17.
*/
public class ORM5HQLParser implements HQLParser {
@Override
public Object parseHQL(String hqlString) {
HqlParser parser = HqlParser.getInstance( hqlString );
//TODO: Filters
// parser.setFilter( filter );
AST ast = null;
try {
parser.statement();
ast = parser.getAST();
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
return ast;
}
@Override
public void configure(SessionFactoryImplementor sessionFactoryImplementor) {
}
}
| true |
02315bf62a16020c6304730607913bd1593a60ab | Java | chengzhu6/SharedPreferencePractice | /app/src/main/java/com/thoughtworks/myapplication/SPActivity.java | UTF-8 | 1,551 | 2.375 | 2 | [] | no_license | package com.thoughtworks.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SPActivity extends AppCompatActivity {
private static final String DEFAULT_VALUE = "";
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s_p_activty);
sharedPreferences = getApplicationContext()
.getSharedPreferences(String.valueOf(R.string.preferences_file_key), Context.MODE_PRIVATE);
final EditText editText = findViewById(R.id.edit_text);
setOldValue(editText);
findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String inputValue = editText.getText().toString();
saveInputValue(inputValue);
}
});
}
private void setOldValue(EditText editText) {
String oldValue = sharedPreferences.getString(String.valueOf(R.string.edit_text), DEFAULT_VALUE);
editText.getText().append(oldValue);
}
private void saveInputValue(String inputValue) {
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(String.valueOf(R.string.edit_text), inputValue);
edit.apply();
}
} | true |
c66884473804b8061f9c813de2fd0f199e917e7f | Java | somalians/stack-java-backend | /src/main/java/backend/repository/PessoaRepository.java | UTF-8 | 352 | 1.820313 | 2 | [] | no_license | package backend.repository;
import backend.model.Pessoa;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
/**
* Created by adriano on 24/02/16.
*/
@Repository
@Transactional
public interface PessoaRepository extends CrudRepository<Pessoa, Long>{}
| true |
d6025ebadd104805a23f883476616fe75b318239 | Java | zhao907219202/GreenKitchen | /src/main/java/com/zy/dto/Recipe.java | UTF-8 | 4,245 | 2.203125 | 2 | [] | no_license | package com.zy.dto;
import java.util.HashSet;
import java.util.Set;
/**
* Recipe entity. @author MyEclipse Persistence Tools
*/
public class Recipe implements java.io.Serializable {
// Fields
private Integer id;
private User user;
private String title;
private Integer collectednum;
private Integer likednum;
private Integer commentednum;
private String difficulty;
private String time;
private String timestamp;
private String description;
private String note;
private Set recipeTypes = new HashSet(0);
private Set recipeMaterials = new HashSet(0);
private Set recipeSteps = new HashSet(0);
private Set userRecipes = new HashSet(0);
private Set recipeSpices = new HashSet(0);
private Set comments = new HashSet(0);
// Constructors
/** default constructor */
public Recipe() {
}
/** minimal constructor */
public Recipe(User user, String title, String difficulty, String time,
String timestamp) {
this.user = user;
this.title = title;
this.difficulty = difficulty;
this.time = time;
this.timestamp = timestamp;
}
/** full constructor */
public Recipe(User user, String title, Integer collectednum,
Integer likednum, Integer commentednum, String difficulty,
String time, String timestamp, String description, String note,
Set recipeTypes, Set recipeMaterials, Set recipeSteps,
Set userRecipes, Set recipeSpices, Set comments) {
this.user = user;
this.title = title;
this.collectednum = collectednum;
this.likednum = likednum;
this.commentednum = commentednum;
this.difficulty = difficulty;
this.time = time;
this.timestamp = timestamp;
this.description = description;
this.note = note;
this.recipeTypes = recipeTypes;
this.recipeMaterials = recipeMaterials;
this.recipeSteps = recipeSteps;
this.userRecipes = userRecipes;
this.recipeSpices = recipeSpices;
this.comments = comments;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getCollectednum() {
return this.collectednum;
}
public void setCollectednum(Integer collectednum) {
this.collectednum = collectednum;
}
public Integer getLikednum() {
return this.likednum;
}
public void setLikednum(Integer likednum) {
this.likednum = likednum;
}
public Integer getCommentednum() {
return this.commentednum;
}
public void setCommentednum(Integer commentednum) {
this.commentednum = commentednum;
}
public String getDifficulty() {
return this.difficulty;
}
public void setDifficulty(String difficulty) {
this.difficulty = difficulty;
}
public String getTime() {
return this.time;
}
public void setTime(String time) {
this.time = time;
}
public String getTimestamp() {
return this.timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
public Set getRecipeTypes() {
return this.recipeTypes;
}
public void setRecipeTypes(Set recipeTypes) {
this.recipeTypes = recipeTypes;
}
public Set getRecipeMaterials() {
return this.recipeMaterials;
}
public void setRecipeMaterials(Set recipeMaterials) {
this.recipeMaterials = recipeMaterials;
}
public Set getRecipeSteps() {
return this.recipeSteps;
}
public void setRecipeSteps(Set recipeSteps) {
this.recipeSteps = recipeSteps;
}
public Set getUserRecipes() {
return this.userRecipes;
}
public void setUserRecipes(Set userRecipes) {
this.userRecipes = userRecipes;
}
public Set getRecipeSpices() {
return this.recipeSpices;
}
public void setRecipeSpices(Set recipeSpices) {
this.recipeSpices = recipeSpices;
}
public Set getComments() {
return this.comments;
}
public void setComments(Set comments) {
this.comments = comments;
}
} | true |
53cec23205c709f5aa4ae8771eeacd2b2c5f91a8 | Java | Braden98/Algorithm | /Sort/Heap.java | UTF-8 | 2,463 | 4.03125 | 4 | [] | no_license | package Algorithm.Sort;
/**
* @Description (二叉)堆的设计与实现
* 堆是一棵完全二叉树,且每个节点大于其任意一个孩子,故其增删效率高
* 堆在内部由 数组线性表 实现,也可以改为其他数据结构,上述规约不变即可
* @Author ubique
* @Date 2019/5/16 11:44 AM
*/
public class Heap <E extends Comparable<E>> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
public Heap(){
}
public Heap(E[] objects){
for(int i=0;i<objects.length;i++){
add(objects[i]);
}
}
public void add(E newObject) {
list.add(newObject);
int cur = list.size() - 1;
while (cur > 0) {
//得到父节点在数组线性表中的 Index
int parentIndex = (cur - 1) / 2;
//如果子节点比父节点大,就交换
if (list.get(cur).compareTo(
list.get(parentIndex)) > 0) {
E temp = list.get(cur);
list.set(cur, list.get(parentIndex));
list.set(parentIndex, temp);
} else {
break;
}
cur = parentIndex;
}
}
public E remove(){
if(list.size()==0){
return null;
}
E removeObject = list.get(0);
//数组的配套操作,最后一个元素调到首位,然后开始调整二叉树成 Heap
list.set(0,list.get(list.size()-1));
list.remove(list.size()-1);
int cur=0;
while (cur<list.size()){
int leftChildIndex = 2*cur+1;
int rightChildIndex = 2*cur+2;
if(leftChildIndex>=list.size()){
//此时已经是 Heap
break;
}
int maxIndex=leftChildIndex;
if(rightChildIndex<list.size()){
if(list.get(maxIndex).compareTo(
list.get(rightChildIndex))<0){
maxIndex=rightChildIndex;
}
}
if(list.get(cur).compareTo(list.get(maxIndex))<0){
E temp = list.get(maxIndex);
list.set(maxIndex,list.get(cur));
list.set(cur,temp);
cur=maxIndex;
}
else {
break;
}
}
return removeObject;
}
public int getSize(){
return list.size();
}
}
| true |
c32410f1dc6ca9b2c572310ff5f65ccf6fccef7d | Java | YingYou/wallgame | /FlowAuto-22/app/src/main/java/com/yw/FlowAuto/view/SharePageAdapter.java | UTF-8 | 2,118 | 2.34375 | 2 | [] | no_license | /**
* @Title: BusinessDetailsAdapter.java
* @Package com.bw.mmd.business.adapter
* @Description: TODO(用一句话描述该文件做什么)
* @author YangWei
* @date 2014-7-17 下午8:19:18
* @version V1.0
*/
package com.yw.FlowAuto.view;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
*/
public class SharePageAdapter extends FragmentStatePagerAdapter {
public ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
public String[] mStringslist = null;
public SharePageAdapter(FragmentManager fm, Context context) {
super(fm);
}
/* (non-Javadoc)
* @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
@Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return mFragments.get(arg0);
}
/* (non-Javadoc)
* @see android.support.v4.view.PagerAdapter#getCount()
*/
@Override
public int getCount() {
return 2;
}
/* (non-Javadoc)
* @see android.support.v4.view.PagerAdapter#getPageTitle(int)
*/
@Override
public CharSequence getPageTitle(int position) {
return null;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
super.destroyItem(container, position, object);
}
/**
* @Title: addFragment
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param 设定文件
* @return void 返回类型
* @throws
*/
public void addFragment(Fragment fragment,String title/*String[] lsit*/) {
mFragments.add(fragment);
// mStringslist.add(title);
notifyDataSetChanged();
}
public void addFragment(ArrayList<Fragment> list){
mFragments = list;
notifyDataSetChanged();
}
public void Clear() {
mFragments.clear();
}
}
| true |
58415c46a98ac4eda9e7ce78fd317083182104ec | Java | Halatak/33_Projet_Immo_WS | /src/main/java/fr/adaming/model/BienLocation.java | WINDOWS-1250 | 2,709 | 2.40625 | 2 | [] | no_license | package fr.adaming.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@DiscriminatorValue(value = "Location")
@Entity
public class BienLocation extends BienImmobilier implements Serializable {
private static final long serialVersionUID = 1L;
// Attributs
private double caution;
private double loyerMensuel;
private String typeBail;
// garniture ==> meubl = true, non-meubl = false
private boolean garniture;
// Constructeurs
public BienLocation() {
super();
}
public BienLocation(String statut, Date dateSoumission, Date dateDispo, double revenu, String coordonneePersAgence,
int nombreChambres, String latitude, String longitude, Adresse adresse, double caution, double loyerMensuel,
String typeBail, boolean garniture) {
super(statut, dateSoumission, dateDispo, revenu, coordonneePersAgence, nombreChambres, latitude, longitude,
adresse);
this.caution = caution;
this.loyerMensuel = loyerMensuel;
this.typeBail = typeBail;
this.garniture = garniture;
}
public BienLocation(int id, String statut, Date dateSoumission, Date dateDispo, double revenu,
String coordonneePersAgence, int nombreChambres, String latitude, String longitude, Adresse adresse,
double caution, double loyerMensuel, String typeBail, boolean garniture) {
super(id, statut, dateSoumission, dateDispo, revenu, coordonneePersAgence, nombreChambres, latitude, longitude,
adresse);
this.caution = caution;
this.loyerMensuel = loyerMensuel;
this.typeBail = typeBail;
this.garniture = garniture;
}
// Getters & setters
public double getCaution() {
return caution;
}
public void setCaution(double caution) {
this.caution = caution;
}
public double getLoyerMensuel() {
return loyerMensuel;
}
public void setLoyerMensuel(double loyerMensuel) {
this.loyerMensuel = loyerMensuel;
}
public String getTypeBail() {
return typeBail;
}
public void setTypeBail(String typeBail) {
this.typeBail = typeBail;
}
public boolean isGarniture() {
return garniture;
}
public void setGarniture(boolean garniture) {
this.garniture = garniture;
}
// To String
@Override
public String toString() {
return "BienLocation [caution=" + caution + ", loyerMensuel=" + loyerMensuel + ", typeBail=" + typeBail
+ ", garniture=" + garniture + ", id=" + id + ", statut=" + statut + ", dateSoumission="
+ dateSoumission + ", dateDispo=" + dateDispo + ", revenu=" + revenu + ", coordonneePersAgence="
+ coordonneePersAgence + ", nombreChambres=" + nombreChambres + "]";
}
}
| true |
f5c4b1ca79cae18baf5cc22aeb44ed6d00c1f2c4 | Java | trowqe/phoneshop | /core/src/main/java/com/es/core/service/order/OrderServiceImpl.java | UTF-8 | 2,570 | 2.375 | 2 | [] | no_license | package com.es.core.service.order;
import com.es.core.dao.order.OrderDao;
import com.es.core.model.cart.Cart;
import com.es.core.model.order.Order;
import com.es.core.model.order.OrderItem;
import com.es.core.model.order.OrderStatus;
import com.es.core.model.order.OutOfStockException;
import com.es.core.service.cart.CartService;
import com.es.core.service.phone.PhoneService;
import com.es.core.service.stock.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
@Value("${delivery.price}")
private BigDecimal deliveryPrice;
@Autowired
private PhoneService phoneService;
@Autowired
private CartService cartService;
@Autowired
private StockService stockService;
@Autowired
private OrderDao orderDao;
@Override
public Order getOrderByOrderId(Long orderId) {
return orderDao.getOrder(orderId).orElse(null);
}
@Override
public Order createOrder(Cart cart) {
Order order = new Order();
order.setOrderItems(setOrderItemsFromCart(cart, order));
order.setSubtotal(cartService.countTotalSum());
order.setTotalPrice(cartService.countTotalSum().add(deliveryPrice));
order.setDeliveryPrice(deliveryPrice);
order.setStatus(OrderStatus.NEW);
return order;
}
private List<OrderItem> setOrderItemsFromCart(Cart cart, Order order) {
List<OrderItem> orderItems = new ArrayList<>();
cart.getItems().forEach((k, v) -> {
OrderItem orderItem = createOrderItem(k, v, order);
try {
stockService.checkStock(orderItem);
} catch (OutOfStockException e) {
orderItem.setQuantity(0L);
}
orderItems.add(orderItem);
});
return orderItems;
}
private OrderItem createOrderItem(Long phoneId, Long quantity, Order order) {
OrderItem orderItem = new OrderItem();
orderItem.setQuantity(quantity);
orderItem.setOrder(order);
orderItem.setPhone(phoneService.get(phoneId));
return orderItem;
}
@Override
public Long placeOrder(Order order) throws OutOfStockException {
order.getOrderItems()
.forEach(i->stockService.checkStock(i));
return orderDao.saveOrder(order);
}
}
| true |
9e37ec79ef160f3888d6a55a1daefd5295252e52 | Java | Cfilipovic/Bukkit | /ShopAPI/src/com/cfil360/shopapi/ShopAPI.java | UTF-8 | 1,084 | 2.328125 | 2 | [] | no_license | package com.cfil360.shopapi;
import com.cfil360.shopapi.Objects.Purchase;
import com.cfil360.shopapi.Util.InventoryHandler;
import com.cfil360.shopapi.Util.MySQL;
import com.cfil360.shopapi.Util.PurchaseInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
/**
* Created by connor on 6/18/2014.
*/
public class ShopAPI extends JavaPlugin {
public static MySQL mySQL;
public void onEnable() {
mySQL = new MySQL("localhost", "r", "pass", "db");
}
public static void insertPurchase(Player player, String name, String item, int price) {
mySQL.insertPurchase(player, name, item, price);
}
public static Inventory getPurchaseInventory(Player player) { return PurchaseInventory.getPurchaseInventory(player); }
public static ArrayList<Purchase> getPurchases(Player player) {
return mySQL.getPurchases(player);
}
public static InventoryHandler getInventoryHandler() {
return InventoryHandler.getInstance();
}
}
| true |
6b671148125c1da80c8778969cbf06bc2761918d | Java | sivapolam/365Carnival | /app/src/main/java/com/techplicit/mycarnival/ui/activities/TestActivity.java | UTF-8 | 411 | 1.609375 | 2 | [] | no_license | package com.techplicit.mycarnival.ui.activities;
import android.os.Bundle;
import com.techplicit.mycarnival.R;
/**
* Created by pnaganjane001 on 25/01/16.
*/
public class TestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.fragment_about, frameLayout);
}
}
| true |
0bbfe616f77ff5ef08e4b9726cd72503e77817fd | Java | gcdd1993/demos | /demo-java-design-pattern/src/main/java/bridgePattern/exercise/Client.java | UTF-8 | 308 | 1.664063 | 2 | [] | no_license | package bridgePattern.exercise;
/**
* @author: gaochen
* Date: 2019/1/21
*/
public class Client {
public static void main(String[] args) {
Export export = new XMLExport(new MysqlType());
export.export();
export = new PDFExport(new PGType());
export.export();
}
}
| true |
ce099e271708db073a4f541742632670068fa5aa | Java | esther9998/StreetFighter_Java | /src/Ryu.java | UTF-8 | 5,989 | 2.4375 | 2 | [] | no_license | import java.awt.Graphics;
import java.awt.Image;
import java.awt.KeyEventPostProcessor;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Ryu extends IJPanel implements Runnable {
Image source;
Image source2;
Image[] sprite;
Image[] kick;
Image[] death;
Image[] back;
Image[] go;
Image[] base;
Image[] punch;
Image[] hit;
Image[] punch2;
Image image;
Ryu() {
try {
source = ImageIO.read(new File("actRyu.png"));
source2 = ImageIO.read(new File("actRyu1.png"));
kick = new Image[11];
for (int i = 0; i < kick.length; i++) {
Image t = new BufferedImage(130, 90, BufferedImage.TRANSLUCENT); // 4512,77
t.getGraphics().drawImage(source2, 0, 0, 130, 90, 125 * i, 1406, 125 + 125 * i, 1406 + 85, this);
kick[i] = t;
}
death = new Image[7];
for (int i = 0; i < death.length; i++) {
Image t = new BufferedImage(170, 90, BufferedImage.TRANSLUCENT); // 4512,77
t.getGraphics().drawImage(source, 0, 0, 170, 90, 168 * i, 4512, 162 + 168 * i, 4512 + 75, this);
death[i] = t;
}
back = new Image[11];
for (int i = 0; i < back.length; i++) {
Image t = new BufferedImage(110, 115, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 110, 115, 113 * i, 553, 113 + 113 * i, 553 + 113, this);
back[i] = t;
}
go = new Image[11];
for (int i = 0; i < go.length; i++) {
Image t = new BufferedImage(110, 115, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 110, 115, 113 * i, 437, 113 + 113 * i, 437 + 113, this);
go[i] = t;
}
base = new Image[5];
for (int i = 0; i < base.length; i++) {
Image t = new BufferedImage(80, 120, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 80, 120, 79 * i, 0, 79 + 79 * i, 115, this);
base[i] = t;
}
punch = new Image[8];
for (int i = 0; i < punch.length; i++) {
Image t = new BufferedImage(110, 120, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 110, 120, 111 * i, 1928, 110 + 110 * i, 1928 + 116, this);
punch[i] = t;
}
hit = new Image[7];
for (int i = 0; i < hit.length; i++) {
Image t = new BufferedImage(95, 115, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 95, 115, 1000 + 101 * i, 4000, 1000 + 101 + 101 * i, 4119, this);
hit[i] = t;
}
punch2 = new Image[11];
for (int i = 0; i < punch2.length; i++) {
Image t = new BufferedImage(90, 133, BufferedImage.TRANSLUCENT);
t.getGraphics().drawImage(source, 0, 0, 90, 133, 90 * i, 670, 90 + 90 * i, 670 + 133, this);
punch2[i] = t;
}
} catch (IOException e) {
System.out.println("image load fail");
}
Thread t = new Thread(this);
t.start();
}
protected void paintComponent(Graphics g) {
setOpaque(false);
if (image != null)
g.drawImage(image, 45, 0, 162, getHeight(), this);
super.paintComponent(g);
}
public void run() {
int cnt = 0;
while (true) {
if (di == 0) {
image = base[cnt];
cnt++;
cnt %= base.length;
if(di != 0) {
cnt = 0;
break;
}
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
updateUI();
} else if (di == 1) {
for (int i = 0; i < go.length; i++) {
image = go[cnt];
cnt++; // 1 // 1
cnt %= go.length; // 1 // 0
if (di != 1) {
cnt = 0;
break;
}
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
} else if (di == 2) {
for (int i = 0; i < back.length; i++) {
image = back[cnt];
cnt++; // 1 // 1
cnt %= back.length; // 1 // 0
if (di != 2) {
cnt = 0;
break;
}
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
} else if (di == 3) {
for (int i = 0; i < punch.length; i++) {
image = punch[cnt];
cnt++; // 1 // 1
cnt %= punch.length; // 1 // 0
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
di = 0;
cnt = 0;
} else if (di == 4) {
for (int i = 0; i < kick.length; i++) {
image = kick[cnt];
cnt++; // 1 // 1
cnt %= kick.length; // 1 // 0
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
di = 0;
cnt = 0;
} else if (di == 5) {
for (int i = 0; i < punch2.length; i++) {
image = punch2[cnt];
cnt++; // 1 // 1
cnt %= punch2.length; // 1 // 0
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
di = 0;
cnt = 0;
} else if (di == 6) {
for (int i = 0; i < hit.length; i++) {
image = hit[cnt];
cnt++; // 1 // 1
cnt %= hit.length; // 1 // 0
if (di != 6) {
cnt = 0;
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
di = 0;
cnt = 0;
} else if (di == 7) {
for (int i = 0; i < death.length; i++) {
image = death[cnt];
cnt++;
if(cnt == death.length) {
cnt--;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateUI();
}
}
}
}
}
| true |
4895ee7be7c00a804fec1dbdc376c12f38e22024 | Java | rtaneza/Carbs | /src/com/gmail/taneza/ronald/carbs/myfoods/MyFoodDetailsActivity.java | ISO-8859-10 | 9,649 | 1.890625 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2013 Ronald Taeza
*
* 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.gmail.taneza.ronald.carbs.myfoods;
import java.util.Locale;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.gmail.taneza.ronald.carbs.R;
import com.gmail.taneza.ronald.carbs.common.CarbsApp;
import com.gmail.taneza.ronald.carbs.common.FoodDbAdapter;
import com.gmail.taneza.ronald.carbs.common.FoodItem;
import com.gmail.taneza.ronald.carbs.common.FoodItemInfo;
public class MyFoodDetailsActivity extends ActionBarActivity {
public static final String NEW_FOOD_DEFAULT_NAME = "My food";
public static final String NEW_FOOD_DEFAULT_UNIT_TEXT = "g";
public static final int NEW_FOOD_DEFAULT_QUANTITY_PER_UNIT = 100;
public static final int NEW_FOOD_DEFAULT_CARBS = 0;
public enum Mode {
NewFood,
EditFood
}
public final static int MY_FOOD_RESULT_OK = RESULT_OK;
public final static int MY_FOOD_RESULT_CANCELED = RESULT_CANCELED;
public final static int MY_FOOD_RESULT_DELETE = RESULT_FIRST_USER;
public final static String MY_FOOD_ITEM_MESSAGE = "com.gmail.taneza.ronald.carbs.MY_FOOD_ITEM_MESSAGE";
public final static String MY_FOOD_ITEM_INFO_RESULT = "com.gmail.taneza.ronald.carbs.MY_FOOD_ITEM_INFO_RESULT";
public final static String MY_FOOD_ITEM_RESULT = "com.gmail.taneza.ronald.carbs.MY_FOOD_ITEM_RESULT";
public final static String MY_FOOD_ACTIVITY_MODE_MESSAGE = "com.gmail.taneza.ronald.carbs.MY_FOOD_ACTIVITY_MODE_MESSAGE";
private FoodDbAdapter mFoodDbAdapter;
private FoodItem mFoodItem;
private TextView mFoodNameTextView;
private EditText mQuantityEditText;
private TextView mNumCarbsTextView;
private Spinner mQuantityUnitTextSpinner;
private Mode mMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_food_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFoodDbAdapter = ((CarbsApp)getApplication()).getFoodDbAdapter();
// Get the message from the intent
Intent intent = getIntent();
mFoodItem = intent.getParcelableExtra(MY_FOOD_ITEM_MESSAGE);
FoodItemInfo foodItemInfo;
Mode mode = Mode.values()[intent.getIntExtra(MY_FOOD_ACTIVITY_MODE_MESSAGE, Mode.NewFood.ordinal())];
mMode = mode;
if (mode == Mode.NewFood) {
foodItemInfo = new FoodItemInfo(mFoodItem, NEW_FOOD_DEFAULT_NAME, NEW_FOOD_DEFAULT_QUANTITY_PER_UNIT, NEW_FOOD_DEFAULT_CARBS, NEW_FOOD_DEFAULT_UNIT_TEXT);
} else {
foodItemInfo = mFoodDbAdapter.getFoodItemInfo(mFoodItem);
setTitle(R.string.title_activity_my_food_edit);
Button okButton = (Button) findViewById(R.id.my_food_ok_button);
okButton.setText(R.string.save_food_details);
}
mFoodNameTextView = (TextView) findViewById(R.id.my_food_name);
mFoodNameTextView.setText(foodItemInfo.getName());
// Request focus and show soft keyboard automatically
mFoodNameTextView.requestFocus();
getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mQuantityEditText = (EditText) findViewById(R.id.my_food_quantity_edit);
mQuantityEditText.setText(Integer.toString(foodItemInfo.getQuantityPerUnit()));
mQuantityUnitTextSpinner = (Spinner) findViewById(R.id.my_food_quantity_unit_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this,
R.array.quantity_unit_text_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mQuantityUnitTextSpinner.setAdapter(arrayAdapter);
mQuantityUnitTextSpinner.setSelection(arrayAdapter.getPosition(foodItemInfo.getUnitText()));
mNumCarbsTextView = (TextView) findViewById(R.id.my_food_carbs);
// Display decimal place only when non-zero, so it's easier to edit
String numCarbsString;
float numCarbs = foodItemInfo.getNumCarbsInGrams();
if (numCarbs == (int)numCarbs) {
numCarbsString = String.format(Locale.getDefault(), "%.0f", numCarbs);
} else {
numCarbsString = String.format(Locale.getDefault(), "%.1f", numCarbs);
}
mNumCarbsTextView.setText(numCarbsString);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my_food_details, menu);
if (mMode == Mode.NewFood) {
MenuItem menuItem = menu.findItem(R.id.menu_my_food_delete);
menuItem.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_my_food_delete:
deleteItem();
return true;
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void deleteItem() {
new AlertDialog.Builder(this)
.setMessage(R.string.delete_item_from_my_foods)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
Intent data = getIntent();
data.putExtra(MY_FOOD_ITEM_RESULT, (Parcelable)mFoodItem);
setResult(MY_FOOD_RESULT_DELETE, data);
finish();
Toast.makeText(getApplicationContext(),
getText(R.string.food_deleted_from_my_foods),
Toast.LENGTH_SHORT)
.show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
public void cancel(View v) {
setResult(MY_FOOD_RESULT_CANCELED);
finish();
}
public void addOrUpdate(View v) {
String foodName = mFoodNameTextView.getText().toString().trim();
int exceptId = 0;
if (mMode == Mode.EditFood) {
exceptId = mFoodItem.getId();
}
if (mFoodDbAdapter.myFoodNameExists(foodName, exceptId)) {
mFoodNameTextView.setError(getText(R.string.my_food_name_exists_error));
return;
}
int quantityPerUnit;
try {
quantityPerUnit = Integer.parseInt(mQuantityEditText.getText().toString());
}
catch (NumberFormatException e) {
mQuantityEditText.setError(getText(R.string.my_food_enter_a_number));
return;
}
Float numCarbsInGramsPerUnit;
try {
numCarbsInGramsPerUnit = Float.parseFloat(mNumCarbsTextView.getText().toString());
}
catch (NumberFormatException e) {
mNumCarbsTextView.setError(getText(R.string.my_food_enter_a_number));
return;
}
FoodItemInfo foodItemInfo = new FoodItemInfo(mFoodItem,
foodName,
quantityPerUnit,
numCarbsInGramsPerUnit,
mQuantityUnitTextSpinner.getSelectedItem().toString());
Intent data = getIntent();
data.putExtra(MY_FOOD_ITEM_INFO_RESULT, (Parcelable)foodItemInfo);
setResult(MY_FOOD_RESULT_OK, data);
finish();
}
}
| true |
ae428770637061b25ba1cd66a1bbdeecf9cbfcb2 | Java | artur-android/TestSamsungRecorder | /app/src/main/java/com/sec/android/app/voicenote/p007ui/view/PlaySpeedPopup.java | UTF-8 | 9,292 | 1.6875 | 2 | [] | no_license | package com.sec.android.app.voicenote.p007ui.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sec.android.app.voicenote.C0690R;
import com.sec.android.app.voicenote.provider.Log;
import com.sec.android.app.voicenote.provider.SALogProvider;
import java.util.Locale;
/* renamed from: com.sec.android.app.voicenote.ui.view.PlaySpeedPopup */
public class PlaySpeedPopup implements IPopupView {
private static final String TAG = "PlaySpeedPopup";
private static PlaySpeedPopup sPlaySpeedPopup;
private int mAnchorMargin;
private View mAnchorView;
private int[] mLocalParentPos = new int[2];
private int mMaxStep;
private TextView mPlaySpeedText;
private TextView mPlaySpeedTextDefault;
private PopupWindow mPopupPlaySpeed;
/* access modifiers changed from: private */
// public SeslSeekBar mSeekBar;
/* access modifiers changed from: private */
public OnPlaySpeedChangeListener mVolumeChangeListener = null;
/* renamed from: com.sec.android.app.voicenote.ui.view.PlaySpeedPopup$OnPlaySpeedChangeListener */
public interface OnPlaySpeedChangeListener {
void onPlaySpeedChange(float f);
}
public static synchronized PlaySpeedPopup getInstance(Context context, View view, int i) {
PlaySpeedPopup playSpeedPopup;
synchronized (PlaySpeedPopup.class) {
if (sPlaySpeedPopup == null) {
sPlaySpeedPopup = new PlaySpeedPopup(context, view, i);
}
playSpeedPopup = sPlaySpeedPopup;
}
return playSpeedPopup;
}
private PlaySpeedPopup(final Context context, View view, int i) {
Log.m19d(TAG, "create");
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(C0690R.layout.play_speed_popup, (ViewGroup) null);
this.mPopupPlaySpeed = new PopupWindow(linearLayout, -1, -2) {
public void dismiss() {
PlaySpeedPopup.this.dismiss(false);
super.dismiss();
}
};
this.mPopupPlaySpeed.setWidth(i - context.getResources().getDimensionPixelOffset(C0690R.dimen.play_speed_popup_side_margin));
this.mPopupPlaySpeed.setContentView(linearLayout);
this.mPopupPlaySpeed.setOutsideTouchable(true);
this.mPopupPlaySpeed.setElevation((float) context.getResources().getDimensionPixelOffset(C0690R.dimen.play_speed_popup_bg_elevation));
this.mAnchorView = view;
this.mAnchorMargin = context.getResources().getDimensionPixelSize(C0690R.dimen.play_speed_popup_anchor_margin);
this.mMaxStep = Math.round(15.0f);
linearLayout.measure(0, 0);
this.mPopupPlaySpeed.setFocusable(true);
// this.mSeekBar = (SeslSeekBar) this.mPopupPlaySpeed.getContentView().findViewById(C0690R.C0693id.play_speed_popup_seekbar);
// this.mSeekBar.setMax(this.mMaxStep);
// this.mSeekBar.setThumbTintList(colorToColorStateList(context, C0690R.C0691color.play_speed_popup_seekbar_progress_color));
// this.mSeekBar.setOnSeekBarChangeListener(new SeslSeekBar.OnSeekBarChangeListener(context) {
// final /* synthetic */ Context val$context;
//
// public void onStopTrackingTouch(SeslSeekBar seslSeekBar) {
// }
//
// {
// this.val$context = r2;
// }
//
// public void onProgressChanged(SeslSeekBar seslSeekBar, int i, boolean z) {
// Log.m26i(PlaySpeedPopup.TAG, "onProgressChanged progress : " + i + " fromUser : " + z);
// float access$000 = PlaySpeedPopup.this.convertSpeed(i);
// SeslSeekBar access$100 = PlaySpeedPopup.this.mSeekBar;
// access$100.setContentDescription(this.val$context.getResources().getString(C0690R.string.play_speed_controller) + ", " + String.format(Locale.getDefault(), "%.1f", new Object[]{Float.valueOf(access$000)}));
// PlaySpeedPopup.this.setSpeedText(access$000);
// if (PlaySpeedPopup.this.mVolumeChangeListener != null) {
// PlaySpeedPopup.this.mVolumeChangeListener.onPlaySpeedChange(access$000);
// }
// }
//
// public void onStartTrackingTouch(SeslSeekBar seslSeekBar) {
// SALogProvider.insertSALog(context.getResources().getString(C0690R.string.screen_player_comm), context.getResources().getString(C0690R.string.event_player_speed_updown));
// }
// });
this.mPlaySpeedText = (TextView) linearLayout.findViewById(C0690R.C0693id.play_speed_text);
this.mPlaySpeedTextDefault = (TextView) linearLayout.findViewById(C0690R.C0693id.play_speed_text_default);
this.mPlaySpeedTextDefault.setText(String.format(Locale.getDefault(), "%.1f", new Object[]{Double.valueOf(1.0d)}));
}
public void show() {
PopupWindow popupWindow;
Log.m19d(TAG, "show");
if (this.mAnchorView == null || (popupWindow = this.mPopupPlaySpeed) == null) {
throw new IllegalStateException("Play speed panel internal state error occur");
}
final View contentView = popupWindow.getContentView();
int[] iArr = new int[2];
this.mAnchorView.getLocationInWindow(iArr);
int measuredHeight = (iArr[1] - contentView.getMeasuredHeight()) - this.mAnchorMargin;
this.mPopupPlaySpeed.showAtLocation(this.mAnchorView, 8388659, this.mLocalParentPos[0], measuredHeight);
contentView.postDelayed(new Runnable() {
private final /* synthetic */ View f$1;
{
this.f$1 = contentView;
}
public final void run() {
PlaySpeedPopup.this.lambda$show$0$PlaySpeedPopup(this.f$1);
}
}, 0);
}
public /* synthetic */ void lambda$show$0$PlaySpeedPopup(View view) {
// if (this.mSeekBar != null) {
// RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(C0690R.C0693id.play_speed_popup_bar_layout);
// FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) relativeLayout.getLayoutParams();
// int measuredWidth = this.mSeekBar.getMeasuredWidth();
// if (view.getResources().getConfiguration().getLayoutDirection() == 1) {
// layoutParams.rightMargin = ((measuredWidth / this.mMaxStep) - 2) * 10;
// } else {
// layoutParams.leftMargin = (measuredWidth / this.mMaxStep) * 5;
// }
// relativeLayout.setLayoutParams(layoutParams);
// if (relativeLayout.getVisibility() == 8) {
// relativeLayout.setVisibility(0);
// }
// }
}
public void dismiss(boolean z) {
Log.m19d(TAG, "dismiss");
PopupWindow popupWindow = this.mPopupPlaySpeed;
if (popupWindow != null) {
if (z) {
popupWindow.dismiss();
}
this.mPopupPlaySpeed = null;
}
// SeslSeekBar seslSeekBar = this.mSeekBar;
// if (seslSeekBar != null) {
// seslSeekBar.setOnSeekBarChangeListener((SeslSeekBar.OnSeekBarChangeListener) null);
// this.mSeekBar = null;
// }
this.mVolumeChangeListener = null;
sPlaySpeedPopup = null;
}
public boolean isShowing() {
PopupWindow popupWindow = this.mPopupPlaySpeed;
return popupWindow != null && popupWindow.isShowing();
}
public void setValue(float f) {
int round = Math.round((f - 0.5f) * 10.0f);
if (round < 0) {
round = 0;
} else {
int i = this.mMaxStep;
if (round > i) {
round = i;
}
}
Log.m19d(TAG, "setValue value : " + f + " v : " + round);
// this.mSeekBar.setProgress(round);
setSpeedText(f);
}
/* access modifiers changed from: private */
public void setSpeedText(float f) {
this.mPlaySpeedText.setText(String.format(Locale.getDefault(), "%.1f", new Object[]{Float.valueOf(f)}) + "x");
}
public void setOnVolumeChangeListener(OnPlaySpeedChangeListener onPlaySpeedChangeListener) {
this.mVolumeChangeListener = onPlaySpeedChangeListener;
}
/* access modifiers changed from: private */
public float convertSpeed(int i) {
float f = (float) i;
if (f < 0.0f) {
f = 0.0f;
} else {
int i2 = this.mMaxStep;
if (f > ((float) i2)) {
f = (float) i2;
}
}
float f2 = (0.1f * f) + 0.5f;
Log.m19d(TAG, "convertSpeed position : " + i + " step : " + f + " speed : " + f2);
return f2;
}
private ColorStateList colorToColorStateList(Context context, int i) {
return new ColorStateList(new int[][]{new int[0]}, new int[]{context.getColor(i)});
}
public void setLocalPositionParent(int[] iArr) {
this.mLocalParentPos = iArr;
}
}
| true |
2ff29119d884f8e1c529fc495603d1bba31efece | Java | hectorggp/BUYnRATE | /src/com/buynrate/apps/android/BnRApplication.java | UTF-8 | 260 | 1.71875 | 2 | [] | no_license | package com.buynrate.apps.android;
import android.app.Application;
import android.util.Log;
public class BnRApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Log.d("BnRApplicaton", "Applicatoni Start!");
}
}
| true |
9fc7b16d4d6491b1dbccf99372b06065cbd13aa7 | Java | thanhnguyen2112/JavaApplication_AdvancedJava | /src/Generics/MyList.java | UTF-8 | 235 | 2.875 | 3 | [] | no_license | package Generics;
public class MyList {
private final Object [] items = new Object [10];
private int count;
public void add(Object item) {
items[count++] = item;
}
public Object get (int index) {
return items[index];
}
}
| true |
d93d3fc74711c62c1ac229d0ce0ec4f9b6fe1e53 | Java | ArturchiKGilyazov/5_semestr | /Stickman-master/Stickman-master/src/main/java/request_type/FriendRequests.java | UTF-8 | 2,887 | 2.28125 | 2 | [] | no_license | package request_type;
import DB.FRIEND_DB;
import exceptions.UnknownTypeOfRequest;
import managers.Managers;
import com.google.protobuf.MessageLite;
import friend.Friend;
import proto_files.DangerStickman;
import proto_files.FriendMessages;
import user.User;
import java.sql.SQLException;
import java.util.List;
import java.util.NoSuchElementException;
public class FriendRequests implements FriendRequests_I{
private final FRIEND_DB friendDB = new FRIEND_DB();
@Override
public DangerStickman.PacketWrapper execute(MessageLite _request) throws UnknownTypeOfRequest {
DangerStickman.PacketWrapper.FriendWrapper request = (DangerStickman.PacketWrapper.FriendWrapper) _request;
if(request.hasFindFriendsRequest()){
}
if(request.hasMakeFriendsRequest()){
}
if(request.hasConfirmationFriendsRequest()){
}
if(request.hasRemoveFriendRequest()){
}
if(request.hasUpdateFriendsListRequest()){
}
throw new UnknownTypeOfRequest();
}
private FriendMessages.FindFriendsResponse.Builder FindFriends(String find_query){
List<Friend> finded = null;
try {
finded = friendDB.FindAllFriend(find_query);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
FriendMessages.FindFriendsResponse.Builder builder = FriendMessages.FindFriendsResponse.newBuilder();
finded.forEach(e -> builder.addFriends((FriendMessages.friend) e.Serialize()));
return builder;
}
private void MakeRequestForFriend(Integer from, Integer to){
friendDB.MakeRequestForFriend(from.toString(), to.toString());
User toUser = null;
User fromUser = null;
try {
toUser = Managers.getUserManager().GetUser(to);
fromUser = Managers.getUserManager().GetUser(from);
} catch (NoSuchElementException e){
return;
}
toUser.send((DangerStickman.PacketWrapper) new Friend(fromUser.getId(), fromUser.getName(), fromUser.getTrophies()).Serialize());
}
private void GetConfirmationFromUser(){
}
private void RemoveFriend(Integer from, Integer to){
try {
friendDB.RemoveFriend(from.toString(), to.toString());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
User fromUser = null;
User toUser = null;
try{
fromUser = Managers.getUserManager().GetUser(from);
//TODO logic
} catch (NoSuchElementException e){
}
try{
toUser = Managers.getUserManager().GetUser(to);
//TODO logic
} catch (NoSuchElementException e){
}
}
private FriendMessages.UpdateFriendsListResponse.Builder UpdateFriendList(Integer for_user){
}
}
| true |
7230edb07d1b0a749d3cea668b821dfd196db466 | Java | vendor-vandor/pidome-unofficial | /pidome-pidome-client/src/org/pidome/client/system/client/data/ClientData.java | UTF-8 | 14,537 | 1.796875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pidome.client.system.client.data;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.pidome.client.config.AppProperties;
import org.pidome.client.config.AppPropertiesException;
import org.pidome.client.services.server.ServerStream;
import org.pidome.client.services.server.ServerStreamEvent;
import org.pidome.client.services.server.ServerStreamListener;
import org.pidome.client.system.parsers.Parser;
import org.pidome.client.system.parsers.ServerProtocolParser;
import org.pidome.client.system.parsers.ParseException;
/**
*
* @author John Sirach
*/
public class ClientData extends Parser implements ServerStreamListener {
protected static ServerStream serverStream;
HashMap<String,Object> sessionData = new HashMap<>();
static ClientSession session = new ClientSession();
static Logger LOG = LogManager.getLogger(ClientData.class);
static List _loggedinListeners = new ArrayList();
static List _dataConnectionListeners = new ArrayList();
Map<String, String> TelnetServer = new HashMap<>();
Map<String, String> HTTPServer = new HashMap<>();
public final static Map<String,Object> internalServerData = new HashMap<>();
private String mainResourceId;
static ClientData me;
public ClientData(){
ServerStream.addEventListener(this);
me = this;
}
public static ClientData getInstance(){
return me;
}
public final void initializeClientDataConnection(Map<String,Object> serverData) throws UnknownHostException, IOException {
mainResourceId = (String)serverData.get("TELNETADDRESS");
serverStream = new ServerStream((String)serverData.get("TELNETADDRESS"), (int)serverData.get("TELNETPORT"), (boolean)serverData.get("STREAMSSL"));
try {
AppProperties.setProperty("system", "TELNETADDRESS", (String)serverData.get("TELNETADDRESS"));
AppProperties.setProperty("system", "TELNETPORT", String.valueOf((int)serverData.get("TELNETPORT")));
AppProperties.setProperty("system", "STREAMSSL", String.valueOf((boolean)serverData.get("STREAMSSL")));
AppProperties.store("system", "Server data save");
} catch (Exception ex){
LOG.error("Could not save server data: {}", ex.getMessage());
}
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.CONNECTED, null, 0, null);
}
public static String getLoginName(){
return ClientSession.getClientName();
}
public final void startDataConnection(){
serverStream.start();
try {
if(AppProperties.getProperty("system", "client.firstrun").equals("false")){
serverStream.send(session.getAuthString());
} else {
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE,session.getSessionName(),0, "firstrun");
}
} catch (ClientSessionException ex) {
LOG.error("Could not send initial login: {}", ex.getMessage());
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE,session.getSessionName(),500, ex.getMessage());
} catch (AppPropertiesException ex) {
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE,session.getSessionName(),0, "firstrun");
}
}
public final void stopDataConnection(){
LOG.debug("Stopping server stream");
if(serverStream!=null){
serverStream.stop();
}
}
@Override
public void handleStreamEvent(ServerStreamEvent event) {
switch(event.getEventType()){
case ServerStreamEvent.DATARECEIVED:
try {
ServerProtocolParser client = parseServerStreamData((String)event.getData());
try {
switch ((String) client.getId()) {
case "ClientService.signOn":
session.setData((Map<String,Object>)client.getResult().get("data"));
if (session.loginError()) {
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE, session.getSessionName(), session.getLoginError(), session.getErrorMessage());
} else {
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGGEDIN, session.getSessionName(), 200, "");
}
break;
case "SystemService.getClientInitPaths":
((Map<String,Object>)client.getResult().get("data")).put("httpaddress", mainResourceId);
_fireDataConnectionEvent(ClientDataConnectionEvent.INITRECEIVED, (Map<String,Object>)client.getResult().get("data"));
break;
}
} catch (NullPointerException ex){
try {
LOG.debug("Going to method handling");
Map<String,Object> params = client.getParameters();
switch(client.getNameSpace()){
case ServerProtocolParser.CLIENT:
switch(client.getMethod()){
case "approveClient":
if((boolean)params.get("aproved")){
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGGEDIN, session.getSessionName(), 200, "");
} else {
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE, session.getSessionName(), 401, "Approval denied");
}
break;
default:
_fireDataConnectionEvent(ClientDataConnectionEvent.CLIENTRECEIVED, client.getMethod(), params);
break;
}
break;
case ServerProtocolParser.MACRO:
_fireDataConnectionEvent(ClientDataConnectionEvent.MCRRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.DEVICE:
_fireDataConnectionEvent(ClientDataConnectionEvent.DEVRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.CAT:
_fireDataConnectionEvent(ClientDataConnectionEvent.CATRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.LOC:
_fireDataConnectionEvent(ClientDataConnectionEvent.LOCRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.SYSTEM:
_fireDataConnectionEvent(ClientDataConnectionEvent.SYSRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.MEDIA:
_fireDataConnectionEvent(ClientDataConnectionEvent.MEDIARECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.PLUGIN:
_fireDataConnectionEvent(ClientDataConnectionEvent.PLUGINRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.DAYPART:
_fireDataConnectionEvent(ClientDataConnectionEvent.DAYPARTRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.PRESENCE:
_fireDataConnectionEvent(ClientDataConnectionEvent.USERPRESENCERECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.USERSTATUS:
_fireDataConnectionEvent(ClientDataConnectionEvent.USERSTATUSRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.UTILITYMEASURE:
_fireDataConnectionEvent(ClientDataConnectionEvent.UTILITYMEASURERECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.NOTIFICATION:
_fireDataConnectionEvent(ClientDataConnectionEvent.NOTIFICATIONRECEIVED, client.getMethod(), params);
break;
case ServerProtocolParser.msg_OK:
switch(client.getNameSpace()){
case ServerProtocolParser.MACRO:
_fireDataConnectionEvent(ClientDataConnectionEvent.MCRRECEIVED, client.getMethod(), params);
break;
}
break;
}
} catch (Exception exception){
LOG.error("Error in handling request: {}", exception.getMessage(), exception);
}
}
} catch (ParseException ex){
LOG.error("Could not parse/handle server data: {}", ex.getMessage());
_fireDataLoggedInConnectionEvent(ClientDataConnectionEvent.LOGINFAILURE, session.getSessionName(), 500, ex.getMessage());
}
break;
case ServerStreamEvent.CONNECTIONLOST:
session.logOut();
_fireDataConnectionEvent(ClientDataConnectionEvent.DISCONNECTED);
break;
}
}
public static void sendData(String data){
serverStream.send(data);
}
public static void login(String clientName, String password) throws ClientSessionException {
session.setClientName(clientName);
sendData(session.getAuthString(clientName, password));
}
public static void goCustomConnect(String serverAddress, int serverPort, boolean isSSL){
if(!serverAddress.equals("") && serverPort!=0){
internalServerData.put("TELNETADDRESS", serverAddress);
internalServerData.put("TELNETPORT", serverPort);
internalServerData.put("STREAMSSL", isSSL);
try {
me.initializeClientDataConnection(internalServerData);
} catch (IOException ex) {
LOG.error("Could not connect: {}", ex.getMessage());
getInstance()._fireDataConnectionEvent(ClientDataConnectionEvent.CONNECTERROR, ex.getMessage());
}
} else {
getInstance()._fireDataConnectionEvent(ClientDataConnectionEvent.CONNECTERROR, "Incorrect server data");
}
}
/// Listeners for plain data
public static synchronized void addClientDataConnectionListener(ClientDataConnectionListener l) {
LOG.debug("Added data listener: {}", l.getClass().getName());
_dataConnectionListeners.add(l);
}
public static synchronized void removeClientDataConnectionListener(ClientDataConnectionListener l) {
LOG.debug("Removed data listener: {}", l.getClass().getName());
_dataConnectionListeners.remove(l);
}
synchronized void _fireDataConnectionEvent(String EventType){
_fireDataConnectionEvent(EventType, null);
}
synchronized void _fireDataConnectionEvent(String EventType, Object data){
LOG.debug("New event: {}", EventType);
ClientDataConnectionEvent event = new ClientDataConnectionEvent(EventType);
event.setData(data);
Iterator listeners = _dataConnectionListeners.iterator();
while (listeners.hasNext()) {
((ClientDataConnectionListener) listeners.next()).handleClientDataConnectionEvent(event);
}
}
synchronized void _fireDataConnectionEvent(String EventType, String method, Object data){
LOG.debug("New event: {} with method: {}", EventType, method);
ClientDataConnectionEvent event = new ClientDataConnectionEvent(EventType);
event.setData(data);
event.setMethod(method);
Iterator listeners = _dataConnectionListeners.iterator();
while (listeners.hasNext()) {
((ClientDataConnectionListener) listeners.next()).handleClientDataConnectionEvent(event);
}
}
//// Listeners for connection and login listeners
public static synchronized void addClientLoggedInConnectionListener(ClientDataConnectionListener l) {
LOG.debug("Added logged in listener: {}", l.getClass().getName());
_loggedinListeners.add(l);
}
public static synchronized void removeClientLoggedInConnectionListener(ClientDataConnectionListener l) {
LOG.debug("Removed logged in listener: {}", l.getClass().getName());
_loggedinListeners.remove(l);
}
synchronized void _fireDataLoggedInConnectionEvent(String EventType, String clientName, int errorCode, String message){
LOG.debug("New event: {}", EventType);
ClientDataConnectionEvent event = new ClientDataConnectionEvent(EventType);
event.setClientData(clientName, errorCode, message);
Iterator listeners = _loggedinListeners.iterator();
while (listeners.hasNext()) {
((ClientDataConnectionListener) listeners.next()).handleClientDataConnectionEvent(event);
}
}
}
| true |
9c3caf1205d55808561b8e01d5b1ab17a2d0df92 | Java | SebaFarias/modulo_programacion_basica_en_java | /java/Banco/Banco.java | UTF-8 | 8,239 | 3.21875 | 3 | [] | no_license | package Banco;
import java.util.Scanner;
//19-05-2021
public class Banco {
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
boolean continuar = true;
int seleccion;
float saldo = 0F;
do{
seleccion = menuPrincipal( leer );
switch( seleccion ){
case 1: mostrarSaldo( saldo );
break;
case 2: saldo = depositar( leer, saldo );
break;
case 3: saldo = girar( leer, saldo );
break;
case 4: salir();
continuar = false;
break;
}
}while(continuar);
}
static int menuPrincipal( Scanner leer ){
int seleccion;
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Banco de Talca |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
System.out.println("| ¿Qué desea Hacer? |");
System.out.println("| |");
System.out.println("|(1)Consulta de Saldo Realizar Abono(2)|");
System.out.println("| |");
System.out.println("|(3)Realizar Giro Salir(4)|");
System.out.println("| |");
do{
System.out.println("|-------------Indique su opción-----------|");
seleccion = leer.nextInt();
}while( seleccion < 1 && seleccion > 4);
return seleccion;
}
static void mostrarSaldo( float saldo ){
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| Consulta de Saldo |");
System.out.println("|Saldo actual: $"+saldo);
System.out.println("| |");
System.out.println("|-----------------------------------------|");
}
static float depositar( Scanner leer, float saldo){
boolean valido = false;
float nuevoSaldo, deposito = 0F;
do{
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Depósito |");
System.out.println("| |");
System.out.println("| Indique monto a depositar: |");
deposito = leer.nextFloat();
if(deposito > 0){
valido = true;
}else{
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Depósito |");
System.out.println("| |");
System.out.println("| Valor Inválido |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
}
}while(!valido);
nuevoSaldo = saldo + deposito;
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Depósito Realizado con éxito |");
System.out.println("| |");
System.out.println("|Saldo actual: $"+nuevoSaldo);
System.out.println("| |");
System.out.println("|-----------------------------------------|");
return nuevoSaldo;
}
static float girar( Scanner leer, float saldo){
if(saldo <=0){
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Giro |");
System.out.println("| |");
System.out.println("| Saldo insuficiente |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
return saldo;
}
boolean valido = false;
float nuevoSaldo, giro = 0F;
do{
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Giro |");
System.out.println("| |");
System.out.println("| Indique monto a girar: |");
giro = leer.nextFloat();
if(giro > 0 && giro <= saldo){
valido = true;
}else{
if(giro > saldo){
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Giro |");
System.out.println("| |");
System.out.println("| Saldo insuficiente |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
}else{
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Realizar Giro |");
System.out.println("| |");
System.out.println("| Valor Inválido |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
}
}
}while(!valido);
nuevoSaldo = saldo - giro;
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Giro Realizado con éxito |");
System.out.println("| |");
System.out.println("|Saldo actual: $"+nuevoSaldo);
System.out.println("| |");
System.out.println("|-----------------------------------------|");
return nuevoSaldo;
}
static void salir(){
//imprimirEspacio();
System.out.println("|-----------------------------------------|");
System.out.println("| |");
System.out.println("| Gracias por preferir el |");
System.out.println("| Banco de Talca |");
System.out.println("| Adios! |");
System.out.println("| |");
System.out.println("|-----------------------------------------|");
}
public static void imprimirEspacio(){
for( int i = 0; i< 10; i++){
System.out.println("");
}
}
} | true |
22eb2156a3cd9194d57cbdccb70cda67199aa806 | Java | zlren/TaoTaoNew | /taotao2-sso/src/main/java/lab/zlren/taotao/sso/controller/UserController.java | UTF-8 | 4,660 | 2.28125 | 2 | [] | no_license | package lab.zlren.taotao.sso.controller;
import lab.zlren.taotao.common.utils.CookieUtils;
import lab.zlren.taotao.sso.pojo.User;
import lab.zlren.taotao.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* UserController
* Created by zlren on 2017/2/22.
*/
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
public static final String COOKIE_NAME = "TT_TOKEN";
@RequestMapping(value = "register", method = RequestMethod.GET)
public String toRegister() {
return "register";
}
@RequestMapping(value = "login", method = RequestMethod.GET)
public String toLogin() {
return "login";
}
@RequestMapping(value = "check/{param}/{type}", method = RequestMethod.GET)
public ResponseEntity<Boolean> check(
@PathVariable("param") String param,
@PathVariable("type") Integer type) {
try {
Boolean bool = this.userService.check(param, type);
if (null == bool) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
return ResponseEntity.ok(!bool); // 这个逻辑是反的
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
/**
* 注册,SpringMVC的数据校验
*
* @param user
* @return
*/
@RequestMapping(value = "doRegister", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> doRegister(@Valid User user, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<String, Object>();
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> msgs = new ArrayList<>();
for (ObjectError objectError : allErrors) {
String defaultMessage = objectError.getDefaultMessage();
msgs.add(defaultMessage);
}
result.put("status", "500");
result.put("data", StringUtils.join(msgs, "|"));
return result;
}
Boolean bool = this.userService.saveUser(user);
if (bool) {
// 注册成功
result.put("status", "200");
} else {
result.put("status", "500");
result.put("data", "是的!");
}
return result;
}
@RequestMapping(value = "doLogin", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> doLogin(
@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request,
HttpServletResponse response) {
Map<String, Object> result = new HashMap<String, Object>();
try {
String token = this.userService.doLogin(username, password);
if (null == token) {
// 失败
result.put("status", 400); // 非200
} else {
// 登陆成功,将token写入到cookie中
result.put("status", 200);
CookieUtils.setCookie(request, response, COOKIE_NAME, token);
}
} catch (Exception e) {
e.printStackTrace();
// 失败
result.put("status", 400); // 非200
}
return result;
}
@RequestMapping(value = {"token"}, method = RequestMethod.GET)
public ResponseEntity<User> queryUserByToken(@PathVariable("token") String token) {
try {
User user = this.userService.queryUserByToken(token);
if (null == user) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
return ResponseEntity.ok(user);
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
| true |
33329d68e4246ceec8102b62a178332fdebae877 | Java | feantori/java-actionscript-api-for-android | /droid/utils/IDataOutput.java | UTF-8 | 4,660 | 2.296875 | 2 | [] | no_license | /**
* Jasafa - Java ActionScript API For Android
* Java implementation of ActionScript3
*
* MIT Licensed (http://www.opensource.org/licenses/mit-license.php)
* Copyright (c) 2010 Mj Mendoza IV <mjmendoza@konsolscript.org>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package droid.utils;
import droid.misc.Any;
import droid.utils.ByteArray;
/**
* flash.utils.ByteArray implementation
* @author Mj Mendoza IV
*
* The IDataOutput interface provides a set of methods for writing binary data.
*/
public interface IDataOutput {
/**
* Not to be used for manual/direct manipulation.
*/
public String endian = "";
/**
* The byte order for the data, either the "bigEndian" or "littleEndian" constant from the Endian class.
* @return
*/
public String getEndian();
/**
* The byte order for the data, either the "bigEndian" or "littleEndian" constant from the Endian class.
* @param type
*/
public void setEndian(String type);
/**
* Not to be used for manual/direct manipulation.
*/
public int objectEncoding = 0;
/**
* Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be used when writing to, or reading binary data.
* @return
*/
public int getObjectEncoding();
/**
* Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be used when writing to, or reading binary data.
* @param version
*/
public void setObjectEncoding(int version);
/**
* Writes a Boolean value.
* @param value
*/
public void writeBoolean(boolean value);
/**
* Writes a byte.
* @param value
*/
public void writeByte(int value);
/**
* Writes a sequence of length bytes from the specified byte array, bytes, starting offset(zero-based index) bytes into the byte stream.
* @param bytes
*/
public void writeBytes(ByteArray bytes);
/**
* Writes a sequence of length bytes from the specified byte array, bytes, starting offset(zero-based index) bytes into the byte stream.
* @param bytes
* @param offset
*/
public void writeBytes(ByteArray bytes, int offset);
/**
* Writes a sequence of length bytes from the specified byte array, bytes, starting offset(zero-based index) bytes into the byte stream.
* @param bytes
* @param offset
* @param length
*/
public void writeBytes(ByteArray bytes, int offset, int length);
/**
* Writes an IEEE 754 double-precision (64-bit) floating point number.
* @param value
*/
public void writeDouble(double value);
/**
* Writes an IEEE 754 single-precision (32-bit) floating point number.
* @param value
*/
public void writeFloat(Double value);
/**
* Writes a 32-bit signed integer.
* @param value
*/
public void writeInt(int value);
/**
* Writes a multibyte string to the byte stream using the specified character set.
* @param value
* @param charSet
*/
public void writeMultiByte(String value, String charSet);
/**
* Writes an object to the byte stream or byte array in AMF serialized format.
* @param object
*/
public void writeObject(Any object);
/**
* Writes a 16-bit integer.
* @param value
*/
public void writeShort(int value);
/**
* Writes a 32-bit unsigned integer.
* @param value
*/
public void writeUnsignedInt(long value);
/**
* Writes a UTF-8 string to the byte stream.
* @param value
*/
public void writeUTF(String value);
/**
* Writes a UTF-8 string.
* @param value
*/
public void writeUTFBytes(String value);
}
| true |
a2827f858da8b33f789beb581b118844940ab0c4 | Java | LightSun/InjectKnife | /inject-knife/src/test/java/injectknife/test/SimpleTest.java | UTF-8 | 1,333 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package injectknife.test;
import com.heaven7.java.injectknife.*;
import com.heaven7.java.injectknife.internal.InjectService;
import com.heaven7.java.injectknife.internal.ProvideMethod;
import org.junit.Test;
@InjectService(SimpleTest_$InjectService$.class)
public class SimpleTest implements InjectProvider , InjectParameterSupplier{
private final InjectKnife.MethodInjector injector;
public SimpleTest() {
injector = InjectKnife.from(this, new ObserverImpl())
.withInjectObserver(new ObserverImpl2());
}
//最终可以字节码注入
@Test
@ProvideMethod
public void onCreate(){
getInjector().inject(null);
System.out.println(InjectProvider.class.isAssignableFrom(getClass()));
}
@Test
@ProvideMethod
public void onStart(){
getInjector().inject(null);
}
@Test
@ProvideMethod
public void onDestroy(){
getInjector().inject(null);
}
@Override
public InjectKnife.MethodInjector getInjector() {
return injector;
}
@Override
public Object[] getParameters(InjectProvider provider, InjectObserver observer, int methodFlag) {
System.out.println("getParameters() : provider = " + provider
+ " ,methodFlag = " + methodFlag);
return new Object[0];
}
}
| true |
ab32039249ed932eee439d78c2238b9760786a7c | Java | nitishgoyal13/statesman | /statesman-model/src/main/java/io/appform/statesman/model/Action.java | UTF-8 | 304 | 1.804688 | 2 | [] | no_license | package io.appform.statesman.model;
import io.appform.statesman.model.action.ActionType;
import io.appform.statesman.model.action.template.ActionTemplate;
/**
*
*/
public interface Action<J extends ActionTemplate> {
ActionType getType();
void apply(J actionTemplate, Workflow workflow);
}
| true |
819f6173a21a525c7e6c1bf44877cdcd6b2cff0f | Java | bitcoinaustria/bliver | /app/src/at/bitcoinaustria/bliver/db/SqlHelper.java | UTF-8 | 2,537 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package at.bitcoinaustria.bliver.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import at.bitcoinaustria.bliver.Bitcoins;
public class SqlHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "bliver";
private static final int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE delivery (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
"server_url TEXT, \n" +
"order_id TEXT, \n" +
"order_description TEXT, \n" +
"order_status TEXT, \n" +
"vendor TEXT, \n" +
"amount TEXT, \n" +
"multisig_address TEXT, \n" +
"tx_input_hash TEXT, \n" +
"tx_id TEXT\n" +
");";
private final Context context;
public SqlHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DB_CREATE);
final DeliveryDao deliveryDao = new DeliveryDao(context);
deliveryDao.save(sqLiteDatabase, new Delivery(
"http://10.200.1.73/bliver/multisig.txt",
"123",
"testbestellung 123",
OrderStatus.AWAITING_DELIVERY,
Vendor.EBAY,
Bitcoins.valueOf(300000000L),
"ewru23u3bfiow3UOH352ddw",
"",
""
));
deliveryDao.save(sqLiteDatabase, new Delivery(
"http://10.200.1.73/bliver/multisig.txt",
"120",
"Amazon Kindle Order",
OrderStatus.AWAITING_DELIVERY,
Vendor.AMAZON,
Bitcoins.valueOf(1200000000L),
"i340dsfjii2kaoweIGHKJW",
"",
""
));
deliveryDao.save(sqLiteDatabase, new Delivery(
"http://10.200.1.73/bliver/multisig.txt",
"99",
"MyPad Order",
OrderStatus.AWAITING_DELIVERY,
Vendor.ALIBABA,
Bitcoins.valueOf(600000000L),
"ljN328HUOhiowio2309HO21",
"",
""
));
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
throw new UnsupportedOperationException("not implemented");
}
}
| true |
d6b778460606d237e3f8e700eb9523d383224a57 | Java | kbhat1234/automation-selenium-java | /src/main/java/com/selenium/testing/automation/WebElementTest1.java | UTF-8 | 1,863 | 2.46875 | 2 | [] | no_license | package com.selenium.testing.automation;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebElementTest1 {
static String appUrl = "http://demoqa.com/html-contact-form/";
static String driverPath = "E:\\browserdrivers\\chromedriver_win32\\chromedriver.exe";
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", driverPath);
WebDriver driver = new ChromeDriver();
driver.get(appUrl);
driver.manage().window().maximize();
//WebElement ele = driver.findElement(By.id("lname"));
//System.out.println(ele.getText());
Thread.sleep(4000);
driver.findElement(By.className("firstname")).sendKeys("Karthik");
driver.findElement(By.id("lname")).sendKeys("Bhat");
driver.findElement(By.name("country")).sendKeys("India");
WebElement ele = driver.findElement(By.id("subject"));
String text = ele.getText();
System.out.println(text);
System.out.println(ele.getAttribute("id"));
driver.findElement(By.id("subject")).sendKeys("Hello world");
Dimension size = driver.findElement(By.id("subject")).getSize();
System.out.println("Height is " + size.height);
System.out.println("Width is " + size.width);
WebElement element = driver.findElement(By.id("subject"));
Point point = element.getLocation();
System.out.println("X s is " + point.x + " Y point is " + point.y);
boolean display = element.isDisplayed();
System.out.println(display);
boolean enable = element.isEnabled();
System.out.println(enable);
driver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div/form/input[4]")).submit();
driver.close();
driver.quit();
// element.getCssValue(propertyName)
}
}
| true |