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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f5f412256902c5fd95207cc9febfacb0a1b16305
|
Java
|
besom/bbossgroups-mvn
|
/bboss_persistent/src/main/java/com/frameworkset/common/poolman/util/StatementParser.java
|
UTF-8
| 19,837
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2008 biaoping.yin
*
* 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.frameworkset.common.poolman.util;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import com.frameworkset.common.poolman.StatementInfo;
import com.frameworkset.common.poolman.sql.ParserException;
import com.frameworkset.common.poolman.sql.PrimaryKey;
import com.frameworkset.common.poolman.sql.PrimaryKeyCacheManager;
import com.frameworkset.common.poolman.sql.Sequence;
import com.frameworkset.common.poolman.sql.UpdateSQL;
import com.frameworkset.util.RegexUtil;
import com.frameworkset.util.SimpleStringUtil;
/**
* 解析sql语句程序
*
* @author biaoping.yin created on 2005-3-31 version 1.0
*/
public class StatementParser implements Serializable
{
private static Logger log = Logger.getLogger(StatementParser.class);
/**
* insert正则表达式解析insert语句 如果insert语句与正则表达式匹配,本方法根据表达式对语句的分组
* 将insert语句拆分为6部分,并且将这几部分存放到字符串数组返回 分别为: 1.insert关键字 2.into关键字 3.表名称 4.表字段组
* 5.values关键字 6.插入字段值组
*
* 比如insert语句: Insert into oa_meetingpromptsound ( soundCode , soundName ,
* soundFileName ) values ( '。.尹标平','bb','d()d' ) 将被分解为以下部分: 1.Insert 2.into
* 3.oa_meetingpromptsound 4.( soundCode , soundName , soundFileName )
* 5.values 6.( '。.尹标平','bb','d()d' )
*/
public static String[] parserInsert(String insert)
{
/**
* 定义insert语句的正则表达式 该表达式将insert语句拆分为6部分,分别为: 1.insert关键字 2.into关键字 3.表名称
* 4.表字段组 5.values关键字 6.插入字段值组 比如insert语句: Insert into
* oa_meetingpromptsound ( soundCode , soundName , soundFileName )
* values ( '。.尹标平','bb','d()d' ) 将被分解为以下部分: 1.Insert 2.into
* 3.oa_meetingpromptsound 4.( soundCode , soundName , soundFileName )
* 5.values 6.( '。.尹标平','bb','d()d' )
*/
String patternStr = "\\s*(insert)\\s+" + // 解析insert关键词
"(into)\\s+" + // 解析into关键词
"([^\\(^\\s]+)\\s*" + // 解析表名称
"(\\([^\\)]+\\))\\s*" + // 解析表字段
"(values)\\s*" + // 解析value关键词
"(\\(.*(.*\n*)*.*)"; // 解析字段值
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try
{
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
}
catch (MalformedPatternException e)
{
e.printStackTrace();
return null;
}
PatternMatcher matcher = new Perl5Matcher();
MatchResult result = null;
String[] tokens = null;
boolean match = matcher.matches(insert, pattern);
if (match)
{
result = matcher.getMatch();
tokens = new String[6];
for (int i = 0; i < 6; i++)
{
tokens[i] = result.group(i + 1).trim();
}
}
return tokens;
}
public static String[] parseField(String fieldStr)
{
// ( soundCode , soundName , soundFileName )
//fieldStr = fieldStr.trim();
// String regx = "\\([\\s*([^\\,]+)\\,?]+\\)";
String regx = "([^\\,^\\(^\\)]+)\\s*\\,?\\s*";
return RegexUtil.containWithPatternMatcherInput(fieldStr,regx);
// PatternCompiler compiler = new Perl5Compiler();
// Pattern pattern = null;
// try
// {
// pattern = compiler.compile(regx,
// Perl5Compiler.CASE_INSENSITIVE_MASK);
// }
// catch (MalformedPatternException e)
// {
// e.printStackTrace();
// return null;
// }
// PatternMatcher matcher = new Perl5Matcher();
// MatchResult result = null;
// String[] tokens = null;
// if (matcher.matches(fieldStr, pattern))
// {
// result = matcher.getMatch();
//
// tokens = new String[result.groups()];
// for (int i = 0; i < result.groups(); i++)
// {
// tokens[i] = result.group(i + 1).trim();
// }
// }
// return tokens;
}
public static String[] parserValues(String values)
{
String patternStr = "([^\\,]*)[\\,]?"; // 解析字段值
String patternStr1 = "('?[^\\,]*'?)[\\,]?"; // 解析字段值
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
String[] ret = RegexUtil.containWithPatternMatcherInput(values,patternStr1);
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try
{
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
}
catch (MalformedPatternException e)
{
e.printStackTrace();
return null;
}
PatternMatcher matcher = new Perl5Matcher();
MatchResult result = null;
String[] tokens = null;
boolean match = matcher.matches(values.trim(), pattern);
System.out.println(match);
if (match)
{
result = matcher.getMatch();
tokens = new String[6];
for (int i = 0; i < 6; i++)
{
tokens[i] = result.group(i + 1).trim();
System.out.println(tokens[i]);
}
}
return tokens;
}
class ParserValues
{
Stack operations = new Stack();
}
public static void main(String[] args)
{
String insert = "insert into td_cms_channel(NAME, DISPLAY_NAME, PARENT_ID,CHNL_PATH, CREATEUSER, CREATETIME, ORDER_NO,SITE_ID, STATUS, OUTLINE_TPL_ID, DETAIL_TPL_ID,CHNL_OUTLINE_DYNAMIC, DOC_DYNAMIC,CHNL_OUTLINE_PROTECT, DOC_PROTECT,WORKFLOW,PARENT_WORKFLOW) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// String insert = "insert into TD_CMS_DOCUMENT(TITLE, SUBTITLE, AUTHOR,DOCKIND,DOCOUTPUTID,CONTENT,STATUS, KEYWORDS,DOCABSTRACT,DOCTYPE,DOCLEVEL,DOCWTIME,TITLECOLOR, PUBLISHTIME,DOCFLAG,DOCPUBURL,DOCUMENTPRIOR,CREATEUSER, CREATETIME,LASTVISITTIME,PARENTDOCUMENT_ID, DOCSOURCE_ID,DETAILTEMPLATE_ID,CHANNEL_ID,USER_ID,ISLOCK,LINKTARGET,LINKFILE) values('eee','eee','eee', 'null','null','', 0,'eee','eee',0, 0,TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),'#000000',TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),0, 'null',100,0,TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'), TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),0,2,1, 2,1,0,'null','null')";
parserInsert(insert);
// String update = "update table1 set name='aaa' where id='1'";
// parserUpdateSQL(update);
// String patternStr = "(insert)\\s+" + // 解析insert关键词
// "(into)\\s+" + // 解析into关键词
// "([^\\(]+)\\s*" + // 解析表名称
// "(\\([^\\)]+\\))\\s+" + // 解析表字段
// "(values)\\s*" + // 解析value关键词
// "(\\(.+)"; // 解析字段值
//
// // parseField("( soundCode , soundName , soundFileName )");\
// /**
// * 'XXXXX',
// * ',XXXXXXX,
// * XXXXXXXX,'
// * ','
// * ,
// * ',XXXXX'
// */
// String sql = "'姜儒振 同志在 2005-05-12 批示:\r\n"
// + "据悉,长沙市政府拟改扩建阜埠路,这是对两所高,校8万师生所做的一件大好事。该报告所提建议,请长沙市政府认真研究,妥善处理。\r\n"
// + "请云昭省长批示。',to_date('2005-04-23 11:04:44','yyyy-mm-dd hh24:mi:ss'),2,1558";
//// for (int i = 0; i < 1; i++)
//// parserValues(sql);
//
// String fields = "( name , id , desc )";
// String ret[] = parseField(fields);
// String sqls[] = parserInsert("insert into TD_CMS_DOCUMENT(TITLE, SUBTITLE, AUTHOR,DOCKIND,DOCOUTPUTID,CONTENT,STATUS, KEYWORDS,DOCABSTRACT,DOCTYPE,DOCLEVEL,DOCWTIME,TITLECOLOR, PUBLISHTIME,DOCFLAG,DOCPUBURL,DOCUMENTPRIOR,CREATEUSER, CREATETIME,LASTVISITTIME,PARENTDOCUMENT_ID, DOCSOURCE_ID,DETAILTEMPLATE_ID,CHANNEL_ID,USER_ID,ISLOCK,LINKTARGET,LINKFILE) values('eee','eee','eee', 'null','null','', 0,'eee','eee',0, 0,TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),'#000000',TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),0, 'null',100,0,TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'), TO_DATE('29-12-2006 10:54:49', 'DD-MM-YYYY HH24:MI:SS'),0,2,1, 2,1,0,'null','null')");
//
// System.out.println(ret.length);
// System.out.println(sqls.length);
// // System.out.println("dbName:" +
// // SQLManager.getInstance().getDefaultDBName());
// // Object[] temp =
// // PoolManStatement.refactorInsertStatement(sql,SQLManager.getInstance().getDefaultDBName());
// // System.out.println(temp[0]);
// // System.out.println(temp[1]);
// // System.out.println(temp[2]);
// // System.out.println(temp[3]);
// //
// // parserInsert(sql);
}
// /**
// * 分析updatesql语句中包含的表名,关键字,和更新部分:table name
// * 例如:update table1 set name='aaa' where id='1';
// * @param updateSQL
// * @return String[4] {update,table1,set,values and where clause}
// */
// public static String[] parserUpdateSQL(String updateSQL)
// {
// String regex = "\\s*(update)\\s+([^\\s]+)\\s+(set)\\s+(.+)";
// PatternCompiler compiler = new Perl5Compiler();
// Pattern pattern = null;
// try
// {
// pattern = compiler.compile(regex,
// Perl5Compiler.CASE_INSENSITIVE_MASK);
// }
// catch (MalformedPatternException e)
// {
// e.printStackTrace();
//
// return null;
// }
// PatternMatcher matcher = new Perl5Matcher();
// MatchResult result = null;
// String[] tokens = null;
// boolean match = matcher.matches(updateSQL, pattern);
//
// if (match)
// {
// result = matcher.getMatch();
// tokens = new String[4];
// for (int i = 0; i < 4; i++)
// {
// tokens[i] = result.group(i + 1).trim();
// }
// }
//
// return tokens;
// }
// public static Object[] refactorUpdateStatement(StatementInfo stateinfo) throws ParserException
// {
// return refactorUpdateStatement(stateinfo.getCon(),stateinfo.getSql(),stateinfo.getDbname());
// }
// /**
// * 拆分update语句,获取update的表和对应的主键字段信息
// * @param updateStmt
// * @param dbname
// * @return
// * @throws ParserException
// */
// private static Object[] refactorUpdateStatement(Connection con,String updateStmt,String dbname) throws ParserException
// {
// //{update,table1,set,values and where clause}
// String[] updateInfos = StatementParser.parserUpdateSQL(updateStmt);
// if(updateInfos == null)
// throw new ParserException("非法的更新语句:" + updateStmt);
//
// String tableName = updateInfos[1];
// PrimaryKey primaryKey = null;
// try
// {
//
// primaryKey = PrimaryKeyCacheManager.getInstance()
// .getPrimaryKeyCache(dbname)
// .getIDTable(con,tableName.toLowerCase());
// if(primaryKey == null)
// {
// //System.out.println("表'" + tableName + "'没有定义主键或定义了多主键!");
// primaryKey = new PrimaryKey(dbname,updateInfos[1],null,null,con);
// primaryKey.setHasTableinfo(false);
// log.debug("未给表["+ tableName + "]定义主键信息,请检查tableinfo表中是否存在该表的记录:" + updateStmt);
// }
// return new Object[] {primaryKey,updateInfos};
//
// }
// catch(Exception e)
// {
// log.info("[db:"
// + dbname
// + "] tableinfo not initialed or initial failed"
// + " or check the table "
// + "[tableinfo has been created] or table[" + tableName
// + "'s information has been inserted into tableinfo"
// + "]\r\n please check log to view detail.");
// //e.printStackTrace();
// throw new ParserException("未给表["+ tableName + "]定义主键信息,请检查tableinfo表中是否存在该表的记录:" + updateStmt);
//
//
//
// }
//
//
// }
/**
* added by biaoping.yin on 2005.03.29
* 重构insert语句,添加主键信息,首先获取主键值
* @param insertStmt 数据库插入语句
* @param dbname 数据库名称
* @return ret
* ret[0]:存放insert语句
* ret[1]:存放新的主键值,如果不是插入语句则为空
* ret[2]:更新表tableinfo中插入表对应主键值语句,如果不是插入语句则为空
* ret[3]:PrimaryKey对象,如果不是插入语句则为空
* ret[4]:标识主键是自动产生还是用户指定,0-标识自动
* 1-标识用户指定
* 如果不是插入语句则为空
* ret[6]:field字段数组;
* @throws SQLException
*
*/
public static Object[] refactorInsertStatement(Connection con,String insertStmt,String dbname) throws SQLException
{
return refactorInsertStatement(con,insertStmt,dbname,false);
}
public static Object[] refactorInsertStatement(StatementInfo stmtInfo) throws SQLException
{
return refactorInsertStatement(stmtInfo.getCon(),stmtInfo.getSql(),stmtInfo.getDbname(), stmtInfo.isPrepared());
}
/**
* added by biaoping.yin on 2005.03.29
* 重构insert语句,添加主键信息,首先获取主键值
* @param insertStmt 数据库插入语句
* @param dbname 数据库名称
* @return ret
* ret[0]:存放insert语句
* ret[1]:存放新的主键值,如果不是插入语句则为空
* ret[2]:更新表tableinfo中插入表对应主键值语句,如果不是插入语句则为空
* ret[3]:PrimaryKey对象,如果不是插入语句则为空
* ret[4]:标识主键是自动产生还是用户指定,0-标识自动
* 1-标识用户指定
* 如果不是插入语句则为空
* ret[6]:field字段数组;
* @throws SQLException
*
*/
public static Object[] refactorInsertStatement(Connection con ,String insertStmt,String dbname,boolean prepared) throws SQLException
{
Object[] ret = new Object[6];
//String tableName = this.getInsertTableName(insertStmt);
//this.getInsertTableName(insertStmt);
/**
* 1.Insert
* 2.into
* 3.oa_meetingpromptsound
* 4.( soundCode , soundName , soundFileName )
* 5.values
* 6.( '。.尹标平','bb','d()d' )
*/
String tableInfos[] = StatementParser.parserInsert(insertStmt);
if(tableInfos == null)
{
ret[0] = insertStmt;
return ret;
}
String insert = tableInfos[0];
String into = tableInfos[1];
String tableName = tableInfos[2];
String fields = tableInfos[3];
String values_key = tableInfos[4];
String values = tableInfos[5];
PrimaryKey primaryKey = null;
try
{
primaryKey = PrimaryKeyCacheManager.getInstance()
.getPrimaryKeyCache(dbname)
.getIDTable(con,tableName.toLowerCase());
}
catch(Exception e)//如果抛出sql异常,忽略,不影响整个事务的处理。
{
log.info("[db:"
+ dbname
+ "] tableinfo not initialed or initial failed"
+ " or check the table "
+ "[tableinfo has been created] or table[" + tableName
+ "'s information has been inserted into tableinfo"
+ "]\r\n please check log to view detail.");
//e.printStackTrace();
ret[0] = insertStmt;
return ret;
}
if(primaryKey == null)
{
//System.out.println("表'" + tableName + "'没有定义主键或定义了多主键!");
ret[0] = insertStmt;
PrimaryKey t_p = new PrimaryKey(dbname,tableName,null,null,con);
ret[3] = t_p;
return ret;
}
//定义表的主键名称变量
String idName = primaryKey.getPrimaryKeyName();
boolean contain = containKey(fields,idName);
ret[4] = new Integer(0);
ret[5] = StatementParser.parseField(fields);
if(contain)
{
String s_temp = values.trim();
s_temp = s_temp.substring(1,s_temp.length() -1);
String keyValue = getKeyValue(s_temp);
ret[0] = insertStmt;
ret[1] = keyValue;
PrimaryKey t_p = new PrimaryKey(primaryKey.getDbname(),
primaryKey.getTableName(),
primaryKey.getPrimaryKeyName(),
keyValue,con);
ret[3] = t_p;
ret[4] = new Integer(1);
return ret;
}
//将表的主键字段属性插入到insert语句中
StringBuffer temp = new StringBuffer(fields);
temp.insert(1,idName + ",");
fields = temp.toString();
temp = new StringBuffer(values);
// //定义主键值变量
Sequence idValue = primaryKey.generateObjectKey(con);
temp.insert(1,PrimaryKey.changeID(idValue.getPrimaryKey(),dbname,primaryKey.getType()) + ",");
values = temp.toString();
temp = new StringBuffer(insert);
temp.append(" ")
.append(into)
.append(" ")
.append(tableName)
.append(fields)
.append(" ")
.append(values_key)
.append(values);
//started here
//设置insert语句
ret[0] = temp.toString();
//设置新的主键值
ret[1] = idValue.getPrimaryKey();
//设置更新tableinfo的语句
List datas = new ArrayList();
datas.add(new Long(idValue.getSequence()));
datas.add(tableName.toLowerCase());
datas.add(new Long(idValue.getSequence()));
UpdateSQL preparedUpdate = new UpdateSQL(dbname,tableName,UpdateSQL.TABLE_INFO_UPDATE, datas);
// ret[2] = "update tableinfo set table_id_value=" + idValue.getSequence() +" where table_name='"+ tableName.toLowerCase() + "' and table_id_value <" + idValue.getSequence() ;
ret[2] = preparedUpdate ;
//设置表主键信息封装类
ret[3] = primaryKey;
// ret[4] = new Integer(0);
return ret;
}
private static String getKeyValue(String values)
{
String regx = "";
return "";
}
/**
* 判断是否已有主键
* @param fields
* @param idName
* @return boolean
*/
private static boolean containKey(String fields,String idName)
{
String temp = fields.trim();
temp = temp.substring(1,temp.length() - 1);
//System.out.println(temp);
String field[] = SimpleStringUtil.split(temp,",");
for(int i = 0; field != null && i < field.length; i ++)
{
if(field[i].trim().equalsIgnoreCase(idName.trim()))
return true;
}
return false;
}
}
| true
|
452729d9702ad51039ce2127176ba5ddb0e79f6a
|
Java
|
m-alves/TourGuide
|
/app/src/main/java/com/example/android/santacatarinasitimos/Interest.java
|
UTF-8
| 4,560
| 3.171875
| 3
|
[] |
no_license
|
package com.example.android.santacatarinasitimos;
/**
* Created by Utilizador on 02/06/2017.
*/
/**
* {@link Interest} represents a point of interest.
* It contains a name, a description, distance to village, a contact and an image for that point of interest.
*/
public class Interest {
/** Name */
private int mNameResourceId;
/** Description */
private int mDescriptionResourceId;
/** Distance */
private int mDistanceResourceId = NO_DISTANCE_PROVIDED;
/** Constant value that represents no distance was provided for this point of interest */
private static final int NO_DISTANCE_PROVIDED = -1;
/** Contact */
private int mContactResourceId = NO_CONTACT_PROVIDED;
/** Constant value that represents no contact was provided for this point of interest */
private static final int NO_CONTACT_PROVIDED = -1;
/** Image resource ID for the Point of Interest */
private int mImageResourceId;
/**
* Create a new Interest object.
*
* @param nameResourceId is the string resource ID for the name associated with the Point of Interest.
* @param descriptionResourceId is the string resource ID for the description associated with the Point of Interest.
* @param distanceResourceId is the string resource ID for the distance associated with the Point of Interest
* @param contactResourceId is the string resource ID for the contact associated with the Point of Interest
* @param imageResourceId is the drawable resource ID for the image associated with the Point of Interest
*/
public Interest(int nameResourceId, int descriptionResourceId, int distanceResourceId, int contactResourceId, int imageResourceId) {
mNameResourceId = nameResourceId;
mDescriptionResourceId = descriptionResourceId;
mDistanceResourceId = distanceResourceId;
mContactResourceId = contactResourceId;
mImageResourceId = imageResourceId;
}
/**
* Create a new Interest object.
*
* @param nameResourceId is the string resource ID for the name associated with the Point of Interest.
* @param descriptionResourceId is the string resource ID for the description associated with the Point of Interest.
* @param contactResourceId is the string resource ID for the contact associated with the Point of Interest
* @param imageResourceId is the drawable resource ID for the image associated with the Point of Interest
*/
public Interest (int nameResourceId, int descriptionResourceId, int contactResourceId, int imageResourceId) {
mNameResourceId = nameResourceId;
mDescriptionResourceId = descriptionResourceId;
mContactResourceId = contactResourceId;
mImageResourceId = imageResourceId;
}
/**
* Create a new Interest object.
*
* @param nameResourceId is the string resource ID for the name associated with the Point of Interest.
* @param descriptionResourceId is the string resource ID for the description associated with the Point of Interest.
* @param imageResourceId is the drawable resource ID for the image associated with the Point of Interest
*/
public Interest (int nameResourceId, int descriptionResourceId, int imageResourceId) {
mNameResourceId = nameResourceId;
mDescriptionResourceId = descriptionResourceId;
mImageResourceId = imageResourceId;
}
/**
* Return the name resource ID of the Interest.
*/
public int getNameResourceId() {
return mNameResourceId;
}
/**
* Return the description resource ID of the Interest.
*/
public int getDescriptionResourceId() {
return mDescriptionResourceId;
}
/**
* Return the distance resource ID of the Interest.
*/
public int getDistanceResourceId() {
return mDistanceResourceId;
}
/**
* Return the contact resource ID of the Interest.
*/
public int getContactResourceId() {
return mContactResourceId;
}
/**
* Return the image resource ID of the Interest.
*/
public int getImageResourceId() {
return mImageResourceId;
}
/**
* Returns whether or not there is distance for this Interest.
*/
public boolean hasDistance() {
return mDistanceResourceId != NO_DISTANCE_PROVIDED;
}
/**
* Returns whether or not there is contact for this Interest.
*/
public boolean hasContact() {
return mContactResourceId != NO_CONTACT_PROVIDED;
}
}
| true
|
03abcb16baf810ba142359c173d01741aaf64170
|
Java
|
EstebanDalelR/tinderAnalysis
|
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/match/presenter/ad.java
|
UTF-8
| 341
| 1.640625
| 2
|
[] |
no_license
|
package com.tinder.match.presenter;
import java8.util.Optional;
import java8.util.function.Predicate;
final /* synthetic */ class ad implements Predicate {
/* renamed from: a */
static final Predicate f39209a = new ad();
private ad() {
}
public boolean test(Object obj) {
return ((Optional) obj).c();
}
}
| true
|
d85dade5c4db8694de61155ac13ef8117777ad77
|
Java
|
cckmit/fcs
|
/FBPM/AM/fcs-am-integration/src/main/java/com/born/fcs/am/intergration/service/CouncilApplyServiceClient.java
|
UTF-8
| 2,372
| 2.046875
| 2
|
[] |
no_license
|
package com.born.fcs.am.intergration.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.born.fcs.pm.ws.enums.CompanyNameEnum;
import com.born.fcs.pm.ws.enums.CouncilTypeEnum;
import com.born.fcs.pm.ws.info.council.CouncilApplyInfo;
import com.born.fcs.pm.ws.order.council.CouncilApplyOrder;
import com.born.fcs.pm.ws.order.council.CouncilApplyQueryOrder;
import com.born.fcs.pm.ws.result.base.FcsBaseResult;
import com.born.fcs.pm.ws.result.base.QueryBaseBatchResult;
import com.born.fcs.pm.ws.service.council.CouncilApplyService;
/**
*
*
*
* @author Fei
*
*/
@Service("councilApplyServiceClient")
public class CouncilApplyServiceClient extends ClientAutowiredBaseService implements
CouncilApplyService {
@Override
public FcsBaseResult saveCouncilApply(final CouncilApplyOrder order) {
return callInterface(new CallExternalInterface<FcsBaseResult>() {
@Override
public FcsBaseResult call() {
return councilApplyWebService.saveCouncilApply(order);
}
});
}
@Override
public List<CouncilApplyInfo> queryCouncilApplyByProjectCode(final String projectCode) {
return callInterface(new CallExternalInterface<List<CouncilApplyInfo>>() {
@Override
public List<CouncilApplyInfo> call() {
return councilApplyWebService.queryCouncilApplyByProjectCode(projectCode);
}
});
}
@Override
public CouncilApplyInfo queryCouncilApplyByApplyId(final long applyId) {
return callInterface(new CallExternalInterface<CouncilApplyInfo>() {
@Override
public CouncilApplyInfo call() {
return councilApplyWebService.queryCouncilApplyByApplyId(applyId);
}
});
}
@Override
public QueryBaseBatchResult<CouncilApplyInfo> queryCouncilApply(final CouncilApplyQueryOrder order) {
return callInterface(new CallExternalInterface<QueryBaseBatchResult<CouncilApplyInfo>>() {
@Override
public QueryBaseBatchResult<CouncilApplyInfo> call() {
return councilApplyWebService.queryCouncilApply(order);
}
});
}
@Override
public String getAvailableCouncilCodeSeq(final CompanyNameEnum company,
final CouncilTypeEnum councilType) {
return callInterface(new CallExternalInterface<String>() {
@Override
public String call() {
return councilApplyWebService.getAvailableCouncilCodeSeq(company, councilType);
}
});
}
}
| true
|
7abdcaa5a940442e3c67a4d41fed0a65fb97aab4
|
Java
|
zhaoqingyue/AppMarket
|
/Marcket/src/cld/kcloud/utils/KCloudNetUtils.java
|
UTF-8
| 11,882
| 1.898438
| 2
|
[] |
no_license
|
package cld.kcloud.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import android.util.Log;
import cld.kmarcket.appinfo.AppInfo;
import cld.kmarcket.util.CommonUtil;
import cld.kmarcket.util.ConfigUtils;
import cld.kmarcket.util.LogUtil;
import cld.weather.api.CldSapNetUtil;
import cld.weather.api.CldSapReturn;
import cld.weather.api.KSign;
import cld.weather.api.NetUtil;
public class KCloudNetUtils {
private final static String TAG = "KCloudNetUtils";
/** 首次密文. */
public static String account_key = "";
public static String kgo_key = "";
public static final int umsaver = 1;
public static final int rscharset = 1;
public static final int rsformat = 1;
public static final int apiver = 1;
public static final int cid = 1010;
public static final String prover = "C3486-C7M04-3721J0Q";
public static final int system_code = 1;
public static final int device_code = 1;
public static final int product_code = 2;
public static final int width = 1600;
public static final int height = 480;
public static String launcher_ver = "";
public static void setAccountKey(String key) {
account_key = decodeKey(key);
Log.d(TAG, "account_key = " + account_key);
}
private static String getHeadUrl() {
if (NetUtil.isTestVersion()) {
return "http://tmctest.careland.com.cn/";
} else {
return "http://stat.careland.com.cn/";
}
}
public static CldSapReturn getKgoSign() {
String key = "";
Map<String, Object> map = new HashMap<String, Object>();
map.put("umsaver", umsaver);
map.put("rscharset", rscharset);
map.put("rsformat", rsformat);
map.put("apiver", apiver);
map.put("cid", cid);
map.put("prover", prover);
if (NetUtil.isTestVersion()) {
key = "373275EB226022907CCA40BD2AE481D8";
} else {
key = "373275EB226022907CCA40BD2AE481D8";
}
CldSapReturn errRes = KSign.getGetParms(map, getHeadUrl()
+ "kgo/api/kgo_get_code.php", key);
return errRes;
}
public static void setKgoKey(String key) {
kgo_key = decodeKey(key);
Log.d(TAG, "kgo_key = " + kgo_key);
}
public static boolean isGetSign() {
if (!TextUtils.isEmpty(kgo_key))
return true;
return false;
}
static String decodeKey(String keyCode){
if (TextUtils.isEmpty(keyCode)) {
return "";
} else {
String key = keyCode.substring(keyCode.length() - 6);
String str = keyCode.substring(0, keyCode.length() - 6);
CldEDecrpy cldEDecrpy = new CldEDecrpy(str, key);
keyCode = cldEDecrpy.decrypt();
return keyCode;
}
}
/**
* 检测kgo_key,如果不存在,则获取kgo_key
*/
public static void checkKgoSign()
{
launcher_ver = CommonUtil.getVernameByPkgname("com.cld.launcher");
LogUtil.i(LogUtil.TAG, " launcher_ver: " + launcher_ver);
String result;
CldSapReturn request = null;
if (!KCloudNetUtils.isGetSign())
{
request = KCloudNetUtils.getKgoSign();
LogUtil.i(LogUtil.TAG, "kgosign url: " + request.url);
result = CldSapNetUtil.sapGetMethod(request.url);
LogUtil.i(LogUtil.TAG, "kgosign result: " + result);
if (result != null)
{
try
{
JSONObject object = new JSONObject(result);
if (object.getInt("errcode") == 0)
{
KCloudNetUtils.setKgoKey(object.getString("code"));
}
else
{
//Message message = handler.obtainMessage();
//message.what = CLDMessageId.MSG_ID_KGO_GETCODE_FAILED;
//handler.sendMessage(message);
return;
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
/**
* 获取推荐应用
* @param page
* @param size
* @param appInfoList
* @return
*/
public static CldSapReturn getNetApp(int page, int size,
ArrayList<AppInfo> appInfoList)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("umsaver", umsaver);
map.put("rscharset", rscharset);
map.put("rsformat", rsformat);
map.put("apiver", apiver);
map.put("cid", cid); //可以不要
map.put("prover", prover);//可以不要
map.put("encrypt", 0);
map.put("system_code", 1);
map.put("device_code", 1);
map.put("product_code", 2);
map.put("launcher_ver", launcher_ver);
map.put("width", width);
map.put("height", height);
map.put("page", page);
map.put("size", size);
//appInfoList不加入计算sign
String myMd5 = KSign.formatSource(map);
List<Map<String, Object>> apllist = new ArrayList<Map<String,Object>>();
Map<String, Object> mapApp = null;
for (AppInfo item : appInfoList)
{
mapApp = new HashMap<String, Object>();
mapApp.put("packname", item.getPkgName());
apllist.add(mapApp);
}
map.put("install_app", apllist);
CldSapReturn errRes = KSign.getPostParms(map, getHeadUrl()
+ "kgo/api/kgo_get_recommend_app.php", kgo_key, myMd5);
return errRes;
}
/**
* 获取升级应用
* @param page
* @param size
* @param appInfoList
* @return
*/
public static CldSapReturn getUpdateApp(int page, int size,
ArrayList<AppInfo> appInfoList, long duid, long kuid, int regionId)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("umsaver", umsaver);
map.put("rscharset", rscharset);
map.put("rsformat", rsformat);
map.put("apiver", apiver);
map.put("encrypt", 0);
map.put("page", page);
map.put("size", size);
map.put("area_code", regionId); //先定位,获取区域id
map.put("launcher_ver", launcher_ver);
map.put("cid", ConfigUtils.cid);
map.put("prover", ConfigUtils.appver);
map.put("system_code", ConfigUtils.system_code);
map.put("device_code", ConfigUtils.device_code);
map.put("product_code", ConfigUtils.product_code);
map.put("width", ConfigUtils.device_width);
map.put("height", ConfigUtils.device_height);
map.put("custom_code", ConfigUtils.custom_code);
map.put("duid", duid);
map.put("kuid", kuid);
/**
* 可配置测试
*/
if (!NetUtil.isTestVersion()){
map.put("system_ver", CommonUtil.getSystemVer()); //android系统版本
} else {
map.put("system_ver", ConfigUtils.system_ver); //android系统版本
}
map.put("plan_code", ConfigUtils.plan_code); //方案商编号
map.put("dpi", ConfigUtils.device_dpi); //设备分辨率
//appInfoList不加入计算sign
String myMd5 = KSign.formatSource(map);
List<Map<String, Object>> apllist = new ArrayList<Map<String,Object>>();
Map<String, Object> mapApp = null;
for (AppInfo item : appInfoList)
{
mapApp = new HashMap<String, Object>();
mapApp.put("packname", item.getPkgName());
mapApp.put("vercode", "" + item.getVerCode());
apllist.add(mapApp);
}
map.put("install_app", apllist);
CldSapReturn errRes = KSign.getPostParms(map, getHeadUrl()
+ "kgo/api/kgo_get_app_upgrade.php", kgo_key, myMd5);
return errRes;
}
/**
* 获取app状态
* @param appInfoList
* @return
*/
public static CldSapReturn getAppStatus(ArrayList<AppInfo> appInfoList)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("umsaver", umsaver);
map.put("rscharset", rscharset);
map.put("rsformat", rsformat);
map.put("apiver", apiver);
map.put("cid", cid); //可以不要
map.put("prover", prover);//可以不要
map.put("encrypt", 0);
//appInfoList不加入计算sign
String myMd5 = KSign.formatSource(map);
List<Map<String, Object>> apllist = new ArrayList<Map<String,Object>>();
Map<String, Object> mapApp = null;
for (AppInfo item : appInfoList)
{
mapApp = new HashMap<String, Object>();
mapApp.put("packname", item.getPkgName());
apllist.add(mapApp);
}
map.put("install_app", apllist);
CldSapReturn errRes = KSign.getPostParms(map, getHeadUrl()
+ "kgo/api/kgo_get_app_status.php", kgo_key, myMd5);
return errRes;
}
/**
* 获取app下载次数
* @param appInfo
* @return
*/
public static CldSapReturn getUpdateAppDownloadTime(AppInfo appInfo)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("umsaver", umsaver);
map.put("rscharset", rscharset);
map.put("rsformat", rsformat);
map.put("apiver", apiver);
map.put("cid", cid); //可以不要
map.put("prover", prover);//可以不要
map.put("encrypt", 0);
map.put("packname", appInfo.getPkgName());
map.put("vercode", appInfo.getVerCode());
CldSapReturn errRes = KSign.getGetParms(map, getHeadUrl()
+ "kgo/api/kgo_get_update_app_down_times.php", kgo_key);
return errRes;
}
/**
* 密钥加密 解密
*
* @author Zhouls
* @date 2014-8-13 下午4:05:06
*/
public static class CldEDecrpy {
/** The str. */
private String str;
/** The key box. */
private int[] keyBox;
/**
* Instantiates a new cld e decrpy.
*
* @param str
* the str
* @param key
* the key
*/
public CldEDecrpy(String str, String key) {
this.str = str;
keyBox = new int[3];
keyBox[0] = Integer.parseInt(key.substring(0, 2));
keyBox[1] = Integer.parseInt(key.substring(2, 4));
keyBox[2] = Integer.parseInt(key.substring(4, 6));
}
/**
* 加密
*
* @return char
* @author Zhouls
* @date 2014-8-13 下午5:13:26
*/
public String encrypt() {
String enStr = "";
int tempKey;
for (int i = 0; i < str.length(); i++) {
tempKey = keyBox[i % 3] % 24;
enStr = enStr
+ getChEncrpyt(getIndexEncrpyt(str.charAt(i)) + tempKey);
}
return enStr;
}
/**
* 解密
*
* @return char
* @author Zhouls
* @date 2014-8-13 下午5:00:18
*/
public String decrypt() {
String deStr = "";
int tempKey;
for (int i = 0; i < str.length(); i++) {
tempKey = keyBox[i % 3] % 24;
deStr += getChDecrpyt(getIndexDecrpyt(str.charAt(i)) - tempKey);
}
return deStr;
}
/**
* 获取加密字符
*
* @param i
* the i
* @return String
* @author Zhouls
* @date 2014-8-13 下午4:22:18
*/
private char getChEncrpyt(int i) {
if (i >= 0 && i <= 25) {
return chr(ord('a') + i);
} else if (i >= 26 && i <= 35) {
return chr(ord('0') + i - 26);
} else if (i >= 36 && i <= 61) {
return chr(ord('A') + i - 36);
}
return '0';
}
/**
* 获取解密字符
*
* @param i
* the i
* @return String
* @author Zhouls
* @date 2014-8-13 下午4:21:09
*/
private char getChDecrpyt(int i) {
if (i == 0) {
return '-';
} else if (i == 1) {
return ';';
} else if (i >= 2 && i <= 11) {
return chr(i + ord('0') - 2);
} else if (i >= 12 && i <= 37) {
return chr(i + ord('A') - 12);
}
return '0';
}
/**
* 获取加密索引
*
* @param c
* the c
* @return int
* @author Zhouls
* @date 2014-8-13 下午4:20:45
*/
private int getIndexDecrpyt(char c) {
if (ord(c) >= ord('0') && ord(c) <= ord('9')) {
return ord(c) + 26 - ord('0');
} else if (ord(c) >= ord('A') && ord(c) <= ord('Z')) {
return ord(c) + 36 - ord('A');
} else {
return ord(c) - ord('a');
}
}
/**
* 获取解密索引
*
* @param c
* the c
* @return int
* @author Zhouls
* @date 2014-8-13 下午4:22:13
*/
private int getIndexEncrpyt(char c) {
if (c == '-') {
return 0;
}
if (c == ';') {
return 1;
} else if (c >= '0' && c <= '9') {
return c - '0' + 2;
} else if (c >= 'A' && c <= 'Z') {
return c - 'A' + 12;
}
return 0;
}
/**
* int转char
*
* @param i
* the i
* @return char
* @author Zhouls
* @date 2014-8-13 下午4:31:41
*/
private char chr(int i) {
char c = (char) i;
return c;
}
/**
* char转int
*
* @param c
* the c
* @return int
* @author Zhouls
* @date 2014-8-13 下午4:29:52
*/
private int ord(char c) {
int a = c;
return a;
}
}
}
| true
|
9438f4f56e80862ff396dc0f53deb35e3500b94a
|
Java
|
CLee1207/Ecommence
|
/scc_ec/src/main/java/com/baosight/scc/ec/service/jpa/FavouriteShopServiceImpl.java
|
UTF-8
| 2,445
| 2.21875
| 2
|
[] |
no_license
|
package com.baosight.scc.ec.service.jpa;
import com.baosight.scc.ec.model.*;
import com.baosight.scc.ec.repository.FavouriteShopsRepository;
import com.baosight.scc.ec.service.FavouriteShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.*;
/**
* Created by zodiake on 2014/6/3.
*/
@Service
@Transactional
public class FavouriteShopServiceImpl implements FavouriteShopService {
@Autowired
private FavouriteShopsRepository repository;
@PersistenceContext
private EntityManager em;
@Override
public Page<FavouriteShops> findByUser(EcUser user, Pageable pageable) {
Page<FavouriteShops> page = repository.findByUser(user, pageable);
for (Iterator<FavouriteShops> i = page.iterator(); i.hasNext(); ) {
FavouriteShops favouriteShops = i.next();
Shop shop = favouriteShops.getShop();
EcUser u = shop.getUser();
TypedQuery<Item> query = em.createNamedQuery("item.findByUser", Item.class);
query.setParameter("user", u);
List<Item> items = query.setMaxResults(4).getResultList();
for (Item im : items) {
if (im instanceof Fabric) {
im.setUrl(Fabric.class.getName());
} else if (im instanceof Material) {
im.setUrl(Material.class.getName());
}
}
shop.setNewestItem(items);
}
return page;
}
@Override
public FavouriteShops save(EcUser user, Shop shop) {
FavouriteShops favouriteShops=new FavouriteShops();
favouriteShops.setShop(shop);
favouriteShops.setUser(user);
FavouriteShops source=repository.save(favouriteShops);
return source;
}
@Override
public boolean countByUserAndShop(EcUser user, Shop shop) {
return repository.countByUserAndShop(user,shop)>0;
}
@Override
public void delete(FavouriteShops favouriteShops) {
repository.delete(favouriteShops);
}
}
| true
|
dbb92686afa0e055d176b1dc4ce35f3a7f551097
|
Java
|
haobinaa/jvm-study
|
/src/main/java/com/haobin/jvmstudy/concurrent/AtomicLongT.java
|
UTF-8
| 424
| 2.65625
| 3
|
[] |
no_license
|
package com.haobin.jvmstudy.concurrent;
import java.util.concurrent.atomic.AtomicLong;
/**
* @Author HaoBin
* @Create 2020/3/13 17:34
* @Description: atomicLong/LongAdder
**/
public class AtomicLongT {
static AtomicLong atomicLong = new AtomicLong(1);
public static void main(String[] args) {
System.out.println(atomicLong.getAndIncrement());
System.out.println(atomicLong.get());
}
}
| true
|
0b69fb077eafeeb72862c01947fb8bcddf1adfef
|
Java
|
carlemil/ProjectEuler
|
/completed/Euler0055.java
|
UTF-8
| 2,471
| 3.34375
| 3
|
[] |
no_license
|
package completed;
import java.math.BigInteger;
import com.kjellstrand.euler.Tools;
//If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
//
//Not all numbers produce palindromes so quickly. For example,
//
//349 + 943 = 1292,
//1292 + 2921 = 4213
//4213 + 3124 = 7337
//
//That is, 349 took three iterations to arrive at a palindrome.
//
//Although no one has proved it yet, it is thought that some numbers,
//like 196, never produce a palindrome. A number that never forms a
//palindrome through the reverse and add process is called a Lychrel
//number. Due to the theoretical nature of these numbers, and for the
//purpose of this problem, we shall assume that a number is Lychrel
//until proven otherwise. In addition you are given that for every
//number below ten-thousand, it will either (i) become a palindrome in
//less than fifty iterations, or, (ii) no one, with all the computing
//power that exists, has managed so far to map it to a palindrome. In
//fact, 10677 is the first number to be shown to require over fifty
//iterations before producing a palindrome: 4668731596684224866951378664
//(53 iterations, 28-digits).
//
//Surprisingly, there are palindromic numbers that are themselves Lychrel
//numbers; the first example is 4994.
//
//How many Lychrel numbers are there below ten-thousand?
//
//NOTE: Wording was modified slightly on 24 April 2007 to emphasise the
//theoretical nature of Lychrel numbers.
public class Euler0055 {
public static void main(String[] args) {
long time = System.currentTimeMillis();
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
BigInteger t;
int c = 0;
boolean lychel = true;
for (int i = 0; i < 10000; i++) {
a = new BigInteger(String.valueOf(i));
b = Tools.reverseBigInt(a);
lychel = true;
int j = 0;
while (j++ < 50 && lychel) {
a = a.add(b);
t = Tools.reverseBigInt(a);
if (a.equals(t)) {
lychel = false;
break;
}
b = t;
}
if (lychel) {
c++;
}
}
System.out.println(c);
System.out.println("time: " + (System.currentTimeMillis() - time) + "ms");
}
}
| true
|
91bee1eaca6fc7d092fb27f0ca02b2bbff7806ab
|
Java
|
chenzhuo1791/simple-provider-user
|
/src/main/java/com/spring/dao/CyUserDao.java
|
UTF-8
| 285
| 1.890625
| 2
|
[] |
no_license
|
package com.spring.dao;
import com.spring.model.CyUser;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface CyUserDao {
@Select("SELECT * FROM cy_user cu WHERE cu.id = #{id}")
CyUser getUserById(Long id);
}
| true
|
25ab4ec4387928fa4dbe8a7fbb24b4b854da3212
|
Java
|
petermatts/Crypto-Research
|
/Java/src/crypto/SHA512.java
|
UTF-8
| 809
| 3.375
| 3
|
[] |
no_license
|
package crypto;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA512 {
public static String hash(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] arr = md.digest(input.getBytes());
BigInteger num = new BigInteger(1, arr);
String hash = num.toString(16);
while(hash.length() < 32)
hash = "0" + hash;
return hash.toUpperCase();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String hash_empty = hash("");
System.out.println(hash_empty);
String hash_helloworld = hash("Hello World");
System.out.println(hash_helloworld);
}
}
| true
|
70c7177d73dbcfe1182577d1a727b4d5d717ff65
|
Java
|
aleks232/invest-application
|
/src/main/java/com/edu/invest/domain/Orders.java
|
UTF-8
| 2,645
| 2.359375
| 2
|
[] |
no_license
|
package com.edu.invest.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
import java.time.Instant;
/**
* A Orders.
*/
@Entity
@Table(name = "orders")
public class Orders implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "start_date")
private Instant startDate;
@Column(name = "end_date")
private Instant endDate;
@Column(name = "price")
private Long price;
@ManyToOne
@JsonIgnoreProperties("orders")
private Lots lot;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Instant getStartDate() {
return startDate;
}
public Orders startDate(Instant startDate) {
this.startDate = startDate;
return this;
}
public void setStartDate(Instant startDate) {
this.startDate = startDate;
}
public Instant getEndDate() {
return endDate;
}
public Orders endDate(Instant endDate) {
this.endDate = endDate;
return this;
}
public void setEndDate(Instant endDate) {
this.endDate = endDate;
}
public Long getPrice() {
return price;
}
public Orders price(Long price) {
this.price = price;
return this;
}
public void setPrice(Long price) {
this.price = price;
}
public Lots getLot() {
return lot;
}
public Orders lot(Lots lots) {
this.lot = lots;
return this;
}
public void setLot(Lots lots) {
this.lot = lots;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Orders)) {
return false;
}
return id != null && id.equals(((Orders) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Orders{" +
"id=" + getId() +
", startDate='" + getStartDate() + "'" +
", endDate='" + getEndDate() + "'" +
", price=" + getPrice() +
"}";
}
}
| true
|
f436ebb5664528002800a36c4f16168d2dea64d0
|
Java
|
happyjianguo/yizhangtong
|
/sms-common/src/main/java/com/zb/sms/common/mns/MnsConsumerHandler.java
|
UTF-8
| 442
| 1.90625
| 2
|
[] |
no_license
|
package com.zb.sms.common.mns;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.model.Message;
/**
* 功能: MNS队列消息处理器
* 创建: liuchongguang - liuchongguang@zillionfortune.com
* 日期: 2016/12/19 0019 10:45
* 版本: V1.0
*/
public interface MnsConsumerHandler extends Runnable {
/**
* 处理MNS队列消息
*
* @param queue
* @param message
*/
void handle(CloudQueue queue, Message message);
}
| true
|
6249b4fbdb1c7b07ded59654c946f7d323473fd4
|
Java
|
leonliu06/thinkingInJava
|
/src/main/java/net/mrliuli/generics/TupleTest.java
|
UTF-8
| 218
| 2.140625
| 2
|
[] |
no_license
|
package net.mrliuli.generics;
public class TupleTest {
static TwoTuple<String, Integer> f(){
return Tuple.tuple("hi", 47);
}
static TwoTuple f2(){
return Tuple.tuple("hi", 47);
}
}
| true
|
3e24c3cb60a20ea65a103d2a7e59ea48a7a6bf7a
|
Java
|
jeromeCondere/Nostalgia
|
/src/utils/communication/message/Netlogo/NetlogoInputMessageChecker.java
|
UTF-8
| 853
| 2.078125
| 2
|
[] |
no_license
|
package utils.communication.message.Netlogo;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import NosException.CheckMessageException;
import jade.lang.acl.ACLMessage;
import utils.Netlogo.NetlogoJson;
import utils.communication.message.MessageChecker;
public class NetlogoInputMessageChecker implements MessageChecker {
@Override
public Object check(ACLMessage message,Object [] params) throws CheckMessageException {
JSONObject jsonObject=null;
JSONParser jsonParser = (JSONParser) params[0];
try {
jsonObject = (JSONObject) jsonParser.parse(message.getContent());
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new CheckMessageException("Json parse error.");
}
return jsonObject;//code for normal Json
}
}
| true
|
3481ef5beeb7ca5f3b95623070a6fab738898cad
|
Java
|
2757412961/MybatisSearch
|
/SCS_Search/src/main/java/cn/edu/zju/gislab/SCSServices/service/PredictionPaperService.java
|
UTF-8
| 1,319
| 2.125
| 2
|
[] |
no_license
|
package cn.edu.zju.gislab.SCSServices.service;
import com.alibaba.fastjson.JSONObject;
public interface PredictionPaperService {
/**
* 查询海区预报单条件:年、月、日、预报单名称
* @return
*/
public JSONObject getSeaAreaForecastConditon(String year, String month, String day);
/**
* 查询执法预报单条件:年、月、日、时,预报单名称
* @return
*/
public JSONObject getLawAreaForecastConditon(String year, String month, String day, String hour);
/**
* 查询台风预报单条件:台风编号、预报次数、发布时间
* @return
*/
public JSONObject getTyphoonForecastConditon(String num, String releaseNum, String releaseDate);
/**
* 查询热带低压预报单条件:台风编号、预报时间、发布时间
* @return
*/
public JSONObject getTropicsForecastConditon(String typhNum, String releaseNum, String releaseDate);
/**
* 未来十天预报单:年、月、日
* @return
*/
public JSONObject getNextTenDaysForecastConditon(String year, String month, String day);
/**
* 海冰预报单:年、编号、周期
* @return
*/
public JSONObject getSeaIceForecastConditon(String year, String iceNum, String cycle);
}
| true
|
ad0b474defd0b6a073a121e444320d2e1900fbd8
|
Java
|
carolinepanjaitan/BangunDatar
|
/Balok.java
|
UTF-8
| 2,356
| 2.96875
| 3
|
[] |
no_license
|
package com.bangundatar.interfes;
import java.util.Scanner;
public class Balok implements IBangunDatar {
int luas, volume, panjang, lebar, tinggi;
public Balok(int luas, int volume, int panjang, int lebar, int tinggi) {
this.luas = luas;
this.volume = volume;
this.panjang = panjang;
this.lebar = lebar;
this.tinggi = tinggi;
}
Balok() {
}
public int getLuas() {
return luas;
}
public void setLuas(int luas) {
this.luas = luas;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public int getPanjang() {
return panjang;
}
public void setPanjang(int panjang) {
this.panjang = panjang;
}
public int getLebar() {
return lebar;
}
public void setLebar(int lebar) {
this.lebar = lebar;
}
public int getTinggi() {
return tinggi;
}
public void setTinggi(int tinggi) {
this.tinggi = tinggi;
}
@Override
public void hitungLuas() {
System.out.println("Masukkan nilai panjang: ");
Scanner sc = new Scanner(System.in);
int panjang = sc.nextInt();
System.out.println("Masukkan nilai lebar: ");
Scanner sb = new Scanner(System.in);
int lebar = sb.nextInt();
System.out.println("Masukkan nilai tinggi: ");
Scanner sd = new Scanner(System.in);
int tinggi = sd.nextInt();
luas = 2 * ((panjang * lebar) + (panjang * tinggi) + (lebar * tinggi));
System.out.println("Luas Balok adalah " +luas);
}
@Override
public void hitungKeliling() {
}
@Override
public void volume() {
System.out.println("Masukkan nilai panjang: ");
Scanner sc = new Scanner(System.in);
int panjang = sc.nextInt();
System.out.println("Masukkan nilai lebar: ");
Scanner sb = new Scanner(System.in);
int lebar = sb.nextInt();
System.out.println("Masukkan nilai tinggi: ");
Scanner sd = new Scanner(System.in);
int tinggi = sd.nextInt();
volume = panjang * lebar * tinggi;
System.out.println("Volume Balok adalah " +volume);
}
}
| true
|
f19dc9b7bad724513077aadebdf169ad515f3f17
|
Java
|
decc/national-household-model-core-components
|
/core-projects/nhm-simulation-measures/src/test/java/uk/org/cse/nhm/simulation/measure/boilers/BiomassBoilerMeasureTest.java
|
UTF-8
| 4,923
| 1.882813
| 2
|
[] |
no_license
|
package uk.org.cse.nhm.simulation.measure.boilers;
import static org.mockito.Mockito.mock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Optional;
import uk.org.cse.commons.names.Name;
import uk.org.cse.nhm.NHMException;
import uk.org.cse.nhm.hom.emf.technologies.EmitterType;
import uk.org.cse.nhm.hom.emf.technologies.FuelType;
import uk.org.cse.nhm.hom.emf.technologies.ITechnologyModel;
import uk.org.cse.nhm.hom.emf.technologies.boilers.FlueType;
import uk.org.cse.nhm.hom.emf.technologies.boilers.IBoiler;
import uk.org.cse.nhm.hom.emf.technologies.impl.TechnologyModelImpl;
import uk.org.cse.nhm.hom.structure.StructureModel;
import uk.org.cse.nhm.hom.types.BuiltFormType;
import uk.org.cse.nhm.simulation.measure.util.Util;
import uk.org.cse.nhm.simulator.let.ILets;
import uk.org.cse.nhm.simulator.scope.IComponentsScope;
import uk.org.cse.nhm.simulator.scope.ISettableComponentsScope;
import uk.org.cse.nhm.simulator.state.dimensions.energy.IPowerTable;
import uk.org.cse.nhm.simulator.state.functions.IComponentsFunction;
import uk.org.cse.nhm.simulator.state.functions.impl.ConstantComponentsFunction;
/**
* Make a house case with or without the various conditions which needs to be good for the measures
* @param enoughExternalSpace if true has enough external space
* @param isNotFlat if true it's not a flat
* @param enoughFloorArea if true, there is enough floor area
* @return
* @throws NHMException
*/
public class BiomassBoilerMeasureTest extends AbstractGasBoilerMeasureTest {
private StandardBoilerMeasure measure;
private final float minimumExternalSpace = 1f;
private final float minimumFloorArea = 1f;
private final IComponentsFunction<Number> efficiency =
ConstantComponentsFunction.<Number>of(Name.of("Test eff"), 0.8d)
;
private final IComponentsFunction<Number> cylinderVolume = ConstantComponentsFunction.<Number>of(Name.of("Test vol"), 110f);
private final float cylinderInsulationThickness = 50f;
@Before
public void initalize() {
measure = new StandardBoilerMeasure(
dims.time,
Util.mockWetHeatingMeasureFactory(),
dims.technology,
dims.structure,
operations,
FuelType.BIOMASS_PELLETS,
Util.mockSizingFunction(Optional.of(1000d)),
Util.mockCapexFunction(1000d, 2000d),
Util.mockOpexFunction(1000d, 2000d, 3000d),
ConstantComponentsFunction.<Number>of(Name.of("Test"), 0d),
efficiency,
efficiency,
cylinderVolume,
cylinderInsulationThickness,
minimumFloorArea,
minimumExternalSpace);
}
@Test
public void testSuitability() throws NHMException {
final boolean[] tf = new boolean[] {false, true};
for (final boolean espace : tf) {
for (final boolean notFlat : tf) {
for (final boolean ispace : tf) {
final IComponentsScope hc = makeHouseCase(espace, notFlat, ispace);
Assert.assertEquals(
String.format("external space: %s, not a flat : %s, internal space: %s",
espace, notFlat, ispace),
espace && notFlat && ispace,
measure.isSuitable(hc, ILets.EMPTY));
}
}
}
}
/**
* Make a house case with or without the various conditions which needs to be good for the measures
* @param enoughExternalSpace if true has enough external space
* @param isNotFlat if true it's not a flat
* @param enoughFloorArea if true, there is enough floor area
* @return
* @throws NHMException
*/
private ISettableComponentsScope makeHouseCase(final boolean enoughExternalSpace, final boolean isNotFlat, final boolean enoughFloorArea) throws NHMException {
final StructureModel structure = new StructureModel(isNotFlat ? BuiltFormType.Detached : BuiltFormType.PurposeBuiltHighRiseFlat) {
{
setBackPlotDepth(1.0);
setBackPlotWidth(enoughExternalSpace ? minimumExternalSpace : minimumExternalSpace - 1);
setFrontPlotDepth(1.0);
setFrontPlotWidth(enoughExternalSpace ? minimumExternalSpace : minimumExternalSpace - 1);
}
@Override
public double getFloorArea() {
return enoughFloorArea ? minimumFloorArea : minimumFloorArea-1;
}
};
final ITechnologyModel technologies = new TechnologyModelImpl() {
};
return Util.mockComponents(dims, structure, technologies, mock(IPowerTable.class));
}
@Test
public void testBasicInstallation() throws NHMException {
final ISettableComponentsScope input = makeHouseCase(true, true, true);
final ITechnologyModel output = Util.applyAndGetTech(dims, measure, input);
assertBoilerBasics(output, 0.8, FuelType.BIOMASS_PELLETS, EmitterType.RADIATORS, false, 1983, cylinderInsulationThickness, cylinderVolume.compute(null, null).doubleValue());
final IBoiler boiler = (IBoiler)output.getIndividualHeatSource();
Assert.assertEquals(FlueType.FAN_ASSISTED_BALANCED_FLUE, boiler.getFlueType());
Assert.assertEquals(3000d, boiler.getAnnualOperationalCost(), 0d);
}
}
| true
|
ec6f89b575613b46e621c58fb66cd032d204b69d
|
Java
|
FanHuaRan/MusicStore-Spring
|
/MusicStoreRest/src/com/fhr/musicstorerest/daos/GenreDAO.java
|
UTF-8
| 1,271
| 2.28125
| 2
|
[] |
no_license
|
package com.fhr.musicstorerest.daos;
import java.util.List;
import java.util.Set;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.fhr.musicstorerest.models.Genre;
/**
*
* @author fhr
*
*/
@Repository
public class GenreDAO extends HibernateBaseDao<Genre> {
private static final Logger log = LoggerFactory.getLogger(GenreDAO.class);
// property constants
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
@Autowired
public GenreDAO(SessionFactory sessionFactory){
super();
this.setSessionFactory(sessionFactory);
}
protected void initDao() {
// do nothing
}
public List findByName(Object name) {
return findByProperty(NAME, name);
}
public List findByDescription(Object description) {
return findByProperty(DESCRIPTION, description);
}
public static GenreDAO getFromApplicationContext(ApplicationContext ctx) {
return (GenreDAO) ctx.getBean("GenreDAO");
}
}
| true
|
286925b906eebd1387fe112a04fab95caa48d5f4
|
Java
|
vishalyadav1/Wedding-Bingo
|
/src/main/java/com/example/my/weddingbingo/Mehndi.java
|
UTF-8
| 1,753
| 1.898438
| 2
|
[] |
no_license
|
package com.example.my.weddingbingo;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class Mehndi extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mehndi);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
startActivity(new Intent(Mehndi.this, Welcome.class));
// mTextMessage.setText(R.string.title_home);
break;
case R.id.ic_dashboard:
Intent intent = new Intent(Mehndi.this, Feedback.class);
startActivity(intent);
// mTextMessage.setText(R.string.title_feedback);
break;
case R.id.ic_notifications:
Intent intent1 = new Intent(Mehndi.this, About.class);
startActivity(intent1);
// mTextMessage.setText(R.string.title_about_us);
break;
}
return false;
}
});
}
}
| true
|
c5200538c8b67825ee25ac4c0d4902c0f2e2822f
|
Java
|
momokys/news
|
/src/cn/momoky/news/domain/NewsType.java
|
UTF-8
| 965
| 2.3125
| 2
|
[] |
no_license
|
package cn.momoky.news.domain;
/**
* @ClassName NewsType
* @Description TODO
* @Author 钟智峰
* @Date 2020/10/10 16:07
* @Version 1.0
*/
public class NewsType {
private Integer typeid;
private String typename;
private String remark;
public NewsType() {
}
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "NewsType{" +
"typeid=" + typeid +
", typename='" + typename + '\'' +
", remark='" + remark + '\'' +
'}';
}
}
| true
|
70e5bfe8f5d5725b03172c330872bb07bb507034
|
Java
|
axoneuk/devintest
|
/M1 - FlowControl & Arrays/src/com/axone/devintest/arrays/Employee.java
|
UTF-8
| 375
| 3
| 3
|
[] |
no_license
|
package com.axone.devintest.arrays;
public class Employee {
int empID;
String empName;
int empAge;
int holidays;
private int salary;
/**
*
* Some javadoc comments
*/
public Employee(){
System.out.println("Constrcutor");
}
public String getEmpName(){
return empName;
}
private void doSomething(){
System.out.println("doing something");
}
}
| true
|
e1ae5322400344330ae65b904f3dae5d1ecfbe6f
|
Java
|
jacsonsantos/parcial-poo-ii
|
/src/repository/QuartoRepository.java
|
UTF-8
| 4,040
| 2.546875
| 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 repository;
import database.ConexaoDB;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import model.Quarto;
/**
*
* @author jacson
*/
public class QuartoRepository {
ConexaoDB cone = new ConexaoDB();
//Quarto quarto = new Quarto();
public void salvar(Quarto quarto) {
cone.conectar();
try {
PreparedStatement ps = cone.con.prepareStatement("INSERT INTO "
+ "quarto (nome, numero, categoria, status) VALUES(?,?,?,?)");
ps.setString(1, quarto.getNome());
ps.setInt(2, quarto.getNumero());
ps.setInt(3, quarto.getCategoria());
ps.setInt(4, quarto.getStatus());
ps.execute();
JOptionPane.showMessageDialog(null, "Quarto Salvo!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao salvar Quarto!");
}
cone.desconectarConexao();
}
public void editar(Quarto quarto) {
cone.conectar();
try {
PreparedStatement ps = cone.con.prepareStatement("UPDATE quarto "
+ "SET nome = ?, numero = ?, categoria = ?, status = ? WHERE id = ?");
ps.setString(1, quarto.getNome());
ps.setInt(2, quarto.getNumero());
ps.setInt(3, quarto.getCategoria());
ps.setInt(4, quarto.getStatus());
ps.setInt(5, quarto.getId());
ps.execute();
JOptionPane.showMessageDialog(null, "Quarto Atualizado!");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Erro ao atualizar Quarto!");
}
cone.desconectarConexao();
}
public void deletar(Quarto quarto) {
cone.conectar();
try {
PreparedStatement ps = cone.con.prepareStatement("DELETE FROM quarto WHERE id = ?");
ps.setInt(1, quarto.getId());
ps.execute();
JOptionPane.showMessageDialog(null, "Quarto Deletado!");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Erro ao deletar Quarto!");
}
cone.desconectarConexao();
}
public Quarto buscar(Quarto quarto) {
cone.conectar();
cone.executeSql("SELECT * FROM quarto WHERE nome like '%"+ quarto.getPesquisa() +"%'");
try{
cone.rs.first();
quarto.setNome( cone.rs.getString("nome") );
quarto.setNumero(Integer.valueOf(cone.rs.getInt("numero")) );
quarto.setCategoria(Integer.valueOf(cone.rs.getInt("categoria")) );
quarto.setStatus(Integer.valueOf(cone.rs.getInt("status")) );
quarto.setId(Integer.valueOf(cone.rs.getInt("id")));
} catch(SQLException exception) {
JOptionPane.showMessageDialog(null, "Quarto não encontrado!");
}
cone.desconectarConexao();
return quarto;
}
public Quarto buscar(int id) {
cone.conectar();
Quarto quarto = new Quarto();
cone.executeSql("SELECT * FROM quarto WHERE id = "+ id);
try{
cone.rs.first();
quarto.setNome( cone.rs.getString("nome") );
quarto.setNumero(Integer.valueOf(cone.rs.getInt("numero")) );
quarto.setCategoria(Integer.valueOf(cone.rs.getInt("categoria")) );
quarto.setStatus(Integer.valueOf(cone.rs.getInt("status")) );
quarto.setId(Integer.valueOf(cone.rs.getInt("id")));
} catch(SQLException exception) {
JOptionPane.showMessageDialog(null, "Quarto não encontrado!");
}
cone.desconectarConexao();
return quarto;
}
}
| true
|
62e49f3c898ad4ffb60f1be0e6960fb920c5b7fb
|
Java
|
cherkavi/java-code-example
|
/parser-e-shop/deprecated/src/html_parser/page/PageWalkerAware.java
|
WINDOWS-1251
| 824
| 2.65625
| 3
|
[] |
no_license
|
package html_parser.page;
/** , "" , */
public abstract class PageWalkerAware {
/** ,
* @param number - ,
* @return
*/
public abstract String getUrl(int number);
/** Url
* @param baseHref - URL
* */
public abstract void reset(String baseHref);
}
| true
|
cbf8aaeffcd42f126fe6ec550c5fd5ee1197e66c
|
Java
|
darrenlu666/DragSlideLayout
|
/app/src/main/java/com/ldh/android/dragslidelayout/DragLayout.java
|
UTF-8
| 14,944
| 2.265625
| 2
|
[] |
no_license
|
package com.ldh.android.dragslidelayout;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
/**
* Created by ldh on 2017/12/25.
*/
public class DragLayout extends RelativeLayout {
private static final String TAG = "DragLayout";
public static final long TIME_TITLE_SHOW_HIDE = 300;//标题栏隐藏和显示动画时间
private ViewDragHelper mViewDragHelper;
private View mDragView;
public static final String POS_MOVING = "POS_MOVING";
public static final String POS_LEFT_TOP = "POS_LEFT_TOP";
public static final String POS_RIGHT_TOP = "POS_RIGHT_TOP";
public static final String POS_LEFT_BOTTOM = "POS_LEFT_BOTTOM";
public static final String POS_RIGHT_BOTTOM = "POS_RIGHT_BOTTOM";
public static final String POS_LEFT_TOP_MARGIN_TITLE = "POS_LEFT_TOP_MARGIN_TITLE";
public static final String POS_RIGHT_TOP_MARGIN_TITLE = "POS_RIGHT_TOP_MARGIN_TITLE";
private String mCurrentPos = POS_LEFT_TOP_MARGIN_TITLE;
private int mCurrentLeft;
private int mCurrentTop;
private int mCenterX;
private int mCenterY;
private int mWidth;
private int mHeight;
private View mTitleView;//标题栏
private boolean isTitleShow = true;
private boolean isClickable;//若设置为true,可允许该viewGroup拦截点击事件。默认为false
public DragLayout(Context context) {
this(context, null);
}
public DragLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DragLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mViewDragHelper = ViewDragHelper.create(this, 1f, new ViewDragCallBack());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mCenterX = w / 2;
mCenterY = h / 2;
mWidth = w;
mHeight = h;
}
public static class DragLayoutBuilder{
private Context mContext;
private View mDragView;
private View mTitleView;
private boolean isClickable;
private DragLayout mDragLayout;
public DragLayoutBuilder(Context context,DragLayout dragLayout) {
mContext = context;
mDragLayout = dragLayout;
}
public DragLayout getDragLayout() {
return mDragLayout;
}
public DragLayoutBuilder setDragView(View view) {
mDragView = view;
return this;
}
public DragLayoutBuilder setViewBelowTitle(View view) {
mTitleView = view;
return this;
}
public DragLayoutBuilder setBlankZoneClickable(boolean isClickable) {
this.isClickable = isClickable;
return this;
}
public DragLayoutBuilder build(){
mDragLayout.setDragView(mDragView);
mDragLayout.setViewBelowTitle(mTitleView);
mDragLayout.setBlankZoneClickable(isClickable);
return this;
}
}
private void setDragedViewPos(String currentPos){
mCurrentPos = currentPos;
}
private void setDragView(@NonNull View view) {
mDragView = view;
}
public void setViewToTop(View view) {//标题隐藏了
if(mDragView == null)
throw new IllegalStateException("have not setDragView");
mTitleView = view;
isTitleShow = false;
if (POS_LEFT_TOP_MARGIN_TITLE.equals(mCurrentPos)) {
mCurrentPos = POS_LEFT_TOP;
mCurrentLeft = mDragView.getLeft();
mCurrentTop = mDragView.getTop();
setTranslate(mCurrentPos);
} else if (POS_RIGHT_TOP_MARGIN_TITLE.equals(mCurrentPos)) {
mCurrentPos = POS_RIGHT_TOP;
mCurrentLeft = mDragView.getLeft();
mCurrentTop = mDragView.getTop();
setTranslate(mCurrentPos);
}
}
public void setViewBelowTitle(View view) {//标题显示了
if(mDragView == null)
throw new IllegalStateException("have not setDragView");
mTitleView = view;
isTitleShow = true;
if (POS_LEFT_TOP.equals(mCurrentPos)) {
mCurrentLeft = mDragView.getLeft();
mCurrentTop = mDragView.getTop();
mCurrentPos = POS_LEFT_TOP_MARGIN_TITLE;
setTranslate(mCurrentPos);
} else if (POS_RIGHT_TOP.equals(mCurrentPos)) {
mCurrentLeft = mDragView.getLeft();
mCurrentTop = mDragView.getTop();
mCurrentPos = POS_RIGHT_TOP_MARGIN_TITLE;
setTranslate(mCurrentPos);
}
}
private void setBlankZoneClickable(boolean isClickable) {
this.isClickable = isClickable;
}
private class ViewDragCallBack extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return mDragView == child;
}
/**
* 处理水平方向上的拖动
*
* @param child 拖动的View
* @param left 移动到x轴的距离
* @param dx 建议的移动的x距离
*/
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
//两个if主要是让view在ViewGroup中
if (left < getPaddingLeft()) {
mCurrentLeft = getPaddingLeft();
return mCurrentLeft;
}
if (left > getWidth() - child.getMeasuredWidth() - getPaddingRight()) {
mCurrentLeft = getWidth() - child.getMeasuredWidth() - getPaddingRight();
return mCurrentLeft;
}
mCurrentLeft = left;
return left;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
//两个if主要是让view在ViewGroup中
if (top < getPaddingTop()) {
mCurrentTop = getPaddingTop();
return mCurrentTop;
}
if (top > getHeight() - child.getMeasuredHeight() - getPaddingBottom()) {
mCurrentTop = getHeight() - child.getMeasuredHeight() - getPaddingBottom();
return mCurrentTop;
}
mCurrentTop = top;
return top;
}
@Override
public void onViewDragStateChanged(int state) {
switch (state) {
case ViewDragHelper.STATE_DRAGGING://正在拖动过程中
mCurrentPos = POS_MOVING;
break;
case ViewDragHelper.STATE_IDLE://view没有被拖动,或者正在进行fling
if (mCurrentLeft + mDragView.getMeasuredWidth() / 2 <= mCenterX & mCurrentTop + mDragView.getMeasuredHeight() / 2 <= mCenterY) {//左上角
mCurrentPos = isTitleShow ? POS_LEFT_TOP_MARGIN_TITLE : POS_LEFT_TOP;
} else if (mCurrentLeft + mDragView.getMeasuredWidth() / 2 >= mCenterX & mCurrentTop + mDragView.getMeasuredHeight() / 2 <= mCenterY) {//右上角
mCurrentPos = isTitleShow ? POS_RIGHT_TOP_MARGIN_TITLE : POS_RIGHT_TOP;
} else if (mCurrentLeft + mDragView.getMeasuredWidth() / 2 <= mCenterX & mCurrentTop + mDragView.getMeasuredHeight() / 2 >= mCenterY) {//左下角
mCurrentPos = POS_LEFT_BOTTOM;
} else if (mCurrentLeft + mDragView.getMeasuredWidth() / 2 >= mCenterX & mCurrentTop + mDragView.getMeasuredHeight() / 2 >= mCenterY) {//右下角
mCurrentPos = POS_RIGHT_BOTTOM;
} else {//右上角
mCurrentPos = POS_RIGHT_TOP;
}
setTranslate(mCurrentPos);
break;
case ViewDragHelper.STATE_SETTLING://fling完毕后被放置到一个位置
break;
}
super.onViewDragStateChanged(state);
}
@Override
public int getViewHorizontalDragRange(View child) {
return getMeasuredWidth() - child.getMeasuredWidth();
}
@Override
public int getViewVerticalDragRange(View child) {
return getMeasuredHeight() - child.getMeasuredHeight();
}
}
private float dx = 0f;
private float dy = 0f;
private void setTranslate(final String posStyle) {
switch (posStyle) {
case POS_LEFT_TOP:
dx = -mCurrentLeft;
dy = -mCurrentTop;
break;
case POS_RIGHT_TOP:
dx = mWidth - mCurrentLeft - mDragView.getMeasuredWidth();
dy = -mCurrentTop;
break;
case POS_LEFT_BOTTOM:
dx = -mCurrentLeft;
dy = mHeight - mCurrentTop - mDragView.getMeasuredHeight();
break;
case POS_RIGHT_BOTTOM:
dx = mWidth - mCurrentLeft - mDragView.getMeasuredWidth();
dy = mHeight - mCurrentTop - mDragView.getMeasuredHeight();
break;
case POS_LEFT_TOP_MARGIN_TITLE:
dx = -mCurrentLeft;
dy = -mCurrentTop + (mTitleView == null ? 0 : mTitleView.getMeasuredHeight());
break;
case POS_RIGHT_TOP_MARGIN_TITLE:
dx = mWidth - mCurrentLeft - mDragView.getMeasuredWidth();
dy = -mCurrentTop + (mTitleView == null ? 0 : mTitleView.getMeasuredHeight());
break;
}
TranslateAnimation mTranslateAnimation = new TranslateAnimation(0, dx, 0, dy);
mTranslateAnimation.setDuration(TIME_TITLE_SHOW_HIDE);
mTranslateAnimation.setFillAfter(true);
mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mDragView.clearAnimation();
LayoutParams params = (LayoutParams) mDragView.getLayoutParams();
removeRule(params);
params.setMargins(0, 0, 0, 0);
switch (posStyle) {
case POS_LEFT_TOP:
//mDragView.layout(0, 0, mDragView.getMeasuredWidth(), mDragView.getMeasuredHeight());
//params.setMargins(0,0,mWidth - mDragView.getMeasuredWidth() ,mHeight - mDragView.getMeasuredHeight());
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
break;
case POS_RIGHT_TOP:
//mDragView.layout(mWidth - mDragView.getMeasuredWidth(), 0, mWidth, mDragView.getMeasuredHeight());
//params.setMargins(mWidth - mDragView.getMeasuredWidth() ,0,0,mHeight - mDragView.getMeasuredHeight());
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
break;
case POS_LEFT_BOTTOM:
//mDragView.layout(0, mHeight - mDragView.getMeasuredHeight(), mDragView.getMeasuredWidth(), mHeight);
//params.setMargins(0,mHeight - mDragView.getMeasuredHeight(),mWidth - mDragView.getMeasuredWidth(),0);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
break;
case POS_RIGHT_BOTTOM:
//mDragView.layout(mWidth - mDragView.getMeasuredWidth(), mHeight - mDragView.getMeasuredHeight(), mWidth, mHeight);
//params.setMargins(mWidth - mDragView.getMeasuredWidth(),mHeight - mDragView.getMeasuredHeight(),0,0);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
break;
case POS_LEFT_TOP_MARGIN_TITLE:
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.setMargins(0, mTitleView == null ? 0 : mTitleView.getMeasuredHeight(), 0, 0);
break;
case POS_RIGHT_TOP_MARGIN_TITLE:
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.setMargins(0, mTitleView == null ? 0 : mTitleView.getMeasuredHeight(), 0, 0);
break;
}
mDragView.setLayoutParams(params);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mDragView.startAnimation(mTranslateAnimation);
}
private void removeRule(LayoutParams params) {
params.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mViewDragHelper.cancel();
break;
}
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && isClickable)
if (mOnDragLayoutClickListener != null) {
mOnDragLayoutClickListener.layoutClick();
}
mViewDragHelper.processTouchEvent(event);
return true;
}
@Override
public boolean isInEditMode() {
return true;
}
public interface OnDragLayoutClickListener {//点击可移动的view之外的区域
void layoutClick();
}
private OnDragLayoutClickListener mOnDragLayoutClickListener;
public void setOnDragLayoutClickListener(OnDragLayoutClickListener listener) {
mOnDragLayoutClickListener = listener;
}
}
| true
|
f93684415339aac2f1945e4c86fc968e0c3ede25
|
Java
|
ClawHub/ClawDataSource
|
/src/pool/ClawDataSource.java
|
UTF-8
| 7,157
| 2.796875
| 3
|
[] |
no_license
|
package pool;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;
import javax.sql.DataSource;
/**
* <Description>自定义数据库连接池<br>
*
* @author clawhub<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2019-02-25 10:33 <br>
*/
public class ClawDataSource implements DataSource {
/**
* The PrintWriter to which log messages should be directed.
*/
private PrintWriter logWriter = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
/**
* 队列,用于存储连接
*/
private LinkedBlockingQueue<Connection> holder;
/**
* 参数
*/
private PoolConfig poolConfig;
/**
* The Jdbc url.
*/
private String jdbcUrl;
/**
* The Connect properties.
*/
private Properties connectProperties;
/**
* The Username.
*/
private String username;
/**
* The Password.
*/
private String password;
/**
* The Driver.
*/
private Driver driver;
/**
* Pool config my data source.
*
* @param poolConfig the pool config
* @return the my data source
*/
public ClawDataSource poolConfig(PoolConfig poolConfig) {
this.poolConfig = poolConfig;
//初始化连接数小于最大连接数
if (poolConfig.getInitialSize() > poolConfig.getMaxActive()) {
poolConfig.initialSize(poolConfig.getMaxActive());
}
return this;
}
/**
* Username my data source.
*
* @param username the username
* @return the my data source
*/
public ClawDataSource username(String username) {
this.username = username;
return this;
}
/**
* Password my data source.
*
* @param password the password
* @return the my data source
*/
public ClawDataSource password(String password) {
this.password = password;
return this;
}
/**
* Jdbc url my data source.
*
* @param jdbcUrl the jdbc url
* @return the my data source
*/
public ClawDataSource jdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
return this;
}
/**
* Build my data source.
*
* @return the my data source
*/
public ClawDataSource build() {
//组装参数
connectProperties = new Properties();
connectProperties.put("user", username);
connectProperties.put("password", password);
//如果最大连接数是负数,则不限制线程池大小
if (poolConfig.getMaxActive() < 0) {
holder = new LinkedBlockingQueue<>();
} else {
//设置连接池最大值=最大活跃连接数
holder = new LinkedBlockingQueue<>(poolConfig.getMaxActive());
}
//初始化连接池
try {
init();
} catch (SQLException e) {
e.printStackTrace();
}
return this;
}
/**
* 初始化连接池
*
* @throws SQLException the sql exception
*/
private void init() throws SQLException {
//获取驱动名称
String driverClass = DriverUtil.getDriverClassName(jdbcUrl);
//获取驱动
driver = DriverUtil.createDriver(null, driverClass);
//初始化连接
for (int i = 0; i < poolConfig.getInitialSize(); ++i) {
//创建连接
Connection connection = createConnection();
//加到连接池
holder.offer(connection);
}
}
/**
* 创建连接
*
* @return the connection
* @throws SQLException the sql exception
*/
private Connection createConnection() throws SQLException {
return driver.connect(jdbcUrl, connectProperties);
}
@Override
public Connection getConnection() throws SQLException {
//连接
Connection connection = holder.poll();
System.out.println("getConnection:" + connection);
//如果获取的连接为空,则证明当前连接数量达到最大值
if (connection == null) {
// 当池消耗殆尽且消耗的策略,默认策略1
// * 0:WHEN_EXHAUSTED_FAIL
// * 1:WHEN_EXHAUSTED_BLOCK
// * 2:WHEN_EXHAUSTED_GROW
int strategy = poolConfig.getWhenExhaustedStrategy();
System.out.println("strategy:" + strategy);
//根据策略处理连接
if (strategy == PoolConstant.WHEN_EXHAUSTED_FAIL) {
//返回异常
throw new SQLException("WHEN_EXHAUSTED_FAIL");
} else if (strategy == PoolConstant.WHEN_EXHAUSTED_BLOCK) {
//阻塞到最长等待时间
long expectGetTime = System.nanoTime() + poolConfig.getMaxWaitMillis();
while (expectGetTime < System.nanoTime()) {
//从连接池中获取连接
connection = holder.poll();
//如果获取到连接
if (connection != null) {
//返回此连接
return connection;
}
}
} else if (strategy == PoolConstant.WHEN_EXHAUSTED_GROW) {
//新创建一个连接
return createConnection();
} else {
throw new SQLException("不支持的策略");
}
}
//返回连接对象
return connection;
}
/**
* Free connection.
*
* @param connection the connection
*/
public void freeConnection(Connection connection) {
//加入连接池,如果超过最大连接数,直接扔掉
holder.offer(connection);
}
@Override
public Connection getConnection(String username, String password) {
throw new UnsupportedOperationException("Not supported by DataSource");
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("BasicDataSource is not a wrapper.");
}
@Override
public boolean isWrapperFor(Class<?> iface) {
return false;
}
@Override
public PrintWriter getLogWriter() {
return logWriter;
}
@Override
public void setLogWriter(PrintWriter out) {
logWriter = out;
}
@Override
public void setLoginTimeout(int seconds) {
throw new UnsupportedOperationException("Not supported by BasicDataSource");
}
@Override
public int getLoginTimeout() {
throw new UnsupportedOperationException("Not supported by BasicDataSource");
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
}
| true
|
6d5b5e3bf65a4f4fb6189c027829589da897f34e
|
Java
|
NaMaG/GeoPharma_faces-config
|
/target/generated-sources/annotations/com/deenech/gest_el_act/Entities/Activite_.java
|
UTF-8
| 541
| 1.585938
| 2
|
[] |
no_license
|
package com.deenech.gest_el_act.Entities;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2019-04-11T14:45:55")
@StaticMetamodel(Activite.class)
public class Activite_ {
public static volatile SingularAttribute<Activite, Long> idAct;
public static volatile SingularAttribute<Activite, String> libelle;
public static volatile SingularAttribute<Activite, Boolean> supprime;
}
| true
|
18f552c24477540965145f863cc18e411a9979cb
|
Java
|
vrqin/taxi
|
/ectaxi/src/main/java/com/spring/jersy/hibernate/model/service/PassenIntegrityService.java
|
UTF-8
| 578
| 1.835938
| 2
|
[] |
no_license
|
package com.spring.jersy.hibernate.model.service;
import com.spring.jersy.hibernate.model.entity.PassenIntegrity;
import com.spring.jersy.hibernate.publics.util.PageList;
/**
* Created by Administrator on 2016/9/10.
*/
public interface PassenIntegrityService {
public PageList findList(int page, int rows, String sort, String order, String key, Integer isblacklist, String begintime, String endtime, Integer clientid) throws Exception;
public PassenIntegrity findPassenIntegrityByPhone(String phone);
public void saveOrUpd(PassenIntegrity passenIntegrity);
}
| true
|
de70529f03d5a8b1576e7bf5622f57bb1747dcf8
|
Java
|
Gregory664/test_junit
|
/src/test/java/TestClass.java
|
UTF-8
| 215
| 1.679688
| 2
|
[] |
no_license
|
import org.junit.Test;
import org.junit.*;
import static org.junit.Assert.assertEquals;
public class TestClass {
@Test
public void TestHello() {
assertEquals("Hello", Solution.Hello());
}
}
| true
|
84bef37fec2c0f96c3e990ff88948044068a94b4
|
Java
|
SjoerdvanderHeijden/endless-ql
|
/JS/qlparser/src/main/java/nl/uva/js/qlparser/wrappers/arithmetic/CalculatableMoney.java
|
UTF-8
| 1,181
| 2.734375
| 3
|
[] |
no_license
|
package nl.uva.js.qlparser.wrappers.arithmetic;
import com.fasterxml.jackson.annotation.JsonValue;
import org.joda.money.Money;
import java.math.RoundingMode;
public class CalculatableMoney extends Calculatable<Money> {
private CalculatableMoney(Money value) {
super(value);
}
public CalculatableMoney(String value) {
super(Money.parse(value));
}
@Override
public Calculatable<Money> plus(Calculatable<Money> other) {
return new CalculatableMoney(this.get().plus(other.get()));
}
@Override
public Calculatable<Money> min(Calculatable<Money> other) {
return new CalculatableMoney(this.get().minus(other.get()));
}
@Override
public Calculatable<Money> mult(Calculatable<Money> other) {
return new CalculatableMoney(this.get().multipliedBy(other.get().getAmount(), RoundingMode.HALF_UP));
}
@Override
public Calculatable<Money> div(Calculatable<Money> other) {
return new CalculatableMoney(this.get().dividedBy(other.get().getAmount(), RoundingMode.HALF_UP));
}
@Override
@JsonValue
public String toString() {
return super.toString();
}
}
| true
|
e1a144e60d4c953ca38954505776d6161289705f
|
Java
|
jkxyx205/project
|
/project-admin/src/main/java/com/rick/project/admin/auth/repository/UserRepository.java
|
UTF-8
| 513
| 1.90625
| 2
|
[] |
no_license
|
package com.rick.project.admin.auth.repository;
import com.rick.project.admin.auth.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* All rights Reserved, Designed By www.xhope.top
*
* @version V1.0
* @Description: (用一句话描述该文件做什么)
* @author: Rick.Xu
* @date: 12/19/19 2:22 PM
* @Copyright: 2019 www.yodean.com. All rights reserved.
*/
public interface UserRepository extends JpaRepository<User, String> {
User findByUsername(String username);
}
| true
|
a5f9908e0d5e11d6d07181694d4865ad8bd99d1b
|
Java
|
lxykad/VideoPlayer
|
/app/src/main/java/com/lxy/livedata/di/scope/ActivityScope.java
|
UTF-8
| 359
| 1.882813
| 2
|
[] |
no_license
|
package com.lxy.livedata.di.scope;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
/**
*
* @author a
* @date 2018/1/19
*
* 自定义scope实现全局单例
* singleTon 只在某一个类里是单例
*/
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}
| true
|
49c55b5926030e1ea03b71c49083f16fbbf58960
|
Java
|
VladPalamarchuk/SVCalendarAndroidStudio
|
/app/src/main/java/com/example/calendar/CheckEmail.java
|
UTF-8
| 510
| 2.53125
| 3
|
[] |
no_license
|
package com.example.calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckEmail {
public static final Pattern pattern = Pattern
.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
public static boolean Check(String word) {
Matcher matcher = pattern.matcher(word);
if (matcher.matches())
return true;
else
return false;
}
}
| true
|
dde7d39e390406b29f90a86c62700e4388b4ee97
|
Java
|
johnnywong233/test
|
/demo/src/main/java/project/httpclient/HttpRequestTest.java
|
UTF-8
| 1,790
| 2.71875
| 3
|
[] |
no_license
|
package project.httpclient;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import project.httpclient.dto.UserDTO;
import utils.HttpClientUtil;
/**
* Author: Johnny
* Date: 2016/10/29
* Time: 0:34
*/
public class HttpRequestTest {
private static Logger logger = LoggerFactory.getLogger(HttpRequestTest.class);
public static void main(String[] args) throws Exception {
getRequestTest();
postRequestTest();
}
private static void getRequestTest() {
String url = "http://localhost:8080/SpringMVC/greet?name=lisi";
JSONObject jsonObject = HttpClientUtil.httpGet(url);
if (jsonObject != null) {
String userName = (String) jsonObject.get("userName");
logger.info("http Get request process success");
logger.info("userName:" + userName);
} else {
logger.info("http Get request process fail");
}
}
private static void postRequestTest() throws Exception {
String url = "http://localhost:8080/SpringMVC/process";
UserDTO userDTO = new UserDTO();
userDTO.setName("johnny");
userDTO.setAge(25);
JSONObject jsonParam = JSONObject.fromObject(userDTO);
JSONObject responseJSONObject = HttpClientUtil.httpPost(url, jsonParam);
if (responseJSONObject != null && "SUCCESS".equals(responseJSONObject.get("status"))) {
JSONObject userStr = (JSONObject) responseJSONObject.get("userDTO");
userDTO = (UserDTO) JSONObject.toBean(userStr, UserDTO.class);
logger.info("http Post request process success");
logger.info("userDTO:" + userDTO);
} else {
logger.info("http Post request process fail");
}
}
}
| true
|
a9c1d0e559d1100603738f3f411a1a9e4a3e3e5d
|
Java
|
nezda/yawni
|
/api/src/test/java/org/yawni/wordnet/HasLemma.java
|
UTF-8
| 2,710
| 2.328125
| 2
|
[
"LicenseRef-scancode-wordnet",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-only",
"Apache-2.0",
"MIT",
"BSD-2-Clause",
"ICU"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yawni.wordnet;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.BaseMatcher;
//"item", isIn(collection<T>)
//- matches("item") => collection.contains("item")
//different T's for factory method and matches()
//"lemma" isLemmaOf(word)
//- matches("lemma") => word.getLowercasedLemma().equals("lemma")
//"lemma" isLemmaOf(wordSense)
// inverted order (hasLemma("lemma")
//word, hasLemma("lemma")
//- matches(word) => "lemma".equals(word.getLowercasedLemma())
// maybe would be more properly implemented as IsLemmaOf ?
// assertThat("'hood", isLemmaOf(wordSenseX))
//
// hack to support Word and WordSense which currently have no
// common interface (e.g., GetLemma/HaveLemma/Lemma)
class HasLemma<T> extends BaseMatcher<T> {
private final Object wordOrWordSense;
private HasLemma(final Word word) {
this.wordOrWordSense = word;
}
private HasLemma(final WordSense wordSense) {
this.wordOrWordSense = wordSense;
}
@Override
public boolean matches(Object operand) {
String lemma = (String) operand;
if (wordOrWordSense instanceof Word) {
return lemma.equals(((Word)wordOrWordSense).getLowercasedLemma());
} else if (wordOrWordSense instanceof WordSense) {
return lemma.equals(((WordSense)wordOrWordSense).getLemma());
} else {
throw new IllegalArgumentException("wordOrWordSense: "+wordOrWordSense+
" unsupported class: " + wordOrWordSense.getClass());
}
}
@Override
public void describeTo(final Description description) {
description.
appendText("is lemma of ").
appendValue(wordOrWordSense);
}
@Factory
public static <T> Matcher<T> isLemmaOf(final Word operand) {
return new HasLemma<>(operand);
}
@Factory
public static <T> Matcher<T> isLemmaOf(final WordSense operand) {
return new HasLemma<>(operand);
}
}
| true
|
b55c16c5fbbc5510ce37bb85d351f73cb1f3317b
|
Java
|
asbnotebook/spring-boot
|
/spring-boot-elk-example/src/main/java/com/asbnotebook/SpringBootElkExampleApplication.java
|
UTF-8
| 750
| 1.96875
| 2
|
[] |
no_license
|
package com.asbnotebook;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringBootElkExampleApplication {
private static Log log = LogFactory.getLog(SpringBootElkExampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootElkExampleApplication.class, args);
}
@GetMapping("/test")
public String testELK() {
log.info("Inside test ELK!!");
return "Hello!!";
}
}
| true
|
161e8b83d10b2594adf693dd633ffa73696427f8
|
Java
|
SaberDoTcodeR/project-2
|
/src/DuelystServer/model/Card/Spell/HealthWithProfit.java
|
UTF-8
| 3,252
| 2.71875
| 3
|
[] |
no_license
|
package DuelystServer.model.Card.Spell;
import DuelystServer.model.Account;
import DuelystServer.model.Battle.Battle;
import DuelystServer.model.Cell;
import DuelystServer.model.ErrorType;
import javafx.scene.image.Image;
public class HealthWithProfit extends Spell {
public HealthWithProfit() {
super("HealthWithProfit", 0, 2250);
}
public HealthWithProfit(HealthWithProfit healthWithProfit) {
super(healthWithProfit);
}
@Override
public ErrorType castSpell(Battle battle, Cell cell, Account player) {
/* if (cell.getHero() == null && cell.getMinion() == null) {
//request.setError(ErrorType.INVALID_TARGET);
} else {
if (cell.getHero() != null) {
if (player.getMainDeck().isContain(cell.getHero())) {
WeaknessBuff weaknessBuff = new WeaknessBuff(6 - cell.getHero().getHolyCounter(), false);
weaknessBuff.decrementHp(cell.getHero());
weaknessBuff.setTurnCounter(2);
weaknessBuff.setCasting(weaknessBuff, null, cell.getHero(), null);
cell.getHero().getOwnBuffs().add(weaknessBuff);
for (int i = 0; i < 2; i++) {
HolyBuff holyBuff = new HolyBuff();
holyBuff.holy(cell.getHero());
holyBuff.setTurnCounter(2);
holyBuff.setCasting(holyBuff, null, cell.getHero(), null);
cell.getHero().getOwnBuffs().add(holyBuff);
}
}
} else {
//request.setError(ErrorType.INVALID_TARGET);
}
}
if (cell.getMinion() != null) {
if (player.getMainDeck().isContain(cell.getMinion())) {
WeaknessBuff weaknessBuff = new WeaknessBuff(6 - cell.getMinion().getHolyCounter(), false);
weaknessBuff.decrementHp(cell.getMinion());
weaknessBuff.setTurnCounter(2);
weaknessBuff.setCasting(weaknessBuff, null, null, cell.getMinion());
cell.getMinion().getOwnBuffs().add(weaknessBuff);
for (int i = 0; i < 2; i++) {
HolyBuff holyBuff = new HolyBuff();
holyBuff.holy(cell.getMinion());
holyBuff.setTurnCounter(2);
holyBuff.setCasting(holyBuff, null, null, cell.getMinion());
cell.getMinion().getOwnBuffs().add(holyBuff);
}
} else {
//request.setError(ErrorType.INVALID_TARGET);
}
}*/
return null;
}
public Spell duplicate() {
HealthWithProfit healthWithProfit = new HealthWithProfit(this);
return healthWithProfit;
}
@Override
public String getDesc() {
return SpellWork.HEALTH_WITH_PROFIT.getMessage();
}
@Override
public String showDetails() {
String details;
details = " Type : " + getType() + " - Name : " +
this.getClass().getSimpleName() + " - MP : " + this.getCostToUse() +
" - Desc: " + SpellWork.HEALTH_WITH_PROFIT.getMessage();
return details;
}
}
| true
|
65dc96386812fb34ddd3ea5b1e05620a797d42f6
|
Java
|
rowbothn/ENSE475_SnakeGame
|
/android_snake_game-master/app/src/androidTest/java/com/codepath/proj_Code/RankActivityTest.java
|
UTF-8
| 1,067
| 1.890625
| 2
|
[] |
no_license
|
package com.codepath.proj_Code;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import com.codepath.examples.basicsnakegame.R;
import org.junit.Rule;
import org.junit.Test;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
public final class RankActivityTest {
@Rule
public ActivityScenarioRule<RankActivity> s1 = new ActivityScenarioRule<>(RankActivity.class);
@Test
public void testLayout() {
onView(withId(R.id.rankLayout)).check(matches(isDisplayed()));
}
@Test
public void testTitle(){
onView(withId(R.id.rankTitle)).check(matches(isDisplayed()));
}
@Test
public void testDate(){
onView(withId(R.id.rankDate)).check(matches(isDisplayed()));
}
@Test
public void testPoint(){
onView(withId(R.id.rankPoint)).check(matches(isDisplayed()));
}
}
| true
|
d44572cc1ca9af90ed5aa7b04420ff11707a5ef9
|
Java
|
sumervardhan/SlogoIDE
|
/src/view/turtlearena/BasicTurtleArena.java
|
UTF-8
| 5,508
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
package view.turtlearena;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of the TurtleArena, contains the scene and the turtles within that the user sees, allows for visual properties to change through defined methods.
*
* @author Goh Khian Wei
*/
public class BasicTurtleArena implements TurtleArena {
private Image defaultImage;
private Color defaultPenColor;
private double defaultPenWidth;
private Map<Integer, Double> turtleCurX;
private Map<Integer, Double> turtleCurY;
private Map<Integer, Turtle> turtleControl;
private Map<Node, Integer> lines;
private Pane arena;
private double xOffset;
private double yOffset;
public BasicTurtleArena(Image defaultImage, Color defaultPenColor, double defaultPenWidth) {
this.defaultImage = defaultImage;
this.defaultPenColor = defaultPenColor;
this.defaultPenWidth = defaultPenWidth;
lines = new HashMap<>();
turtleCurX = new HashMap<>();
turtleCurY = new HashMap<>();
turtleControl = new HashMap<>();
initArena();
}
@Override
public Node getTurtleArena() {
return arena;
}
@Override
public void changeBackgroundColor(Color color) {
arena.setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)));
}
@Override
public void changeTurtleImage(int turtleIndex, Image image) {
turtleControl.get(turtleIndex).setTurtleImage(image);
moveTurtle(turtleIndex, turtleCurX.get(turtleIndex), turtleCurY.get(turtleIndex));
}
@Override
public void changePenColor(int turtleIndex, Color color) {
turtleControl.get(turtleIndex).setPenColor(color);
}
@Override
public void changePenThickness(int turtleIndex, double thickness) {
turtleControl.get(turtleIndex).setPenThickness(thickness);
}
@Override
public void addTurtle(int turtleIndex) {
turtleControl.put(turtleIndex, new BasicTurtle(defaultImage, defaultPenColor, defaultPenWidth));
arena.getChildren().add(turtleControl.get(turtleIndex).getTurtle());
moveTurtle(turtleIndex, 0, 0);
}
@Override
public void hideTurtle(int turtleIndex) {
turtleControl.get(turtleIndex).hide();
}
@Override
public void showTurtle(int turtleIndex) {
turtleControl.get(turtleIndex).show();
}
@Override
public void addLine(int turtleIndex, double xPos, double yPos) {
turtleCurX.put(turtleIndex, xPos);
turtleCurY.put(turtleIndex, yPos);
Node newLine = turtleControl.get(turtleIndex).addLine(xPos + xOffset, yPos + yOffset);
lines.put(newLine, turtleIndex);
arena.getChildren().add(newLine);
turtleControl.get(turtleIndex).getTurtle().toFront();
}
@Override
public void moveTurtle(int turtleIndex, double xPos, double yPos) {
turtleCurX.put(turtleIndex, xPos);
turtleCurY.put(turtleIndex, yPos);
turtleControl.get(turtleIndex).move(xOffset + xPos, yOffset + yPos);
}
@Override
public void rotateTurtle(int turtleIndex, double angle) {
turtleControl.get(turtleIndex).rotate(angle);
}
@Override
public void clearScreen() {
arena.getChildren().clear();
lines.clear();
turtleControl.entrySet().forEach(controller -> {
arena.getChildren().add(controller.getValue().getTurtle());
moveTurtle(controller.getKey(), 0, 0);
});
}
public void setDefaultImage(Image image) {
defaultImage = image;
}
public void setDefaultPenColor(Color color) {
defaultPenColor = color;
}
public void setDefaultPenWidth(double width) {
defaultPenWidth = width;
}
private void initArena() {
arena = new Pane();
arena.getStylesheets().add(getClass().getResource(ArenaConstants.ARENA_CSS_FILE).toExternalForm());
arena.getStyleClass().add(ArenaConstants.CSS_TAG_ARENA);
turtleControl.values().forEach(control -> arena.getChildren().add(control.getTurtle()));
initArenaDynamicSizeChange();
initArenaClipping();
}
private void initArenaDynamicSizeChange() {
arena.heightProperty().addListener(e -> sizeChangeHandler());
arena.widthProperty().addListener(e -> sizeChangeHandler());
}
private void initArenaClipping() {
Rectangle clip = new Rectangle(0, 0, 0, 0);
clip.widthProperty().bind(arena.widthProperty());
clip.heightProperty().bind(arena.heightProperty());
arena.setClip(clip);
}
private void sizeChangeHandler() {
double newXOffset = arena.getBoundsInLocal().getCenterX();
double newYOffset = arena.getBoundsInLocal().getCenterY();
turtleControl.values().forEach(control -> control.moveOffset(newXOffset - xOffset, newYOffset - yOffset));
lines.keySet().forEach(line -> {
line.relocate(line.getBoundsInParent().getMinX() + newXOffset - xOffset, line.getBoundsInParent().getMinY() + newYOffset - yOffset);
});
xOffset = newXOffset;
yOffset = newYOffset;
}
}
| true
|
e3da286338048ea5da7bc2cdd62bfcf428d29da6
|
Java
|
OksanaMurdza/ParkHub
|
/backend/src/main/java/ua/com/parkhub/mappers/modelToEntity/UuidTokenModelToEntity.java
|
UTF-8
| 1,130
| 2.484375
| 2
|
[] |
no_license
|
package ua.com.parkhub.mappers.modelToEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.com.parkhub.mappers.Mapper;
import ua.com.parkhub.model.UserModel;
import ua.com.parkhub.model.UuidTokenModel;
import ua.com.parkhub.persistence.entities.User;
import ua.com.parkhub.persistence.entities.UuidToken;
@Component
public class UuidTokenModelToEntity implements Mapper<UuidTokenModel, UuidToken> {
private Mapper<UserModel, User> userModelToEntityMapper;
@Autowired
public UuidTokenModelToEntity(Mapper<UserModel, User> userModelToEntityMapper) {
this.userModelToEntityMapper = userModelToEntityMapper;
}
@Override
public UuidToken transform(UuidTokenModel from) {
if(from == null) {
return null;
}
UuidToken entity = new UuidToken();
entity.setId(from.getId());
entity.setToken(from.getToken());
entity.setUser(userModelToEntityMapper.transform(from.getUser()));
entity.setExpirationDate(from.getExpirationDate());
return entity;
}
}
| true
|
40b2f2d4708a4f08e948c4150bf5168f650e5235
|
Java
|
yauritux/venice-legacy
|
/Venice/Venice-Interface-Model/src/main/java/com/gdn/venice/facade/FrdBlacklistReasonSessionEJBRemote.java
|
UTF-8
| 2,780
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.gdn.venice.facade;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remote;
import com.gdn.venice.persistence.FrdBlacklistReason;
import com.djarum.raf.utilities.JPQLAdvancedQueryCriteria;
import com.gdn.venice.facade.finder.FinderReturn;
@Remote
public interface FrdBlacklistReasonSessionEJBRemote {
/**
* queryByRange - allows querying by range/block
*
* @param jpqlStmt
* @param firstResult
* @param maxResults
* @return a list of FrdBlacklistReason
*/
public List<FrdBlacklistReason> queryByRange(String jpqlStmt, int firstResult,
int maxResults);
/**
* persistFrdBlacklistReason persists a country
*
* @param frdBlacklistReason
* @return the persisted FrdBlacklistReason
*/
public FrdBlacklistReason persistFrdBlacklistReason(FrdBlacklistReason frdBlacklistReason);
/**
* persistFrdBlacklistReasonList - persists a list of FrdBlacklistReason
*
* @param frdBlacklistReasonList
* @return the list of persisted FrdBlacklistReason
*/
public ArrayList<FrdBlacklistReason> persistFrdBlacklistReasonList(
List<FrdBlacklistReason> frdBlacklistReasonList);
/**
* mergeFrdBlacklistReason - merges a FrdBlacklistReason
*
* @param frdBlacklistReason
* @return the merged FrdBlacklistReason
*/
public FrdBlacklistReason mergeFrdBlacklistReason(FrdBlacklistReason frdBlacklistReason);
/**
* mergeFrdBlacklistReasonList - merges a list of FrdBlacklistReason
*
* @param frdBlacklistReasonList
* @return the merged list of FrdBlacklistReason
*/
public ArrayList<FrdBlacklistReason> mergeFrdBlacklistReasonList(
List<FrdBlacklistReason> frdBlacklistReasonList);
/**
* removeFrdBlacklistReason - removes a FrdBlacklistReason
*
* @param frdBlacklistReason
*/
public void removeFrdBlacklistReason(FrdBlacklistReason frdBlacklistReason);
/**
* removeFrdBlacklistReasonList - removes a list of FrdBlacklistReason
*
* @param frdBlacklistReasonList
*/
public void removeFrdBlacklistReasonList(List<FrdBlacklistReason> frdBlacklistReasonList);
/**
* findByFrdBlacklistReasonLike - finds a list of FrdBlacklistReason Like
*
* @param frdBlacklistReason
* @return the list of FrdBlacklistReason found
*/
public List<FrdBlacklistReason> findByFrdBlacklistReasonLike(FrdBlacklistReason frdBlacklistReason,
JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults);
/**
* findByFrdBlacklistReason>LikeFR - finds a list of FrdBlacklistReason> Like with a finder return object
*
* @param frdBlacklistReason
* @return the list of FrdBlacklistReason found
*/
public FinderReturn findByFrdBlacklistReasonLikeFR(FrdBlacklistReason frdBlacklistReason,
JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults);
}
| true
|
ad1587025c984a0fa0c45a1d6c6f3bd634e23fdd
|
Java
|
ldebello/javacuriosities
|
/Hibernate/HibernateBasics/src/main/java/ar/com/javacuriosities/hibernate/model/Person.java
|
UTF-8
| 1,910
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package ar.com.javacuriosities.hibernate.model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "people_entity")
@Table(name = "people")
@EntityListeners(AuditListener.class)
public class Person implements Auditable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "zip", column = @Column(length = 10)),
@AttributeOverride(name = "city", column = @Column(nullable = false))
})
private Address address;
@Embedded
private Audit audit;
public Person() {
}
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public Audit getAudit() {
return audit;
}
@Override
public void setAudit(Audit audit) {
this.audit = audit;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", address=" + address +
", audit=" + audit +
'}';
}
}
| true
|
5a3e08442d3b8e71ab4a71a99c938dcf21f3c625
|
Java
|
maheshgaya/BuildItBigger
|
/app/src/pro/java/com/udacity/gradle/builditbigger/product/Utils.java
|
UTF-8
| 506
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.udacity.gradle.builditbigger.product;
import android.content.Context;
import android.view.View;
/**
* This class does not apply to Paid version
* However, they are left empty as placeholders
* Usage in: MainFragment.java
*/
public class Utils {
public static void getAdView(View view){
}
public static void getInterstitialAd(Context context){
}
public static void showInterstitialAd(){
}
public static boolean isAdAvailable(){
return false;
}
}
| true
|
74881a901a6d58c6e04096d3aaa15ea5194aa6be
|
Java
|
indahfitri/sales_tracking
|
/app/src/main/java/com/user/salestracking/List_Call.java
|
UTF-8
| 27,385
| 1.617188
| 2
|
[] |
no_license
|
package com.user.salestracking;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.calendardatepicker.MonthAdapter;
import com.user.salestracking.Api_Service.Api_url;
import com.user.salestracking.Api_Service.RequestHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class List_Call extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private SessionManager session;
private HashMap<String, String> user;
private ListView listView;
List<DataListCall> dataListCall;
AlertDialog.Builder dialogs;
private ProgressDialog dialog;
LayoutInflater inflater;
TextView txt_nama, txt_email, txt_alamat, txt_jk, txt_noHp, txt_catatan;
TextView txt_tgl_pembayaran, tgl_lahir;
Button btn_call, btn_visit, btn_closing, btn_save;
View dialogView;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private TextView txtName, txtCabang, txtType;
private Toolbar toolbar;
public static int navItemIndex = 0;
private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
private String[] pay = {
"Transfer",
"Cash"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Sales Tracking");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
findViewById(R.id.drawer_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// open right drawer
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
}
else
drawer.openDrawer(GravityCompat.END);
}
});
mHandler = new Handler();
dialog = new ProgressDialog(List_Call.this);
dataListCall = new ArrayList<>();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtCabang = (TextView) navHeader.findViewById(R.id.website);
txtType = (TextView) navHeader.findViewById(R.id.type);
TextView txtTitle = (TextView) findViewById(R.id.title);
txtTitle.setText("LIST CALL");
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// setUpNavigationView();
listView = (ListView) findViewById(R.id.list_view);
session = new SessionManager(getApplicationContext());
user = session.getUserDetails();
txtName.setText(user.get(SessionManager.KEY_NAMA));
txtCabang.setText(user.get(SessionManager.KEY_EMAIL));
if (user.get(SessionManager.KEY_TYPE_ACCOUNT).equals("3")){
txtType.setText("Sales Marketing");
}else if (user.get(SessionManager.KEY_TYPE_ACCOUNT).equals("1")){
txtType.setText("Admin");
}else if (user.get(SessionManager.KEY_TYPE_ACCOUNT).equals("2")){
txtType.setText("Donatur");
}else {
txtType.setText("Owner");
}
request();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
dialogFormDetail(position);
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.setDrawerIndicatorEnabled(false);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.list_call:
Intent intent = new Intent(List_Call.this,List_Call.class);
startActivity(intent);
finish();
break;
case R.id.list_visit:
Intent intent1 = new Intent(List_Call.this,List_visit.class);
startActivity(intent1);
finish();
break;
case R.id.list_closing:
Intent intent2 = new Intent(List_Call.this,List_closing.class);
startActivity(intent2);
finish();
break;
}
return false;
}
});
}
private void popup(){
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setMessage("Anda Yakin ingin keluar dari aplikasi?")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
logout();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Logout?");
alert.show();
}
private void popup_close(){
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setMessage("Anda Yakin ingin keluar dari aplikasi?")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void logout(){
session.logoutUser();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
private void request() {
class RegisterUser extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
return requestHandler.getRequest(Api_url.GET_LIST_CALL);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("please wait...");
dialog.show();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
result(result);
}
}
RegisterUser ru = new RegisterUser();
ru.execute();
}
private void result(String result){
Log.d("result", result);
JSONObject jsonObject;
JSONArray jsonArray;
try {
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
// if (user.get(SessionManager.KEY_TYPE_ACCOUNT).equals("1")){
// dataListCall.add(new DataListCall(
// jsonObject.getString("nama"),
// jsonObject.getString("email"),
// jsonObject.getString("jenis_kelamin"),
// jsonObject.getString("alamat"),
// jsonObject.getString("no_hp"),
// jsonObject.getString("aktivitas"),
// jsonObject.getString("hasil_aktivitas"),
// jsonObject.getString("catatan"),
// jsonObject.getString("type_aktivitas"),
// jsonObject.getString("date_record"),
// jsonObject.getString("assign_by")));
// CallListAdapter adapter = new CallListAdapter(this, R.layout.row_data_call, dataListCall);
// listView.setAdapter(adapter);
// }else {
if (jsonObject.getString("assign_by").equals(user.get(SessionManager.KEY_NAMA))){
dataListCall.add(new DataListCall(
jsonObject.getString("nama"),
jsonObject.getString("email"),
jsonObject.getString("jenis_kelamin"),
jsonObject.getString("alamat"),
jsonObject.getString("no_hp"),
jsonObject.getString("aktivitas"),
jsonObject.getString("hasil_aktivitas"),
jsonObject.getString("catatan"),
jsonObject.getString("type_aktivitas"),
jsonObject.getString("date_record"),
jsonObject.getString("assign_by")));
CallListAdapter adapter = new CallListAdapter(this, R.layout.row_data_call, dataListCall);
listView.setAdapter(adapter);
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void dialogFormDetail(final int pos) {
dialogs = new AlertDialog.Builder(List_Call.this);
inflater = getLayoutInflater();
dialogView = inflater.inflate(R.layout.dialog_detail_call, null);
dialogs.setView(dialogView);
dialogs.setCancelable(true);
txt_nama = (TextView) dialogView.findViewById(R.id.tv_name);
txt_email = (TextView) dialogView.findViewById(R.id.tv_email);
txt_alamat = (TextView) dialogView.findViewById(R.id.tv_alamat);
TextView tv_noHp = (TextView) dialogView.findViewById(R.id.tv_noHp);
TextView tv_noted = (TextView) dialogView.findViewById(R.id.tv_note);
TextView tv_aktivitas = (TextView) dialogView.findViewById(R.id.tv_aktivitas);
TextView tv_hsl_aktivitas = (TextView) dialogView.findViewById(R.id.tv_hsl_aktivitas);
TextView tv_date = (TextView) dialogView.findViewById(R.id.tv_date);
TextView tv_registeredBy = (TextView) dialogView.findViewById(R.id.tv_registeredBy);
txt_nama.setText(dataListCall.get(pos).getName());
txt_email.setText(dataListCall.get(pos).getEmail());
txt_alamat.setText(dataListCall.get(pos).getAlamat());
tv_noHp.setText(dataListCall.get(pos).getNo_hp());
tv_noted.setText(dataListCall.get(pos).getCatatan());
tv_aktivitas.setText(dataListCall.get(pos).getAktivitas());
tv_hsl_aktivitas.setText(dataListCall.get(pos).getHasil_aktivitas());
tv_date.setText(dataListCall.get(pos).getDate_record());
tv_registeredBy.setText(dataListCall.get(pos).getAssign_by());
dialogs.show();
}
private void dialogCreate_donatur() {
dialogs = new AlertDialog.Builder(this);
inflater = getLayoutInflater();
dialogView = inflater.inflate(R.layout.dialog_edit_donatur, null);
dialogs.setView(dialogView);
dialogs.setCancelable(true);
final String url = Api_url.URL_EDIT_DONATUR;
final Spinner spinner = (Spinner) dialogView.findViewById(R.id.spinner1);
txt_nama = (EditText) dialogView.findViewById(R.id.txt_nama);
final EditText txt_alamat = (EditText) dialogView.findViewById(R.id.txt_alamat);
final EditText txt_email = (EditText) dialogView.findViewById(R.id.txt_email);
tgl_lahir = (TextView) dialogView.findViewById(R.id.txt_tgl_lahir);
txt_noHp = (EditText) dialogView.findViewById(R.id.txt_noHp);
TextView txt_title = (TextView)dialogView.findViewById(R.id.txt_title);
txt_title.setText("CREATE DONATUR");
tgl_lahir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
showCalendar_edit();
}
});
btn_save = (Button) dialogView.findViewById(R.id.btn_save);
btn_save.setText("CREATE");
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (txt_nama.getText().toString().equals("") || txt_alamat.getText().toString().equals("") || txt_email.getText().toString().equals("") || tgl_lahir.getText().toString().equals("") || txt_noHp.getText().toString().equals("")){
Toast.makeText(getApplicationContext(), "field tidak boleh kosong", Toast.LENGTH_SHORT).show();
}else {
request_create(txt_nama.getText().toString(),txt_email.getText().toString(), txt_alamat.getText().toString(),
spinner.getSelectedItem().toString(),tgl_lahir.getText().toString(),txt_noHp.getText().toString(),url, "");
}
}
});
dialogs.show();
}
private void dialogCreate_akun() {
dialogs = new AlertDialog.Builder(this);
inflater = getLayoutInflater();
dialogView = inflater.inflate(R.layout.dialog_edit_donatur, null);
dialogs.setView(dialogView);
dialogs.setCancelable(true);
final String url = Api_url.URL_EDIT_DONATUR;
final Spinner spinner = (Spinner) dialogView.findViewById(R.id.spinner1);
txt_nama = (EditText) dialogView.findViewById(R.id.txt_nama);
final EditText txt_alamat = (EditText) dialogView.findViewById(R.id.txt_alamat);
final EditText txt_email = (EditText) dialogView.findViewById(R.id.txt_email);
tgl_lahir = (TextView) dialogView.findViewById(R.id.txt_tgl_lahir);
txt_noHp = (EditText) dialogView.findViewById(R.id.txt_noHp);
TextView txt_title = (TextView)dialogView.findViewById(R.id.txt_title);
txt_title.setText("CREATE ACCOUNT");
LinearLayout ln_password = (LinearLayout) dialogView.findViewById(R.id.ln_password);
LinearLayout ln_cabang = (LinearLayout) dialogView.findViewById(R.id.ln_cabang);
ln_password.setVisibility(View.VISIBLE);
ln_cabang.setVisibility(View.VISIBLE);
tgl_lahir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
showCalendar_edit();
}
});
btn_save = (Button) dialogView.findViewById(R.id.btn_save);
btn_save.setText("CREATE");
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (txt_nama.getText().toString().equals("") || txt_alamat.getText().toString().equals("") || txt_email.getText().toString().equals("") || tgl_lahir.getText().toString().equals("") || txt_noHp.getText().toString().equals("")){
Toast.makeText(getApplicationContext(), "field tidak boleh kosong", Toast.LENGTH_SHORT).show();
}else {
request_create(txt_nama.getText().toString(),txt_email.getText().toString(), txt_alamat.getText().toString(),
spinner.getSelectedItem().toString(),tgl_lahir.getText().toString(),txt_noHp.getText().toString(),url, "");
}
}
});
dialogs.show();
}
public void showCalendar() {
Calendar calendar = Calendar.getInstance();
MonthAdapter.CalendarDay currDate = new MonthAdapter.CalendarDay();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
currDate.setDay(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
CalendarDatePickerDialogFragment cdp = new CalendarDatePickerDialogFragment()
.setOnDateSetListener(new CalendarDatePickerDialogFragment.OnDateSetListener() {
@Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
int month = monthOfYear+1;
String date = "";
if (dayOfMonth < 10){
if (month < 10){
date = "0"+dayOfMonth+"-"+"0"+month+"-"+year;
}else {
date = "0"+dayOfMonth+"-"+month+"-"+year;
}
}else {
if (month < 10){
date = dayOfMonth+"-"+"0"+month+"-"+year;
}else {
date = dayOfMonth+"-"+month+"-"+year;
}
}
txt_tgl_pembayaran.setText(date);
}
})
.setFirstDayOfWeek(Calendar.SUNDAY)
.setPreselectedDate(year, month, day)
.setDateRange(null, null)
.setDoneText("Yes")
.setThemeLight()
.setCancelText("Cancel");
cdp.show((getSupportFragmentManager()),"Promise Date");
}
public void showCalendar_edit() {
Calendar calendar = Calendar.getInstance();
MonthAdapter.CalendarDay currDate = new MonthAdapter.CalendarDay();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
currDate.setDay(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
CalendarDatePickerDialogFragment cdp = new CalendarDatePickerDialogFragment()
.setOnDateSetListener(new CalendarDatePickerDialogFragment.OnDateSetListener() {
@Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
int month = monthOfYear+1;
String date = "";
if (dayOfMonth < 10){
if (month < 10){
date = "0"+dayOfMonth+"-"+"0"+month+"-"+year;
}else {
date = "0"+dayOfMonth+"-"+month+"-"+year;
}
}else {
if (month < 10){
date = dayOfMonth+"-"+"0"+month+"-"+year;
}else {
date = dayOfMonth+"-"+month+"-"+year;
}
}
tgl_lahir.setText(date);
}
})
.setFirstDayOfWeek(Calendar.SUNDAY)
.setPreselectedDate(year, month, day)
.setDateRange(null, null)
.setDoneText("Yes")
.setThemeLight()
.setCancelText("Cancel");
cdp.show((getSupportFragmentManager()),"Promise Date");
}
private void request_create(final String nama, final String email, final String alamat, final String jenis_kelamin, final String tanggal_lahir,
final String noHp,final String url,final String id) {
class insert_call extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);
@SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy HH:mm");
String formattedDate = df.format(c);
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("nama", nama);
params.put("email", email);
params.put("alamat", alamat);
params.put("jenis_kelamin", jenis_kelamin);
params.put("nomor_hanphone", noHp);
params.put("tgl_lahir", tanggal_lahir);
params.put("id", id);
//returing the response
return requestHandler.sendPostRequest(url, params);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
dialog.setMessage("please wait...");
dialog.show();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("result", result);
dialog.dismiss();
try {
JSONObject obj = new JSONObject(result);
if (obj.getInt("status") == 0) {
popup_success(obj.getString("message"));
} else {
popup_failed(obj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
insert_call ru = new insert_call();
ru.execute();
}
private void popup_success(String message){
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(List_Call.this, MainActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void popup_failed(String message){
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.dashboard) {
startActivity(new Intent(List_Call.this, Dashboard_activity.class));
drawer.closeDrawers();
finish();
}else if (id == R.id.list_call) {
startActivity(new Intent(List_Call.this, List_Call.class));
drawer.closeDrawers();
finish();
} else if (id == R.id.list_visit) {
startActivity(new Intent(List_Call.this, List_visit.class));
drawer.closeDrawers();
finish();
} else if (id == R.id.list_closing) {
startActivity(new Intent(List_Call.this, List_closing.class));
drawer.closeDrawers();
finish();
} else if (id == R.id.nav_about_us) {
Toast.makeText(getApplicationContext(), "about_us", Toast.LENGTH_SHORT).show();
} else if (id == R.id.create_donatur) {
dialogCreate_donatur();
} else if (id == R.id.create_akun) {
dialogCreate_akun();
} else if (id == R.id.list_donatur) {
startActivity(new Intent(List_Call.this, MainActivity.class));
drawer.closeDrawers();
finish();
} else if (id == R.id.logout) {
popup();
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
return true;
}
@Override
public void onBackPressed() {
popup_close();
}
}
| true
|
9f0afa4d00dfe7d3c191ccf7902b5cf4db5c81d4
|
Java
|
DeraDeveloper/snippet
|
/src/main/java/com/storage/snippet/controller/SnippetController.java
|
UTF-8
| 1,383
| 2.15625
| 2
|
[] |
no_license
|
package com.storage.snippet.controller;
import com.storage.snippet.apimodel.SnippetCreationRequest;
import com.storage.snippet.apimodel.SnippetCreationResponse;
import com.storage.snippet.exceptions.RequestProcessingException;
import com.storage.snippet.exceptions.ResourceNotFoundException;
import com.storage.snippet.exceptions.ValidationException;
import com.storage.snippet.service.SnippetManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/snippets")
public class SnippetController {
@Autowired
private SnippetManagementService snippetManagementService;
@PostMapping
public SnippetCreationResponse createSnippet(@RequestBody SnippetCreationRequest snippetCreationRequest) throws ValidationException {
return snippetManagementService.createSnippet(snippetCreationRequest);
}
@GetMapping("/{name}")
public SnippetCreationResponse createSnippet(@PathVariable("name") String name) throws ResourceNotFoundException, RequestProcessingException {
return snippetManagementService.getSnippet(name);
}
@PostMapping("/{name}/like")
public SnippetCreationResponse likeSnippet(@PathVariable("name") String name) throws ResourceNotFoundException {
return snippetManagementService.likeSnippet(name);
}
}
| true
|
6baacea9ef05cd3e82a47cdac4a373bd64c74536
|
Java
|
palmenhq/twig4j-core
|
/src/main/java/org/twig4j/core/loader/Loader.java
|
UTF-8
| 798
| 2.421875
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package org.twig4j.core.loader;
import org.twig4j.core.exception.LoaderException;
/**
* Interface all loaders must implement.
*/
public interface Loader {
/**
* Get the source code of a template, given it's name.
*
* @param name The name of the template to load
*
* @return The template source code
*
* @throws LoaderException If the template does not exist
*/
public String getSource(String name) throws LoaderException;
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param name The name of the template to load
*
* @return The cache key
*
* @throws LoaderException If the template does not exist
*/
public String getCacheKey(String name) throws LoaderException;
}
| true
|
e52f562e7721b3177f0083e317f9dfd2b519992b
|
Java
|
MeganMcConville/bookshelf-backend
|
/src/main/java/com/megansportfolio/mybookshelfbackend/comment/CommentController.java
|
UTF-8
| 715
| 2.0625
| 2
|
[] |
no_license
|
package com.megansportfolio.mybookshelfbackend.comment;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
@RestController
@RequestMapping(value = "/comments", consumes = "application/json")
public class CommentController {
@Autowired
private CommentService commentService;
@RequestMapping(method = RequestMethod.POST)
public long saveComment(@RequestBody Comment comment){
return commentService.saveComment(comment);
}
}
| true
|
6ff6f1ee82638e4473c04f6e2562199d04bc241d
|
Java
|
CarlaX/JavaAlgorithm
|
/Week01/src/main/java/com/fzw/week01/question01/Solution.java
|
UTF-8
| 1,495
| 3.328125
| 3
|
[] |
no_license
|
package com.fzw.week01.question01;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
/**
* @author fzw
* @description 66. 加一
* @date 2021-06-29
**/
public class Solution {
@Test
public void test() {
int[] result = null;
result = this.plusOne(new int[]{1, 2, 3, 4});
System.out.println(Arrays.toString(result));
result = this.plusOne(new int[]{1, 2, 3, 9});
System.out.println(Arrays.toString(result));
result = this.plusOne(new int[]{1, 2, 9, 9});
System.out.println(Arrays.toString(result));
result = this.plusOne(new int[]{1, 9, 9, 9});
System.out.println(Arrays.toString(result));
result = this.plusOne(new int[]{9, 9, 9, 9});
System.out.println(Arrays.toString(result));
result = this.plusOne(new int[]{0});
System.out.println(Arrays.toString(result));
}
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
int temp = digits[i] + 1;
if (temp < 10) {
digits[i] = temp;
break;
} else {
digits[i] = 0;
if (i == 0) {
int[] newDigits = new int[digits.length + 1];
newDigits[0] = 1;
System.arraycopy(digits, 0, newDigits, 1, digits.length);
digits = newDigits;
}
}
}
return digits;
}
}
| true
|
c9eafa07a9f95fa57cac90402dc9eb52c698955b
|
Java
|
wangye43/algorithm
|
/src/zyz/algorithm/bit/BitwiseANDofNumbersRange_140.java
|
UTF-8
| 675
| 3.453125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package zyz.algorithm.bit;
/**
* @author zyz
* @title: 数字范围按位与
* @seq: 201
* @address: https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
* 官方题解所说的 一定存在连续的两个数 xx 和 x+1x+1,满足 xx 的第 i+1i+1 位为 00,后面全为 11
* 是 在保证了最大前缀为前i位,则第i+1位一定是有两个数是不同的
* 而n +1 =n (二进制也是+1的关系) 所以一定有一个011 一个100 因为 011+1=110
*/
public class BitwiseANDofNumbersRange_140 {
public int rangeBitwiseAnd(int left, int right) {
int n=0;
while(left<right)
{
right>>=1;
left>>=1;
n++;
}
return left<<n;
}
}
| true
|
b3f01d9068c2a338f16c21b792224ca7ce72279f
|
Java
|
blublab/ad_aufgabe4
|
/src/avl/Main.java
|
UTF-8
| 1,473
| 2.953125
| 3
|
[] |
no_license
|
package avl;
import java.io.IOException;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.DirectedPseudograph;
public class Main {
public static void main(String[] args) throws IOException {
int[] folge = Reader.getSequence("./Files/zahlen1.dat");
AVLBaum avlbaum = new AVLBaum();
for (int n : folge) {
avlbaum.insert(n);
}
Graph<Knoten, DefaultWeightedEdge> g = tree2Graph(avlbaum);
Knoten root = avlbaum.root;
System.out.println("Summe Baum Preorder: " + avlbaum.preOrderSum(root));
System.out.println("Summe Baum Postorder: " + avlbaum.postOrderSum(root));
int sum = 0;
for (int n: folge){
sum += n;
}
System.out.println("Summe Folge: " + sum);
Visualizer.starte(g, root);
avlbaum.remove(2);
Visualizer.starte(g, root);
}
private static Graph<Knoten, DefaultWeightedEdge> tree2Graph(AVLBaum tree) {
Graph<Knoten, DefaultWeightedEdge> g = new DirectedPseudograph<Knoten, DefaultWeightedEdge>(
DefaultWeightedEdge.class);
g.addVertex(tree.root);
tree2GraphRek(tree.root, g);
return g;
}
private static void tree2GraphRek(Knoten k,
Graph<Knoten, DefaultWeightedEdge> g) {
if (k.links != null) {
g.addVertex(k.links);
g.addEdge(k, k.links);
tree2GraphRek(k.links, g);
}
if (k.rechts != null) {
g.addVertex(k.rechts);
g.addEdge(k, k.rechts);
tree2GraphRek(k.rechts, g);
}
}
}
| true
|
e1d48c63daf1fffcec553c7abb3d926503d29d93
|
Java
|
iBuildApp-Network/Marketplace
|
/Android/main/src/main/java/com/appbuilder/core/DownloadHelperCallback.java
|
UTF-8
| 328
| 1.9375
| 2
|
[] |
no_license
|
package com.appbuilder.core;
import com.appbuilder.core.DownloadHelper;
public interface DownloadHelperCallback {
public void DownloadHelperCallbackStarted(DownloadHelper obj);
public void DownloadHelperCallbackSuccess(DownloadHelper obj);
public void DownloadHelperCallbackFailed(DownloadHelper obj, String errorString);
}
| true
|
5e0a3604a8d03fb3d8e694f1b956c714a781066c
|
Java
|
harikayarramsetty/MagentoGitJenkin
|
/src/test/java/com/google/pages/DashboardPage.java
|
UTF-8
| 730
| 2.171875
| 2
|
[] |
no_license
|
package com.google.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DashboardPage {
private static By logoutLocator=By.partialLinkText("Out");
public static void waitForLogoutPresence(WebDriver driver)
{
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.presenceOfElementLocated(logoutLocator));
}
public static String getCurrentTitle(WebDriver driver)
{
String actualTitle = driver.getTitle();
return actualTitle;
}
public static void clickOnLogOut(WebDriver driver)
{
driver.findElement(logoutLocator).click();
}
}
| true
|
204be669448834685db2a00e91ba3a838ac51321
|
Java
|
Plugineers/VoxelVoyage
|
/src/main/java/com/przlabs/voyage/entity/UselessDragon.java
|
UTF-8
| 375
| 1.9375
| 2
|
[] |
no_license
|
package com.przlabs.voyage.entity;
import net.minecraft.server.v1_12_R1.EntityEnderDragon;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftEnderDragon;
public class UselessDragon extends CraftEnderDragon {
public UselessDragon(CraftServer server, EntityEnderDragon entity) {
super(server, entity);
}
}
| true
|
16faabe6052ddcde290242e3f1fdf15c2dc69489
|
Java
|
Infrosdo/springBoot
|
/06-jsp/src/main/java/priv/huke/controller/StudentController.java
|
UTF-8
| 1,452
| 2.296875
| 2
|
[] |
no_license
|
package priv.huke.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import priv.huke.Service.StudentService;
import priv.huke.vo.Student;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService service;
Logger log = Logger.getLogger(StudentController.class);
@RequestMapping("/test")
public String test(){
return "test";
}
@RequestMapping("/index")
public String index(){
log.info("-------------index");
return "index";
}
// @PostMapping(value = "/register",consumes = "application/json")
@RequestMapping("/register")
public String registerHandle(@ModelAttribute Student student, Model model) throws Exception {
log.info("-------------"+student.toString());
int result = service.addStudent(student);
log.info("-------------"+result);
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
return "welcome";
}
@RequestMapping("/getStudent")
public String getStudent(Model model){
log.info("-------------getStudent");
String s = service.Sel(1).toString();
model.addAttribute("s", s);
return "select";
}
}
| true
|
3dc4851e963ce2c96298a9c9670818637fec2578
|
Java
|
liestory/spring-tablegame
|
/table-game-impl/src/main/java/ru/tablegame/controller/AdminPanelController.java
|
UTF-8
| 1,219
| 2.078125
| 2
|
[] |
no_license
|
package ru.tablegame.controller;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Контролел управления юзерами в рамках 1 игры
* TODO: поидее должна быть логика упраления админом определнной game другиеи users
* Пока ее нет и продумываю.
*
* @author nemykin 03.11.2020
*/
@RestController
@RequestMapping("/api/admin/panel")
@Slf4j
@AllArgsConstructor
public class AdminPanelController {
// @PostMapping(value = "/change_status")
// public UserDto userRegistration(@Validated @RequestBody UserDto userDto, BindingResult result) {
//// if (result.hasErrors()) {
//// userDto.setErrors(result.getAllErrors());
//// return userDto;
//// }
//// //TODO: подумать о том как правильно сделать тут DTO для настройки админом других пользователей
//// // userService.changeRole(userDto);
// return userDto;
// }
}
| true
|
42ca63d5bb93d9b121297357dace55f900267af5
|
Java
|
spinfo/upcase
|
/src/main/java/de/uni_koeln/spinfo/upcase/model/form/UploadForm.java
|
UTF-8
| 2,300
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package de.uni_koeln.spinfo.upcase.model.form;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class UploadForm {
private List<MultipartFile> files;
private String collectionName;
private String description;
private String license;
public UploadForm() {
super();
}
public UploadForm(List<MultipartFile> files, String collectionName, final String license) {
super();
this.files = files;
this.collectionName = collectionName;
this.license = license;
}
public UploadForm(List<MultipartFile> files, String collectionName, String description, final String license) {
super();
this.files = files;
this.collectionName = collectionName;
this.description = description;
this.license = license;
}
public List<MultipartFile> getFiles() {
return files;
}
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((collectionName == null) ? 0 : collectionName.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UploadForm other = (UploadForm) obj;
if (collectionName == null) {
if (other.collectionName != null)
return false;
} else if (!collectionName.equals(other.collectionName))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
}
@Override
public String toString() {
return "UploadForm [collectionName=" + collectionName + ", description=" + description + "]";
}
}
| true
|
f569f12d7b8775150ab99afe0b06491603ebc1c5
|
Java
|
panuza/Apiservice
|
/src/com/crunchify/restjersey/HtmlService.java
|
UTF-8
| 1,621
| 2.296875
| 2
|
[] |
no_license
|
package com.crunchify.restjersey;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
@Path("/film.html")
public class HtmlService {
@GET
@Produces("text/html")
public void test(@Context ServletContext context, @Context HttpServletRequest request,
@Context HttpServletResponse response) throws URISyntaxException, ServletException, IOException {
Utills utills = new Utills();
ArrayList<HashMap<String, String>> list = utills.getList();
Random random = new Random();
int index = random.nextInt(list.size());
List<String> keys = new ArrayList<String>(list.get(index).keySet());
// String myJsfPage ="../NewFile.html";
// response.getWriter().print("Year: "
// +list.get(index).get(list.get(index).keySet().iterator().next()) + "
// Title :" +keys.iterator().next().toString().replace("\"", ""));
request.setAttribute("year", list.get(index).get(list.get(index).keySet().iterator().next()));
request.setAttribute("title", list.get(index).get(list.get(index).keySet().iterator().next()));
// response.sendRedirect("/NewFile.html");
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/NewFile.jsp");
rd.forward(request, response);
}
}
| true
|
c21536d22624fabf29873ebb08ba4198a594898a
|
Java
|
buzzbuzzyo/CS3343
|
/src/ShowStatus.java
|
UTF-8
| 264
| 2.5
| 2
|
[] |
no_license
|
public class ShowStatus implements Command {
@Override
public void execute(String[] cmdParts) {
try {
ShopSystem shopSystem = ShopSystem.getInstance();
shopSystem.showStatus();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| true
|
8fc4477cab67fd06c0877b9b1259297ea6b46ee6
|
Java
|
yueguangdoufu/Gaokaozyfz
|
/src/main/java/com/txy/gkzyfz/test/Guanliyuan.java
|
UTF-8
| 3,798
| 2.125
| 2
|
[] |
no_license
|
package com.txy.gkzyfz.test;
public class Guanliyuan {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column guanliyuan.gid
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
private String gid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column guanliyuan.gname
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
private String gname;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column guanliyuan.gusername
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
private String gusername;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column guanliyuan.gpassword
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
private String gpassword;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column guanliyuan.gid
*
* @return the value of guanliyuan.gid
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public String getGid() {
return gid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column guanliyuan.gid
*
* @param gid the value for guanliyuan.gid
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public void setGid(String gid) {
this.gid = gid == null ? null : gid.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column guanliyuan.gname
*
* @return the value of guanliyuan.gname
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public String getGname() {
return gname;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column guanliyuan.gname
*
* @param gname the value for guanliyuan.gname
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public void setGname(String gname) {
this.gname = gname == null ? null : gname.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column guanliyuan.gusername
*
* @return the value of guanliyuan.gusername
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public String getGusername() {
return gusername;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column guanliyuan.gusername
*
* @param gusername the value for guanliyuan.gusername
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public void setGusername(String gusername) {
this.gusername = gusername == null ? null : gusername.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column guanliyuan.gpassword
*
* @return the value of guanliyuan.gpassword
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public String getGpassword() {
return gpassword;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column guanliyuan.gpassword
*
* @param gpassword the value for guanliyuan.gpassword
*
* @mbg.generated Sun Apr 19 22:54:29 CST 2020
*/
public void setGpassword(String gpassword) {
this.gpassword = gpassword == null ? null : gpassword.trim();
}
}
| true
|
84437f1a756c19e9ccc5c385c8bf089624e41872
|
Java
|
Matfork/android_lessons_belatrix
|
/L07EJ1/app/src/main/java/com/example/matt/l07ej1/MainActivity.java
|
UTF-8
| 1,075
| 2.1875
| 2
|
[] |
no_license
|
package com.example.matt.l07ej1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.iv1);
ImageView img2 = (ImageView) findViewById(R.id.iv2);
ImageView img3 = (ImageView) findViewById(R.id.iv3);
img.setOnClickListener(onClickListener);
img2.setOnClickListener(onClickListener);
img3.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//v.getId()
Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
MainActivity.this.startActivity(myIntent);
}
};
}
| true
|
92459d9dd0c271902404990ee19fc6e527be9fd7
|
Java
|
gokul2000/SleepTracker
|
/app/src/main/java/com/example/sleeptracker/sleepTracker/SleepNigthRepository.java
|
UTF-8
| 2,431
| 2.640625
| 3
|
[] |
no_license
|
package com.example.sleeptracker.sleepTracker;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.example.sleeptracker.database.SleepDataBase;
import com.example.sleeptracker.database.SleepDataBaseDao;
import com.example.sleeptracker.database.SleepNight;
import java.util.List;
public class SleepNigthRepository {
private SleepDataBaseDao sleepDataBaseDao;
private LiveData<List<SleepNight>> allnights;
public SleepNigthRepository(Application application)
{
SleepDataBase sleepDataBase = SleepDataBase.getInstance(application);
sleepDataBaseDao=sleepDataBase.sleepDataBaseDao();
allnights=sleepDataBaseDao.getAllNights();
}
public void insert(SleepNight night)
{
new InsertNight(sleepDataBaseDao).execute(night);
}
public void update(SleepNight night)
{
new UpdateNight(sleepDataBaseDao).execute(night);
}
public void clear()
{
new DeleteAllNights(sleepDataBaseDao).execute();
}
public LiveData<List<SleepNight>> getAllnights() {
return allnights;
}
private static class InsertNight extends AsyncTask<SleepNight,Void,Void>
{
private SleepDataBaseDao sleepDataBaseDao;
private InsertNight(SleepDataBaseDao sleepDataBaseDao){
this.sleepDataBaseDao=sleepDataBaseDao;
}
@Override
protected Void doInBackground(SleepNight... sleepNights) {
sleepDataBaseDao.insert(sleepNights[0]);
return null;
}
}
private static class UpdateNight extends AsyncTask<SleepNight,Void,Void>
{
private SleepDataBaseDao sleepDataBaseDao;
private UpdateNight(SleepDataBaseDao sleepDataBaseDao){
this.sleepDataBaseDao=sleepDataBaseDao;
}
@Override
protected Void doInBackground(SleepNight... sleepNights) {
sleepDataBaseDao.update(sleepNights[0]);
return null;
}
}
private static class DeleteAllNights extends AsyncTask<Void,Void,Void>
{
private SleepDataBaseDao sleepDataBaseDao;
private DeleteAllNights(SleepDataBaseDao sleepDataBaseDao){
this.sleepDataBaseDao=sleepDataBaseDao;
}
@Override
protected Void doInBackground(Void... voids) {
sleepDataBaseDao.clear();
return null;
}
}
}
| true
|
e8ac18905db8236240781abc05ddaabdaebe7d36
|
Java
|
NivraLeak/ideoWili
|
/src/main/java/com/studydesk/Controller/CourseController.java
|
UTF-8
| 4,222
| 2.28125
| 2
|
[] |
no_license
|
package com.studydesk.Controller;
import com.studydesk.Model.Career;
import com.studydesk.Model.Course;
import com.studydesk.Resource.CareerResource;
import com.studydesk.Resource.CourseResource;
import com.studydesk.Resource.SaveCareerResource;
import com.studydesk.Resource.SaveCourseResource;
import com.studydesk.Service.CourseService;
import com.studydesk.repository.CourseRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@Tag(name = "courses", description = "Courses API")
@RestController
@RequestMapping("/api")
public class CourseController {
@Autowired
private ModelMapper mapper;
@Autowired
private CourseService courseService;
@Operation(summary = "Get Courses", description = "Get All Courses by Pages", tags = { "courses" })
@GetMapping("/courses")
public Page<CourseResource> getAllCourses(
@Parameter(description="Pageable Parameter")
Pageable pageable) {
Page<Course> postsPage = courseService.getAllCourses(pageable);
List<CourseResource> resources = postsPage.getContent().stream().map(this::convertToResource).collect(Collectors.toList());
return new PageImpl<>(resources, pageable, resources.size());
}
@Operation(summary = "Get Courses by Id", description = "Get a Courses by specifying Id", tags = { "courses" })
@GetMapping("/courses/{id}")
public CourseResource getCareerById(
@Parameter(description="Post Id")
@PathVariable(name = "id") Long postId) {
return convertToResource(courseService.getCourseById(postId));
}
@PostMapping("/courses")
public CourseResource createCourse(@Valid @RequestBody SaveCourseResource resource){
Course course = convertToEntity(resource);
return convertToResource(courseService.createCourse(course));
}
@PutMapping("/courses/{id}")
public CourseResource updateCourse(@PathVariable(name = "id") Long postId, @Valid @RequestBody SaveCourseResource resource) {
Course course = convertToEntity(resource);
return convertToResource(courseService.updateCourse(postId,course));
}
@DeleteMapping("/courses/{id}")
public ResponseEntity<?> deleteCourse(@PathVariable(name = "id") Long postId) {
return courseService.deleteCourses(postId);
}
@GetMapping("/tags/{tagId}/courses")
public Page<CourseResource> getAllCoursesByCareerId(@PathVariable(name = "tagId") Long tagId, Pageable pageable){
Page<Course> postPage = courseService.getAllCoursesByCareerId(tagId, pageable);
List<CourseResource> resources = postPage.getContent().stream().map(this::convertToResource).collect(Collectors.toList());
return new PageImpl<>(resources, pageable, resources.size());
}
@PostMapping("/courses/{courseId}/careers/{careerId}")
public CourseResource assingCoursesCareer(@PathVariable(name = "courseId") Long postId,
@PathVariable(name = "careerId") Long tagId){
return convertToResource(courseService.assignCourseCareer(postId, tagId));
}
@DeleteMapping("/courses/{courseId}/careers/{careerId}")
public CourseResource unassignCourseCareer(@PathVariable(name = "courseId") Long postId,
@PathVariable(name = "careerId") Long tagId) {
return convertToResource(courseService.unassignCourseCareer(postId, tagId));
}
private Course convertToEntity(SaveCourseResource resource){
return mapper.map(resource, Course.class);
}
private CourseResource convertToResource(Course entity){
return mapper.map(entity, CourseResource.class);
}
}
| true
|
d20d5d1f1a773486f8c52a35a09fc32ec705b048
|
Java
|
shravansukumar1991/javatraining
|
/Loan_Approval1.java
|
UTF-8
| 1,668
| 2.625
| 3
|
[] |
no_license
|
package training;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Loan_Approval1 {
public static void main(String[] args) throws IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demodb","root","pragatha");
Statement stmt = con.createStatement();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name:");
String name = br.readLine();
String q="select * from Loan_Approval1 where name='"+name+"'";
ResultSet rs=stmt.executeQuery(q);
if(rs.next())
{
System.out.println(rs.getString(1)+ " " +rs.getInt(2));
System.out.println("Enter Loan amount");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
int loan = Integer.parseInt(br1.readLine());
if(loan<3*12*rs.getInt(2)) {
System.out.println(name + " Loan Approved");
}
else {
System.out.println(name + " Loan NOT Approved");
}}
else
{
System.out.println("Record Not Found...");
}
stmt.close();
con.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
| true
|
62f27735b4935383ab6e133f812030b341c6cf9e
|
Java
|
manessaraj/designpatterns
|
/src/main/java/ChainOfResponsibility/Client.java
|
UTF-8
| 725
| 2.546875
| 3
|
[] |
no_license
|
package ChainOfResponsibility;
import java.time.LocalDate;
public class Client {
public static void main(String[] args) {
LeaveApplication leaveApplication = LeaveApplication.getBuilder().withType(LeaveApplication.Type.PTO)
.from(LocalDate.now()).to(LocalDate.of(2020, 07, 27)).build();
LeaveApprover leaveApprover = createChain();
System.out.println(leaveApplication);
leaveApprover.processLeaveApplication(leaveApplication);
System.out.println(leaveApplication.getProcessedBy());
}
private static LeaveApprover createChain() {
Director director = new Director(null);
Manager manager = new Manager(director);
ProjectLead projectLead = new ProjectLead(manager);
return projectLead;
}
}
| true
|
ac2e71660067d1b9c26bcf78e870a4f519cff9bc
|
Java
|
reverseengineeringer/net.cloudpath.xpressconnect
|
/src/org/xbill/DNS/Cache.java
|
UTF-8
| 22,997
| 2.390625
| 2
|
[] |
no_license
|
package org.xbill.DNS;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
public class Cache
{
private static final int defaultMaxEntries = 50000;
private CacheMap data;
private int dclass;
private int maxcache = -1;
private int maxncache = -1;
public Cache()
{
this(1);
}
public Cache(int paramInt)
{
this.dclass = paramInt;
this.data = new CacheMap(50000);
}
public Cache(String paramString)
throws IOException
{
this.data = new CacheMap(50000);
Master localMaster = new Master(paramString);
while (true)
{
Record localRecord = localMaster.nextRecord();
if (localRecord == null)
break;
addRecord(localRecord, 0, localMaster);
}
}
private void addElement(Name paramName, Element paramElement)
{
while (true)
{
Object localObject2;
int i;
List localList;
int j;
try
{
localObject2 = this.data.get(paramName);
if (localObject2 == null)
{
this.data.put(paramName, paramElement);
return;
}
i = paramElement.getType();
if (!(localObject2 instanceof List))
break label127;
localList = (List)localObject2;
j = 0;
if (j >= localList.size())
break label115;
if (((Element)localList.get(j)).getType() == i)
{
localList.set(j, paramElement);
continue;
}
}
finally
{
}
j++;
continue;
label115: localList.add(paramElement);
continue;
label127: Element localElement = (Element)localObject2;
if (localElement.getType() == i)
{
this.data.put(paramName, paramElement);
}
else
{
LinkedList localLinkedList = new LinkedList();
localLinkedList.add(localElement);
localLinkedList.add(paramElement);
this.data.put(paramName, localLinkedList);
}
}
}
private Element[] allElements(Object paramObject)
{
try
{
List localList;
if ((paramObject instanceof List))
localList = (List)paramObject;
for (Element[] arrayOfElement = (Element[])localList.toArray(new Element[localList.size()]); ; arrayOfElement = new Element[] { (Element)paramObject })
return arrayOfElement;
}
finally
{
}
}
private Object exactName(Name paramName)
{
try
{
Object localObject2 = this.data.get(paramName);
return localObject2;
}
finally
{
localObject1 = finally;
throw localObject1;
}
}
private Element findElement(Name paramName, int paramInt1, int paramInt2)
{
try
{
Object localObject2 = exactName(paramName);
if (localObject2 == null);
Element localElement;
for (Object localObject3 = null; ; localObject3 = localElement)
{
return localObject3;
localElement = oneElement(paramName, localObject2, paramInt1, paramInt2);
}
}
finally
{
}
}
private RRset[] findRecords(Name paramName, int paramInt1, int paramInt2)
{
SetResponse localSetResponse = lookupRecords(paramName, paramInt1, paramInt2);
if (localSetResponse.isSuccessful())
return localSetResponse.answers();
return null;
}
private final int getCred(int paramInt, boolean paramBoolean)
{
if (paramInt == 1)
if (!paramBoolean);
do
{
return 4;
return 3;
if (paramInt != 2)
break;
}
while (paramBoolean);
return 3;
if (paramInt == 3)
return 1;
throw new IllegalArgumentException("getCred: invalid section");
}
private static int limitExpire(long paramLong1, long paramLong2)
{
if ((paramLong2 >= 0L) && (paramLong2 < paramLong1))
paramLong1 = paramLong2;
long l = paramLong1 + System.currentTimeMillis() / 1000L;
if ((l < 0L) || (l > 2147483647L))
return 2147483647;
return (int)l;
}
private static void markAdditional(RRset paramRRset, Set paramSet)
{
if (paramRRset.first().getAdditionalName() == null);
while (true)
{
return;
Iterator localIterator = paramRRset.rrs();
while (localIterator.hasNext())
{
Name localName = ((Record)localIterator.next()).getAdditionalName();
if (localName != null)
paramSet.add(localName);
}
}
}
private Element oneElement(Name paramName, Object paramObject, int paramInt1, int paramInt2)
{
if (paramInt1 == 255)
try
{
throw new IllegalArgumentException("oneElement(ANY)");
}
finally
{
}
int k;
Object localObject1;
if ((paramObject instanceof List))
{
List localList = (List)paramObject;
k = 0;
int m = localList.size();
localObject1 = null;
if (k < m)
{
Element localElement2 = (Element)localList.get(k);
int n = localElement2.getType();
if (n == paramInt1)
localObject1 = localElement2;
}
else
{
label94: if (localObject1 != null)
break label144;
localObject1 = null;
}
}
while (true)
{
return localObject1;
k++;
break;
Element localElement1 = (Element)paramObject;
int i = localElement1.getType();
localObject1 = null;
if (i != paramInt1)
break label94;
localObject1 = localElement1;
break label94;
label144: if (localObject1.expired())
{
removeElement(paramName, paramInt1);
localObject1 = null;
}
else
{
int j = localObject1.compareCredibility(paramInt2);
if (j < 0)
localObject1 = null;
}
}
}
private void removeElement(Name paramName, int paramInt)
{
while (true)
{
Object localObject2;
int i;
try
{
localObject2 = this.data.get(paramName);
if (localObject2 == null)
return;
if (!(localObject2 instanceof List))
break label114;
List localList = (List)localObject2;
i = 0;
if (i >= localList.size())
continue;
if (((Element)localList.get(i)).getType() == paramInt)
{
localList.remove(i);
if (localList.size() != 0)
continue;
this.data.remove(paramName);
continue;
}
}
finally
{
}
i++;
continue;
label114: if (((Element)localObject2).getType() == paramInt)
this.data.remove(paramName);
}
}
private void removeName(Name paramName)
{
try
{
this.data.remove(paramName);
return;
}
finally
{
localObject = finally;
throw localObject;
}
}
public SetResponse addMessage(Message paramMessage)
{
boolean bool1 = paramMessage.getHeader().getFlag(5);
Record localRecord = paramMessage.getQuestion();
int i = paramMessage.getHeader().getRcode();
int j = 0;
SetResponse localSetResponse = null;
boolean bool2 = Options.check("verbosecache");
if (((i != 0) && (i != 3)) || (localRecord == null))
return null;
Name localName1 = localRecord.getName();
int k = localRecord.getType();
int m = localRecord.getDClass();
Object localObject = localName1;
HashSet localHashSet = new HashSet();
RRset[] arrayOfRRset1 = paramMessage.getSectionRRsets(1);
int n = 0;
if (n < arrayOfRRset1.length)
{
if (arrayOfRRset1[n].getDClass() != m);
while (true)
{
n++;
break;
int i10 = arrayOfRRset1[n].getType();
Name localName2 = arrayOfRRset1[n].getName();
int i11 = getCred(1, bool1);
if (((i10 == k) || (k == 255)) && (localName2.equals(localObject)))
{
addRRset(arrayOfRRset1[n], i11);
j = 1;
if (localObject == localName1)
{
if (localSetResponse == null)
localSetResponse = new SetResponse(6);
RRset localRRset5 = arrayOfRRset1[n];
localSetResponse.addRRset(localRRset5);
}
markAdditional(arrayOfRRset1[n], localHashSet);
}
else if ((i10 == 5) && (localName2.equals(localObject)))
{
addRRset(arrayOfRRset1[n], i11);
if (localObject == localName1)
{
RRset localRRset4 = arrayOfRRset1[n];
localSetResponse = new SetResponse(4, localRRset4);
}
localObject = ((CNAMERecord)arrayOfRRset1[n].first()).getTarget();
}
else if ((i10 == 39) && (((Name)localObject).subdomain(localName2)))
{
addRRset(arrayOfRRset1[n], i11);
if (localObject == localName1)
{
RRset localRRset3 = arrayOfRRset1[n];
localSetResponse = new SetResponse(5, localRRset3);
}
DNAMERecord localDNAMERecord = (DNAMERecord)arrayOfRRset1[n].first();
try
{
Name localName3 = ((Name)localObject).fromDNAME(localDNAMERecord);
localObject = localName3;
}
catch (NameTooLongException localNameTooLongException)
{
}
}
}
}
RRset[] arrayOfRRset2 = paramMessage.getSectionRRsets(2);
RRset localRRset1 = null;
RRset localRRset2 = null;
int i1 = 0;
if (i1 < arrayOfRRset2.length)
{
if ((arrayOfRRset2[i1].getType() == 6) && (((Name)localObject).subdomain(arrayOfRRset2[i1].getName())))
localRRset1 = arrayOfRRset2[i1];
while (true)
{
i1++;
break;
if ((arrayOfRRset2[i1].getType() == 2) && (((Name)localObject).subdomain(arrayOfRRset2[i1].getName())))
localRRset2 = arrayOfRRset2[i1];
}
}
int i6;
int i8;
label581: label588: RRset[] arrayOfRRset3;
int i3;
if (j == 0)
if (i == 3)
{
i6 = 0;
if ((i != 3) && (localRRset1 == null) && (localRRset2 != null))
break label655;
int i7 = getCred(2, bool1);
SOARecord localSOARecord = null;
if (localRRset1 != null)
localSOARecord = (SOARecord)localRRset1.first();
addNegative((Name)localObject, i6, localSOARecord, i7);
if (localSetResponse == null)
{
if (i != 3)
break label649;
i8 = 1;
localSetResponse = SetResponse.ofType(i8);
}
arrayOfRRset3 = paramMessage.getSectionRRsets(3);
i3 = 0;
label598: if (i3 >= arrayOfRRset3.length)
break label772;
int i4 = arrayOfRRset3[i3].getType();
if ((i4 == 1) || (i4 == 28) || (i4 == 38))
break label734;
}
while (true)
{
i3++;
break label598;
i6 = k;
break;
label649: i8 = 2;
break label581;
label655: int i9 = getCred(2, bool1);
addRRset(localRRset2, i9);
markAdditional(localRRset2, localHashSet);
if (localSetResponse != null)
break label588;
localSetResponse = new SetResponse(3, localRRset2);
break label588;
if ((i != 0) || (localRRset2 == null))
break label588;
int i2 = getCred(2, bool1);
addRRset(localRRset2, i2);
markAdditional(localRRset2, localHashSet);
break label588;
label734: if (localHashSet.contains(arrayOfRRset3[i3].getName()))
{
int i5 = getCred(3, bool1);
addRRset(arrayOfRRset3[i3], i5);
}
}
label772: if (bool2)
System.out.println("addMessage: " + localSetResponse);
return localSetResponse;
}
public void addNegative(Name paramName, int paramInt1, SOARecord paramSOARecord, int paramInt2)
{
long l = 0L;
if (paramSOARecord != null);
try
{
l = paramSOARecord.getTTL();
Element localElement = findElement(paramName, paramInt1, 0);
if (l == 0L)
if ((localElement != null) && (localElement.compareCredibility(paramInt2) <= 0))
removeElement(paramName, paramInt1);
while (true)
{
return;
if ((localElement != null) && (localElement.compareCredibility(paramInt2) <= 0))
localElement = null;
if (localElement == null)
addElement(paramName, new NegativeElement(paramName, paramInt1, paramSOARecord, paramInt2, this.maxncache));
}
}
finally
{
}
}
public void addRRset(RRset paramRRset, int paramInt)
{
while (true)
{
try
{
long l = paramRRset.getTTL();
Name localName = paramRRset.getName();
int i = paramRRset.getType();
Element localElement = findElement(localName, i, 0);
if (l == 0L)
{
if ((localElement != null) && (localElement.compareCredibility(paramInt) <= 0))
removeElement(localName, i);
return;
}
if ((localElement != null) && (localElement.compareCredibility(paramInt) <= 0))
localElement = null;
if (localElement != null)
continue;
if ((paramRRset instanceof CacheRRset))
{
localCacheRRset = (CacheRRset)paramRRset;
addElement(localName, localCacheRRset);
continue;
}
}
finally
{
}
CacheRRset localCacheRRset = new CacheRRset(paramRRset, paramInt, this.maxcache);
}
}
public void addRecord(Record paramRecord, int paramInt, Object paramObject)
{
while (true)
{
Element localElement;
try
{
Name localName = paramRecord.getName();
int i = paramRecord.getRRsetType();
boolean bool = Type.isRR(i);
if (!bool)
return;
localElement = findElement(localName, i, paramInt);
if (localElement == null)
{
addRRset(new CacheRRset(paramRecord, paramInt, this.maxcache), paramInt);
continue;
}
}
finally
{
}
if ((localElement.compareCredibility(paramInt) == 0) && ((localElement instanceof CacheRRset)))
((CacheRRset)localElement).addRR(paramRecord);
}
}
public void clearCache()
{
try
{
this.data.clear();
return;
}
finally
{
localObject = finally;
throw localObject;
}
}
public RRset[] findAnyRecords(Name paramName, int paramInt)
{
return findRecords(paramName, paramInt, 2);
}
public RRset[] findRecords(Name paramName, int paramInt)
{
return findRecords(paramName, paramInt, 3);
}
public void flushName(Name paramName)
{
removeName(paramName);
}
public void flushSet(Name paramName, int paramInt)
{
removeElement(paramName, paramInt);
}
public int getDClass()
{
return this.dclass;
}
public int getMaxCache()
{
return this.maxcache;
}
public int getMaxEntries()
{
return this.data.getMaxSize();
}
public int getMaxNCache()
{
return this.maxncache;
}
public int getSize()
{
return this.data.size();
}
protected SetResponse lookup(Name paramName, int paramInt1, int paramInt2)
{
while (true)
{
int i;
int j;
int k;
Name localName;
Object localObject3;
int m;
Object localObject2;
int i1;
Element localElement3;
try
{
i = paramName.labels();
j = i;
break label434;
if (k == 0)
break label480;
localName = Name.root;
localObject3 = this.data.get(localName);
if (localObject3 == null)
{
break label462;
localName = new Name(paramName, i - j);
continue;
}
if ((m != 0) && (paramInt1 == 255))
{
localObject2 = new SetResponse(6);
Element[] arrayOfElement = allElements(localObject3);
int n = 0;
i1 = 0;
if (i1 < arrayOfElement.length)
{
Element localElement5 = arrayOfElement[i1];
if (localElement5.expired())
{
removeElement(localName, localElement5.getType());
break label491;
}
if ((!(localElement5 instanceof CacheRRset)) || (localElement5.compareCredibility(paramInt2) < 0))
break label491;
((SetResponse)localObject2).addRRset((CacheRRset)localElement5);
n++;
break label491;
}
if (n <= 0)
break label351;
return localObject2;
}
if (m == 0)
break label307;
localElement3 = oneElement(localName, localObject3, paramInt1, paramInt2);
if ((localElement3 != null) && ((localElement3 instanceof CacheRRset)))
{
localObject2 = new SetResponse(6);
((SetResponse)localObject2).addRRset((CacheRRset)localElement3);
continue;
}
}
finally
{
}
if (localElement3 != null)
{
localObject2 = new SetResponse(2);
}
else
{
Element localElement4 = oneElement(localName, localObject3, 5, paramInt2);
if ((localElement4 != null) && ((localElement4 instanceof CacheRRset)))
{
localObject2 = new SetResponse(4, (CacheRRset)localElement4);
continue;
label307: Element localElement1 = oneElement(localName, localObject3, 39, paramInt2);
if ((localElement1 != null) && ((localElement1 instanceof CacheRRset)))
localObject2 = new SetResponse(5, (CacheRRset)localElement1);
}
else
{
label351: Element localElement2 = oneElement(localName, localObject3, 2, paramInt2);
if ((localElement2 != null) && ((localElement2 instanceof CacheRRset)))
{
localObject2 = new SetResponse(3, (CacheRRset)localElement2);
}
else if ((m != 0) && (oneElement(localName, localObject3, 0, paramInt2) != null))
{
localObject2 = SetResponse.ofType(1);
continue;
label421: SetResponse localSetResponse = SetResponse.ofType(0);
localObject2 = localSetResponse;
continue;
label434: if (j >= 1)
if (j != 1)
break label468;
}
else
{
label462: label468: for (k = 1; ; k = 0)
{
if (j != i)
break label474;
m = 1;
break;
j--;
break label434;
break label421;
}
label474: m = 0;
continue;
label480: if (m != 0)
{
localName = paramName;
continue;
label491: i1++;
}
}
}
}
}
}
public SetResponse lookupRecords(Name paramName, int paramInt1, int paramInt2)
{
return lookup(paramName, paramInt1, paramInt2);
}
public void setMaxCache(int paramInt)
{
this.maxcache = paramInt;
}
public void setMaxEntries(int paramInt)
{
this.data.setMaxSize(paramInt);
}
public void setMaxNCache(int paramInt)
{
this.maxncache = paramInt;
}
public String toString()
{
StringBuffer localStringBuffer = new StringBuffer();
try
{
Iterator localIterator = this.data.values().iterator();
while (localIterator.hasNext())
{
Element[] arrayOfElement = allElements(localIterator.next());
for (int i = 0; i < arrayOfElement.length; i++)
{
localStringBuffer.append(arrayOfElement[i]);
localStringBuffer.append("\n");
}
}
return localStringBuffer.toString();
}
finally
{
}
}
private static class CacheMap extends LinkedHashMap
{
private int maxsize = -1;
CacheMap(int paramInt)
{
super(0.75F, true);
this.maxsize = paramInt;
}
int getMaxSize()
{
return this.maxsize;
}
protected boolean removeEldestEntry(Map.Entry paramEntry)
{
return (this.maxsize >= 0) && (size() > this.maxsize);
}
void setMaxSize(int paramInt)
{
this.maxsize = paramInt;
}
}
private static class CacheRRset extends RRset
implements Cache.Element
{
private static final long serialVersionUID = 5971755205903597024L;
int credibility;
int expire;
public CacheRRset(RRset paramRRset, int paramInt, long paramLong)
{
super();
this.credibility = paramInt;
this.expire = Cache.limitExpire(paramRRset.getTTL(), paramLong);
}
public CacheRRset(Record paramRecord, int paramInt, long paramLong)
{
this.credibility = paramInt;
this.expire = Cache.limitExpire(paramRecord.getTTL(), paramLong);
addRR(paramRecord);
}
public final int compareCredibility(int paramInt)
{
return this.credibility - paramInt;
}
public final boolean expired()
{
return (int)(System.currentTimeMillis() / 1000L) >= this.expire;
}
public String toString()
{
StringBuffer localStringBuffer = new StringBuffer();
localStringBuffer.append(super.toString());
localStringBuffer.append(" cl = ");
localStringBuffer.append(this.credibility);
return localStringBuffer.toString();
}
}
private static abstract interface Element
{
public abstract int compareCredibility(int paramInt);
public abstract boolean expired();
public abstract int getType();
}
private static class NegativeElement
implements Cache.Element
{
int credibility;
int expire;
Name name;
int type;
public NegativeElement(Name paramName, int paramInt1, SOARecord paramSOARecord, int paramInt2, long paramLong)
{
this.name = paramName;
this.type = paramInt1;
long l = 0L;
if (paramSOARecord != null)
l = paramSOARecord.getMinimum();
this.credibility = paramInt2;
this.expire = Cache.limitExpire(l, paramLong);
}
public final int compareCredibility(int paramInt)
{
return this.credibility - paramInt;
}
public final boolean expired()
{
return (int)(System.currentTimeMillis() / 1000L) >= this.expire;
}
public int getType()
{
return this.type;
}
public String toString()
{
StringBuffer localStringBuffer = new StringBuffer();
if (this.type == 0)
localStringBuffer.append("NXDOMAIN " + this.name);
while (true)
{
localStringBuffer.append(" cl = ");
localStringBuffer.append(this.credibility);
return localStringBuffer.toString();
localStringBuffer.append("NXRRSET " + this.name + " " + Type.string(this.type));
}
}
}
}
| true
|
d5c25a69309c19d47db26d0217f358822cb62ec2
|
Java
|
MNicholasPro/simpleTestCode
|
/src/main/java/HashCode/testHashCode.java
|
UTF-8
| 1,089
| 3.125
| 3
|
[] |
no_license
|
package main.java.HashCode;
import java.util.Objects;
/**
* V1.0.0
* Created by zhoumingkai on 2017/1/20.
*/
public class testHashCode {
public static void main(String[] args){
String s = "OK";
StringBuilder sb = new StringBuilder("OK");
System.out.println(s.hashCode() + " " + sb.hashCode());
String t = new String("OK");
StringBuilder tb = new StringBuilder("OK");
System.out.println(t.hashCode() + " " + tb.hashCode());
String name = "zhoumingkai";
int a = Objects.hash(name);
StringBuilder b = new StringBuilder("zhoumingkai");
int c = Objects.hash(b);
System.out.println("a=" + a + "," + "c=" + c + "," + "b=" + b);
String aa = "abcde";
String bb = "abcde";
StringBuilder cc = new StringBuilder("abcde");
System.out.println("aa=" + aa + "," + "cc=" + cc + "," + "bb=" + bb);
System.out.println(aa.equals(bb) + "," + (aa.hashCode() == bb.hashCode()));
System.out.println(aa.equals(bb) + "," + (aa.hashCode() == cc.hashCode()));
}
}
| true
|
38deab141d96f6b2788f3dc43b7edd964c83d0bd
|
Java
|
hadipash/MScApp
|
/app/src/main/java/hk/hku/cs/msccompsc_app/MainPage/SliderIntro.java
|
UTF-8
| 930
| 2.125
| 2
|
[] |
no_license
|
package hk.hku.cs.msccompsc_app.MainPage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import hk.hku.cs.msccompsc_app.R;
public class SliderIntro extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.slider_main, container, false);
ImageView img = rootView.findViewById(R.id.slider_img);
img.setImageResource(R.drawable.slider1);
RelativeLayout rl = rootView.findViewById(R.id.slider_overlay);
rl.setVisibility(View.VISIBLE);
return rootView;
}
}
| true
|
2e4f8900217ea5c1833a9655e41d133bdbc84613
|
Java
|
yigitpirildak/SimpleJNADemo
|
/src/main/java/com/jna/example/TemperatureSamplerJnaInterface.java
|
UTF-8
| 428
| 2.171875
| 2
|
[] |
no_license
|
package com.jna.example;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface TemperatureSamplerJnaInterface extends Library {
TemperatureSamplerJnaInterface INSTANCE = (TemperatureSamplerJnaInterface) Native.load(System.getProperty("user.dir") + "/native/out/libtemperaturesampler.so", TemperatureSamplerJnaInterface.class);
float getTemperature();
TemperatureData getDetailedTemperature();
}
| true
|
2cf51e4c65603c783d52e80731258af5eafd8ee3
|
Java
|
hmbtl/Azerlotoreya
|
/app/src/main/java/nms/az/azerlotereya/activities/RulesActivity.java
|
UTF-8
| 3,145
| 1.976563
| 2
|
[] |
no_license
|
package nms.az.azerlotereya.activities;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import nms.az.azerlotereya.R;
import nms.az.azerlotereya.fragments.GameRulesFragment;
import nms.az.azerlotereya.fragments.GeneralRulesFragment;
public class RulesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_rules);
initToolbar();
initViewPagerAndTabs();
}
@Override
protected void onResume() {
super.onResume();
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
setTitle(getString(R.string.rules));
mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
mToolbar.setNavigationIcon(R.drawable.ic_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
private void initViewPagerAndTabs() {
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(pagerAdapter);
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.abc_fade_in, R.anim.slide_out_bottom);
}
private class PagerAdapter extends FragmentPagerAdapter {
private FragmentManager fm;
private FragmentTransaction ft;
public PagerAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new GameRulesFragment();
case 1:
return new GeneralRulesFragment();
default:
return new GameRulesFragment();
}
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.game_rules);
case 1:
return getString(R.string.general_rules);
}
return getString(R.string.game_rules);
}
@Override
public int getCount() {
return 2;
}
}
}
| true
|
756a04795c474ae141488cbfc4817b07a399012f
|
Java
|
SiteView/ECC8.13
|
/trunk/java.prj/ITSMCSharp2Java/Fusion.Api/Fusion/Api/Formatter.java
|
WINDOWS-1252
| 5,245
| 2.296875
| 2
|
[] |
no_license
|
package Fusion.Api;
/**
* @author Administrator
* @version 1.0
* @created 15--2010 14:44:33
*/
public class Formatter extends FusionAggregate {
public Formatter(){
}
public void finalize() throws Throwable {
super.finalize();
}
/**
*
* @param evalBundle
*/
public Formatter(Fusion.Api.EvaluationBundle evalBundle){
}
/**
*
* @param fusionObject
*/
public Formatter(Object fusionObject){
}
/**
*
* @param strName
*/
public int Counter(String strName){
return 0;
}
public BusinessObject CurBusinessObject(){
return null;
}
public Field CurField(){
return null;
}
public String GetFieldValue(){
return "";
}
/**
*
* @param strName
*/
public String GetFieldValue(String strName){
return "";
}
/**
*
* @param strRuleName
*/
public Fusion.Api.RuleDef GetRule(String strRuleName){
return null;
}
/**
*
* @param strValue
* @param iLength
*/
public static String Left(String strValue, int iLength){
return "";
}
/**
*
* @param strValue
*/
public static int Length(String strValue){
return 0;
}
/**
*
* @param strValue
* @param iTotalWidth
*/
public static String PadLeft(String strValue, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param cPaddingChar
* @param iTotalWidth
*/
public static String PadLeft(String strValue, char cPaddingChar, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param strPaddingStr
* @param iTotalWidth
*/
public static String PadLeft(String strValue, String strPaddingStr, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param iTotalWidth
*/
public static String PadRight(String strValue, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param cPaddingChar
* @param iTotalWidth
*/
public static String PadRight(String strValue, char cPaddingChar, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param strPaddingStr
* @param iTotalWidth
*/
public static String PadRight(String strValue, String strPaddingStr, int iTotalWidth){
return "";
}
/**
*
* @param strValue
* @param iLength
*/
public static String Right(String strValue, int iLength){
return "";
}
/**
*
* @param strValue
* @param cInsertChar
* @param iInterval
*/
public static String Split(String strValue, char cInsertChar, int iInterval){
return "";
}
/**
*
* @param strValue
* @param strInsertChars
* @param iInterval
*/
public static String Split(String strValue, String strInsertChars, int iInterval){
return "";
}
/**
*
* @param strValue
* @param cInsertChar
* @param iInterval
*/
public static String SplitLeft(String strValue, char cInsertChar, int iInterval){
return "";
}
/**
*
* @param strValue
* @param strInsertChars
* @param iInterval
*/
public static String SplitLeft(String strValue, String strInsertChars, int iInterval){
return "";
}
/**
*
* @param strValue
* @param cInsertChar
* @param iInterval
*/
public static String SplitRight(String strValue, char cInsertChar, int iInterval){
return "";
}
/**
*
* @param strValue
* @param strInsertChars
* @param iInterval
*/
public static String SplitRight(String strValue, String strInsertChars, int iInterval){
return "";
}
/**
*
* @param strValue
* @param iStartAt
*/
public static String SubString(String strValue, int iStartAt){
return "";
}
/**
*
* @param strValue
* @param iStartAt
* @param iLength
*/
public static String SubString(String strValue, int iStartAt, int iLength){
return "";
}
/**
*
* @param strName
*/
public String SystemFunction(String strName){
return "";
}
/**
*
* @param strName
*/
public String Token(String strName){
return "";
}
/**
*
* @param strValue
*/
public static String ToLower(String strValue){
return "";
}
/**
*
* @param bValue
*/
public static String ToString(boolean bValue){
return "";
}
/**
*
* @param dtValue
*/
public static String ToString(DateTime dtValue){
return "";
}
/**
*
* @param dValue
*/
public static String ToString(decimal dValue){
return "";
}
/**
*
* @param dValue
*/
public static String ToString(double dValue){
return "";
}
/**
*
* @param iValue
*/
public static String ToString(int iValue){
return "";
}
/**
*
* @param strValue
*/
public static String ToUpper(String strValue){
return "";
}
/**
*
* @param strValue
*/
public static String Trim(String strValue){
return "";
}
/**
*
* @param strValue
*/
public static String TrimEnd(String strValue){
return "";
}
/**
*
* @param strValue
*/
public static String TrimStart(String strValue){
return "";
}
private Fusion.BusinessLogic.Rules.Formatter WhoAmI(){
return null;
}
}
| true
|
e0b74ca1cc0ffc85f547645c7c2ac5c34ab497fa
|
Java
|
YuFei-Soft/Project-Manage
|
/src/pet/Duck.java
|
ISO-8859-7
| 238
| 2.46875
| 2
|
[] |
no_license
|
package pet;
public class Duck extends Pet {
public Duck() {
super();
}
public Duck(String name, int legNum) {
super(name, legNum);
}
@Override
public String getShot() {
return "¸¸****";
}
}
| true
|
4a082ed2e46961ea1bebab9f004d395c69524cbc
|
Java
|
nowonbun/Public_Portal_System
|
/PPS.Portal/src/main/java/entity/bean/CardBean.java
|
UTF-8
| 2,263
| 2.140625
| 2
|
[] |
no_license
|
package entity.bean;
import java.util.List;
import entity.SelectNode;
public class CardBean extends ObjectBean {
private String code;
private String name;
private String title;
private String description;
private String img;
private boolean hasImg;
private String icon;
private String color;
private String step;
private String type;
private int seq;
private String controller;
private String template;
private List<SelectNode> cardtypelist;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public boolean isHasImg() {
return hasImg;
}
public void setHasImg(boolean hasImg) {
this.hasImg = hasImg;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getStep() {
return step;
}
public void setStep(String step) {
this.step = step;
}
public String getController() {
return this.controller;
}
public void setController(String controller) {
this.controller = controller;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public List<SelectNode> getCardtypelist() {
return cardtypelist;
}
public void setCardtypelist(List<SelectNode> cardtypelist) {
this.cardtypelist = cardtypelist;
}
}
| true
|
676e277bf0317ccc5a1414c636d79268a9a5e963
|
Java
|
mahbubmukul/adtest
|
/app/src/main/java/com/example/acer/adtest/MainActivity.java
|
UTF-8
| 799
| 2.015625
| 2
|
[] |
no_license
|
package com.example.acer.adtest;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener{
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
| true
|
dbc9035a600ea7b0c27d84fa932a1ea8669dddc7
|
Java
|
JoinNova/baekjoon
|
/boj10430.java
|
UTF-8
| 325
| 2.890625
| 3
|
[] |
no_license
|
//boj10430 나머지
import java.util.*;
class Main{
public static void main(String arg[]){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
System.out.printf("%d\n%d\n%d\n%d",(a+b)%c,(a%c+b%c)%c,(a*b)%c,(a%c*b%c)%c);
}
}
| true
|
b45df744bdd18eea0998604f754ccc88f47dc9de
|
Java
|
DrunkenKiwwi/tp3
|
/Tp3/src/tp2_fxml/modele/FormesFactory.java
|
UTF-8
| 1,388
| 2.828125
| 3
|
[] |
no_license
|
package tp2_fxml.modele;
import tp2_fxml.exception.FormeException;
import tp2_fxml.exception.ZoneDessinException;
public class FormesFactory {
private int largeur = 0;
private int hauteur = 0;
public FormesFactory(int largeur, int hauteur) {
if (validerDimension(largeur) && validerDimension(hauteur)) {
setLargeur(largeur);
setHauteur(hauteur);
}
}
public int getLargeur() {
return largeur;
}
public void setLargeur(int largeur) {
this.largeur = largeur;
}
public int getHauteur() {
return hauteur;
}
public void setHauteur(int hauteur) {
this.hauteur = hauteur;
}
public Forme getInstance(DataFactory data) throws FormeException, ZoneDessinException {
Forme forme = null;
if (validerFormeDansZone(data.getLargeur(), data.getHauteur(), data.getPosX(), data.getPosY())){
forme = data.envoyerForme(data.getType());
} else {
throw new ZoneDessinException();
}
return forme;
}
private boolean validerDimension(int dim) {
return (dim > 0);
}
private boolean validerFormeDansZone(int largeur, int hauteur, int posX, int posY) {
return (validerX(largeur + posX) && validerY(hauteur + posY));
}
private boolean validerX(int x) {
return ((x > 0) && (x < this.getLargeur()));
}
private boolean validerY(int y) {
return ((y > 0) && (y < this.getHauteur()));
}
}
| true
|
b362bd1199a3a24df6452942a39a6036cada806d
|
Java
|
Koschara121/IIS
|
/src/main/java/IIS/config/ApplicationConfig.java
|
UTF-8
| 241
| 1.625
| 2
|
[] |
no_license
|
package IIS.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@ComponentScan(basePackages = "/IIS")
public class ApplicationConfig {
}
| true
|
fe89181fa6b09d590239108859b6d89b1e43683a
|
Java
|
mobanisto/gcc-bridge
|
/runtime/src/main/java/org/renjin/gcc/runtime/BooleanPtr.java
|
UTF-8
| 2,437
| 2.203125
| 2
|
[] |
no_license
|
/*
* Renjin : JVM-based interpreter for the R language for the statistical analysis
* Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.gnu.org/licenses/gpl-2.0.txt
*/
package org.renjin.gcc.runtime;
public class BooleanPtr extends AbstractPtr implements Ptr {
public static final BooleanPtr NULL = new BooleanPtr();
public final boolean[] array;
public final int offset;
public static BooleanPtr malloc(int bytes) {
return new BooleanPtr(new boolean[bytes]);
}
private BooleanPtr() {
array = null;
offset = 0;
}
public BooleanPtr(boolean[] array, int offset) {
this.array = array;
this.offset = offset;
}
public BooleanPtr(boolean... values) {
this.array = values;
this.offset = 0;
}
public boolean unwrap() {
return array[offset];
}
@Override
public boolean[] getArray() {
return array;
}
@Override
public int getOffsetInBytes() {
return offset;
}
@Override
public BooleanPtr realloc(int newSizeInBytes) {
return new BooleanPtr(Realloc.realloc(array, offset, newSizeInBytes));
}
@Override
public Ptr pointerPlus(int bytes) {
return new BooleanPtr(array, offset + bytes);
}
@Override
public byte getByte(int offset) {
return array[offset] ? (byte)1 : (byte)0;
}
@Override
public void setByte(int offset, byte value) {
array[offset] = (value != 0);
}
@Override
public int toInt() {
throw new UnsupportedOperationException("TODO");
}
@Override
public boolean isNull() {
return array == null && offset == 0;
}
public static BooleanPtr cast(Object voidPointer) {
if(voidPointer instanceof MallocThunk) {
return ((MallocThunk) voidPointer).booleanPtr();
}
return (BooleanPtr) voidPointer;
}
}
| true
|
0e70a579cf546dd136bf4bc6ac023e1d97adba92
|
Java
|
Purnama88/PurEff
|
/src/main/java/net/purnama/pureff/service/PaymentInInvoiceSalesDraftService.java
|
UTF-8
| 2,904
| 1.929688
| 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 net.purnama.pureff.service;
import java.util.List;
import javax.transaction.Transactional;
import net.purnama.pureff.dao.PaymentInInvoiceSalesDraftDao;
import net.purnama.pureff.entity.CurrencyEntity;
import net.purnama.pureff.entity.PartnerEntity;
import net.purnama.pureff.entity.transactional.InvoiceSalesEntity;
import net.purnama.pureff.entity.transactional.draft.PaymentInDraftEntity;
import net.purnama.pureff.entity.transactional.draft.PaymentInInvoiceSalesDraftEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author Purnama
*/
@Service("paymentininvoicesalesdraftService")
public class PaymentInInvoiceSalesDraftService {
@Autowired
PaymentInInvoiceSalesDraftDao paymentininvoicesalesdraftDao;
@Transactional
public void addPaymentinInvoiceSalesDraft(PaymentInInvoiceSalesDraftEntity paymentininvoicesalesdraft) {
paymentininvoicesalesdraftDao.addPaymentInInvoiceSalesDraft(paymentininvoicesalesdraft);
}
@Transactional
public void updatePaymentinInvoiceSalesDraft(PaymentInInvoiceSalesDraftEntity paymentininvoicesalesdraft) {
paymentininvoicesalesdraftDao.updatePaymentInInvoiceSalesDraft(paymentininvoicesalesdraft);
}
@Transactional
public void deletePaymentinInvoiceSalesDraft(String id) {
paymentininvoicesalesdraftDao.deletePaymentInInvoiceSalesDraft(id);
}
@Transactional
public PaymentInInvoiceSalesDraftEntity getPaymentinInvoiceSalesDraft(String id) {
return paymentininvoicesalesdraftDao.getPaymentInInvoiceSalesDraft(id);
}
@Transactional
public PaymentInInvoiceSalesDraftEntity
getPaymentInInvoiceSalesDraftEntity(PaymentInDraftEntity paymentindraft,
InvoiceSalesEntity invoicesales){
return paymentininvoicesalesdraftDao.
getPaymentInInvoiceSalesDraftEntity(paymentindraft, invoicesales);
}
@Transactional
public List<PaymentInInvoiceSalesDraftEntity>
getPaymentInInvoiceSalesDraftEntityList(PaymentInDraftEntity paymentindraft){
return paymentininvoicesalesdraftDao.
getPaymentInInvoiceSalesDraftEntityList(paymentindraft);
}
@Transactional
public List<PaymentInInvoiceSalesDraftEntity>
getPaymentInInvoiceSalesDraftEntityList(PaymentInDraftEntity paymentindraft,
PartnerEntity partner, CurrencyEntity currency){
return paymentininvoicesalesdraftDao.
getPaymentInInvoiceSalesDraftEntityList(paymentindraft, partner, currency);
}
}
| true
|
cb690f0315160f1dd3255dff7962ccd8fab2c398
|
Java
|
ricky453/ContadorWIDGET
|
/app/src/main/java/a2018/ipam/widgetcontador/Wbotones.java
|
UTF-8
| 2,931
| 2.4375
| 2
|
[] |
no_license
|
package a2018.ipam.widgetcontador;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.widget.RemoteViews;
/**
* Implementation of App Widget functionality.
*/
public class Wbotones extends AppWidgetProvider {
private static String textUpdate;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static void updateAppWidgets(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, String text){
textUpdate = text;
for (int appWidgetId : appWidgetIds){
updateAppWidget(context, appWidgetManager, appWidgetId, textUpdate);
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, String text) {
Bundle option = appWidgetManager.getAppWidgetOptions(appWidgetId);
float ancho = option.getInt(appWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);//recibe el ancho del widget
int imagen1 = R.drawable.imgpequena;
int imagen2 = R.drawable.imgmediana;
int imagen3 = R.drawable.imggrande;
int imagen;
if(ancho < 200){
imagen = imagen1;
}else{
if (ancho < 300){
imagen = imagen2;
}else{
imagen = imagen3;
}
}
//intento para abrir la MainActivity
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wbotones);
views.setOnClickPendingIntent(R.id.imgvWidget,pendingIntent);//cuando se da click en el lblTitulo del widget se abrira la MainActivity
views.setImageViewResource(R.id.imgvWidget, imagen);
views.setTextViewText(R.id.lblNumero,text);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds){
UpdateService.startActionUpdateWidget(context);
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appwidgetManager, int appWidgetId, Bundle newOptions){
updateAppWidget(context, appwidgetManager, appWidgetId, textUpdate);
}
}
| true
|
a8efe597b3e5bee0654c98ac4130f2de765e95fa
|
Java
|
AhmedSM1/Movies-Application
|
/app/src/main/java/com/example/movies/popularmovies/UI/MainActivity.java
|
UTF-8
| 12,890
| 1.679688
| 2
|
[] |
no_license
|
package com.example.movies.popularmovies.UI;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movies.popularmovies.Adapters.MovieAdapter;
import com.example.movies.popularmovies.Database.MovieViewModel;
import com.example.movies.popularmovies.Database.ViewModelFactory;
import com.example.movies.popularmovies.Model.Movie;
import com.example.movies.popularmovies.R;
import com.example.movies.popularmovies.Utils.MyJobDispatcher;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.Trigger;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity{
private List<Movie> movies;
public static final String TAG = MainActivity.class.getName();
public static final String LIFE_CYCLE = "LIFE CYCLE";
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
public static final int RC_SIGN_IN = 1;
public static final String ANONYMOUS = "anonymous";
public ActionBar actionBar;
private String mUserID;
private MovieAdapter adapter;
private RecyclerView recyclerView;
private GridLayoutManager layoutManager;
private final String RECYCLER_POSITION_KEY = "recycler_position";
private int mPosition = RecyclerView.NO_POSITION;
private static Bundle mBundleState;
// job dispatcher
public static final String JOB_TAG = "jobTag";
//notification
int INTERVAL_MINUTES = 1;
int INTERVAL_SECONDS = (int) (TimeUnit.MINUTES.toSeconds(INTERVAL_MINUTES)) ;
int SYNC_FLEXTIME_SECONDS = INTERVAL_SECONDS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.getDisplayOptions();
actionBar.setTitle(getSortValue());
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(getString(R.string.banner_ad_unit_id));
adView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
Log.d(LIFE_CYCLE,"onCreate");
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//user is signed in
Log.d(TAG, "onAuthStateChanged: " +user.getDisplayName());
mUserID = user.getUid();
//if user is signed in generate Movies and pass in the username
generateMovies(mUserID);
}else {
onSignedOutCleanUp();
//user is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build()))
.build(), RC_SIGN_IN);
}
}
};
//when the device is rotated the adapter will be null so we have to init in onCreate
adapter = new MovieAdapter(getApplicationContext(),movies);
recyclerView = findViewById(R.id.recyclerView);
notificationsJobScheduler(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
if (resultCode == RESULT_OK){
Toast.makeText(MainActivity.this,R.string.sign_in,Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(MainActivity.this,R.string.sign_in_can,Toast.LENGTH_SHORT).show();
finish(); }
}
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
// Restore RecyclerView state
if (mBundleState != null) {
mPosition = mBundleState.getInt(RECYCLER_POSITION_KEY);
if (mPosition == RecyclerView.NO_POSITION) mPosition = 0;
// Scroll the RecyclerView to mPosition
recyclerView.smoothScrollToPosition(mPosition);
}
}
@Override
protected void onPause() {
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
// Save RecyclerView state
mBundleState = new Bundle();
if (layoutManager != null){
mPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
mBundleState.putInt(RECYCLER_POSITION_KEY, mPosition);
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (recyclerView != null && layoutManager != null){
outState.putInt(RECYCLER_POSITION_KEY,layoutManager.findFirstCompletelyVisibleItemPosition());
}
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
// Restore RecyclerView state
if (savedInstanceState.containsKey(RECYCLER_POSITION_KEY)) {
mPosition = savedInstanceState.getInt(RECYCLER_POSITION_KEY);
if (mPosition == RecyclerView.NO_POSITION) mPosition = 0;
// Scroll the RecyclerView to mPosition
recyclerView.smoothScrollToPosition(mPosition);
}
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_sorting, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
return true;
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this);
}
return super.onOptionsItemSelected(item);
}
private String getSortValue() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPreferences.getString(getString(R.string.sort_by_key), getString(R.string.sort_popularity));
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(LIFE_CYCLE, "onRestart ");
if (movies != null){
movies.clear();
}
getSortValue();
mUserID = FirebaseAuth.getInstance().getUid();
generateMovies(mUserID);
actionBar.setTitle(getSortValue());
}
private void onSignedOutCleanUp(){
mUserID = ANONYMOUS;
if (movies!= null){
movies.clear();
}
}
private void generateMovies(String mUserID){
Log.d(LIFE_CYCLE,"GENERATE ");
movies = new ArrayList<>();
final ViewModelFactory modelFactory = new ViewModelFactory(mUserID,this);
MovieViewModel viewModel = ViewModelProviders.of(this,modelFactory).get(MovieViewModel.class);
if (getSortValue().equals(getString(R.string.sort_by_favorites))) {
if (!viewModel.getLiveData().hasActiveObservers()) viewModel.getLiveData().observe(this, new Observer<DataSnapshot>() {
@Override
public void onChanged(DataSnapshot dataSnapshot) {
Log.d(TAG,dataSnapshot.toString());
movies.clear();
for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
//Movie movie = itemSnapShot.getValue(Movie.class);
Log.d(TAG, "itemSnapShot = " + itemSnapShot.getValue());
for (DataSnapshot data :itemSnapShot.getChildren()) {
Movie movie = data.getValue(Movie.class);
Log.d(TAG, movie.title+"data = " + data.child("title").getValue());
movies.add(movie);
}
adapter.notifyDataSetChanged();
}
Log.d(TAG, "movies list: "+movies.size());
}
});
} else if (getSortValue().equals(getString(R.string.sort_popularity))){
viewModel.getMovies( getString(R.string.sort_popularity) ).observe(this, new Observer<List<Movie>>() {
@Override
public void onChanged(@Nullable List<Movie> moviesModels) {
movies.clear();
if (moviesModels != null) {
movies.addAll(moviesModels);
adapter.notifyDataSetChanged();
}
}
});
}else if (getSortValue().equals(getString(R.string.sort_top_rated))){
viewModel.getMovies(getString(R.string.sort_top_rated)).observe(this, new Observer<List<Movie>>() {
@Override
public void onChanged(@Nullable List<Movie> moviesModels) {
movies.clear();
if (moviesModels != null) {
movies.addAll(moviesModels);
Log.d(TAG,"Top rated movies inserted");
adapter.notifyDataSetChanged();
}
}
});
}
recyclerView = findViewById(R.id.recyclerView);
// Calling the Adapter object and setting it to the recycler view.
adapter = new MovieAdapter(this, movies);
recyclerView.setAdapter(adapter);
layoutManager = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(layoutManager);
adapter.notifyDataSetChanged();
}
private void notificationsJobScheduler(Context context){
//Schedule a job to send a notification
GooglePlayDriver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher firebaseJobDispatcher = new FirebaseJobDispatcher(driver);
Job job = firebaseJobDispatcher.newJobBuilder()
.setService(MyJobDispatcher.class)
.setTag(JOB_TAG)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(
Trigger.executionWindow(
INTERVAL_SECONDS,
INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS
)
)
.setReplaceCurrent(true)
.build();
firebaseJobDispatcher.schedule(job);
}
}
| true
|
7caed69c4de3fc8503827d7bef680cff7308e93b
|
Java
|
sdgSnow/SdgDialog
|
/dialoglibrary/src/main/java/com/sdg/dialoglibrary/pop/NormalPop.java
|
UTF-8
| 2,564
| 2.46875
| 2
|
[] |
no_license
|
package com.sdg.dialoglibrary.pop;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.sdg.dialoglibrary.R;
public class NormalPop extends BasePop {
private String title;
private String message;
private String yes = "确定";
private String no = "取消";
private float width = 9/10f;
private Callback callback;
private TextView tv_title;
private TextView tv_message;
private TextView tv_no;
private TextView tv_yes;
private boolean backDismiss = false;//默认false,点击返回键不消失
public NormalPop(AppCompatActivity activity) {
super(activity,true,true);
}
@Override
public int getLayoutRes() {
return R.layout.dialog_normal;
}
@Override
public void init(View view) {
tv_title = view.findViewById(R.id.tv_title);
tv_message = view.findViewById(R.id.tv_message);
tv_no = view.findViewById(R.id.tv_no);
tv_yes = view.findViewById(R.id.tv_yes);
tv_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
callback.yes();
}
});
tv_no.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
callback.no();
}
});
setKeyDownDismiss(backDismiss);
}
public NormalPop setTitle(String title) {
this.title = title;
tv_title.setText(title);
return this;
}
public NormalPop setMessage(String message) {
this.message = message;
tv_message.setText(message);
return this;
}
public NormalPop setBackDismiss(boolean backDismiss) {
this.backDismiss = backDismiss;
return this;
}
public NormalPop setYes(String yes) {
this.yes = yes;
tv_yes.setText(yes);
return this;
}
public NormalPop setNo(String no) {
this.no = no;
tv_no.setText(no);
return this;
}
public NormalPop setWidth(float width) {
if(width > 1){
this.width = 9/10f;
return this;
}
this.width = width;
return this;
}
public NormalPop setCallback(Callback callback) {
this.callback = callback;
return this;
}
public interface Callback {
void yes();
void no();
}
}
| true
|
40928159f6c6ff7b49e9c670cd8706b31b94c6f6
|
Java
|
yyi/console-admin
|
/console-web/src/main/java/com/founder/console/web/ConsoleWebApplication.java
|
UTF-8
| 2,317
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.founder.console.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
@SpringBootApplication(exclude = DispatcherServletAutoConfiguration.class)
@ComponentScan(
basePackages = "com",
excludeFilters =
@ComponentScan.Filter({Controller.class, ControllerAdvice.class}))
@EnableAspectJAutoProxy(proxyTargetClass = true,exposeProxy = true)
@EnableScheduling
@EnableRedisHttpSession
public class ConsoleWebApplication {
public static void main(String[] args) {
SpringApplication.run(ConsoleWebApplication.class, args);
}
// @Override
// public void onStartup(ServletContext container) throws ServletException {
//
// AnnotationConfigWebApplicationContext webContext =
// new AnnotationConfigWebApplicationContext();
// webContext.register(WebConfig.class);
// ServletRegistration.Dynamic dispatcher = container.addServlet(
// "springWebDispatcher", new DispatcherServlet(webContext)
// );
// dispatcher.setLoadOnStartup(1);
// dispatcher.setMultipartConfig(new MultipartConfigElement(
// null, 20_971_520L, 41_943_040L, 512_000
// ));
// dispatcher.addMapping("/");
//
// AnnotationConfigWebApplicationContext restContext =
// new AnnotationConfigWebApplicationContext();
// restContext.register(AjaxConfig.class);
// DispatcherServlet servlet = new DispatcherServlet(restContext);
// servlet.setDispatchOptionsRequest(true);
// dispatcher = container.addServlet(
// "springRestDispatcher", servlet
// );
// dispatcher.setLoadOnStartup(2);
// dispatcher.addMapping("/rest/*");
//
// }
}
| true
|
7eaa583378cbdafd4f7be5707fca1c9b2f42b325
|
Java
|
iacdingping/shanglvka
|
/shanglvka-core/src/main/java/com/slk/core/manager/mp/WeixinUserManager.java
|
UTF-8
| 2,778
| 2.0625
| 2
|
[] |
no_license
|
package com.slk.core.manager.mp;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.slk.core.PageList;
import com.slk.core.PageQuery;
import com.slk.core.dao.mp.WeixinUserDao;
import com.slk.core.entity.mp.WeixinUser;
import com.slk.core.query.mp.WeixinUserQuery;
import com.thinkgem.jeesite.common.utils.StringUtils;
/**
*
* @author dingp email:dingp@51box.cn
* @version 1.0
* @since 1.0
* */
@Service
@Transactional
public class WeixinUserManager {
@Autowired
private WeixinUserDao userDao;
/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写 */
public void setUserDao(WeixinUserDao dao) {
this.userDao = dao;
}
/**
* 创建User
**/
public WeixinUser save(WeixinUser user) {
Assert.notNull(user,"'user' must be not null");
user.setCreateDate(new Date());
user.setDelFlag(0);
user.setQueried(false);
this.userDao.save(user);
return user;
}
/**
* 更新User
**/
public WeixinUser update(WeixinUser user) {
Assert.notNull(user,"'user' must be not null");
user.setUpdateDate(new Date());
this.userDao.update(user);
return user;
}
/**
* 设置员工
**/
public void setStaff(java.lang.Long id) {
WeixinUser user = getById(id);
if (user.getIsStaff()) {
user.setIsStaff(false);
} else {
user.setIsStaff(true);
}
this.userDao.update(user);
}
/**
* 根据ID得到User
**/
public WeixinUser getById(java.lang.Long id) {
return this.userDao.getById(id);
}
/**
* 统计总数User
**/
public Long count(PageQuery query) {
return userDao.count(query);
}
/**
* list User
**/
public List<WeixinUser> list(PageQuery query) {
return userDao.list(query);
}
/**
* 分页查询: User
**/
@Transactional(readOnly = true)
public PageList<WeixinUser> findPage(WeixinUserQuery query) {
Assert.notNull(query, "'query' must be not null");
return new PageList<WeixinUser>(userDao.findPage(query),
query.getPage(), query.getPageSize(), count(query));
}
public WeixinUser getbyPlatformCode(String fromUserName) {
WeixinUserQuery query = new WeixinUserQuery();
query.setPlatformCode(fromUserName);
List<WeixinUser> lists = list(query);
return lists.isEmpty() ? null : lists.get(0);
}
public void cancelAttentionUser(String fromUserName) {
userDao.cancelAttentionUser(fromUserName);
}
public boolean exists(String fromUserName) {
WeixinUserQuery query = new WeixinUserQuery();
query.setPlatformCode(fromUserName);
return count(query) > 0;
}
}
| true
|
cb82aed1b40c868485d7ad3bd353db94ef86a406
|
Java
|
SuprasannaBhaumik/letscode
|
/src/main/java/com/learn/code/RomanToInteger.java
|
UTF-8
| 2,627
| 3.640625
| 4
|
[
"Apache-2.0"
] |
permissive
|
package com.learn.code;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class RomanToInteger {
public static void main(String[] args) {
System.out.println(RomanToInteger.romanToInt("MCMXCIV"));
}
public static Map<String, Integer> getMap () {
Map<String, Integer> romanMap = new HashMap<>();
romanMap.put("I", 1 );
romanMap.put("IV", 4);
romanMap.put("V", 5);
romanMap.put("IX", 9);
romanMap.put("X", 10);
romanMap.put("XL", 40);
romanMap.put("L", 50);
romanMap.put("XC", 90);
romanMap.put("C", 100);
romanMap.put("CD", 400);
romanMap.put("D", 500);
romanMap.put("CM", 900);
romanMap.put("M", 1000);
return romanMap;
}
public static int romanToInt(String s) {
Map<String, Integer> romanMap = getMap();
if(romanMap.containsKey(s)) {
return romanMap.get(s);
}
char[] charArray = s.toCharArray();
int i = 0;
int count = 0;
while(i<charArray.length) {
if(charArray[i] == 'I' && i < charArray.length - 1) {
if(charArray[i+1] == 'V' || charArray[i+1] == 'X') {
count += romanMap.get(Character.toString(charArray[i]) + Character.toString(charArray[i+1]));
i+=2;
} else {
count += romanMap.get(Character.toString(charArray[i]));
i++;
}
} else if (charArray[i] == 'X' && i < charArray.length - 1) {
if(charArray[i+1] == 'L' || charArray[i+1] == 'C') {
count += romanMap.get(Character.toString(charArray[i]) + Character.toString(charArray[i+1]));
i+=2;;
} else {
count += romanMap.get(Character.toString(charArray[i]));
i++;
}
} else if (charArray[i] == 'C' && i < charArray.length - 1) {
if(charArray[i+1] == 'D' || charArray[i+1] == 'M') {
count += romanMap.get(Character.toString(charArray[i]) + Character.toString(charArray[i+1]));
i+=2;
} else {
count += romanMap.get(Character.toString(charArray[i]));
i++;
}
} else {
count += romanMap.get(Character.toString(charArray[i]));
i++;
}
}
return count;
}
}
| true
|
8823557c8b0add730f3b358f3ef861c4b622fcd0
|
Java
|
zhangqiangoffice/ace
|
/src/com/lyq/action/TestAction.java
|
UTF-8
| 1,017
| 2.28125
| 2
|
[] |
no_license
|
package com.lyq.action;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
@SuppressWarnings("unchecked")
public TestAction(){
ActionContext context = ActionContext.getContext();
request = (Map<String, Object>)context.get("request");
session = context.getSession();
application = context.getApplication();
}
public String execute() throws Exception{
String re = "request info";
String se = "sessiont info";
String ap = "application info";
request.put("info", re);
session.put("info", se);
application.put("info", ap);
String r = request.get("info").toString();
String s = session.get("info").toString();
String a = application.get("info").toString();
Thread.sleep(1000);
return SUCCESS;
}
}
| true
|
05821b696a9e0735b18f25cacb1fb57ade0a7c8c
|
Java
|
Bhushan-CPatil/NMMCBirthdayWishes
|
/app/src/main/java/com/ornettech/qcandbirthdaywishes/utility/SendSMSWhatsApp.java
|
UTF-8
| 9,128
| 2.078125
| 2
|
[] |
no_license
|
package com.ornettech.qcandbirthdaywishes.utility;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import androidx.core.app.ActivityCompat;
import android.telephony.PhoneNumberUtils;
import android.widget.Toast;
import java.io.File;
import java.net.URLEncoder;
/**
* Created by New on 12/07/2017.
*/
public class SendSMSWhatsApp {
public static String SMS = "SMS";
public static String WHATSAPP = "WHP";
// public static void dialogSMS(final Context context,
// final String mob, String name,
// final String type) {
//
// final Dialog myDialog = new Dialog(context);
// myDialog.setContentView(R.layout.message_dialogbox);
// myDialog.setCancelable(false);
//
// Button sendsms = myDialog.findViewById(R.id.btn_sendsms);
// Button btncancel = myDialog.findViewById(R.id.btn_cnclsms);
// TextView txtmob = myDialog.findViewById(R.id.txtmsg_mob);
// TextView txtname = myDialog.findViewById(R.id.txtmsg_fullName);
//
// txtmob.setText(mob);
// txtname.setText(name);
//
// myDialog.show();
// btncancel.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// myDialog.cancel();
// }
// });
//
// sendsms.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// EditText edttext = myDialog.findViewById(R.id.edt_txtmsg);
// String smsText = edttext.getText().toString().trim();
//
// String msg_mob = chkMobNo(mob);
// String msg_sms = chkSMS(smsText);
//
// if (msg_mob.length() > 0)
// Toast.makeText(context, msg_mob, Toast.LENGTH_LONG).show();
//
// else if (msg_sms.length() > 0)
// Toast.makeText(context, msg_sms, Toast.LENGTH_LONG).show();
//
// else {
//
// String msg = "";
//
// if(type.contentEquals("WHP"))
// msg = sendWhatsApp(context, mob, smsText);
//
// else if(type.contentEquals("SMS"))
// msg = sendSMS(mob, smsText);
//
// Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
// myDialog.dismiss();
// }
// }
// });
// }
//
public static void sentToWhatsapp(Context mycontext, File imageurl, String mobno, String msg){
Uri imgUri = Uri.parse(imageurl.getAbsolutePath());
String smsNumber = "91"+mobno;
boolean isWhatsappInstalled = whatsappInstalledOrNot(mycontext,"com.whatsapp");
if (isWhatsappInstalled) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker"));//"com.whatsapp.Conversation"
//sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/*");
sendIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net");
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.putExtra(Intent.EXTRA_TEXT, msg);
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mycontext.startActivity(sendIntent);
} else {
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
Toast.makeText(mycontext, "WhatsApp not Installed",
Toast.LENGTH_SHORT).show();
mycontext.startActivity(goToMarket);
}
}
public static String sendWhatsApp(Context context, String number, String msg){
String wh_msg = "";
boolean isWhatsappInstalled = whatsappInstalledOrNot(context, "com.whatsapp");
if (isWhatsappInstalled) {
if(number.length()==10) {
PackageManager packageManager = context.getPackageManager();
Intent i = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="
+ "+91" + number + "&text=" + URLEncoder.encode(msg, "UTF-8");
i.setPackage("com.whatsapp");
i.setData(Uri.parse(url));
if (i.resolveActivity(packageManager) != null)
context.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}else{
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
if(msg.length()>65536){
whatsappIntent.putExtra(Intent.EXTRA_TEXT, msg.substring(0,65536));
}else{
whatsappIntent.putExtra(Intent.EXTRA_TEXT, msg);
}
whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(whatsappIntent);
}catch (Exception e){
Toast.makeText(context, "Error while opening whatsapp !", Toast.LENGTH_SHORT).show();
}
}
} else {
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
wh_msg = "WhatsApp not Installed";
context.startActivity(goToMarket);
}
return wh_msg;
}
private static boolean whatsappInstalledOrNot(Context context, String uri) {
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
public static void callMobNo(Context context, String mob) {
String msg_mob = chkMobNo(mob);
if (msg_mob.length() == 0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + mob));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
context.startActivity(callIntent);
}else{
Toast.makeText(context,msg_mob, Toast.LENGTH_LONG).show();
}
}
// public static String sendSMS(String mobno, String text) {
//
// String msg = "";
// try {
// SmsManager smsdiv = SmsManager.getDefault();
// ArrayList<String> parts = smsdiv.divideMessage(text);
// smsdiv.sendMultipartTextMessage( mobno,null, parts,
// null, null);
//
// msg = "SMS Sent.!";
// } catch (Exception e) {
// msg = "SMS Not Sent.!";
// e.toString();
// }
//
// return msg;
// }
public static String chkMobNo(String mobno){
String msg = "";
if( mobno != null && mobno.length() == 0 )
msg = "Mobile No Required..!";
return msg;
}
public static String chkSMS(String sms){
String msg = "";
if( sms != null && sms.length() == 0 )
msg = "Enter text to send sms";
return msg;
}
public static void dialMobNo(Context context, String mob) {
String msg_mob = chkMobNo(mob);
if (msg_mob.length() == 0) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + mob));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
context.startActivity(callIntent);
}else{
Toast.makeText(context,msg_mob, Toast.LENGTH_LONG).show();
}
}
// public void sendMessage( Context context, String number, String msg) {
//
// String msg_mob = chkMobNo(number);
// String msg_sms = chkSMS(msg);
//
// if (msg_mob.length() > 0)
// Toast.makeText(context, msg_mob, Toast.LENGTH_LONG).show();
//
// else if (msg_sms.length() > 0)
// Toast.makeText(context, msg_sms, Toast.LENGTH_LONG).show();
//
// else {
// String sms_status = sendSMS(number, msg);
// Toast.makeText(context, sms_status, Toast.LENGTH_LONG).show();
// }
// }
}
| true
|
63368912c18e5a72288415a20492431d132983a2
|
Java
|
CosineLiao/HuskyNote
|
/app/src/main/java/husky/note/huskynote/model/Account.java
|
UTF-8
| 4,647
| 2.0625
| 2
|
[] |
no_license
|
package husky.note.huskynote.model;
import com.google.gson.annotations.SerializedName;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
import husky.note.huskynote.database.AppDataBase;
/**
* Created by Administrator on 2017/10/18.
*/
@Table(name = "Account", database = AppDataBase.class)
public class Account extends BaseModel
{
public static final int EDITOR_RICH_TEXT = 0;
public static final int EDITOR_MARKDOWN = 1;
@SerializedName("Ok")
boolean isOk;
@SerializedName("Msg")
String msg;
@Column(name = "id")
@PrimaryKey(autoincrement = true)
long localUserId;
@Column(name = "userId")
@SerializedName("UserId")
String userId;
@Column(name = "userName")
@SerializedName("Username")
String userName = "";
@Column(name = "email")
@SerializedName("Email")
String email = "";
@Column(name = "verified")
@SerializedName("Verified")
boolean verified;
@Column(name = "avatar")
@SerializedName("Avatar")
String avatar = "";
@Column(name = "token")
@SerializedName("Token")
String accessToken = "";
@Column(name = "defaultEditor")
int defaultEditor = EDITOR_MARKDOWN;
@Column(name = "host")
@SerializedName("Host")
String host = "";
@Column(name = "noteUsn")
int noteUsn;
@Column(name = "notebookUsn")
int notebookUsn;
@Column(name = "lastUseTime")
long lastUseTime;
@Deprecated
@Column(name = "lastUsn")
@SerializedName("LastSyncUsn")
int lastSyncUsn;
public Account()
{
}
public boolean isOk()
{
return isOk;
}
public long getLocalUserId()
{
return localUserId;
}
public String getUserId()
{
return userId;
}
public String getUserName()
{
return userName;
}
public String getEmail()
{
return email;
}
public boolean isVerified()
{
return verified;
}
public String getAvatar()
{
return avatar;
}
public String getAccessToken()
{
return accessToken;
}
@Deprecated
public int getLastSyncUsn()
{
return lastSyncUsn;
}
public int getDefaultEditor()
{
return defaultEditor;
}
public String getHost()
{
return host;
}
public String getMsg()
{
return msg;
}
public void setAccessToken(String accessToken)
{
this.accessToken = accessToken;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public void setAvatar(String avatar)
{
this.avatar = avatar;
}
public void setHost(String host)
{
this.host = host;
}
@Deprecated
public void setLastUsn(int lastUsn)
{
this.lastSyncUsn = lastUsn;
}
public void setEmail(String email)
{
this.email = email;
}
public void setVerified(boolean verified)
{
this.verified = verified;
}
public void setDefaultEditor(int defaultEditor)
{
this.defaultEditor = defaultEditor;
}
public int getNoteUsn()
{
return noteUsn;
}
public int getNotebookUsn()
{
return notebookUsn;
}
public void setNoteUsn(int noteUsn)
{
this.noteUsn = noteUsn;
}
public void setNotebookUsn(int notebookUsn)
{
this.notebookUsn = notebookUsn;
}
public void updateLastUseTime()
{
lastUseTime = System.currentTimeMillis() / 1000;
}
public long getLastUseTime()
{
return lastUseTime;
}
public static Account getCurrent()
{
return null;
}
@Override
public String toString()
{
return "Account{" +
"isOk=" + isOk +
", msg='" + msg + '\'' +
", localUserId=" + localUserId +
", userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", email='" + email + '\'' +
", verified=" + verified +
", avatar='" + avatar + '\'' +
", accessToken='" + accessToken + '\'' +
", defaultEditor=" + defaultEditor +
", lastSyncUsn=" + lastSyncUsn +
", host='" + host + '\'' +
'}';
}
}
| true
|
7815b3d074415392edc753d9021b9fe31592bc8a
|
Java
|
OceanicSix/Java_Program
|
/src/study/beginning/test_main.java
|
UTF-8
| 136
| 1.5625
| 2
|
[] |
no_license
|
package study.beginning;
public class test_main {
public static void test_main() {
System.out.println("test main");
}
}
| true
|
19667a59b1c00ff60f28d2018c65d3922daedab2
|
Java
|
TailorRubick/sms-jeecg-boot
|
/jeecg-boot/jeecg-boot-module-activiti/src/main/java/org/jeecg/modules/activiti/listener/TimerListener.java
|
UTF-8
| 608
| 2.25
| 2
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
package org.jeecg.modules.activiti.listener;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
public class TimerListener implements TaskListener, ExecutionListener {
@Override
public void notify(DelegateTask delegateTask) {
System.out.println("TimerListener -- Task!");
}
@Override
public void notify(DelegateExecution execution) throws Exception {
System.out.println("TimerListener -- execution!");
}
}
| true
|
d6dbb3fbaf943e12ed032fcabc76009787e2aafa
|
Java
|
cvidalse/testEDD-AreasVerdes
|
/src/java/Modelo/Mapa.java
|
UTF-8
| 2,177
| 2.734375
| 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 Modelo;
import Datos.DAOAreasVerdes;
import Datos.DAOPoblacion;
import java.util.HashMap;
import java.util.List;
/**
*
* @author raguileoam
*/
public class Mapa {
private List<Poblacion> poblaciones;
private List<AreasVerdes> areasVerdes;
private HashMap<String, Double[]> interseccion;
private final Double[] coords={-38.736277, -72.590618};
public Mapa(String dir) {
this.poblaciones=DAOPoblacion.loadJSON(dir);
this.areasVerdes=DAOAreasVerdes.loadJSON(dir);
interseccion=interseccion();
}
public List<Poblacion> getPoblaciones() {
return poblaciones;
}
public HashMap<String, Double[]> getInterseccion() {
return interseccion;
}
public List<AreasVerdes> getAreasVerdes() {
return areasVerdes;
}
public Double[] getCoords() {
return coords;
}
/**
* Determina área total de areas verdes y poblacion total en un sector determinado.
* @return Hashmap con sector como clave y un array que contiene el area total de areas verdes
* y la poblacion total en un sector.
*/
public HashMap<String, Double[]> interseccion(){
HashMap<String, Double[]> hmap = new HashMap<>();
for(Poblacion poblacion:poblaciones){
for(AreasVerdes areaVerde:areasVerdes){
if(poblacion.getDistrito().equals(areaVerde.getSector())){
String sector=poblacion.getDistrito();
double numHabitantes=poblacion.getPersonas();
double numAreasVerdes=areaVerde.getArea();
if(hmap.containsKey(sector)){
numAreasVerdes+=hmap.get(sector)[0];
numHabitantes+=hmap.get(sector)[1];
}
Double[] values={numAreasVerdes,numHabitantes};
hmap.put(sector, values);
}
}
}
return hmap;
}
}
| true
|
9422ffa849e36b25b05f14f13d01fc364dd49268
|
Java
|
navychen2003/javen
|
/android/framework/trunk/src/org/javenstudio/cocoka/storage/CacheManager.java
|
UTF-8
| 2,952
| 2.53125
| 3
|
[] |
no_license
|
package org.javenstudio.cocoka.storage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import android.content.SharedPreferences;
import org.javenstudio.cocoka.android.ResourceHelper;
import org.javenstudio.cocoka.util.BlobCache;
import org.javenstudio.common.util.Logger;
public class CacheManager {
private static final Logger LOG = Logger.getLogger(CacheManager.class);
private static final String KEY_CACHE_UP_TO_DATE = "cache-up-to-date";
private final Map<String, BlobCache> sCacheMap =
new HashMap<String, BlobCache>();
private final Storage mStorage;
private boolean sOldCheckDone = false;
public CacheManager(Storage storage) {
mStorage = storage;
if (mStorage == null)
throw new NullPointerException("Storage is null");
}
public final Storage getStorage() { return mStorage; }
// Return null when we cannot instantiate a BlobCache, e.g.:
// there is no SD card found.
// This can only be called from data thread.
public BlobCache getCache(String filename,
int maxEntries, int maxBytes, int version) {
synchronized (sCacheMap) {
if (!sOldCheckDone) {
removeOldFilesIfNecessary();
sOldCheckDone = true;
}
BlobCache cache = sCacheMap.get(filename);
if (cache == null) {
String cacheDir = getStorage().getDirectory().getAbsolutePath();
String path = cacheDir + "/" + filename;
try {
cache = new BlobCache(path, maxEntries, maxBytes, false, version);
sCacheMap.put(filename, cache);
if (LOG.isInfoEnabled()) {
LOG.info("new BlobCache: path=" + path + " maxEntries=" + maxEntries
+ " maxBytes=" + maxBytes + " version=" + version);
}
} catch (IOException e) {
if (LOG.isErrorEnabled())
LOG.error("Cannot instantiate cache!", e);
}
}
return cache;
}
}
// Removes the old files if the data is wiped.
private void removeOldFilesIfNecessary() {
SharedPreferences pref = ResourceHelper.getSharedPreferences();
int n = 0;
try {
n = pref.getInt(KEY_CACHE_UP_TO_DATE, 0);
} catch (Throwable t) {
// ignore.
}
if (n != 0) return;
pref.edit().putInt(KEY_CACHE_UP_TO_DATE, 1).commit();
String cacheDir = getStorage().getDirectory().getAbsolutePath();
String prefix = cacheDir + "/";
BlobCache.deleteFiles(prefix + "imgcache");
BlobCache.deleteFiles(prefix + "rev_geocoding");
BlobCache.deleteFiles(prefix + "bookmark");
}
}
| true
|
6810bfb5432a5db2670e09ad11a5966fd3c1929d
|
Java
|
kvswim/kjv_datastructures
|
/Assignment 7/Assignment 7/MovetoFrontListSet.java
|
UTF-8
| 3,060
| 3.296875
| 3
|
[] |
no_license
|
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**Kyle Verdeyen.
* kverdey1@jhu.edu
* @author root
*
* @param <T>
*/
public class MovetoFrontListSet<T> implements Set<T> {
private static class Node<T> {
T data;
Node<T> next;
Node<T> prev;
}
private Node<T> head;
private int version;
private class SetIterator implements Iterator<T> {
private Node<T> current;
private int version;
SetIterator() {
this.current = MovetoFrontListSet.this.head;
this.version = MovetoFrontListSet.this.version;
}
private void checkVersion() throws ConcurrentModificationException {
if (this.version != MovetoFrontListSet.this.version) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
this.checkVersion();
return this.current != null;
}
@Override
public T next() {
this.checkVersion();
T t = this.current.data;
this.current = this.current.next;
return t;
}
@Override
public void remove() {
this.checkVersion();
throw new UnsupportedOperationException();
}
}
private Node<T> find(T t) {
for (Node<T> n = this.head; n != null; n = n.next) {
if (n.data.equals(t)) {
//connecting the surrounding nodes together
if (n == head) {
return n;
} else if (n.next == null) {
n.prev.next = null;
} else {
n.next.prev = n.prev;
n.prev.next = n.next;
}
n.next = this.head;
n.prev = null;
this.head.prev = n;
return n;
}
}
return null;
}
@Override
public void insert(T t) {
if (this.has(t)) {
return;
}
Node<T> n = new Node<T>();
n.data = t;
n.next = this.head;
n.prev = null;
if (this.head != null) {
this.head.prev = n;
}
this.head = n;
this.version++;
}
@Override
public void remove(T t) {
Node<T> position = null;
for (Node<T> n = this.head; n != null; n = n.next) {
if (n.data.equals(t)) {
position = n;
}
}
if (position == null) {
return;
}
if (position.next != null) {
position.next.prev = position.prev;
}
if (position.prev != null) {
position.prev.next = position.next;
} else {
this.head = position.next;
}
this.version++;
}
@Override
public boolean has(T t) {
return this.find(t) != null;
}
@Override
public Iterator<T> iterator() {
return new SetIterator();
}
}
| true
|
ce535d8caf150e907e20ff6341c5a14f81d7280d
|
Java
|
darrennight/MyMaterialDemo
|
/app/src/main/java/com/meterial/demo/commonActivity/KenBurns/MainActivity.java
|
UTF-8
| 1,856
| 2.1875
| 2
|
[] |
no_license
|
package com.meterial.demo.commonActivity.KenBurns;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.meterial.demo.R;
/**
* https://github.com/flavioarfaria/KenBurnsView
*/
public class MainActivity extends AppCompatActivity {
private static final int POS_SINGLE_IMG = 0;
private static final int POS_MULTI_IMG = 1;
private static final int POS_FROM_URL = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ken_burns);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.main_options, android.R.layout.simple_list_item_1);
final ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onListItemClick(parent, view, position, id);
}
});
}
protected void onListItemClick(AdapterView<?> parent, View v, int position, long id) {
switch (position) {
case POS_SINGLE_IMG:
startActivity(new Intent(this, SingleImageActivity.class));
break;
case POS_MULTI_IMG:
startActivity(new Intent(this, MultiImageActivity.class));
break;
case POS_FROM_URL:
startActivity(new Intent(this, FromURLActivity.class));
break;
}
}
}
| true
|
d4bdf80ebf360f52c2f14e4f95195b519ed2addb
|
Java
|
5l1v3r1/sony-headphones-hack
|
/base-dex2jar.jar.src--files/com/google/android/gms/common/api/GoogleApiClient.java
|
UTF-8
| 17,161
| 1.515625
| 2
|
[] |
no_license
|
package com.google.android.gms.common.api;
import android.accounts.Account;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import androidx.b.a;
import androidx.fragment.app.c;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.internal.zzba;
import com.google.android.gms.common.api.internal.zzce;
import com.google.android.gms.common.api.internal.zzci;
import com.google.android.gms.common.api.internal.zzcu;
import com.google.android.gms.common.api.internal.zzdh;
import com.google.android.gms.common.api.internal.zzi;
import com.google.android.gms.common.api.internal.zzt;
import com.google.android.gms.common.internal.Hide;
import com.google.android.gms.common.internal.zzbq;
import com.google.android.gms.common.internal.zzr;
import com.google.android.gms.common.internal.zzt;
import com.google.android.gms.internal.zzcyg;
import com.google.android.gms.internal.zzcyj;
import com.google.android.gms.internal.zzcyk;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public abstract class GoogleApiClient {
public static final int SIGN_IN_MODE_OPTIONAL = 2;
public static final int SIGN_IN_MODE_REQUIRED = 1;
private static final Set<GoogleApiClient> zzfsv = Collections.newSetFromMap(new WeakHashMap<GoogleApiClient, Boolean>());
public static void dumpAll(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString) {
// Byte code:
// 0: getstatic com/google/android/gms/common/api/GoogleApiClient.zzfsv : Ljava/util/Set;
// 3: astore #5
// 5: aload #5
// 7: monitorenter
// 8: iconst_0
// 9: istore #4
// 11: aload_0
// 12: invokestatic valueOf : (Ljava/lang/Object;)Ljava/lang/String;
// 15: ldc ' '
// 17: invokevirtual concat : (Ljava/lang/String;)Ljava/lang/String;
// 20: astore #6
// 22: getstatic com/google/android/gms/common/api/GoogleApiClient.zzfsv : Ljava/util/Set;
// 25: invokeinterface iterator : ()Ljava/util/Iterator;
// 30: astore #7
// 32: aload #7
// 34: invokeinterface hasNext : ()Z
// 39: ifeq -> 88
// 42: aload #7
// 44: invokeinterface next : ()Ljava/lang/Object;
// 49: checkcast com/google/android/gms/common/api/GoogleApiClient
// 52: astore #8
// 54: aload_2
// 55: aload_0
// 56: invokevirtual append : (Ljava/lang/CharSequence;)Ljava/io/PrintWriter;
// 59: ldc 'GoogleApiClient#'
// 61: invokevirtual append : (Ljava/lang/CharSequence;)Ljava/io/PrintWriter;
// 64: iload #4
// 66: invokevirtual println : (I)V
// 69: aload #8
// 71: aload #6
// 73: aload_1
// 74: aload_2
// 75: aload_3
// 76: invokevirtual dump : (Ljava/lang/String;Ljava/io/FileDescriptor;Ljava/io/PrintWriter;[Ljava/lang/String;)V
// 79: iload #4
// 81: iconst_1
// 82: iadd
// 83: istore #4
// 85: goto -> 32
// 88: aload #5
// 90: monitorexit
// 91: return
// 92: astore_0
// 93: aload #5
// 95: monitorexit
// 96: aload_0
// 97: athrow
// Exception table:
// from to target type
// 11 32 92 finally
// 32 79 92 finally
// 88 91 92 finally
// 93 96 92 finally
}
@Hide
public static Set<GoogleApiClient> zzahz() {
synchronized (zzfsv) {
return zzfsv;
}
}
public abstract ConnectionResult blockingConnect();
public abstract ConnectionResult blockingConnect(long paramLong, TimeUnit paramTimeUnit);
public abstract PendingResult<Status> clearDefaultAccountAndReconnect();
public abstract void connect();
public void connect(int paramInt) {
throw new UnsupportedOperationException();
}
public abstract void disconnect();
public abstract void dump(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString);
public abstract ConnectionResult getConnectionResult(Api<?> paramApi);
@Hide
public Context getContext() {
throw new UnsupportedOperationException();
}
@Hide
public Looper getLooper() {
throw new UnsupportedOperationException();
}
public abstract boolean hasConnectedApi(Api<?> paramApi);
public abstract boolean isConnected();
public abstract boolean isConnecting();
public abstract boolean isConnectionCallbacksRegistered(ConnectionCallbacks paramConnectionCallbacks);
public abstract boolean isConnectionFailedListenerRegistered(OnConnectionFailedListener paramOnConnectionFailedListener);
public abstract void reconnect();
public abstract void registerConnectionCallbacks(ConnectionCallbacks paramConnectionCallbacks);
public abstract void registerConnectionFailedListener(OnConnectionFailedListener paramOnConnectionFailedListener);
public abstract void stopAutoManage(c paramc);
public abstract void unregisterConnectionCallbacks(ConnectionCallbacks paramConnectionCallbacks);
public abstract void unregisterConnectionFailedListener(OnConnectionFailedListener paramOnConnectionFailedListener);
@Hide
public <C extends Api.zze> C zza(Api.zzc<C> paramzzc) {
throw new UnsupportedOperationException();
}
@Hide
public void zza(zzdh paramzzdh) {
throw new UnsupportedOperationException();
}
@Hide
public boolean zza(Api<?> paramApi) {
throw new UnsupportedOperationException();
}
@Hide
public boolean zza(zzcu paramzzcu) {
throw new UnsupportedOperationException();
}
@Hide
public void zzaia() {
throw new UnsupportedOperationException();
}
@Hide
public void zzb(zzdh paramzzdh) {
throw new UnsupportedOperationException();
}
@Hide
public <A extends Api.zzb, R extends Result, T extends com.google.android.gms.common.api.internal.zzm<R, A>> T zzd(T paramT) {
throw new UnsupportedOperationException();
}
@Hide
public <A extends Api.zzb, T extends com.google.android.gms.common.api.internal.zzm<? extends Result, A>> T zze(T paramT) {
throw new UnsupportedOperationException();
}
@Hide
public <L> zzci<L> zzt(L paramL) {
throw new UnsupportedOperationException();
}
public static final class Builder {
private final Context mContext;
private Looper zzalj;
private String zzehh;
private Account zzeho;
private final Set<Scope> zzfsw = new HashSet<Scope>();
private final Set<Scope> zzfsx = new HashSet<Scope>();
private int zzfsy;
private View zzfsz;
private String zzfta;
private final Map<Api<?>, zzt> zzftb = (Map<Api<?>, zzt>)new a();
private final Map<Api<?>, Api.ApiOptions> zzftc = (Map<Api<?>, Api.ApiOptions>)new a();
private zzce zzftd;
private int zzfte = -1;
private GoogleApiClient.OnConnectionFailedListener zzftf;
private GoogleApiAvailability zzftg = GoogleApiAvailability.getInstance();
private Api.zza<? extends zzcyj, zzcyk> zzfth = zzcyg.zzegv;
private final ArrayList<GoogleApiClient.ConnectionCallbacks> zzfti = new ArrayList<GoogleApiClient.ConnectionCallbacks>();
private final ArrayList<GoogleApiClient.OnConnectionFailedListener> zzftj = new ArrayList<GoogleApiClient.OnConnectionFailedListener>();
private boolean zzftk = false;
public Builder(Context param1Context) {
this.mContext = param1Context;
this.zzalj = param1Context.getMainLooper();
this.zzehh = param1Context.getPackageName();
this.zzfta = param1Context.getClass().getName();
}
public Builder(Context param1Context, GoogleApiClient.ConnectionCallbacks param1ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener param1OnConnectionFailedListener) {
this(param1Context);
zzbq.checkNotNull(param1ConnectionCallbacks, "Must provide a connected listener");
this.zzfti.add(param1ConnectionCallbacks);
zzbq.checkNotNull(param1OnConnectionFailedListener, "Must provide a connection failed listener");
this.zzftj.add(param1OnConnectionFailedListener);
}
private final <O extends Api.ApiOptions> void zza(Api<O> param1Api, O param1O, Scope... param1VarArgs) {
HashSet<Scope> hashSet = new HashSet<Scope>(param1Api.zzahk().zzr(param1O));
int j = param1VarArgs.length;
int i;
for (i = 0; i < j; i++)
hashSet.add(param1VarArgs[i]);
this.zzftb.put(param1Api, new zzt(hashSet));
}
public final Builder addApi(Api<? extends Api.ApiOptions.NotRequiredOptions> param1Api) {
zzbq.checkNotNull(param1Api, "Api must not be null");
this.zzftc.put(param1Api, null);
List<Scope> list = param1Api.zzahk().zzr(null);
this.zzfsx.addAll(list);
this.zzfsw.addAll(list);
return this;
}
public final <O extends Api.ApiOptions.HasOptions> Builder addApi(Api<O> param1Api, O param1O) {
zzbq.checkNotNull(param1Api, "Api must not be null");
zzbq.checkNotNull(param1O, "Null options are not permitted for this Api");
this.zzftc.put(param1Api, (Api.ApiOptions)param1O);
List<Scope> list = param1Api.zzahk().zzr(param1O);
this.zzfsx.addAll(list);
this.zzfsw.addAll(list);
return this;
}
public final <O extends Api.ApiOptions.HasOptions> Builder addApiIfAvailable(Api<O> param1Api, O param1O, Scope... param1VarArgs) {
zzbq.checkNotNull(param1Api, "Api must not be null");
zzbq.checkNotNull(param1O, "Null options are not permitted for this Api");
this.zzftc.put(param1Api, (Api.ApiOptions)param1O);
zza((Api)param1Api, (Api.ApiOptions)param1O, param1VarArgs);
return this;
}
public final Builder addApiIfAvailable(Api<? extends Api.ApiOptions.NotRequiredOptions> param1Api, Scope... param1VarArgs) {
zzbq.checkNotNull(param1Api, "Api must not be null");
this.zzftc.put(param1Api, null);
zza(param1Api, null, param1VarArgs);
return this;
}
public final Builder addConnectionCallbacks(GoogleApiClient.ConnectionCallbacks param1ConnectionCallbacks) {
zzbq.checkNotNull(param1ConnectionCallbacks, "Listener must not be null");
this.zzfti.add(param1ConnectionCallbacks);
return this;
}
public final Builder addOnConnectionFailedListener(GoogleApiClient.OnConnectionFailedListener param1OnConnectionFailedListener) {
zzbq.checkNotNull(param1OnConnectionFailedListener, "Listener must not be null");
this.zzftj.add(param1OnConnectionFailedListener);
return this;
}
public final Builder addScope(Scope param1Scope) {
zzbq.checkNotNull(param1Scope, "Scope must not be null");
this.zzfsw.add(param1Scope);
return this;
}
public final GoogleApiClient build() {
String str;
StringBuilder stringBuilder;
zzbq.checkArgument(this.zzftc.isEmpty() ^ true, "must call addApi() to add at least one API");
zzr zzr = zzaic();
Api api = null;
Map map = zzr.zzamh();
a<Api, Boolean> a = new a();
a<Api.zzc<?>, zzt> a1 = new a();
ArrayList<zzt> arrayList = new ArrayList();
Iterator<Api> iterator = this.zzftc.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
boolean bool;
Api api1 = iterator.next();
Object object = this.zzftc.get(api1);
if (map.get(api1) != null) {
bool = true;
} else {
bool = false;
}
a.put(api1, Boolean.valueOf(bool));
zzt zzt = new zzt(api1, bool);
arrayList.add(zzt);
Api.zza zza1 = api1.zzahl();
zzt = (zzt)zza1.zza(this.mContext, this.zzalj, zzr, object, (GoogleApiClient.ConnectionCallbacks)zzt, (GoogleApiClient.OnConnectionFailedListener)zzt);
a1.put(api1.zzahm(), zzt);
int j = i;
if (zza1.getPriority() == 1) {
if (object != null) {
i = 1;
} else {
i = 0;
}
j = i;
}
i = j;
if (zzt.zzacn()) {
if (api == null) {
api = api1;
i = j;
continue;
}
String str1 = api1.getName();
str = api.getName();
stringBuilder = new StringBuilder(String.valueOf(str1).length() + 21 + String.valueOf(str).length());
stringBuilder.append(str1);
stringBuilder.append(" cannot be used with ");
stringBuilder.append(str);
throw new IllegalStateException(stringBuilder.toString());
}
}
if (str != null)
if (!i) {
boolean bool;
if (this.zzeho == null) {
bool = true;
} else {
bool = false;
}
zzbq.zza(bool, "Must not set an account in GoogleApiClient.Builder when using %s. Set account in GoogleSignInOptions.Builder instead", new Object[] { str.getName() });
zzbq.zza(this.zzfsw.equals(this.zzfsx), "Must not set scopes in GoogleApiClient.Builder when using %s. Set account in GoogleSignInOptions.Builder instead.", new Object[] { str.getName() });
} else {
str = str.getName();
StringBuilder stringBuilder1 = new StringBuilder(String.valueOf(str).length() + 82);
stringBuilder1.append("With using ");
stringBuilder1.append(str);
stringBuilder1.append(", GamesOptions can only be specified within GoogleSignInOptions.Builder");
throw new IllegalStateException(stringBuilder1.toString());
}
i = zzba.zza(a1.values(), true);
null = new zzba(this.mContext, new ReentrantLock(), this.zzalj, (zzr)stringBuilder, this.zzftg, this.zzfth, (Map)a, this.zzfti, this.zzftj, (Map)a1, this.zzfte, i, arrayList, false);
synchronized (GoogleApiClient.zzaib()) {
GoogleApiClient.zzaib().add(null);
if (this.zzfte >= 0)
zzi.zza(this.zzftd).zza(this.zzfte, (GoogleApiClient)null, this.zzftf);
return (GoogleApiClient)null;
}
}
public final Builder enableAutoManage(c param1c, int param1Int, GoogleApiClient.OnConnectionFailedListener param1OnConnectionFailedListener) {
boolean bool;
zzce zzce1 = new zzce((Activity)param1c);
if (param1Int >= 0) {
bool = true;
} else {
bool = false;
}
zzbq.checkArgument(bool, "clientId must be non-negative");
this.zzfte = param1Int;
this.zzftf = param1OnConnectionFailedListener;
this.zzftd = zzce1;
return this;
}
public final Builder enableAutoManage(c param1c, GoogleApiClient.OnConnectionFailedListener param1OnConnectionFailedListener) {
return enableAutoManage(param1c, 0, param1OnConnectionFailedListener);
}
public final Builder setAccountName(String param1String) {
Account account;
if (param1String == null) {
param1String = null;
} else {
account = new Account(param1String, "com.google");
}
this.zzeho = account;
return this;
}
public final Builder setGravityForPopups(int param1Int) {
this.zzfsy = param1Int;
return this;
}
public final Builder setHandler(Handler param1Handler) {
zzbq.checkNotNull(param1Handler, "Handler must not be null");
this.zzalj = param1Handler.getLooper();
return this;
}
public final Builder setViewForPopups(View param1View) {
zzbq.checkNotNull(param1View, "View must not be null");
this.zzfsz = param1View;
return this;
}
public final Builder useDefaultAccount() {
return setAccountName("<<default account>>");
}
@Hide
public final zzr zzaic() {
zzcyk zzcyk = zzcyk.zzklp;
if (this.zzftc.containsKey(zzcyg.API))
zzcyk = (zzcyk)this.zzftc.get(zzcyg.API);
return new zzr(this.zzeho, this.zzfsw, this.zzftb, this.zzfsy, this.zzfsz, this.zzehh, this.zzfta, zzcyk);
}
}
public static interface ConnectionCallbacks {
public static final int CAUSE_NETWORK_LOST = 2;
public static final int CAUSE_SERVICE_DISCONNECTED = 1;
void onConnected(Bundle param1Bundle);
void onConnectionSuspended(int param1Int);
}
public static interface OnConnectionFailedListener {
void onConnectionFailed(ConnectionResult param1ConnectionResult);
}
}
/* Location: /home/egaebel/Programs/sony-headphones-hack/base-dex2jar.jar!/com/google/android/gms/common/api/GoogleApiClient.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
| true
|
b0e4830745a6951f4da5874dd8dfbb51cfce0f7f
|
Java
|
zd87/masterpiece
|
/back/src/main/java/co/simplon/masterpiece/repositories/ServerRepository.java
|
UTF-8
| 456
| 1.96875
| 2
|
[] |
no_license
|
package co.simplon.masterpiece.repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import co.simplon.masterpiece.dtos.ServerViewDto;
import co.simplon.masterpiece.entities.Server;
public interface ServerRepository extends JpaRepository<Server, Long> {
Optional<Server> findById(Long id);
List<ServerViewDto> findAllProjectedBy();
Server findByFullName(String fullName);
}
| true
|
bd951beafd5a8ecb3613df27d48a32b3a91bf6d6
|
Java
|
carolinemckinnon/Lex
|
/edu/ucla/sspace/util/SemanticSpaceMatrix.java
|
UTF-8
| 1,877
| 2.640625
| 3
|
[] |
no_license
|
package edu.ucla.sspace.util;
import edu.ucla.sspace.common.SemanticSpace;
import edu.ucla.sspace.matrix.AbstractMatrix;
import edu.ucla.sspace.vector.DoubleVector;
import edu.ucla.sspace.vector.Vectors;
import java.util.Set;
public class SemanticSpaceMatrix
extends AbstractMatrix
{
private final SemanticSpace sspace;
private final BiMap<Integer, String> rowToWord;
private final int columns;
public SemanticSpaceMatrix(SemanticSpace sspace)
{
this.sspace = sspace;
rowToWord = new HashBiMap();
columns = sspace.getVectorLength();
for (String word : sspace.getWords()) {
rowToWord.put(Integer.valueOf(rowToWord.size()), word);
}
}
private boolean checkModifications()
{
return (sspace.getWords().size() != rowToWord.size()) ||
(columns != sspace.getVectorLength());
}
public Integer getRowIndex(String term)
{
return (Integer)rowToWord.inverse().get(term);
}
public DoubleVector getRowVector(int row)
{
if ((row < 0) || (row >= rowToWord.size()))
throw new IndexOutOfBoundsException("Row is out of bounds: " + row);
return Vectors.asDouble(sspace.getVector((String)rowToWord.get(Integer.valueOf(row))));
}
public int columns()
{
return columns;
}
public int rows()
{
return rowToWord.size();
}
public void set(int row, int col, double val)
{
throw new UnsupportedOperationException(
"Cannot modify SemanticSpace-backed matrix");
}
public void setColumn(int column, DoubleVector values)
{
throw new UnsupportedOperationException(
"Cannot modify SemanticSpace-backed matrix");
}
public void setRow(int row, DoubleVector values)
{
throw new UnsupportedOperationException(
"Cannot modify SemanticSpace-backed matrix");
}
}
| true
|
25d72cc6792a41ee0dceade31165664b9ebe9578
|
Java
|
pervez72/namota
|
/app/src/main/java/com/example/namota/MainActivity.java
|
UTF-8
| 1,401
| 2.578125
| 3
|
[] |
no_license
|
package com.example.namota;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private EditText editText;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.ButtonID);
editText = findViewById(R.id.EdittextID);
textView = findViewById(R.id.namota_text);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.ButtonID){
makenamota();
}
}
void makenamota(){
String value=editText.getText().toString();
if (value.isEmpty()){
Toast.makeText(this, "Please Enter Number ", Toast.LENGTH_SHORT).show();
}
else{
int number=Integer.parseInt(value);
String text="";
for (int i=1; i<=10; i++){
text=text+""+number+" X "+i+"="+number*i+"\n";
}
textView.setText(text);
}
}
}
| true
|
3ed04ea23a9f2bf6492882b874f03cb2cfe6d38b
|
Java
|
Gibbrich/tetris
|
/src/test/tetris/TetrisTest.java
|
UTF-8
| 3,272
| 2.875
| 3
|
[] |
no_license
|
package test.tetris;
import com.sun.tools.javac.util.Pair;
import main.tetris.Figure;
import main.tetris.Matrix;
import main.tetris.Point;
import main.tetris.Tetris;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static main.tetris.Figure.*;
import static main.tetris.Tetris.GRID_HEIGHT;
import static main.tetris.Tetris.GRID_WIDTH;
import static org.junit.Assert.*;
public class TetrisTest {
@Test
public void solve_returns_empty_Matrix_if_no_figures_passed() {
final Set<Matrix> set = new Tetris().solve(GRID_WIDTH, GRID_HEIGHT);
final Matrix expected = new Matrix(GRID_HEIGHT, GRID_WIDTH);
assertEquals(1, set.size());
final Matrix result = set.iterator().next();
assertEquals(expected, result);
}
@Test
public void solve_returns_empty_set_if_grid_is_smaller_then_any_figure() {
final Set<Matrix> set = new Tetris().solve(2, 2, FIGURES);
assertTrue(set.isEmpty());
}
@Test
public void solve_returns_set_with_all_possible_variants_how_figures_can_be_placed_in_grid() {
final String result1 = getResult(0, 0, 0, 1);
final String result2 = getResult(1, 0, 0, 0);
final String result3 = getResult(1, 0, 0, 1);
final String result4 = getResult(1, 1, 0, 0);
final String result5 = getResult(0, 2, 2, 0);
final String result6 = getResult(1, 2, 0, 1);
final String result7 = getResult(1, 1, 0, 1);
final String result8 = getResult(1, 0, 1, 1);
final HashSet<String> expected = new HashSet<>();
expected.add(result1);
expected.add(result2);
expected.add(result3);
expected.add(result4);
expected.add(result5);
expected.add(result6);
expected.add(result7);
expected.add(result8);
final Set<String> result = new Tetris()
.solve(GRID_WIDTH, GRID_HEIGHT, A, B)
.stream()
.map(Matrix::toString)
.collect(Collectors.toSet());
assertEquals(expected, result);
}
private void putFigureWithCoordinate(int x, int y, Figure figure, List<Pair<Point, Figure>> list) {
final Point point = new Point(x, y);
final Pair<Point, Figure> figureWithCoordinate = new Pair<>(point, figure);
list.add(figureWithCoordinate);
}
private String getResult(int x1, int y1, int x2, int y2) {
final List<Pair<Point, Figure>> result = new ArrayList<>();
putFigureWithCoordinate(x1, y1, A, result);
putFigureWithCoordinate(x2, y2, B, result);
final StringBuilder sb = new StringBuilder();
for (Pair<Point, Figure> pair : result) {
sb.append(pair.snd.getName()).append(":");
for (Point point : pair.snd.getPoints()) {
final int x = point.getX() + pair.fst.getX();
final int y = point.getY() + pair.fst.getY();
sb.append(x).append(",").append(y).append(";");
}
sb.deleteCharAt(sb.length() - 1).append("\n");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
| true
|
0cd58075da8dd64f6a8ecf63f6704378f9027c61
|
Java
|
yuvalherziger/quintly-java-api
|
/src/main/java/com/quintly/api/Credentials.java
|
UTF-8
| 791
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
package com.quintly.api;
import org.apache.commons.lang3.Validate;
public class Credentials {
private Integer clientId;
private String clientSecret;
public Credentials(Integer clientId, String clientSecret) {
this.validate(clientId, clientSecret);
this.clientId = clientId;
this.clientSecret = clientSecret;
}
private void validate(Integer clientId, String clientSecret) {
Validate.notNull(clientId, "The 'clientId' parameter is mandatory");
Validate.notNull(clientSecret, "The 'clientSecret' parameter is mandatory");
Validate.notEmpty(clientSecret, "The 'clientSecret' parameter cannot be empty");
}
public String toString() {
return String.format("%s:%s", this.clientId, this.clientSecret);
}
}
| true
|
0e0acb2c01d93669dac12a426b94ddfe95623a74
|
Java
|
yao1996/LeetCode
|
/src/com/ykqfrost/greedy/LeetCode763.java
|
UTF-8
| 2,929
| 3.703125
| 4
|
[] |
no_license
|
package com.ykqfrost.greedy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author ykq
* @date 2020/10/22
* 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入:S = "ababcbacadefegdehijhklij"
* 输出:[9,7,8]
* 解释:
* 划分结果为 "ababcbaca", "defegde", "hijhklij"。
* 每个字母最多出现在一个片段中。
* 像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
*
* <p>
* 提示:
* <p>
* S的长度在[1, 500]之间。
* S只包含小写字母 'a' 到 'z' 。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/partition-labels
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class LeetCode763 {
public List<Integer> partitionLabels(String S) {
HashMap<Character, Integer> occurs = new HashMap<>();
List<HashMap<Character, Integer>> list = new ArrayList<>();
List<Integer> res = new ArrayList<>();
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
Integer pos = occurs.get(c);
if (pos == null) {
HashMap<Character, Integer> map = new HashMap<>();
map.put(c, 1);
list.add(map);
res.add(1);
occurs.put(c, 1);
} else {
int num = -1;
HashMap<Character, Integer> current = null;
int length = -1;
for (int j = 0; j < list.size(); j++) {
HashMap<Character, Integer> map = list.get(j);
if (map.get(c) != null) {
num = j;
current = map;
length = res.get(num);
continue;
}
if (current != null) {
current.putAll(map);
}
if (length != -1) {
length += res.get(j);
}
}
if (list.size() > num + 1) {
list.subList(num + 1, list.size()).clear();
}
if (res.size() > num) {
res.subList(num, res.size()).clear();
}
length++;
res.add(length);
}
}
return res;
}
public static void main(String[] args) {
String s = "ababcbacadefegdehijhklij";
LeetCode763 leetCode763 = new LeetCode763();
List<Integer> list = leetCode763.partitionLabels(s);
System.out.println(list);
}
}
| true
|
33a7536b5ac118221bfbe7d3f128a3ca68ff6aa0
|
Java
|
Jahia/graphql-core
|
/graphql-dxm-provider/src/main/java/org/jahia/modules/graphql/provider/dxm/sdl/fetchers/ListDataFetcher.java
|
UTF-8
| 6,246
| 1.851563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2002-2022 Jahia Solutions Group SA. 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 org.jahia.modules.graphql.provider.dxm.sdl.fetchers;
import graphql.schema.*;
import org.jahia.modules.graphql.provider.dxm.node.GqlJcrNode;
import org.jahia.modules.graphql.provider.dxm.node.GqlJcrNodeImpl;
import org.jahia.modules.graphql.provider.dxm.sdl.SDLConstants;
import org.jahia.services.content.JCRContentUtils;
import org.jahia.services.content.JCRNodeWrapper;
import org.jahia.services.content.JCRValueWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created at 23 Jan$
*
* @author chooliyip
**/
public class ListDataFetcher extends FinderListDataFetcher {
private static Logger logger = LoggerFactory.getLogger(ListDataFetcher.class);
private Field field;
public ListDataFetcher(Field field) {
super("", null);
this.field = field;
}
@Override
public List get(DataFetchingEnvironment environment) {
return getStream(environment).collect(Collectors.toList());
}
@Override
public Stream<GqlJcrNode> getStream(DataFetchingEnvironment environment) {
GqlJcrNode node = environment.getSource();
JCRNodeWrapper jcrNode = node.getNode();
if (environment.getFieldDefinition().getType() instanceof GraphQLObjectType) {
//In this case we are dealing with connection at field level of a type i. e. text : TextConnection etc.
GraphQLObjectType obj = (GraphQLObjectType) ((GraphQLList) ((GraphQLObjectType) environment.getFieldDefinition().getType()).getFieldDefinition("nodes").getType()).getWrappedType();
GraphQLDirective mappingDirective = obj.getDirective(SDLConstants.MAPPING_DIRECTIVE);
if (mappingDirective != null) {
String nodeType = mappingDirective.getArgument(SDLConstants.MAPPING_DIRECTIVE_NODE).getValue().toString();
return resolveChildren(jcrNode, nodeType);
}
}
GraphQLType type = resolveWrappedObject(environment.getFieldDefinition().getType());
if (type instanceof GraphQLObjectType) {
GraphQLDirective mappingDirective = ((GraphQLObjectType) type).getDirective(SDLConstants.MAPPING_DIRECTIVE);
GraphQLArgument arg = mappingDirective != null ? mappingDirective.getArgument(SDLConstants.MAPPING_DIRECTIVE_NODE) : null;
return resolveFromArgument(jcrNode, arg);
}
try {
return resolveProperty(jcrNode);
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
private GraphQLType resolveWrappedObject(GraphQLType type) {
return type instanceof GraphQLList ? ((GraphQLList) type).getWrappedType() : type;
}
private Object getProperty(int propertyType, JCRValueWrapper value) {
try {
switch (propertyType) {
case PropertyType.STRING:
return value.getString();
case PropertyType.BOOLEAN:
return value.getBoolean();
case PropertyType.DOUBLE:
return value.getDouble();
case PropertyType.LONG:
return value.getLong();
case PropertyType.WEAKREFERENCE:
logger.debug("Fetch weak reference {}", field.getProperty());
return new GqlJcrNodeImpl(value.getNode());
default:
return null;
}
} catch (RepositoryException ex) {
logger.error("Failed to retrieve node property {}", ex);
return null;
}
}
private Stream resolveProperty(JCRNodeWrapper jcrNode) throws RepositoryException {
if (!jcrNode.hasProperty(field.getProperty())) {
return Stream.empty();
}
int propertyType = jcrNode.getProperty(field.getProperty()).getType();
return Arrays.stream(jcrNode.getProperty(field.getProperty()).getRealValues())
.map(value -> getProperty(propertyType, value))
.filter(Objects::nonNull);
}
private Stream<GqlJcrNode> resolveChildren(JCRNodeWrapper node, String nodeType) {
return JCRContentUtils.getChildrenOfType(node, nodeType).stream()
.map(GqlJcrNodeImpl::new);
}
private Stream resolveFromArgument(JCRNodeWrapper node, GraphQLArgument arg) {
if (arg != null) {
try {
String nodeType = arg.getValue().toString();
if (field == null) {
logger.debug("Fetch children of type {}", nodeType);
//Case when child name is not specified, get children directly from jcrNode
return resolveChildren(node, nodeType);
}
//Case when property is a weak reference
if (node.hasProperty(field.getProperty())) {
return resolveProperty(node);
}
//Case when child mapping is specified, get children from mapped node
logger.debug("Fetch children of type {} from child {}", nodeType, field.getProperty());
return resolveChildren(node.getNode(field.getProperty()), nodeType);
} catch (RepositoryException e) {
//Do nothing, return empty list below
}
}
return Stream.empty();
}
}
| true
|