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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a3dde44d4868f7435a64cf1e73de1a9223a94b63
|
Java
|
zgc456/dubbo
|
/demo1/project-prodo/src/main/java/com/zheng/Project_Porta_Applicaton.java
|
UTF-8
| 367
| 1.546875
| 2
|
[] |
no_license
|
package com.zheng;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by lenovo on 2018/3/27.
*/
@SpringBootApplication
public class Project_Porta_Applicaton {
public static void main(String[] args) {
SpringApplication.run(Project_Porta_Applicaton.class,args);
}
}
| true
|
06588c2d8281f4223af5438189c5cb3148327abe
|
Java
|
Eveveen/Shopping-be
|
/src/main/java/com/service/iface/UserMessageServiceIface.java
|
UTF-8
| 245
| 1.617188
| 2
|
[] |
no_license
|
package com.service.iface;
import java.util.List;
import com.entity.UserMessage;
public interface UserMessageServiceIface {
public List<UserMessage> findMsgByReceiverId(int receiverId);
public int updateReadStatus(int receiverId);
}
| true
|
e36325b0a7b2d96ac088557934ea82dfce23da1b
|
Java
|
jonfhancock/MindBody
|
/MindBodyHancock/src/com/jonfhancock/mindbody/models/SessionType.java
|
UTF-8
| 2,988
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.jonfhancock.mindbody.models;
import android.content.ContentProviderOperation.Builder;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import com.alexgilleran.icesoap.annotation.XMLField;
import com.alexgilleran.icesoap.annotation.XMLObject;
import com.jonfhancock.mindbody.data.provider.MindBodyContent.Appointment.Columns;
@XMLObject("//SessionType")
public class SessionType implements Parcelable {
private static final String FIELD_ID = "ID";
private static final String FIELD_DEFAULT_TIME_LENGTH = "DefaultTimeLength";
private static final String FIELD_PROGRAM_ID = "ProgramID";
private static final String FIELD_NAME = "Name";
@XMLField(FIELD_ID)
private long mID;
@XMLField(FIELD_DEFAULT_TIME_LENGTH)
private int mDefaultTimeLength;
@XMLField(FIELD_PROGRAM_ID)
private long mProgramID;
@XMLField(FIELD_NAME)
private String mName;
public SessionType() {
}
public void setID(long iD) {
mID = iD;
}
public long getID() {
return mID;
}
public void setDefaultTimeLength(int defaultTimeLength) {
mDefaultTimeLength = defaultTimeLength;
}
public int getDefaultTimeLength() {
return mDefaultTimeLength;
}
public void setProgramID(long programID) {
mProgramID = programID;
}
public long getProgramID() {
return mProgramID;
}
public void setName(String name) {
mName = name;
}
public String getName() {
return mName;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SessionType) {
return ((SessionType) obj).getID() == mID;
}
return false;
}
@Override
public int hashCode() {
return ((Long) mID).hashCode();
}
public SessionType(Parcel in) {
mID = in.readLong();
mDefaultTimeLength = in.readInt();
mProgramID = in.readLong();
mName = in.readString();
}
public SessionType(Cursor c) {
mID = c.getLong(Columns.SESSION_TYPE_ID.getIndex());
mDefaultTimeLength = c.getInt(Columns.SESSION_TYPE_DEFAULT_TIME
.getIndex());
mProgramID = c.getLong(Columns.SESSION_TYPE_PROGRAM_ID.getIndex());
mName = c.getString(Columns.SESSION_TYPE_NAME.getIndex());
}
public Builder addValues(Builder builder) {
builder.withValue(Columns.SESSION_TYPE_ID.getName(), mID)
.withValue(Columns.SESSION_TYPE_DEFAULT_TIME.getName(),
mDefaultTimeLength)
.withValue(Columns.SESSION_TYPE_PROGRAM_ID.getName(),
mProgramID)
.withValue(Columns.SESSION_TYPE_NAME.getName(), mName);
return builder;
}
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<SessionType> CREATOR = new Parcelable.Creator<SessionType>() {
public SessionType createFromParcel(Parcel in) {
return new SessionType(in);
}
public SessionType[] newArray(int size) {
return new SessionType[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mID);
dest.writeInt(mDefaultTimeLength);
dest.writeLong(mProgramID);
dest.writeString(mName);
}
}
| true
|
5052a7fe20cf0da29c468f9f6362adbb37761028
|
Java
|
Mahran-Yacoub/World-Map-Dijkstra
|
/src/weigthed/graph/Country.java
|
UTF-8
| 1,345
| 3.390625
| 3
|
[] |
no_license
|
package weigthed.graph;
/**
* This class will be used to create objects to represent countries as vertices
* in a graph
*
*/
public class Country {
/** Name of a country */
private String name;
/** Y AXIS */
private double latitude;
/** X - Axis */
private double longitude;
public Country(String name) {
this.name = name;
}
public Country(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (o.getClass() != this.getClass()) {
return false;
}
Country country = (Country) o;
if (this.name.equals(country.name)) {
return true;
}
return false;
}
@Override
public String toString() {
return this.name ;
}
}
| true
|
1524a47f79f06a26acbb77214e1614637d46c220
|
Java
|
ttr843/esexample
|
/src/main/java/ru/itis/example/es/utils/elastic/ElasticSearchQueryBuilder.java
|
UTF-8
| 2,598
| 2.421875
| 2
|
[] |
no_license
|
package ru.itis.example.es.utils.elastic;
import lombok.Getter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* @author <a href="mailto:ruslan.pashin@waveaccess.ru">Ruslan Pashin</a>
*/
@Getter
public class ElasticSearchQueryBuilder {
private final BoolQueryBuilder filterBuilder = boolQuery().must(matchAllQuery());
private int termCount = 0;
public void addToQuery(TermType type, String fieldName, Object value) {
if (isEmpty(value) || type == null) {
return;
}
switch (type) {
case LIKE:
filterBuilder.must(wildcardQuery(fieldName, "*" + ((String) value) + "*"));
break;
case IN:
filterBuilder.must(termsQuery(fieldName, (Collection<?>) value));
break;
case MATCH:
filterBuilder.must(matchPhraseQuery(fieldName, value));
break;
case EXISTS:
boolean exists = BooleanUtils.isTrue((Boolean) value);
if (exists) {
filterBuilder.must(existsQuery(fieldName));
} else {
filterBuilder.mustNot(existsQuery(fieldName));
}
break;
case FULL_LIKE: {
String[] values = ((String) value).split(" ");
for (String v : values) {
filterBuilder.should(wildcardQuery(fieldName, "*" + v.toLowerCase() + "*"));
}
filterBuilder.should(matchPhraseQuery(fieldName, value));
filterBuilder.minimumShouldMatch(values.length);
}
case NOT_EQ:
filterBuilder.mustNot(termQuery(fieldName, value));
break;
default:
filterBuilder.must(termQuery(fieldName, value));
}
this.termCount++;
}
private boolean isEmpty(Object value) {
if (value == null) {
return true;
}
boolean isEmpty = false;
if (value instanceof String) {
isEmpty = StringUtils.isEmpty((String) value);
} else if (value instanceof Collection) {
isEmpty = CollectionUtils.isEmpty((Collection<?>) value);
}
return isEmpty;
}
public enum TermType {
EQ, LIKE, IN, MATCH, EXISTS, NOT_EQ, FULL_LIKE
}
}
| true
|
c6431a3f6607c92e5a371a4e4db6d50c805643d2
|
Java
|
dobrosi/JCFS
|
/src/main/java/com/programgyar/jcfs/Main.java
|
UTF-8
| 928
| 2.46875
| 2
|
[] |
no_license
|
package com.programgyar.jcfs;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import co.paralleluniverse.javafs.JavaFS;
public class Main {
public static void main(String[] args) {
JCFileSystem jcFileSystem = JCFileSystem.getInstance();
// Path foo = jcFileSystem.getPath("/foo");
//
// try {
// Files.createFile(foo);
//
// Path hello = foo.resolve("hello.txt"); // /foo/hello.txt
// Files.write(hello, Arrays.asList("hello world"), StandardCharsets.UTF_8);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("done.");
Map<String, String> options = new HashMap<>();
try {
JavaFS.mount(jcFileSystem, Paths.get("test-drive"), false, true, options);
Thread.sleep(Long.MAX_VALUE);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
| true
|
e5dff5bd8589603fe7a23d5272defc6a1f706b4b
|
Java
|
jtrpan/ForestGUI
|
/src/Evergreen.java
|
UTF-8
| 1,225
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
import java.awt.*;
// imports
public class Evergreen extends Coniferous { // subclass of coniferous and tree
final int GROUND = 450; // height of the ground
public Evergreen (int xPos) {
super(xPos);
} // get the position in parameter
public void grow (Graphics g){
// This method would draw an EVERGREEN tree, not a regular tree.
int x = super.getPos(); // get the position
int h = super.getHeight(); // get the height
int w = super.getWidth(); // get the width
int []x1pts = {x-15, x+(w/2), x+w+15}; // x coordinates of triangles
int []y1pts = {GROUND-h/2,GROUND-h/2-50,GROUND-h/2}; // y coordinates of triangle 1
int []y2pts = {GROUND-h/2-h/3,GROUND-h-87,GROUND-h/2-h/3}; // y coordinates of triangle 2
Color brown = new Color (83,53,10); // custom trunk color
Color everLeaf = new Color (58, 95, 11); // custom leaf color
g.setColor(brown);
g.fillRect(x,GROUND-h, w, h); // draw brown rectangle as trunk
g.setColor(everLeaf);
g.fillPolygon(x1pts,y1pts,3);
g.fillPolygon(x1pts,y2pts,3); // draw green triangles as leaves
}
}
| true
|
66990b47b9dc69a3bca8cf1de0b971f9e22bfbab
|
Java
|
indeedeng/proctor
|
/proctor-pipet/proctor-pipet-deploy/src/main/java/com/indeed/proctor/pipet/deploy/AppInit.java
|
UTF-8
| 1,182
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.indeed.proctor.pipet.deploy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.ServletRegistration;
/**
* Alternative to creating a web.xml by overriding methods in a class.
*
* <p>Consider using WebApplicationInitializer if you need something more advanced in the future.
* (See commit history for previous usage of that.)
*/
public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {AppConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// PropertiesInitializer customizes the location of our properties files.
registration.setInitParameter(
"contextInitializerClasses", PropertiesInitializer.class.getName());
super.customizeRegistration(registration);
}
}
| true
|
1cfce1f5b36608ab24c54a50ff1e67d0b012fc28
|
Java
|
ABigdataer/FileManagementSystem-DataAnalysis
|
/PersonalAdministration/DataAnalysis/src/main/java/runner/DataAnalysisRunner.java
|
UTF-8
| 9,997
| 2.03125
| 2
|
[] |
no_license
|
package runner;
import kvbean.key.BirthdayMapperKey;
import kvbean.key.BirthdayReducerKey;
import kvbean.key.EducationalBackgroundStatistics;
import kvbean.value.BasicData;
import mapper.BirthdayDataAnalysisMapper;
import mapper.EducationDataAnalysisMapper;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.filecache.DistributedCache;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import reducer.BirthdayDataAnalysisReducer;
import reducer.EducationDataAnalysisReducer;
import java.io.IOException;
/**
* 1、调度Mapper和Reducer的Runner类
* 2、继承Tool,实现setConf、getConf和run方法
*/
public class DataAnalysisRunner implements Tool{
public static Configuration conf = null;
public static String driverClass = "com.mysql.jdbc.Driver";
public static String dbUrl = "jdbc:mysql://mini:3306/db_employee?useUnicode=true&characterEncoding=UTF-8";
public static String userName = "root";
public static String passwd = "123456";
public static String [] fields1 = {"id","headcount","juniorhighschoolsum" , "seniorsighschoolsum" , "technicalsecondaryschoolsum" , "juniorcollegesum" , "bachelordegreesum" , "mastersum" , "doctorsum" , "postdoctorsum"};
public static String[] fields2 = {"id", "name", "age", "entrydurationtime"};
public static Path path = new Path("hdfs://mini:9000/lib/mysql/mysql-connector-java-5.1.39-bin.jar");
public static int result2 ;
/**
* 该方法用来准备MR程序会用到的HBaseConf
*
* @param conf
*/
@Override
public void setConf(Configuration conf) {
/**
* 1、通过HBaseConfiguration.create(conf)读取链接HBAse的配置
* 2、默认优先读取default配置,再读取hadoop-core.xml配置,最后
* 读取hbase-site.xml配置,后读取的配置属性会覆盖前面优先级较高的
* 配置属性
*/
this.conf = HBaseConfiguration.create(conf);
}
/**
* MR默认调用该方法获取配置信息
*
* @return
*/
@Override
public Configuration getConf() {
return this.conf;
}
@Override
public int run(String[] strings) throws Exception {
String tableName1 = "tb_educationalstatistics";
DBConfiguration.configureDB(conf,driverClass,dbUrl,userName,passwd);
//实例化操作HBase的Job类
Job job1 = Job.getInstance(conf,"DataAnalysisRunner1");
// 设置reduce task的运行实例数
job1.setNumReduceTasks(1); // 默认是1
job1.setJarByClass(DataAnalysisRunner.class);
//组装Mapper InpouFormat
initHBaseInputConfig(job1);
//组装Reducer OutputFormat
initReducerOutputConfig(job1);
// 添加mysql数据库jar
//DistributedCache.addFileToClassPath(path , conf);
//将数据输出到数据库
DBOutputFormat.setOutput(job1,tableName1,fields1);
int result = job1.waitForCompletion(true) ? 0 : 1;
if (result == 0) {
//DBConfiguration.configureDB(conf, driverClass, dbUrl, userName, passwd);
String tableName2 = "tb_age_entrydurationtime";
//实例化操作HBase的Job类
Job job2 = Job.getInstance(conf, "DataAnalysisRunner2");
// 设置reduce task的运行实例数
job2.setNumReduceTasks(1); // 默认是1
job2.setJarByClass(DataAnalysisRunner.class);
//组装Mapper InpouFormat
initHBaseInputConfig2(job2);
//组装Reducer OutputFormat
initReducerOutputConfig2(job2);
// 添加mysql数据库jar
//DistributedCache.addFileToClassPath(path, conf);
DBOutputFormat.setOutput(job2, tableName2, fields2);
//提交运行作业job2 并打印信息
result2 = job2.waitForCompletion(true) ? 0 : 1;
}
return result2;
}
/**
* 用来运行Runner的主类,是Runner的入口
* @param args
*/
public static void main(String[] args) {
try {
int status = ToolRunner.run(new DataAnalysisRunner(), args);
System.exit(status);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 1、组装Mapper InpouFormat
* 2、用TableMapReduceUtil.initTableReducerJob将数据写到关系型数据库中
* 3、
* ①将数据写入表的第一种方式是用TableMapReduceUtil.initTableReducerJob的方法,这里既可以在map阶段输出,也能在reduce阶段输出。
* ②写入表的方式还有一种,就是调用hbase的原生api,即HTable.put的方式写入数据(这种方式适合写少量数据,或者统计后的结果)
* @param job1
*/
private static void initHBaseInputConfig(Job job1) {
//HBase的链接类
Connection connection = null;
//HBase的表管理类
Admin admin = null;
//目标表
String tableName = "data:employeeinformation";
try {
connection = ConnectionFactory.createConnection(conf);
admin = connection.getAdmin();
/**
* 校验表是否存在,如果不存在则直接返回,若存在则运行Mapper类
*/
if (!admin.tableExists(TableName.valueOf(tableName))) throw new RuntimeException("*************无法找到对应表!************");
//创建表扫描器,作为TableMapReduceUtil.initTableMapperJob的参数,用来扫描HBase中的表结构
Scan scan = new Scan();
/**
* 1、初始化TableMapperJOb;
* 2、指定表扫描器,取出HBase中tableName中的数据作为Mapper的输入
* 3、指定MapperClass和其输出key\value类型
*/
TableMapReduceUtil.initTableMapperJob(tableName, scan, EducationDataAnalysisMapper.class, Text.class, IntWritable.class, job1);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 设置Reducer类,以及输出键值类型
* @param job1
*/
private static void initReducerOutputConfig(Job job1) {
job1.setReducerClass(EducationDataAnalysisReducer.class);
job1.setOutputKeyClass(EducationalBackgroundStatistics.class);
job1.setOutputValueClass(NullWritable.class);
job1.setOutputFormatClass(DBOutputFormat.class);
}
/**
* 1、组装Mapper InpouFormat
* 2、用TableMapReduceUtil.initTableReducerJob将数据写到关系型数据库中
* 3、
* ①将数据写入表的第一种方式是用TableMapReduceUtil.initTableReducerJob的方法,这里既可以在map阶段输出,也能在reduce阶段输出。
* ②写入表的方式还有一种,就是调用hbase的原生api,即HTable.put的方式写入数据(这种方式适合写少量数据,或者统计后的结果)
* @param job2
*/
private static void initHBaseInputConfig2(Job job2) {
//HBase的链接类
Connection connection = null;
//HBase的表管理类
Admin admin = null;
//目标表
String tableName = "data:employeeinformation";
try {
connection = ConnectionFactory.createConnection(conf);
admin = connection.getAdmin();
/**
* 校验表是否存在,如果不存在则直接返回,若存在则运行Mapper类
*/
if (!admin.tableExists(TableName.valueOf(tableName))) throw new RuntimeException("*************无法找到对应表!************");
//创建表扫描器,作为TableMapReduceUtil.initTableMapperJob的参数,用来扫描HBase中的表结构
Scan scan = new Scan();
/**
* 1、初始化TableMapperJOb;
* 2、指定表扫描器,取出HBase中tableName中的数据作为Mapper的输入
* 3、指定MapperClass和其输出key\value类型
*/
TableMapReduceUtil.initTableMapperJob(tableName, scan, BirthdayDataAnalysisMapper.class, BirthdayMapperKey.class, BasicData.class, job2);
} catch (IOException e) {
e.printStackTrace();
} finally {
/**
* 关闭资源,避免内存溢出
*/
try {
if (admin != null)
admin.close();
if (connection != null && !connection.isClosed())
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 设置Reducer类,以及输出键值类型
* @param job2
*/
private static void initReducerOutputConfig2(Job job2) {
job2.setReducerClass(BirthdayDataAnalysisReducer.class);
job2.setOutputKeyClass(BirthdayReducerKey.class);
job2.setOutputValueClass(NullWritable.class);
job2.setOutputFormatClass(DBOutputFormat.class);
}
}
| true
|
d2077cd2716ce9a4bdb2b25b8c2f07868d79f191
|
Java
|
heroyuy/systar
|
/history/SoyoMaker2012/src/com/soyomaker/render/OrthoPreviewRender.java
|
UTF-8
| 17,434
| 2.53125
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.soyomaker.render;
import com.soyomaker.model.map.CollideLayer;
import com.soyomaker.model.map.Map;
import com.soyomaker.model.map.NpcState;
import com.soyomaker.model.map.SpriteLayer;
import com.soyomaker.model.map.Tile;
import com.soyomaker.model.map.TileLayer;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
/**
*
* @author Administrator
*/
public class OrthoPreviewRender extends PreviewRender {
/**
*
* @param map
*/
public OrthoPreviewRender(Map map) {
super(map);
}
@Override
public Dimension getPreferredSize() {
Dimension tsize = getTileSize();
return new Dimension(
map.getWidth() * tsize.width,
map.getHeight() * tsize.height);
}
/**
*
* @param tx
* @param ty
* @param border
* @return
*/
protected Polygon createGridPolygon(int tx, int ty, int border) {
Dimension tsize = getTileSize();
Polygon poly = new Polygon();
poly.addPoint(tx - border, ty - border);
poly.addPoint(tx + tsize.width + border, ty - border);
poly.addPoint(tx + tsize.width + border, ty + tsize.height + border);
poly.addPoint(tx - border, ty + tsize.height + border);
return poly;
}
@Override
protected void paintTileLayer(Graphics2D g2d, TileLayer layer) {
Dimension tsize = getTileSize();
if (tsize.width <= 0 || tsize.height <= 0) {
return;
}
int startX = 0;
int startY = 0;
int endX = this.getWidth() / tsize.width + 1;
int endY = this.getHeight() / tsize.height + 1;
// Draw this map layer
for (int y = startY, gy = (startY + 1) * tsize.height;
y < endY; y++, gy += tsize.height) {
for (int x = startX, gx = startX * tsize.width;
x < endX; x++, gx += tsize.width) {
Tile tile = layer.getTileAt(x, y);
if (tile != null) {
if (showTile) {
tile.draw(g2d, gx, gy, zoom);
}
if (!tile.isCross() && showCollide) {
g2d.setColor(Color.RED);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(2.0F, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER));
g2d.drawOval(gx + 1, gy - tsize.height + 1, tsize.width - 3, tsize.height - 3);
g2d.drawLine(gx + 1, gy - (tsize.height >> 1), gx + tsize.width - 2, gy - (tsize.height >> 1));
}
}
}
}
}
@Override
protected void paintCollideLayer(Graphics2D g2d, CollideLayer layer) {
Dimension tsize = getTileSize();
if (tsize.width <= 0 || tsize.height <= 0) {
return;
}
int startX = 0;
int startY = 0;
int endX = this.getWidth() / tsize.width + 1;
int endY = this.getHeight() / tsize.height + 1;
// (endY +2 for high tiles, could be done more properly)
// Draw this map layer
for (int y = startY, gy = (startY + 1) * tsize.height;
y < endY; y++, gy += tsize.height) {
for (int x = startX, gx = startX * tsize.width;
x < endX; x++, gx += tsize.width) {
if (layer.getCollideAt(x, y)) {
g2d.setColor(Color.RED);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(2.0F, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER));
g2d.drawOval(gx + 1, gy - tsize.height + 1, tsize.width - 3, tsize.height - 3);
g2d.drawLine(gx + 1, gy - (tsize.height >> 1), gx + tsize.width - 2, gy - (tsize.height >> 1));
}
}
}
}
@Override
protected void paintSpriteLayer(Graphics2D g2d, SpriteLayer layer) {
Dimension tsize = getTileSize();
if (tsize.width <= 0 || tsize.height <= 0) {
return;
}
int startX = 0;
int startY = 0;
int endX = this.getWidth() / tsize.width + 1;
int endY = this.getHeight() / tsize.height + 1;
// (endY +2 for high tiles, could be done more properly)
// Draw this map layer
for (int y = startY, gy = (startY + 1) * tsize.height;
y < endY; y++, gy += tsize.height) {
for (int x = startX, gx = startX * tsize.width;
x < endX; x++, gx += tsize.width) {
if (layer.getNpcAt(x, y) != null) {
if (layer.getNpcAt(x, y).getNpcState(0).
getImg() != null) {
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP, 1.0f));
switch (layer.getNpcAt(x, y).getNpcState(0).getFace()) {
case NpcState.DOWN_ONE_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
0, 0, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.LEFT_ONE_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
0, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4,
2 * layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.RIGHT_ONE_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
0, 2 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4), layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4,
3 * layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.UP_ONE_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
0, 3 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4), layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null), null);
break;
case NpcState.DOWN_LEFT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4, 0, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null),
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.DOWN_RIGHT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4, 0, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 2,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.DOWN_TWO_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
2 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4), 0, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.LEFT_LEFT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null),
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, null);
break;
case NpcState.LEFT_RIGHT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 2,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, null);
break;
case NpcState.LEFT_TWO_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
2 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4), layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, null);
break;
case NpcState.RIGHT_LEFT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null),
3 * layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, null);
break;
case NpcState.RIGHT_RIGHT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 2,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * 3 / 4, null);
break;
case NpcState.RIGHT_TWO_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
2 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4), layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 2, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * 3 / 4, null);
break;
case NpcState.UP_LEFT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * 3 / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null),
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null), null);
break;
case NpcState.UP_RIGHT_STEP:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4, 3 * layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 2,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null), null);
break;
case NpcState.UP_TWO_STAND:
g2d.drawImage(layer.getNpcAt(x, y).getNpcState(0).getImg(), gx + 1, gy - (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) * zoom) / 4 + 1, gx + (int) (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * zoom) / 4 - 1, gy - 1,
2 * (layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) / 4), 3 * layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null) / 4, layer.getNpcAt(x, y).getNpcState(0).getImg().getWidth(null) * 3 / 4,
layer.getNpcAt(x, y).getNpcState(0).getImg().getHeight(null), null);
break;
}
}
}
}
}
}
@Override
public Point screenToTileCoords(int x, int y) {
Dimension tsize = getTileSize();
return new Point(x / tsize.width, y / tsize.height);
}
@Override
public Point screenToPixelCoords(int x, int y) {
return new Point(
(int) (x / zoom), (int) (y / zoom));
}
@Override
public Point tileToScreenCoords(int x, int y) {
Dimension tsize = getTileSize();
return new Point(x * tsize.width, y * tsize.height);
}
}
| true
|
04d5707dee195f0c6e4359e27eca45253ec7cc1c
|
Java
|
pyp163/BlueTooth
|
/app/src/main/java/org/apache/commons/net/ftp/parser/NTFTPEntryParser.java
|
UTF-8
| 2,762
| 2.328125
| 2
|
[] |
no_license
|
package org.apache.commons.net.ftp.parser;
import java.text.ParseException;
import org.apache.commons.net.ftp.Configurable;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
public class NTFTPEntryParser extends ConfigurableFTPFileEntryParserImpl
{
private static final String DEFAULT_DATE_FORMAT = "MM-dd-yy hh:mma";
private static final String DEFAULT_DATE_FORMAT2 = "MM-dd-yy kk:mm";
private static final String REGEX = "(\\S+)\\s+(\\S+)\\s+(?:(<DIR>)|([0-9]+))\\s+(\\S.*)";
private FTPTimestampParser timestampParser;
public NTFTPEntryParser()
{
this(null);
}
public NTFTPEntryParser(FTPClientConfig paramFTPClientConfig)
{
super("(\\S+)\\s+(\\S+)\\s+(?:(<DIR>)|([0-9]+))\\s+(\\S.*)");
configure(paramFTPClientConfig);
paramFTPClientConfig = new FTPClientConfig("WINDOWS", "MM-dd-yy kk:mm", null, null, null, null);
paramFTPClientConfig.setDefaultDateFormatStr("MM-dd-yy kk:mm");
this.timestampParser = new FTPTimestampParserImpl();
((Configurable)this.timestampParser).configure(paramFTPClientConfig);
}
public FTPClientConfig getDefaultConfiguration()
{
return new FTPClientConfig("WINDOWS", "MM-dd-yy hh:mma", null, null, null, null);
}
public FTPFile parseFTPEntry(String paramString)
{
FTPFile localFTPFile = new FTPFile();
localFTPFile.setRawListing(paramString);
String str3;
String str1;
String str2;
if (matches(paramString))
{
paramString = new StringBuilder();
paramString.append(group(1));
paramString.append(" ");
paramString.append(group(2));
str3 = paramString.toString();
paramString = group(3);
str1 = group(4);
str2 = group(5);
}
try
{
localFTPFile.setTimestamp(super.parseTimestamp(str3));
}
catch (ParseException localParseException2)
{
try
{
while (true)
{
localFTPFile.setTimestamp(this.timestampParser.parseTimestamp(str3));
label109: if ((str2 != null) && (!str2.equals(".")))
{
if (str2.equals(".."))
return null;
localFTPFile.setName(str2);
if ("<DIR>".equals(paramString))
{
localFTPFile.setType(1);
localFTPFile.setSize(0L);
return localFTPFile;
}
localFTPFile.setType(0);
if (str1 != null)
localFTPFile.setSize(Long.parseLong(str1));
return localFTPFile;
}
return null;
return null;
localParseException2 = localParseException2;
}
}
catch (ParseException localParseException1)
{
break label109;
}
}
}
}
| true
|
a31d36613e87bfa2d69a9cbc5f8f0276f52a023f
|
Java
|
Archsystemsllc/radservices
|
/src/main/java/com/archsystemsinc/qam/model/CsrLog_.java
|
UTF-8
| 733
| 1.78125
| 2
|
[] |
no_license
|
package com.archsystemsinc.qam.model;
import java.util.Date;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel (CsrLog.class)
public abstract class CsrLog_ {
public static volatile SingularAttribute<CsrLog, Long> id;
public static volatile SingularAttribute<CsrLog, String> jurisdiction;
public static volatile SingularAttribute<CsrLog, Integer> macId;
public static volatile SingularAttribute<CsrLog, Long> complianceStatus;
public static volatile SingularAttribute<CsrLog, Long> uploadStatus;
public static volatile SingularAttribute<CsrLog, Date> createdDate;
public static volatile SingularAttribute<CsrLog, Integer> userId;
}
| true
|
6fba3d6afd05b25a214585687161e3a5d2f0c703
|
Java
|
immortius/Terasology
|
/engine/src/main/java/org/terasology/world/block/family/AbstractBlockFamily.java
|
UTF-8
| 1,716
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.world.block.family;
import com.google.common.collect.Sets;
import org.terasology.world.block.BlockUri;
import java.util.Locale;
import java.util.Set;
/**
* @author Immortius
*/
public abstract class AbstractBlockFamily implements BlockFamily {
private BlockUri uri;
private Set<String> categories = Sets.newHashSet();
public AbstractBlockFamily(BlockUri uri, Iterable<String> categories) {
this.uri = uri;
for (String category : categories) {
this.categories.add(category.toLowerCase(Locale.ENGLISH));
}
}
@Override
public BlockUri getURI() {
return uri;
}
@Override
public String getDisplayName() {
return getArchetypeBlock().getDisplayName();
}
@Override
public Iterable<String> getCategories() {
return categories;
}
@Override
public boolean hasCategory(String category) {
return categories.contains(category.toLowerCase(Locale.ENGLISH));
}
@Override
public String toString() {
return "BlockFamily[" + uri.toString() + "]";
}
}
| true
|
2fe8ae34a8918520ccdee1fc45a39351758b0280
|
Java
|
MeGAS-island/TruinOgLifid
|
/TruinOgLifid/TruinOgLifid/src/is/tru/truin/BaenastundFragment.java
|
UTF-8
| 1,283
| 1.921875
| 2
|
[] |
no_license
|
package is.tru.truin;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class BaenastundFragment extends Fragment implements OnClickListener {
Button btnHaldaAfram01;
public BaenastundFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_baenastund, container, false);
Button btnHaldaAfram01 = (Button) rootView.findViewById(R.id.button_001);
btnHaldaAfram01.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
Fragment newFragment = new BaenastundKyrrdFragment();
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
| true
|
69088d7ab13af2fe4812daa55fd7b3f89ac01fdd
|
Java
|
clearmode/JavaHTTPServer
|
/HTTPServer/src/koch/dan/httpserver/RequestResponder.java
|
UTF-8
| 1,183
| 3
| 3
|
[] |
no_license
|
package koch.dan.httpserver;
/**
* Created by Dan on 6/11/2017.
*/
import java.io.*;
import java.net.*;
public class RequestResponder implements Runnable
{
private Socket _clientSocket;
public RequestResponder(Socket clientSocket)
{
_clientSocket = clientSocket;
}
@Override
public void run()
{
try
{
Respond();
_clientSocket.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
}
}
private void Respond() throws IOException
{
BufferedReader requestReader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
DataOutputStream responseStream = new DataOutputStream(_clientSocket.getOutputStream());
char[] buffer = new char[1024];
requestReader.read(buffer);
byte[][] response = ParseRequest(buffer);
for (byte[] aResponse : response)
{
responseStream.write(aResponse);
}
}
private byte[][] ParseRequest(char[] request)
{
return new byte[1][1];
}
}
| true
|
6157aab6ba79cb6675c661bdecba116816596fdc
|
Java
|
VITALIoTOrg/vital-ppi-citybikes
|
/src/main/java/eu/vital/reply/jsonpojos/Service.java
|
UTF-8
| 4,174
| 2.265625
| 2
|
[] |
no_license
|
package eu.vital.reply.jsonpojos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import javax.validation.Valid;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"@context",
"id",
"type",
"operations"
})
public class Service {
@JsonProperty("@context")
private String Context;
@JsonProperty("id")
private String id;
@JsonProperty("type")
private String type;
@JsonProperty("operations")
@Valid
private List<Operation> operations = new ArrayList<Operation>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The Context
*/
@JsonProperty("@context")
public String getContext() {
return Context;
}
/**
*
* @param Context
* The @context
*/
@JsonProperty("@context")
public void setContext(String Context) {
this.Context = Context;
}
public Service withContext(String Context) {
this.Context = Context;
return this;
}
/**
*
* @return
* The id
*/
@JsonProperty("id")
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
@JsonProperty("id")
public void setId(String id) {
this.id = id;
}
public Service withId(String id) {
this.id = id;
return this;
}
/**
*
* @return
* The type
*/
@JsonProperty("type")
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
public Service withType(String type) {
this.type = type;
return this;
}
/**
*
* @return
* The operations
*/
@JsonProperty("operations")
public List<Operation> getOperations() {
return operations;
}
/**
*
* @param operations
* The operations
*/
@JsonProperty("operations")
public void setOperations(List<Operation> operations) {
this.operations = operations;
}
public Service withOperations(List<Operation> operations) {
this.operations = operations;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Service withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(Context).append(id).append(type).append(operations).append(additionalProperties).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Service) == false) {
return false;
}
Service rhs = ((Service) other);
return new EqualsBuilder().append(Context, rhs.Context).append(id, rhs.id).append(type, rhs.type).append(operations, rhs.operations).append(additionalProperties, rhs.additionalProperties).isEquals();
}
}
| true
|
48f1e5f6301eec30badce98e466d2a3f728b8bd7
|
Java
|
nileshmane1988/Selenium
|
/Selenium3/src/webpages/ActitimeLoginPage1.java
|
UTF-8
| 1,141
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
package webpages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ActitimeLoginPage1
{
//datamember should be declared globally with access specifier private, return type should be WebElement.
private WebElement username;
private WebElement password;
private WebElement checkbox;
private WebElement loginbutton;
//datamember should be intialized within constructor
public ActitimeLoginPage(WebDriver driver)
{
username=driver.findElement(By.id("username"));
password=driver.findElement(By.name("pwd"));
checkbox=driver.findElement(By.id("keepLoggedInCheckBox"));
loginbutton=driver.findElement(By.id("loginButton"));
}
//datamember should be utilized with method
public void setUsername()
{
username.sendKeys("admin");
}
public void setPassword()
{
password.sendKeys("manager");
}
public void selctCheckBox()
{
checkbox.click();
}
public void clickOnLoginButton()
{
loginbutton.click();
}
public boolean verifyErrorrMsg() {
// TODO Auto-generated method stub
return false;
}
}
| true
|
383cc47dc1c77f77e7e62434dfb1f8e34bec6f08
|
Java
|
dmitryako/kingroup
|
/tsvlib_java/javax/iox/table/TableDisplayOpt.java
|
UTF-8
| 1,753
| 2.34375
| 2
|
[] |
no_license
|
package javax.iox.table;
import javax.textx.FractionDigitsModel;
/**
* Copyright: www.DmitryKonovalov.org, jc138691, 3/06/2007, 11:16:55
*/
public class TableDisplayOpt
{
private FractionDigitsModel digitsModel;
private int maxNumCols;
private int maxNumRows;
private boolean countOn;
public static final int DEFAULT_MAX_NUM_ROWS = 1000;
public static final int DEFAULT_MAX_NUM_COLS = 100;
public TableDisplayOpt() {
digitsModel = new FractionDigitsModel();
}
public FractionDigitsModel getDigitsModel()
{
return digitsModel;
}
public void setDigitsModel(FractionDigitsModel digitsModel)
{
this.digitsModel = digitsModel;
}
public int getMaxNumCols()
{
return maxNumCols;
}
public void setMaxNumCols(int maxNumCols)
{
this.maxNumCols = maxNumCols;
}
public int calcMaxNumCols(int nCols)
{
if (maxNumCols <= 0)
return nCols;
return Math.min(nCols, maxNumCols);
}
public int calcMaxNumRows(int nRows)
{
if (maxNumRows <= 0)
return nRows;
return Math.min(nRows, maxNumRows);
}
public boolean viewAll(int nCols)
{
if (maxNumCols <= 0)
return true;
return (nCols <= maxNumCols);
}
public void loadDefault()
{
setMaxNumCols(DEFAULT_MAX_NUM_COLS);
setMaxNumRows(DEFAULT_MAX_NUM_ROWS);
digitsModel.loadDefault();
setCountOn(true);
}
public int getMaxNumRows()
{
return maxNumRows;
}
public void setMaxNumRows(int maxNumRows)
{
this.maxNumRows = maxNumRows;
}
public void setCountOn(boolean countOn)
{
this.countOn = countOn;
}
public boolean getCountOn()
{
return countOn;
}
}
| true
|
7c7372a94fb1976c980b674a6743f1e04660c165
|
Java
|
flywind2/joeis
|
/src/irvine/oeis/a270/A270994.java
|
UTF-8
| 316
| 2.4375
| 2
|
[] |
no_license
|
package irvine.oeis.a270;
import irvine.oeis.LinearRecurrence;
/**
* A270994 <code>a(n) = 9454129 + 11184810*n</code>.
* @author Sean A. Irvine
*/
public class A270994 extends LinearRecurrence {
/** Construct the sequence. */
public A270994() {
super(new long[] {-1, 2}, new long[] {9454129, 20638939});
}
}
| true
|
f27f1a6e3e494e1726191ac6dbd1169f3b42cb3d
|
Java
|
springwindyike/mall-project
|
/mall-common/src/main/java/com/ishare/mall/common/base/dto/pay/AliRefundNotifyDTO.java
|
UTF-8
| 2,021
| 1.789063
| 2
|
[] |
no_license
|
package com.ishare.mall.common.base.dto.pay;
import com.ishare.mall.common.base.dto.generic.GenericDTO;
/**
* Created by YinLin on 2015/8/27.
* Description : 阿里退款
* Version 1.0
*/
public class AliRefundNotifyDTO extends GenericDTO {
private static final long serialVersionUID = -2601175208254084539L;
private String notify_time; //通知时间
private String notify_type; //通知类型
private String notify_id; //通知校验id
private String sign_type; //签名方式
private String sign; //签名
private String batch_no; //退款批次号
private String success_num; //退款成功总数
private String result_details; //退款结果明细
public String getNotify_time() {
return notify_time;
}
public void setNotify_time(String notify_time) {
this.notify_time = notify_time;
}
public String getNotify_type() {
return notify_type;
}
public void setNotify_type(String notify_type) {
this.notify_type = notify_type;
}
public String getNotify_id() {
return notify_id;
}
public void setNotify_id(String notify_id) {
this.notify_id = notify_id;
}
public String getSign_type() {
return sign_type;
}
public void setSign_type(String sign_type) {
this.sign_type = sign_type;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getBatch_no() {
return batch_no;
}
public void setBatch_no(String batch_no) {
this.batch_no = batch_no;
}
public String getSuccess_num() {
return success_num;
}
public void setSuccess_num(String success_num) {
this.success_num = success_num;
}
public String getResult_details() {
return result_details;
}
public void setResult_details(String result_details) {
this.result_details = result_details;
}
}
| true
|
7a0c01bc87683b8677a9782131926c8711a034bd
|
Java
|
raviselenium18/TestingOne
|
/src/test/java/One.java
|
UTF-8
| 1,479
| 2.40625
| 2
|
[] |
no_license
|
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class One {
/*
* System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
* driver = new FirefoxDriver();
* static String driverPath = "IE driver path";
*/
static String driverPath = "D:\\Software\\Java\\jars\\";
public WebDriver driver;
@BeforeClass
public void setUp() {
System.out.println("Hello Sweta Ji");
System.out.println("launching IE browser !!");
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5L, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
// WebDriver driver = new FirefoxDriver();
@Test
public void add() {
System.out.println("Add");
//driver = new ChromeDriver();
//System.setProperty("webdriver.chrome.driver", "D:\\Software\\Java\\jars\\chromedriver.exe");
driver.get("https://facebook.com");
driver.findElement(By.cssSelector("#email")).sendKeys("testing@gmail.com");
driver.findElement(By.cssSelector("#pass")).sendKeys("Testing123!");
driver.findElement(By.cssSelector("#loginbutton")).click();
}
@Test
public void multiply() {
System.out.println("Multiply");
//driver.quit();
}
}
| true
|
88dedbfda92d834620c98e0b6e9f081a61490998
|
Java
|
JUWON-KEVIN-LEE/FC_STUDY
|
/Android/AndroidMemo2/app/src/main/java/com/immymemine/kevin/androidmemo2/DBHelper.java
|
UTF-8
| 1,452
| 2.84375
| 3
|
[] |
no_license
|
package com.immymemine.kevin.androidmemo2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by quf93 on 2017-09-21.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "sqlite.db";
private static final int DB_VERSION = 1;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// super 에서 넘겨받은 DB 가 생성되어 있는지 확인한 후
// 없으면 onCreate 호출
// 있으면 버전 체크해서 존재하는 DB 보다 버전이 높으면 onUpgrade 를 호출해준다
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 최초 생성할 Table 을 정의
// DB 가 업데이트되면 모든 히스토리가 Query 에 반영되어 있어야 한다
String createQuery = "CREATE TABLE `note` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT, `content` TEXT, `n_datetime` TEXT )";
db.execSQL(createQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// oldVersion 과 newVersion 을 비교해서
// 히스토리를 모두 반영해야 한다
}
}
| true
|
3818c6954772008a7ff9e935fd87501c4a36c816
|
Java
|
laitsky/if402
|
/UAS_27047_VincentDiamond/src/umn/ac/id/_27047/Main.java
|
UTF-8
| 17,618
| 2.578125
| 3
|
[] |
no_license
|
package umn.ac.id._27047;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static ArrayList<Aktor> aktors = new ArrayList<>();
static ArrayList<Celebgram> celebgrams = new ArrayList<>();
static ArrayList<Majalah> majalahs = new ArrayList<>();
static ArrayList<Baliho> balihos = new ArrayList<>();
static ArrayList<Order> orders = new ArrayList<>();
public static void main(String[] args) {
seedData();
Scanner scanner = new Scanner(System.in);
int menuInput;
int kategori;
int umur;
int tinggiBadan;
int beratBadan;
int jmlFollowers;
int luas;
int jmlHariSewa;
String bidang = null;
String nama;
String media;
String ltkHlmPromosi;
String tglMulai;
while (true) {
menuUtama();
menuInput = scanner.nextInt();
switch (menuInput) {
case 1:
menuPenambahanMedia();
menuInput = scanner.nextInt();
showKategori();
kategori = scanner.nextInt();
switch (kategori) {
case 1:
bidang = "Furnitur";
break;
case 2:
bidang = "Makanan";
break;
case 3:
bidang = "Tanaman";
break;
case 4:
bidang = "Otomotif";
break;
case 5:
bidang = "Musik";
break;
default:
System.out.println("Input kamu salah!");
break;
}
switch (menuInput) {
case 1:
System.out.print("Masukkan nama: ");
scanner.nextLine();
nama = scanner.nextLine();
System.out.print("Masukkan umur: ");
umur = scanner.nextInt();
System.out.print("Masukkan tinggi badan: ");
tinggiBadan = scanner.nextInt();
System.out.print("Masukkan berat badan: ");
beratBadan = scanner.nextInt();
System.out.print("Masukkan jumlah followers: ");
jmlFollowers = scanner.nextInt();
System.out.print("Masukkan media sosial yang digunakan: ");
scanner.nextLine();
media = scanner.nextLine();
celebgrams.add(new Celebgram(nama, umur, tinggiBadan, beratBadan, jmlFollowers, media, bidang));
System.out.println("Media baru telah dimasukkan");
break;
case 2:
System.out.print("Masukkan nama: ");
scanner.nextLine();
nama = scanner.nextLine();
System.out.print("Masukkan luas: ");
luas = scanner.nextInt();
System.out.print("Masukkan letak halaman promosi: ");
scanner.nextLine();
ltkHlmPromosi = scanner.nextLine();
majalahs.add(new Majalah(nama, luas, ltkHlmPromosi, bidang));
System.out.println("Media baru telah dimasukkan");
break;
}
break;
case 2:
System.out.println("===============================");
System.out.println("\tWemen Marketing Agent\t");
int idx = 1;
int reqIdx;
int total = 0;
int totalPayment;
int nominalPembayaran;
int aktorIdx = aktors.size();
int celebIdx = aktorIdx + celebgrams.size();
int balihoIdx = celebIdx + balihos.size();
int majalahIdx = balihoIdx + majalahs.size();
showKategori();
kategori = scanner.nextInt();
switch (kategori) {
case 1:
bidang = "Furnitur";
break;
case 2:
bidang = "Makanan";
break;
case 3:
bidang = "Tanaman";
break;
case 4:
bidang = "Otomotif";
break;
case 5:
bidang = "Musik";
break;
default:
System.out.println("Input kamu salah!");
break;
}
System.out.print("Tanggal mulai (DDMMYYYY): ");
scanner.nextLine();
tglMulai = scanner.nextLine();
System.out.print("Banyak hari penyewaan: ");
jmlHariSewa = scanner.nextInt();
for (Aktor a : aktors) {
System.out.println("===============================");
System.out.println("No\t\t\t: " + idx);
System.out.println("Media\t\t: Aktor");
System.out.println("Nama\t\t: " + a.getNama());
System.out.println("Tinggi Badan: " + a.getTinggiBadan());
System.out.println("Berat Badan\t: " + a.getBeratBadan());
System.out.println("Jumlah Fans\t: " + a.getFans());
System.out.println("Nama Fansclub: " + a.getFanClub());
System.out.println("Harga\t\t: " + (a.getHarga() * jmlHariSewa));
idx++;
}
for (Celebgram c : celebgrams) {
System.out.println("===============================");
System.out.println("No\t\t\t: " + idx);
System.out.println("Media\t\t: Celebgram");
System.out.println("Nama\t\t: " + c.getNama());
System.out.println("Tinggi Badan: " + c.getTinggiBadan());
System.out.println("Berat Badan\t: " + c.getBeratBadan());
System.out.println("Jumlah Fans\t: " + c.getFollowers());
System.out.println("Nama Fansclub: " + c.getAkunMedia());
System.out.println("Bidang\t\t: " + c.getBidang());
System.out.print("Harga\t\t: ");
if (c.getBidang().equals(bidang)) {
System.out.println(c.getHarga() + (c.getHarga() * jmlHariSewa + 50_000 * jmlHariSewa));
} else {
System.out.println(c.getHarga() * jmlHariSewa);
}
idx++;
}
for (Baliho b : balihos) {
System.out.println("===============================");
System.out.println("No\t\t\t: " + idx);
System.out.println("Media\t\t: Baliho");
System.out.println("Nama\t\t: " + b.getNama());
System.out.println("Luas\t\t: " + b.getLuas());
System.out.println("Letak\t\t: " + b.getLetak());
System.out.println("Harga\t\t: " + b.getHarga() * jmlHariSewa);
idx++;
}
for (Majalah m : majalahs) {
System.out.println("===============================");
System.out.println("No\t\t\t: " + idx);
System.out.println("Media\t\t: Majalah");
System.out.println("Nama\t\t: " + m.getNama());
System.out.println("Luas\t\t: " + m.getLuas());
System.out.println("Letak\t\t: " + m.getLetak());
System.out.println("Bidang\t\t: " + m.getBidang());
System.out.print("Harga\t\t: ");
if (m.getBidang().equals(bidang)) {
System.out.println(m.getHarga() + (m.getHarga() * jmlHariSewa + 200_000 * jmlHariSewa));
} else {
System.out.println(m.getHarga() * jmlHariSewa);
}
idx++;
}
System.out.print("Masukkan nomor media: ");
reqIdx = scanner.nextInt();
System.out.print("Masukkan uang untuk pembayaran: ");
nominalPembayaran = scanner.nextInt();
if (reqIdx <= aktorIdx) {
if (nominalPembayaran < aktors.get(reqIdx).getHarga() * jmlHariSewa) {
System.out.println("Uang tidak mencukupi");
} else {
totalPayment = aktors.get(reqIdx).getHarga() * jmlHariSewa;
orders.add(new Order(aktors.get(reqIdx - 1), bidang, tglMulai, "Aktor", jmlHariSewa, totalPayment));
System.out.println("Pemesanan anda sukses");
}
} else if (reqIdx <= celebIdx) {
reqIdx -= (aktorIdx + 1);
if (celebgrams.get(reqIdx).getBidang().equals(bidang)) {
total = 500_000 * jmlHariSewa;
}
if (nominalPembayaran < celebgrams.get(reqIdx).getHarga() * jmlHariSewa + total) {
System.out.println("Uang tidak mencukupi");
} else {
totalPayment = (celebgrams.get(reqIdx).getHarga() * jmlHariSewa) + total;
orders.add(new Order(celebgrams.get(reqIdx), bidang, tglMulai, "Celebgram", jmlHariSewa, totalPayment));
System.out.println("Pemesanan anda sukses");
}
} else if (reqIdx <= balihoIdx) {
reqIdx -= (celebIdx + 1);
if (nominalPembayaran < balihos.get(reqIdx).getHarga() * jmlHariSewa) {
System.out.println("Uang tidak mencukupi");
} else {
totalPayment = balihos.get(reqIdx).getHarga() * jmlHariSewa;
orders.add(new Order(balihos.get(reqIdx), bidang, tglMulai, "Baliho", jmlHariSewa, totalPaymernet
));
System.out.println("Pemesanan anda sukses");
}
} else if (reqIdx <= majalahIdx) {
reqIdx -= (balihoIdx + 1);
if (majalahs.get(reqIdx).getBidang().equals(bidang)) {
total = 200_000 * jmlHariSewa;
}
if (nominalPembayaran < majalahs.get(reqIdx).getHarga() * jmlHariSewa + total) {
System.out.println("Uang tidak mencukupi");
} else {
totalPayment = (majalahs.get(reqIdx).getHarga() * jmlHariSewa) + total;
orders.add(new Order(majalahs.get(reqIdx), bidang, tglMulai, "Majalah", jmlHariSewa, totalPayment));
System.out.println("Pemesanan anda sukses");
}
} else {
System.out.println("Nomor media tidak terdapat di dalam daftar media");
}
break;
case 3:
if (orders.isEmpty()) {
System.out.println("Tidak ada pesanan!");
break;
}
printOrders();
System.out.println("===============================");
System.out.println("1. Batalkan order");
System.out.println("2. Kembali ke menu utama");
System.out.println("===============================");
System.out.print("Pilih menu (1-2): ");
menuInput = scanner.nextInt();
if (menuInput == 1) {
System.out.print("Masukkan nomor yang ingin dibatalkan: ");
reqIdx = scanner.nextInt();
reqIdx--;
if (orders.get(reqIdx).getTanggal().equals("03062020")) {
System.out.println("Pesanan ini tidak dapat dibatalkan");
} else {
orders.remove(reqIdx);
System.out.println("Pesanan anda berhasil dibatalkan");
}
} else if (menuInput == 2) {
break;
}
break;
case 4:
showCredit();
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Angka yang dimasukkan tidak valid!");
}
}
}
private static void seedData() {
aktors.add(new Aktor("Chris Evans", 30, 170, 60, 100_000, "Captain America Lovers"));
aktors.add(new Aktor("Robert Downey Jr.", 31, 171, 61, 120_000, "Ironman Lovers"));
aktors.add(new Aktor("Chris Hemsworth", 32, 172, 62, 140_000, "Thor Lovers"));
celebgrams.add(new Celebgram("Awkarin", 25, 165, 45, 100_000, "Instagram", "Furnitur"));
celebgrams.add(new Celebgram("Anya Geraldine", 26, 166, 46, 120_000, "Twitter", "Makanan"));
celebgrams.add(new Celebgram("Devina Aurel", 27, 167, 47, 140_000, "Youtube", "Tanaman"));
balihos.add(new Baliho("Baliho Jakarta Pusat", 6, "Jakarta Pusat"));
balihos.add(new Baliho("Baliho Jakarta Barat", 8, "Jakarta Barat"));
balihos.add(new Baliho("Baliho Jakarta Utara", 9, "Jakarta Utara"));
majalahs.add(new Majalah("Home Decor", 15, "Halaman 2", "Furnitur"));
majalahs.add(new Majalah("Sedap", 18, "Halaman 3", "Makanan"));
majalahs.add(new Majalah("Otomotif", 21, "Halaman 4", "Tanaman"));
}
private static void menuUtama() {
System.out.println("===============================");
System.out.println("\tWemen Marketing Agent\t");
System.out.println("===============================");
System.out.println("1. Penambahan Media");
System.out.println("2. Penyewaan Media");
System.out.println("3. Check Employment / Rental");
System.out.println("4. Credits");
System.out.println("5. Exit");
System.out.println("===============================");
System.out.print("Pilih Menu (1-5): ");
}
private static void menuPenambahanMedia() {
System.out.println("===============================");
System.out.println("\tWemen Marketing Agent\t");
System.out.println("===============================");
System.out.println("1. Celebgram");
System.out.println("2. Majalah");
System.out.println("===============================");
System.out.print("Pilih Media (1-2): ");
}
private static void showKategori() {
System.out.println("===============================");
System.out.println("1. Furnitur");
System.out.println("2. Makanan");
System.out.println("3. Tanaman");
System.out.println("4. Otomotif");
System.out.println("5. Musik");
System.out.println("===============================");
System.out.print("Pilih Kategori (1-5): ");
}
private static void printOrders() {
int idx = 1;
System.out.println("===============================");
System.out.println("\tWemen Marketing Agent\t");
System.out.println("===============================");
for (Order o : orders) {
System.out.println("No\t\t\t: " + (idx));
System.out.println("Media\t\t: " + o.getMedia());
System.out.println("Nama\t\t: " + o.getMediaPromosi().getNama());
System.out.println("Tanggal\t\t: " + o.getTanggal());
System.out.println("Durasi Kontrak: " + o.getJangkaWaktu());
System.out.println("Harga\t\t: " + o.getMediaPromosi().getHarga());
}
}
private static void showCredit() {
System.out.println("===============================");
System.out.println("\tWemen Marketing Agent\t");
System.out.println("===============================");
System.out.println("Name: Vincent Diamond");
System.out.println("NIM: 00000027047");
System.out.println("===============================");
}
}
| true
|
ba07f4bea351760b567ddde171dd4fd5eb628637
|
Java
|
LichtHund/DocDex
|
/discord/src/main/java/me/piggypiglet/docdex/config/Config.java
|
UTF-8
| 1,516
| 1.96875
| 2
|
[
"MIT"
] |
permissive
|
package me.piggypiglet.docdex.config;
import com.google.gson.annotations.JsonAdapter;
import com.google.inject.Singleton;
import me.piggypiglet.docdex.config.deserialization.UrlDeserializer;
import me.piggypiglet.docdex.db.server.JavadocCategory;
import me.piggypiglet.docdex.file.annotations.File;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
// ------------------------------
// Copyright (c) PiggyPiglet 2020
// https://www.piggypiglet.me
// ------------------------------
@File(
internalPath = "/config.json",
externalPath = "./config.json",
stopOnFirstCreate = true
)
@Singleton
public final class Config {
private String token;
private String prefix;
@JsonAdapter(UrlDeserializer.class) private String url;
private String defaultJavadoc;
private Map<String, JavadocCategory> defaultCategories;
private Presence presence;
private MysqlConfig mysql;
@NotNull
public String getToken() {
return token;
}
@NotNull
public String getPrefix() {
return prefix;
}
@NotNull
public String getUrl() {
return url;
}
@NotNull
public String getDefaultJavadoc() {
return defaultJavadoc;
}
@NotNull
public Map<String, JavadocCategory> getDefaultCategories() {
return defaultCategories;
}
@NotNull
public Presence getPresence() {
return presence;
}
@NotNull
public MysqlConfig getMysql() {
return mysql;
}
}
| true
|
4a485301c23783511cd6c89e74359d7d19ff0cec
|
Java
|
Megaprog/tuples
|
/src/main/java/org/jmmo/tuple/Tuple5.java
|
UTF-8
| 4,547
| 3.125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.jmmo.tuple;
import org.jmmo.function.Consumer5;
import org.jmmo.function.Function5;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Objects;
public class Tuple5<T0, T1, T2, T3, T4> implements Tuple, Comparable<Tuple5<T0, T1, T2, T3, T4>> {
private static final long serialVersionUID = 8215132094283212974L;
private final T0 value0;
private final T1 value1;
private final T2 value2;
private final T3 value3;
private final T4 value4;
protected Tuple5(T0 value0, T1 value1, T2 value2, T3 value3, T4 value4) {
this.value0 = value0;
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
this.value4 = value4;
}
public static <V0, V1, V2, V3, V4> Tuple5<V0, V1, V2, V3, V4> of(V0 v0, V1 v1, V2 v2, V3 v3, V4 v4) {
return new Tuple5<>(v0, v1, v2, v3, v4);
}
@SuppressWarnings("unchecked")
public static <A, V0 extends A, V1 extends A, V2 extends A, V3 extends A, V4 extends A> Tuple5<V0, V1, V2, V3, V4> fromArray(A[] values) {
return new Tuple5<>((V0) values[0], (V1) values[1], (V2) values[2], (V3) values[3], (V4) values[4]);
}
@SuppressWarnings("unchecked")
public static <A, V0 extends A, V1 extends A, V2 extends A, V3 extends A, V4 extends A> Tuple5<V0, V1, V2, V3, V4> fromIterator(Iterator<A> iterator) {
return new Tuple5<>((V0) iterator.next(), (V1) iterator.next(), (V2) iterator.next(), (V3) iterator.next(), (V4) iterator.next());
}
public void unfold(Consumer5<T0, T1, T2, T3, T4> valueConsumer) {
valueConsumer.accept(getValue0(), getValue1(), getValue2(), getValue3(), getValue4());
}
public <R> R unfoldResult(Function5<T0, T1, T2, T3, T4, R> valueFunction) {
return valueFunction.apply(getValue0(), getValue1(), getValue2(), getValue3(), getValue4());
}
public T0 getValue0() {
return value0;
}
public T1 getValue1() {
return value1;
}
public T2 getValue2() {
return value2;
}
public T3 getValue3() {
return value3;
}
public T4 getValue4() {
return value4;
}
@Override public int getSize() {
return 5;
}
@SuppressWarnings("unchecked")
@Override public <E> E get(int i) {
switch (i) {
case 0: return (E) getValue0();
case 1: return (E) getValue1();
case 2: return (E) getValue2();
case 3: return (E) getValue3();
case 4: return (E) getValue4();
}
throw new IndexOutOfBoundsException("Tuple5 contains five elements but " + i + " element requested");
}
@Override public Object[] toArray() {
return new Object[] { getValue0(), getValue1(), getValue2(), getValue3(), getValue4() };
}
@SuppressWarnings("unchecked")
private static final Comparator<Tuple5> comparator =
Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue0(), Tuple1.nullComparator)
.thenComparing(
Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue1(), Tuple1.nullComparator))
.thenComparing(
Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue2(), Tuple1.nullComparator))
.thenComparing(
Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue3(), Tuple1.nullComparator))
.thenComparing(
Comparator.<Tuple5, Comparable<Object>>comparing(tuple -> (Comparable) tuple.getValue4(), Tuple1.nullComparator));
@SuppressWarnings("unchecked")
@Override public int compareTo(Tuple5<T0, T1, T2, T3, T4> o) {
return comparator.compare(this, o);
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tuple5)) return false;
Tuple5<?, ?, ?, ?, ?> tuple5 = (Tuple5<?, ?, ?, ?, ?>) o;
return Objects.deepEquals(getValue0(), tuple5.getValue0()) &&
Objects.deepEquals(getValue1(), tuple5.getValue1()) &&
Objects.deepEquals(getValue2(), tuple5.getValue2()) &&
Objects.deepEquals(getValue3(), tuple5.getValue3()) &&
Objects.deepEquals(getValue4(), tuple5.getValue4());
}
@Override public int hashCode() {
return Tuple.hashCode(this);
}
@Override public String toString() {
return Tuple.toString(this);
}
}
| true
|
2469b8828a3ca01762a9540547ae8c6db6984558
|
Java
|
vcolonges/MachINSAlaver
|
/app/src/main/java/com/machinsa_laver/machinsalaver/fragments/ResidencesFragment.java
|
UTF-8
| 4,320
| 2.0625
| 2
|
[] |
no_license
|
package com.machinsa_laver.machinsalaver.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.machinsa_laver.machinsalaver.Application;
import com.machinsa_laver.machinsalaver.R;
import com.machinsa_laver.machinsalaver.SaisirVA;
import com.machinsa_laver.machinsalaver.adapter.MachineAdapter;
import com.machinsa_laver.machinsalaver.adapter.ResidenceImageAdapter;
import com.machinsa_laver.machinsalaver.model.Machine;
import com.machinsa_laver.machinsalaver.model.Residence;
import com.machinsa_laver.machinsalaver.model.ResidenceImage;
import java.util.ArrayList;
public class ResidencesFragment extends Fragment {
private ListView mListView;
private TextView residenceC;
ArrayList<ResidenceImage> dataModels;
private static ResidenceImageAdapter adapter;
public ResidencesFragment() {
// Required empty public constructor
}
public static ResidencesFragment newInstance(String param1, String param2) {
ResidencesFragment fragment = new ResidencesFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View finalView = inflater.inflate(R.layout.fragment_residences, container, false);
mListView = (ListView) finalView.findViewById(R.id.listResi);
dataModels= new ArrayList<>();
ArrayList<String> listeResi = new ArrayList<>();
listeResi.add("Résidence B");
listeResi.add("Résidence D");
listeResi.add("Résidence E");
listeResi.add("Résidence F");
listeResi.add("Résidence G/J");
listeResi.add("Résidence H");
listeResi.add("Résidence I");
for (String res : listeResi){
boolean resCourante = false;
if(Application.RESIDENCE.equals(res)) {
resCourante = true;
}
dataModels.add(new ResidenceImage(res, resCourante));
}
adapter = new ResidenceImageAdapter(dataModels,getActivity().getApplicationContext());
mListView.setAdapter(adapter);
this.residenceC = (TextView) finalView.findViewById(R.id.residencecourante);
residenceC.setText("Résidence actuelle : "+Application.RESIDENCE);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ResidenceImage entry = (ResidenceImage) parent.getItemAtPosition(position);
Application.RESIDENCE = entry.getNom();
residenceC.setText("Résidence actuelle : "+Application.RESIDENCE);
// entry.setEstLaResidenceCourante(true);
/* Fragment frag = new HomeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
val transaction = supportFragmentManager.beginTransaction()
val tag = fragments[index].tag
// if the fragment has not yet been added to the container, add it first
if (supportFragmentManager.findFragmentByTag(tag) == null) {
transaction.add(R.id.container, fragments[index], tag)
}
transaction.hide(fragments[navigationBar.currentTabPosition])
transaction.show(fragments[index])
transaction.commit()
ft.commit();*/
}
});
return finalView;
}
}
| true
|
196765ee5ede7e38a90f2e8fa739aff96c1eaed5
|
Java
|
AlexRenCN/ExampleForSpel
|
/src/main/java/com/alex/spel/CallingConstructors.java
|
UTF-8
| 649
| 2.40625
| 2
|
[] |
no_license
|
package com.alex.spel;
import com.alex.bean.User;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
* 调用构造函数
*/
public class CallingConstructors {
public static void main(String[] args) {
ExpressionParser parser=new SpelExpressionParser();
User user=parser.parseExpression("new com.alex.bean.User()").getValue(User.class);
user.setName("alex");
System.out.println(user);
}
}
| true
|
329eeb6cbe9cb569e60acd9f74affbbb7862b088
|
Java
|
crisgicr/medicamentos
|
/src/main/java/com/medicamentos/model/Usuario.java
|
UTF-8
| 2,737
| 2.28125
| 2
|
[] |
no_license
|
package com.medicamentos.model;
// Generated 31/10/2017 08:33:58 PM by Hibernate Tools 5.2.5.Final
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Usuario generated by hbm2java
*/
@Entity
@Table(name = "usuario", catalog = "medicamentos")
@SuppressWarnings("serial")
public class Usuario implements java.io.Serializable {
private int id;
private String identificacion;
private String clave;
private String role;
private char estado;
private String nombre;
private List<Establecimiento> establecimientos;
public Usuario() {
}
public Usuario(int id, String identificacion, String clave, String role, char estado) {
this.id = id;
this.identificacion = identificacion;
this.clave = clave;
this.role = role;
this.estado = estado;
}
public Usuario(int id, String identificacion, String clave, String role, char estado, List<Establecimiento> establecimientos) {
this.id = id;
this.identificacion = identificacion;
this.clave = clave;
this.role = role;
this.estado = estado;
this.establecimientos = establecimientos;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "identificacion", unique = true, nullable = false, length = 45)
public String getIdentificacion() {
return this.identificacion;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
@Column(name = "clave", nullable = false, length = 100)
public String getClave() {
return this.clave;
}
public void setClave(String clave) {
this.clave = clave;
}
@Column(name = "rol", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "usuario")
public List<Establecimiento> getEstablecimientos() {
return this.establecimientos;
}
public void setEstablecimientos(List<Establecimiento> establecimientos) {
this.establecimientos = establecimientos;
}
@Column(name = "estado", nullable = false, length = 1)
public char getEstado() {
return estado;
}
public void setEstado(char estado) {
this.estado = estado;
}
@Column(name = "nombre", nullable = false, length = 100)
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| true
|
cd4c40c77f7a42f6506ca583c005bf3a363fce4d
|
Java
|
RukmaniGanapathy/mcproject
|
/app/src/main/java/edu/project/mobilecomputing/mc_project/ui/Constants.java
|
UTF-8
| 2,632
| 2.203125
| 2
|
[] |
no_license
|
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.project.mobilecomputing.mc_project.ui;
import com.google.android.gms.maps.model.LatLng;
import java.util.HashMap;
/**
* Constants used in this sample.
*/
public final class Constants {
//Referred from https://github.com/googlesamples/android-play-location/tree/master/Geofencing/
private Constants() {
}
public static final String PACKAGE_NAME = "com.google.android.gms.location.Geofence";
public static final String SHARED_PREFERENCES_NAME = PACKAGE_NAME + ".SHARED_PREFERENCES_NAME";
public static final String GEOFENCES_ADDED_KEY = PACKAGE_NAME + ".GEOFENCES_ADDED_KEY";
/**
* Used to set an expiration time for a geofence. After this amount of time Location Services
* stops tracking the geofence.
*/
public static final long GEOFENCE_EXPIRATION_IN_HOURS = 12;
/**
* For this sample, geofences expire after twelve hours.
*/
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS =
GEOFENCE_EXPIRATION_IN_HOURS * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 800; // 1 mile, 1.6 km
public static HashMap<String, LatLng> SUPERMARKETS = new HashMap<String, LatLng>();
static {
//populate from google maps
SUPERMARKETS.put("UPALMS", new LatLng(33.419310, -111.919532));
SUPERMARKETS.put("Walmart Supercenter, Elliot Rd", new LatLng(33.350258, -111.960815));
SUPERMARKETS.put("Walmart Express - Arizona State University", new LatLng(33.414428, -111.929201));
SUPERMARKETS.put("Walmart Supercenter, Southern", new LatLng(33.393357, -111.928466));
SUPERMARKETS.put("Noble library", new LatLng(33.420132, -111.930642));
SUPERMARKETS.put("SF", new LatLng(37.621313, -122.378955));
}
public static HashMap<String, LatLng> getSUPERMARKETS() {
return SUPERMARKETS;
}
public static void setSUPERMARKETS(HashMap<String, LatLng> SUPERMARKETS) {
Constants.SUPERMARKETS = SUPERMARKETS;
}
}
| true
|
5075526c126efa62eb5fa7e40757e98a5a8671be
|
Java
|
jvelezb/estructura-datos-ago-2015
|
/segundoParcial/Vehiculos/src/vehiculos/Vocho.java
|
UTF-8
| 920
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vehiculos;
/**
*
* @author juanvelezballesteros
*/
public class Vocho implements Vehiculo{
@Override
public void direccion(){
System.out.println("Vocho construye su volante");
}
@Override
public String frenar(){
System.out.println("Vocho"
+ " implementa "
+ "sus frenos de baja velocidad");
return "Frenando Vocho ";
}
@Override
public String acelerar(){
System.out.println("Vocho acelerando muuuuy lento");
return "Vocho tratando de Acelerar";
}
@Override
public int velocidad(){
System.out.println("V0cho con palanca de 4 velocidades");
return 100;
}
}
| true
|
b009113c0c8f652e580a2bb10e60f2e8181cbb77
|
Java
|
darthoo/TaskAndRewards
|
/app/src/main/java/com/yolotasker/yolotasker/data/impl/TaskRepositoryImpl.java
|
UTF-8
| 847
| 2.15625
| 2
|
[] |
no_license
|
package com.yolotasker.yolotasker.data.impl;
import android.content.Context;
import com.yolotasker.yolotasker.data.TaskRepository;
import com.yolotasker.yolotasker.data.db.DBHelper;
import com.yolotasker.yolotasker.data.model.Task;
import com.yolotasker.yolotasker.ui.activity.MainActivity;
import java.lang.annotation.Inherited;
import java.util.List;
import javax.inject.Inject;
/**
* Created by AndroidDev on 24.07.2017.
*/
public class TaskRepositoryImpl implements TaskRepository {
private DBHelper dbHelper;
@Inject
public TaskRepositoryImpl(DBHelper dbHelper) {
//TODO Implement dependency injection via dagger
this.dbHelper = dbHelper;
}
@Override
public List<Task> getTasks() {
return dbHelper.selectAllTasks();
}
@Override
public void addTask(Task task) {
}
}
| true
|
bdd876955f225c9b7ec175f132962897accfa3d7
|
Java
|
pinpoint-apm/pinpoint
|
/collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteFilterChain.java
|
UTF-8
| 1,943
| 2.046875
| 2
|
[
"DOC",
"LicenseRef-scancode-free-unknown",
"CC0-1.0",
"OFL-1.1",
"GPL-1.0-or-later",
"CC-PDDC",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"MITNFA",
"MIT",
"CC-BY-4.0",
"OFL-1.0"
] |
permissive
|
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.collector.cluster.route;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.navercorp.pinpoint.collector.cluster.route.filter.RouteFilter;
public class DefaultRouteFilterChain<T extends RouteEvent> implements RouteFilterChain<T> {
private final Logger logger = LogManager.getLogger(this.getClass());
private final List<RouteFilter<T>> filterList;
public DefaultRouteFilterChain() {
this.filterList = new CopyOnWriteArrayList<>();
}
public DefaultRouteFilterChain(List<RouteFilter<T>> filterList) {
this.filterList = new CopyOnWriteArrayList<>(filterList);
}
@Override
public void addLast(RouteFilter<T> filter) {
filterList.add(filter);
}
@Override
public void doEvent(T event) {
for (RouteFilter<T> filter : filterList) {
try {
filter.doEvent(event);
} catch (Exception e) {
if (logger.isWarnEnabled()) {
logger.warn(filter.getClass().getSimpleName() + " filter occurred exception. Error:" + e.getMessage() + ".", e);
}
}
}
}
}
| true
|
7df57dda31d2809a0b03c1b9240a48975696b417
|
Java
|
SkateScout/c-geo-opensource
|
/src/cgeo/geocaching/cgCacheDifficultyComparator.java
|
UTF-8
| 598
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package cgeo.geocaching;
import java.util.Comparator;
import android.util.Log;
public class cgCacheDifficultyComparator implements Comparator<cgCache> {
public int compare(cgCache cache1, cgCache cache2) {
try {
if (cache1.difficulty == null || cache2.difficulty == null) {
return 0;
}
if (cache1.difficulty > cache2.difficulty) {
return 1;
} else if (cache2.difficulty > cache1.difficulty) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgCacheDifficultyComparator.compare: " + e.toString());
}
return 0;
}
}
| true
|
2134b21f39d52c9bfe6ab71337ac53d768170c35
|
Java
|
tn841/java_intern
|
/webCrawling/src/main/java/com/test/controller/MemberController.java
|
UTF-8
| 3,503
| 2.359375
| 2
|
[] |
no_license
|
package com.test.controller;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.test.member.Member;
import com.test.member.MemberDaoImpl;
@Controller
public class MemberController {
@Autowired
public MemberDaoImpl memberDao;
@RequestMapping(value="login")
public ModelAndView login(
@RequestParam(value="error", required=false) String error,
@RequestParam(value="logout", required=false) String logout
){
ModelAndView mv = new ModelAndView();
if(error != null){
mv.addObject("error", "아이디 또는 비밀번호가 틀렸습니다.");
}
if(logout != null){
mv.addObject("msg", "성공적으로 로그아웃 되었습니다.");
}
mv.setViewName("login");
return mv;
}
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView mv = new ModelAndView();
ArrayList<Member> member_list = new ArrayList<Member>();
member_list = memberDao.selectAll();
System.out.println("memberdao : "+memberDao);
System.out.println("member_list : "+member_list);
mv.setViewName("hello");
mv.addObject("title", "select_All");
mv.addObject("member_list", member_list);
return mv;
}
@RequestMapping("select_one")
public ModelAndView select_one(@RequestParam int no){
ModelAndView mv = new ModelAndView();
Member findMember = memberDao.select(no);
System.out.println("findMember : "+findMember);
mv.addObject("title", "select_one");
mv.setViewName("hello");
return mv;
}
@RequestMapping("insert")
public ModelAndView insert(){
ModelAndView mv = new ModelAndView();
int last_no = memberDao.select_last_no();
System.out.println("last_no : "+last_no);
int result = memberDao.insert_member(new Member("name"+(last_no+1), 0));
System.out.println("insert result : "+result);
mv.addObject("title", "insert");
mv.setViewName("hello");
return mv;
}
@RequestMapping("update")
public ModelAndView update(){
ModelAndView mv = new ModelAndView();
int last_no = memberDao.select_last_no();
Member targetMember = memberDao.select(last_no);
targetMember.setMember_name(targetMember.getMember_name()+"_edit!");
targetMember.setMember_age(targetMember.getMember_age()+1);
memberDao.update(targetMember);
//System.out.println("insert result : "+result);
mv.addObject("title", "update");
mv.setViewName("hello");
return mv;
}
@RequestMapping("/delete")
public ModelAndView delete(@RequestParam int no){
ModelAndView mv = new ModelAndView();
int rrow = memberDao.delete_member(no);
System.out.println("삭제된 열 갯수 : "+rrow);
mv.addObject("title", "delete");
mv.setViewName("hello");
return mv;
}
@RequestMapping("/timestamp")
public ModelAndView timestamp(){
ModelAndView mv = new ModelAndView();
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
System.out.println("ts 확인 : "+ts);
mv.addObject("title", "timestamp");
mv.setViewName("hello");
return mv;
}
}
| true
|
4f651a21885fabf1d8276cfe1ff9778de813ed23
|
Java
|
bohdanvan/javaoop-group75
|
/src/com/bvan/oop/lesson10/tree/RatingToMovieExample.java
|
UTF-8
| 1,113
| 3.515625
| 4
|
[] |
no_license
|
package com.bvan.oop.lesson10.tree;
import com.bvan.oop.lesson10.Movie;
import com.bvan.oop.lesson10.MoviesFactory;
import java.util.List;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* @author bvanchuhov
*/
public class RatingToMovieExample {
public static void main(String[] args) {
NavigableMap<Double, Movie> ratingToMovie = new TreeMap<>();
List<Movie> movies = MoviesFactory.createMovies();
for (Movie movie : movies) {
ratingToMovie.put(movie.getRating(), movie);
}
for (Movie movie : ratingToMovie.values()) {
System.out.println(movie);
}
System.out.println();
SortedMap<Double, Movie> myMovies = ratingToMovie.tailMap(7.8);
for (Movie movie : myMovies.values()) {
System.out.println(movie);
}
System.out.println(ratingToMovie.lastKey());
System.out.println(ratingToMovie.firstKey());
System.out.println(ratingToMovie.floorEntry(8.0));
System.out.println(ratingToMovie.ceilingEntry(8.0));
}
}
| true
|
7fa41775f9dca1b0d4bf4feb405a4a00c55cd7fe
|
Java
|
DTMGEEK/PhoneProtectPro
|
/AndrodProtectorPro/AndroidPortectPro/app/src/main/java/com/example/androiddefprot/receiver/CallPhoneReceiver.java
|
UTF-8
| 1,122
| 2.59375
| 3
|
[] |
no_license
|
package com.example.androiddefprot.receiver;
import com.example.androiddefprot.ui.LostProtectedActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
*
* @Title: CallPhoneReceiver.java
* @Package com.example.androiddefprot.receiver
* @Description: 拨号界面特征码,监听,当监听到拨打123123时就会进入到 手机卫士的防盗界面
* @author lian_weijian@163.com
* @version V1.0
*/
public class CallPhoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String number = this.getResultData();
if("123123".equals(number)){
Intent lostIntent = new Intent(context,LostProtectedActivity.class);
//指定要激活的activity在自己的任务栈里面运行
lostIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //在Activity任务栈外面调用Activity,激活的Activity必须运
context.startActivity(lostIntent);
// 终止掉这个电话
// 不能通过 abortBroadcast();
this.setResultData(null); //终止拨打电话
}
}
}
| true
|
97d745b28e1990b13885bcb48b3ab987456f005a
|
Java
|
zlh142857/mycsa
|
/shiro/src/main/java/com/hx/config/SystemLogoutFilter.java
|
UTF-8
| 1,204
| 2.1875
| 2
|
[] |
no_license
|
package com.hx.config;/*
*//*
*@作者:张立恒
*@时间:2018/10/15 12:06
*@功能:
*/
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
public class SystemLogoutFilter extends LogoutFilter {
private static final Logger log = LoggerFactory.getLogger( SystemLogoutFilter.class);
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
Subject subject = getSubject(request, response);
try {
subject.logout();
} catch (SessionException ise) {
log.error(ise.toString());
}
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "成功");
out.println(result);
out.flush();
out.close();
return false;
}
}
| true
|
32d2be81318230aa43a02c1fcac0883501588d56
|
Java
|
khillansinghyolo/Code
|
/Project1/src/pkg/Read.java
|
UTF-8
| 511
| 3.078125
| 3
|
[] |
no_license
|
package pkg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Read {
public void readData(int initial ,int end) throws Exception
{
BufferedReader file=new BufferedReader(new FileReader(new File("../Project1/File.txt")));
int k=1;
String i="";
while(( i=file.readLine())!=null)
{
if(k>=initial && k<=end)
{
System.out.println(i);
}
k=k+1;
}
}
public static void main(String[] args)throws Exception {
new Read().readData(2,5);
}
}
| true
|
39ba7e752d7a7cb029528f0085a195ddc717669d
|
Java
|
zhanght86/zsbank
|
/src/com/sinosoft/midplat/jxnxs/net/JxnxsNetImpl.java
|
GB18030
| 5,728
| 1.984375
| 2
|
[] |
no_license
|
package com.sinosoft.midplat.jxnxs.net;
import java.net.Socket;
import javax.crypto.Cipher;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.xpath.XPath;
import com.sinosoft.midplat.common.IOTrans;
import com.sinosoft.midplat.common.JdomUtil;
import com.sinosoft.midplat.common.NoFactory;
import com.sinosoft.midplat.common.NumberUtil;
import com.sinosoft.midplat.common.SaveMessage;
import com.sinosoft.midplat.exception.MidplatException;
import com.sinosoft.midplat.bjbank.service.KeyChangeRollback;
import com.sinosoft.midplat.net.SocketNetImpl;
public class JxnxsNetImpl extends SocketNetImpl {
private String cOutFuncFlag = null;
private String cInsuID = null;
private String cOutFlag = null;
private String reFlag = null;
public JxnxsNetImpl(Socket pSocket, Element pThisConfRoot) throws MidplatException {
super(pSocket, pThisConfRoot);
}
public Document receive() throws Exception {
cLogger.info("Into JxnxsNetImpl.receive()...");
//ͷ
byte[] mHeadBytes = new byte[16];
IOTrans.readFull(mHeadBytes, cSocket.getInputStream());
//չ˾4λ
cInsuID = new String(mHeadBytes, 0, 4).trim();
///ձ־1λ12Ӧ
reFlag = new String(mHeadBytes, 4, 1).trim();
//3λ
cOutFuncFlag = new String(mHeadBytes, 5, 3).trim();
cLogger.info("״룺" + reFlag + cOutFuncFlag);
//ijȣ峤Ҷ롢0ķʽ䡣
int mBodyLength = Integer.parseInt(new String(mHeadBytes, 8, 8).trim());
cLogger.debug("ijȣ" + mBodyLength);
//
byte[] mBodyBytes = new byte[mBodyLength];
IOTrans.readFull(mBodyBytes, cSocket.getInputStream());
cSocket.shutdownInput();
//ũв"GB2312"
Document mXmlDoc = JdomUtil.build(mBodyBytes,"GB2312");
Element mRootEle = mXmlDoc.getRootElement();
//
XPath mXPath = XPath.newInstance("business/funcFlag[@outcode='" + reFlag + cOutFuncFlag + "']");
cFuncFlag = mXPath.valueOf(cThisConfRoot);
StringBuffer mSaveName = new StringBuffer(Thread.currentThread()
.getName()).append('_').append(NoFactory.nextAppNo()).append(
'_').append(cFuncFlag).append("_in.xml");
SaveMessage.save(mXmlDoc, cTranComEle.getText(), mSaveName.toString());
cLogger.info("汨ϣ" + mSaveName);
//ɱͷ
Element mClientIpEle = new Element(ClientIp);
mClientIpEle.setText(cClientIp);
Element mFuncFlagEle = new Element(FuncFlag);
mFuncFlagEle.setText(cFuncFlag);
Element mHeadEle = new Element(Head);
mHeadEle.addContent(mClientIpEle);
mHeadEle.addContent(cTranComEle);
mHeadEle.addContent(mFuncFlagEle);
mRootEle.addContent(mHeadEle);
cLogger.info("Out JxnxsNetImpl.receive()!");
return mXmlDoc;
}
public void send(Document pOutNoStd) throws Exception {
cLogger.info("Into JxnxsNetImpl.send()...");
/* ͨϵͳ쳣 */
try{
cOutFlag = pOutNoStd.getRootElement().getChild("MAIN").getChildText("OKFLAG");
}catch(Exception exp){
/*
* صpOutNoStdΪϵͳıģ
* ͨϵͳУ׳쳣ƽ̨ƽ쳣ϢװΪĵıĸʽ
* ڴ轫תΪеķDZĸʽж˽ͱչʾϢ
*/
if (pOutNoStd.getRootElement().getChild(Head) != null
&& pOutNoStd.getRootElement().getChild(Head).getChild(Flag).getText().equals("1")) {
// УرʶFlag=1Ϊʧܣ1 ɹ0 ʧ
cOutFlag = "1111";
pOutNoStd.getRootElement().getChild(Head).getChild(Flag).setText("1111");
pOutNoStd.getRootElement().getChild(Head).getChild(Flag).setName("RESULTCODE");
pOutNoStd.getRootElement().getChild(Head).getChild(Desc).setName("ERR_INFO");
pOutNoStd.getRootElement().getChild(Head).setName("MAIN");
if("021".equals(cOutFuncFlag)){//˱
pOutNoStd.getRootElement().setName("INSUREQRET");
}else if ("022".equals(cOutFuncFlag)){//ɷ
pOutNoStd.getRootElement().setName("RETURN");
}else if("002".equals(cOutFuncFlag)){//ճ
pOutNoStd.getRootElement().setName("FEETRANSCANCRET");
}
}
}
StringBuffer mSaveName = new StringBuffer(Thread.currentThread().getName())
.append('_').append(NoFactory.nextAppNo())
.append('_').append(cFuncFlag)
.append("_out.xml");
SaveMessage.save(pOutNoStd, cTranComEle.getText(), mSaveName.toString());
cLogger.info("汨ϣ"+mSaveName);
//ũвáGB2312
byte[] mBodyBytes = JdomUtil.toBytes(pOutNoStd,"GB2312");
byte[] mHeadBytes = new byte[16];
//˾
byte[] mInsuIDBytes = cInsuID.getBytes();
System.arraycopy(mInsuIDBytes, 0, mHeadBytes, 0, 4);
///ձ־
reFlag = "2";
byte[] mReFlagBytes = reFlag.getBytes();
System.arraycopy(mReFlagBytes, 0, mHeadBytes, 4, 1);
//3λ
byte[] mFuncFlagBytes = cOutFuncFlag.getBytes();
System.arraycopy(mFuncFlagBytes, 0, mHeadBytes, 5, mFuncFlagBytes.length);
//峤
String mLengthStr = NumberUtil.fillWith0(mBodyBytes.length, 8);//Ҷ롢0ķʽ
cLogger.info("رijȣ" + mLengthStr);
byte[] mLengthBytes = mLengthStr.getBytes();
System.arraycopy(mLengthBytes, 0, mHeadBytes, 8, mLengthBytes.length);
cSocket.getOutputStream().write(mHeadBytes); //ͱͷ
cSocket.getOutputStream().write(mBodyBytes); //ͱ
cSocket.shutdownOutput();
cLogger.info("Out JxnxsNetImpl.send()!");
}
}
| true
|
4e36cf02495ef64a7711a7c5efa4c31580d3098f
|
Java
|
rusakovichma/updates-r-simple
|
/core/src/test/java/de/idos/updates/DefaultVersionInstallerTest.java
|
UTF-8
| 956
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package de.idos.updates;
import de.idos.updates.store.Installation;
import de.idos.updates.store.OngoingInstallation;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultVersionInstallerTest {
VersionTransfer transfer = mock(VersionTransfer.class);
VersionReceptacle receptacle = mock(VersionReceptacle.class);
DefaultVersionInstaller installer = new DefaultVersionInstaller(transfer, receptacle);
@Test
public void handsOutInstallationFromTransfer() throws Exception {
OngoingInstallation installation = mock(Installation.class);
Version version = mock(Version.class);
when(transfer.transferVersionTo(version, receptacle)).thenReturn(installation);
OngoingInstallation install = installer.install(version);
assertThat(install, is(installation));
}
}
| true
|
2160ee9dfa5badafbdf66e92463f9e24dc781f90
|
Java
|
Josephaguele/Java-Lectures-Deitel
|
/src/ch04/Exercises/e19/SalesCommissionLauncher.java
|
UTF-8
| 349
| 2.34375
| 2
|
[] |
no_license
|
package ch04.Exercises.e19;
public class SalesCommissionLauncher
{
public static void main(String[]args)
{
// calling object SalesCommissionCalculator
SalesCommissionCalculator commissionCalculator = new SalesCommissionCalculator();
commissionCalculator.computeEarnings(); // calling method computeEarnings.
}
}
| true
|
68e2a794811a241fdd96f2040e58936723cb0ccd
|
Java
|
maiconloure/poo_exercises_java
|
/src/first_exercise/App.java
|
UTF-8
| 435
| 2.6875
| 3
|
[] |
no_license
|
package first_exercise;
public class App {
public static void main(String[] args) throws Exception {
Client client = new Client();
client.setName("Nippon");
client.setSurname("Hyakkei");
client.setAge(55);
client.setCPF(123123131);
client.setAccount(new CheckingAccount(100));
CheckingAccount account = client.getAccount();
account.deposit(250);
System.out.println(account.getBalance());
}
}
| true
|
4aa546a83ddaca82315b46e859c4a940dfd6d0bc
|
Java
|
shaohan0228/zstack
|
/storage/src/main/java/org/zstack/storage/snapshot/SnapshotCanonicalEvents.java
|
UTF-8
| 962
| 1.945313
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.zstack.storage.snapshot;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.EventFacade;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
public class SnapshotCanonicalEvents {
public static String INNER_SNAPSHOT_CREATED = "/primary-storage/inner-snapshot-created";
public static class InnerVolumeSnapshotCreated {
public String volumeUuid;
public VolumeSnapshotInventory snapshot;
public String primaryStorageUuid;
public InnerVolumeSnapshotCreated(String volumeUuid, String primaryStorageUuid, VolumeSnapshotInventory snapshot) {
this.volumeUuid = volumeUuid;
this.primaryStorageUuid = primaryStorageUuid;
this.snapshot = snapshot;
}
public void fire() {
EventFacade evtf = Platform.getComponentLoader().getComponent(EventFacade.class);
evtf.fire(INNER_SNAPSHOT_CREATED, this);
}
}
}
| true
|
846397bf5bb07ee4210d080a07b65c95291647ae
|
Java
|
Joao6/sim
|
/src/main/java/com/sim/web/rest/controller/MasterRestController.java
|
UTF-8
| 10,074
| 1.992188
| 2
|
[] |
no_license
|
package com.sim.web.rest.controller;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.sim.model.criteria.InstituicaoCriteria;
import com.sim.model.criteria.PacienteCriteria;
import com.sim.model.criteria.UsuarioCriteria;
import com.sim.model.entity.Instituicao;
import com.sim.model.entity.Master;
import com.sim.model.entity.Usuario;
import com.sim.model.service.InstituicaoService;
import com.sim.model.service.MasterService;
import com.sim.model.service.PacienteService;
import com.sim.model.service.UsuarioService;
import com.sim.web.constraints.AppConstraints;
import com.sim.web.utils.PaginaRetorno;
import com.sim.web.utils.responseForm.InstituicaoResponseForm;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author Joao Pedro
*/
@RestController
@RequestMapping(value = "/master/rest/")
public class MasterRestController {
InstituicaoService instituicaoService = new InstituicaoService();
MasterService masterService = new MasterService();
PacienteService pacienteService = new PacienteService();
@RequestMapping(value = "instituicao-list", method = RequestMethod.GET)
public String getInstituicoes(HttpServletResponse response,
@RequestParam(value = "nomeInstituicao", required = false) String nomeInstituicao,
@RequestParam(value = "confVersao", required = false) String confVersao,
@RequestParam(value = "offset", required = false) Long offset) {
String instituicoes = null;
try {
Map<Long, Object> criteria = new HashMap<>();
criteria.put(UsuarioCriteria.INSTITUICAO, true);
if (nomeInstituicao != null && !nomeInstituicao.isEmpty()) {
criteria.put(UsuarioCriteria.NOME_ILIKE, nomeInstituicao);
}
if (confVersao != null && !confVersao.isEmpty()) {
criteria.put(InstituicaoCriteria.CONF_VERSAO, confVersao);
}
List<InstituicaoResponseForm> instituicaoResponseList = new ArrayList<>();
List<Instituicao> instituicaoList = instituicaoService.readByCriteria(criteria, AppConstraints.LIMIT_DEFAULT, offset);
Long count = instituicaoService.countByCriteria(criteria, AppConstraints.LIMIT_DEFAULT, offset);
Map<Long, Object> criteriaQtdPaciente = new HashMap<>();
for (Instituicao instituicao : instituicaoList) {
criteriaQtdPaciente.put(PacienteCriteria.INSTITUICAO, instituicao.getId());
Long countQtd = pacienteService.countByCriteria(criteriaQtdPaciente, AppConstraints.LIMIT_DEFAULT, offset);
InstituicaoResponseForm instituicaoResponse =
new InstituicaoResponseForm(instituicao.getId(), instituicao.getNome(), instituicao.getEmail(),
instituicao.getTelefone(), instituicao.getConfVersao(), countQtd);
instituicaoResponseList.add(instituicaoResponse);
criteriaQtdPaciente.clear();
}
PaginaRetorno<InstituicaoResponseForm> responseForm = new PaginaRetorno<>();
responseForm.setCount(count);
responseForm.setDados(instituicaoResponseList);
Gson g = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
instituicoes = g.toJson(responseForm);
response.setStatus(200);
} catch (Exception e) {
response.setStatus(500);
response.setHeader("erro", e.getMessage());
}
return instituicoes;
}
@RequestMapping(value = "cadastrar-instituicao", method = RequestMethod.POST)
@ResponseBody
public void salvarInstituicao(HttpServletResponse response,
@RequestBody String instituicao, HttpSession session) throws Exception {
try {
Type type = new TypeToken<Instituicao>() {
}.getType();
Gson g = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
Instituicao inst = g.fromJson(instituicao, type);
Map<String, Object> fields = new HashMap<>();
Map<String, String> errors = new HashMap<>();
fields.put("id", inst.getId());
fields.put("nome", inst.getNome());
fields.put("email", inst.getEmail());
fields.put("versao", inst.getConfVersao());
fields.put("telefone", inst.getTelefone());
errors = instituicaoService.validate(fields);
if (errors.isEmpty()) {
instituicaoService.create(inst);
response.setStatus(200);
} else {
response.setStatus(401);
response.setHeader("error", errors.toString());
}
} catch (Exception e) {
response.setStatus(500);
response.setHeader("erro", e.getMessage());
}
}
@RequestMapping(value = "editar-instituicao", method = RequestMethod.PUT)
@ResponseBody
public void editarInstituicao(HttpServletResponse response,
@RequestBody String instituicao, HttpSession session) {
try {
Type type = new TypeToken<Instituicao>() {
}.getType();
Gson g = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
Instituicao inst = g.fromJson(instituicao, type);
Map<String, Object> fields = new HashMap<>();
Map<String, String> errors = new HashMap<>();
fields.put("id", inst.getId());
fields.put("nome", inst.getNome());
fields.put("email", inst.getEmail());
fields.put("versao", inst.getConfVersao());
fields.put("telefone", inst.getTelefone());
errors = instituicaoService.validate(fields);
if (errors.isEmpty()) {
instituicaoService.update(inst);
response.setStatus(200);
} else {
response.setStatus(401);
response.setHeader("error", errors.toString());
}
} catch (Exception e) {
response.setStatus(500);
response.setHeader("error", e.getMessage());
}
}
@RequestMapping(value = "master", method = RequestMethod.GET)
@ResponseBody
public String getMaster(HttpServletResponse response, HttpSession session) {
String master = null;
try {
Master masterSession = (Master) session.getAttribute("usuarioLogado");
masterSession = masterService.readById(masterSession.getId());
Gson g = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
master = g.toJson(masterSession);
response.setStatus(200);
} catch (Exception e) {
response.setStatus(500);
response.setHeader("error", e.getMessage());
}
return master;
}
@RequestMapping(value = "instituicao/{id}", method = RequestMethod.GET)
@ResponseBody
public String getInstituicao(HttpServletResponse response, @PathVariable Long id) {
String instituicao = null;
try {
Instituicao inst = instituicaoService.readById(id);
Gson g = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
instituicao = g.toJson(inst);
response.setStatus(200);
} catch (Exception e) {
response.setStatus(500);
response.setHeader("error", e.getMessage());
}
return instituicao;
}
@RequestMapping(value = "editar-master", method = RequestMethod.PUT)
@ResponseBody
public void editarDadosMaster(HttpServletResponse response,
@RequestBody String master, HttpSession session) {
try {
Type type = new TypeToken<Master>() {
}.getType();
Gson g = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
Master mas = g.fromJson(master, type);
Map<String, Object> fields = new HashMap<>();
Map<String, String> errors = new HashMap<>();
fields.put("nome", mas.getNome());
fields.put("email", mas.getEmail());
fields.put("id", mas.getId());
errors = masterService.validate(fields);
if (errors.isEmpty()) {
masterService.update(mas);
session.setAttribute("usuarioLogado", mas);
response.setStatus(200);
} else {
response.setStatus(401);
response.setHeader("error", errors.toString());
}
} catch (Exception e) {
response.setStatus(500);
response.setHeader("error", e.getMessage());
}
}
@RequestMapping(value = "valida-email", method = RequestMethod.GET)
@ResponseBody
public Boolean validaEmail(HttpServletResponse response, @RequestParam(value = "email", required = true) String email) {
Boolean isEmailOk = false;
try {
UsuarioService s = new UsuarioService();
Usuario usuario = s.validaEmail(email);
if (usuario != null) {
isEmailOk = false;
} else {
isEmailOk = true;
}
response.setStatus(200);
} catch (Exception e) {
response.setStatus(500);
response.setHeader("erro", e.getMessage());
}
return isEmailOk;
}
}
| true
|
e52c31508ba0f3ae86afe96cf8c51ed4753fc2bc
|
Java
|
TSSaint/meta64
|
/src/main/java/com/meta64/mobile/service/NodeRenderService.java
|
UTF-8
| 12,506
| 2.1875
| 2
|
[] |
no_license
|
package com.meta64.mobile.service;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.meta64.mobile.config.AppProp;
import com.meta64.mobile.config.JcrProp;
import com.meta64.mobile.config.SessionContext;
import com.meta64.mobile.model.NodeInfo;
import com.meta64.mobile.model.UserPreferences;
import com.meta64.mobile.request.AnonPageLoadRequest;
import com.meta64.mobile.request.ExpandAbbreviatedNodeRequest;
import com.meta64.mobile.request.InitNodeEditRequest;
import com.meta64.mobile.request.RenderNodeRequest;
import com.meta64.mobile.response.AnonPageLoadResponse;
import com.meta64.mobile.response.ExpandAbbreviatedNodeResponse;
import com.meta64.mobile.response.InitNodeEditResponse;
import com.meta64.mobile.response.RenderNodeResponse;
import com.meta64.mobile.user.UserSettingsDaemon;
import com.meta64.mobile.util.Convert;
import com.meta64.mobile.util.ExUtil;
import com.meta64.mobile.util.JcrUtil;
import com.meta64.mobile.util.ThreadLocals;
/**
* Service for rendering the content of a page. The actual page is not rendered on the server side.
* What we are really doing here is generating a list of POJOS that get converted to JSON and sent
* to the client. But regardless of format this is the primary service for pulling content up for
* rendering the pages on the client as the user browses around on the tree.
*/
@Component
public class NodeRenderService {
private static final Logger log = LoggerFactory.getLogger(NodeRenderService.class);
@Autowired
private AppProp appProp;
@Autowired
private Convert convert;
@Autowired
private UserSettingsDaemon userSettingsDaemon;
@Autowired
private SessionContext sessionContext;
/* Note: this should match nav.ROWS_PER_PAGE variable in TypeScript */
private static int ROWS_PER_PAGE = 25;
/*
* This is the call that gets all the data to show on a page. Whenever user is browsing to a new
* page, this method gets called once per page and retrieves all the data for that page.
*/
public void renderNode(Session session, RenderNodeRequest req, RenderNodeResponse res, boolean allowRootAutoPrefix) {
try {
if (session == null) {
session = ThreadLocals.getJcrSession();
}
res.setOffsetOfNodeFound(-1);
List<NodeInfo> children = new LinkedList<NodeInfo>();
res.setChildren(children);
String targetId = req.getNodeId();
log.trace("renderNode targetId:" + targetId);
Node node = JcrUtil.safeFindNode(session, targetId);
/*
* if the node was a path type and was not found then try with the "/root" prefix before
* giving up. We allow ID parameters to omit the leading "/root" part of the path for
* shortening the path just for user convenience.
*/
if (node == null && targetId.startsWith("/") && allowRootAutoPrefix) {
targetId = "/root" + targetId;
node = JcrUtil.safeFindNode(session, targetId);
}
if (node == null) {
res.setMessage("Node not found.");
res.setSuccess(false);
return;
}
log.trace("found node:" + targetId);
/* If user is trying to continue reading, we want to go to the next logical node after targetId node to continue reading, based off of
* what the parent is of all the nodes on the page.
*/
// if (req.isContinueReadingMode()) {
// node = getContinuationNodeFromStartingNode(node);
// }
String path = node.getPath();
userSettingsDaemon.setSettingVal(sessionContext.getUserName(), JcrProp.USER_PREF_LAST_NODE, path);
UserPreferences userPreferences = sessionContext.getUserPreferences();
boolean advancedMode = userPreferences != null ? userPreferences.isAdvancedMode() : false;
// boolean showMetaData = userPreferences != null ? userPreferences.isShowMetaData() :
// false;
/*
* If this is true it means we need to keep scanning child nodes until we find the
* targetId, so we can make that one be the first of the search results to display, and
* set that offset upon return. During the scan once the node is found, we do set this
* scanToNode var back to false, so it represents always if we're still scanning or not.
*/
boolean scanToNode = false;
if (req.isRenderParentIfLeaf() && !JcrUtil.hasDisplayableNodes(advancedMode, node)) {
res.setDisplayedParent(true);
req.setUpLevel(1);
}
int levelsUpRemaining = req.getUpLevel();
if (levelsUpRemaining > 0) {
scanToNode = true;
while (node != null && levelsUpRemaining > 0) {
node = node.getParent();
log.trace(" upLevel to nodeid: " + node.getPath());
levelsUpRemaining--;
}
}
NodeInfo nodeInfo = convert.convertToNodeInfo(sessionContext, session, node, true, true, false);
NodeType type = JcrUtil.safeGetPrimaryNodeType(node);
boolean ordered = type == null ? false : type.hasOrderableChildNodes();
nodeInfo.setChildrenOrdered(ordered);
// log.debug("Primary type: " + type.getName() + " childrenOrdered=" +ordered);
res.setNode(nodeInfo);
/*
* If we are scanning to a node we know we need to start from zero offset, or else we
* use the offset passed in
*/
int offset = scanToNode ? 0 : req.getOffset();
NodeIterator nodeIter = JcrUtil.getNodes(node);
int idx = 0, count = 0, idxOfNodeFound = -1;
boolean endReached = false;
try {
if (req.isGoToLastPage()) {
offset = (int) nodeIter.getSize() - ROWS_PER_PAGE;
if (offset < 0) {
offset = 0;
}
res.setOffsetOfNodeFound(offset);
}
/*
* Calling 'skip' here technically violates the fact that nodeVisibleInSimpleMode()
* can return false for some nodes, but because of the performance boost it offers
* i'm doing it anyway. I don't think skipping to far or too little by one or two
* will ever be a noticeable issue in the paginating so this should be fine, because
* there will be a very small number of nodes that are not visible to the user, so I
* can't think of a pathological case here.
*/
if (!scanToNode && offset > 0) {
nodeIter.skip(offset);
idx = offset;
}
List<Node> slidingWindow = null;
/*
* If we are scanning for a specific node, and starting at zero offset, then we need
* to be capturing all the nodes as we go, in a sliding window, so that in case we
* find this node on the first page then we can use the slidingWindow nodes to build
* the entire first page, because we will need to send back these nodes starting
* from the first one.
*/
if (offset == 0 && scanToNode) {
slidingWindow = new LinkedList<Node>();
}
while (true) {
Node n = nodeIter.nextNode();
if (advancedMode || JcrUtil.nodeVisibleInSimpleMode(node)) {
idx++;
if (idx > offset) {
if (scanToNode) {
String testPath = n.getPath();
/*
* If this is the node we are scanning for turn off scan mode, but
* record its index position
*/
if (testPath.equals(path)) {
scanToNode = false;
/*
* If we found our target node, and it's on the first page, then
* we don't need to set idxOfNodeFound, but just leave it unset,
* and we need to load in the nodes we had collected so far,
* before continuing
*/
if (idx <= ROWS_PER_PAGE && slidingWindow != null) {
/* loop over all our precached nodes */
for (Node sn : slidingWindow) {
count++;
children.add(convert.convertToNodeInfo(sessionContext, session, sn, true, true, false));
}
}
else {
idxOfNodeFound = idx;
}
}
/*
* else, we can continue while loop after we incremented 'idx'.
* Nothing else to do on this iteration/node
*/
else {
/* Are we still within the bounds of the first page ? */
if (idx <= ROWS_PER_PAGE && slidingWindow != null) {
slidingWindow.add(n);
}
continue;
}
}
count++;
children.add(convert.convertToNodeInfo(sessionContext, session, n, true, true, false));
if (count >= ROWS_PER_PAGE) {
try {
Node finalNode = nodeIter.nextNode();
if (!advancedMode && !JcrUtil.nodeVisibleInSimpleMode(finalNode)) {
endReached = true;
}
}
catch (Exception e) {
endReached = true;
// we don't rethrow or log this exception. It's normal flow
}
/* break out of while loop, we have enough children to send back */
break;
}
}
// log.trace(" node[" + nodeCount + "] path: " + n.getPath());
}
else {
log.trace(" MODE-REJECT node[" + idx + "] path: " + n.getPath());
}
}
}
catch (NoSuchElementException ex) {
endReached = true;
// not an error. Normal iterator end condition.
}
if (idx == 0) {
log.trace(" no child nodes found.");
}
if (idxOfNodeFound != -1) {
res.setOffsetOfNodeFound(idxOfNodeFound);
}
res.setEndReached(endReached);
}
catch (Exception ex) {
throw ExUtil.newEx(ex);
}
}
/* Returns the next node the user would want to read after the 'node' if they are simply trying to "continue reading" */
public Node getContinuationNodeFromStartingNode(Session session, Node node) {
throw ExUtil.newEx("feature is not yet enabled. Not yet coded.");
}
public void initNodeEdit(Session session, InitNodeEditRequest req, InitNodeEditResponse res) {
if (session == null) {
session = ThreadLocals.getJcrSession();
}
String nodeId = req.getNodeId();
Node node = JcrUtil.safeFindNode(session, nodeId);
if (node == null) {
res.setMessage("Node not found.");
res.setSuccess(false);
return;
}
NodeInfo nodeInfo = convert.convertToNodeInfo(sessionContext, session, node, false, false, true);
res.setNodeInfo(nodeInfo);
res.setSuccess(true);
}
public void expandAbbreviatedNode(Session session, ExpandAbbreviatedNodeRequest req, ExpandAbbreviatedNodeResponse res) {
if (session == null) {
session = ThreadLocals.getJcrSession();
}
String nodeId = req.getNodeId();
Node node = JcrUtil.safeFindNode(session, nodeId);
if (node == null) {
res.setMessage("Node not found.");
res.setSuccess(false);
return;
}
NodeInfo nodeInfo = convert.convertToNodeInfo(sessionContext, session, node, true, false, false);
res.setNodeInfo(nodeInfo);
res.setSuccess(true);
}
/*
* There is a system defined way for admins to specify what node should be displayed in the
* browser when a non-logged in user (i.e. anonymouse user) is browsing the site, and this
* method retrieves that page data.
*/
public void anonPageLoad(Session session, AnonPageLoadRequest req, AnonPageLoadResponse res) {
if (session == null) {
session = ThreadLocals.getJcrSession();
}
boolean allowRootAutoPrefix = false;
String id = null;
if (id == null) {
if (!req.isIgnoreUrl() && sessionContext.getUrlId() != null) {
id = sessionContext.getUrlId();
allowRootAutoPrefix = true;
}
else {
id = appProp.getUserLandingPageNode();
}
}
if (!StringUtils.isEmpty(id)) {
RenderNodeResponse renderNodeRes = new RenderNodeResponse();
RenderNodeRequest renderNodeReq = new RenderNodeRequest();
/*
* if user specified an ID= parameter on the url, we display that immediately, or else
* we display the node that the admin has configured to be the default landing page
* node.
*/
renderNodeReq.setNodeId(id);
renderNode(session, renderNodeReq, renderNodeRes, allowRootAutoPrefix);
res.setRenderNodeResponse(renderNodeRes);
}
else {
res.setContent("No content available.");
}
res.setSuccess(true);
}
}
| true
|
0c924bc01f66c049005fa0242d687a327c3aa11b
|
Java
|
gBadessa/javaTestApp
|
/src/br/com/gbadessa/ui/ExecutaAppViewModel.java
|
UTF-8
| 4,165
| 2.6875
| 3
|
[] |
no_license
|
package br.com.gbadessa.ui;
import br.com.gbadessa.Main;
import br.com.gbadessa.model.business.ILogCorridaBusiness;
import br.com.gbadessa.model.viewobjecties.LogCorridaViewObject;
import br.com.gbadessa.util.ConstantesUtil;
import br.com.gbadessa.util.StringMethodsUtil;
import br.com.gbadessa.util.StringResourcesUtil;
import java.util.List;
/**
* ExecutaAppViewModel
* Classe que acessa os objetos de negócio (Business) e retorna status das execuções para a View que é a responsável
* pela exibição das mensagens para o usuário.
*/
public class ExecutaAppViewModel {
//region Atributos
private ILogCorridaBusiness logCorridaBusiness;
//endregion Atributos
//region Contrutores
public ExecutaAppViewModel() {
iniciaBusinessObjects();
}
//endregion Contrutores
//region Metodos
/**
* iniciaBusinessObjects
* Método responsável por recuperar objeto Container e extrair do mesmo os objetos de negócios instanciados ao iniciar a aplicação.
*/
private void iniciaBusinessObjects() {
logCorridaBusiness = Main.appContainer.getLogCorridaBusiness();
}
public void run() {
try {
buscaResultados();
} catch (Exception e) {
e.printStackTrace();
}
}
public void buscaResultados(){
List<LogCorridaViewObject> resultadoCorrida = logCorridaBusiness.getResultados();
imprimeCabecalhoResultado();
resultadoCorrida.forEach(item -> {
String resultado =
ajustaLinhaImpressao(item.getPosicaoChegada().toString()) +
ajustaLinhaImpressao(item.getCodPiloto()) +
ajustaLinhaImpressao(item.getNomePiloto()) +
ajustaLinhaImpressao(item.getNumVoltasCompletadas().toString()) +
ajustaLinhaImpressao(item.getTempoTotalProva().toString()) +
ajustaLinhaImpressao(item.getMelhorVoltaPiloto().toString()) +
ajustaLinhaImpressao(item.getMelhorVoltaCorrida()) +
ajustaLinhaImpressao(item.getVelocidadeMediaPiloto().toString()) +
ajustaLinhaImpressao(item.getTempoAposVencedor().toString());
//
solicitaImpressaoMsg(resultado);
});
}
private void imprimeCabecalhoResultado(){
solicitaImpressaoMsg(StringResourcesUtil.msgAppFinalizando);
//
String result =
ajustaLinhaImpressao(StringResourcesUtil.Posiçao) +
ajustaLinhaImpressao(StringResourcesUtil.CodigoPiloto) +
ajustaLinhaImpressao(StringResourcesUtil.NomePiloto) +
ajustaLinhaImpressao(StringResourcesUtil.VoltasCompletadas) +
ajustaLinhaImpressao(StringResourcesUtil.TempoTotalProva) +
ajustaLinhaImpressao(StringResourcesUtil.MelhorVoltaPiloto) +
ajustaLinhaImpressao(StringResourcesUtil.MelhorVoltaCorrida) +
ajustaLinhaImpressao(StringResourcesUtil.VelocMediaPiloto) +
ajustaLinhaImpressao(StringResourcesUtil.TempoAposVencedor);
//
solicitaImpressaoMsg(result);
}
private String ajustaLinhaImpressao(String str){
Integer length = ConstantesUtil.CABECALHO_COLUNAS_SIZE;
return StringMethodsUtil.RPad(str, length, ' ');
}
private void solicitaImpressaoMsg(String str) {
if(iExecutaAppViewModelListner != null)
iExecutaAppViewModelListner.onPrintMsg(str);
}
//endregion Metodos
//region Interfaces
private IExecutaAppViewModelListner iExecutaAppViewModelListner;
public interface IExecutaAppViewModelListner {
void onPrintMsg(String msg);
}
//region getters setters
public IExecutaAppViewModelListner getiExecutaAppViewModelListner() {
return iExecutaAppViewModelListner;
}
public void setiExecutaAppViewModelListner(IExecutaAppViewModelListner iExecutaAppViewModelListner) {
this.iExecutaAppViewModelListner = iExecutaAppViewModelListner;
}
//endregion getters setters
//endregion Interfaces
}
| true
|
7d1a0d8241b953006a68caefb2c996df0292e382
|
Java
|
Pluckerpluck/MultiInv
|
/src/uk/co/tggl/pluckerpluck/multiinv/inventory/MIEnderchestInventory.java
|
UTF-8
| 5,070
| 2.640625
| 3
|
[] |
no_license
|
package uk.co.tggl.pluckerpluck.multiinv.inventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.Serializable;
public class MIEnderchestInventory implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8407863073614592570L;
protected MIItemStack[] MIInventoryContents = new MIItemStack[27];
// Create an MIInventory from a PlayerInventory
public MIEnderchestInventory(Inventory inventory) {
// Iterate and store inventory contents
ItemStack[] inventoryContents = inventory.getContents();
MIInventoryContents = new MIItemStack[inventoryContents.length];
for(int i = 0; i < inventoryContents.length; i++) {
MIInventoryContents[i] = new MIItemStack(inventoryContents[i]);
}
}
// Create an MIInventory from an arry of ItemStacks
public MIEnderchestInventory(ItemStack[] inventory) {
// Iterate and store inventory contents
MIInventoryContents = new MIItemStack[inventory.length];
for(int i = 0; i < inventory.length; i++) {
MIInventoryContents[i] = new MIItemStack(inventory[i]);
}
}
// Create an MIInventory from a string containing inventory data
public MIEnderchestInventory(String inventoryString) {
if(inventoryString != null && !inventoryString.equals("")) {
if(inventoryString.startsWith("{")) {
//New JSON format
JSONParser parser = new JSONParser();
JSONObject jsonInventory = null;
try {
jsonInventory = (JSONObject)parser.parse(inventoryString);
@SuppressWarnings("unchecked")
int invLength = ((Number)jsonInventory.getOrDefault("size", 0)).intValue();
MIInventoryContents = new MIItemStack[invLength];
JSONObject items = (JSONObject)jsonInventory.get("items");
for(int i = 0; i < invLength; i++) {
if(items.containsKey(String.valueOf(i))) {
MIInventoryContents[i] = new MIItemStack((JSONObject)items.get(String.valueOf(i)));
}else {
MIInventoryContents[i] = new MIItemStack();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}else {
// Fill MIInventoryContents
String[] inventoryData = inventoryString.split(";");
MIInventoryContents = new MIItemStack[inventoryData.length];
for(int i = 0; i < inventoryData.length; i++) {
MIInventoryContents[i] = new MIItemStack(inventoryData[i]);
}
}
}
}
public MIEnderchestInventory(Player player) {
this(player.getEnderChest());
}
public MIEnderchestInventory() {
}
public void loadIntoInventory(Inventory inventory) {
// Iterate and get inventory contents
ItemStack[] inventoryContents = new ItemStack[MIInventoryContents.length];
for(int i = 0; i < inventoryContents.length; i++) {
if(MIInventoryContents[i] != null) {
inventoryContents[i] = MIInventoryContents[i].getItemStack();
} else {
inventoryContents[i] = null;
}
inventory.setContents(inventoryContents);
}
}
public static MIItemStack[] getInventoryContents(String inventoryString) {
if(inventoryString != null && !inventoryString.equals("")) {
// Fill MIInventoryContents
String[] inventoryData = inventoryString.split(";");
MIItemStack[] micontents = new MIItemStack[inventoryData.length];
for(int i = 0; i < inventoryData.length; i++) {
micontents[i] = new MIItemStack(inventoryData[i]);
}
return micontents;
}
return null;
}
public MIItemStack[] getInventoryContents() {
return MIInventoryContents;
}
@SuppressWarnings("unchecked")
public String toString() {
JSONObject inventoryContents = new JSONObject();
inventoryContents.put("size", MIInventoryContents.length);
JSONObject items = new JSONObject();
for(int i = 0; i < MIInventoryContents.length; i++) {
JSONObject item = MIInventoryContents[i].getJSONItem();
if(item != null) {
items.put(String.valueOf(i), item);
}
}
inventoryContents.put("items", items);
return inventoryContents.toJSONString();
/*
// Initial capacity = (20 + 4) * 7 - 1
StringBuilder inventoryString = new StringBuilder(167);
// Add MIInventoryContents
for(MIItemStack itemStack : MIInventoryContents) {
if(itemStack == null) {
itemStack = new MIItemStack();
}
inventoryString.append(itemStack.toString());
inventoryString.append(";");
}
// Remove final ";"
inventoryString.deleteCharAt(inventoryString.length() - 1);
return inventoryString.toString();*/
}
}
| true
|
278d1341c6ea9d969ceedd31f7d24554ff247259
|
Java
|
zhang1998/browser
|
/second/quark/src/main/java/com/ucpro/feature/lightapp/d/b/c.java
|
UTF-8
| 2,370
| 1.867188
| 2
|
[] |
no_license
|
package com.ucpro.feature.lightapp.d.b;
import android.webkit.ValueCallback;
import com.uc.encrypt.f;
import com.ucweb.common.util.h.m;
import com.ucweb.common.util.k.a;
import java.io.File;
/* compiled from: ProGuard */
public final class c implements Runnable {
final /* synthetic */ ValueCallback a;
final /* synthetic */ b b;
public c(b bVar, ValueCallback valueCallback) {
this.b = bVar;
this.a = valueCallback;
}
public final void run() {
boolean z = true;
synchronized (b.b) {
if (this.b.a != null) {
this.a.onReceiveValue(this.b.a.b);
} else if (a.h(b.d())) {
r2 = null;
File file = new File(b.d());
if (file.exists()) {
byte[] e = a.e(file);
if (e != null) {
r2 = new h();
r2.a(f.b(e, com.uc.encrypt.a.b));
}
}
r4 = new StringBuilder("UserToken file is exist in user data dir\nstart to read\nUserTolen path in user data dir is: ").append(b.d()).append("\nSuccess: ");
if (r2 == null) {
z = false;
}
r4.append(String.valueOf(z));
if (r2 != null) {
this.b.a = r2;
m.a(2, new g(this));
} else {
m.a(2, new e(this));
a.c(b.d());
}
} else {
new StringBuilder("UserToken file is not exist in user data dir\nget UserToken from assets\nUserToken path in assets is: ").append("lightapp/dXNlcnRva2V1");
r2 = a.a("lightapp/dXNlcnRva2V1", this.b.c);
r4 = new StringBuilder("UserToken file is not exist in user data dir\nget UserToken from assets\nSuccess: ");
if (r2 == null) {
z = false;
}
r4.append(String.valueOf(z));
if (r2 != null) {
this.b.a = r2;
new StringBuilder("UserToken is: ").append(this.b.a.b);
m.a(2, new d(this));
a.a(this.b.a, b.d());
} else {
m.a(2, new f(this));
}
}
}
}
}
| true
|
435466acfe0328a8357a912bee699670ba926e9b
|
Java
|
pavelperc/newgena
|
/console/src/main/java/org/processmining/models/bpmn_with_time/MessageFlowWithTime.java
|
UTF-8
| 1,479
| 2.765625
| 3
|
[] |
no_license
|
package org.processmining.models.bpmn_with_time;
import org.processmining.models.TokenWithTime;
import org.processmining.models.base_bpmn.MessageFlow;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Created by Ivan on 03.09.2015.
*/
public class MessageFlowWithTime implements MessageFlow<TokenWithTime>
{
private org.processmining.models.graphbased.directed.bpmn.elements.MessageFlow actualFlow;
private Queue<TokenWithTime> tokens = new PriorityQueue<TokenWithTime>();
public MessageFlowWithTime(org.processmining.models.graphbased.directed.bpmn.elements.MessageFlow actualFlow)
{
this.actualFlow = actualFlow;
}
@Override
public org.processmining.models.graphbased.directed.bpmn.elements.MessageFlow getFlow()
{
return actualFlow;
}
@Override
public int getNumberOfTokens()
{
return tokens.size();
}
@Override
public boolean hasTokens()
{
return !tokens.isEmpty();
}
@Override
public void addToken(TokenWithTime token)
{
tokens.add(token);
}
@Override
public TokenWithTime consumeToken()
{
return tokens.remove();
}
@Override
public void removeToken(TokenWithTime token)
{
tokens.remove(token);
}
@Override
public void removeAllTokens()
{
tokens.clear();
}
@Override
public TokenWithTime peekToken()
{
return tokens.peek();
}
}
| true
|
1e9d218df8db8d35781b6527f6894085f6acd154
|
Java
|
lazyboyl/txc
|
/tx-core/src/main/java/com/tx/core/config/EnableTxc.java
|
UTF-8
| 316
| 1.65625
| 2
|
[] |
no_license
|
package com.tx.core.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({TxcScannerRegister.class})
public @interface EnableTxc {
String [] basePackages() default {"com.tx.core"};
}
| true
|
80d3ff04b11b6d885cc8cd8d923dcd6258d0b32c
|
Java
|
ftfetter/sales
|
/src/main/java/com/github/ftfetter/sales/pojos/CustomerData.java
|
UTF-8
| 1,214
| 2.671875
| 3
|
[] |
no_license
|
package com.github.ftfetter.sales.pojos;
public class CustomerData {
private String cnpj;
private String name;
private String businessArea;
public CustomerData(String cnpj, String name, String businessArea) {
this.cnpj = cnpj;
this.name = name;
this.businessArea = businessArea;
}
public String getCnpj() {
return cnpj;
}
public String getName() {
return name;
}
public String getBusinessArea() {
return businessArea;
}
public static final class Builder {
private String cnpj;
private String name;
private String businessArea;
public static Builder of() {
return new Builder();
}
public Builder cnpj(String cnpj) {
this.cnpj = cnpj;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder businessArea(String businessArea) {
this.businessArea = businessArea;
return this;
}
public CustomerData build() {
return new CustomerData(cnpj,name,businessArea);
}
}
}
| true
|
66a64e2fdb806ae57b32233a04bc67670fe40815
|
Java
|
fypgroup41/FYP_Project_Mobile
|
/src/fyp/main/S_Main.java
|
UTF-8
| 828
| 2.109375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fyp.main;
import java.net.HttpURLConnection;
/**
*
* @author test
*/
public class S_Main extends AsyncTask_Type {
private MainActivity activity;
public MainActivity getActivity() {
return activity;
}
public void setActivity(MainActivity activity) {
this.activity = activity;
}
public S_Main(MainActivity activity, String http_method) {
super(http_method);
this.activity = activity;
}
public void doWay(String output) {
}
public void executeAsyncTask() {
}
public void showRecord(Integer val) {
}
}
| true
|
8c335818b7289fc951bc0883328e5a0c3c063707
|
Java
|
thestmv/Tiko_2019
|
/Suoritus.java
|
UTF-8
| 2,715
| 2.6875
| 3
|
[] |
no_license
|
import java.math.BigDecimal;
import java.util.HashMap;
public class Suoritus {
//Attribuutit
private int id;
private BigDecimal kokonaisHinta;
private String type; //urakka tai tavallinen
private int tuntimaara;
private float tuntiHinta;
private float kotiTalousVahennys;
private float alv;
private String tyoTyyppi; // suunnittelu/normaali/aputyö
private Tarvikeluettelo kaytetytTarvikkeet;
public Suoritus(int id, BigDecimal kh, String t, int tm, float th, float ktv, float al, String tt){
this.id = id;
kaytetytTarvikkeet = new Tarvikeluettelo();
this.kokonaisHinta = kh;
type = t;
tuntimaara = tm;
this.tuntiHinta = th;
kotiTalousVahennys = ktv;
alv = al;
tyoTyyppi = tt;
}
public Suoritus(BigDecimal kh, String t, int tm, float th, float ktv, float al, String tt){
kaytetytTarvikkeet = new Tarvikeluettelo();
this.kokonaisHinta = kh;
type = t;
tuntimaara = tm;
this.tuntiHinta = th;
kotiTalousVahennys = ktv;
alv = al;
tyoTyyppi = tt;
}
public HashMap<Tarvike, Integer> getTarvikkeet(){
return kaytetytTarvikkeet.getTarvikkeet();
}
public void lisaaTarvike(Tarvike t, int kpl){
kaytetytTarvikkeet.asetaTarvike(t, kpl);
}
public int vahennaTarvikkeita(Tarvike t, int kpl){
return kaytetytTarvikkeet.vahennaTarvike(t, kpl);
}
//Setterit
public void setId(int id) {
this.id = id;
}
//Getteri
public int getId(){
return id;
}
public BigDecimal getKokonaisHinta() {
return kokonaisHinta;
}
public String getType(){
return type;
}
public int getTuntimaara(){
return tuntimaara;
}
public float getTuntiHinta(){
return tuntiHinta;
}
public float getKotiTalousVahennus(){
return kotiTalousVahennys;
}
public float getAlv(){
return alv;
}
public String getTyoTyyppi(){
return tyoTyyppi;
}
//Setterit
/* Jos tyyppi on urakka, niin tuntimaara on
*
*/
/*public void setType(){
if(type.equals == urakka){
tuntiHinta == null;
tyoTyyppi == null;
} else {
}
}*/
@Override
public String toString() {
return "******************************\n" +
"* TyösuoritusID: " + id + "\n" +
"* kokonaisHinta: " + kokonaisHinta + "\n" +
"* Tyyppi: " + type + "\n" +
"* Tuntimaara: " + tuntimaara + "\n" +
"* TuntiHinta: " + tuntiHinta + "\n" +
"* KotiTalousVahennys: " + kotiTalousVahennys + "\n" +
"* Alv: " + alv + "\n" +
"* tyoTyyppi: " + tyoTyyppi + "\n" +
"******************************\n";
}
public void setKokonaisHinta(BigDecimal kokonaisHinta) {
this.kokonaisHinta = kokonaisHinta;
}
}
| true
|
238bcc4b71ecd0b79283d1455f28991e494b03da
|
Java
|
WarzouMc/VirtualCard
|
/VirtualCard/src/main/java/fr/warzou/virtualcard/core/modules/link/Size.java
|
UTF-8
| 1,460
| 2.953125
| 3
|
[] |
no_license
|
package fr.warzou.virtualcard.core.modules.link;
import java.util.Arrays;
/**
* Define the size of all module face.
* This was implemented for the {@link Linkable} interface to make easier every linkage checks and getters.
* @author Warzou
*/
public interface Size {
/**
* This methode allow to get the different face size of this module, notably use for {@link LinkedModule}.
* @return Size for all face in order ({@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#LEFT},
* {@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#RIGHT}, {@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#FRONT},
* {@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#BEHIND}, {@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#UP},
* {@link fr.warzou.virtualcard.core.modules.link.LinkedModule.Face#DOWN})
*/
int[] size();
/**
* This method return every point who is allow the module linkage, notably use for {@link LinkedModule}
* @return Every point could support module linkage.
*/
Point[] linkablePoint();
/**
* Check if a {@link Point} is linkable.
* @param point Target {@link Point} to be checked
* @return true if {@link Size#linkablePoint()} contain the target point, and false otherwise
*/
default boolean isLinkable(Point point) {
return Arrays.asList(linkablePoint()).contains(point);
}
}
| true
|
dd5c5ee80e2b432981cff8eaf515f04eafd683c6
|
Java
|
BrainRTP/WildBot
|
/src/main/java/ru/wildcubes/wildbot/settings/SettingsReader.java
|
UTF-8
| 6,085
| 2.96875
| 3
|
[] |
no_license
|
package ru.wildcubes.wildbot.settings;
import ru.wildcubes.wildbot.logging.Tracer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class SettingsReader {
private static final String SETTING_NAME_PLACEHOLDER = "{setting_name}";
private static final String SETTING_VALUE_PLACEHOLDER = "{setting_value}";
private static List<Setting> requiredSettings = new ArrayList<Setting>() {{
//VK API group access
add(Setting.builder().name("group-id").inputType(Setting.InputType.INT)
.requestInputMessage("Enter your Group ID")
.wrongInputMessage("Not valid Group ID .")
.successInputMessage("Group ID set to TODO")
.build()
);
add(Setting.builder().name("group-key").inputType(Setting.InputType.SINGLE_STRING)
.requestInputMessage("Enter your Group Access Key")
.wrongInputMessage("Invalid Group Access Key")
.successInputMessage("Group Access Key set to TODO")
.build()
);
// Callback Handling Server
add(Setting.builder().name("callback-server-host").inputType(Setting.InputType.SINGLE_STRING)
.requestInputMessage("Please specify the host you would like to use for Callback Handling")
.wrongInputMessage("Given value is not a valid host")
.successInputMessage("Callback Handling host set to {setting_value}")
.build()
);
add(Setting.builder().name("callback-server-port").inputType(Setting.InputType.INT)
.requestInputMessage("Please specify the port you would like to use for Callback Handling")
.wrongInputMessage("Given value is not a valid port")
.successInputMessage("Callback Handling port set to {setting_value}")
.build()
);
}};
public static void readRequiredSettings() {
for (Setting requiredSetting : requiredSettings) readSetting(requiredSetting);
}
public static void readSetting(final Setting setting) {
if (SettingsManager.getSetting(setting.getName()) == null) {
Tracer.infoP(Arrays.asList(setting.getRequestInputMessage().toArray()),
Arrays.asList(SETTING_NAME_PLACEHOLDER, setting.getName()));
final Object settingValue = readSettingFromConsole(setting);
SettingsManager.setSetting(setting.getName(), settingValue, true);
Tracer.infoP(Arrays.asList(setting.getSuccessInputMessage().toArray()),
Arrays.asList(SETTING_NAME_PLACEHOLDER, setting.getName(),
SETTING_VALUE_PLACEHOLDER, settingValue));
}
}
private static Object readSettingFromConsole(final Setting setting) {
final Scanner scanner = new Scanner(System.in);
try {
switch (setting.getInputType()) {
case BOOLEAN: return scanner.nextBoolean();
case SHORT: {
short value = scanner.nextShort();
if (value < setting.getMin()
|| value > setting.getMax()) throw new InputMismatchException();
return value;
}
case INT: {
int value = scanner.nextInt();
if (value < setting.getMin()
|| value > setting.getMax()) throw new InputMismatchException();
return value;
}
case FLOAT: {
float value = scanner.nextFloat();
if (value < setting.getMin()
|| value > setting.getMax()) throw new InputMismatchException();
return value;
}
case DOUBLE: {
double value = scanner.nextDouble();
if (value < setting.getMin()
|| value > setting.getMax()) throw new InputMismatchException();
}
case BIG_INT: {
BigInteger value = scanner.nextBigInteger();
if (value.compareTo(BigInteger.valueOf(setting.getMin())) < 0
|| value.compareTo(BigInteger.valueOf(setting.getMax())) > 0) throw
new InputMismatchException();
return value;
}
case BIG_DEC: {
BigDecimal value = scanner.nextBigDecimal();
if (value.compareTo(BigDecimal.valueOf(setting.getMin())) < 0
|| value.compareTo(BigDecimal.valueOf(setting.getMax())) > 0) throw
new InputMismatchException();
return value;
}
case LONG: {
long value = scanner.nextLong();
if (value < setting.getMin()
|| value > setting.getMax()) throw new InputMismatchException();
return value;
}
case SINGLE_STRING: {
String value = scanner.next();
if (value.length() < setting.getMin()
|| value.length() > setting.getMax()) throw new InputMismatchException();
return value;
}
case STRING: {
String value = scanner.nextLine();
if (value.length() < setting.getMin()
|| value.length() > setting.getMax()) throw new InputMismatchException();
return value;
}
default: return scanner.nextLine();
}
} catch (InputMismatchException e) {
Tracer.warnP(Arrays.asList(setting.getWrongInputMessage().toArray()),
Arrays.asList(SETTING_NAME_PLACEHOLDER, setting.getName()));
return readSettingFromConsole(setting);
}
}
}
| true
|
bd8ca7d820faf6d1b9ee51028c459bb18e767f09
|
Java
|
milk9111/FirebaseAuthDemo
|
/ChallengeApp/app/src/main/java/group7/tcss450/uw/edu/challengeapp/LoginFragment.java
|
UTF-8
| 3,537
| 2.3125
| 2
|
[] |
no_license
|
package group7.tcss450.uw.edu.challengeapp;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.auth.FirebaseAuth;
public class LoginFragment extends Fragment implements View.OnClickListener {
private OnLoginInteractionListener mListener;
public LoginFragment() {
// Required empty public constructor
}
@Override
public void onStart() {
super.onStart();
Log.d("ACTIVITY", "Made it into LoginFragment!");
/*if (getArguments() != null) {
String name = getString(getArguments().getInt("key"));
updateColorContent(name);
}*/
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_login, container, false);
Button b = (Button) v.findViewById(R.id.confirm_register);
b.setOnClickListener(this);
Log.d("ACTIVITY", "Set confirm button onClick");
return v;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnLoginInteractionListener) {
mListener = (OnLoginInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public String getUsername() {
EditText editText = (EditText) getActivity().findViewById(R.id.username);
String returnString = editText.getText().toString();
Log.d("ACTIVITY", "Username is " + returnString);
return returnString;
}
public String getPassword() {
EditText editText = (EditText) getActivity().findViewById(R.id.password);
String returnString = editText.getText().toString();
Log.d("ACTIVITY", "Password is " + returnString);
return returnString;
}
@Override
public void onClick(View v) {
EditText userNameText = (EditText) getActivity().findViewById(R.id.username);
String username = userNameText.getText().toString();
EditText passWordText = (EditText) getActivity().findViewById(R.id.password);
String password = passWordText.getText().toString();
if (!username.equals("") && !password.equals("")) {
if (mListener != null) {
mListener.onLoginInteraction(username, password);
}
} else {
if (username.equals("")) {
userNameText.setError(getString(R.string.username_empty));
} else {
passWordText.setError(getString(R.string.password_empty));
}
if (FirebaseAuth.getInstance().fetchProvidersForEmail(username).equals("")) {
userNameText.setError(getString(R.string.non_existing_email));
}
}
}
public interface OnLoginInteractionListener {
void onLoginInteraction(String username, String password);
}
}
| true
|
e2fbcdb93a6bed82b92d6414339a1a3a716e66de
|
Java
|
linhct030132/QLBH1
|
/src/qlbh/model/NhaCungCap.java
|
UTF-8
| 1,500
| 2.3125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package qlbh.model;
/**
*
* @author Steven
*/
public class NhaCungCap {
private String MaNhaCungCap, TenNhaCungCap, DiaChi,
Fax,Email;
public NhaCungCap() {
}
public NhaCungCap(String MaNhaCungCap, String TenNhaCungCap, String DiaChi, String Fax, String Email) {
this.MaNhaCungCap = MaNhaCungCap;
this.TenNhaCungCap = TenNhaCungCap;
this.DiaChi = DiaChi;
this.Fax = Fax;
this.Email = Email;
}
public String getMaNhaCungCap() {
return MaNhaCungCap;
}
public void setMaNhaCungCap(String MaNhaCungCap) {
this.MaNhaCungCap = MaNhaCungCap;
}
public String getTenNhaCungCap() {
return TenNhaCungCap;
}
public void setTenNhaCungCap(String TenNhaCungCap) {
this.TenNhaCungCap = TenNhaCungCap;
}
public String getDiaChi() {
return DiaChi;
}
public void setDiaChi(String DiaChi) {
this.DiaChi = DiaChi;
}
public String getFax() {
return Fax;
}
public void setFax(String Fax) {
this.Fax = Fax;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
}
| true
|
904dd1267fa9e9f063f20c11e078f5659caf6e41
|
Java
|
WilsonParker/UIManager
|
/uimanager/src/main/java/developers/hare/com/uimanager/UI/PhotoManager.java
|
UTF-8
| 6,171
| 2.140625
| 2
|
[] |
no_license
|
package developers.hare.com.uimanager.UI;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import com.miguelbcr.ui.rx_paparazzo2.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo2.entities.FileData;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import developers.hare.com.uimanager.R;
import developers.hare.com.uimanager.Util.File.FileManager;
import developers.hare.com.uimanager.Util.LogManager;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import static android.app.Activity.RESULT_OK;
/**
* @description
*
*
* implementation "com.github.miguelbcr:RxPaparazzo:0.6.0-2.x"
* implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
*
* @author Hare
* @since 2018-08-24
**/
public class PhotoManager {
private static final PhotoManager ourInstance = new PhotoManager();
private OnPhotoBindListener onPhotoBindListener;
private UCrop.Options options = new UCrop.Options();
public static PhotoManager getInstance() {
return ourInstance;
}
private void createOptions(Activity activity) {
options.setToolbarColor(ContextCompat.getColor(activity, R.color.colorPrimaryDark));
}
public void onGalleryMultiSelect(Activity activity, OnPhotoBindListener onPhotoBindListener) {
this.onPhotoBindListener = onPhotoBindListener;
createOptions(activity);
RxPaparazzo.multiple(activity)
.usingGallery() // 바로 앨범을 실행
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response -> {
if (response.resultCode() != RESULT_OK) {
return;
}
response.data().forEach(this::bindData);
});
}
public void onGallerySingleSelect(Activity activity, OnPhotoBindListener onPhotoBindListener) {
this.onPhotoBindListener = onPhotoBindListener;
createOptions(activity);
RxPaparazzo.single(activity)
.crop(options)
.usingGallery()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response -> {
if (response.resultCode() != RESULT_OK) {
return;
}
bindData(response.data());
});
}
public void onCameraSelect(Activity activity, OnPhotoBindListener onPhotoBindListener) {
this.onPhotoBindListener = onPhotoBindListener;
createOptions(activity);
RxPaparazzo.single(activity)
.crop(options)
.usingCamera() // 바로 카메라를 실행
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Function<Throwable, Response<Activity, FileData>>() {
@Override
public Response<Activity, FileData> apply(@NonNull Throwable throwable){
LogManager.log(PhotoManager.class, "apply(@NonNull Throwable throwable)", throwable);
return null;
}
})
.subscribe(response -> {
// See response.resultCode() doc
if (response.resultCode() != RESULT_OK) {
return;
}
bindData(response.data());
});
}
private void bindData(FileData fileData) {
onPhotoBindListener.bindData(fileData);
}
public Bitmap rotate(File file) {
FileManager fileManager = FileManager.getInstance();
Bitmap bitmap = fileManager.encodeFileToBitmap(file);
ExifInterface exif = null;
try {
exif = new ExifInterface(file.getCanonicalPath());
} catch (Exception e) {
LogManager.log(getClass(), "rotate(File)", e);
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bmRotated = rotateBitmap(bitmap, orientation);
return bmRotated;
}
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
public interface OnPhotoBindListener {
void bindData(FileData fileData);
}
}
| true
|
6b2724e262a62b7f4ed965e515b516f24fba8388
|
Java
|
bellmit/smile-framework
|
/smile-core/src/main/java/org/smile/collection/AbstractSetDecorator.java
|
UTF-8
| 1,370
| 3.171875
| 3
|
[] |
no_license
|
package org.smile.collection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* 对一个set进行外部包装
* @author 胡真山
*
* @param <E>
*/
public abstract class AbstractSetDecorator<E> implements Set<E>{
protected Set<E> realSet;
protected AbstractSetDecorator(Set<E> set){
this.realSet=set;
}
@Override
public int size() {
return realSet.size();
}
@Override
public boolean isEmpty() {
return realSet.isEmpty();
}
@Override
public boolean contains(Object o) {
return realSet.contains(o);
}
@Override
public Iterator<E> iterator() {
return realSet.iterator();
}
@Override
public Object[] toArray() {
return realSet.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return realSet.toArray(a);
}
@Override
public boolean add(E e) {
return realSet.add(e);
}
@Override
public boolean remove(Object o) {
return realSet.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return realSet.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return realSet.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return realSet.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return realSet.removeAll(c);
}
@Override
public void clear() {
realSet.clear();
}
}
| true
|
a245355605547d21aea7370aabcfbd4a1a197aca
|
Java
|
lemonliu1993/spring
|
/src/com/lemon/beans/collections/Main.java
|
UTF-8
| 855
| 2.5
| 2
|
[] |
no_license
|
package com.lemon.beans.collections;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author created by liuyumeng
* @date 2018年8月30日 --- 上午7:49:09
*/
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) ctx.getBean("person3");
System.out.println(person);
NewPerson newPerson = (NewPerson) ctx.getBean("newPerson");
System.out.println(newPerson);
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource);
Person person4 = (Person) ctx.getBean("person4");
System.out.println(person4);
Person person5 = (Person) ctx.getBean("person5");
System.out.println(person5);
}
}
| true
|
f6742df4c91d84f8feaf3e5dcda3104f06472399
|
Java
|
MrBlackwell/FurnitureStock
|
/src/main/java/Main.java
|
UTF-8
| 974
| 2.296875
| 2
|
[] |
no_license
|
import javax.swing.*;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class Main {
static Access access = new Access();
static ImageIcon image = new ImageIcon(
"src\\main\\resources\\dolly.png");
public static void main(String[] args){
try {
javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) {}
String path="";
Properties props = new Properties();
try {
props.load(new InputStreamReader
(new FileInputStream("path.ini"), "windows-1251"));
path = (props.getProperty("PATH", ""));
} catch (Exception ignored) {}
if(path.equals("")){
new Path();
} else {
if(Access.connectDB(path)){
new login();
} else {
new Path();
}
}
}
}
| true
|
3e8067e05d1c1cce24cf00c33b23c90b90726d21
|
Java
|
FlowCI/flow-core-x
|
/core/src/main/java/com/flowci/core/job/domain/JobOutput.java
|
UTF-8
| 1,545
| 1.75
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 flow.ci
*
* 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.flowci.core.job.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.flowci.core.common.domain.Mongoable;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.core.index.Indexed;
/**
* @author yang
*/
@Getter
@Setter
public abstract class JobOutput extends Mongoable {
public static abstract class ContentType {
public static final String ZIP = "zip";
public static final String GZIP = "gzip";
public static final String JSON = "json";
public static final String XML = "xml";
public static final String HTML = "html";
}
@JsonIgnore
@Indexed(name = "index_job_report_jobid")
private String jobId;
// path for FileManager
@JsonIgnore
protected String path;
protected String fileName;
@JsonIgnore
protected boolean zipped;
protected String contentType;
protected Long contentSize = 0L;
}
| true
|
6ff792b53b91246a279b0cc79a9adbceda1b9201
|
Java
|
DoggeHill/Slaak
|
/src/hyll/sk/uniza/users/BasicUser.java
|
UTF-8
| 1,223
| 2.890625
| 3
|
[] |
no_license
|
package hyll.sk.uniza.users;
import hyll.sk.uniza.helpers.DatabaseLoader;
import hyll.sk.uniza.messages.TextMessage;
import hyll.sk.uniza.messages.VoiceMessage;
import java.io.IOException;
/**
* Class to represent basic user
* Limitations:
* Buffer size:5
* Can send only texts
* @author patri
*/
public class BasicUser extends User {
public BasicUser(String nickName) {
super(nickName);
super.setBufferSize(5);
}
public void sendMessage(User user) {
if (!(super.getMessageToSend() instanceof TextMessage)) {
try {
//we need to delete those files, because we have created them but had not sent
if (super.getMessageToSend() instanceof VoiceMessage) {
DatabaseLoader.deleteAudioFile();
} else {
DatabaseLoader.deletepictureFile();
}
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalArgumentException("This user can only send texts... ");
} else {
super.sendMessage(user);
}
}
@Override
protected int getLimit() {
return -1;
}
}
| true
|
663f15a19504d05e3cc2e0dbed419b2fe8213efd
|
Java
|
sjtudclab/SDMManageSystemWindows
|
/src/org/dclab/service/ModelService.java
|
UTF-8
| 7,386
| 2.0625
| 2
|
[] |
no_license
|
package org.dclab.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.dclab.mapping.ModelMapperI;
import org.dclab.mapping.MyModelMapperI;
import org.dclab.mapping.NameContentMapperI;
import org.dclab.model.Model;
import org.dclab.model.MyModel;
import org.dclab.model.ProjectList;
import org.dclab.util.OclValidate;
import org.dclab.util.ZipTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.dom4j.DocumentException;
//import org.python.util.PythonInterpreter;
@Service
public class ModelService {
@Autowired
private ModelMapperI modelMapperI;
@Autowired
private MyModelMapperI myModelMapperI;
@Autowired
private NameContentMapperI nameContentMapperI;
public static int CLIENT_PORT = 2181;
public static int TIME_OUT = 2000;
public void setModelMapperI(ModelMapperI modelMapperI) {
this.modelMapperI = modelMapperI;
}
public List<MyModel> checkModel(String username,int validation) {
if(validation==1)
return myModelMapperI.getModelCodeByUserID(username);
else
return myModelMapperI.getModelByUserID(username);
}
public List<Model> checkSDM(int bigClass, int middleClass, int smallClass) {
System.out.println("samll:" + smallClass);
return modelMapperI.getElementByClass(bigClass, middleClass, smallClass);
}
public void downloadModel(int elementID, HttpServletResponse response) throws InterruptedException, IOException {
String path = myModelMapperI.getFileIDByEId(elementID);
File file = new File(path);
String filename = path.substring(path.lastIndexOf("\\")+1);
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(filename, "UTF-8"));
if (!file.isDirectory()) {
InputStream iStream = new FileInputStream(file);
org.apache.commons.io.IOUtils.copy(iStream, response.getOutputStream());
response.flushBuffer();
iStream.close();
}
}
public void downloadSDM(HttpServletResponse response) throws InterruptedException, IOException {
String filename = "SDM.face";
String path = System.getProperty("project.root") + "files" + File.separator + "SDMFile" + File.separator + filename;
File file = new File(path);
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(filename, "UTF-8"));
if (!file.isDirectory()) {
InputStream iStream = new FileInputStream(file);
org.apache.commons.io.IOUtils.copy(iStream, response.getOutputStream());
response.flushBuffer();
iStream.close();
}
}
public int createSDM(Model model) throws Exception {
System.out.println("here:" + model.getDescription());
if(nameContentMapperI.getContentByName(model.getEnglishName())==null){
return -2;
}
if (modelMapperI.insertModel(model) == 1) {
System.out.println("sucess");
return model.getElementID();
} else {
return -1;
}
}
public int createModel(MyModel model) throws Exception {
System.out.println("here:" + model.getDescription());
if (myModelMapperI.insertModel(model) == 1) {
System.out.println("sucess");
System.out.println(model.getElementID());
return model.getElementID();
} else {
return -1;
}
}
public String uploadSDM(MultipartFile file, int elementID) throws Exception {
String path = System.getProperty("project.root") + "files" + File.separator + "SDMFile" + File.separator;
try {
FileOutputStream fos = new FileOutputStream(path + file.getOriginalFilename());
fos.write(file.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
modelMapperI.updatePath(elementID, path + file.getOriginalFilename());
// map.put("info", "上传成功");
System.out.println(path + file.getOriginalFilename());
return path + file.getOriginalFilename();
}
public String uploadModel(MultipartFile file, int elementID) throws Exception {
String path = System.getProperty("project.root") + "files" + File.separator + "ModelManage" + File.separator;
try {
FileOutputStream fos = new FileOutputStream(path + file.getOriginalFilename());
fos.write(file.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
myModelMapperI.updatePath(elementID, path + file.getOriginalFilename());
// map.put("info", "上传成功");
System.out.println(path + file.getOriginalFilename());
return path + file.getOriginalFilename();
}
public String oclValidate(int elementId) throws DocumentException, IOException {
String path = myModelMapperI.getFileIDByEId(elementId);
OclValidate oclValidate;
oclValidate = new OclValidate();
String returnCode = oclValidate.validateOcl(path);
if (returnCode.length() == 0) {
returnCode = "conform OCL";
myModelMapperI.updateValidation(elementId,1);
}
System.out.println("returnCode:" + returnCode);
return returnCode;
}
public void getFile(int elementID, HttpServletResponse response) throws IOException, InterruptedException {
String path = myModelMapperI.getFileIDByEId(elementID);
String dir = System.getProperty("project.root") + "files"+File.separator + "ModelManage";
Process process = null;
String modelFileName = path.substring(path.lastIndexOf("\\")+1);
System.out.println("modelname:"+modelFileName);
String command1 = "python " + "codegen.py "+ modelFileName;
System.out.println("command1:" + command1);
process = Runtime.getRuntime().exec(command1, null, new File(dir));
process.waitFor();
String fileName = dir + File.separator + "DM";
File file = new File(fileName);
String filename = "DM.zip";
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(filename, "UTF-8"));
if (file.isDirectory()) {
String src = dir + File.separator + "DM";
String dst = dir + File.separator + "DM.zip";
ZipTool.compress(src, dst);
try {
// get your file as InputStream
InputStream is = new FileInputStream(new File(dst));
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
deleteDir(file);
} else {
String filename1 = dir + File.separator + "DM.zip";
InputStream iStream = new FileInputStream(new File(filename1));
org.apache.commons.io.IOUtils.copy(iStream, response.getOutputStream());
response.flushBuffer();
iStream.close();
}
}
public List<ProjectList> projectlist(String username) {
System.out.println("文件列表");
return myModelMapperI.getProjectlist(username);
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除目录中的子目录下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
}
| true
|
0184c87ac3d16b39f47c9bc6be9ad73e0e46c33c
|
Java
|
castrorodrigo355/tota-server
|
/src/main/java/utn/frba/proyecto/utils/JSONUtils.java
|
UTF-8
| 287
| 2.09375
| 2
|
[] |
no_license
|
package utn.frba.proyecto.utils;
import com.google.gson.Gson;
import spark.ResponseTransformer;
public class JSONUtils {
public static String toJSON(Object model) {
return new Gson().toJson(model);
}
public static ResponseTransformer json() {
return JSONUtils::toJSON;
}
}
| true
|
90022391d25cae4c8650343d5e9a513d04866635
|
Java
|
sheelarajeshkumar/MSIT_Code
|
/snake&ladder/src/Dice.java
|
UTF-8
| 225
| 2.75
| 3
|
[] |
no_license
|
import java.util.Random;
public class Dice {
public static int roll(){
Random randomGenerator = new Random();
//r.nextInt(High-Low) + Low;
int randomInt = randomGenerator.nextInt(6-1)+1;
return randomInt;
}
}
| true
|
34164ca5f5f24d5b72846b69a5c001cf9d554efb
|
Java
|
CS2113-AY1819S1-W13-2/main
|
/src/main/java/seedu/divelog/commons/core/Messages.java
|
UTF-8
| 1,504
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
package seedu.divelog.commons.core;
/**
* Container for user visible messages.
*/
public class Messages {
public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
public static final String MESSAGE_INVALID_DIVE_DISPLAYED_INDEX = "The index provided is invalid!\n"
+ "It should be based on the numbers you see in the side panel.";
public static final String MESSAGE_DIVE_LISTED_OVERVIEW = "%1$d dives listed!";
public static final String MESSAGE_INVALID_TIME_FORMAT = "Invalid time format! (Not 24Hr format) ";
public static final String MESSAGE_INVALID_DATE_FORMAT = "Invalid date format! (Not DDMMYYYY) ";
public static final String MESSAGE_INVALID_DATE_LIMITS = "Start and End date or time or Safety Stop Time"
+ " are not in chronological order!\n"
+ "Start Date should be earlier than End Date!\n"
+ "Safety Stop should be between Start and End time";
public static final String MESSAGE_INVALID_TIMEZONE_FORMAT = "Invalid timezone format! (UTC format)";
public static final String MESSAGE_ERROR_LIMIT_EXCEED = "Dive is too deep and too long!!";
public static final String MESSAGE_ERROR_DIVES_OVERLAP =
"The dive overlaps with another dive. Not updating the divelog.";
public static final String MESSAGE_MAX_DEPTH_EXCEEDED = "The deepest you can go is 42m - don't risk your life!";
}
| true
|
46f2e60fd8998ceb9fb6e9172ba36e353b29728d
|
Java
|
sharonzidi/cs5004_object_oriented_design
|
/Lecture/Daytime_lectures/Lecture3_OO_Design_Exercise/src/test/java/problem2/DaycareCenterTest.java
|
UTF-8
| 9,083
| 2.515625
| 3
|
[] |
no_license
|
package problem2;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class DaycareCenterTest {
private InfantTeacher infant0;
private InfantTeacher infant1;
private InfantTeacher infant2;
private InfantTeacher infant3;
private InfantTeacher infant4;
private ToddlerTeacher toddler0;
private ToddlerTeacher toddler1;
private ToddlerTeacher toddler2;
private ToddlerTeacher toddler3;
private ToddlerTeacher toddler4;
private PreschoolTeacher preschool0;
private PreschoolTeacher preschool1;
private PreschoolTeacher preschool2;
private PreschoolTeacher preschool3;
private PreschoolTeacher preschool4;
private SubstituteTeacher sub0;
private SubstituteTeacher sub1;
private SubstituteTeacher sub2;
private SubstituteTeacher sub3;
private SubstituteTeacher sub4;
private DaycareCenter center0;
@Before
public void setUp() throws Exception {
Person teacher0 = new Person("Cody", "Schraeder");
Person teacher1 = new Person("Ryan", "Super");
Person teacher2 = new Person("Kyle", "Steps");
Person teacher3 = new Person("Todd", "Kim");
Person teacher4 = new Person("Sarah", "Knee");
Person coTeacher0 = new Person("Susanna", "Hi");
Person coTeacher1 = new Person("Sarah", "Zoo");
Person coTeacher2 = new Person("Tyler", "Bentley");
Person coTeacher3 = new Person("Amanda", "Fly");
Person coTeacher4 = new Person("Alex", "Lok");
infant0 = new InfantTeacher(teacher0, "Fields", coTeacher0, 8, 8, 0, true);
infant1 = new InfantTeacher(teacher1, "", coTeacher1, 1, 0, 1, false);
infant2 = new InfantTeacher(teacher2, "Runners", coTeacher2, 6, 3, 3, true);
infant3 = new InfantTeacher(teacher3, "Energizers", coTeacher3, 5, 5, 5, false);
infant4 = new InfantTeacher(teacher4, "Munchkins", coTeacher4, 3, 2, 3, true);
toddler0 = new ToddlerTeacher(teacher0, "Fields", coTeacher0, 14, 3, 11, true);
toddler1 = new ToddlerTeacher(teacher1, "", coTeacher1, 1, 0, 1, false);
toddler2 = new ToddlerTeacher(teacher2, "Runners", coTeacher2, 6, 3, 3, true);
toddler3 = new ToddlerTeacher(teacher3, "Energizers", coTeacher3, 12, 5, 7, false);
toddler4 = new ToddlerTeacher(teacher4, "Munchkins", coTeacher4, 3, 2, 1, true);
preschool0 = new PreschoolTeacher(teacher0, "Fields", coTeacher0, 20, 8, true);
preschool1 = new PreschoolTeacher(teacher1, "", coTeacher1, 1, 0, false);
preschool2 = new PreschoolTeacher(teacher2, "Runners", coTeacher2, 10, 10, true);
preschool3 = new PreschoolTeacher(teacher3, "Energizers", coTeacher3, 15, 5, false);
preschool4 = new PreschoolTeacher(teacher4, "Munchkins", coTeacher4, 7, 6, true);
sub0 = new SubstituteTeacher(coTeacher0, "Fields", teacher0, 0, true);
sub1 = new SubstituteTeacher(coTeacher1, "", teacher1, 1, true);
sub2 = new SubstituteTeacher(coTeacher2, "Runners", teacher2, 60, true);
sub3 = new SubstituteTeacher(coTeacher3, "Energizers", teacher3, 33, false);
sub4 = new SubstituteTeacher(coTeacher4, "Munchkins", teacher4, 20, false);
center0 = new DaycareCenter();
}
@Test
public void convertSubstituteTeacher() throws Exception {
Person expTeacher0 = new Person("Susanna", "Hi");
Person expTeacher1 = new Person("Sarah", "Zoo");
Person expTeacher2 = new Person("Tyler", "Bentley");
Person expTeacher3 = new Person("Amanda", "Fly");
Person expTeacher4 = new Person("Alex", "Lok");
Person expCoTeacher0 = new Person("Cody", "Schraeder");
Person expCoTeacher1 = new Person("Ryan", "Super");
Person expCoTeacher2 = new Person("Kyle", "Steps");
Person expCoTeacher3 = new Person("Todd", "Kim");
Person expCoTeacher4 = new Person("Sarah", "Knee");
InfantTeacher expInfant0 = new InfantTeacher(expTeacher0, "Fields", expCoTeacher0, 8, 8, 0,
true);
InfantTeacher expInfant1 = new InfantTeacher(expTeacher1, "", expCoTeacher1, 1, 0, 1, true);
InfantTeacher expInfant2 = new InfantTeacher(expTeacher2, "Runners", expCoTeacher2, 6, 3, 3,
true);
InfantTeacher expInfant3 = new InfantTeacher(expTeacher3, "Energizers", expCoTeacher3, 5, 5, 5,
false);
InfantTeacher expInfant4 = new InfantTeacher(expTeacher4, "Munchkins", expCoTeacher4, 3, 2, 3,
false);
ToddlerTeacher expToddler0 = new ToddlerTeacher(expTeacher0, "Fields", expCoTeacher0, 14, 3, 11,
true);
ToddlerTeacher expToddler1 = new ToddlerTeacher(expTeacher1, "", expCoTeacher1, 1, 0, 1, true);
ToddlerTeacher expToddler2 = new ToddlerTeacher(expTeacher2, "Runners", expCoTeacher2, 6, 3, 3,
true);
ToddlerTeacher expToddler3 = new ToddlerTeacher(expTeacher3, "Energizers", expCoTeacher3, 12, 5,
7,
false);
ToddlerTeacher expToddler4 = new ToddlerTeacher(expTeacher4, "Munchkins", expCoTeacher4, 3, 2,
1, false);
PreschoolTeacher expPreschool0 = new PreschoolTeacher(expTeacher0, "Fields", expCoTeacher0, 20,
8,
true);
PreschoolTeacher expPreschool1 = new PreschoolTeacher(expTeacher1, "", expCoTeacher1, 1, 0,
true);
PreschoolTeacher expPreschool2 = new PreschoolTeacher(expTeacher2, "Runners", expCoTeacher2, 10,
10, true);
PreschoolTeacher expPreschool3 = new PreschoolTeacher(expTeacher3, "Energizers", expCoTeacher3,
15,
5, false);
PreschoolTeacher expPreschool4 = new PreschoolTeacher(expTeacher4, "Munchkins", expCoTeacher4,
7, 6, false);
assertEquals(expInfant0, center0.convertSubstituteTeacher(sub0, "Infant", infant0));
assertEquals(expInfant1, center0.convertSubstituteTeacher(sub1, "Infant", infant1));
assertEquals(expInfant2, center0.convertSubstituteTeacher(sub2, "Infant", infant2));
assertEquals(expInfant3, center0.convertSubstituteTeacher(sub3, "Infant", infant3));
assertEquals(expInfant4, center0.convertSubstituteTeacher(sub4, "Infant", infant4));
assertEquals(expToddler0, center0.convertSubstituteTeacher(sub0, "Toddler", toddler0));
assertEquals(expToddler1, center0.convertSubstituteTeacher(sub1, "Toddler", toddler1));
assertEquals(expToddler2, center0.convertSubstituteTeacher(sub2, "Toddler", toddler2));
assertEquals(expToddler3, center0.convertSubstituteTeacher(sub3, "Toddler", toddler3));
assertEquals(expToddler4, center0.convertSubstituteTeacher(sub4, "Toddler", toddler4));
assertEquals(expPreschool0,
center0.convertSubstituteTeacher(sub0, "Preschool", preschool0));
assertEquals(expPreschool1,
center0.convertSubstituteTeacher(sub1, "Preschool", preschool1));
assertEquals(expPreschool2,
center0.convertSubstituteTeacher(sub2, "Preschool", preschool2));
assertEquals(expPreschool3,
center0.convertSubstituteTeacher(sub3, "Preschool", preschool3));
assertEquals(expPreschool4,
center0.convertSubstituteTeacher(sub4, "Preschool", preschool4));
}
@Test(expected = MismatchTeacherLabelException.class)
public void mismatchLabelException1() throws Exception {
FullTimeDaycareTeacher illegal = center0.convertSubstituteTeacher(sub0, "Toddler", infant0);
}
@Test(expected = MismatchTeacherLabelException.class)
public void mismatchLabelException2() throws Exception {
FullTimeDaycareTeacher illegal = center0.convertSubstituteTeacher(sub0, "None", infant0);
}
@Test(expected = MismatchTeacherNamesException.class)
public void mismatchTeacherNamesException1() throws Exception {
SubstituteTeacher illegalSub = new SubstituteTeacher(new Person("Susanna", "Hi"), "Fields",
new Person("a", "a"), 0, true);
FullTimeDaycareTeacher illegal = center0
.convertSubstituteTeacher(illegalSub, "Infant", infant0);
}
@Test(expected = MismatchTeacherNamesException.class)
public void mismatchTeacherNamesException2() throws Exception {
SubstituteTeacher illegalSub = new SubstituteTeacher(new Person("False", "False"), "Fields",
new Person("Cody", "Schraeder"), 0, true);
FullTimeDaycareTeacher illegal = center0
.convertSubstituteTeacher(illegalSub, "Infant", infant0);
}
@Test(expected = MismatchClassroomException.class)
public void mismatchClassroomException() throws Exception {
SubstituteTeacher illegalSub = new SubstituteTeacher(new Person("Susanna", "Hi"), "Clouds",
new Person("Cody", "Schraeder"), 0, true);
FullTimeDaycareTeacher illegal = center0
.convertSubstituteTeacher(illegalSub, "Infant", infant0);
}
@Test
public void testToString() {
assertEquals("This is a daycare center.", center0.toString());
}
@Test
public void equals() {
assertTrue(center0.equals(new DaycareCenter()));
assertFalse(center0.equals(null));
assertFalse(center0.equals(new Integer(2)));
}
@Test
public void testHashCode() {
Integer test0 = new Integer(8);
Double test1 = new Double(8.2);
assertEquals(center0.hashCode(), center0.hashCode());
assertNotEquals(center0.hashCode(), test0.hashCode());
assertNotEquals(center0.hashCode(), test1.hashCode());
}
}
| true
|
095695964e99e9ff4bd3500773dd12683fefcd9d
|
Java
|
farbod2u/Multi
|
/Exception/src/main/java/ir/saeed/multi/MyNotFoundException.java
|
UTF-8
| 270
| 2.03125
| 2
|
[] |
no_license
|
package ir.saeed.multi;
public class MyNotFoundException extends RuntimeException {
public MyNotFoundException(String message) {
super(message);
}
public MyNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| true
|
d927a06c7f846f933264360d64c2f74af7500f27
|
Java
|
jungpil/koverlap-r2
|
/obj/Unit.java
|
UTF-8
| 26,459
| 2.671875
| 3
|
[] |
no_license
|
package obj;
import java.util.Vector;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import util.Globals;
import util.Debug;
public class Unit {
private int index;
private String unitName;
// private int localKnowledgeIndex[] = new int[Globals.N / 2]; // [commented 3/24/12]
/**
* domain - what elements are within the purview of a unit
* fullKnowledge - what the unit knows; (includes overlapping knowledge of other domains) --> withinDomainOwnKnowledge OR(+) outsideDomainOwnKnowledge
* withinDomainOwnKnowledge - what the unit knows in own domain; --> domain AND fullKnowledge
* outsideDomainOwnKnowledge - what the unit knows in others' domains;
* withinDomainOthersKnowledge - what other units know of my own domain;
**/
private boolean[] domain;
private boolean[] fullKnowledge;
private boolean[] withinDomainOwnKnowledge;
private boolean[] outsideDomainOwnKnowledge;
private int[] withinDomainOthersKnowledge;
private double[] selectionProbabilities;
// private boolean control[] = new boolean[Globals.N]; // NO LONGER NEEDED; authority is assumed to be false; so for now this is the same as domain[]
// private Location globalLocation;
// private Location localLoc;
//private int knowledgeSize = 0;
// private int overlapIndex[] = new int[Globals.busOverlap];
// private int localKnowledgeIndex[];
// private int knowledgeOverlapIndex[];
private boolean move; // if unit's decision is to move to new location, set this to true
// private boolean move;
//private Vector<Location> neighbors;
private Vector<Location> neighbors;
/** constructor **/
/** @params
* idx - index unit
* name - name of unit (IS, business, or just unit1 etc.) mainly for reporting purposes
* domainDistributionCnts - distribution of number of domains e.g., [4,8,4] where N = 16 with 3 units
* knowledgeIdxs - the String representation of ALL units' knowledge. ALL other units' knowledge is needed so that we
* can assign overlapping knowledge to others' known elements
* - e.g., knoweldgeIdx = "1,1,0,0,0,0;0,0,1,1,0,0;0,0,0,0,1,1" -> [[1,1,0,0,0,0],[0,0,1,1,0,0],[0,0,0,0,1,1]]
* knowledgeOverlapSize - the number of other units' knowledge elements this unit is knowledgeable about -- extent of shared
* domain knowledge; this is used to pick
* called by Organization: units[i] = new Unit(i, Globals.unitNames[i], Globals.domainDistributionCounts, Globals.localKnowledgeIndices, Globals.knowledgeOverlapIndex[i]);
**/
//public Unit(int idx, String name, int[] domainDistributionCnts, String knowledgeIdxs, int knowledgeOverlapSize) {
public Unit(int idx, String name, Location loc, int[] domainDistributionCnts, String knowledgeIdxs) {
// set unit index and name
index = idx;
unitName = name;
// set unit's knowledge domain (control) ---- MUST BE DONE IN THIS ORDER domain[] needs to be set before knowledge can be set
setDomain(domainDistributionCnts); // set own knowledge domain
setKnowledges(knowledgeIdxs);
Debug.println("INIT Unit " + idx + " (" + name + ") - loc:" + loc.toString()
+ ", domain " + Debug.arrayToString(domain)
+ ", wiDomOwnK " + Debug.arrayToString(withinDomainOwnKnowledge)
+ ", outDomOwnK " + Debug.arrayToString(outsideDomainOwnKnowledge)
+ ", wiDomOthK " + Debug.arrayToString(withinDomainOthersKnowledge)
+ ", fullK " + Debug.arrayToString(fullKnowledge));
// set neighbors for current location (init); @note: no need to save location; only need location info to set neighbors
// resetSearchHistory(loc); // initialize nieghbor vector and sets neighbors // NO NEED DONE IN Org.determineFocalUnitIdx
//
/** @todofor now; not sure if Unit will be responsible for search or Organization
* organization should search by delegating recommendation to units; units don't need (or know) global location knowledge
// if (Globals.debug) { System.out.println("overlap set for infoSys"); }
// setLocation(globalLoc);
// if (Globals.debug) { System.out.println("set location for infoSys"); }
// resetSearchHistory();
// if (Globals.debug) { System.out.println("reset search history for infoSys"); }
*/
}
public Location getRecommendation(Location loc) {
// need to take care of 2 situations: experiential search vs. exhaustive search
//Landscape.getFitness(Location l, boolean[] know) {
// get own current perceived fitness value
double currentFitness = Globals.landscape.getFitness(loc, fullKnowledge);
Debug.println("Unit.getRecommendation: org.location: " + loc.toString() + ", unit.location: " + loc.toString(fullKnowledge) + ", perceived fitness: " + currentFitness);
Location selectedNeighbor = pickNeighbor(loc);
double selectedNeighborFitness = Globals.landscape.getFitness(selectedNeighbor, fullKnowledge);
Debug.println("selected vs. current: " + selectedNeighborFitness + " : " + currentFitness);
if (selectedNeighborFitness > currentFitness) {
return selectedNeighbor;
} else {
return null;
}
// @NOTE: with this implementation, the unit doesn't really know which neighbor was recommended. I don't think it is needed
}
private Location pickNeighbor(Location loc) {
// @todo: it's kind of awkward having to pass the location every time but there is really no
// need to store the location as a data member
// implement neighbor selection method here
// exhaustive vs. experiential
Location candidate = null;
if (Globals.search.equals("experiential")) {
setNeighborSelectionProbabilities(loc);
double r = Globals.rand.nextDouble();
Debug.println("neighbor pick random number: " + r);
int selectedNeighborIndex = -1;
for (int i = 0; i < selectionProbabilities.length; i++) {
if (r < selectionProbabilities[i]) {
selectedNeighborIndex = i;
break;
}
}
candidate = (Location)neighbors.remove(selectedNeighborIndex);
} else if (Globals.search.equals("exhaustive")) {
// return highest performing neighbor; selection probability is irrelevant
double currentMax = 0.0d;
int currentMaxIdx = -1;
for (int i = 0; i < neighbors.size(); i++) {
if (Globals.landscape.getFitness((Location)neighbors.get(i), fullKnowledge) > currentMax) {
currentMaxIdx = i;
}
}
candidate = neighbors.get(currentMaxIdx);
}
return candidate;
}
private void setDomain(int[] domainDistributionCnts) {
// set control domain; e.g., domainDistributionCnts = [4,8,4]
// => e.g., domain[] for unit1 = [t,t,t,t,f,f,f,f,f,f,f,f,f,f,f,f] for unit2 = [f,f,f,f,t,t,t,t,t,t,t,t,f,f,f,f]
domain = new boolean[Globals.N]; // initialized to all false
int tmpStart = 0;
for (int i = 0; i < domainDistributionCnts.length; i++) {
if (index == i) {
for (int j = tmpStart; j < tmpStart + domainDistributionCnts[i]; j++) {
domain[j] = true;
}
} else {
tmpStart += domainDistributionCnts[i];
}
}
}
protected boolean knowDomainAt(int idx) {
return domain[idx];
}
private void setNeighborSelectionProbabilities(Location loc) {
// implementation neighbor selection probability computation
// Globals.neighborSelectionApproach = {"random", "myknowledge", "othersknowledge", "cross"}
// 1. random - pick a random neighbor; neighbors only perturb within domain elements
// 2. myknowledge - pick a random neighbor; neighbor set also includes perturbations of other domain elements if focal unit has shared knowledge
// -> if I know, then I can consider implications of those changes as well
// 3. othersknowledge - give preferential weight (weighted probability by Globals.preferenceWeightages) for elements within my domain for which other units have shared knowledge
// -> if other unit knows an element, then focus on setting that first; neighbor set is same as random
// 4. cross - combination of myknowledge and othersknowledge - preferential weightage + expanded neighborset
// init selectionProbabilities array to fit neighbor vector size (to account for previously visited/discarded locations)
selectionProbabilities = new double[neighbors.size()];
// we could combine random + myknowledge and othersknowledge + cross but since these may change, let's keep them separate for now
// ACTUALLY DON'T DO IT HERE. WE NEED TO DO IT WHEN SETTING THE WEIGHTS
if (Globals.neighborSelectionApproach.equals("random")) { // option 0
// pick random neighbor from neighbor set and return
selectionProbabilities[0] = 1d / neighbors.size();
for (int i = 1; i < selectionProbabilities.length - 1; i++) {
selectionProbabilities[i] = selectionProbabilities[i-1] + (1d / neighbors.size());
}
selectionProbabilities[selectionProbabilities.length - 1] = 1d; // no need; init will set it to
} else if (Globals.neighborSelectionApproach.equals("myknowledge")) { // option 2
// also consider neighbors that alter what the focal unit knows (setNeighbors must change!!)
selectionProbabilities[0] = 1d / neighbors.size();
for (int i = 1; i < selectionProbabilities.length - 1; i++) {
selectionProbabilities[i] = selectionProbabilities[i-1] + (1d / neighbors.size());
}
selectionProbabilities[selectionProbabilities.length - 1] = 1d; // no need; init will set it to
} else if (Globals.neighborSelectionApproach.equals("othersknowledge")) { // option 1
// give preferential weight to other units' knowledge of my domain
// check neighbors diff with current location and
double[] diffAtOthersSharedKnowledge = new double[neighbors.size()];
for (int i = 0; i < diffAtOthersSharedKnowledge.length; i++) diffAtOthersSharedKnowledge[i] = 1d; // init to 1
for (int i = 0; i < neighbors.size(); i++) { // loop through neighbors
Location nb = (Location)neighbors.get(i);
// need to find neighbor which has different value (from current location) for elements
for (int j = 0; j < Globals.N; j++) {
if (!nb.getLocationAt(j).equals(loc.getLocationAt(j))) { // element index
if (withinDomainOthersKnowledge[j] > 0) { // some other unit knows this element
diffAtOthersSharedKnowledge[i] = Globals.preferentialWeightage;
} // else { countDiff[j] = 1; } // if other unit does not know this element j
} // else { countDiff[j] = 1; } if value of this element for considered neighbor is the same as current location value for this element
}
// now that we've identified whether this neighbor
}
double sumWeights = 0d;
for (int i = 0; i < diffAtOthersSharedKnowledge.length; i++) {
sumWeights += diffAtOthersSharedKnowledge[i];
}
selectionProbabilities[0] = diffAtOthersSharedKnowledge[0] / sumWeights;
for (int i = 1; i < selectionProbabilities.length - 1; i++) {
selectionProbabilities[i] = selectionProbabilities[i-1] + (diffAtOthersSharedKnowledge[i] / sumWeights);
}
selectionProbabilities[selectionProbabilities.length - 1] = 1d; // no need; init will set it to
} else if (Globals.neighborSelectionApproach.equals("cross")) { // option 4
// give preferential weight to other units' knowledge of my domain
// check neighbors diff with current location and
// also consider neighbors that alter what the focal unit knows (setNeighbors must change!!)
double[] diffAtOthersSharedKnowledge = new double[neighbors.size()];
for (int i = 0; i < diffAtOthersSharedKnowledge.length; i++) diffAtOthersSharedKnowledge[i] = 1d; // init to 1
for (int i = 0; i < neighbors.size(); i++) { // loop through neighbors
Location nb = (Location)neighbors.get(i);
// need to find neighbor which has different value (from current location) for elements
for (int j = 0; j < Globals.N; j++) {
if (!nb.getLocationAt(j).equals(loc.getLocationAt(j))) { // element index
if (withinDomainOthersKnowledge[j] > 0) { // some other unit knows this element
diffAtOthersSharedKnowledge[i] = Globals.preferentialWeightage;
} // else { countDiff[j] = 1; } // if other unit does not know this element j
} // else { countDiff[j] = 1; } if value of this element for considered neighbor is the same as current location value for this element
}
// now that we've identified whether this neighbor
}
double sumWeights = 0d;
for (int i = 0; i < diffAtOthersSharedKnowledge.length; i++) {
sumWeights += diffAtOthersSharedKnowledge[i];
}
selectionProbabilities[0] = diffAtOthersSharedKnowledge[0] / sumWeights;
for (int i = 1; i < selectionProbabilities.length - 1; i++) {
selectionProbabilities[i] = selectionProbabilities[i-1] + (diffAtOthersSharedKnowledge[i] / sumWeights);
}
selectionProbabilities[selectionProbabilities.length - 1] = 1d; // no need; init will set it to
} else {
System.err.println("Globals.neighborSelectionApproach not set");
System.exit(1);
}
Debug.print(printAllNeighbors());
}
//knoweldgeIdxs = "1,1,0,0,0,0;0,0,1,1,0,0;0,0,0,0,1,1" -> [[1,1,0,0,0,0],[0,0,1,1,0,0],[0,0,0,0,1,1]]
private void setKnowledges(String knowledgeIdxs) {
// note: setDomain(domainDistributionCounts) must be completed before this method -> domain[] has to be set
// done in Constructor
fullKnowledge = new boolean[Globals.N]; // initialized to all false
withinDomainOwnKnowledge = new boolean[Globals.N]; // initialized to all false
outsideDomainOwnKnowledge = new boolean[Globals.N]; // initialized to all false
withinDomainOthersKnowledge = new int[Globals.N]; // innitialize to all zero (0)
// 1. set fullKnowledge[] -- what the unit knows including overlapping knowledge of others' domains
for (int i = 0; i < knowledgeIdxs.split(";").length; i++) {
if (index == i) { // for focal unit
for (int j = 0; j < knowledgeIdxs.split(";")[i].split(",").length; j++) {
if (knowledgeIdxs.split(";")[i].split(",")[j].equals("1")) {
fullKnowledge[j] = true;
}
}
} else { // for other units
for (int j = 0; j < knowledgeIdxs.split(";")[i].split(",").length; j++) {
if (knowledgeIdxs.split(";")[i].split(",")[j].equals("1")) {
if (domain[j]) withinDomainOthersKnowledge[j]++;
}
}
}
}
// 2. distinguish between own and others' knowledge
for (int i = 0; i < fullKnowledge.length; i++) {
if (fullKnowledge[i]) { // if unit "knows"
if (domain[i]) { // if within unit's own domain
withinDomainOwnKnowledge[i] = true;
} else { // if outside of unit's own domain
outsideDomainOwnKnowledge[i] = true;
}
}
}
}
// get own knowledge size -- how many elements the unit knows within own domain
public int getWithinDomainOwnKnowledgeSize() {
int count = 0;
for (boolean boolValue : withinDomainOwnKnowledge) if (boolValue) count++;
return count;
}
// get overlapping knowledge size -- how many elements the unit knows outside own domain
public int getOutsideDomainOwnKnowledge() {
int count = 0;
for (boolean boolValue : outsideDomainOwnKnowledge) if (boolValue) count++;
return count;
}
// get full knowledge size -- how many elements the unit knows altogether
public int getFullKnowledgeSize() {
int count = 0;
for (boolean boolValue : fullKnowledge) if (boolValue) count++;
return count;
}
public void proposalAccepted() {
move = true;
}
public void proposalRejected() {
move = false;
}
public boolean decisionIsMove() {
return move;
}
public boolean hasNeighbors() {
if (neighbors.size() > 0) {
return true;
} else {
return false;
}
}
/**
* For a given location and maxDistance, fill neighbor vector with neighbors of variations in "maxDistance" elements
* i.e., if maxDistance = 2, then add all 1-off neighbors and all 2-off neighbors
* Note: ownKnowledge is used as mask for neighbors
*/
private void setNeighbors(Location loc, int maxDistance) {
// implementation neighbor selection
// Globals.neighborSelectionApproach = {"random", "myknowledge", "othersknowledge", "cross"}
// 1. random - pick a random neighbor; neighbors only perturb within domain elements
// 2. myknowledge - pick a random neighbor; neighbor set also includes perturbations of other domain elements if focal unit has shared knowledge
// -> if I know, then I can consider implications of those changes as well
// 3. othersknowledge - give preferential weight (weighted probability by Globals.preferenceWeightages) for elements within my domain for which other units have shared knowledge
// -> if other unit knows an element, then focus on setting that first; neighbor set is same as random
// 4. cross - combination of myknowledge and othersknowledge - preferential weightage + expanded neighborset
Debug.println("Unit.setNeighbors(loc: " + loc.toString() + ", dist:" + maxDistance + ") for Unit #" + index + " (" + unitName + ")");
if (Globals.neighborSelectionApproach.equals("random")) { // option 0
/** OPTION 1: RANDOM **/
List<Integer> ownNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < withinDomainOwnKnowledge.length; i++) {
if (withinDomainOwnKnowledge[i]) ownNeighborCombinationKnowledgeIndices.add(i);
}
// get all of the combinations
// e.g., if withinDomainOwnKnowledge = [t, t, t, t, f, f, t, f] and maxDistance = 1
// then neighborIndexCombinations = [[], [0], [1], [2], [3], [6]]; NOTE the empty one (always returned)
// if maxDistance = 2
// then neighborIndexCombinations = [[], [0], [1], [2], [3], [6], [0,1], [0,2], [0,3], [0,6], [1,2], [1,3], [1,6], [2,3], [2,6], [3,6]];
Set<Set<Integer>> ownNeighborIndexCombinations = getCombinationsFor(ownNeighborCombinationKnowledgeIndices, maxDistance);
for (Set<Integer> combo : ownNeighborIndexCombinations) {
if (!combo.isEmpty()) {
String[] neighborLocString = loc.getLocation();
for (Integer comboInt : combo) { // loop through each Int in neighborCombination
neighborLocString[comboInt] = flip(neighborLocString[comboInt]);
}
neighbors.add(new Location(neighborLocString));
// Debug.println("add neighbor: " + Debug.arrayToString(neighborLocString));
}
}
} else if (Globals.neighborSelectionApproach.equals("myknowledge")) { // option 2
/** OPTION 2: MYKNOWLEDGE **/
Vector<Location> tempNeighbors = new Vector<Location>();
List<Integer> ownNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < withinDomainOwnKnowledge.length; i++) {
if (withinDomainOwnKnowledge[i]) ownNeighborCombinationKnowledgeIndices.add(i);
}
Set<Set<Integer>> ownNeighborIndexCombinations = getCombinationsFor(ownNeighborCombinationKnowledgeIndices, maxDistance);
for (Set<Integer> combo : ownNeighborIndexCombinations) {
if (!combo.isEmpty()) {
String[] neighborLocString = loc.getLocation();
for (Integer comboInt : combo) { // loop through each Int in neighborCombination
neighborLocString[comboInt] = flip(neighborLocString[comboInt]);
}
tempNeighbors.add(new Location(neighborLocString));
// Debug.println("add tempNeighbor: " + Debug.arrayToString(neighborLocString));
}
}
List<Integer> othersNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < outsideDomainOwnKnowledge.length; i++) {
if (outsideDomainOwnKnowledge[i]) othersNeighborCombinationKnowledgeIndices.add(i);
}
Set<Set<Integer>> othersNeighborIndexCombinations = getCombinationsFor(othersNeighborCombinationKnowledgeIndices, othersNeighborCombinationKnowledgeIndices.size());
for (Set<Integer> sharedCombo : othersNeighborIndexCombinations) {
if (!sharedCombo.isEmpty()) {
for (Location tempNeighbor : tempNeighbors) {
String[] neighborLocString = tempNeighbor.getLocation();
// neighbors.add(new Location(neighborLocString)); // add original in temp
// Debug.println("add neighbor (orig in temp): " + Debug.arrayToString(neighborLocString));
for (Integer sharedComboInt : sharedCombo) {
neighborLocString[sharedComboInt] = flip(neighborLocString[sharedComboInt]);
}
neighbors.add(new Location(neighborLocString)); // add modified
// Debug.println("add neighbor: " + Debug.arrayToString(neighborLocString));
}
}
}
for (Location tempNeighbor : tempNeighbors) {
String[] neighborLocString = tempNeighbor.getLocation();
neighbors.add(new Location(neighborLocString)); // add original in temp
}
} else if (Globals.neighborSelectionApproach.equals("othersknowledge")) { // option 1
List<Integer> ownNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < withinDomainOwnKnowledge.length; i++) {
if (withinDomainOwnKnowledge[i]) ownNeighborCombinationKnowledgeIndices.add(i);
}
Set<Set<Integer>> ownNeighborIndexCombinations = getCombinationsFor(ownNeighborCombinationKnowledgeIndices, maxDistance);
for (Set<Integer> combo : ownNeighborIndexCombinations) {
if (!combo.isEmpty()) {
String[] neighborLocString = loc.getLocation();
for (Integer comboInt : combo) { // loop through each Int in neighborCombination
neighborLocString[comboInt] = flip(neighborLocString[comboInt]);
}
neighbors.add(new Location(neighborLocString));
// Debug.println("add neighbor: " + Debug.arrayToString(neighborLocString));
}
}
} else if (Globals.neighborSelectionApproach.equals("cross")) { // option 4
Vector<Location> tempNeighbors = new Vector<Location>();
List<Integer> ownNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < withinDomainOwnKnowledge.length; i++) {
if (withinDomainOwnKnowledge[i]) ownNeighborCombinationKnowledgeIndices.add(i);
}
Set<Set<Integer>> ownNeighborIndexCombinations = getCombinationsFor(ownNeighborCombinationKnowledgeIndices, maxDistance);
for (Set<Integer> combo : ownNeighborIndexCombinations) {
if (!combo.isEmpty()) {
String[] neighborLocString = loc.getLocation();
for (Integer comboInt : combo) { // loop through each Int in neighborCombination
neighborLocString[comboInt] = flip(neighborLocString[comboInt]);
}
tempNeighbors.add(new Location(neighborLocString));
// Debug.println("add tempNeighbor: " + Debug.arrayToString(neighborLocString));
}
}
List<Integer> othersNeighborCombinationKnowledgeIndices = new ArrayList<Integer>();
for (int i = 0; i < outsideDomainOwnKnowledge.length; i++) {
if (outsideDomainOwnKnowledge[i]) othersNeighborCombinationKnowledgeIndices.add(i);
}
Set<Set<Integer>> othersNeighborIndexCombinations = getCombinationsFor(othersNeighborCombinationKnowledgeIndices, othersNeighborCombinationKnowledgeIndices.size());
for (Set<Integer> sharedCombo : othersNeighborIndexCombinations) {
if (!sharedCombo.isEmpty()) {
for (Location tempNeighbor : tempNeighbors) {
String[] neighborLocString = tempNeighbor.getLocation();
// neighbors.add(new Location(neighborLocString)); // add original in temp
// Debug.println("add neighbor: " + Debug.arrayToString(neighborLocString));
for (Integer sharedComboInt : sharedCombo) {
neighborLocString[sharedComboInt] = flip(neighborLocString[sharedComboInt]);
}
neighbors.add(new Location(neighborLocString)); // add modified
// Debug.println("add neighbor: " + Debug.arrayToString(neighborLocString));
}
}
}
for (Location tempNeighbor : tempNeighbors) {
String[] neighborLocString = tempNeighbor.getLocation();
neighbors.add(new Location(neighborLocString)); // add original in temp
}
} else {
System.err.println("Globals.neighborSelectionApproach not set");
System.exit(1);
}
Debug.print("setNeighbors(" + neighbors.size() + ") - ");
for (Location n : neighbors) Debug.print("[" + n.toString() + "] ");
Debug.println("");
}
private String flip(String value) {
if (value.equals("0")) {
return "1";
} else if (value.equals("1")) {
return "0";
} else {
Debug.println("cannot flip empty value");
return " ";
}
}
public String printAllNeighbors() {
String retString = "";
for (int i = 0; i < neighbors.size(); i++) {
Location l = (Location)neighbors.get(i);
retString += l.toString() + " - perceived fitness: (" + l.toString(fullKnowledge) + ") " + Globals.landscape.getFitness(l, fullKnowledge) + ", selectionProb: " + selectionProbabilities[i] + "\n";
}
return retString;
}
private Set<Set<Integer>> getCombinationsFor(List<Integer> group, int subsetSize) {
Set<Set<Integer>> resultingCombinations = new HashSet<Set<Integer>> ();
int totalSize=group.size();
if (subsetSize > totalSize) {
subsetSize = totalSize;
}
if (subsetSize == 0) {
resultingCombinations.add(new HashSet<Integer>());
//emptySet(resultingCombinations);
} else if (subsetSize <= totalSize) {
List<Integer> remainingElements = new ArrayList<Integer> (group);
// Integer X = popLast(remainingElements);
Integer X = remainingElements.remove(remainingElements.size()-1);
Set<Set<Integer>> combinationsExclusiveX = getCombinationsFor(remainingElements, subsetSize);
Set<Set<Integer>> combinationsInclusiveX = getCombinationsFor(remainingElements, subsetSize-1);
for (Set<Integer> combination : combinationsInclusiveX) {
combination.add(X);
}
resultingCombinations.addAll(combinationsExclusiveX);
resultingCombinations.addAll(combinationsInclusiveX);
}
return resultingCombinations;
}
protected void resetSearchHistory(Location loc) {
neighbors = new Vector<Location>();
move = false;
setNeighbors(loc, Globals.numAlternatives);
}
public String toString() {
String retString = unitName + ", domain " + Debug.arrayToString(domain);
retString += ", withinDomainOwnKnowledge " + Debug.arrayToString(withinDomainOwnKnowledge);
retString += ", outsideDomainOwnKnowledge " + Debug.arrayToString(outsideDomainOwnKnowledge);
retString += ", fullKnowledge " + Debug.arrayToString(fullKnowledge);
retString += ", withinDomainOthersKnowledge " + Debug.arrayToString(withinDomainOthersKnowledge);
retString += ", neighbors: ";
for (int i = 0; i < neighbors.size(); i++) {
retString += ((Location)neighbors.get(i)).toString() + selectionProbabilities[i] + ", ";
}
return retString;
}
}
| true
|
70f467207178f3796f601dc951df71a0234f8a9b
|
Java
|
kunkan/ZipWriter
|
/src/main/java/com/kunal/zipwriter/model/Asset.java
|
UTF-8
| 743
| 2.65625
| 3
|
[] |
no_license
|
package com.kunal.zipwriter.model;
public class Asset {
private int assetId;
private String assetName;
private double assetPrice;
public Asset(int assetId, String assetName, double assetPrice) {
super();
this.assetId = assetId;
this.assetName = assetName;
this.assetPrice = assetPrice;
}
public int getAssetId() {
return assetId;
}
public void setAssetId(int assetId) {
this.assetId = assetId;
}
public String getAssetName() {
return assetName;
}
public void setAssetName(String assetName) {
this.assetName = assetName;
}
public double getAssetPrice() {
return assetPrice;
}
public void setAssetPrice(double assetPrice) {
this.assetPrice = assetPrice;
}
}
| true
|
2ee128362e460349033093c77fc3aa5e29ecd949
|
Java
|
michaelmosmann/wicket-praxis
|
/de.wicketpraxis--pom/webapp-blog/src/main/java/de/wicketpraxis/wicket/model/Models.java
|
UTF-8
| 612
| 2.140625
| 2
|
[] |
no_license
|
package de.wicketpraxis.wicket.model;
import org.apache.wicket.model.IModel;
import de.wicketpraxis.wicket.model.transformation.ModelSet;
public abstract class Models {
public static <T, M1> ModelSet.Set1<M1> on(IModel<M1> model) {
return new ModelSet.Set1<M1>(model);
}
public static <T, M1, M2> ModelSet.Set2<M1, M2> on(IModel<M1> model, IModel<M2> model2) {
return new ModelSet.Set2<M1, M2>(model, model2);
}
public static <T, M1, M2, M3> ModelSet.Set3<M1, M2, M3> on(IModel<M1> model, IModel<M2> model2, IModel<M3> model3) {
return new ModelSet.Set3<M1, M2, M3>(model, model2, model3);
}
}
| true
|
32a59d482fb95cadc0cc2eb50452ee065ccf3b40
|
Java
|
superhy/ailab-mltk
|
/test/test/mltk/mahout/cluster/ClusterDataModelTest.java
|
GB18030
| 3,058
| 2.484375
| 2
|
[] |
no_license
|
package test.mltk.mahout.cluster;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.mahout.math.Vector;
import org.junit.Test;
import org.mltk.mahout.cluster.ClusterDataModel;
import org.mltk.mahout.cluster.ClusterPreUtil;
import org.mltk.mahout.cluster.impl.CanopyClusterAssist;
import org.mltk.mahout.cluster.impl.CanopyKmeansClusterImpl;
import org.mltk.mahout.cluster.impl.HDFSKmeansClusterImpl;
import org.mltk.mahout.cluster.impl.KmeansClusterImpl;
public class ClusterDataModelTest {
@Test
public void testKmeansCluster() {
double[][] points = { { 1, 1, 0, 0 }, { 1, 2, 0, 0 }, { 2, 1, 0, 1 },
{ 2, 2, 1, 1 }, { 3, 3, 2, 1 }, { 8, 8, 7, 2 }, { 9, 8, 9, 2 },
{ 8, 9, 9, 3 }, { 9, 9, 8, 3 } };
ClusterDataModel clusterDriver = new KmeansClusterImpl(2, 1, 3);
Map<Integer, Integer> clusterResMap = clusterDriver.exec(points);
// ֵԣ
Iterator<Integer> iterator = clusterResMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
Integer value = clusterResMap.get(key);
System.out.println(key.toString() + " belongs to cluster "
+ value.toString());
}
}
@Test
public void testHDFSKmeansCluster() {
// ClusterDataModelPre testObj = new ClusterDataModelPre();
// testObj.kmeansCluster();
double[][] points = { { 1, 1, 0, 0 }, { 1, 2, 0, 0 }, { 2, 1, 0, 1 },
{ 2, 2, 1, 1 }, { 3, 3, 2, 1 }, { 8, 8, 7, 2 }, { 9, 8, 9, 2 },
{ 8, 9, 9, 3 }, { 9, 9, 8, 3 } };
ClusterDataModel clusterDriver = new HDFSKmeansClusterImpl(2, 1, 3);
Map<Integer, Integer> clusterResMap = clusterDriver.exec(points);
// ֵԣ
Iterator<Integer> iterator = clusterResMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
Integer value = clusterResMap.get(key);
System.out.println(key.toString() + " belongs to cluster "
+ value.toString());
}
}
@Test
public void testCanopyKmeansCluster() {
// ClusterDataModelPre testObj = new ClusterDataModelPre();
// testObj.kmeansCluster();
double[][] points = { { 1, 1, 0, 0 }, { 1, 2, 0, 0 }, { 2, 1, 0, 1 },
{ 2, 2, 1, 1 }, { 3, 3, 2, 1 }, { 8, 8, 7, 2 }, { 9, 8, 9, 2 },
{ 8, 9, 9, 3 }, { 9, 9, 8, 3 } };
ClusterDataModel clusterDriver = new CanopyKmeansClusterImpl(1, 3,
10.0, 9.5);
List<Vector> pointsVectors = ClusterPreUtil.getPoints(1, points);
CanopyClusterAssist.setCanopyVectors(ClusterPreUtil
.getPoints(1, points));
Map<Integer, Integer> clusterResMap = clusterDriver.exec(pointsVectors);
// System.out.println(clusterResMap.size());
// ֵԣ
Iterator<Integer> iterator = clusterResMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
Integer value = clusterResMap.get(key);
System.out.println(key.toString() + " belongs to cluster "
+ value.toString());
}
}
}
| true
|
58b1ea59a825b7401308ea4e9c1cf89292db4313
|
Java
|
2733284198/sync2es
|
/src/test/java/com/jte/sync2es/extract/impl/MysqlSourceOriginDataExtractImplTest.java
|
UTF-8
| 1,302
| 1.859375
| 2
|
[] |
no_license
|
package com.jte.sync2es.extract.impl;
import com.jte.sync2es.Tester;
import com.jte.sync2es.conf.RuleConfigParser;
import com.jte.sync2es.extract.SourceOriginDataExtract;
import com.jte.sync2es.model.config.Sync2es;
import com.jte.sync2es.model.mysql.TableMeta;
import org.buildobjects.process.ProcBuilder;
import org.buildobjects.process.ProcResult;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.Resource;
import java.sql.SQLException;
public class MysqlSourceOriginDataExtractImplTest extends Tester {
@Resource
SourceOriginDataExtract sourceOriginDataExtract;
@Resource
RuleConfigParser ruleParser;
@Resource
Sync2es sync2es;
@Before
public void initRules()
{
ruleParser.initRules();
}
@Test
public void dumpDataTest() throws SQLException, IllegalAccessException {
TableMeta tableMeta=RuleConfigParser.RULES_MAP.getIfPresent("test$wzh");
Assert.assertNotNull(sourceOriginDataExtract.dumpData(tableMeta));
}
@Test
public void commandTest()
{
ProcBuilder builder = new ProcBuilder(sync2es.getMysqldump());
builder.withArg("--help");
ProcResult result=builder.run();
System.out.println(result.getOutputString());
}
}
| true
|
ed52f4d94281de72bcb914588377304dfd34be92
|
Java
|
junit/GenesisServer
|
/Code_Java/test/src/com/genesis/test/gameserver/battleprop/Level.java
|
UTF-8
| 890
| 2.3125
| 2
|
[] |
no_license
|
package com.genesis.test.gameserver.battleprop;
import com.genesis.common.prop.battleprop.BattlePropContainer;
import com.genesis.common.prop.battleprop.propholder.IPropHolder;
import com.genesis.common.prop.battleprop.propholder.Prop;
import com.genesis.common.prop.battleprop.source.PropSourceType;
public class Level implements IPropHolder<LevelPropPart> {
// private final int level;
private final Prop<LevelPropPart> propEffectManager;
public Level(int level) {
// this.level = level;
this.propEffectManager =
new Prop<LevelPropPart>(PropSourceType.StarAndLevel, level, LevelPropPart.class);
}
@Override
public Prop<LevelPropPart> getProp() {
return this.propEffectManager;
}
@Override
public void addProp(BattlePropContainer battlePropContainer) {
// TODO Auto-generated method stub
}
}
| true
|
c7b1b1f1f26d812d2e2b73a46322af355cdd232d
|
Java
|
Z2su/trex_jisoo
|
/trex/src/main/java/com/trex/service/CrshServiceImpl.java
|
UTF-8
| 996
| 2.203125
| 2
|
[] |
no_license
|
package com.trex.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.trex.dao.CrshDAO;
import com.trex.dto.CrshVO;
public class CrshServiceImpl implements CrshService {
@Autowired
private CrshDAO crshDAO;
public void setCrshDAO(CrshDAO crshDAO) {
this.crshDAO = crshDAO;
}
@Override
public List<CrshVO> getList() throws Exception {
List<CrshVO> crshlist = crshDAO.selectList();
return crshlist;
}
@Override
public CrshVO getcrsh(String crsh_code) throws SQLException {
CrshVO crsh = crshDAO.select(crsh_code);
return crsh;
}
@Override
public void write(CrshVO crsh) throws SQLException {
int num = crshDAO.NextSeq();
crsh.setCrsh_code("CRSH"+String.format("%04d", num));
crsh.setCrsh_num(num);
crshDAO.insert(crsh);
}
@Override
public void remove(String crsh_code) throws SQLException {
crshDAO.delete(crsh_code);
}
}
| true
|
ef205bb50fc3693f829a84a6f33645d8f76d383c
|
Java
|
pangjian527/ticker_web_portal
|
/src/main/java/com/tl/ticker/web/action/CenterAction.java
|
UTF-8
| 3,420
| 1.882813
| 2
|
[] |
no_license
|
package com.tl.ticker.web.action;
import com.tl.rpc.common.ServiceToken;
import com.tl.rpc.consumer.Consumer;
import com.tl.rpc.consumer.ConsumerService;
import com.tl.rpc.order.Order;
import com.tl.rpc.order.OrderResult;
import com.tl.rpc.order.OrderService;
import com.tl.rpc.product.Product;
import com.tl.rpc.product.ProductService;
import com.tl.rpc.recharge.Recharge;
import com.tl.rpc.recharge.RechargeService;
import com.tl.rpc.recharge.SearchResult;
import com.tl.ticker.web.action.entity.OrderItemResult;
import com.tl.ticker.web.action.entity.RechargeResult;
import com.tl.ticker.web.common.Constant;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.LinkedList;
import java.util.List;
/**
* Created by pangjian on 16-12-24.
*/
@Controller
public class CenterAction {
@RequestMapping("/portal/center")
public String execute(Model model, HttpSession session, HttpServletRequest request,String code) throws Exception{
Object object = session.getAttribute(Constant.SESSION_USER);
if(object == null){
return "redirect:/portal/login";
}
Consumer consumer = (Consumer)object;
if("recharge".equals(code)){
List<RechargeResult> rechargeList = this.getRechargeList(consumer);
model.addAttribute("rechargeList",rechargeList);
}else{
List<OrderItemResult> orderList = this.getOrderList(consumer);
model.addAttribute("orderList",orderList);
}
model.addAttribute("consumer",consumer);
return "center/person";
}
private List<OrderItemResult> getOrderList(Consumer consumer) throws Exception{
ServiceToken token = new ServiceToken();
OrderResult orderResult = orderService.searchOrderByUserId(token, 200, 0,consumer.getId());
List<OrderItemResult> listResult = new LinkedList<OrderItemResult>();
for (Order order :orderResult.getResult()) {
OrderItemResult itemResult = OrderItemResult.fromOrder(order);
Product product = productService.getByProductId(token, order.getProductId());
itemResult.setTitle(product.getTitle());
itemResult.setMobile(consumer.getMobile());
listResult.add(itemResult);
}
return listResult;
}
public List<RechargeResult> getRechargeList(Consumer consumer) throws Exception{
ServiceToken token = new ServiceToken();
SearchResult searchResult = rechargeService.searchRecharge(token, 50, 0, consumer.getId());
List<RechargeResult> listResult = new LinkedList<RechargeResult>();
for (Recharge recharge :searchResult.getResult()) {
RechargeResult rechargeResult = RechargeResult.formRecharge(recharge);
rechargeResult.mobile = consumer.getMobile();
listResult.add(rechargeResult);
}
return listResult;
}
@Autowired
private OrderService orderService;
@Autowired
private ProductService productService;
@Autowired
private ConsumerService consumerService;
@Autowired
private RechargeService rechargeService;
}
| true
|
37a03ae66d47ad58123993fe866347ef37d3f806
|
Java
|
MirzaMasic/BILD-IT-zadaci
|
/src/zadaci_20_08_2016/IdenticalArray.java
|
UTF-8
| 2,987
| 3.8125
| 4
|
[] |
no_license
|
package zadaci_20_08_2016;
import java.util.Scanner;
public class IdenticalArray {
public static boolean equals(int[][] m1, int[][] m2) {
// Petlja koja prolazi kroz prvi niz i poredi vrijendosti prvog niza sa
// vrojednostima drugog niza , ako vrijednosti nisu identicne vraca
// false a ako su identicne vraca true
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[i].length; j++) {
if (m1[i][j] != m2[i][j]) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Unos korsinika koliko zeli da nizovi budu veliki
System.out.println("Umesite broj redova vaseg prvog niza");
int firstArrayRow = input.nextInt();
System.out.println("Unesite broj koloni u vasem prvom nizu");
int firstArrayColumn = input.nextInt();
int[][] array1 = new int[firstArrayRow][firstArrayColumn];
System.out.println("-------------------------------------");
System.out.println("Umesite broj redova vaseg drugog niza");
int secondArrayRow = input.nextInt();
System.out.println("Unesite broj koloni u vasem drugom nizu");
int secondArrayColumn = input.nextInt();
int[][] array2 = new int[secondArrayRow][secondArrayColumn];
// Unos vrijednosti korisnika u prvi niz
System.out.println("---------------------------------------");
System.out.println("Unesite vrijednosti u prvi niz");
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
array1[i][j] = input.nextInt();
}
}
// Unos vrijednosti korisnika u drugi niz
System.out.println("----------------------------------");
System.out.println("Unesite vrijednosti u drugi niz");
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
array2[i][j] = input.nextInt();
}
}
// Ispisivanje unesenih vrijednosti u prvom nizu
System.out.println(" ############ Vas prvi niz ############");
System.out.println("---------------------------------------");
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
System.out.print(array1[i][j] + " ");
}
System.out.println();
}
// Ispisivanje unesenih vrijednosti u drugom nizu
System.out.println("########### Vas drugi niz ############");
System.out.println("----------------------------------");
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
System.out.print(array2[i][j] + " ");
}
System.out.println();
}
// Pozivanje metode i ispisivanje rezultata dali su nizovi identicni ili ne
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
if (equals(array1, array2) == true) {
System.out.println("Vasa dva niza su identicna");
} else {
System.out.println("Vasa 2 niza nisu identicna");
}
}
}
| true
|
e42713babf386ffd0344e8c9825b07ec5c1dbb3b
|
Java
|
wozent/badstudentbackend
|
/src/main/java/badstudent/mappings/浙江省/金华市/金华区/金华区Mappings.java
|
UTF-8
| 272
| 1.695313
| 2
|
[] |
no_license
|
package badstudent.mappings.浙江省.金华市.金华区;
import badstudent.mappings.MappingBase;
public class 金华区Mappings extends MappingBase {
@Override
protected void initMappings() {
subAreaMappings.put("浙江师范大学",null);
}
}
| true
|
622b54c5ae98e2bc7a602fe5a0ab46e908fcb1cb
|
Java
|
hgong/jcr
|
/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java
|
UTF-8
| 10,385
| 2.109375
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.services.jcr.config;
import org.exoplatform.services.jcr.util.StringNumberParser;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by The eXo Platform SAS.
*
* @author <a href="mailto:geaz@users.sourceforge.net">Gennady Azarenkov </a>
* @version $Id: MappedParametrizedObjectEntry.java 1807 2005-08-28 13:34:58Z geaz $
*/
public abstract class MappedParametrizedObjectEntry
{
private static final Log LOG = ExoLogger
.getLogger("org.exoplatform.services.jcr.config.MappedParametrizedObjectEntry");
protected String type;
protected Map<String, SimpleParameterEntry> parameters = new LinkedHashMap<String, SimpleParameterEntry>();
public MappedParametrizedObjectEntry()
{
}
public MappedParametrizedObjectEntry(String type, List<SimpleParameterEntry> parameters)
{
this.type = type;
setParameters(parameters);
}
public Collection<SimpleParameterEntry> getParameters()
{
return parameters.values();
}
public Iterator<SimpleParameterEntry> getParameterIterator()
{
return parameters.values().iterator();
}
public boolean hasParameters()
{
return !parameters.isEmpty();
}
public boolean hasParameter(String name)
{
return parameters.containsKey(name);
}
/**
* Parse named parameter.
*
* @param name
* parameter name
* @return String
* @throws RepositoryConfigurationException
*/
public String getParameterValue(String name) throws RepositoryConfigurationException
{
String value = getParameterValue(name, null);
if (value == null)
throw new RepositoryConfigurationException("Parameter " + name + " not found ");
return value;
}
/**
* Parse named parameter.
*
* @param name
* parameter name
* @param defaultValue
* default value
* @return String
*/
public String getParameterValue(String name, String defaultValue)
{
String value = defaultValue;
SimpleParameterEntry p = parameters.get(name);
if (p != null)
{
value = p.getValue();
}
return value;
}
public void putParameterValue(String name, String value)
{
SimpleParameterEntry p = parameters.get(name);
if (p != null)
{
p.setValue(value);
return;
}
SimpleParameterEntry newParam = new SimpleParameterEntry(name, value);
addParameter(newParam);
}
/**
* Parse named parameter as Integer.
*
* @param name
* parameter name
* @param defaultValue
* default Integer value
* @return Integer value
*/
public Integer getParameterInteger(String name, Integer defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseInt(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
}
/**
* Set parameter as integer
*
* @param name
* @param defaultValue
*/
public void putIntegerParameter(String name, Integer value)
{
putParameterValue(name, value.toString());
}
/**
* Parse named parameter as Integer.
*
* @param name
* parameter name
* @return Integer value
* @throws RepositoryConfigurationException
*/
public Integer getParameterInteger(String name) throws RepositoryConfigurationException
{
try
{
return StringNumberParser.parseInt(getParameterValue(name));
}
catch (NumberFormatException e)
{
throw new RepositoryConfigurationException(name + ": unparseable Integer. " + e, e);
}
}
/**
* Parse named parameter as Long.
*
* @param name
* parameter name
* @param defaultValue
* default Long value
* @return Long value
*/
public Long getParameterLong(String name, Long defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseLong(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
}
/**
* Parse named parameter as Long.
*
* @param name
* parameter name
* @return Long value
* @throws RepositoryConfigurationException
*/
public Long getParameterLong(String name) throws RepositoryConfigurationException
{
try
{
return StringNumberParser.parseLong(getParameterValue(name));
}
catch (NumberFormatException e)
{
throw new RepositoryConfigurationException(name + ": unparseable Long. " + e, e);
}
}
/**
* Parse named parameter as Double.
*
* @param name
* parameter name
* @param defaultValue
* default Double value
* @return Double value
*/
public Double getParameterDouble(String name, Double defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseDouble(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
}
/**
* Parse named parameter as Double.
*
* @param name
* parameter name
* @return Double value
* @throws RepositoryConfigurationException
*/
public Double getParameterDouble(String name) throws RepositoryConfigurationException
{
try
{
return StringNumberParser.parseDouble(getParameterValue(name));
}
catch (NumberFormatException e)
{
throw new RepositoryConfigurationException(name + ": unparseable Long. " + e, e);
}
}
/**
* Parse named parameter using {@link StringNumberParser.parseTime} and return time in
* milliseconds (Long value).
*
* @param name
* parameter name
* @param defaultValue
* default time value
* @return
*/
public Long getParameterTime(String name, Long defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
try
{
return StringNumberParser.parseTime(value);
}
catch (NumberFormatException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
return defaultValue;
}
/**
* Parse named parameter using {@link StringNumberParser.parseTime} and return time in
* milliseconds (Long value).
*
* @param name
* parameter name
* @return Long value
* @throws RepositoryConfigurationException
*/
public Long getParameterTime(String name) throws RepositoryConfigurationException
{
try
{
return StringNumberParser.parseTime(getParameterValue(name));
}
catch (NumberFormatException e)
{
throw new RepositoryConfigurationException(name + ": unparseable time (as Long). " + e, e);
}
}
/**
* Parse named parameter as Boolean.
*
* @param name
* parameter name
* @param defaultValue
* default value
* @return boolean value
*/
public Boolean getParameterBoolean(String name, Boolean defaultValue)
{
String value = getParameterValue(name, null);
if (value != null)
{
return new Boolean(value);
}
return defaultValue;
}
/**
* Set parameter as boolean
*
* @param name
* @param value
*/
public void putBooleanParameter(String name, Boolean value)
{
putParameterValue(name, value.toString());
}
/**
* Parse named parameter as Boolean.
*
* @param name
* @return Boolean value
* @throws RepositoryConfigurationException
*/
public Boolean getParameterBoolean(String name) throws RepositoryConfigurationException
{
return new Boolean(getParameterValue(name));
}
public String getType()
{
return type;
}
public void setParameters(List<SimpleParameterEntry> parameters)
{
Map<String, SimpleParameterEntry> mParameters = new LinkedHashMap<String, SimpleParameterEntry>();
if (parameters != null)
{
for (SimpleParameterEntry param : parameters)
{
mParameters.put(param.getName(), param);
}
}
this.parameters = mParameters;
}
public void addParameter(SimpleParameterEntry param)
{
parameters.put(param.getName(), param);
}
public SimpleParameterEntry getParameter(String name)
{
return parameters.get(name);
}
public void setType(String type)
{
this.type = type;
}
}
| true
|
4b75d08c5a8e8e3370c2e4b42f1524ce8a1aabf6
|
Java
|
oncekiller/xsd2jsonSchema
|
/Xsd2JsonSchemaSoftware/src/main/java/JavaClassToJsonSchemaPhase.java
|
UTF-8
| 8,261
| 2.40625
| 2
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.kjetland.jackson.jsonSchema.JsonSchemaGenerator;
//Class qui permet de générer les fichiers json SCHEMA de la norme et des CODE listes
//Modifie également ces fichiers créés
public class JavaClassToJsonSchemaPhase extends App{
public static String path=new File("").getAbsolutePath();
public static InputStream inputRegroupedCodeList, inputResultXsd;
public static XmlSchemaCollection schemaCol = new XmlSchemaCollection();
public static XmlSchema schemaRegroupedCodeList, schemaResultXsd;
public static void main(String[] args) throws IOException {
try {
GetCodeListInformationPhase.run();
}catch(Throwable e) {
e.printStackTrace();
new ErrorScreen(e.getMessage(), "TransformJavaClassPhaseRun");
}
//On récupert le nom de la class de l'élément root du schema Xsd du fichier "resultXsd.xsd"
//On le sauvegarde dans la variable "nameElementRoot"
inputResultXsd = new FileInputStream(fileResultXsd);
schemaResultXsd = schemaCol.read(new StreamSource(inputResultXsd));
String nameElementRoot= schemaResultXsd.getElements().get(schemaResultXsd.getElements().keySet().toArray()[0]).getName();
File rep = new File(path+"\\src/main/java/generated");
//permet de creer une liste des fichiers java contenus dans le dossier src/main/java/generated
File[] fichiersJavaRep = rep.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
});
int checkFindNameRootClass=0;
for(File file : fichiersJavaRep) {
//regarde si le nom du fichier parcourru est celui de la class root
if(file.getName().contentEquals(nameElementRoot.concat(".java"))){
nameRootClassJava=nameElementRoot.concat(".java");
checkFindNameRootClass=1;
}
}
//Si on ne trouve pas le nom de la class root avec la méthode précedente on parcourt tous les fichiers java créés un a un, ligne par ligne et on voit lequel est le root
//Celui qui possède l'annotation "@XmlRootElement"
if(checkFindNameRootClass!=1) {
for(File file : fichiersJavaRep) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "";
while((line = reader.readLine()) != null){
if(line.contains("@XmlRootElement")) {
nameRootClassJava=file.getName();
}
}
}
}
//Creer le fichier json Schema de la norme
transformJavaClasstoJsonSchema(nameRootClassJava,true);
//Creer les fichiers json Schema des CODE listes
for(String type : ListTypeCodeList) {
transformJavaClasstoJsonSchema(type,false);
addDescriptionToJSchemaCodeList(type);
}
}
//Permet la création des fichiers json SCHEMA et de leurs contenus
//Prend un argument le nom d'une class java, et si elle appartient au élèments de la norme ou de la CodeList
//Ressort le fichier json correspondant
public static void transformJavaClasstoJsonSchema(String javaClassName, Boolean norme ) throws IOException {
//Fichier Json final créé a partir des arguments de la fonction
File fichierJsonFinal;
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new SimpleModule());
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
//récupére la class Java avec le nom indiqué en attribut
Class<?> rootClassJava = null;
JsonNode jsonSchema= null;
//Génére le schéma Json SCHEMA correspondant
try {
rootClassJava = Class.forName("generated."+javaClassName.replace(".java", ""));
jsonSchema = schemaGen.generateJsonSchema(rootClassJava);
}
catch(ClassNotFoundException e) {
e.printStackTrace();
new ErrorScreen(e.getMessage(), "Generate Json File");
}
//Créer le fichier .json au bon endroit dans le dossier
//Dossier "resources/json/" pour la norme
//Dossier "resources/json/codeList" pour les CODE listes
//Si le fichier créé est celui de la norme
if(norme) {
fichierJsonFinal = new File(path+"\\resources/json/"+javaClassName.replace(".java", "")+".json");
}
//Si le fichier créé est un élément des CODE listes
else {
fichierJsonFinal = new File(path+"\\resources/json/codeList/"+javaClassName.replace(".java", "")+".json");
}
fichierJsonFinal.createNewFile();
//Copie le schema Json dans le fichier créé
BufferedWriter writerFichierJsonFinal = new BufferedWriter(new FileWriter(fichierJsonFinal));
writerFichierJsonFinal.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
writerFichierJsonFinal.close();
// Pour le fichier json de la norme, enléve les enumerations des CODE listes qui ne servent à rien
if (norme) {
BufferedReader reader = new BufferedReader(new FileReader(fichierJsonFinal));
String line="" ,previousLine="", newContent="";
while((line = reader.readLine()) != null){
if(line.contains("\"enum\" : [")) {
if(!line.endsWith(",")&& previousLine.contains("\"$ref\" : \"codeList")) {
newContent=newContent.substring(0,newContent.length()-3)+"\r\n";
}
}
else {
newContent+=line+"\r\n";
}
previousLine = line;
}
FileWriter writer = new FileWriter(fichierJsonFinal);
writer.write(newContent);
writer.flush();
writer.close();
}
}
//Fonction qui ajoute les descriptions et valeurs d'énumération du tableau de description "descriptionCodeListTab" aux fichiers Json des CODE listes
public static void addDescriptionToJSchemaCodeList(String nameCodeList) throws IOException {
File fichierJson = new File(path+"\\resources/json/codeList/"+nameCodeList+".json");
BufferedReader reader = new BufferedReader(new FileReader(fichierJson));
String line = "",oldtext="";
//Ajoute l'attribut "description" au fichier Json avec les valeurs du tableau correspondant au fichier parcourru
while((line = reader.readLine()) != null){
oldtext +=line+"\r\n";
if(line.contains("\"title\" :")) {
oldtext+= " \"description\" : \" ";
for(String value: descriptionCodeListTab.get(nameCodeList).keySet()) {
oldtext+=value+ " : ( " ;
oldtext+="TITLE : "+ descriptionCodeListTab.get(nameCodeList).get(value)[0]+" / ";
oldtext+="DEFINITION : "+ descriptionCodeListTab.get(nameCodeList).get(value)[1]+" ) | ";
}
oldtext= oldtext.substring(0,oldtext.length()-3);
oldtext +=" \",\t\n";
}
}
FileWriter writer = new FileWriter(fichierJson);
writer.write(oldtext);
writer.flush();
writer.close();
BufferedReader reader2 = new BufferedReader(new FileReader(fichierJson));
String line2="" , oldtext2="";
while((line2 = reader2.readLine()) != null){
//Enleve les TRANSFORM_ pour les valeurs des enums qui ont ete modifie
line2=line2.replaceAll("TRANSFORM_", "");
oldtext2+=line2+"\r\n";
}
FileWriter writer2 = new FileWriter(fichierJson);
writer2.write(oldtext2);
writer2.flush();
writer2.close();
}
}
| true
|
9ffa875179eff9e909fee448e2434b285195a833
|
Java
|
kwonminki/Android_Test
|
/app/src/main/java/kr/ac/kangwon/hello/Lab_04_circulate.java
|
UTF-8
| 2,486
| 2.875
| 3
|
[] |
no_license
|
package kr.ac.kangwon.hello;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Lab_04_circulate extends AppCompatActivity {
EditText e1, e2;
TextView e3;
public void plus(View view){
e1=(EditText)findViewById(R.id.editText2);
e2=(EditText)findViewById(R.id.editText);
e3=(TextView)findViewById(R.id.circulate_result1);
double x = Double.parseDouble(e1.getText().toString());
double y = Double.parseDouble(e2.getText().toString());
Double result = x+y;
e3.setText(" "+result.toString());
}
public void minus(View view){
e1=(EditText)findViewById(R.id.editText2);
e2=(EditText)findViewById(R.id.editText);
e3=(TextView)findViewById(R.id.circulate_result1);
double x = Double.parseDouble(e1.getText().toString());
double y = Double.parseDouble(e2.getText().toString());
Double result = x-y;
e3.setText(" "+result.toString());
}
public void times(View view){
e1=(EditText)findViewById(R.id.editText2);
e2=(EditText)findViewById(R.id.editText);
e3=(TextView)findViewById(R.id.circulate_result1);
double x = Double.parseDouble(e1.getText().toString());
double y = Double.parseDouble(e2.getText().toString());
Double result = x*y;
e3.setText(" "+result.toString());
}
public void divided(View view){
e1=(EditText)findViewById(R.id.editText2);
e2=(EditText)findViewById(R.id.editText);
e3=(TextView)findViewById(R.id.circulate_result1);
Double x = Double.parseDouble(e1.getText().toString());
Double y = Double.parseDouble(e2.getText().toString());
double z = Double.parseDouble(e1.getText().toString());
double w = Double.parseDouble(e2.getText().toString());
Double result = Double.parseDouble(String.format("%.3f",z/w)) ;
Integer u = (int)(x/y);
Integer v = (int)(x%y);
if(u>1) {
e3.setText(" " + result.toString() + " 몫 : " + u.toString() + " 나머지 : " + v.toString());
}
else{
e3.setText(" " + result.toString());
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circulate);
}
}
| true
|
d82a7184ca5ccab4b05e24ae496b57273f437182
|
Java
|
chenxin6/Java
|
/Day07/Day07_1.java
|
UTF-8
| 1,764
| 3.703125
| 4
|
[] |
no_license
|
class Day07_1 {
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 5, 6, 7, 8, 9, 0};
int[] indexes = new int[arr.length];
System.out.println(arr.length);
/*int ret = findIndex(arr, 2);
if (ret != -1) {
System.out.println("ret = " + ret);
} else {
System.out.println("Not Found");
}
*/
/*
int ret = findMaxIndex(arr);
if (ret != -1) {
System.out.println("Max is " + arr[ret] + " at " + ret);
}
*/
/*
int count = findAllMaxIndex(arr, indexes);
for (int i = 0; i < count; i++) {
System.out.println("arr[" + indexes[i] + "] = " + arr[indexes[i]]);
}
*/
}
public static int findIndex(int[] array, int number) {
if (null == array || array.length == 0) {
System.out.println("输入的参数不合法");
return -1;
}
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == number) {
index = i;
break;
}
}
return index;
}
public static int findMaxIndex(int[] array) {
if (null == array || array.length == 0) {
System.out.println("输入的参数的不合法");
return -1;
}
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[index] < array [i]) {
index = i;
}
}
return index;
}
public static int findAllMaxIndex(int[] array, int[] indexes) {
if (null == array || array.length == 0 || null == indexes ||
indexes.length == 0) {
System.out.println("输入的参数不合法");
return -1;
}
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
}
}
int count = 0;
for (int j = 0; j < array.length; j++) {
if (max == array[j]) {
indexes[count] = j;
count++;
}
}
return count;
}
}
| true
|
461e4da36dca6f3b7321abad832cdd7e72fbf25c
|
Java
|
nao99/studyportal-authentication
|
/src/main/java/org/studyportal/authentication/api/model/user/UserDto.java
|
UTF-8
| 1,477
| 2.484375
| 2
|
[] |
no_license
|
package org.studyportal.authentication.api.model.user;
import org.studyportal.authentication.domain.model.user.User;
import org.studyportal.authentication.domain.model.user.UserDetailed;
import org.springframework.security.core.GrantedAuthority;
import java.util.List;
import java.util.stream.Collectors;
/**
* UserDto class
*
* @author Nikolai Osipov <nao99.dev@gmail.com>
* @version 1.0.0
* @since 2021-02-26
*/
public class UserDto {
/**
* User
*/
private final UserDetailed user;
/**
* UserDto constructor
*
* @param user a user
*/
public UserDto(final UserDetailed user) {
this.user = user;
}
public Long getId() {
return user.getId();
}
public String getUsername() {
return user.getUsername();
}
public String getEmail() {
return user.getEmail();
}
public List<String> getRoles() {
return user.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if (!other.getClass().isAssignableFrom(User.class)) {
return false;
}
UserDto otherUserDto = (UserDto) other;
return otherUserDto.user.equals(user);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * 17 + user.hashCode();
}
}
| true
|
62a0831c7955e2eb20696cfea836531537e67cf3
|
Java
|
Jasonandy/alpaca
|
/alpaca-pay/alpaca-pay-service/src/main/java/cn/ucaner/alpaca/pay/trade/utils/httpclient/HttpClientWrapper.java
|
UTF-8
| 3,049
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package cn.ucaner.alpaca.pay.trade.utils.httpclient;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpException;
import java.io.IOException;
import java.util.Map;
/**
* @Package:cn.ucaner.alpaca.pay.trade.utils.httpclient
* @ClassName:HttpClientWrapper
* @Description: <p> 封装了HttpClient 往服务器发送请求的接口
*
* 让用户 不适用任何HttpClient的api 直接调用该接口就可以实现相应的操作
* </p>
* @Author: -
* @CreatTime:2018年5月11日 上午9:58:08
* @Modify By:
* @ModifyTime: 2018年5月11日
* @Modify marker:
* @version V1.0
*/
public interface HttpClientWrapper {
/**
* 设置协议头的信息 用户可以根据自己的需求而设定,否则使用默认的设置
* @param headers
*/
public void addHttpHeader(Map<String, String> headers);
/**
* 清除cookie信息
*/
public void clearCookie();
/**
* 把一组cookies加到 httpclient 中
* @param cookies
*/
public void addCookies(Cookie[] cookies);
/**
* 增加单个的cookie
* @param cookie
*/
public void addCookie(Cookie cookie);
/**
*
* @param method
* @param url
* @param params
* @param charset
* @return 返回带编码集的字符串
* @throws HttpException
* @throws IOException
*/
public String doRequest(MethodType method, String url,
Map<String, String> params, String charset) throws HttpException,
IOException;
/**
*
* @param method
* @param url
* @param charset
* @return 返回带编码集的结果
* @throws HttpException
* @throws IOException
*/
public String doRequest(MethodType method, String url, String charset) throws HttpException, IOException;
/**
* 无返回值 实现HttpResponseCallBack接口 对流进行处理封转返回值 外部可以利用到流来得到结果 主要考虑的是多线程下载的情况
*
* @param method
* @param url
* @param params
* @param charset
* @throws HttpException
* @throws IOException
*/
// HttpResponseCallBack 是设置的一个回调类 ,主要是考虑由于httpClient 返回的流 当连接关闭时流也关闭了
// 所以利用回调的方式在流关闭之间嵌入用户代码,来操做流
public void doRequest(HttpResponseCallBack callback, MethodType method, String url, Map<String, String> params, String charset)
throws HttpException, IOException;
/**
* 无返回值 外部可以利用到流来得到结果 主要考虑的是多线程下载的情况
*
* @param method
* @param url
* @param charset
* @param callback
* @throws HttpException
* @throws IOException
*/
// HttpResponseCallBack 是设置的一个回调类 ,主要是考虑由于httpClient 返回的流 当连接关闭时流也关闭了
// 所以利用回调的方式在流关闭之间嵌入用户代码,来操做流
public void doRequest(HttpResponseCallBack callback, MethodType method,String url, String charset) throws HttpException, IOException;
}
| true
|
045cff1ca2b9a46a4228a272d1b70aef1623ef49
|
Java
|
aunroel/Missle_Command
|
/src/main/java/mypackage/ContactResolver.java
|
UTF-8
| 369
| 2.46875
| 2
|
[] |
no_license
|
package mypackage;
import java.util.ArrayList;
import java.util.Iterator ;
class ContactResolver {
// Resolves a set of particle contacts
void resolveContacts(ArrayList contacts) {
Iterator itr = contacts.iterator() ;
while(itr.hasNext()) {
Contact contact = (Contact)itr.next() ;
contact.resolve() ;
}
}
}
| true
|
64551f746870c26322233010676242c1f1f2f705
|
Java
|
vafin-mk/codingame
|
/src/main/java/puzzles/hard/surface/Solution.java
|
UTF-8
| 2,804
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
package puzzles.hard.surface;
import java.util.*;
class Solution {
public static void main(String args[]) {
new Solver(new Scanner(System.in)).solve();
}
}
class Solver {
static final int LAND = 0;
static final int UNKNOWN = -1;
static final int CALCULATING = -2;
final Scanner scanner;
final int width;
final int height;
final int testSize;
final int[][] cells;
final List<Point> testCells;
Solver(Scanner scanner) {
this.scanner = scanner;
width = scanner.nextInt();
height = scanner.nextInt();
if (scanner.hasNextLine()) {
scanner.nextLine();
}
cells = new int[width][height];
for (int y = 0; y < height; y++) {
String row = scanner.nextLine();
for (int x = 0; x < row.length(); x++) {
char ch = row.charAt(x);
cells[x][y] = (ch == '#') ? LAND : UNKNOWN;
}
}
testSize = scanner.nextInt();
testCells = new ArrayList<>();
for (int i = 0; i < testSize; i++) {
int X = scanner.nextInt();
int Y = scanner.nextInt();
testCells.add(new Point(X, Y));
}
}
void solve() {
recalculateSizes();
for (int i = 0; i < testSize; i++) {
Point checkPoint = testCells.get(i);
System.out.println(cells[checkPoint.x][checkPoint.y]);
}
}
void calculateSize(Point from) {
Queue<Point> unvisited = new LinkedList<>();
Set<Point> lake = new HashSet<>();
unvisited.add(from);
while (!unvisited.isEmpty()) {
Point curr = unvisited.poll();
if (cells[curr.x][curr.y] != UNKNOWN) continue;
lake.add(curr);
cells[curr.x][curr.y] = CALCULATING;
unvisited.addAll(adjacents(curr));
}
for (Point point : lake) {
cells[point.x][point.y] = lake.size();
}
}
void recalculateSizes() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (cells[x][y] != UNKNOWN) continue;
calculateSize(new Point(x, y));
}
}
}
List<Point> adjacents(Point from) {
List<Point> result = new ArrayList<>(4);
if (from.x > 0) {
result.add(new Point(from.x - 1, from.y));
}
if (from.x < width - 1) {
result.add(new Point(from.x + 1, from.y));
}
if (from.y > 0) {
result.add(new Point(from.x, from.y - 1));
}
if (from.y < height - 1) {
result.add(new Point(from.x, from.y + 1));
}
return result;
}
}
class Point {
final int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
@Override
public String toString() {
return x + "," + y;
}
}
| true
|
7b1d9e187017948f0e433a6647ec06efcfe26b84
|
Java
|
thehjain/Binary-Search-Tree-Notes
|
/SearchInBST.java
|
UTF-8
| 297
| 3.171875
| 3
|
[] |
no_license
|
//here we have to simply search given node in binary
//search tree.
boolean search(Node root, int val) {
if (root == null) return false;
if (root.data == val)
return true;
if (root.data > val)
search(root.left, val);
else
search(root.right, val);
}
//Problem is available on leetcode
| true
|
aaef02f3d334b4a96d7c9587c3843418117eb255
|
Java
|
SeekMentore/SeekMentore
|
/src/main/java/com/utils/ValidationUtils.java
|
UTF-8
| 6,337
| 2.375
| 2
|
[] |
no_license
|
package com.utils;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import com.constants.BeanConstants;
import com.constants.ValidationConstants;
import com.model.components.commons.SelectLookup;
import com.service.components.CommonsService;
import com.utils.context.AppContext;
public class ValidationUtils implements ValidationConstants {
public static Boolean checkIfResponseIsStringYes(final String yesNoResponse) {
if (checkStringAvailability(yesNoResponse)) {
if (YES.equals(yesNoResponse)) {
return true;
}
}
return false;
}
public static Boolean checkObjectAvailability(final Object object) {
if (null != object) {
return true;
}
return false;
}
public static Boolean checkNonNegativeNumberAvailability(final Integer object) {
if (checkObjectAvailability(object)) {
if (object >= 0) {
return true;
}
}
return false;
}
public static Boolean checkNonNegativeNumberAvailability(final Long object) {
if (checkObjectAvailability(object)) {
if (object >= 0) {
return true;
}
}
return false;
}
public static Boolean checkNonNegativeNonZeroNumberAvailability(final Integer object) {
if (checkObjectAvailability(object)) {
if (object > 0) {
return true;
}
}
return false;
}
public static Boolean checkNonNegativeNonZeroNumberAvailability(final Long object) {
if (checkObjectAvailability(object)) {
if (object > 0) {
return true;
}
}
return false;
}
public static Boolean checkStringAvailability(final String stringObject) {
if (checkObjectAvailability(stringObject)) {
if (!EMPTY_STRING.equals(stringObject.trim())) {
return true;
}
}
return false;
}
public static Boolean checkStringContainsText(final String stringObject, final String textToSearch) {
if (checkStringAvailability(stringObject) && checkStringAvailability(textToSearch)) {
if (stringObject.indexOf(textToSearch) != -1) {
return true;
}
}
return false;
}
public static Boolean checkNonEmptyList(final List<?> dataList) {
if (checkObjectAvailability(dataList)) {
return !dataList.isEmpty();
}
return false;
}
public static Boolean checkNonEmptyArray(final Object[] objectArray) {
if (checkObjectAvailability(objectArray)) {
return objectArray.length > 0;
}
return false;
}
public static Boolean validatePlainNotNullAndEmptyTextString(final Object text) {
if (null != text && !EMPTY_STRING.equals(text.toString()))
return true;
return false;
}
public static Boolean validateNameString(final String name, Boolean spaceAllowed) {
if (validatePlainNotNullAndEmptyTextString(name)) {
return Pattern.compile(REGEX_FOR_NAME_WITH_SPACES, Pattern.CASE_INSENSITIVE).matcher(name).find()
?
(spaceAllowed
? true
:
(name.indexOf(WHITESPACE) == -1)
)
:
false;
}
return false;
}
public static Boolean validateDate(final Date date) {
if (null != date) {
return true;
}
return false;
}
public static Boolean validatePhoneNumber(final String contactNumber, final int length) {
if (validatePlainNotNullAndEmptyTextString(contactNumber)) {
return Pattern.compile(REGEX_FOR_NUMBERS, Pattern.CASE_INSENSITIVE).matcher(contactNumber).find()
? (contactNumber.length() == length)
: false;
}
return false;
}
public static Boolean validateNumber (
final Integer number,
final Boolean hasMaxCount,
final int maxCount,
final Boolean hasMinCount,
final int minCount
) {
if (null == number)
return false;
final Boolean patternMatched = Pattern.compile(REGEX_FOR_NUMBERS, Pattern.CASE_INSENSITIVE).matcher(String.valueOf(number)).find();
final Boolean isUnderMaxCountLimit = hasMaxCount ? number <= maxCount : true;
final Boolean isUnderMinCountLimit = hasMinCount ? number >= minCount : true;
return patternMatched && isUnderMaxCountLimit && isUnderMinCountLimit;
}
public static Boolean validateAgainstSelectLookupValues (
final String delimitedValues,
final String delimiter,
final String selectLookUpTable
) {
if (validatePlainNotNullAndEmptyTextString(delimitedValues)) {
final List<SelectLookup> selectLookupList = getCommonsService().getSelectLookupList(selectLookUpTable);
for (final String value : delimitedValues.split(delimiter)) {
if (!selectLookupList.contains(new SelectLookup(value))) {
return false;
}
}
return true;
}
return false;
}
public static Boolean validateEmailAddress(final String email) {
if (validatePlainNotNullAndEmptyTextString(email)) {
try {
new InternetAddress(email).validate();
return true;
} catch (AddressException ex) {}
}
return false;
}
public static Boolean validateSemicolonSeperatedEmailAddress(final String semicolonSeperatedEmailAddress) {
if (validatePlainNotNullAndEmptyTextString(semicolonSeperatedEmailAddress)) {
final String emailAddresses[] = semicolonSeperatedEmailAddress.split(SEMICOLON);
if (checkNonEmptyArray(emailAddresses)) {
for (final String email : emailAddresses) {
if (validatePlainNotNullAndEmptyTextString(email)) {
try {
new InternetAddress(email).validate();
} catch (AddressException ex) {
return false;
}
} else {
return false;
}
}
return true;
}
}
return false;
}
public static Boolean validateFileExtension(final String[] extensions, final String filename) {
if (validatePlainNotNullAndEmptyTextString(filename)) {
final String fileExtension = filename.substring(filename.lastIndexOf(DOT) + 1);
if (checkStringAvailability(fileExtension)) {
for (final String extension : extensions) {
if (extension.trim().equalsIgnoreCase(fileExtension.trim())) {
return true;
}
}
}
}
return false;
}
public static Boolean validateFileSizeInMB(final byte[] fileBytes, final Double maxSizeInMB) {
return ApplicationUtils.computeFileSizeInMB((long)fileBytes.length) <= maxSizeInMB;
}
public static CommonsService getCommonsService() {
return AppContext.getBean(BeanConstants.BEAN_NAME_COMMONS_SERVICE, CommonsService.class);
}
}
| true
|
dbf2833c6167450123983ed3fd1d17cea8ec9b93
|
Java
|
JeniferCorado/Clase02
|
/Clase02/src/Ejercicio15/Ejercicio15.java
|
UTF-8
| 620
| 3.078125
| 3
|
[] |
no_license
|
package Ejercicio15;
import java.util.Scanner;
public class Ejercicio15 {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
int hora;
System.out.println("Ingrese la hora");
hora=s.nextInt();
if (hora>5 && hora <13)
{
System.out.println("Buenos dias");
}
else if ((hora>5 && hora <21))
{
System.out.println("Buenas tardes");
}
else
{
System.out.println("Buenas noches");
}
}
}
| true
|
271982e63a3c700b1968b6c7bc880d8d30f3426e
|
Java
|
Elizabethssss/cycle-rent
|
/src/main/java/com/belikov/valteris/cycle/detail/model/Detail.java
|
UTF-8
| 1,239
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package com.belikov.valteris.cycle.detail.model;
import com.belikov.valteris.cycle.bicycle.model.Bicycle;
import com.belikov.valteris.cycle.order.model.Order;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import java.util.List;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "details")
public class Detail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "description", nullable = false)
private String description;
@Column(name = "photo", nullable = false)
private String photo;
@Column(name = "price", nullable = false)
private double price;
@ManyToMany(mappedBy = "details")
private List<Order> orders;
@ManyToMany(mappedBy = "details")
private List<Bicycle> bicycles;
}
| true
|
00a7dde94378e8aa83e76020da86fb8d313cdaf8
|
Java
|
ysm20140508/fund
|
/src/main/java/com/jxnu/it/management/form/UserQuery.java
|
UTF-8
| 1,473
| 2.046875
| 2
|
[] |
no_license
|
package com.jxnu.it.management.form;
/**
* Created by yunva on 2016/1/22.
*/
public class UserQuery {
private String name;
private String account;
private Integer roleId;
private Integer page;
private Integer pageSize;
private String status;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "UserQuery{" +
"name='" + name + '\'' +
", account='" + account + '\'' +
", roleId=" + roleId +
", page=" + page +
", pageSize=" + pageSize +
", status=" + status +
'}';
}
}
| true
|
b430c60b3f77064432adc3ad8fd07b350cb67d5d
|
Java
|
emillevic/Projeto1-Compiladores
|
/src/problema1/compiladores/FunctionsProcedures.java
|
UTF-8
| 2,449
| 3.125
| 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 problema1.compiladores;
import java.util.ArrayList;
/**
*
* @author Mille
*/
public class FunctionsProcedures {
private String nome;
private String retorno;
private ArrayList<Variaveis> parametro = new ArrayList<Variaveis>();
private ArrayList<Variaveis> localvar = new ArrayList<Variaveis>();
public FunctionsProcedures(String nome, String retorno) {
this.nome = nome;
this.retorno = retorno;
}
public FunctionsProcedures(String nome) {
this.nome = nome;
}
public String getRetorno() {
return retorno;
}
public void setRetorno(String retorno) {
this.retorno = retorno;
}
public void addParametro(Variaveis var){
parametro.add(var);
}
public void addVar(Variaveis var){
localvar.add(var);
}
public boolean compareTo(FunctionsProcedures obj){
boolean flag = false;
if(this.nome.equals(obj.getNome())){
if(this.parametro.size() == obj.getParametro().size()){
for(int i = 0; i< this.parametro.size(); i++){
if(!parametro.get(i).getTipo().equals(obj.getParametro().get(i).getTipo())){
flag = true;
return false;
}else if(i == this.parametro.size()-1){
return true;
}
}
}
}
return false;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public ArrayList<Variaveis> getParametro() {
return parametro;
}
public void setParametro(ArrayList<Variaveis> parametro) {
this.parametro = parametro;
}
public ArrayList<Variaveis> getLocalvar() {
return localvar;
}
public void setLocalvar(ArrayList<Variaveis> localvar) {
this.localvar = localvar;
}
@Override
public String toString() {
return "FunctionsProcedures{" + "nome=" + nome + ", retorno=" + retorno + ", parametro=" + parametro + ", localvar=" + localvar + '}';
}
}
| true
|
ef9104dfd1e091920d48e17dd8f91993c63f142d
|
Java
|
joyhongtang/test
|
/test/src/main/java/com/joyhong/test/MessageEventTest.java
|
UTF-8
| 317
| 1.992188
| 2
|
[] |
no_license
|
package com.joyhong.test;
public class MessageEventTest {
public static final String HUMAN_SENSOR_OFF = "humanSensor.off";
public static final String HUMAN_SENSOR_ON = "humanSensor.on";
public final String message;
public MessageEventTest(String message) {
this.message = message;
}
}
| true
|
3b872265a3a716a116ed11db9f18e7c0ae5a65b7
|
Java
|
kalphageek/tr-subscribe-service
|
/src/main/java/me/kalpha/trsubscribeservice/trmart/entity/Eqp1Tr.java
|
UTF-8
| 1,594
| 1.976563
| 2
|
[] |
no_license
|
package me.kalpha.trsubscribeservice.trmart.entity;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.domain.Persistable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
@Table(name = "eqp1tr")
@NoArgsConstructor
@Getter @Setter
@ToString(of = {"id","name","value","eventTime", "createdDate", "createdBy"})
public class Eqp1Tr implements Persistable<Long> {
@Id
private Long id;
private String name;
private Long value;
@Column(name = "event_time")
private LocalDateTime eventTime;
@Column(name = "created_date")
private LocalDateTime createdDate;
@Column(name = "created_by")
private String createdBy;
public List<Eqp1TrDet> getEqp1TrDets() {
if (eqp1TrDets == null)
eqp1TrDets = new ArrayList<>();
return eqp1TrDets;
}
@OneToMany(mappedBy = "eqp1Tr")
List<Eqp1TrDet> eqp1TrDets;
@Override
public boolean isNew() {
if (createdDate == null) {
createdDate = LocalDateTime.now();
return true;
} else return false;
}
}
| true
|
568df30523968219b940acb9142e1301e4c7011c
|
Java
|
uzairafridii/KPTehsilMunicipalAdministrationServices
|
/app/src/main/java/com/uzair/kptehsilmunicipaladministrationservices/Models/DeathCertificatePresenterImplmenter.java
|
UTF-8
| 10,542
| 2.015625
| 2
|
[] |
no_license
|
package com.uzair.kptehsilmunicipaladministrationservices.Models;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.uzair.kptehsilmunicipaladministrationservices.Presenters.DeathCertificatePresenter;
import com.uzair.kptehsilmunicipaladministrationservices.R;
import com.uzair.kptehsilmunicipaladministrationservices.Views.DeathCertificateView;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeathCertificatePresenterImplmenter implements DeathCertificatePresenter
{
private DeathCertificateView deathView;
private Context context;
private List<String> urls = new ArrayList<>();
private int counter = 0;
public DeathCertificatePresenterImplmenter(DeathCertificateView deathView, Context context) {
this.deathView = deathView;
this.context = context;
}
@Override
public void onSubmitForm(final DatabaseReference dbRef, StorageReference storeRef, final FirebaseAuth mAuth,
final String deceasedName, final String deceasedCnic,
final String religion, final String relation, final String fName, final String fCnic, final String mName,
final String mCnic, final String husbandName, final String husbandCnic, final String deceasedDateOfBirth,
final String gravyardName, final String placeOfBirth, final String uc, final String gender, final List<Uri> uriList)
{
if(dbRef != null && storeRef !=null && mAuth != null &&
!deceasedName.isEmpty() && !deceasedCnic.isEmpty() &&
!religion.isEmpty() && !relation.isEmpty() && !fName.isEmpty() && !fCnic.isEmpty() &&
!mName.isEmpty() && !mCnic.isEmpty() && !husbandName.isEmpty() && !husbandCnic.isEmpty() &&
!deceasedDateOfBirth.isEmpty() && ! gravyardName.isEmpty() && !placeOfBirth.isEmpty() && !uc.isEmpty()
&&!gender.isEmpty() &&!uriList.isEmpty())
{
deathView.onShowProgressDialog();
for (int i = 0; i < uriList.size(); i++) {
Uri Image = uriList.get(i);
// storage reference to add images
final StorageReference imagePath = storeRef.child("DeathCertificateImages")
.child("image/" + Image.getLastPathSegment());
imagePath.putFile(uriList.get(i)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// to get download url
imagePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
counter = counter + 1;
String url = String.valueOf(uri);
urls.add(url);
// counter is equal to urls arraylist then upload all urls and data
if( counter == uriList.size()) {
// get user name reference
dbRef.child("Users").child(mAuth.getCurrentUser().getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
String date = DateFormat.getDateTimeInstance().
format(Calendar.getInstance().getTime());
// get the applicant name and cnic
String userName = dataSnapshot.child("user_name").getValue().toString();
String userCnic = dataSnapshot.child("user_cnic").getValue().toString();
// push key ref
DatabaseReference databaseRef = dbRef.child("Certificates").push();
Map formData = new HashMap<>();
formData.put("certificateType" , "Death");
formData.put("applicantName" , userName);
formData.put("applicantCnic" , userCnic);
formData.put("deceasedName" , deceasedName);
formData.put("deceasedCnic" , deceasedCnic);
formData.put("religion" , religion);
formData.put("relation" , relation);
formData.put("fatherName" , fName);
formData.put("fatherCnic" , fCnic);
formData.put("motherName" , mName);
formData.put("motherCnic" , mCnic);
formData.put("husbandName" , husbandName);
formData.put("husbandCnic" , husbandCnic);
formData.put("placeOfBirth" , placeOfBirth);
formData.put("unionCouncil" , uc);
formData.put("gravyard" , gravyardName);
formData.put("deceasedDateOfBirth" , deceasedDateOfBirth);
formData.put("date" , date);
formData.put("pushKey" , databaseRef.getRef().getKey());
formData.put("uid" , mAuth.getCurrentUser().getUid());
formData.put("cnicImages" , urls);
formData.put("status" , "Pending");
formData.put("gender" , gender);
databaseRef.setValue(formData)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
deathView.onDismissProgressDialog();
deathView.clearAllFileds();
successDialog("Apply Successfully Done");
} else {
deathView.showMessage("Error in uploading", "error");
deathView.onDismissProgressDialog();
}
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {}
});
}
}
});
}
});
}
}
else
{
deathView.showMessage("Please cnic and all fields are require", "info");
}
}
@Override
public void onSetSpinnerAdapter() {
deathView.setSpinnerAdapter();
}
@Override
public void chooseGalleryClick() {
deathView.chooseGallery();
}
@Override
public void previewImage(List<Uri> uri)
{
if (uri.size() > 2 || uri.size() < 2)
{
deathView.showMessage("Please select front and back side image", "warning");
}
else
{
deathView.displayImagePreview(uri);
}
}
private void successDialog(String dialogBody)
{
View myView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_for_complaint, null);
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setView(myView);
final AlertDialog dialog = alert.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
TextView body = myView.findViewById(R.id.message);
body.setText(dialogBody);
myView.findViewById(R.id.btnOk).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
deathView.closeActivity();
}
});
alert.show();
}
}
| true
|
74b768515cab2a879d37e907d9e953978f7f26f0
|
Java
|
aribpassos/exemplo-jpa
|
/src/br/com/algaworks/app/ConsultaVeiculoPorIndent.java
|
UTF-8
| 487
| 2.203125
| 2
|
[] |
no_license
|
package br.com.algaworks.app;
import javax.persistence.EntityManager;
import br.com.algaworks.util.JpaUtil;
import br.com.algaworks.veiculos.dominio.Veiculo;
public class ConsultaVeiculoPorIndent {
public static void main(String[] args) {
EntityManager manager = JpaUtil.getEntityManager();
Veiculo veiculo = manager.find(Veiculo.class, 2L);
System.out.println(veiculo.getModelo() + " - "
+ veiculo.getProprietario().getNome());
manager.close();
JpaUtil.close();
}
}
| true
|
949e2ecd6c715863e7ea3c892a48c827b3a1918b
|
Java
|
xm5646/GOE
|
/project-geo-dbserver/src/main/java/com/project/goe/projectgeodbserver/service/CardInfoService.java
|
UTF-8
| 2,481
| 2.28125
| 2
|
[] |
no_license
|
package com.project.goe.projectgeodbserver.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.project.goe.projectgeodbserver.entity.CardInfo;
import com.project.goe.projectgeodbserver.repository.CardInfoRepository;
@Service
public class CardInfoService {
@Autowired
private CardInfoRepository cardInfoRepository;
public CardInfo findByCardInfoId(long cardInfoId) {
return this.cardInfoRepository.findByCardInfoId(cardInfoId);
}
public List<CardInfo> findByUserId(long userId) {
return this.cardInfoRepository.findByUserId(userId);
}
public Map<Long,CardInfo> findAllMap(){
List<CardInfo> cardInfoList = this.cardInfoRepository.findAll();
Map<Long,CardInfo> cardMap = new HashMap<Long,CardInfo>();
if (cardInfoList!=null && cardInfoList.size()>0) {
for (CardInfo cardInfo : cardInfoList) {
cardMap.put(cardInfo.getCardInfoId(), cardInfo);
}
}
return cardMap;
}
public CardInfo findByCardNumber(String cardNumber) {
return this.cardInfoRepository.findByCardNumber(cardNumber);
}
// 更新或新增银行卡信息
@Transactional
public CardInfo save(CardInfo cardInfo) {
return this.cardInfoRepository.save(cardInfo);
}
// 删除单个银行卡信息
@Transactional
public void delete(CardInfo cardInfo) {
this.cardInfoRepository.delete(cardInfo);
}
// 分页查询银行卡信息
public Page<CardInfo> findAllCardInfoBySort(Pageable pageable) {
return this.cardInfoRepository.findAll(pageable);
}
// 根据用户id查询分页查询银行卡信息
public Page<CardInfo> findCardInfoByAccount(CardInfo cardInfo, Pageable pageable) {
Specification<CardInfo> spec = new Specification<CardInfo>() {
@Override
public Predicate toPredicate(Root<CardInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate p = cb.equal(root.get("userId").as(long.class), cardInfo.getUserId());
return p;
}
};
return this.cardInfoRepository.findAll(spec, pageable);
}
}
| true
|
e7fe23f9cfce3ed9fb1637024db643cfe8868511
|
Java
|
Dmytro99/Epam
|
/homework 02/OopHomework/src/main/java/com/epam/EnumFurniture.java
|
UTF-8
| 99
| 1.546875
| 2
|
[] |
no_license
|
package com.epam;
public enum EnumFurniture {
BED,
BOOKCASE,
CUPBOARD,
BENCH,
DOOR
}
| true
|
cd5a5f55e707798d61d5a5a317cbacb93210b4f6
|
Java
|
monkipython/GPS-device-tracker
|
/GPSDeviceDemo/src/com/veclink/poofpetgps/task/WifiConnectCheckTask.java
|
UTF-8
| 4,588
| 1.9375
| 2
|
[] |
no_license
|
package com.veclink.poofpetgps.task;
import android.content.Context;
import android.os.Handler;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.google.gson.Gson;
import com.veclink.poofpetgps.Global;
import com.veclink.poofpetgps.LocationUtil;
import com.veclink.poofpetgps.bluetooth.pojo.WifiInfo;
import com.veclink.poofpetgps.tcp.TcpSocketManager;
import com.veclink.poofpetgps.tcp.pojo.LocationInfo;
import com.veclink.poofpetgps.tcp.pojo.WifiConnectMessage;
import com.veclink.poofpetgps.util.CreateUploadDataUtil;
import com.veclink.poofpetgps.util.Gpsutil;
import com.veclink.poofpetgps.util.GsonUtil;
import com.veclink.poofpetgps.util.StorageUtil;
import com.veclink.poofpetgps.wifi.MobileNetUtil;
import com.veclink.poofpetgps.wifi.WifiAdmin;
import java.util.List;
/**
* Created by chenshen on 2016/6/28.
* wifi检测任务
*/
public class WifiConnectCheckTask implements Runnable {
private WifiAdmin wifiAdmin;
private Context mContext;
private static int count;
public WifiConnectCheckTask(Context mContext) {
wifiAdmin = WifiAdmin.getInstance(mContext);
this.mContext = mContext;
}
@Override
public void run() {
Log.v("WifiConnectCheckTask","start");
if(Global.isWifiConnected&&wifiAdmin.isWifiEnabled()){//如果是打开并且连接状态说明到时间了需要关闭wifi
wifiAdmin.closeWifi();
/**
* 这里上传一次wifi围栏信息。
*/
Log.v("WifiConnectCheckTask","关闭wifi ");
return;
}
if(wifiAdmin.isWifiEnabled()==false)wifiAdmin.openWifi();
Log.v("WifiConnectCheckTask","打开wifi ");
wifiAdmin.startScan();
List<WifiInfo> wifiInfoList = StorageUtil.readWifiInfoObjects(mContext);
for(final WifiInfo wifiInfo:wifiInfoList){
Log.v("WifiConnectCheckTask","addNetwork "+wifiInfo.toString());
wifiAdmin.addNetwork(wifiAdmin.createWifiInfo(wifiInfo.ssid,wifiInfo.pwd,wifiInfo.type));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(Global.isWifiConnected){
count = 0;
Global.config.wifiOpenCloseTimeInteval = 30;
LocationUtil.getInstance(mContext).onDestroy();
/**
* 这里上传一次wifi围栏信息。
*/
WifiConnectMessage wifiConnectMessage = new WifiConnectMessage(wifiInfo.ssid,wifiInfo.macAddress,wifiInfo.penName);
String json = GsonUtil.toJson(wifiConnectMessage);
byte[] uploaddata = CreateUploadDataUtil.createUploadData(CreateUploadDataUtil.WIFI_FAIL_LOCATION, json);
TcpSocketManager.getInstance().sendMessage(uploaddata);
break;
}
}
count++;
if(Global.isWifiConnected==false){
Global.config.wifiOpenCloseTimeInteval = 15;
}
if(count>=Global.MAX_TRY_CHECK_COUNT){
MobileNetUtil.setMobileNetEnable();
TcpSocketManager.getInstance().startTcpConnect();
LocationUtil.getInstance(mContext).setProofLocationListener(new LocationUtil.ProofLocationListener() {
@Override
public void startLocation() {
}
@Override
public void onLoacationChange(AMapLocation loc) {
/**
* 这里上传gps信息
*/
LocationInfo locationInfo = new LocationInfo(String.valueOf(loc.getLongitude()),String.valueOf(loc.getLatitude()));
String json = GsonUtil.toJson(locationInfo);
byte[] uploaddata = CreateUploadDataUtil.createUploadData(CreateUploadDataUtil.WIFI_FAIL_LOCATION, json);
TcpSocketManager.getInstance().sendMessage(uploaddata);
LocationUtil.getInstance(mContext).onDestroy();//上传后关闭gps
}
@Override
public void sopLocation() {
}
});
LocationUtil.getInstance(mContext).gpsLocationOption(Global.config.gpsLoacationTimeInteval);
LocationUtil.getInstance(mContext).startLocation();
}
}
}
| true
|