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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1eaaa0204e4fcfee3c9c7e9b98ba64dd3a4a74c9
|
Java
|
Ganom/Testapk
|
/com/upsight/android/internal/persistence/subscription/Subscriptions.java
|
UTF-8
| 1,732
| 2.09375
| 2
|
[] |
no_license
|
package com.upsight.android.internal.persistence.subscription;
import com.squareup.otto.Bus;
import com.upsight.android.internal.persistence.subscription.DataStoreEvent.Action;
import com.upsight.android.persistence.UpsightSubscription;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
public class Subscriptions {
public static <T> Action1<T> publishCreated(final Bus bus, final String type) {
return new Action1<T>() {
public void call(T t) {
bus.post(new DataStoreEvent(Action.Created, type, t));
}
};
}
public static <T> Action1<T> publishUpdated(final Bus bus, final String type) {
return new Action1<T>() {
public void call(T t) {
bus.post(new DataStoreEvent(Action.Updated, type, t));
}
};
}
public static <T> Action1<T> publishRemoved(final Bus bus, final String type) {
return new Action1<T>() {
public void call(T t) {
bus.post(new DataStoreEvent(Action.Removed, type, t));
}
};
}
public static Observable<DataStoreEvent> toObservable(Bus bus) {
return Observable.create(new OnSubscribeBus(bus)).onBackpressureBuffer();
}
public static UpsightSubscription from(Subscription subscription) {
return new SubscriptionAdapter(subscription);
}
public static AnnotatedSubscriber create(Object target) {
SubscriptionHandlerVisitor visitor = new SubscriptionHandlerVisitor(target);
new ClassSubscriptionReader(target.getClass()).accept(visitor);
return new AnnotatedSubscriber(visitor.getHandlers());
}
private Subscriptions() {
}
}
| true
|
3d6e66512f614fde0ab2880446bfcf16d301c340
|
Java
|
zybotian/ssm
|
/server/src/main/java/org/oasis/service/CsCaseService.java
|
UTF-8
| 449
| 1.796875
| 2
|
[] |
no_license
|
package org.oasis.service;
import org.oasis.model.CsCase;
import org.oasis.mybatis.mapper.CsCaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author tianbo
* @date 2019-03-08
*/
@Service
public class CsCaseService {
@Autowired
private CsCaseMapper dao;
public CsCase selectByPrimaryKey(Integer id) {
return dao.selectByPrimaryKey(id);
}
}
| true
|
b59013a8100b4f36a822711958736fc1215ae3a3
|
Java
|
dcleyne/CampaignManager
|
/test/TestMapLayoutRenderer.java
|
UTF-8
| 1,198
| 2.75
| 3
|
[] |
no_license
|
package test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Vector;
import javax.imageio.ImageIO;
import bt.managers.MapManager;
import bt.mapping.MapSet;
import bt.ui.renderers.MapLayoutRenderer;
import bt.util.ExceptionUtil;
import bt.util.PropertyUtil;
public class TestMapLayoutRenderer
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
PropertyUtil.loadSystemProperties("bt/system.properties");
Vector<MapSet> mapSets = MapManager.getInstance().getMapSets();
for (MapSet mapSet : mapSets)
{
BufferedImage image = MapLayoutRenderer.getInstance().renderMapLayout(mapSet);
System.out.println(mapSet.getName());
String filename = "/tmp/" + mapSet.getName().replace('/', '-') + ".png";
ImageIO.write(image, "PNG", new File(filename));
System.out.println("Rendered Ok " + mapSet.getName());
//System.exit(0);
}
}
catch (Exception ex)
{
System.out.print(ExceptionUtil.getExceptionStackTrace(ex));
}
}
}
| true
|
038ef6a5229069666abd129db0937e6b48a3ea65
|
Java
|
itsasm/data-processing
|
/src/main/java/com/data_processing/app/execution/DataExecutor.java
|
UTF-8
| 2,777
| 2.578125
| 3
|
[] |
no_license
|
package com.data_processing.app.execution;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.data_processing.app.dao.DataDAO;
import com.data_processing.app.model.Task;
@Component
public class DataExecutor {
@Autowired
private DataDAO dao;
private static Logger logger = LoggerFactory.getLogger(DataExecutor.class);
static ExecutorService executor;
public void invalidateRequest() {
if (dao.getTask() != null && !dao.getTask().isEmpty()) {
dao.getTask().clear();
if (!executor.isShutdown())
executor.shutdownNow();
}
}
public void startDataProcessing() throws InterruptedException, ExecutionException {
executor = Executors.newCachedThreadPool();
for (Task task : dao.getTask()) {
Future<Task> future = null;
if (!task.isCancelled()) {
future = executor.submit(task);
} else {
dao.getCancelledTaskList().add(task);
logger.info(task.getName() + " has been cancelled");
continue;
}
Task cancelled = null;
while (!future.isDone()) {
if (task.isCancelled()) {
cancelled = future.get();
future.cancel(true);
}
}
if (future.isCancelled()) {
dao.getCancelledTaskList().add(cancelled);
logger.info("Task ID...... : " + future.get().getId() + ", isCancelled : " + future.get().isCancelled()
+ ", f: " + future.isCancelled());
}
if (future.isDone()) {
logger.info("Task " + future.get().getName() + " {" + future.get().getDesc() + "} finished......");
dao.getSubmittedTaskList().add(future.get());
}
}
executor.shutdown();
}
public List<String> stopDataProcessing(List<Task> cancelList) {
List<String> reply = new ArrayList<>();
if (dao.getTask().isEmpty()) {
reply.add("No Running Task Found...");
return reply;
}
if (executor.isShutdown()) {
reply.add("Task already been completed.");
return reply;
}
for (Task task : cancelList) {
try {
int index = dao.getTask().indexOf(task);
if (index >= 0) {
dao.getTask().get(index).setCancelled(true);
logger.info(task.getName()+" set to cancel.");
Thread.sleep(10);
}
reply.add("Task Set To Cancel : " + task.getName());
} catch (ConcurrentModificationException | InterruptedException e) {
logger.error("Error Occurred : " + e.getMessage());
reply.add("Task Could Not Be Cancelled : " + task.getName());
}
}
return reply;
}
}
| true
|
4340e03b603febd99292e35231643cb834bc1823
|
Java
|
ThousandPulse/helloword
|
/src/studentSystem/dbconnect/DBModify.java
|
UTF-8
| 16,296
| 2.765625
| 3
|
[] |
no_license
|
package studentSystem.dbconnect;
import java.sql.*;
public class DBModify {
private String SQL;
private ResultSet rs;
private static Statement st;
public DBModify(Statement st) {
DBModify.st = st;
}
private String[][] showAll(String SQL) {
int studentCount = getStudentCount();
String[][] result = new String[studentCount][7];
try {
rs = st.executeQuery(SQL);
int j = 0;
while (rs.next()) {
for (int i = 1; i < 8; i++) {
result[j][i - 1] = rs.getString(i);
}
j++;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public int getStudentCount() {
SQL = " SELECT Count(*) FROM [dbo].[student]";
try {
int i = 0;
rs = st.executeQuery(SQL);
while (rs.next())
i++;
return i;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return 0;
}
public int getReportCount() {
SQL = "SELECT Count(*) FROM [dbo].[result]";
try {
int i = 0;
rs = st.executeQuery(SQL);
while (rs.next())
i++;
return i;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return 0;
}
public int getCourseCount() {
SQL = "SELECT Count(*) FROM [dbo].[course]";
try {
int i = 0;
rs = st.executeQuery(SQL);
while (rs.next())
i++;
return i;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return 0;
}
public String getStudentID(String studentName) {
SQL = "SELECT student_id FROM [dbo].[student] WHERE student_name = '" + studentName + "'";
String studentID = null;
try {
rs = st.executeQuery(SQL);
while (rs.next())
studentID = rs.getNString(1);
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return studentID;
}
public String getStudentIDForLoginID(String loginID) {
SQL = "SELECT * FROM [dbo].[student] WHERE login_id = "+loginID ;
String studentID = null;
try {
rs = st.executeQuery(SQL);
while (rs.next())
studentID = rs.getNString(1);
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return studentID;
}
public String getClassroomIDForName(String classroomName) {
SQL = "SELECT classroom_id FROM [dbo].[classroom] WHERE classroom_name = '" + classroomName + "'";
String classroomID = null;
try {
rs = st.executeQuery(SQL);
while (rs.next())
classroomID = rs.getNString(1);
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return classroomID;
}
public String[] getStudentClassroomCourse(String studentName) {
String studentID = getStudentID(studentName);
String[] courseIDList = new String[getCourseCount()];
SQL = "SELECT course_id FROM [dbo].[classroom_student],[dbo].[course] " +
"WHERE student_id = '" + studentID + "' " +
"AND classroom_student.classroom_id = course.classroom_id";
try {
rs = st.executeQuery(SQL);
int i = 0;
while (rs.next()) {
courseIDList[i] = rs.getNString(1);
i++;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return courseIDList;
}
public String[] selectLogin(String loginName, String loginPwd) {
SQL = "SELECT * FROM [dbo].[login] WHERE login_name = '" + loginName + "' " +
"and login_pwd = '" + loginPwd + "'";
String[] result = new String[4];
try {
rs = st.executeQuery(SQL);
while (rs.next()) {
for (int i = 1; i < 5; i++) {
result[i - 1] = rs.getString(i);
}
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public String[][] selectStudent() {
SQL = "SELECT * FROM [dbo].[student]";
return showAll(SQL);
}
public String[][] selectStudentForName(String studentName) {
SQL = "SELECT * FROM [dbo].[student] WHERE student_name = '" + studentName + "'";
return showAll(SQL);
}
public String[][] selectStudentForID(String studentID) {
SQL = "SELECT * FROM [dbo].[student] WHERE student_id = '" + studentID + "'";
return showAll(SQL);
}
public boolean selectStudentForLoginID(String loginID) {
SQL = "SELECT * FROM [dbo].[student] WHERE login_id = " + loginID ;
String[][] loginStudent = showAll(SQL);
return loginStudent[0][0] != null;
}
public boolean selectTeacherForLoginID(String loginID) {
SQL = "SELECT * FROM [dbo].[teacher] WHERE login_id = " + loginID;
String[] result = new String[3];
try {
rs = st.executeQuery(SQL);
while (rs.next()) {
result[0] = rs.getString(1);
result[1] = rs.getString(2);
result[2] = rs.getString(3);
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result[0] != null;
}
public String[][] selectStudentForClassroomID(String classroomID) {
SQL = "SELECT student.* FROM classroom_student,student WHERE" +
" classroom_student.student_id = student.student_id and classroom_id = '" + classroomID + "'";
return showAll(SQL);
}
public String[][] selectStudentForClassroomName(String classroomName) {
String[][] student = new String[0][0];
try {
SQL = "SELECT classroom_id FROM [dbo].[classroom] WHERE classroom_name = '" + classroomName + "'";
rs = st.executeQuery(SQL);
while (rs.next()) {
student = selectStudentForClassroomID(rs.getString(1));
}
return student;
} catch (SQLException sqlException) {
//System.out.println("?????");
sqlException.printStackTrace();
}
return student;
}
public String[][] selectStudentResultForCourseName(String courseName) {
int studentCount = getStudentCount();
String[][] result = new String[studentCount][2];
try {
SQL = "SELECT [student_name]" +
" ,[course_result]" +
" FROM [dbo].[result],[dbo].[student],[dbo].[course]" +
" where course.course_name = '" + courseName + "'" +
" and result.course_id = course.course_id" +
" and result.student_id = student.student_id";
rs = st.executeQuery(SQL);
int j = 0;
while (rs.next()) {
for (int i = 1; i < 3; i++) {
result[j][i - 1] = rs.getString(i);
}
j++;
}
return result;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public String[] selectCourseNameList(String classroomID) {
String[] courseList = new String[getCourseCount()];
try {
SQL = "SELECT [course_name] FROM [dbo].[course] WHERE classroom_id = '" + classroomID + "'";
rs = st.executeQuery(SQL);
int i = 0;
while (rs.next()) {
courseList[i] = rs.getString(1);
i++;
}
} catch (SQLException sqlException) {
System.out.println("?????");
// sqlException.printStackTrace();
}
return courseList;
}
public String[][] selectAllStudentResult() {
int reportCount = getReportCount();
String[][] result = new String[reportCount][3];
try {
SQL = "SELECT [student_name],[course_result],[course_name]" +
" FROM [dbo].[result],[dbo].[student],[dbo].[course]" +
" where result.course_id = course.course_id" +
" and result.student_id = student.student_id";
rs = st.executeQuery(SQL);
int j = 0;
while (rs.next()) {
for (int i = 1; i < 4; i++) {
result[j][i - 1] = rs.getString(i);
}
j++;
}
return result;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public String[][] selectSelfStudentResult(String studentID) {
int reportCount = getReportCount();
String[][] result = new String[reportCount][3];
try {
SQL = "SELECT [student_name],[course_result],[course_name]" +
" FROM [dbo].[result],[dbo].[student],[dbo].[course]" +
" where student.student_id = '"+studentID+"'" +
" and result.course_id = course.course_id" +
" and result.student_id = student.student_id";
rs = st.executeQuery(SQL);
int j = 0;
while (rs.next()) {
for (int i = 1; i < 4; i++) {
result[j][i - 1] = rs.getString(i);
}
j++;
}
return result;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public String[][] selectClassroomStudentResult(String classroomName) {
int reportCount = getReportCount();
String[][] result = new String[reportCount][3];
try {
SQL = "SELECT [student_name],[course_result],[course_name]" +
" FROM [dbo].[result],[dbo].[student],[dbo].[course]," +
"[dbo].[classroom],[dbo].[classroom_student]" +
" where classroom.classroom_name = '" + classroomName + "'" +
" and result.course_id = course.course_id" +
" and result.student_id = student.student_id" +
" and student.student_id = classroom_student.student_id" +
" and classroom_student.classroom_id = classroom.classroom_id";
rs = st.executeQuery(SQL);
int j = 0;
while (rs.next()) {
for (int i = 1; i < 4; i++) {
result[j][i - 1] = rs.getString(i);
}
j++;
}
return result;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return result;
}
public int upDataStudentName(String studentName, String loginID) {
try {
SQL = "UPDATE [dbo].[student] SET [student_name] = '" + studentName +
"' WHERE login_id = " + loginID;
return st.executeUpdate(SQL);
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int insertUser(String loginName, String loginPwd, String loginType) {
try {
SQL = "INSERT INTO [dbo].[login] ([login_type],[login_name],[login_pwd]) " +
"VALUES\n(" + loginType + ",'" + loginName + "','" + loginPwd + "')";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int insertTeacher(String teacherName, String teacherID, String loginID) {
try {
SQL = "INSERT INTO [dbo].[teacher] ([teacher_id],[teacher_name],[login_id])" +
" VALUES\n('" + teacherID + "','" + teacherName + "'," + loginID + ")";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int insertClassroom(String classroomID, String classroomName, String teacherID) {
try {
SQL = "INSERT INTO [dbo].[classroom] ([classroom_id],[classroom_name],[teacher_id]) " +
"VALUES ('" + classroomID + "','" + classroomName + "','" + teacherID + "'";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int insertCourse(String courseID, String courseName, String classroomID) {
try {
SQL = "INSERT INTO [dbo].[course] ([course_id],[course_name],[classroom_id]) " +
"VALUES ('" + courseID + "','" + courseName + "','" + classroomID + "'";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int insertStudent(String[] student) {
/*
student = [学号,姓名,电话,地址,性别,年龄,登陆账号]
*/
try {
SQL = "INSERT INTO [dbo].[student] ([student_id],[student_name],[student_number]," +
"[student_address],[student_sex],[student_age],[login_id]) VALUES " +
"('" + student[0] + "','" + student[1] + "','" + student[2] + "','" + student[3] +
"','" + student[4] + "'," + student[5] + "," + student[6] + ")";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
public int classroomAddStudent(String classroomID, String studentName) {
String studentID = getStudentID(studentName);
try {
SQL = "INSERT INTO [dbo].[classroom_student] ([classroom_id],[student_id]) " +
"VALUES ('" + classroomID + "','" + studentID + "'";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
private void studentAddCourse_1(String studentID) {//, String courseID
for (String courseID : getStudentClassroomCourse(studentID)) {
if (!courseID.equals("")) {
try {
SQL = "INSERT INTO [dbo].[result] ([student_id],[course_id]) " +
"VALUES ('" + studentID + "','" + courseID + "'";
st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
//return -1;
}
public int deleteStudentInClassroom(String studentName, String classroomName) { // 从班级中删除
String studentID = getStudentID(studentName);
deleteStudentInCourseAll(studentID);
try {
SQL = "DELETE FROM [dbo].[classroom_student] WHERE student_id = '" + studentID + "'";
return st.executeUpdate(SQL); // 返回影响行数
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return -1;
}
private void deleteStudentInCourseAll(String studentID) { // 删除其所有课程
try {
SQL = "DELETE FROM [dbo].[result] WHERE student_id = '" + studentID + "'";
st.executeUpdate(SQL); //
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
| true
|
b0ed54178657f1be195547af953ac3befeb9a199
|
Java
|
zeau/lean_pro
|
/src/main/java/com/bidanet/bdcms/core/driver/cache/RedisCache.java
|
UTF-8
| 3,049
| 2.4375
| 2
|
[] |
no_license
|
package com.bidanet.bdcms.core.driver.cache;
import com.bidanet.bdcms.core.common.JsonParseTool;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Administrator on 2016/7/1.
*/
public class RedisCache implements Cache {
protected static Logger logger=Logger.getLogger(RedisCache.class);
@Autowired
private JedisPool jedisPool;
@Override
public void set(String key, String val){
exec(j->j.set(key, val));
}
@Override
public void set(String key, Object val) {
if (val!=null){
exec(j->j.set(key, JsonParseTool.toJson(val)));
}
}
@Override
public void set(String key, Object val, int seconds) {
exec(j->{
if (key!=null){
j.set(key, JsonParseTool.toJson(val));
j.expire(key, seconds);
}
});
}
public void set(String key, String val, int seconds) {
exec(j->{
if (key!=null){
j.set(key, val);
j.expire(key, seconds);
}
});
}
@Override
public void expire(String key, int seconds){
exec(j-> j.expire(key, seconds));
}
@Override
public String get(String key){
final String[] s = {null};
exec(j-> s[0] =j.get(key));
return s[0];
}
@Override
public List<String> get(String... key) {
List<String> list = new ArrayList();
exec(j->list.addAll(j.mget(key)));
return list;
}
@Override
public <T> T get(String key,Class<T> tClass) {
String s = get(key);
if (s==null) return null;
return JsonParseTool.parseObject(s,tClass,"数据类型不匹配");
}
@Override
public<T> List<T> getArray(String key, Class<T> tClass){
String s = get(key);
if (s==null) return null;
return JsonParseTool.parseArray(s,tClass,"数据类型不匹配");
}
@Override
public void delete(String... key) {
exec(j->j.del(key));
}
@Override
public void clean() {
exec(j->j.flushAll());
}
/**
* 查找
* @param pattam
* @return
*/
public Set<String> keys(String pattam){
Set<String> keys =new HashSet<>();
exec(jedis->keys.addAll(jedis.keys(pattam)) );
return keys;
}
public void exec(RedisExec exec){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
exec.exec(jedis);
}catch (Exception e){
e.printStackTrace();
//logInfoService.addErrorLog("redis",e.getMessage());
}finally {
if (jedis!=null){
jedis.close();
}
}
}
public interface RedisExec{
void exec(Jedis jedis);
}
}
| true
|
be0c23755b00c97d0aabbab2a07bbe90ebfeec18
|
Java
|
ahmedalghareeb/MyloginRegisterApp
|
/app/src/main/java/com/ghareeb/myloginregisterapp/model/User.java
|
UTF-8
| 1,481
| 2.5
| 2
|
[] |
no_license
|
package com.ghareeb.myloginregisterapp.model;
import java.io.Serializable;
import java.util.ArrayList;
public class User implements Serializable {
private String fisrtName;
private String lastName;
private String email;
private String password;
//public static ArrayList<User> users = new ArrayList<>();
public User(String fisrtName, String lastName, String email, String password) {
this.fisrtName = fisrtName;
this.lastName = lastName;
this.email = email;
this.password = password;
//users.add(this);
}
public String getFisrtName() {
return fisrtName;
}
public void setFisrtName(String fisrtName) {
this.fisrtName = fisrtName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"fisrtName='" + fisrtName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
| true
|
a0ad82f40302e3f3192643a7566e14c0769524ab
|
Java
|
apache/karaf
|
/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
|
UTF-8
| 10,111
| 2.125
| 2
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"MIT",
"EPL-1.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.jaas.modules.properties;
import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import org.apache.felix.utils.properties.Properties;
import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.jaas.modules.NamePasswordCallbackHandler;
import org.junit.Assert;
import org.junit.Test;
public class PropertiesLoginModuleTest {
@Test
public void testBasicLogin() throws Exception {
File f = File.createTempFile(getClass().getName(), ".tmp");
try {
Properties p = new Properties(f);
PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
pbe.addUser("abc", "xyz");
pbe.addRole("abc", "myrole");
pbe.addUser("pqr", "abc");
PropertiesLoginModule module = new PropertiesLoginModule();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
Subject subject = new Subject();
module.initialize(subject, new NamePasswordCallbackHandler("abc", "xyz"), null, options);
Assert.assertEquals("Precondition", 0, subject.getPrincipals().size());
Assert.assertTrue(module.login());
Assert.assertTrue(module.commit());
Assert.assertEquals(2, subject.getPrincipals().size());
assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("abc"));
assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("myrole"));
Assert.assertTrue(module.logout());
Assert.assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
} finally {
if (!f.delete()) {
Assert.fail("Could not delete temporary file: " + f);
}
}
}
@Test
public void testLoginIncorrectPassword() throws Exception {
File f = File.createTempFile(getClass().getName(), ".tmp");
try {
Properties p = new Properties(f);
PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
pbe.addUser("abc", "xyz");
pbe.addUser("pqr", "abc");
PropertiesLoginModule module = new PropertiesLoginModule();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
module.initialize(new Subject(), new NamePasswordCallbackHandler("abc", "abc"), null, options);
try {
module.login();
Assert.fail("The login should have failed as the passwords didn't match");
} catch (FailedLoginException fle) {
// good
}
} finally {
if (!f.delete()) {
Assert.fail("Could not delete temporary file: " + f);
}
}
}
@Test
public void testLoginWithGroups() throws Exception {
File f = File.createTempFile(getClass().getName(), ".tmp");
try {
Properties p = new Properties(f);
PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
pbe.addUser("abc", "xyz");
pbe.addRole("abc", "myrole");
pbe.addUser("pqr", "abc");
pbe.addGroup("pqr", "group1");
pbe.addGroupRole("group1", "r1");
PropertiesLoginModule module = new PropertiesLoginModule();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
Subject subject = new Subject();
module.initialize(subject, new NamePasswordCallbackHandler("pqr", "abc"), null, options);
Assert.assertEquals("Precondition", 0, subject.getPrincipals().size());
Assert.assertTrue(module.login());
Assert.assertTrue(module.commit());
Assert.assertEquals(3, subject.getPrincipals().size());
assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("pqr"));
assertThat(names(subject.getPrincipals(GroupPrincipal.class)), containsInAnyOrder("group1"));
assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("r1"));
} finally {
if (!f.delete()) {
Assert.fail("Could not delete temporary file: " + f);
}
}
}
// This is a fairly important test that ensures that you cannot log in under the name of a
// group directly.
@Test
public void testCannotLoginAsGroupDirectly() throws Exception {
testCannotLoginAsGroupDirectly("group1");
testCannotLoginAsGroupDirectly("_g_:group1");
testCannotLoginAsGroupDirectly(PropertiesBackingEngine.GROUP_PREFIX + "group1");
}
private void testCannotLoginAsGroupDirectly(final String name) throws IOException, LoginException {
File f = File.createTempFile(getClass().getName(), ".tmp");
try {
Properties p = new Properties(f);
PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
pbe.addUser("abc", "xyz");
pbe.addRole("abc", "myrole");
pbe.addUser("pqr", "abc");
pbe.addGroup("pqr", "group1");
pbe.addGroupRole("group1", "r1");
PropertiesLoginModule module = new PropertiesLoginModule();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
module.initialize(new Subject(), new NamePasswordCallbackHandler(name, "group"), null, options);
try {
module.login();
Assert.fail("The login should have failed as you cannot log in under a group name directly");
} catch (FailedLoginException fle) {
// good
}
} finally {
if (!f.delete()) {
Assert.fail("Could not delete temporary file: " + f);
}
}
}
@Test
public void testNullUsersFile() {
try {
testWithUsersFile(null);
Assert.fail("LoginException expected");
} catch (LoginException e) {
Assert.assertEquals("The property users may not be null", e.getMessage());
}
}
@Test
public void testNonExistantPropertiesFile() throws LoginException, IOException, UnsupportedCallbackException {
try {
testWithUsersFile(File.separator + "test" + File.separator + "users.properties");
} catch (LoginException e) {
Assert.assertEquals("Users file not found at " + File.separator + "test" + File.separator + "users.properties", e.getMessage());
}
}
@Test
public void testNullPassword() throws Exception {
PropertiesLoginModule module = new PropertiesLoginModule();
Subject subject = new Subject();
CallbackHandler handler = new NullHandler();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, getTestUsersFile());
module.initialize(subject, handler, null, options);
try {
module.login();
Assert.fail("LoginException expected");
} catch (LoginException e) {
Assert.assertEquals("Password can not be null", e.getMessage());
}
}
private void testWithUsersFile(String usersFilePath) throws LoginException {
PropertiesLoginModule module = new PropertiesLoginModule();
Subject sub = new Subject();
CallbackHandler handler = new NamePasswordHandler("test", "test");
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, usersFilePath);
module.initialize(sub, handler, null, options);
module.login();
}
@Test
public void testNullCallbackHandler() {
PropertiesLoginModule module = new PropertiesLoginModule();
Subject subject = new Subject();
Map<String, String> options = new HashMap<>();
options.put(PropertiesLoginModule.USER_FILE, getTestUsersFile());
module.initialize(subject, null, null, options );
try {
module.login();
Assert.fail("LoginException expected");
} catch (LoginException e) {
Assert.assertEquals("Username can not be null", e.getMessage());
}
}
private String getTestUsersFile() {
return this.getClass().getClassLoader().getResource("org/apache/karaf/jaas/modules/properties/test.properties").getFile();
}
}
| true
|
f55a755dc74bc92b5fe8f0247f26bb1e1ae14c84
|
Java
|
ChenJun1/VehicleTerminalSystem1
|
/app/src/main/java/com/cvnavi/app/ui/activity/MainDialogActivity.java
|
UTF-8
| 3,278
| 2.078125
| 2
|
[] |
no_license
|
package com.cvnavi.app.ui.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.cvnavi.app.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 版权所有 上海势航网络科技
* Created: ChenJun
* Email: 791954958@qq.com
* Phone:
* CreatedTime: 2017/7/13 10:18
* version: 1.0
* Depict:
*/
public class MainDialogActivity extends Activity {
@BindView(R.id.close_iv)
ImageView mCloseIv;
@BindView(R.id.kongzai_rb)
RadioButton mKongzaiRb;
@BindView(R.id.banzai_rb)
RadioButton mBanzaiRb;
@BindView(R.id.manzai_rb)
RadioButton mManzaiRb;
@BindView(R.id.zzzt_rg)
RadioGroup mZzztRg;
@BindView(R.id.close_ll)
LinearLayout mCloseLl;
public static void start(Context context) {
Intent starter = new Intent(context, MainDialogActivity.class);
context.startActivity(starter);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dialog_activity_load_status);
ButterKnife.bind(this);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
String status = "";
if (!TextUtils.isEmpty(getIntent().getStringExtra("status"))) {
status = getIntent().getStringExtra("status");
}
init(status);
}
private void init(String status) {
switch (status) {
case "空载":
mKongzaiRb.setChecked(true);
break;
case "半载":
mBanzaiRb.setChecked(true);
break;
case "满载":
mManzaiRb.setChecked(true);
break;
default:
break;
}
}
@OnClick({R.id.close_ll, R.id.kongzai_rb, R.id.banzai_rb, R.id.manzai_rb})
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.close_ll:
this.finish();
break;
case R.id.kongzai_rb:
intent = new Intent();
intent.putExtra("status", "1");
setResult(RESULT_OK, intent);
this.finish();
break;
case R.id.banzai_rb:
intent = new Intent();
intent.putExtra("status", "2");
setResult(RESULT_OK, intent);
this.finish();
break;
case R.id.manzai_rb:
intent = new Intent();
intent.putExtra("status", "3");
setResult(RESULT_OK, intent);
this.finish();
break;
}
}
}
| true
|
3c9506bd152050b8614e13b40b7a9b2925318856
|
Java
|
Kibrom1/ASD
|
/Lab/BankApp_Observer/src/bank/observer/EmailSender.java
|
UTF-8
| 246
| 2.59375
| 3
|
[] |
no_license
|
package bank.observer;
import bank.domain.Customer;
import bank.pattern.*;
public class EmailSender implements IObserver{
public void update(Customer customer,double balance){
System.out.println("Account Balance changed Email sent");
}
}
| true
|
a713f15b8538455b5dac35cce62dce1eacdbb4a0
|
Java
|
xiaoyaozijacky/bcbpm
|
/bcbpm-model/src/main/java/com/bcbpm/model/custom/OptionConfig.java
|
UTF-8
| 1,675
| 2.171875
| 2
|
[] |
no_license
|
/**
*
*/
package com.bcbpm.model.custom;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**<p>Title: OptionConfig</p>
* <p>Company: bcbpm</p>
* @author jacky
* @date 2018年10月15日 下午3:22:45
* @version :
* @description:
*/
public class OptionConfig implements Serializable{
private static final long serialVersionUID = 1L;
private String id;//主键
private String type;// 属性类型 :input single
private List<ConfigOption> options;//字段预选值,例如:select,radio,checkbox等
private String fieldOptionId;//所属字段属性id
@JsonIgnore
private Date created;//创建时间
@JsonIgnore
private String createdBy;//创建人
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
public List<ConfigOption> getOptions(){
return options;
}
public void setOptions(List<ConfigOption> options){
this.options = options;
}
public String getFieldOptionId(){
return fieldOptionId;
}
public void setFieldOptionId(String fieldOptionId){
this.fieldOptionId = fieldOptionId;
}
public Date getCreated(){
return created;
}
public void setCreated(Date created){
this.created = created;
}
public String getCreatedBy(){
return createdBy;
}
public void setCreatedBy(String createdBy){
this.createdBy = createdBy;
}
}
| true
|
48304656a377f4c1893d483b27756cd33cd89742
|
Java
|
MarvinMachry/crudRest
|
/src/main/java/br/edu/ifsul/modelo/Veiculos.java
|
UTF-8
| 1,760
| 2.328125
| 2
|
[] |
no_license
|
package br.edu.ifsul.modelo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "veiculos")
public class Veiculos implements Serializable{
@Id
@SequenceGenerator(name = "seq_veiculo", sequenceName = "seq_veiculo_id", allocationSize = 1)
@GeneratedValue(generator = "seq_veiculo", strategy = GenerationType.SEQUENCE)
private Integer id;
@Column(name = "modelo", nullable = false, length = 20)
private String modelo;
@Column(name = "cor", nullable = false, length = 15)
private String cor;
@Column(name = "placa", nullable = false, length = 7)
private String placa;
@ManyToOne
@JoinColumn(name = "pessoa_id", referencedColumnName = "id", nullable = false)
private Pessoa pessoa;
public Veiculos() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getCor() {
return cor;
}
public void setCor(String cor) {
this.cor = cor;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
}
| true
|
d2e3535b1bf8fe11b47be9db1dc74f07fafa4636
|
Java
|
hoon91/shop_pracitce
|
/Daily/src/main/java/com/daily/controller/MemberController.java
|
UTF-8
| 4,766
| 2.203125
| 2
|
[] |
no_license
|
package com.daily.controller;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import com.daily.service.MemberService;
import com.daily.vo.MemberVO;
@Controller
@RequestMapping(value="/member")
public class MemberController {
@Inject
MemberService memberService;
@RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup() {
return "member/signup";
}
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(MemberVO vo, @ModelAttribute("detailAddress") String detailAddress) throws Exception {
String address= vo.getUseraddress() + " " + detailAddress;
if (detailAddress == null) {
address = vo.getUseraddress();
}
vo.setUseraddress(address);
memberService.signup(vo);
return "redirect:/member/read/" + vo.getUserid();
}
@RequestMapping(value = "/read/{userid}", method = RequestMethod.GET)
public String read(@PathVariable("userid") String userid, Model model) throws Exception {
MemberVO vo = memberService.read(userid);
model.addAttribute("userInfo", vo);
return "member/read";
}
@ResponseBody /* return되는 값은 view의 주소가 아닌 데이터임을 나타내는 어노테이션 */
@RequestMapping(value = "/idCheck", method = RequestMethod.POST)
public int idCheck(MemberVO vo) throws Exception {
String userid = vo.getUserid();
int result = memberService.idCheck(userid);
/* 만약, DB에 ID가 존재하면 1을, 존재하지 않으면 0을 return 할 것임 */
return result;
}
@RequestMapping(value = "/update/{userid}", method = RequestMethod.GET)
public String update(@PathVariable("userid") String userid, Model model) throws Exception {
MemberVO vo = memberService.updateUI(userid);
model.addAttribute("userInfo", vo);
return "member/update";
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(MemberVO vo, @ModelAttribute("detailAddress") String detailAddress) throws Exception {
/* detailAddress : 상세주소 받아오기 */
String adderss = vo.getUseraddress() + " " + detailAddress;
if (detailAddress == null) {
adderss = vo.getUseraddress();
}
vo.setUseraddress(adderss);
memberService.update(vo);
ModelAndView mav = new ModelAndView();
RedirectView redirectView = new RedirectView();
redirectView.setUrl("/member/read/" + vo.getUserid());
redirectView.setExposeModelAttributes(false);
mav.setView(redirectView);
return mav;
}
@RequestMapping(value="/delete/{userid}", method=RequestMethod.GET)
public String delete(@PathVariable("userid") String userid, Model model) throws Exception {
MemberVO vo = memberService.read(userid);
model.addAttribute("userInfo", vo);
return "member/delete";
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(MemberVO vo) throws Exception {
memberService.delete(vo);
return "redirect:/";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginGet() {
return "member/login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginPost(MemberVO vo, HttpServletRequest request, RedirectAttributes rttr) throws Exception {
MemberVO member = memberService.login(vo);
HttpSession session = request.getSession();
if(member != null) {
session.setAttribute("member", member);
} else {
session.setAttribute("member", null);
rttr.addFlashAttribute("msg", false);
return "redirect:/member/login";
}
return "redirect:/";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect("/");
}
}
| true
|
e0a68754085e267cc829383a341543eca2c29c40
|
Java
|
meelrossi/ati-projects
|
/src/controller/tab/SusanTab.java
|
UTF-8
| 1,611
| 2.515625
| 3
|
[] |
no_license
|
package controller.tab;
import java.io.IOException;
import border.SusanBorderAndCorner;
import components.view.OpenImage;
import components.view.SaveImage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import model.ColorImage;
public class SusanTab extends Tab {
@FXML
private OpenImage image;
@FXML
private SaveImage resultImage1;
@FXML
private SaveImage resultImage2;
@FXML
private TextField tField;
@FXML
private TextField toleranceField;
@FXML
private Button calculateButton;
public SusanTab() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/susanTab.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public void initialize() {
image.initialize(this::checkResult);
tField.setPromptText("t");
toleranceField.setPromptText("tolerance");
calculateButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
checkResult();
}
});
}
public void checkResult() {
SusanBorderAndCorner border = new SusanBorderAndCorner(Integer.parseInt(tField.getText()), Double.parseDouble(toleranceField.getText()));
ColorImage img1 = image.getImage();
if (img1 != null) {
resultImage1.setImage(border.markBorders(img1));
resultImage2.setImage(border.markCorners(img1));
}
}
}
| true
|
d8677f2fe5c276936c74d1a4193e686782f9e0eb
|
Java
|
msimar/RouteTable
|
/src/com/mps/dsp/core/TableEntry.java
|
UTF-8
| 2,603
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
package com.mps.dsp.core;
/**
* A class represent rows for the Routing Table of Node.
* It is the basic data structure used to represent row
* in the routing table for each Node.
*
* @author msingh
*
*/
public final class TableEntry implements Comparable<TableEntry>{
/**
* the Destination Node address
*/
public String destination;
/**
* Number of hops between source and destination
*/
public int metric;
/**
* the Source Node address
*/
public String source;
/**
* the Routing interface
*/
public String _interface;
/**
* Creates TableEntry object
* @param source the source Node address
* @param destination the destination Node address
* @param metric the hop between nodes
*/
public TableEntry(String source, String destination, int metric) {
// TODO Auto-generated constructor stub
this.source = source;
this.destination = destination;
this.metric = metric;
this._interface = "eth0";
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return String.format("%15s | %15s | %10s | %4d",this.source, this.destination, this._interface, this.metric);
}
/**
* Create basic template for the given values to represent table entry for routing table.
*
* @param sourceIndex the index for the source node
* @param source the source Node address
* @param destinationIndex the index for the destination node
* @param destination the destination Node address
* @return A String representation of formatted table entry
*/
public static String getTemplate(int sourceIndex, String source, int destinationIndex, String destination){
return String.format("%15s | %15s | %10s | %4d",
"[" + sourceIndex + "]" + source,
"[" + destinationIndex + "]" + destination,
"eth0", 1);
}
/**
* @see java.lang.Comparable#compareTo
*/
@Override
public int compareTo(TableEntry o) {
// TODO Auto-generated method stub
return metric - o.metric;
}
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + metric;
// return result;
// }
//
// /**
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// TableEntry other = (TableEntry) obj;
// if (metric != other.metric)
// return false;
// return true;
// }
}
| true
|
28dec266d40dd70be96918da24277212673e3303
|
Java
|
aksen2011/cal
|
/src/cal/main.java
|
UHC
| 1,128
| 3.5625
| 4
|
[] |
no_license
|
package cal;
public class main {
public static void main(String[] args) {
<<<<<<< HEAD
=======
System.out.println("ù° ڸ Է ּ.");
int n1=(new Scanner(System.in)).nextInt();
System.out.println("ù° ڸ Է ּ.");
int n2=(new Scanner(System.in)).nextInt();
String s=(new Scanner(System.in)).next();
switch(s) {
case "+":
add(n1,n2);
break;
case "-":
min(n1,n2);
break;
case "*":
mul(n1,n2);
break;
case "/":
div(n1,n2);
break;
}
}
void add(int n1,int n2) {
System.out.println(" "+(n1+n2));
}
void minus(int n1, int n2) {
System.out.println(" "+(n1-n2));
}
void max(int n1, int n2, int nMax) {
nMax = n1;
System.out.println(" "+(nMax>n2?nMax:n2));
}
void min(int n1, int n2, int nMin) {
nMin = n1;
System.out.println(" "+(nMin<n2?nMin:n2));
}
void makePic(int n1, int n2) {
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
System.out.print(" .");
}System.out.println();
}
>>>>>>> 447a13e1489967af534d83b7509d717d5ba766ad
}
}
| true
|
2e0b5d958876564bdd8b9dc99026ec3ffeb0e213
|
Java
|
frameworksselenium/LatestPC
|
/src/main/java/com/pc/driver/ParallelE2EDriver.java
|
UTF-8
| 5,185
| 2.265625
| 2
|
[] |
no_license
|
package com.pc.driver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.pc.utilities.FlatFile;
import com.pc.utilities.HTML;
import com.pc.utilities.XlsxReader;
public class ParallelE2EDriver {
static Logger log = null;
//private org.apache.log4j.Logger log;
private Socket socket = null;
// private DataInputStream console = null;
// private DataOutputStream streamOut = null;
private DataInputStream serverStreamIn = null;
private static ConcurrentLinkedQueue<String> testCaseNames = new ConcurrentLinkedQueue<String>();
@BeforeSuite
public void loadConfig() throws Exception {
PropertyConfigurator.configure("log4j.properties");
log = Logger.getLogger(ParallelE2EDriver.class);
//log = LoggerClass.getThreadLogger("Thread" + Thread.currentThread().getName(),strTestCaseName);
try {
HTML.fnSummaryInitialization("Execution Summary Report");
System.out.println("end2endTestCaseName = executeTestCase=");
// commented below line for end to end framework
// XlsxReader.getInstance().addTestCasesFromDataSheetName(testCaseNames);
log.info("Inside BeforeSuite");
for (int i = 0; i < Integer.parseInt(HTML.properties.getProperty("VERYLONGWAIT")); i++) {
try {
Thread.sleep(5000);
socket = new Socket("localhost", 9900);
serverStreamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
break;
} catch (InterruptedException e) {
} catch (java.net.ConnectException e) {
log.info("waiting for E2E server to open connection on port 9900. Exception details below");
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Parameters({ "DataSheetName", "Region", "end2endTestCaseName", "executeTestCase" })
@Test(priority = 1, enabled = true)
public void testParallele2e3(String DataSheetName, String Region, String end2endTestCaseName, String executeTestCase) throws Exception {
log.info("Test NG Thread Started....");
boolean exitLoop = false;
boolean isTestCasePass = false;
String testCaseName = null;
int nThreads = Integer.parseInt((String) HTML.properties.getProperty("THREAD_COUNT"));
log.info("Total Number of Threads = " + HTML.properties.getProperty("THREAD_COUNT"));
ExecutorService multiThreadExecutor = Executors.newFixedThreadPool(nThreads);
try {
testCaseName = testCaseNames.remove();
} catch (java.util.NoSuchElementException e) {
exitLoop = true;
}
if (testCaseName == null) {
exitLoop = true;
}
// while(!exitLoop){
while (true) {
if (testCaseName != null) { // added this if condition for end to end testing
log.info("Running test case in testParallele2e3 = " + testCaseName);
ParallelExecutor parallelExecutor = new ParallelExecutor("RunModeNo", testCaseName, "", Region);
multiThreadExecutor.execute(parallelExecutor);
testCaseName = null;
}
try {
testCaseName = testCaseNames.remove();
} catch (java.util.NoSuchElementException e) {
exitLoop = true;
}
if (testCaseName == null) {
exitLoop = true;
}
}
}
// added this method for end to end testing
@Parameters({ "DataSheetName", "Region", "end2endTestCaseName", "executeTestCase" })
@Test(priority = 1, enabled = true)
public void populateConcurrentLinkedQueue(String DataSheetName, String Region, String end2endTestCaseName, String executeTestCase) throws Exception {
String testCaseName = null;
while (testCaseName == null || (testCaseName != null && !testCaseName.equalsIgnoreCase("shutdown"))) {
testCaseName = null;
testCaseName = serverStreamIn.readUTF();// reading from socket
log.info("Message Received From Server =" + testCaseName);
if (testCaseName != null && !testCaseName.equalsIgnoreCase("shutdown")) {
testCaseNames.add(testCaseName); // populating into concurrentlinkedqueue
System.out.println("Added TestCase Into concurrent linked queue. TestCaseName Received from Server =" + testCaseName);
}
System.out.println("Waiting for Server to send TestCaseName to execute....");
if (testCaseName.equalsIgnoreCase("shutdown")) {
System.exit(0);
}
/*
* System.out.println("Enter Message to send to Server =" + textFromServer);
* testCaseName = console.readLine();//DataInputStream.readUTF(console);
* streamOut.writeUTF(line); streamOut.flush();
*/
}
}
@AfterSuite
public void exitConfig() {
try {
XlsxReader.getInstance().closeConnections();
FlatFile.getInstance().flatFileClose();
HTML.fnSummaryCloseHtml(HTML.properties.getProperty("Release"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Inside AfterSuite");
}
}
| true
|
2cda38fab5d411246623f6c2b936a42a06f84d68
|
Java
|
JustShowTime/springboot-demo-rabbitmq
|
/src/main/java/com/example/demo/rabbit/consumer/DemoQueueConsumer.java
|
UTF-8
| 480
| 2.09375
| 2
|
[] |
no_license
|
package com.example.demo.rabbit.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author czq
* @Date 2020-06-24 17:13:15
*/
@Component
@RabbitListener(queues="demoQueue")
public class DemoQueueConsumer {
@RabbitHandler
public void recieved(String msg) {
System.out.println("[demoQueue] recieved message: "+msg);
}
}
| true
|
bf2fcb7035d198d28e82b4e694332604726e1f45
|
Java
|
ppark3/CourseRegistrationSystem
|
/Admin.java
|
UTF-8
| 723
| 3.46875
| 3
|
[] |
no_license
|
/* Admin class that extends the User class.
* Nothing much is used from this java file.
* It only has methods that would have been useful if the Admin were able to change his/her name. */
public class Admin extends User implements AdminInterface, java.io.Serializable {
// As of now, the default constructor for Admin sets the username and password to what Req09 requires.
public Admin() {
super("Admin", "Admin01", "FIRST NAME", "LAST NAME");
}
public Admin(String u, String p, String f, String l) {
super(u,p,f,l);
}
// Due to Req09, the Admin's login information will always be the same.
public String getUsername() {
return "Admin";
}
public String getPassword() {
return "Admin01";
}
}
| true
|
8c713e03f0df12d4ba82b496f3853e9e3f1e2139
|
Java
|
julioserafim/prontuariov1.3.1
|
/prontuario-v1.3.1/aplicacao/prontuario/src/main/java/ufc/npi/prontuario/controller/ProfessorFormularioController.java
|
UTF-8
| 2,656
| 2.109375
| 2
|
[] |
no_license
|
package ufc.npi.prontuario.controller;
import static ufc.npi.prontuario.util.ConfigurationConstants.PERMISSAO_ADMINISTRACAO;
import static ufc.npi.prontuario.util.ConfigurationConstants.PERMISSAO_ADMINISTRACAO_VERIFICACAO_ID_PROFESSOR;
import static ufc.npi.prontuario.util.PagesConstants.DETALHES_PROFESSOR;
import static ufc.npi.prontuario.util.PagesConstants.FORMULARIO_CADASTRAR_PROFESSOR;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import ufc.npi.prontuario.model.Papel;
import ufc.npi.prontuario.model.Servidor;
import ufc.npi.prontuario.service.AtendimentoService;
import ufc.npi.prontuario.service.TurmaService;
@Controller
@RequestMapping("/professor")
public class ProfessorFormularioController {
@Autowired
private TurmaService turmaService;
@Autowired
private AtendimentoService atendimentoService;
@PreAuthorize(PERMISSAO_ADMINISTRACAO)
@GetMapping("/cadastrar")
public ModelAndView formAdicionarProfessor(Servidor servidor) {
servidor.addPapel(Papel.PROFESSOR);
return new ModelAndView(FORMULARIO_CADASTRAR_PROFESSOR).addObject("servidor", servidor)
.addObject("papeis", Arrays.asList(Papel.PROFESSOR, Papel.ADMINISTRACAO, Papel.ATENDENTE));
}
@PreAuthorize(PERMISSAO_ADMINISTRACAO)
@GetMapping("/editar/{id}")
public ModelAndView formEditarProfessor(@PathVariable("id") Servidor professor, RedirectAttributes attributes) {
return new ModelAndView(FORMULARIO_CADASTRAR_PROFESSOR).addObject("servidor", professor)
.addObject("papeis", Arrays.asList(Papel.PROFESSOR, Papel.ADMINISTRACAO, Papel.ATENDENTE));
}
@PreAuthorize(PERMISSAO_ADMINISTRACAO_VERIFICACAO_ID_PROFESSOR)
@GetMapping("/detalhes/{id}")
public ModelAndView detalhes(@PathVariable("id") Servidor professor, Authentication authentication) {
ModelAndView mv = new ModelAndView(DETALHES_PROFESSOR);
mv.addObject("professor", professor);
mv.addObject("turmas", turmaService.buscarTurmasProfessor(professor));
if (professor.equals((Servidor) authentication.getPrincipal())) {
mv.addObject("atendimentos", atendimentoService.buscarAtendimentosNaoFinalizadosPorProfessor(professor));
}
return mv;
}
}
| true
|
a2114a8da30670c0bc7368100f58ad1301dfb61a
|
Java
|
azizarc88/SmartPrint_SapuSapu
|
/app/src/main/java/id/backbonedev/smartprint/App/TentangItemAdapter.java
|
UTF-8
| 2,054
| 2.140625
| 2
|
[] |
no_license
|
package id.backbonedev.smartprint.App;
import android.app.Activity;
import android.content.Context;
import android.icu.text.UFormat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
import id.backbonedev.smartprint.Data.ItemTentang;
import id.backbonedev.smartprint.R;
/**
* Created by Aziz Nur Ariffianto on 0009, 09 Jan 2018.
*/
public class TentangItemAdapter extends BaseAdapter
{
private String TAG = "#TentangItemAdapter#";
private Activity activity;
private LayoutInflater inflater;
private List<ItemTentang> itemTentangs;
private static Context cc;
public TentangItemAdapter(Activity activity, List<ItemTentang> itemTentangs)
{
this.activity = activity;
this.itemTentangs = itemTentangs;
}
@Override
public int getCount()
{
return itemTentangs.size();
}
@Override
public Object getItem(int i)
{
return itemTentangs.get(i);
}
@Override
public long getItemId(int i)
{
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup)
{
ItemTentang item = itemTentangs.get(i);
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_tentang, null);
TextView LTeks = view.findViewById(R.id.LTeks);
TextView LSubTeks = view.findViewById(R.id.LSubTeks);
ImageView IVIcon = view.findViewById(R.id.IVIcon);
if (TextUtils.isEmpty(item.getSubteks()))
LSubTeks.setVisibility(View.GONE);
LTeks.setText(item.getTeks());
LSubTeks.setText(item.getSubteks());
IVIcon.setImageResource(item.getIcon());
return view;
}
}
| true
|
977203ae66492f5f9e790d593b9a873114ef2126
|
Java
|
jaydi/Flag-android
|
/src/com/tankers/smile/services/apis/redeems/List.java
|
UTF-8
| 1,647
| 2
| 2
|
[] |
no_license
|
package com.tankers.smile.services.apis.redeems;
import java.io.IOException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.Key;
import com.tankers.smile.models.RedeemCollection;
import com.tankers.smile.services.apis.FlagClient;
import com.tankers.smile.services.apis.FlagRequest;
public class List extends FlagRequest<RedeemCollection> {
private static final String REST_PATH = "redeem";
protected List(FlagClient client) {
super(client, "GET", REST_PATH, null, RedeemCollection.class);
}
@Override
public HttpResponse executeUsingHead() throws IOException {
return super.executeUsingHead();
}
@Override
public HttpRequest buildHttpRequestUsingHead() throws IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List setAlt(String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setFields(String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUserIp(String userIp) {
return (List) super.setUserIp(userIp);
}
@Key
private int mark;
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
}
| true
|
9e825bdc1deb2c08bed9d95bedfa564713be3b76
|
Java
|
plutonic88/subgame
|
/src/support/ProfileInfo.java
|
UTF-8
| 2,667
| 2.828125
| 3
|
[] |
no_license
|
package support;
import static subgame.EGAUtils.getSB;
import static subgame.EGAUtils.nf;
import static subgame.EGAUtils.returnSB;
public final class ProfileInfo {
// the outcome represented
public final int[] outcome;
// the payoffs for this outcome
public final double[] payoffs;
// maximum number of possible deviations
public final int numPossibleDeviations;
// the number of deviations sampled
public int numDeviationsSampled;
// number of deviations that were beneficial
public int numBeneficial;
// maximum benefit to deviating
public double maxBenefit;
// total benefit for deviating (used to compute averages)
public double totBenefit;
public ProfileInfo(int[] outcome, double[] payoffs, int numPossibleDeviations) {
this.outcome = outcome.clone();
this.payoffs = payoffs.clone();
this.numPossibleDeviations = numPossibleDeviations;
this.numDeviationsSampled = 0;
this.numBeneficial = 0;
this.maxBenefit = Double.NEGATIVE_INFINITY;
this.totBenefit = 0;
}
public double getEpsBound() {
return Math.max(maxBenefit, 0d);
}
public double getAveBenefit() {
if (numDeviationsSampled <= 0) {
return Double.NEGATIVE_INFINITY;
}
return totBenefit / (double) numDeviationsSampled;
}
public double getFractionSampled() {
if (numPossibleDeviations <= 0) {
return Double.NEGATIVE_INFINITY;
}
return (double) numDeviationsSampled / (double) numPossibleDeviations;
}
public String toString() {
int numPlayers = outcome.length;
StringBuilder sb = getSB();
sb.append("PROFILE: [");
for (int i = 0; i < numPlayers - 1; i++) {
sb.append(outcome[i]).append(",");
}
sb.append(outcome[numPlayers - 1]).append("]");
sb.append(" Payoffs: [");
for (int i = 0; i < numPlayers - 1; i++) {
sb.append(nf.format(payoffs[i])).append(",");
}
sb.append(nf.format(payoffs[numPlayers - 1])).append("]");
// sb.append(" Epsilon Bound: " + nf.format(getEpsBound()));
sb.append(" Max Benefit: ").append(nf.format(maxBenefit));
if (numDeviationsSampled > 0) {
sb.append(" Ave Benefit: ").append(nf.format(totBenefit / (double) numDeviationsSampled));
} else {
sb.append(" Ave Benefit: NaN");
}
sb.append(" Num Beneficial: ").append(numBeneficial);
//sb.append(" Sampled: " + numDeviationsSampled);
if (numPossibleDeviations > 0) {
sb.append(" Fraction Sampled: ")
.append(nf.format((double) numDeviationsSampled / (double) numPossibleDeviations));
} else {
sb.append(" Fraction Sampled: NaN");
}
return returnSB(sb);
}
}
| true
|
628ad75de205e91a1a0a59b0ed0c621397e615f2
|
Java
|
karlis58rg/MovimientoVecinal
|
/app/src/main/java/mx/oax/movimientovecinal/ConfiguracionWidgets.java
|
UTF-8
| 2,247
| 1.9375
| 2
|
[] |
no_license
|
package mx.oax.movimientovecinal;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ConfiguracionWidgets extends AppCompatActivity {
public static int num_imag = 0;
Button btnCrearWidget,btnCambiarImagen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuracion_widgets);
btnCambiarImagen = findViewById(R.id.boton_cambiar_imagen1);
btnCrearWidget = findViewById(R.id.boton_crear_widget1);
btnCambiarImagen.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View view) {
num_imag = (++num_imag)%2;
AppWidgetManager mAppWidgetManager = view.getContext().getSystemService(AppWidgetManager.class);
Intent intent = new Intent(getApplication(),MiWidget.class);
intent.setAction(mAppWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = mAppWidgetManager.getAppWidgetIds(new ComponentName(getApplication(),MiWidget.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);
}
});
btnCrearWidget.setOnClickListener(new View.OnClickListener() {
@SuppressLint("NewApi")
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View view) {
AppWidgetManager mAppWidgetManager = view.getContext().getSystemService(AppWidgetManager.class);
ComponentName myProvider = new ComponentName(view.getContext(),MiWidget.class);
if(mAppWidgetManager.isRequestPinAppWidgetSupported()){
mAppWidgetManager.requestPinAppWidget(myProvider,null,null);
}
}
});
}
}
| true
|
b0f27086d23eb8f83b11307fadaa40d0a4edc8d3
|
Java
|
OleksiiT-in6k/subsequence
|
/test/SequenceTest.java
|
UTF-8
| 1,736
| 2.78125
| 3
|
[] |
no_license
|
/**
* Created by employee on 7/8/16.
*/
import com.interlink.FindingSequence;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.interlink.FindingSequence.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
public class SequenceTest {
@org.junit.Test
public void nullSequenceTest() throws Exception {
assertThat(getSubSequence(null), is(new ArrayList()));
}
@Test
public void emptySequenceTest() throws Exception {
assertThat(getSubSequence(new ArrayList<>()), is(new ArrayList()));
}
@Test
public void singleNumberTest() throws Exception {
List<Integer> input = new ArrayList<>(Arrays.asList(1));
List<Integer> real = getSubSequence(input);
assertThat(real, is(new ArrayList<>(Arrays.asList(1))));
}
@Test
public void doubleNumberTest() throws Exception {
List<Integer> input = new ArrayList<>(Arrays.asList(1, 8));
List<Integer> real = getSubSequence(input);
assertThat(real, is(new ArrayList<>(Arrays.asList(1, 8))));
}
@Test
public void multipleNumberTest() throws Exception {
List<Integer> input = new ArrayList<>(Arrays.asList(8, 9, -1, 3));
List<Integer> real = getSubSequence(input);
assertThat(real, is(new ArrayList<>(Arrays.asList(8, 9, -1, 3))));
}
@Test
public void allPositiveNumbers() throws Exception {
List<Integer> input = new ArrayList<>(Arrays.asList(8, 9, 7, 3));
List<Integer> real = getSubSequence(input);
assertThat(real, is(new ArrayList<>(Arrays.asList(8, 9, 7, 3))));
}
}
| true
|
5e1d5582011d8f23eed52666137ef6655b660d8c
|
Java
|
iuji/BakingApp
|
/app/src/main/java/com/example/android/bakingapp/utils/Constants.java
|
UTF-8
| 283
| 1.6875
| 2
|
[] |
no_license
|
package com.example.android.bakingapp.utils;
public final class Constants {
public Constants() {
}
// Retrofit
public static final String BASE_URL_API = "http://go.udacity.com/";
// Widget
public static final String RECIPE_TO_WIDGET = "recipe_to_widget";
}
| true
|
549281c2b5adfcda2aee78dd4255d2492ba2e94a
|
Java
|
p1212012/game_dev
|
/royalClash/src/entity/Entity.java
|
UTF-8
| 1,790
| 2.53125
| 3
|
[] |
no_license
|
package entity;
import java.awt.Graphics2D;
import states.Main;
import util.MouseHandle;
import util.Vector2f;
public abstract class Entity {
private final int Up = 0;
private final int Down = 1;
private final int Right = 2;
private final int Left = 3;
private final int sky = 0;
private final int ground = 1;
private final int tower = 2;
public Vector2f pos;
protected int delayDamage;
protected boolean attackReady;
protected boolean side;
protected boolean woodHit;
protected int kind;
protected int size;
protected Vector2f dir;
protected int attackCooldown;
protected int health;
protected int damage;
protected int prepareToAttack;
protected int updateTimes;
protected int range;
protected float speed;
protected float deacc;
protected float dirX;
protected float dirY;
protected final float UTBD = 30;// update times before detect
public Entity(Vector2f position, int size, int health, int attackCooldown, int speed, int damage, boolean side, int kind, int range) {
pos = position;
this.range = range;
this.size = size;
this.damage = damage;
this.health = health;
this.attackCooldown = attackCooldown*60;
this.speed = speed;
this.kind = kind;
this.side = side;
woodHit = false;
updateTimes = 0;
prepareToAttack = 0;
attackReady = false;
setDir(new Vector2f(0,0));
}
public int gethurt(int damage) {
health -= damage;
return health;
}
protected void setDir(Vector2f vec) {
dir = vec;
dirX = vec.x;
dirY = vec.y;
}
public int returnHealth() {
return health;
}
public float getSize() {return size;}
public abstract void update();
public abstract void render(Graphics2D g) ;
}
| true
|
57115f96c0684f343fe54bb218a0eda9080bce19
|
Java
|
cor-serpentis/server
|
/src/main/java/gsg/server/logic/GameLoop.java
|
UTF-8
| 1,974
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package gsg.server.logic;
import gsg.infrastructure.Utils;
import gsg.infrastructure.messages.IContainer;
import gsg.infrastructure.messages.MessageContainer;
import gsg.network.ConnectionLibrary;
import gsg.network.InputLoop;
import gsg.network.OutputLoop;
import gsg.network.provider.ProviderFactory;
import gsg.network.provider.input.InputStreamProvider;
import gsg.server.infrastructure.ConnectionRegistrator;
import gsg.server.network.ConnectionLoop;
import gsg.threads.IJob;
import gsg.threads.JobRunnerConfiguration;
import gsg.threads.JobRunnerData;
import org.jbox2d.testbed.framework.TestbedController;
import org.jbox2d.testbed.framework.TestbedFrame;
import org.jbox2d.testbed.framework.TestbedModel;
import org.jbox2d.testbed.framework.TestbedPanel;
import org.jbox2d.testbed.framework.j2d.TestPanelJ2D;
import javax.swing.*;
import java.net.Socket;
/**
* @author zkejid@gmail.com
* Created: 14.07.15 23:36
*/
public class GameLoop implements IJob {
private final DumbView frame;
private final MessageLoop messageLoop;
private final ConnectionLoop connectionLoop;
public GameLoop() {
frame = new DumbView();
final MessageTransport messageTransport = new MessageTransport();
final IContainer frameSide = messageTransport.getSide1();
final ServerMessageProcessor messageProcessor = new ServerMessageProcessor(frame, frameSide);
messageLoop = new MessageLoop(messageProcessor);
connectionLoop = new ConnectionLoop(9189, messageLoop);
TestbedModel model = new TestbedModel();
model.addTest(frame);
TestbedPanel panel = new TestPanelJ2D(model);
JFrame testbed = new TestbedFrame(model, panel, TestbedController.UpdateBehavior.UPDATE_CALLED);
testbed.setVisible(true);
testbed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void onStart(){
Utils.runLoop(messageLoop);
Utils.runLoop(connectionLoop);
}
@Override
public void doJob(JobRunnerConfiguration configuration, JobRunnerData jobRunnerData) {
}
}
| true
|
e9585f965be5f368d5d8105f1c54753f595efccb
|
Java
|
kosztadani/example_mock
|
/src/main/java/dev/kosztadani/examples/mock/api/Sensor.java
|
UTF-8
| 157
| 2.21875
| 2
|
[
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
package dev.kosztadani.examples.mock.api;
public interface Sensor {
/**
* @return The temperature, in degrees Celsius.
*/
int sense();
}
| true
|
57f670712136c8da49a9e72d5c12e54e5ade53e9
|
Java
|
ygSonggoon/CapstonProejct
|
/src/main/java/practice/capston/service/TextContentServiceImpl.java
|
UTF-8
| 2,276
| 2.375
| 2
|
[] |
no_license
|
package practice.capston.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import practice.capston.domain.entity.Image;
import practice.capston.domain.entity.TextContent;
import practice.capston.repository.ImageRepository;
import practice.capston.repository.TextContentRepository;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TextContentServiceImpl implements TextContentService {
private final TextContentRepository textContentRepository;
private final ImageRepository imageRepository;
@Override
public List<TextContent> findAllTextContent(Long id) {
List<TextContent> textContentList = textContentRepository.findAllTextContent(id);
return textContentList;
}
@Override
@Transactional
public TextContent createTextContent(String result, Long imageId) {
Optional<Image> imageById = imageRepository.findImageById(imageId);
if(imageById.isEmpty()){
throw new IllegalStateException("TextContentServiceImpl: 32");
}
Image image = imageById.get();
TextContent textContent = new TextContent(result, image);
TextContent save = textContentRepository.save(textContent);
return save;
}
@Transactional
@Override
public TextContent updateTextContent(Long id, String newValue) {
Optional<TextContent> textContent = textContentRepository.findById(id);
if(textContent.isEmpty()){
throw new IllegalStateException("TextContentServiceImpl: 47");
}
TextContent findTextContent = textContent.get();
findTextContent.changeNewText(newValue);
return findTextContent;
}
@Override
public TextContent findTextById(Long id) {
Optional<TextContent> textContent = textContentRepository.findById(id);
return textContent.get();
}
@Override
@Transactional
public TextContent removeTextById(Long id) {
Optional<TextContent> textContent = textContentRepository.findById(id);
textContentRepository.delete(textContent.get());
return null;
}
}
| true
|
f3bfe39ce918a421afe26f4384858f8bd28dfa27
|
Java
|
zhaoshuzhen01/project
|
/LubanCustom/baselibrary/src/main/java/com/example/baselibrary/photomanager/CacheManager.java
|
UTF-8
| 1,277
| 2.609375
| 3
|
[] |
no_license
|
package com.example.baselibrary.photomanager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import java.io.File;
/**
* 路径及缓存管理
* Created by lile on 15-11-15.
*/
public class CacheManager {
public static final String DIR_CACHE = Environment.getExternalStorageDirectory() + "/";
/**
* 获取图片缓存路径 如果不存在,则创建路径
*
* @param context
* @return
*/
public static String getImgDir(Context context) {
String packageName = context.getPackageName();
String path = DIR_CACHE + "luban_image/camera/";
// String path = DIR_CACHE + "/.img/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
return path;
}
/**
* 清除缓存图片
*/
public static void chearImgCache(Context context) {
try {
String imgDir = getImgDir(context);
File dir = new File(imgDir);
if (dir != null && dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
file.delete();
}
}
} catch (Exception e) {
}
}
}
| true
|
1a035cc3869a0daeca7d24ec31828bcff525f8e9
|
Java
|
bayern39/core
|
/gui/src/main/java/org/jboss/as/console/client/tools/modelling/workbench/repository/UndertowExample.java
|
UTF-8
| 5,963
| 2.015625
| 2
|
[] |
no_license
|
package org.jboss.as.console.client.tools.modelling.workbench.repository;
import org.jboss.as.console.mbui.model.StereoTypes;
import org.jboss.as.console.mbui.model.mapping.DMRMapping;
import org.useware.kernel.model.Dialog;
import org.useware.kernel.model.mapping.Mapping;
import org.useware.kernel.model.structure.Container;
import org.useware.kernel.model.structure.InteractionUnit;
import org.useware.kernel.model.structure.QName;
import org.useware.kernel.model.structure.Select;
import org.useware.kernel.model.structure.builder.Builder;
import static org.jboss.as.console.mbui.model.StereoTypes.Form;
import static org.jboss.as.console.mbui.model.StereoTypes.Pages;
import static org.useware.kernel.model.structure.TemporalOperator.Choice;
import static org.useware.kernel.model.structure.TemporalOperator.Concurrency;
/**
* @author Heiko Braun
* @date 5/14/13
*/
public class UndertowExample implements Sample {
private final Dialog dialog;
public UndertowExample() {
this.dialog = build();
}
public Dialog build()
{
String ns = "org.jboss.undertow";
// entities
Mapping global = new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow");
Container overview = new Container(ns, "undertow", "Undertow Subsytem", Choice, StereoTypes.EditorPanel);
Container handler = new Container(ns, "handler", "Handler", Choice, Pages);
Container filter = new Container(ns, "filter", "Filter", Choice, Pages);
Container errorHandler = new Container(ns, "errorHandler", "Error Handler", Choice, Pages);
Container fileHandler = new Container(ns, "undertow#fileHandler", "File Handler", Concurrency);
// structure & mapping
InteractionUnit root = new Builder()
.start(overview)
.mappedBy(global)
.start(handler)
.start(fileHandler)
.add(new Select(ns, "fileHandler", "FileHandlerSelection"))
.mappedBy(
new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=handler/file=*")
.addAttributes("entity.key", "path")
)
.add(new Container(ns, "undertow#fileAttributes", "Attributes",Form))
.mappedBy(new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=handler/file={selected.entity}")
)
.end()
.end()
/*.start(errorHandler)
.start(new Container(ns, "undertow#error", "Error Pages", Concurrency))
.add(new Select(ns, "errorHandler", "ErrorHandlerSelection"))
.mappedBy(
new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=error-handler/error-page=*")
.addAttributes("entity.key", "path")
)
.add(new Container(ns, "undertow#errorHandlerAttributes", "Attributes",Form))
.mappedBy(new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=error-handler/error-page={selected.entity}")
)
.end()
.end() */
.start(filter)
.start(new Container(ns, "undertow#basicAuth", "Basic Auth", Concurrency))
.add(new Select(ns, "undertow#basicAuthSelection", "BasicAuthSelection"))
.mappedBy(
new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=filter/basic-auth=*")
.addAttributes("entity.key")
)
.add(new Container(ns, "undertow#filterAuthAttributes", "Attributes",Form))
.mappedBy(new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=filter/basic-auth={selected.entity}")
)
.end()
.start(new Container(ns, "undertow#connectionLimit", "Connection Limit", Concurrency))
.add(new Select(ns, "undertow#connectionLimitSelection", "connectionLimitSelection"))
.mappedBy(
new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=filter/connection-limit=*")
.addAttributes("entity.key")
)
.add(new Container(ns, "undertow#connectionLimitAttributes", "Attributes",Form))
.mappedBy(new DMRMapping()
.setAddress("/{selected.profile}/subsystem=undertow/configuration=filter/connection-limit={selected.entity}")
)
.end()
.end()
.end()
.build();
Dialog dialog = new Dialog(QName.valueOf("org.jboss.as:undertow-subsystem"), root);
return dialog;
}
@Override
public String getName() {
return "undertow";
}
@Override
public Dialog getDialog() {
return dialog;
}
}
| true
|
215903e04ee4ae4309e24b18f1d9a489864a7a87
|
Java
|
KMuraliReddy/ISI-Projects
|
/Java-Project/Test/src/MyModelListener.java
|
UTF-8
| 381
| 2.453125
| 2
|
[] |
no_license
|
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class MyModelListener implements TableModelListener {
@Override
public void tableChanged(TableModelEvent e) {
//The table model has been changed, update the progressbar
MyFrame.bar.setValue(MyFrame.bar.getValue() + 1);
}
}
| true
|
5c1517a62caa47d12ee9f5de7c7ac3ddc8cd4063
|
Java
|
yangzongzhuan/RuoYi
|
/ruoyi-system/src/main/java/com/ruoyi/system/domain/SysOperLog.java
|
UTF-8
| 6,720
| 1.882813
| 2
|
[
"MIT"
] |
permissive
|
package com.ruoyi.system.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Date;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 操作日志记录表 oper_log
*
* @author ruoyi
*/
public class SysOperLog extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 日志主键 */
@Excel(name = "操作序号", cellType = ColumnType.NUMERIC)
private Long operId;
/** 操作模块 */
@Excel(name = "操作模块")
private String title;
/** 业务类型(0其它 1新增 2修改 3删除) */
@Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据")
private Integer businessType;
/** 业务类型数组 */
private Integer[] businessTypes;
/** 请求方法 */
@Excel(name = "请求方法")
private String method;
/** 请求方式 */
@Excel(name = "请求方式")
private String requestMethod;
/** 操作类别(0其它 1后台用户 2手机端用户) */
@Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户")
private Integer operatorType;
/** 操作人员 */
@Excel(name = "操作人员")
private String operName;
/** 部门名称 */
@Excel(name = "部门名称")
private String deptName;
/** 请求url */
@Excel(name = "请求地址")
private String operUrl;
/** 操作地址 */
@Excel(name = "操作地址")
private String operIp;
/** 操作地点 */
@Excel(name = "操作地点")
private String operLocation;
/** 请求参数 */
@Excel(name = "请求参数")
private String operParam;
/** 返回参数 */
@Excel(name = "返回参数")
private String jsonResult;
/** 操作状态(0正常 1异常) */
@Excel(name = "状态", readConverterExp = "0=正常,1=异常")
private Integer status;
/** 错误消息 */
@Excel(name = "错误消息")
private String errorMsg;
/** 操作时间 */
@Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date operTime;
/** 消耗时间 */
@Excel(name = "消耗时间", suffix = "毫秒")
private Long costTime;
public Long getOperId()
{
return operId;
}
public void setOperId(Long operId)
{
this.operId = operId;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public Integer getBusinessType()
{
return businessType;
}
public void setBusinessType(Integer businessType)
{
this.businessType = businessType;
}
public Integer[] getBusinessTypes()
{
return businessTypes;
}
public void setBusinessTypes(Integer[] businessTypes)
{
this.businessTypes = businessTypes;
}
public String getMethod()
{
return method;
}
public void setMethod(String method)
{
this.method = method;
}
public String getRequestMethod()
{
return requestMethod;
}
public void setRequestMethod(String requestMethod)
{
this.requestMethod = requestMethod;
}
public Integer getOperatorType()
{
return operatorType;
}
public void setOperatorType(Integer operatorType)
{
this.operatorType = operatorType;
}
public String getOperName()
{
return operName;
}
public void setOperName(String operName)
{
this.operName = operName;
}
public String getDeptName()
{
return deptName;
}
public void setDeptName(String deptName)
{
this.deptName = deptName;
}
public String getOperUrl()
{
return operUrl;
}
public void setOperUrl(String operUrl)
{
this.operUrl = operUrl;
}
public String getOperIp()
{
return operIp;
}
public void setOperIp(String operIp)
{
this.operIp = operIp;
}
public String getOperLocation()
{
return operLocation;
}
public void setOperLocation(String operLocation)
{
this.operLocation = operLocation;
}
public String getOperParam()
{
return operParam;
}
public void setOperParam(String operParam)
{
this.operParam = operParam;
}
public String getJsonResult()
{
return jsonResult;
}
public void setJsonResult(String jsonResult)
{
this.jsonResult = jsonResult;
}
public Integer getStatus()
{
return status;
}
public void setStatus(Integer status)
{
this.status = status;
}
public String getErrorMsg()
{
return errorMsg;
}
public void setErrorMsg(String errorMsg)
{
this.errorMsg = errorMsg;
}
public Date getOperTime()
{
return operTime;
}
public void setOperTime(Date operTime)
{
this.operTime = operTime;
}
public Long getCostTime()
{
return costTime;
}
public void setCostTime(Long costTime)
{
this.costTime = costTime;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("operId", getOperId())
.append("title", getTitle())
.append("businessType", getBusinessType())
.append("businessTypes", getBusinessTypes())
.append("method", getMethod())
.append("requestMethod", getRequestMethod())
.append("operatorType", getOperatorType())
.append("operName", getOperName())
.append("deptName", getDeptName())
.append("operUrl", getOperUrl())
.append("operIp", getOperIp())
.append("operLocation", getOperLocation())
.append("operParam", getOperParam())
.append("status", getStatus())
.append("errorMsg", getErrorMsg())
.append("operTime", getOperTime())
.append("costTime", getCostTime())
.toString();
}
}
| true
|
21bb9ddf816fa095cd290aaf30104fecbce7e373
|
Java
|
gugaroodrigues/ExemploDAOTest
|
/ExercicioDAOTestFilme/test/TestDAOFilme.java
|
UTF-8
| 1,115
| 2.234375
| 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.
*/
import dao.FilmeDAO;
import Bean.Filme;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Alunos
*/
public class TestDAOFilme {
@Test
public void testCadastro() {
FilmeDAO dao = new FilmeDAO();
Filme filme = new Filme();
filme.setId(1);
filme.setNome("O programador");
filme.setAno(2018);
filme.setCategoria("Terror");
filme.setFaixaEtaria("+18");
filme.setAtorPrincipal("Eu");
filme.setDiretor("Eu de novo");
filme.setDublado(false);
filme.setLegenda(true);
filme.setTempoFilme((short)646);
filme.setOrcamento(9001);
filme.setFaturamento(1000.00);
int filmezinho = dao.inserir(filme);
assertNotSame(filmezinho, -1);
}
@Test
public void testEditar(){
}
@Test
public void testApagar(){
}
}
| true
|
ecd3c8909dab60854785e2d5ee8bdfc28e790800
|
Java
|
JiaMingLiu93/homegrown
|
/basic/algorithm/src/main/java/com/homegrown/basic/algorithm/sort/BubbleSort.java
|
UTF-8
| 645
| 3.515625
| 4
|
[] |
no_license
|
package com.homegrown.basic.algorithm.sort;
import java.util.stream.Stream;
/**
* @author youyu
* @date 2020/1/21 10:54 PM
*/
public class BubbleSort {
public static void main(String[] args) {
Integer []a = of(3,2,1,5,4);
for (int i=0;i<a.length;i++){
for (int j=0;j<a.length-1-i;j++){
if (a[j].compareTo(a[j+1]) > 0){
Integer t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
Stream.of(a).forEach(System.out::print);
}
public static Integer[] of(Integer... a){
return a;
}
}
| true
|
ae53dffc34c86d27e37e68e707e6709b2b7e02eb
|
Java
|
MDE4CPP/MDE4CPP
|
/generator/UML4CPP/UML4CPP.generator/src/UML4CPP/generator/main/helpers/IDGeneratorService.java
|
UTF-8
| 479
| 2.59375
| 3
|
[
"EPL-1.0",
"MIT"
] |
permissive
|
package UML4CPP.generator.main.helpers;
public class IDGeneratorService {
public String polynomialRollingHash(String key)
{
//generate a hash value from string using polynomial rolling hash
int n = key.length();
int m = (int) (10e9 + 9);
int p = 53;
long powerOfP = 1;
long hash = 0;
for(int i = 0; i < n; i++)
{
int c = key.charAt(i);
hash = (hash + c * powerOfP) % m;
powerOfP = (powerOfP * p) % m;
}
return Long.toString(hash);
}
}
| true
|
9d923aaf4455f68a9fa0ba7514b59f30156b037c
|
Java
|
pabloblancoo/ShareMyTrip-V2
|
/sdi3-12-EJB/ejbModule/com/sdi/business/impl/classes/rating/EliminarRating.java
|
UTF-8
| 280
| 2.015625
| 2
|
[] |
no_license
|
package com.sdi.business.impl.classes.rating;
import com.sdi.infrastructure.Factories;
public class EliminarRating {
public boolean run(long id) {
try {
Factories.persistence.newRatingDao().delete(id);
return true;
} catch (Exception e) {
return false;
}
}
}
| true
|
911ce3c61f1d6320441a1d3f96f0c2941f4e479d
|
Java
|
deliaserbanescu/SerbanescuAndreeaDelia1072
|
/ProiectCTS/src/clase/ListaProfesori.java
|
UTF-8
| 118
| 1.71875
| 2
|
[] |
no_license
|
package clase;
import java.util.List;
public interface ListaProfesori {
public List<String> getListaProfesori();
}
| true
|
f438614dd022cc66d8e9184da91b0fcc6d5fc536
|
Java
|
kiss9815/CopyKakaoTalk
|
/app/src/main/java/com/juntcompany/copykakaotalk/TalkList/TalkData.java
|
UTF-8
| 1,180
| 1.984375
| 2
|
[] |
no_license
|
package com.juntcompany.copykakaotalk.TalkList;
import android.graphics.drawable.Drawable;
import java.util.Date;
/**
* Created by EOM on 2016-02-07.
*/
public class TalkData {
private int room_profile;
private String room_name;
private String recent_speak;
private int room_people_count;
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getRecent_speak() {
return recent_speak;
}
public void setRecent_speak(String recent_speak) {
this.recent_speak = recent_speak;
}
public String getRoom_name() {
return room_name;
}
public void setRoom_name(String room_name) {
this.room_name = room_name;
}
public int getRoom_people_count() {
return room_people_count;
}
public void setRoom_people_count(int room_people_count) {
this.room_people_count = room_people_count;
}
public int getRoom_profile() {
return room_profile;
}
public void setRoom_profile(int room_profile) {
this.room_profile = room_profile;
}
}
| true
|
b84c3545cf2968d68ee08d8ff290f1e3b8ab9ea6
|
Java
|
justcodedroid/quwang
|
/app/src/main/java/com/example/admin/quwang/http/HeadsInterceptor.java
|
UTF-8
| 933
| 1.90625
| 2
|
[] |
no_license
|
package com.example.admin.quwang.http;
import android.util.Log;
import java.io.IOException;
import java.util.Set;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by admin on 2017/3/25.
*/
public class HeadsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder().addHeader("Authorization", " 8a817deda9d29b4cb23ab3a898f6e0ac")
.addHeader("sign", " e36db3569ac77938ea700ed315817ec0").
addHeader("App-Agent"," version=3.2.0,platform=android,app_store_name=zapp-wandoujia,software_version=6.0,models=Custom Phone - 6.0.0 - API 23 - 768x1280,package_name=com.weishang.qwapp,time=1489484134207")
.addHeader("User-Agent","okhttp/3.4.1").build();
return chain.proceed(request);
}
}
| true
|
635efb6a31032f5615023d25723e0206cebce13e
|
Java
|
Andreas237/AndroidPolicyAutomation
|
/ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/airbnb/lottie/ColorFactory.java
|
UTF-8
| 4,430
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.airbnb.lottie;
import android.graphics.Color;
import org.json.JSONArray;
class ColorFactory
implements AnimatableValue.Factory
{
ColorFactory()
{
// 0 0:aload_0
// 1 1:invokespecial #18 <Method void Object()>
// 2 4:return
}
public Integer valueFromObject(Object obj, float f)
{
obj = ((Object) ((JSONArray)obj));
// 0 0:aload_1
// 1 1:checkcast #22 <Class JSONArray>
// 2 4:astore_1
if(((JSONArray) (obj)).length() == 4)
//* 3 5:aload_1
//* 4 6:invokevirtual #26 <Method int JSONArray.length()>
//* 5 9:iconst_4
//* 6 10:icmpne 113
{
int i = 0;
// 7 13:iconst_0
// 8 14:istore 7
boolean flag = true;
// 9 16:iconst_1
// 10 17:istore 8
for(; i < ((JSONArray) (obj)).length(); i++)
//* 11 19:iload 7
//* 12 21:aload_1
//* 13 22:invokevirtual #26 <Method int JSONArray.length()>
//* 14 25:icmpge 51
if(((JSONArray) (obj)).optDouble(i) > 1.0D)
//* 15 28:aload_1
//* 16 29:iload 7
//* 17 31:invokevirtual #30 <Method double JSONArray.optDouble(int)>
//* 18 34:dconst_1
//* 19 35:dcmpl
//* 20 36:ifle 42
flag = false;
// 21 39:iconst_0
// 22 40:istore 8
// 23 42:iload 7
// 24 44:iconst_1
// 25 45:iadd
// 26 46:istore 7
//* 27 48:goto 19
if(flag)
//* 28 51:iload 8
//* 29 53:ifeq 62
f = 255F;
// 30 56:ldc1 #31 <Float 255F>
// 31 58:fstore_2
else
//* 32 59:goto 64
f = 1.0F;
// 33 62:fconst_1
// 34 63:fstore_2
double d = ((JSONArray) (obj)).optDouble(3);
// 35 64:aload_1
// 36 65:iconst_3
// 37 66:invokevirtual #30 <Method double JSONArray.optDouble(int)>
// 38 69:dstore_3
double d1 = f;
// 39 70:fload_2
// 40 71:f2d
// 41 72:dstore 5
return Integer.valueOf(Color.argb((int)(d * d1), (int)(((JSONArray) (obj)).optDouble(0) * d1), (int)(((JSONArray) (obj)).optDouble(1) * d1), (int)(((JSONArray) (obj)).optDouble(2) * d1)));
// 42 74:dload_3
// 43 75:dload 5
// 44 77:dmul
// 45 78:d2i
// 46 79:aload_1
// 47 80:iconst_0
// 48 81:invokevirtual #30 <Method double JSONArray.optDouble(int)>
// 49 84:dload 5
// 50 86:dmul
// 51 87:d2i
// 52 88:aload_1
// 53 89:iconst_1
// 54 90:invokevirtual #30 <Method double JSONArray.optDouble(int)>
// 55 93:dload 5
// 56 95:dmul
// 57 96:d2i
// 58 97:aload_1
// 59 98:iconst_2
// 60 99:invokevirtual #30 <Method double JSONArray.optDouble(int)>
// 61 102:dload 5
// 62 104:dmul
// 63 105:d2i
// 64 106:invokestatic #37 <Method int Color.argb(int, int, int, int)>
// 65 109:invokestatic #43 <Method Integer Integer.valueOf(int)>
// 66 112:areturn
} else
{
return Integer.valueOf(0xff000000);
// 67 113:ldc1 #44 <Int 0xff000000>
// 68 115:invokestatic #43 <Method Integer Integer.valueOf(int)>
// 69 118:areturn
}
}
public volatile Object valueFromObject(Object obj, float f)
{
return ((Object) (valueFromObject(obj, f)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:fload_2
// 3 3:invokevirtual #47 <Method Integer valueFromObject(Object, float)>
// 4 6:areturn
}
static final ColorFactory INSTANCE = new ColorFactory();
static
{
// 0 0:new #2 <Class ColorFactory>
// 1 3:dup
// 2 4:invokespecial #14 <Method void ColorFactory()>
// 3 7:putstatic #16 <Field ColorFactory INSTANCE>
//* 4 10:return
}
}
| true
|
e3c5f2a5ddef1f9830960e6a29cf03277e670626
|
Java
|
martaboteller/TripMemories_with_sidemenu
|
/app/src/main/java/model/Trip.java
|
UTF-8
| 4,714
| 2.625
| 3
|
[] |
no_license
|
package model;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
@Entity(tableName = "table_trips")
public class Trip {
//Definition of variables for HTTP
@SerializedName("uuid")
private UUID mUUID;
@SerializedName("name")
private String mName;
@SerializedName("country")
private String mCountry;
@SerializedName("date")
private Date mDate;
@SerializedName("comp")
private String mComp;
@SerializedName ("photo")
private String mPhoto;
@SerializedName ("deleted")
private int mDeleted;
@SerializedName("phone")
private String mPhone;
@SerializedName("latitude")
private Double mLatitude;
@SerializedName("longitude")
private Double mLongitude;
@SerializedName("location")
private String mLocation;
@SerializedName("photobase")
private String mPhotobase;
//Constructor1
public Trip(String name, String country){
mUUID = UUID.randomUUID();
this.mName = name;
this.mCountry = country;
this.mDate = new Date();
}
//Constructor2
public Trip(String name, String country,String comp){
mUUID = UUID.randomUUID();
this.mName = name;
this.mCountry = country;
this.mDate = new Date();
this.mComp = comp;
}
//Constructor3
public Trip(String name, String country,Date date,String comp,String photo,int deleted,String phone, Double latitude, Double longitude,String location,String photobase){
mUUID = UUID.randomUUID();
this.mName = name;
this.mCountry = country;
this.mDate = date;
this.mComp = comp;
this.mPhoto = photo;
this.mDeleted = deleted;
this.mPhone = phone;
this.mLatitude =latitude;
this.mLongitude = longitude;
this.mLocation = location;
this.mPhotobase = photobase;
}
//Getters and Setters
public UUID getUUID() {
return mUUID;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getCountry() {
return mCountry;
}
public void setCountry(String country) {
this.mCountry = country;
}
public Date getDate() {return mDate; }
public void setDate(@NonNull Date date) {mDate = date;}
public String getComp() {return mComp;}
public void setComp(String comp) {mComp = comp;}
public String getPhoto() { return "IMG_" + mUUID + ".jpg";}
public void setPhoto(String photo) {mPhoto = photo;}
public int getDeleted() {return mDeleted;}
public void setDeleted(int deleted) {mDeleted = deleted;}
public String getPhone() {return mPhone;}
public void setPhone(String phone) {mPhone = phone;}
public Double getLatitude() {return mLatitude;}
public void setLatitude(Double latitude) {mLatitude = latitude;}
public Double getLongitude() {return mLongitude;}
public void setLongitude(Double longitude) {mLongitude = longitude;}
public String getLocation() {return mLocation;}
public void setLocation(String location) {mLocation = location;}
public String getPhotobase() {return mPhotobase;}
public void setPhotobase(String photobase) {mPhotobase = photobase;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Trip trip = (Trip) o;
return getUUID().equals(trip.getUUID()) &&
getName().equals(trip.getName()) &&
Objects.equals(getCountry(), trip.getCountry()) &&
getDate().equals(trip.getDate());
}
@Override
public int hashCode() {
return Objects.hash(getUUID(), getName(), getCountry(), getDate(),
getComp(),getPhoto(),getDeleted(),getPhone(),getLatitude(),getLongitude());
}
@Override
public String toString() {
return "Trip{" +
"mUUID=" + mUUID +
", mName='" + mName + '\'' +
", mCountry='" + mCountry + '\'' +
", mDate=" + mDate + '\'' +
", mComp='" + mComp + '\'' +
", mPhoto='" + mPhoto + '\'' +
", mDeleted=" + mDeleted + '\'' +
", mPhone='" + mPhone + '\'' +
", mLatitude=" + mLatitude + '\'' +
", mLongitude=" + mLongitude + '\'' +
", mLocation='" + mLocation + '\'' +
", mPhotobase='" + mPhotobase + '\'' +
'}';
}
}
| true
|
2f7a421cbe5ec8b223ef61c9161edd5b775dba28
|
Java
|
Dmitriy-Topoplnik/hw_5_reload
|
/src/ru/hw_5/Utilites/CommandFactory.java
|
UTF-8
| 1,023
| 2.828125
| 3
|
[] |
no_license
|
package ru.hw_5.Utilites;
import ru.hw_5.Utilites.Commands.*;
/**
* Created by admin on 21.11.2016.
*/
public class CommandFactory{
public static ConsoleExectutable getCommand(String input) {
String[] command = input.split("\\s+");
String args ="";
for (int i = 1; i< command.length;i++){
args += command[i];
if (i!=command.length-1) args+=" ";
}
switch (command[0]) {
case "showProducts":
return new ShowProducts();
case "showProductImg":
return new ShowProductImg(args);
case "addToCart":
return new AddToCart(args);
case "showCart":
return new ShowCart();
case "deletefromCart":
return new DeleteFromCart(args);
case "help":
return new Help();
case "exit":
return new Exit();
default:
return new Help();
}
}
}
| true
|
29d3a44c0c665dfc58d11df2a5f71ad7bfc90cc3
|
Java
|
emsnguyen/NoBrainerGrammar---Java-Web-Final-Project
|
/src/java/controller/SelectController.java
|
UTF-8
| 1,304
| 2.21875
| 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 controller;
import dal.CategoryDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Category;
/**
*
* @author emsnguyen
*/
public class SelectController extends BaseAuthenticationController {
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
@Override
protected void handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CategoryDAO catDB = new CategoryDAO();
ArrayList<Category> cats = catDB.getAll();
request.getSession().setAttribute("cats", cats);
request.getRequestDispatcher("select.jsp").forward(request, response);
}
@Override
protected void handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| true
|
45832e26456c1840c6d9d4e26edb04750812c401
|
Java
|
rafal-perkowski/SpringApps
|
/app/SampleApp/src/main/java/pl/rp/app/service/ArtistServiceImpl.java
|
UTF-8
| 1,100
| 2.390625
| 2
|
[] |
no_license
|
package pl.rp.app.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.rp.app.controller.TestController;
import pl.rp.app.model.Artist;
import pl.rp.app.repository.ArtistRepository;
@Service
public class ArtistServiceImpl implements ArtistService {
@Autowired
private ArtistRepository artistRepository;
@Override
public List<Artist> getAllArtists() {
TestController.traceCounter(TestController.InsertType.INOUT, "ArtistServiceImpl getAllArtists()");
return artistRepository.findAll();
}
@Override
public boolean isExist(String name, String surname) {
TestController.traceCounter(TestController.InsertType.INOUT, "ArtistServiceImpl isExist(" + name + ", " + surname + ")");
return artistRepository.getByNameAndSurname(name, surname)!=null ? true : false;
}
@Override
public void saveArtist(Artist artist) {
TestController.traceCounter(TestController.InsertType.INOUT, "ArtistServiceImpl saveArtist(" + artist + ")");
artistRepository.save(artist);
}
}
| true
|
efc679e083f8754ea79448c0f25f35dd1a059d94
|
Java
|
PJbesnard/ChatHack
|
/sources/src/fr/upem/net/tcp/nonblocking/console/CloseConnection.java
|
UTF-8
| 585
| 3.09375
| 3
|
[] |
no_license
|
package fr.upem.net.tcp.nonblocking.console;
/**
* This class allows to call an accept method on a close connection operation
*/
public class CloseConnection implements ConsoleMessageFrame {
private final String login;
public CloseConnection(String login) {
this.login = login;
}
/**
* Gets the login
* @return a String which represents the login
*/
public String getLogin() {
return login;
}
/**
* Accepts the Frame by using the visitor design pattern
*/
@Override
public void accept(ConsoleMessageVisitor visitor) {
visitor.consoleVisit(this);
}
}
| true
|
9ae65ba38b126558bf09c08897b87fab2cbd2b9e
|
Java
|
scdblab/TARDIS
|
/YCSB/mongodb/src/main/java/com/yahoo/ycsb/db/MetricsHelper.java
|
UTF-8
| 4,104
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.yahoo.ycsb.db;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONException;
import org.json.JSONObject;
public class MetricsHelper {
public static AtomicInteger numberOfPendingWritesAttheEndOfFailMode = new AtomicInteger(0);
public static AtomicInteger numberOfPendingWritesAttheEndOfRecoveryMode = new AtomicInteger(0);
public static String writeMetrics(String fileName, Properties prop, long start, long end, long dbRecoverTime,
TimedMetrics timedMetrics, ArrayMetrics arrayMetrics) {
JSONObject obj = new JSONObject();
try {
obj.put("start", start);
obj.put("end", end);
obj.put(MetricsName.METRICS_TOTAL_PENDING_WRITES_FAIL, numberOfPendingWritesAttheEndOfFailMode.get());
obj.put(MetricsName.METRICS_TOTAL_PENDING_WRITES_RECOVERY,
numberOfPendingWritesAttheEndOfRecoveryMode.get());
if (TardisRecoveryEngine.pendingWritesMetrics.getMetrics().containsKey(MetricsName.METRICS_PENDING_WRITES)
&& TardisRecoveryEngine.pendingWritesMetrics.getMetrics()
.containsKey(MetricsName.METRICS_RECOVERED_WRITES_COUNT)) {
int totalPWs = TardisRecoveryEngine.pendingWritesMetrics.getMetrics().get(MetricsName.METRICS_PENDING_WRITES)
.get();
obj.put(MetricsName.METRICS_TOTAL_PENDING_WRITES, totalPWs);
obj.put(MetricsName.METRICS_RECOVERED_WRITES_COUNT, TardisRecoveryEngine.pendingWritesMetrics.getMetrics()
.get(MetricsName.METRICS_RECOVERED_WRITES_COUNT).get());
}
List<ArrayMetricsRecord> array = ArrayMetrics.getInstance().getMetricArray()
.get(MetricsName.METRICS_EW_STATS);
int peak = 0;
long peakTime = 0;
long recoveryFinishTime = 0;
for (int i = 0; i < array.size(); i++) {
RecoverRecord r = RecoverRecord.class.cast(array.get(i));
int sum = r.getDirtyRecords().values().stream().mapToInt(Integer::intValue).sum();
if (sum >= peak) {
peakTime = r.getEnd();
peak = sum;
}
}
if (peakTime < dbRecoverTime + start) {
peakTime = dbRecoverTime + start;
System.out.println("peak time less than actual db recovery time, use actual recover time " + peakTime
+ ", " + dbRecoverTime + start);
}
for (int i = 0; i < array.size(); i++) {
RecoverRecord r = RecoverRecord.class.cast(array.get(i));
if (r.getStart() > peakTime) {
if (r.getDirtyRecords().values().stream().mapToInt(Integer::intValue).sum() == 0) {
recoveryFinishTime = r.getStart();
break;
}
}
}
if (recoveryFinishTime == 0) {
recoveryFinishTime = RecoverRecord.class.cast(array.get(array.size() - 1)).getEnd();
}
obj.put(MetricsName.METRICS_DIRTY_USER, TardisRecoveryEngine.pendingWritesUsers.getMetrics().size());
obj.put(MetricsName.METRICS_RECOVERED_USER, TardisRecoveryEngine.recoveredUsers.getMetrics().size());
obj.put(MetricsName.METRICS_MISSED_USER, TardisRecoveryEngine.pendingWritesUsers.getMetrics().size() - TardisRecoveryEngine.recoveredUsers.getMetrics().size());
obj.put(MetricsName.METRICS_RECOVERY_DURATION, recoveryFinishTime - peakTime);
System.out.println(obj.toString());
timedMetrics.getMetrics().keySet().forEach(i -> {
try {
obj.put(i, timedMetrics.getMetricsAsJson(i));
} catch (Exception e) {
e.printStackTrace();
}
});
arrayMetrics.getMetricArray().keySet().forEach(i -> {
try {
obj.put(i, arrayMetrics.toJSON(i));
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)))) {
bw.write(obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
try {
return obj.toString(4);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private static void put(String key, Properties prop, JSONObject obj) throws JSONException {
if (prop.getProperty(key) != null) {
obj.put(key, prop.getProperty(key));
}
}
}
| true
|
eb3601ffbf17c374f98a32991b930c5c6339fcf0
|
Java
|
wissem007/badges
|
/src/tn/com/smartsoft/framework/presentation/view/tags/xtpl/XTplForEach.java
|
UTF-8
| 929
| 2.25
| 2
|
[] |
no_license
|
package tn.com.smartsoft.framework.presentation.view.tags.xtpl;
import java.io.StringWriter;
import org.apache.commons.lang.StringUtils;
import tn.com.smartsoft.framework.presentation.view.tags.xtpl.utils.XTplUtils;
public class XTplForEach extends XTplBodyNode {
/**
*
*/
private static final long serialVersionUID = 1L;
private String exp;
public String getExp() {
return exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public void writeStarNode(StringWriter xml) {
xml.append("#foreach(");
xml.append(XTplUtils.formatAttributeValue(exp));
xml.append(")\n");
if (StringUtils.isNotBlank(getContenent())) {
xml.append(XTplUtils.formatValue(getContenent()));
xml.append("\n");
}
}
public void writeEndNode(StringWriter xml) {
xml.append("#end\n");
}
public void write(StringWriter buffer) {
writeStarNode(buffer);
writeChildren(buffer);
writeEndNode(buffer);
}
}
| true
|
d22e4838ebcd007d78e9b9dfd8d1b14976a9318c
|
Java
|
hotpads/datarouter
|
/datarouter-util/src/test/java/io/datarouter/util/lang/LineOfCodeTests.java
|
UTF-8
| 1,373
| 2.375
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* 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 io.datarouter.util.lang;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* these can break easily if you modify this class. just update the test
*/
public class LineOfCodeTests{
@Test
public void testSimple(){
LineOfCode lineOfCode = new LineOfCode();
Assert.assertEquals(lineOfCode.getPackageName(), "io.datarouter.util.lang");
Assert.assertEquals(lineOfCode.getClassName(), "LineOfCodeTests");
Assert.assertEquals(lineOfCode.getMethodName(), "testSimple");
Assert.assertEquals(lineOfCode.getLineNumber(), Integer.valueOf(28));
}
@Test
public void testCompareTo(){
LineOfCode first = new LineOfCode();
LineOfCode second = new LineOfCode();
int diff = first.compareTo(second);
Assert.assertEquals(diff, -1);
}
}
| true
|
0e65daab55b86fab7e41d8edce3c3875984339f9
|
Java
|
mhussainshah1/OCPStudyGuide
|
/src/ocp11/ch13/introduction/ZooAnimal-HomeLT.java
|
UTF-8
| 198
| 2.34375
| 2
|
[] |
no_license
|
package ocp11.ch13.introduction;
//Marker annotation
public @interface ZooAnimal {}
class Mammal {}
class Bird {}
@ZooAnimal
class Lion extends Mammal {}
@ZooAnimal
class Peacock extends Bird {}
| true
|
232cf46c2e2772a88e7fd2437ad2b0ca396937f2
|
Java
|
fitsumcs/Hospital-Connectivity
|
/CarRentalList.java
|
UTF-8
| 4,234
| 2.125
| 2
|
[] |
no_license
|
package com.example.yohannes.appbutton;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.yohannes.appbutton.carRental.AbcCarRental;
import com.example.yohannes.appbutton.carRental.AdikaCarRental;
import com.example.yohannes.appbutton.carRental.AmazingCarRental;
import com.example.yohannes.appbutton.carRental.HomenetCarRental;
import com.example.yohannes.appbutton.carRental.RainbowCarRental;
import com.example.yohannes.appbutton.carRental.SenaitCarRental;
import com.example.yohannes.appbutton.carRental.ShangerilaTourCars;
import com.example.yohannes.appbutton.carRental.ZelalemCarRental;
import com.example.yohannes.appbutton.hotels.AbyssiniaHotel;
import com.example.yohannes.appbutton.hotels.AddisRegencyHotel;
import com.example.yohannes.appbutton.hotels.AgPalaceHotel;
import com.example.yohannes.appbutton.hotels.GetfamHotel;
import com.example.yohannes.appbutton.hotels.HiltonHotel;
import com.example.yohannes.appbutton.hotels.JupiterHotel;
import com.example.yohannes.appbutton.hotels.NazraHotel;
import com.example.yohannes.appbutton.hotels.RadissonBluHotel;
import com.example.yohannes.appbutton.hotels.SheratonAddisHotel;
import com.example.yohannes.appbutton.hotels.TheResidenceHotel;
import com.example.yohannes.appbutton.school.GreekSchool;
public class CarRentalList extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_list);
listView = (ListView)findViewById(R.id.list);
String[] FRUITS = new String[] { "ABC","Adika","Amazing Ethiopia","Green Land","Homenet",
"Rainbow","Senait","Shangerila","Zelalem"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,android.R.id.text1,FRUITS);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
if (position == 0){
Intent myintent = new Intent(view.getContext(), AbcCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 1){
Intent myintent = new Intent(view.getContext(), AdikaCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 2){
Intent myintent = new Intent(view.getContext(), AmazingCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 3){
Intent myintent = new Intent(view.getContext(), GreekSchool.class);
startActivityForResult(myintent, 0);
}
if (position == 4){
Intent myintent = new Intent(view.getContext(), HomenetCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 5){
Intent myintent = new Intent(view.getContext(), RainbowCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 6){
Intent myintent = new Intent(view.getContext(), SenaitCarRental.class);
startActivityForResult(myintent, 0);
}
if (position == 7){
Intent myintent = new Intent(view.getContext(), ShangerilaTourCars.class);
startActivityForResult(myintent, 0);
}
if (position == 8){
Intent myintent = new Intent(view.getContext(), ZelalemCarRental.class);
startActivityForResult(myintent, 0);
}
}
});
}
}
| true
|
0e169f02890bff1471a4c0034d05649c89b6ec38
|
Java
|
sunchenglong/lintcode-practice
|
/main/com/sunchenglong/leetcode/EditDistance72.java
|
UTF-8
| 1,010
| 3.109375
| 3
|
[] |
no_license
|
package com.sunchenglong.leetcode;
/**
* Created by Chenglong Sun on 2016/10/17.
*/
public class EditDistance72 {
public int minDistance(String word1, String word2) {
int length1 = word1.length();
int length2 = word2.length();
int[][] f = new int[length1 + 1][length2 + 1];
for (int i = 0; i <= length1; i++)
f[i][0] = i;
for (int i = 0; i <= length2; i++)
f[0][i] = i;
for (int i = 1; i <= length1; i++) {
for (int j = 1; j <= length2; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1))
f[i][j] = f[i - 1][j - 1];
else {
int tmp = Math.min(f[i - 1][j], f[i][j - 1]);
f[i][j] = Math.min(f[i - 1][j - 1] + 1, tmp + 1);
}
}
}
return f[length1][length2];
}
public static void main(String[] args) {
System.out.println(new EditDistance72().minDistance("ab", "bc"));
}
}
| true
|
c50fb6ce079485080fbc8f9c45929647caa9da03
|
Java
|
elOreo/VC2
|
/src/main/java/vc2/data/Adult.java
|
UTF-8
| 7,080
| 2.328125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vc2.data;
import vc2.backprop.Input;
/**
*
* @author Tobias
*/
public class Adult implements Input{
private static final String[] workclasses = new String[]{"Private", "Self-emp-not-inc", "Self-emp-inc", "Federal-gov", "Local-gov", "State-gov", "Without-pay", "Never-worked"};
private static final String[] educations = new String[]{"Bachelors", "Some-college", "11th", "HS-grad", "Prof-school", "Assoc-acdm", "Assoc-voc", "9th", "7th-8th", "12th", "Masters", "1st-4th", "10th", "Doctorate", "5th-6th", "Preschool"};
private static final String[] maritalStatuses = new String[]{"Married-civ-spouse", "Divorced", "Never-married", "Separated", "Widowed", "Married-spouse-absent", "Married-AF-spouse"};
private static final String[] occupations = new String[]{"Tech-support", "Craft-repair", "Other-service", "Sales", "Exec-managerial", "Prof-specialty", "Handlers-cleaners", "Machine-op-inspct", "Adm-clerical", "Farming-fishing", "Transport-moving", "Priv-house-serv", "Protective-serv", "Armed-Forces"};
private static final String[] relationships = new String[]{"Wife", "Own-child", "Husband", "Not-in-family", "Other-relative", "Unmarried"};
private static final String[] races = new String[]{"White", "Asian-Pac-Islander", "Amer-Indian-Eskimo", "Other", "Black"};
private static final String[] sexes = new String[]{"Female", "Male"};
private static final String[] nativeCountries = new String[]{"United-States", "Cambodia", "England", "Puerto-Rico", "Canada", "Germany", "Outlying-US(Guam-USVI-etc)", "India", "Japan", "Greece", "South", "China", "Cuba", "Iran", "Honduras", "Philippines",
"Italy", "Poland", "Jamaica", "Vietnam", "Mexico", "Portugal", "Ireland", "France", "Dominican-Republic", "Laos", "Ecuador", "Taiwan", "Haiti", "Columbia", "Hungary", "Guatemala", "Nicaragua", "Scotland", "Thailand", "Yugoslavia",
"El-Salvador", "Trinadad&Tobago", "Peru", "Hong", "Holand-Netherlands"};
private final int age;
private final String workclass;
private final int fnlwgt;
private final String education;
private final int educationNum;
private final String maritalStatus;
private final String occupation;
private final String relationship;
private final String race;
private final String sex;
private final int capitalGain;
private final int capitalLoss;
private final int hoursPerWeek;
private final String nativeCountry;
private final String income;
public final static int vectorSize = 6+workclasses.length+educations.length+maritalStatuses.length+occupations.length+relationships.length+races.length+sexes.length+nativeCountries.length;
public Adult(
String age,
String workclass,
String fnlwgt,
String education,
String educationNum,
String maritalStatus,
String occupation,
String relationship,
String race,
String sex,
String capitalGain,
String capitalLoss,
String hoursPerWeek,
String nativeCountry,
String income
)
{
this.age = Integer.parseInt(age);
this.workclass = workclass;
this.fnlwgt = Integer.parseInt(fnlwgt);
this.education = education;
this.educationNum = Integer.parseInt(educationNum);
this.maritalStatus = maritalStatus;
this.occupation = occupation;
this.relationship = relationship;
this.race = race;
this.sex = sex;
this.capitalGain = Integer.parseInt(capitalGain);
this.capitalLoss = Integer.parseInt(capitalLoss);
this.hoursPerWeek = Integer.parseInt(hoursPerWeek);
this.nativeCountry = nativeCountry;
this.income = income;
}
public Adult(
String age,
String workclass,
String fnlwgt,
String education,
String educationNum,
String maritalStatus,
String occupation,
String relationship,
String race,
String sex,
String capitalGain,
String capitalLoss,
String hoursPerWeek,
String nativeCountry
)
{
this(age,
workclass,
fnlwgt,
education,
educationNum,
maritalStatus,
occupation,
relationship,
race,
sex,
capitalGain,
capitalLoss,
hoursPerWeek,
nativeCountry,
null);
}
public Adult(String[] data){
this(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14]);
}
public int getAge() {
return age;
}
public String getWorkclass() {
return workclass;
}
public int getFnlwgt() {
return fnlwgt;
}
public String getEducation() {
return education;
}
public int getEducationNum() {
return educationNum;
}
public String getMaritalStatus() {
return maritalStatus;
}
public String getOccupation() {
return occupation;
}
public String getRelationship() {
return relationship;
}
public String getRace() {
return race;
}
public String getSex() {
return sex;
}
public int getCapitalGain() {
return capitalGain;
}
public int getCapitalLoss() {
return capitalLoss;
}
public int getHoursPerWeek() {
return hoursPerWeek;
}
public String getNativeCountry() {
return nativeCountry;
}
private int fillVector(String value, String[] values, double[] out, int offset){
for( int i = 0; i<values.length; i++){
out[offset + i] = value.equals(values[i])?1:0;
}
return offset + values.length;
}
@Override
public double[] getVector() {
double[] result = new double[vectorSize];
int index = 0;
result[index++] = age;
index = fillVector(workclass, workclasses, result, index);
result[index++] = fnlwgt;
index = fillVector(education, educations, result, index);
result[index++] = educationNum;
index = fillVector(maritalStatus, maritalStatuses, result, index);
index = fillVector(occupation, occupations, result, index);
index = fillVector(relationship, relationships, result, index);
index = fillVector(race, races, result, index);
index = fillVector(sex, sexes, result, index);
result[index++] = capitalGain;
result[index++] = capitalLoss;
result[index++] = hoursPerWeek;
index = fillVector(nativeCountry, nativeCountries, result, index);
return result;
}
@Override
public double[] getOutput() {
return income == null ? new double[]{} : new double[] {income.equals(">50K") ? 1 : 0};
}
}
| true
|
caebf06c69f5dc9c22fc63833794f2c12fe3f7f9
|
Java
|
magx2/jSupla
|
/protocol/src/main/java/pl/grzeslowski/jsupla/protocol/api/decoders/sd/ServerDeviceDecoder.java
|
UTF-8
| 295
| 1.632813
| 2
|
[
"MIT"
] |
permissive
|
package pl.grzeslowski.jsupla.protocol.api.decoders.sd;
import pl.grzeslowski.jsupla.protocol.api.decoders.ProtoWithSizeDecoder;
import pl.grzeslowski.jsupla.protocol.api.structs.sd.ServerDevice;
public interface ServerDeviceDecoder<T extends ServerDevice> extends ProtoWithSizeDecoder<T> {
}
| true
|
bdb8408f615d38126d9503c66c61df89d9ec227e
|
Java
|
crianzy/workspace
|
/oa/src/com/czy/oa/base/BaseAction.java
|
GB18030
| 1,228
| 2.203125
| 2
|
[] |
no_license
|
package com.czy.oa.base;
import java.lang.reflect.ParameterizedType;
import javax.annotation.Resource;
import com.czy.oa.service.DepartmentService;
import com.czy.oa.service.PrivilegeService;
import com.czy.oa.service.RoleService;
import com.czy.oa.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
private static final long serialVersionUID = 1895824111764976679L;
@Resource
protected RoleService roleService;
@Resource
protected DepartmentService departmentService;
@Resource
protected UserService userService;
@Resource
protected PrivilegeService privilegeService;
protected T model;
@SuppressWarnings({ "rawtypes", "unchecked" })
public BaseAction() {
// ȡmodel Ϣ
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
Class clazz = (Class) pt.getActualTypeArguments()[0];
// new һʵ
try {
model = (T) clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public T getModel() {
return model;
}
}
| true
|
ee4cca3e5150d7abbcc96bcc1e1159870143fdee
|
Java
|
BioroboticsLab/beetag_app
|
/app/src/main/java/com/aki/beetag/TagDao.java
|
UTF-8
| 766
| 2.0625
| 2
|
[] |
no_license
|
package com.aki.beetag;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
@Dao
public interface TagDao {
@Insert
void insertTags(Tag... tags);
@Update
void updateTags(Tag... tags);
@Delete
void deleteTags(Tag... tags);
@Query("DELETE FROM tag WHERE imageName=:imageName")
void deleteAllTagsOnImage(String imageName);
@Query("SELECT * FROM tag WHERE imageName=:imageName")
List<Tag> loadTagsByImage(String imageName);
@Query("SELECT COUNT(*) FROM TAG WHERE imageName=:imageName")
int getTagCount(String imageName);
}
| true
|
082dbc1160cf4bf7e2011f5a50303068dcfcd19b
|
Java
|
lightning331/JacksGoGo_Android
|
/app/src/main/java/com/kelvin/jacksgogo/Activities/GoClub_Event/GcPostUpdateActivity.java
|
UTF-8
| 2,772
| 1.929688
| 2
|
[] |
no_license
|
package com.kelvin.jacksgogo.Activities.GoClub_Event;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.kelvin.jacksgogo.CustomView.Views.JGGActionbarView;
import com.kelvin.jacksgogo.R;
import com.kelvin.jacksgogo.Utils.Global;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class GcPostUpdateActivity extends AppCompatActivity implements TextWatcher {
@BindView(R.id.gc_post_actionbar) Toolbar mToolbar;
@BindView(R.id.edit_update) EditText editUpdate;
@BindView(R.id.btn_update) Button btnUpdate;
private Context mContext;
private JGGActionbarView actionbarView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gc_post_update);
ButterKnife.bind(this);
mContext = this;
actionbarView = new JGGActionbarView(this);
mToolbar.addView(actionbarView);
setSupportActionBar(mToolbar);
actionbarView.setStatus(JGGActionbarView.EditStatus.GO_CLUB_POST_UPDATE, Global.AppointmentType.UNKNOWN);
actionbarView.setActionbarItemClickListener(new JGGActionbarView.OnActionbarItemClickListener() {
@Override
public void onActionbarItemClick(View view) {
actionbarViewItemClick(view);
}
});
editUpdate.addTextChangedListener(this);
}
private void actionbarViewItemClick(View view) {
if (view.getId() == R.id.btn_back) {
onBackPressed();
}
}
@OnClick(R.id.btn_update)
public void onClickNext() {
finish();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (editUpdate.length() > 0) {
btnUpdate.setBackgroundResource(R.drawable.purple_background);
btnUpdate.setTextColor(ContextCompat.getColor(mContext, R.color.JGGWhite));
btnUpdate.setClickable(true);
} else {
btnUpdate.setBackgroundResource(R.drawable.grey_background);
btnUpdate.setTextColor(ContextCompat.getColor(mContext, R.color.JGGGrey3));
btnUpdate.setClickable(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
}
| true
|
79e9e08ba56e44cfed940419f4e748b0dc89a7c4
|
Java
|
reverseengineeringer/com.yelp.android
|
/src/com/yelp/android/ui/map/t.java
|
UTF-8
| 426
| 1.84375
| 2
|
[] |
no_license
|
package com.yelp.android.ui.map;
class t
implements Runnable
{
t(YelpMap paramYelpMap) {}
public void run()
{
YelpMap localYelpMap = a;
if (YelpMap.c(a) != null) {}
for (boolean bool = true;; bool = false)
{
YelpMap.a(localYelpMap, bool);
return;
}
}
}
/* Location:
* Qualified Name: com.yelp.android.ui.map.t
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true
|
e31ccf3f6beb8a2b796696678a1d160df57650e7
|
Java
|
Yoplitein/SpawnManager
|
/src/main/java/net/yoplitein/spawnmanager/ModInfo.java
|
UTF-8
| 217
| 1.585938
| 2
|
[] |
no_license
|
package net.yoplitein.spawnmanager;
public class ModInfo
{
public static final String ID = "spawnmanager";
public static final String NAME = "Spawn Manager";
public static final String VERSION = "0.1";
}
| true
|
3d298df87f783d9989c8e47737961516fbd6cd39
|
Java
|
amerelsayed2020/Learning
|
/Android/GalileoX_CAAD003X_Professional_Android_App_Development/FacebookRecipes/app/src/main/java/com/example/robert/facebookrecipes/recipeMain/ui/SwipeGestureListener.java
|
UTF-8
| 187
| 1.570313
| 2
|
[] |
no_license
|
package com.example.robert.facebookrecipes.recipeMain.ui;
/**
* Created by robert on 17.8.2017.
*/
public interface SwipeGestureListener {
void onKeep();
void onDismiss();
}
| true
|
97ad9b6bc05d1a19811dc2135d24cd5b94fc1164
|
Java
|
jimmy-20/Proyecto-de-curso-2021
|
/GestionApp/src/main/java/Backend/Connection/RandomConnection.java
|
UTF-8
| 2,844
| 2.921875
| 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 Backend.Connection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* @author FAMILIASOZAORTIZ
*/
public class RandomConnection {
private RandomAccessFile rafH;
private RandomAccessFile rafDDetalle;
private RandomAccessFile rafDFactura;
private RandomAccessFile rafCredito;
private RandomAccessFile rafInventario;
public RandomConnection(File header, File detalle,File factura, File credito, File inventario) throws FileNotFoundException, IOException{
this.rafH = new RandomAccessFile(header, "rw");
this.rafDDetalle = new RandomAccessFile(detalle, "rw");
this.rafDFactura = new RandomAccessFile(factura, "rw");
this.rafCredito = new RandomAccessFile(credito, "rw");
this.rafInventario = new RandomAccessFile(inventario, "rw");
if (rafH.length() == 0){
rafH.seek(0);
rafH.writeInt(0); //n = Cantidad total
rafH.writeInt(0); //k = ID unico
}
}
/**
* Obtiene de regreso el archivo "Header" de compras
* @return Archivo "Header"
**/
public RandomAccessFile getRafH() {
return rafH;
}
/**
* Obtiene el archivo del Detalle de compras
* @return Archivo "Detalle de Compras"
**/
public RandomAccessFile getRafDetalle() {
return rafDDetalle;
}
/**
* Obtiene el archivo del Detalle de Factura de compras
* @return Archivo "Detalle de Factura"
**/
public RandomAccessFile getRafFactura()
{
return rafDFactura;
}
/**
* @Obtiene el archivo de los proveedores a los que les debe
* @return Archivo "Proveedores"
**/
public RandomAccessFile getRafCredito(){
return rafCredito;
}
/**
* Obtiene el archivo en donde se encuentra las compras que fueron trasladada a la bodega
* @return Archivo "Inventario"
**/
public RandomAccessFile getRafInventario(){
return rafInventario;
}
/**
* Cierra los flujos de bytes de todos los archivos con los que se gestiona
* @exception IOException - En caso se produzca un error en los flujos de Bytes
**/
public void close() throws IOException{
if(rafH != null){
rafH.close();
}
if(rafDDetalle != null){
rafDDetalle.close();
}
if (rafDFactura != null){
rafDFactura.close();
}
if (rafInventario != null){
rafInventario.close();
}
}
}
| true
|
b5b45a64b3a360e1e218d4c690b3bd1eaabb124d
|
Java
|
teamdelta2016/TeamDelta
|
/peter/src/main/java/uk/ac/cam/teamdelta/peter/ImageProcImpl.java
|
UTF-8
| 3,383
| 2.578125
| 3
|
[] |
no_license
|
package uk.ac.cam.teamdelta.peter;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import uk.ac.cam.teamdelta.ImageInputSet;
import uk.ac.cam.teamdelta.ImageOutputSet;
import uk.ac.cam.teamdelta.ImageProcParams;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
class ImageProcImpl extends ImageProc {
private static final double NIGHT_MIN = 0.3;
private static final double HEADLIGHT_PERC = 0.15;
private Peripheral peripheralFront;
private Glarer glarer;
private Random r;
ImageProcImpl(ImageProcParams params) {
super(params);
peripheralFront = new Peripheral(Utils.FRONT_ROWS, Utils.FRONT_COLS, Utils.MAT_TYPE);
glarer = new Glarer();
r = new Random();
}
@Override
public ImageOutputSet process(ImageInputSet input, boolean isJunction) {
BufferedImage front = processFront(input.getFrontLeft(), input.getFrontRight());
BufferedImage left = processOther(input.getLeft(), false);
BufferedImage right = processOther(input.getRight(), false);
BufferedImage back = processOther(input.getBack(), true);
return new ImageOutputSet(front, left, right, back);
}
private BufferedImage processOther(BufferedImage iI, boolean isBack){
if(iI == null){
return null;
}
Mat i = Utils.bufferedImageToMat(iI);
if(params.nightTimeFactor > NIGHT_MIN){
Night.nightTime(i, params.nightTimeFactor);
}
if (params.blurValue > 0) {
Utils.blurImage(i, params.blurValue * 2);
}
if(!isBack){
double x = (1 - params.darkEdgesFactor);
Core.multiply(i, new Scalar(x, x, x), i);
}
try {
return Utils.matToBufferedImage(i);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private BufferedImage processFront(BufferedImage fLI, BufferedImage fRI) {
if (fLI == null || fRI == null) {
return null;
}
Mat fL = Utils.bufferedImageToMat(fLI);
Mat fR = Utils.bufferedImageToMat(fRI);
// Stitch
Mat i = Stitcher.stitchImages(fL, fR);
fL.release();
fR.release();
if(params.nightTimeFactor > NIGHT_MIN){
Night.nightTime(i, params.nightTimeFactor);
}
if (params.blurValue > 0) {
Utils.blurImage(i, params.blurValue);
}
i = Utils.resizeImage(i, Utils.FRONT_ROWS, Utils.FRONT_COLS);
Mat ghosted = Ghoster.ghostImage(i, params.ghostFactor, params.ghostFactor, 0.5);
Mat blurred = ghosted.clone();
Utils.blurImage(blurred, params.blurValue * 3);
i = peripheralFront.overlayPeripheral(ghosted, blurred);
ghosted.release();
blurred.release();
if (params.darkEdgesFactor > 0) {
double x = 1 - params.darkEdgesFactor;
i = peripheralFront.multiplyColor(i, new Scalar(x, x, x));
}
if(params.showHeadlights && r.nextDouble() < HEADLIGHT_PERC){
glarer.addCar(i);
}
try{
return Utils.matToBufferedImage(i);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| true
|
3fe7c17a6560f44cbc9f554eabc83b54d7757295
|
Java
|
BeauteousJade/gam-study-service
|
/src/main/java/com/pby/gamstudy/controller/UserController.java
|
UTF-8
| 2,028
| 1.945313
| 2
|
[] |
no_license
|
package com.pby.gamstudy.controller;
import com.pby.gamstudy.bean.User;
import com.pby.gamstudy.bean.body.MineResponseBody;
import com.pby.gamstudy.bean.body.UserProfileResponseBody;
import com.pby.gamstudy.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService mUserService;
@PostMapping("/findUser")
public User findUser(@Param("id") String id) {
return mUserService.findUser(id);
}
@PostMapping("/profile")
public UserProfileResponseBody getUserProfile(@Param("fromUserId") String fromUserId, @Param("toUserId") String toUserId) {
return mUserService.getUserProfile(fromUserId, toUserId);
}
@PostMapping("/mine")
public MineResponseBody findUserInfo(@Param("id") String id) {
return mUserService.findUserInfo(id);
}
@PostMapping("/updateAvatar")
public String updateAvatar(@Param("userId") String userId, @RequestParam("file") MultipartFile file) {
return mUserService.updateAvatar(userId, file);
}
@PostMapping("/findFollowList")
public List<User> findFollowList(@Param("userId") String userId) {
return mUserService.findFollowList(userId);
}
@PostMapping("/findFansList")
public List<User> findFansList(@Param("userId") String userId) {
return mUserService.findFansList(userId);
}
@PostMapping("/modifyUserName")
public boolean modifyUserName(@Param("userId") String userId, @Param("userName") String userName) {
return mUserService.modifyUserName(userId, userName);
}
}
| true
|
590e0db34ca9f981bf587c7eb049512384a5d091
|
Java
|
JameChen/buyertools
|
/buyerTool/src/main/java/com/nahuo/buyertool/MeSettingActivity.java
|
UTF-8
| 11,294
| 1.734375
| 2
|
[] |
no_license
|
package com.nahuo.buyertool;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.nahuo.buyer.tool.R;
import com.nahuo.buyertool.common.Const;
import com.nahuo.buyertool.common.SpManager;
import com.nahuo.buyertool.dialog.AccountDialog;
import com.nahuo.buyertool.provider.UserInfoProvider;
import com.nahuo.buyertool.task.CheckUpdateTask;
import com.nahuo.buyertool.utils.ListDataSave;
import com.nahuo.buyertool.utils.WaterWarkSave;
import com.nahuo.library.controls.LightPopDialog;
import com.nahuo.library.controls.LoadingDialog;
import com.nahuo.library.helper.FunctionHelper;
import com.nahuo.library.helper.ImageUrlExtends;
import com.nahuo.service.autoupdate.AppUpdate;
import com.nahuo.service.autoupdate.AppUpdateService;
import ch.ielse.view.SwitchView;
import static java.lang.Integer.parseInt;
/**
* @description 我的账号
* @created 2014-8-15 上午11:01:44
*/
public class MeSettingActivity extends BaseActivity2 implements OnClickListener, AccountDialog.PopDialogListener {
private Context mContext = this;
private static final String TAG = "MeSettingActivity";
private MeSettingActivity vThis = this;
private AppUpdate mAppUpdate;
private LoadingDialog loadingDialog;
private TextView mTvAddress;
private Button ok_number, ok_com;
private EditText et_single_row, et_compress_row;
private ImageView iv_water_mark_one, iv_water_mark_two;
public static String water_mark_path_one = ImageUrlExtends.HTTP_BANWO_FILES+"/img/shuiyin5.png";
public static String water_mark_path_two = ImageUrlExtends.HTTP_BANWO_FILES+"/img/shuiyin6.png";
private RequestOptions options;
private View layout_water_mark;
private SwitchView mSwitchView, switch_video_view;
private WaterWarkSave save;
private String use_id;
public static int WATER_TYPE_ONE = 1;
public static int WATER_TYPE_TWO = 2;
private TextView tv_clear;
private ListDataSave listDataSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_setting);
BWApplication.getInstance().addActivity(this);
listDataSave = new ListDataSave(this, Const.LOGIN_PRE_KEY);
setTitle("设置");
options = new RequestOptions()
.centerCrop()
.placeholder(R.color.color_f6)
.diskCacheStrategy(DiskCacheStrategy.ALL);
mAppUpdate = AppUpdateService.getAppUpdate(this);
use_id = SpManager.getUserId(this) + "";
save = new WaterWarkSave(this, use_id);
initView();
}
// 初始化数据
private void initView() {
loadingDialog = new LoadingDialog(this);
tv_clear = (TextView) findViewById(R.id.tv_clear);
tv_clear.setOnClickListener(this);
mSwitchView = (SwitchView) findViewById(R.id.switch_view);
switch_video_view = (SwitchView) findViewById(R.id.switch_video_view);
layout_water_mark = findViewById(R.id.layout_water_mark);
ok_number = (Button) findViewById(R.id.ok_number);
ok_com = (Button) findViewById(R.id.ok_com);
iv_water_mark_one = (ImageView) findViewById(R.id.iv_water_mark_one);
iv_water_mark_two = (ImageView) findViewById(R.id.iv_water_mark_two);
et_single_row = (EditText) findViewById(R.id.et_single_row);
et_compress_row = (EditText) findViewById(R.id.et_compress_row);
iv_water_mark_one.setOnClickListener(this);
iv_water_mark_two.setOnClickListener(this);
ok_number.setOnClickListener(this);
ok_com.setOnClickListener(this);
initItem(R.id.item_app_update, "版本更新");
setItemRightText(R.id.item_app_update, "当前版本:" + FunctionHelper.GetAppVersion(vThis));
initItem(R.id.me_checkout, "退出");
Glide.with(this)
.load(water_mark_path_one)
.apply(options)
.into(iv_water_mark_one);
Glide.with(this)
.load(water_mark_path_two)
.apply(options)
.into(iv_water_mark_two);
et_compress_row.setText(save.getCompressMaxSize(WaterWarkSave.BUYTOOLCOMPRESSMAXSIZE + use_id) + "");
switch_video_view.toggleSwitch(SpManager.getUploadCompressVideo(this));
if (save.getHasWaterWark(WaterWarkSave.BUYTOOL_HASWATERWARK + use_id)) {
mSwitchView.toggleSwitch(true);
layout_water_mark.setVisibility(View.VISIBLE);
} else {
mSwitchView.toggleSwitch(false);
layout_water_mark.setVisibility(View.GONE);
}
et_single_row.setText(save.getNoAddWaterCount(WaterWarkSave.BUYTOOLNOADDWATERWARK_COUNT + use_id) + "");
if (save.getWaterType(WaterWarkSave.BUYTOOLWATERWARK_TYPE + use_id) == WATER_TYPE_ONE) {
iv_water_mark_one.setBackground(getResources().getDrawable(R.drawable.water_mark_bg));
iv_water_mark_two.setBackground(null);
} else if (save.getWaterType(WaterWarkSave.BUYTOOLWATERWARK_TYPE + use_id) == WATER_TYPE_TWO) {
iv_water_mark_two.setBackground(getResources().getDrawable(R.drawable.water_mark_bg));
iv_water_mark_one.setBackground(null);
} else {
iv_water_mark_one.setBackground(null);
iv_water_mark_two.setBackground(null);
}
mSwitchView.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
@Override
public void toggleToOn(SwitchView view) {
view.toggleSwitch(true);
save.setHasWaterWark(WaterWarkSave.BUYTOOL_HASWATERWARK + use_id, true);
layout_water_mark.setVisibility(View.VISIBLE);
//ViewHub.showShortToast(MeSettingActivity.this,"true");
}
@Override
public void toggleToOff(SwitchView view) {
view.toggleSwitch(false);
save.setHasWaterWark(WaterWarkSave.BUYTOOL_HASWATERWARK + use_id, false);
layout_water_mark.setVisibility(View.GONE);
//ViewHub.showShortToast(MeSettingActivity.this,"fasle");
}
});
switch_video_view.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
@Override
public void toggleToOn(SwitchView view) {
view.toggleSwitch(true);
SpManager.setUploadCompressVideo(vThis, true);
}
@Override
public void toggleToOff(SwitchView view) {
view.toggleSwitch(false);
SpManager.setUploadCompressVideo(vThis, false);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_clear:
AccountDialog.getInstance(this).setTitle("确定清空账号信息吗?").setPositive(this).showDialog();
break;
case R.id.iv_water_mark_one:
save.setWaterType(WaterWarkSave.BUYTOOLWATERWARK_TYPE + use_id, WATER_TYPE_ONE);
iv_water_mark_one.setBackground(getResources().getDrawable(R.drawable.water_mark_bg));
iv_water_mark_two.setBackground(null);
break;
case R.id.iv_water_mark_two:
save.setWaterType(WaterWarkSave.BUYTOOLWATERWARK_TYPE + use_id, WATER_TYPE_TWO);
iv_water_mark_two.setBackground(getResources().getDrawable(R.drawable.water_mark_bg));
iv_water_mark_one.setBackground(null);
break;
case R.id.ok_number:
String count = et_single_row.getText().toString().trim();
save.setNoAddWaterCount(WaterWarkSave.BUYTOOLNOADDWATERWARK_COUNT + use_id, parseInt(count));
ViewHub.showShortToast(this, "设置成功");
break;
case R.id.ok_com:
String ssi = et_compress_row.getText().toString().trim();
int size = Integer.parseInt(ssi);
if (size <= 1000 && size >= 150) {
save.setCompressMaxSize(WaterWarkSave.BUYTOOLCOMPRESSMAXSIZE + use_id, size);
ViewHub.showShortToast(this, "设置成功");
} else {
ViewHub.showShortToast(this, "建议设置最大压缩值在150-1000KB范围");
}
break;
case R.id.titlebar_btnLeft:// 返回
finish();
break;
case R.id.me_checkout:// 退出登录
ViewHub.showLightPopDialog(this, getString(R.string.dialog_title),
getString(R.string.shopset_exit_confirm), "取消", "退出登录", new LightPopDialog.PopDialogListener() {
@Override
public void onPopDialogButtonClick(int which) {
UserInfoProvider.exitApp(mContext);
}
});
// UploadManager.getInstance(this)
break;
case R.id.item_app_update:// 版本更新
new CheckUpdateTask(this, mAppUpdate, true, true).execute();
break;
default:
break;
}
}
@Override
public void finish() {
Intent data = new Intent();
setResult(RESULT_OK, data);
super.finish();
}
private void toOtherActivity(Class<?> cls) {
Intent intent = new Intent(vThis, cls);
startActivity(intent);
}
@Override
protected void onPause() {
super.onPause();
StatService.onPause(this);
mAppUpdate.callOnPause();
}
@Override
protected void onResume() {
super.onResume();
StatService.onResume(this);
mAppUpdate.callOnResume();
}
private void initItem(int viewId, String text) {
View v = findViewById(viewId);
v.setOnClickListener(this);
TextView tv = (TextView) v.findViewById(R.id.tv_left_text);
ImageView ivLeftIcon = (ImageView) v.findViewById(R.id.iv_left_icon);
tv.setText(text);
ivLeftIcon.setVisibility(View.GONE);
}
private void setItemRightText(int viewId, String text) {
View v = findViewById(viewId);
TextView tv = (TextView) v.findViewById(R.id.tv_right_text);
tv.setText(text);
}
private void setItemRightText(int viewId, Spanned spanned) {
View v = findViewById(viewId);
TextView tv = (TextView) v.findViewById(R.id.tv_right_text);
tv.setText(spanned);
}
@Override
public void onAccountDialogButtonClick() {
listDataSave.clearDataList(Const.LOGIN_PRE_LIST_KEY);
ViewHub.showShortToast(this, "清除成功");
}
}
| true
|
1dd350013495ef879e65c4a645ccd6d70a3ec857
|
Java
|
dake-xue/education
|
/src/main/java/com/zhongsheng/education/entiy/Student.java
|
UTF-8
| 11,147
| 2
| 2
|
[] |
no_license
|
package com.zhongsheng.education.entiy;
import java.util.Date;
import java.util.List;
public class Student {
//学生id
private int sid;
private Integer area;
//校区id
private Integer campusid;
//校区
private String campus;
//学校名称
private String schoolname;
//学生名字
private String sname;
//性别
private String sex;
//班级
private String grade;
//专业
private String major;
//手机号码
private String phone;
//班次
private String classes;
//学费
private String money;
private String jiaofeijine;
//考试年份
private Integer examinationtime;
//入学年份
private Integer admissiontime;
//报名日期
private Date signupdate;
//补费日期
private Date addmoneydate;
//缴费方式
private String paymethod;
//意向专业
private String intentionmajor;
//公共课
private String publiccours;
//专业课
private String majorcours;
//校区负责人
private String campusmanager;
//校园代理
private String campusagent;
//线上上课轮数
private int onlinenumber;
//线下上课轮数
private int offlinenumber;
//职务
private String job;
//收件家庭住址
private String homeaddress;
//身份证号
private String idcard;
//date生日
private Date birthday;
//民族
private String nation;
//备注
private String remarks;
//积分
private int score;
//考试科目
private String subject;
//院系
private String department;
//家庭联系方式
private FamilyInfo familyInfo;
//学校联系方式
private SchoolInfo schoolInfo;
//票据(查询时用)
private List<Bill> billList;
//票据(添加时用)
private Bill bill;
//序号
private Integer number;
//学号
private String snum;
//状态
private Integer status;
private String billNumber;
public String getBillNumber() {
return billNumber;
}
public void setBillNumber(String billNumber) {
this.billNumber = billNumber;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
//未交款
private String weijiaokuan;
private Integer schoolid;
public Integer getSchoolid() {
return schoolid;
}
public void setSchoolid(Integer schoolid) {
this.schoolid = schoolid;
}
public String getWeijiaokuan() {
return weijiaokuan;
}
public void setWeijiaokuan(String weijiaokuan) {
this.weijiaokuan = weijiaokuan;
}
public String getSnum() {
return snum;
}
public void setSnum(String snum) {
this.snum = snum;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Integer getArea() {
return area;
}
public void setArea(Integer area) {
this.area = area;
}
public List<Bill> getBillList() {
return billList;
}
public void setBillList(List<Bill> billList) {
this.billList = billList;
}
public Bill getBill() {
return bill;
}
public void setBill(Bill bill) {
this.bill = bill;
}
public FamilyInfo getFamilyInfo() {
return familyInfo;
}
public String getJiaofeijine() {
return jiaofeijine;
}
public void setJiaofeijine(String jiaofeijine) {
this.jiaofeijine = jiaofeijine;
}
public void setFamilyInfo(FamilyInfo familyInfo) {
this.familyInfo = familyInfo;
}
public SchoolInfo getSchoolInfo() {
return schoolInfo;
}
public void setSchoolInfo(SchoolInfo schoolInfo) {
this.schoolInfo = schoolInfo;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public Integer getCampusid() {
return campusid;
}
public void setCampusid(Integer campusid) {
this.campusid = campusid;
}
public String getCampus() {
return campus;
}
public void setCampus(String campus) {
this.campus = campus;
}
public String getSchoolname() {
return schoolname;
}
public void setSchoolname(String schoolname) {
this.schoolname = schoolname;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public Date getSignupdate() {
return signupdate;
}
public void setSignupdate(Date signupdate) {
this.signupdate = signupdate;
}
public Date getAddmoneydate() {
return addmoneydate;
}
public void setAddmoneydate(Date addmoneydate) {
this.addmoneydate = addmoneydate;
}
public String getPaymethod() {
return paymethod;
}
public void setPaymethod(String paymethod) {
this.paymethod = paymethod;
}
public String getIntentionmajor() {
return intentionmajor;
}
public void setIntentionmajor(String intentionmajor) {
this.intentionmajor = intentionmajor;
}
public String getPubliccours() {
return publiccours;
}
public void setPubliccours(String publiccours) {
this.publiccours = publiccours;
}
public String getMajorcours() {
return majorcours;
}
public void setMajorcours(String majorcours) {
this.majorcours = majorcours;
}
public String getCampusmanager() {
return campusmanager;
}
public void setCampusmanager(String campusmanager) {
this.campusmanager = campusmanager;
}
public String getCampusagent() {
return campusagent;
}
public void setCampusagent(String campusagent) {
this.campusagent = campusagent;
}
public int getOnlinenumber() {
return onlinenumber;
}
public void setOnlinenumber(int onlinenumber) {
this.onlinenumber = onlinenumber;
}
public int getOfflinenumber() {
return offlinenumber;
}
public void setOfflinenumber(int offlinenumber) {
this.offlinenumber = offlinenumber;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getHomeaddress() {
return homeaddress;
}
public void setHomeaddress(String homeaddress) {
this.homeaddress = homeaddress;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Integer getExaminationtime() {
return examinationtime;
}
public void setExaminationtime(Integer examinationtime) {
this.examinationtime = examinationtime;
}
public Integer getAdmissiontime() {
return admissiontime;
}
public void setAdmissiontime(Integer admissiontime) {
this.admissiontime = admissiontime;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", area=" + area +
", campusid=" + campusid +
", campus='" + campus + '\'' +
", schoolname='" + schoolname + '\'' +
", sname='" + sname + '\'' +
", sex='" + sex + '\'' +
", grade='" + grade + '\'' +
", major='" + major + '\'' +
", phone='" + phone + '\'' +
", classes='" + classes + '\'' +
", money='" + money + '\'' +
", jiaofeijine='" + jiaofeijine + '\'' +
", examinationtime=" + examinationtime +
", admissiontime=" + admissiontime +
", signupdate=" + signupdate +
", addmoneydate=" + addmoneydate +
", paymethod='" + paymethod + '\'' +
", intentionmajor='" + intentionmajor + '\'' +
", publiccours='" + publiccours + '\'' +
", majorcours='" + majorcours + '\'' +
", campusmanager='" + campusmanager + '\'' +
", campusagent='" + campusagent + '\'' +
", onlinenumber=" + onlinenumber +
", offlinenumber=" + offlinenumber +
", job='" + job + '\'' +
", homeaddress='" + homeaddress + '\'' +
", idcard='" + idcard + '\'' +
", birthday=" + birthday +
", nation='" + nation + '\'' +
", remarks='" + remarks + '\'' +
", score=" + score +
", subject='" + subject + '\'' +
", department='" + department + '\'' +
", familyInfo=" + familyInfo +
", schoolInfo=" + schoolInfo +
", billList=" + billList +
", bill=" + bill +
", number=" + number +
", snum='" + snum + '\'' +
", status=" + status +
", billNumber='" + billNumber + '\'' +
", weijiaokuan='" + weijiaokuan + '\'' +
", schoolid=" + schoolid +
'}';
}
}
| true
|
3af2d5c88a6f571a1e8295972e3acb6182665486
|
Java
|
jinguanz/WebDemo01
|
/CrackingCode/src/cmu/edu/jinguanz/crackingcode/chapter8/Test.java
|
UTF-8
| 188
| 1.992188
| 2
|
[] |
no_license
|
package cmu.edu.jinguanz.crackingcode.chapter8;
public class Test {
public static void main(String args[]){
/*for(Suit s:Suit.values()){
System.out.println(s);
}*/
Suit
}
}
| true
|
ae33f6c0cd507880b4147b6f3bebcc6405dd6f3f
|
Java
|
Akash-11525/automation
|
/CapitaPCSE_Automation/Automation_Project/src/main/java/testscripts/GMP_CreateGMPRunScripts.java
|
UTF-8
| 9,951
| 1.835938
| 2
|
[] |
no_license
|
package testscripts;
import java.awt.AWTException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import browsersetup.BaseClass;
import helpers.CommonFunctions;
import pageobjects.AdvancedFilter;
import pageobjects.AdvancedFindResult;
import pageobjects.CrmHome;
import pageobjects.LoginScreen;
import pageobjects.GMP.GMPHome;
import pageobjects.GMP.PaymentInstructionFile;
import pageobjects.GMP.VarianceReports;
import verify.Verify;
public class GMP_CreateGMPRunScripts extends BaseClass {
@Test(retryAnalyzer = helpers.RetryMechanism.class, groups = { "Regression","PCSE","OP","Sanity","CLONE","CloneSanity"} ,enabled = true)
@Parameters({"browser", "environment", "clientName" , "evidence"})
public void verifyCreateGMPRun(String browser ,String environment, String clientName , boolean evidence) throws InterruptedException, IOException, AWTException, ParseException
{
String key ="OPT_GOS1_PTR_BR_15";
setup(browser, environment, clientName,"OP");
pageobjects.GMP.GMPhelpers.GOS1Claim(getDriver(),environment,evidence);
tearDown(browser);
Thread.sleep(3000);
setup(browser, environment, clientName,"CRMOP","SUPERUSER");
pageobjects.GMP.GMPhelpers.VerifyOnCRM_GMP(getDriver());
tearDown(browser);
Thread.sleep(3000);
String PaymentDuedate_Excel = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "PaymentDuedate", 1);
Date date= CommonFunctions.convertStringtoCalDate(PaymentDuedate_Excel, "dd/MM/yyyy");
String strDueDate= CommonFunctions.convertDateToString(date, "M/dd/yyyy");
//String strDueDate = "09/01/2019";
setup(browser, environment, clientName, "GMP");
LoginScreen ObjLoginScreen = new LoginScreen(getDriver());
GMPHome ObjGMPHome = ObjLoginScreen.logintoGMP("PCSEPAYMENTSPROCESSOR", environment);
ObjGMPHome = ObjGMPHome.clickOnNewCreateGMP(strDueDate, 1);
ObjGMPHome = ObjGMPHome.clickonSearch(getDriver());
VarianceReports objVarianceReports = ObjGMPHome.VerifyPaymentstatus();
objVarianceReports = objVarianceReports.clickonGeneratePaymentFile();
PaymentInstructionFile objPaymentInstructionFile = objVarianceReports.ClickonPaymentInstructionFile();
objPaymentInstructionFile = objPaymentInstructionFile.ClickOnDownload(getDriver());
System.out.println("The Dot file is generated");
if(evidence)
{
objPaymentInstructionFile.takescreenshots(key+"_Downloaded_Dot1file");
}
tearDown(browser);
Thread.sleep(2000);
setup(browser, environment, clientName,"CRMOP","SUPERUSER");
CrmHome ObjCrmHome = new CrmHome(getDriver());
ObjCrmHome = ObjCrmHome.clickOnInlineDialog();
AdvancedFilter ObjAdvancedFilter = ObjCrmHome.clickAdvanceFind();
int colNum = 1;
String primaryEntity = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectPrimaryEntity",colNum);
String GroupTypeValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectoptGroupType",colNum);
String FieldValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectField",colNum);
String ConditionValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectfilterCondition",colNum);
String ValueForFieldValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "Claim Number", 1);
System.out.println("Claim Number:"+ValueForFieldValue);
String claimStatus = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "ExpectedClaims", 1);
AdvancedFindResult ObjAdvancedFindResult = ObjAdvancedFilter.enterSearchCriteriaAndClickOnResult(primaryEntity, GroupTypeValue,FieldValue,ConditionValue, ValueForFieldValue);
boolean flag = ObjAdvancedFindResult.resultRecordFound();
if (flag)
{
String title = ObjAdvancedFindResult.clickOnLinkFromFirstRecord(0,2);
if(title!= null)
{
String clmStatus = ObjAdvancedFindResult.getDetailsFromResultRecordScreen();
if (clmStatus.contains(claimStatus))
{
// setAssertMessage("The claim status in CRM is Accepted For Payment.", 1);
System.out.println("The claim status in CRM is Accepted For Payment.");
String ClaimStatusCRM = ObjAdvancedFindResult.ClaimsStatus(ValueForFieldValue, evidence,key+"_ClaimStatus");
// Verify Payment Line generated
boolean PaymentLine = ObjAdvancedFindResult.VerifyPaymentLineCreated(ClaimStatusCRM);
List<String> paymentLineDetailsList = new ArrayList<String>();
if(PaymentLine)
{
System.out.println("The Payment Line is generated for claim: " +ValueForFieldValue );
String Paylinestatus = ObjAdvancedFindResult.getPaymentlinestatus();
if(evidence)
{
ObjAdvancedFindResult.takescreenshots(key+"_Paymentstatus_AfterGMPRun");
}
if(Paylinestatus.equalsIgnoreCase("Payment Instruction Issued"))
{
System.out.println("The GMP run is sucessfully");
setAssertMessage("The GMP run is sucessfully", 1);
}
Verify.verifyNotEquals((Paylinestatus.equalsIgnoreCase("Payment Instruction Issued")), "The GMP is not run sucessfully ");
Assert.assertFalse(Verify.verifyFailure(), "There were some Failures as shown above.");
}
}
}
}
}
@Test(retryAnalyzer = helpers.RetryMechanism.class, groups = { "Regression","PCSE","CS","Sanity"} ,enabled = true)
@Parameters({"browser", "environment", "clientName" , "evidence"})
public void verifyCreateGMPRunForGPP(String browser ,String environment, String clientName , boolean evidence) throws InterruptedException, IOException, AWTException, ParseException
{
String key ="2";
setup(browser, environment, clientName,"GPP");
pageobjects.GMP.GMPhelpers.CreateGPPStdClaim(getDriver(),environment);
tearDown(browser);
Thread.sleep(3000);
setup(browser, environment, clientName,"CRMGPP");
pageobjects.GMP.GMPhelpers.VerifyGPPClaimOnCRM_GMP(getDriver());
tearDown(browser);
Thread.sleep(3000);
String PaymentDuedate_Excel = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "PaymentDuedate", 2);
setup(browser, environment, clientName, "GMP");
GMPHome ObjGMPHome = new GMPHome(getDriver());
ObjGMPHome = ObjGMPHome.clickOnNewCreateGMP(PaymentDuedate_Excel,2);
ObjGMPHome = ObjGMPHome.clickonSearch(getDriver());
VarianceReports objVarianceReports = ObjGMPHome.VerifyPaymentstatus();
objVarianceReports = objVarianceReports.clickonGeneratePaymentFile();
PaymentInstructionFile objPaymentInstructionFile = objVarianceReports.ClickonPaymentInstructionFile();
objPaymentInstructionFile = objPaymentInstructionFile.ClickOnDownload(getDriver());
if(evidence)
{
objPaymentInstructionFile.takescreenshots(key+"_Downloaded_Dot1file");
}
tearDown(browser);
Thread.sleep(2000);
setup(browser, environment, clientName,"CRMGPP","SUPERUSER");
CrmHome ObjCrmHome = new CrmHome(getDriver());
ObjCrmHome = ObjCrmHome.clickOnInlineDialog();
AdvancedFilter ObjAdvancedFilter = ObjCrmHome.clickAdvanceFind();
int colNum = 1;
String primaryEntity = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectPrimaryEntity",colNum);
String GroupTypeValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectoptGroupType",colNum);
String FieldValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectField",colNum);
String ConditionValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("CRMTESTDATA.xlsx", "AdvancedFind", "selectfilterCondition",colNum);
String ValueForFieldValue = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "Claim Number", 2);
System.out.println("Claim Number:"+ValueForFieldValue);
String claimStatus = utilities.ExcelUtilities.getKeyValueFromExcelWithPosition("GMPTESTDATA.xlsx", "ClaimDetails", "ExpectedClaims", 2);
AdvancedFindResult ObjAdvancedFindResult = ObjAdvancedFilter.enterSearchCriteriaAndClickOnResult(primaryEntity, GroupTypeValue,FieldValue,ConditionValue, ValueForFieldValue);
boolean flag = ObjAdvancedFindResult.resultRecordFound();
if (flag)
{
String title = ObjAdvancedFindResult.clickOnLinkFromFirstRecord(0,2);
if(title!= null)
{
String clmStatus = ObjAdvancedFindResult.getDetailsFromResultRecordScreen();
if (clmStatus.contains(claimStatus))
{
// setAssertMessage("The claim status in CRM is Accepted For Payment.", 1);
System.out.println("The claim status in CRM is Accepted For Payment.");
String ClaimStatusCRM = ObjAdvancedFindResult.ClaimsStatus(ValueForFieldValue, evidence,key+"_ClaimStatus");
// Verify Payment Line generated
boolean PaymentLine = ObjAdvancedFindResult.VerifyPaymentLineCreated(ClaimStatusCRM);
List<String> paymentLineDetailsList = new ArrayList<String>();
if(PaymentLine)
{
System.out.println("The Payment Line is generated for claim: " +ValueForFieldValue );
String Paylinestatus = ObjAdvancedFindResult.getPaymentlinestatus();
if(evidence)
{
ObjAdvancedFindResult.takescreenshots(key+"_Paymentstatus_AfterGMPRun");
}
if(Paylinestatus.equalsIgnoreCase("Payment Instruction Issued"))
{
System.out.println("The GMP run is sucessfully");
setAssertMessage("The GMP run is sucessfully", 1);
}
Verify.verifyNotEquals((Paylinestatus.equalsIgnoreCase("Payment Instruction Issued")), "The GMP is not run sucessfully ");
}
}
}
}
}
}
| true
|
ddc26765a31c4c97ffbcce06838987d58e1a1eaa
|
Java
|
DoctrinaManagement/Doctrina-app
|
/src/main/java/sign/check.java
|
UTF-8
| 635
| 1.671875
| 2
|
[] |
no_license
|
package sign;
import java.io.*;
import javax.servlet.http.*; // import javax.servlet.ServletException;
import database.DatabaseConnection;
import export.ReUsable;
import java.util.*; // import javax.servlet.http.HttpServletRequest;
import javax.servlet.*;
import java.sql.*;
/**
* @author Pandi
*/
public class check extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
DatabaseConnection data = new DatabaseConnection();
Connection connection = data.connect();
}
}
| true
|
69820bf6606882ce79d2ce295e44754947780a38
|
Java
|
enjoy008/KindyDemos
|
/app/src/main/java/com/kindy/demo/view/CanvasViewTest.java
|
UTF-8
| 4,924
| 2.890625
| 3
|
[] |
no_license
|
package com.kindy.demo.view;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import android.view.View;
public class CanvasViewTest extends View {
private Paint paint;
private ArrayList<PointF> graphics = new ArrayList<PointF>();
public CanvasViewTest(Context context) {
super(context);
paint = new Paint(); // 设置一个笔刷大小是3的黄色的画笔
paint.setColor(Color.YELLOW);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(3);
}
// 在这里我们将测试canvas提供的绘制图形方法
@Override
protected void onDraw(Canvas canvas) {
drawColor(canvas);
// drawLine(canvas);
// drawCircle(canvas);
// drawArc(canvas);
// drawOval(canvas);
// drawRect(canvas);
// drawRoundRect(canvas);
// drawPosText(canvas);
// drawTextOnPath(canvas);
// drawPath(canvas);
onDraw1(canvas);
onDraw2(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
graphics.add(new PointF(event.getX(), event.getY()));
invalidate(); // 重新绘制区域
return true;
}
return super.onTouchEvent(event);
}
protected void onDraw2(Canvas canvas) {
for (PointF point : graphics) {
canvas.drawPoint(point.x, point.y, paint);
}
}
protected void onDraw1(Canvas canvas) {
canvas.save();
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
canvas.translate(canvas.getWidth() / 2, 200); // 将位置移动画纸的坐标点:150,150
canvas.drawCircle(0, 0, 100, paint); // 画圆圈
// 使用path绘制路径文字
canvas.save();
canvas.translate(-75, -75);
Path path = new Path();
path.addArc(new RectF(0, 0, 150, 150), -180, 180);
Paint citePaint = new Paint(paint);
citePaint.setTextSize(14);
citePaint.setStrokeWidth(1);
canvas.drawTextOnPath("http://www.android777.com", path, 28, 0,
citePaint);
canvas.restore();
Paint tmpPaint = new Paint(paint); // 小刻度画笔对象
tmpPaint.setStrokeWidth(1);
float y = 100;
int count = 60; // 总刻度数
for (int i = 0; i < count; i++) {
if (i % 5 == 0) {
canvas.drawLine(0f, y, 0, y + 12f, paint);
canvas.drawText(String.valueOf(i / 5 + 1), -4f, y + 25f,
tmpPaint);
} else {
canvas.drawLine(0f, y, 0f, y + 5f, tmpPaint);
}
canvas.rotate(360 / count, 0f, 0f); // 旋转画纸
}
// 绘制指针
tmpPaint.setColor(Color.GRAY);
tmpPaint.setStrokeWidth(4);
canvas.drawCircle(0, 0, 7, tmpPaint);
tmpPaint.setStyle(Style.FILL);
tmpPaint.setColor(Color.YELLOW);
canvas.drawCircle(0, 0, 5, tmpPaint);
canvas.drawLine(0, 10, 0, -65, paint);
canvas.restore();
}
protected void drawPath(Canvas canvas) {
Path path = new Path(); // 定义一条路径
path.moveTo(10, 10); // 移动到 坐标10,10
path.lineTo(50, 60);
path.lineTo(200, 80);
path.lineTo(10, 10);
canvas.drawPath(path, paint);
}
protected void drawTextOnPath(Canvas canvas) {
Path path = new Path(); // 定义一条路径
path.moveTo(10, 10); // 移动到 坐标10,10
path.lineTo(50, 60);
path.lineTo(200, 80);
path.lineTo(10, 10);
// canvas.drawPath(path, paint);
canvas.drawTextOnPath("Android777开发者博客", path, 10, 10, paint);
}
protected void drawPosText(Canvas canvas) {
// 按照既定点 绘制文本内容
canvas.drawPosText("Android777", new float[] { 10, 10, // 第一个字母在坐标10,10
20, 20, // 第二个字母在坐标20,20
30, 30, // ....
40, 40, 50, 50, 60, 60, 70, 70, 80, 80, 90, 90, 100, 100 },
paint);
}
protected void drawRoundRect(Canvas canvas) {
RectF rect = new RectF(50, 50, 200, 200);
canvas.drawRoundRect(rect, 30, // x轴的半径
30, // y轴的半径
paint);
}
protected void drawRect(Canvas canvas) {
RectF rect = new RectF(50, 50, 200, 200);
canvas.drawRect(rect, paint);
}
protected void drawOval(Canvas canvas) {
// 定义一个矩形区域
RectF oval = new RectF(100, 100, 300, 400);
// 矩形区域内切椭圆
canvas.drawOval(oval, paint);
}
protected void drawLine(Canvas canvas) {
// 画一条线
canvas.drawLine(10, 10, 100, 100, paint);
}
protected void drawColor(Canvas canvas) {
canvas.drawColor(Color.BLACK);
}
protected void drawCircle(Canvas canvas) {
canvas.drawCircle(100, 100, 90, paint);
}
/**
* 绘制弧线区域
*
* @param canvas
*/
protected void drawArc(Canvas canvas) {
RectF rect = new RectF(0, 0, 100, 100);
canvas.drawArc(rect, // 弧线所使用的矩形区域大小
0, // 开始角度
90, // 扫过的角度
true, // 是否使用中心
paint);
}
}
| true
|
051b189417328fa05e69aebe1e68587e5f81dc17
|
Java
|
wds1181977/MallPlus
|
/app/src/main/java/com/tymall/model/GasPriceMddel.java
|
UTF-8
| 7,376
| 2.171875
| 2
|
[] |
no_license
|
package com.tymall.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class GasPriceMddel implements Serializable{
/**
* user_limit : {"level_1":{"rate":0.5,"num":"90"},"level_2":{"rate":0.3,"num":"80"},"level_3":{"rate":0.1,"num":"20"},"level_4":{"rate":0.01,"num":"60"}}
* vip_info : {"vip_level":"1","vip_rate":0}
* step_day : {"1":7,"2":45,"3":90}
* over_rate : 0.01
* rulesList : ["7日内DBM收益手续费","45日内DBM收益手续费","90日内DBM收益手续费","90日外DBM收益手续费","其他币种手续费","普通VIP手续费减免","高级VIP手续费减免","手续费最低10DBM"]
* rulesValue : ["50%","30%","10%","1%","1%","25%","50%","10DBM"]
*/
private UserLimitBean user_limit;
private VipInfoBean vip_info;
private StepDayBean step_day;
private String over_rate;
private List<String> rulesList;
private List<String> rulesValue;
private String inputAmount;
private String fee;
private String vipValue;
private String cf;
public String getInputAmount() {
return inputAmount;
}
public void setInputAmount(String inputAmount) {
this.inputAmount = inputAmount;
}
public String getFee() {
return fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getVipValue() {
return vipValue;
}
public void setVipValue(String vipValue) {
this.vipValue = vipValue;
}
public String getCf() {
return cf;
}
public void setCf(String cf) {
this.cf = cf;
}
public UserLimitBean getUser_limit() {
return user_limit;
}
public void setUser_limit(UserLimitBean user_limit) {
this.user_limit = user_limit;
}
public VipInfoBean getVip_info() {
return vip_info;
}
public void setVip_info(VipInfoBean vip_info) {
this.vip_info = vip_info;
}
public StepDayBean getStep_day() {
return step_day;
}
public void setStep_day(StepDayBean step_day) {
this.step_day = step_day;
}
public String getOver_rate() {
return over_rate;
}
public void setOver_rate(String over_rate) {
this.over_rate = over_rate;
}
public List<String> getRulesList() {
return rulesList;
}
public void setRulesList(List<String> rulesList) {
this.rulesList = rulesList;
}
public List<String> getRulesValue() {
return rulesValue;
}
public void setRulesValue(List<String> rulesValue) {
this.rulesValue = rulesValue;
}
public static class UserLimitBean {
/**
* level_1 : {"rate":0.5,"num":"90"}
* level_2 : {"rate":0.3,"num":"80"}
* level_3 : {"rate":0.1,"num":"20"}
* level_4 : {"rate":0.01,"num":"60"}
*/
private Level1Bean level_1;
private Level2Bean level_2;
private Level3Bean level_3;
private Level4Bean level_4;
public Level1Bean getLevel_1() {
return level_1;
}
public void setLevel_1(Level1Bean level_1) {
this.level_1 = level_1;
}
public Level2Bean getLevel_2() {
return level_2;
}
public void setLevel_2(Level2Bean level_2) {
this.level_2 = level_2;
}
public Level3Bean getLevel_3() {
return level_3;
}
public void setLevel_3(Level3Bean level_3) {
this.level_3 = level_3;
}
public Level4Bean getLevel_4() {
return level_4;
}
public void setLevel_4(Level4Bean level_4) {
this.level_4 = level_4;
}
public static class Level1Bean implements Serializable{
/**
* rate : 0.5
* num : 0
*/
private String rate;
private String num;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
public static class Level2Bean implements Serializable{
/**
* rate : 0.3
* num : 0
*/
private String rate;
private String num;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
public static class Level3Bean implements Serializable{
/**
* rate : 0.1
* num : 0
*/
private String rate;
private String num;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
public static class Level4Bean implements Serializable{
/**
* rate : 0.01
* num : 0
*/
private String rate;
private String num;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
}
public static class VipInfoBean implements Serializable{
/**
* vip_level : 1
* vip_rate : 0
*/
private String vip_level;
private String vip_rate;
public String getVip_level() {
return vip_level;
}
public void setVip_level(String vip_level) {
this.vip_level = vip_level;
}
public String getVip_rate() {
return vip_rate;
}
public void setVip_rate(String vip_rate) {
this.vip_rate = vip_rate;
}
}
public static class StepDayBean {
/**
* 1 : 7
* 2 : 45
* 3 : 90
*/
@SerializedName("1")
private int _$1;
@SerializedName("2")
private int _$2;
@SerializedName("3")
private int _$3;
public int get_$1() {
return _$1;
}
public void set_$1(int _$1) {
this._$1 = _$1;
}
public int get_$2() {
return _$2;
}
public void set_$2(int _$2) {
this._$2 = _$2;
}
public int get_$3() {
return _$3;
}
public void set_$3(int _$3) {
this._$3 = _$3;
}
}
}
| true
|
55b8becb2abc482219365bbbeed1fe545cd72180
|
Java
|
gabrielpessoa/uSocialNetwork
|
/SocialNetworkServer/src/br/edu/ifpe/igarassu/ipi/poo/usn/data/entity/exception/InvalidDataException.java
|
UTF-8
| 193
| 1.984375
| 2
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
package br.edu.ifpe.igarassu.ipi.poo.usn.data.entity.exception;
public class InvalidDataException extends Exception {
public InvalidDataException(String mensagem){
super(mensagem);
}
}
| true
|
18a15b56fba8320e2ffa8f53530107ca46822af4
|
Java
|
rgaertner/Smaller
|
/server/osgi-telnet/src/main/java/de/matrixweb/smaller/osgi/telnetd/CommandException.java
|
UTF-8
| 460
| 1.976563
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
package de.matrixweb.smaller.osgi.telnetd;
/**
* @author marwol
*/
public class CommandException extends RuntimeException {
private static final long serialVersionUID = -6692957917486747409L;
/**
* @param message
* @param cause
*/
public CommandException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* @param cause
*/
public CommandException(final Throwable cause) {
super(cause);
}
}
| true
|
4bc9fbda0ed31eacec908152b9f5b32dfd1f64c1
|
Java
|
kimkc/Algorithm
|
/Baekjoon/graph/No7562.java
|
UHC
| 1,846
| 3.296875
| 3
|
[] |
no_license
|
package Baekjoon.graph;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class No7562 {
static int[][] yNx = {{-2,-1},{-2,1},{-1,-2},{-1,2},
{2,1}, {2, -1},{1,2},{1,-2}};
static int n;
static int[][] board;
static int[] goal = new int[2];
static int bfs(int y, int x) {
if(y == goal[0] && x == goal[1]) {
return 1;
}
Queue<Location> q = new LinkedList<Location>();
q.add(new Location(y, x));
board[y][x] = 1; // 0 !visitedε, ٸ ٽ ְ ݺ Ͼ , Ŀ Ÿ -1ָ ȴ.
while(!q.isEmpty()) {
Location loc = q.remove();
for(int i = 0; i < 8; i++) {
int ny = loc.y + yNx[i][0];
int nx = loc.x + yNx[i][1];
if(ny == goal[0] && nx == goal[1]) {
return board[loc.y][loc.x]+1;
}
if( n > ny && ny >= 0 && n > nx && nx >= 0 && board[ny][nx] == 0) {
board[ny][nx] = board[loc.y][loc.x]+1;
q.add(new Location(ny, nx));
}
}
}
return -1;
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCase = Integer.parseInt(br.readLine());
while(testCase > 0) {
n = Integer.parseInt(br.readLine());
board = new int[n][n];
String[] start = br.readLine().split(" ");
String[] end = br.readLine().split(" ");
goal[0] = Integer.parseInt(end[0]);
goal[1] = Integer.parseInt(end[1]);
System.out.println(bfs(Integer.parseInt(start[0]), Integer.parseInt(start[1]))-1);
testCase--;
}
}
}
class Location{
int y;
int x;
Location(int y, int x){
this.y = y;
this.x = x;
}
}
| true
|
517f213ac1e3b882750dfd00b94ed71e49da37cc
|
Java
|
eMainTec-DREAM/DREAM
|
/JavaSource/dream/mgr/usrrpt/dao/oraImpl/MaUserRptParamListDAOOraImpl.java
|
WINDOWS-1252
| 3,770
| 1.71875
| 2
|
[] |
no_license
|
package dream.mgr.usrrpt.dao.oraImpl;
import java.util.List;
import common.bean.User;
import common.spring.BaseJdbcDaoSupportOra;
import common.util.QueryBuffer;
import dream.mgr.usrrpt.dao.MaUserRptParamListDAO;
import dream.mgr.usrrpt.dto.MaUserRptCommonDTO;
/**
* dao
* @author ssong
* @version $Id:$
* @since 1.0
* @spring.bean id="maUserRptParamListDAOTarget"
* @spring.txbn id="maUserRptParamListDAO"
* @spring.property name="dataSource" ref="dataSource"
*/
public class MaUserRptParamListDAOOraImpl extends BaseJdbcDaoSupportOra implements MaUserRptParamListDAO
{
/**
* grid find
* @author ssong
* @version $Id:$
* @since 1.0
*
* @param maPtMstrCommonDTO
* @param loginUser
* @return List
*/
public List findList(MaUserRptCommonDTO maUserRptCommonDTO, User loginUser)
{
QueryBuffer query = new QueryBuffer();
query.append("SELECT ");
query.append(" '' seqNo, ");
query.append(" x.table_name tableName, ");
query.append(" x.column_name columnName, ");
query.append(" x.description colDesc, ");
query.append(" NVL(use_yn,'N') isDisplay, ");
query.append(" step_num stepNum, ");
query.append(" con_value conValue, ");
query.append(" SFACODE_TO_DESC(whr_con_operator,'WHR_CON_OPERATOR','SYS','','"+loginUser.getLangId()+"') whrConOperator, ");
query.append(" usrrptwhr_id usrrptwhrId, ");
query.append(" (SELECT a.usrrpttab_id FROM TAUSRRPTTAB a WHERE x.table_id = a.table_id AND a.usrrptlist_id = "+maUserRptCommonDTO.getUsrrptlistId()+") usrrpttabId, ");
query.append(" (SELECT a.usrrptlist_id FROM TAUSRRPTTAB a WHERE x.table_id = a.table_id AND a.usrrptlist_id = "+maUserRptCommonDTO.getUsrrptlistId()+") usrrptlistId, ");
query.append(" x.tabcol_id tabcolId ");
query.append("FROM TATABCOL x LEFT OUTER JOIN TAUSRRPTWHR y ON x.tabcol_id = y.tabcol_id AND y.usrrptlist_id = "+maUserRptCommonDTO.getUsrrptlistId()+" ");
query.append("WHERE x.table_id IN (SELECT a.table_id FROM TAUSRRPTTAB a WHERE a.usrrptlist_id = "+maUserRptCommonDTO.getUsrrptlistId()+") ");
query.append(this.getWhere(maUserRptCommonDTO,loginUser));
query.append("ORDER BY 5 DESC, 6, 2, 3 ");
return getJdbcTemplate().queryForList(query.toString());
}
/**
* delete
* @author ssong
* @version $Id:$
* @since 1.0
*
* @param eqPartId
* @param loginUser
* @return
*/
public int deleteList(String eqPartId, User loginUser)
{
QueryBuffer query = new QueryBuffer();
query.append("DELETE FROM TAUSRRPTTAB ");
query.append("WHERE comp_no = '"+loginUser.getCompNo()+"' ");
query.append(" AND usrrpttab_id = '"+eqPartId+"' ");
return this.getJdbcTemplate().update(query.toString());
}
private String getWhere(MaUserRptCommonDTO maUserRptCommonDTO, User loginUser)
{
QueryBuffer query = new QueryBuffer();
if (!"".equals(maUserRptCommonDTO.getUsrrptwhrId()))
{
query.getAndQuery("y.usrrptwhr_id", maUserRptCommonDTO.getUsrrptwhrId());
return query.toString();
}
return query.toString();
}
}
| true
|
7d6732dab866b257c43d6ab5ac1c409fa2361f9f
|
Java
|
Ashish1414/Doodle
|
/app/src/main/java/com/proxima/elearning/AboutStudent.java
|
UTF-8
| 2,234
| 2.171875
| 2
|
[] |
no_license
|
package com.proxima.elearning;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AboutStudent extends AppCompatActivity {
TextView tvName,tvEmail,tvPhone,tvClass,tvCourse,tvInterest;
SharedPreferences sharedPreferences;
String name,email,phone,Class,course,interest;
Button changePassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_student);
tvClass = findViewById(R.id.tvClass);
tvName = findViewById(R.id.tvName);
tvEmail = findViewById(R.id.tvEmail);
tvPhone = findViewById(R.id.tvPhone);
tvCourse = findViewById(R.id.tvCourse);
tvInterest = findViewById(R.id.tvInterest);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null)
{
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_actionbar));
}
getData();
tvName.setText(name);
tvClass.setText(Class);
tvCourse.setText(course);
tvEmail.setText(email);
tvPhone.setText(phone);
tvInterest.setText(interest);
findViewById(R.id.change_password).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(AboutStudent.this,ChangePassword.class);
startActivityForResult(intent,0);
overridePendingTransition(0,0);
}
});
}
private void getData() {
sharedPreferences = getSharedPreferences("Login",0);
name=sharedPreferences.getString("name","");
Class=sharedPreferences.getString("Class","");
phone=sharedPreferences.getString("phone","");
course=sharedPreferences.getString("course","");
email=sharedPreferences.getString("email","");
interest=sharedPreferences.getString("interest","");
}
}
| true
|
59c8a00728cede191af8bc97311d94266716c0f8
|
Java
|
kaltons/My-OrderSystem
|
/src/main/java/com/kaltons/order/service/ProductService.java
|
UTF-8
| 1,349
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package com.kaltons.order.service;
import com.kaltons.order.dto.CartDTO;
import com.kaltons.order.entity.ProductInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
/**
* ProductInfo 业务操作接口类
*
* @author 衍方
* @desc
* @date 2020/9/21 - 22:27
*/
public interface ProductService {
/**
* 根据商品ID查找
* @param productId
* @return
*/
Optional<ProductInfo> findOne(String productId);
/**
* 查找所有上架商品
* @return
*/
List<ProductInfo> findUpAll();
/**
* 卖家查找所有商品
* @param pageable
* @return
*/
Page<ProductInfo> findAll(Pageable pageable);
/**
* 添加商品
* @param productInfo
* @return
*/
ProductInfo save(ProductInfo productInfo);
/**
* 加库存
* @param cartDTOList
*/
void increaseStock(List<CartDTO> cartDTOList);
/**
* 减库存
* @param cartDTOList
*/
void decreaseStock(List<CartDTO> cartDTOList);
/**
* 上架
* @param productId
* @return
*/
ProductInfo onSale(String productId);
/**
* 下架
* @param productId
* @return
*/
ProductInfo offSale(String productId);
}
| true
|
6c37fab12b7bc8f0ff6dc9a39ecac7b3bc3ddca1
|
Java
|
dengjiaping/wanjicardc-android
|
/wanjicardc-android/WjikaClient/app/src/main/java/com/wjika/client/network/entities/ExchangeCardEntity.java
|
UTF-8
| 2,145
| 2.375
| 2
|
[] |
no_license
|
package com.wjika.client.network.entities;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Created by zhaoweiwei on 2016/11/30.
*/
public class ExchangeCardEntity implements Parcelable{
@SerializedName("id")
private String id;
@SerializedName("cardColorValue")
private String cardColorValue;
@SerializedName("thirdCardSortId")
private int thirdCardSortId;
@SerializedName("newCardName")
private String cardName;
@SerializedName("logoUrl")
private String logoUrl;
protected ExchangeCardEntity(Parcel in) {
id = in.readString();
cardColorValue = in.readString();
thirdCardSortId = in.readInt();
cardName = in.readString();
logoUrl = in.readString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCardColorValue() {
return cardColorValue;
}
public void setCardColorValue(String cardColorValue) {
this.cardColorValue = cardColorValue;
}
public int getThirdCardSortId() {
return thirdCardSortId;
}
public void setThirdCardSortId(int thirdCardSortId) {
this.thirdCardSortId = thirdCardSortId;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public static Creator<ExchangeCardEntity> getCREATOR() {
return CREATOR;
}
public static final Creator<ExchangeCardEntity> CREATOR = new Creator<ExchangeCardEntity>() {
@Override
public ExchangeCardEntity createFromParcel(Parcel in) {
return new ExchangeCardEntity(in);
}
@Override
public ExchangeCardEntity[] newArray(int size) {
return new ExchangeCardEntity[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id);
parcel.writeString(cardColorValue);
parcel.writeInt(thirdCardSortId);
parcel.writeString(cardName);
parcel.writeString(logoUrl);
}
}
| true
|
1c6f3a9a91718234b01230eaa1a960d912017740
|
Java
|
mohitrajvardhan17/java1.8.0_151
|
/sun/security/provider/certpath/IndexedCollectionCertStore.java
|
UTF-8
| 11,731
| 2.203125
| 2
|
[] |
no_license
|
package sun.security.provider.certpath;
import java.security.InvalidAlgorithmParameterException;
import java.security.cert.CRL;
import java.security.cert.CRLSelector;
import java.security.cert.CertSelector;
import java.security.cert.CertStoreException;
import java.security.cert.CertStoreParameters;
import java.security.cert.CertStoreSpi;
import java.security.cert.Certificate;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLSelector;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
public class IndexedCollectionCertStore
extends CertStoreSpi
{
private Map<X500Principal, Object> certSubjects;
private Map<X500Principal, Object> crlIssuers;
private Set<Certificate> otherCertificates;
private Set<CRL> otherCRLs;
public IndexedCollectionCertStore(CertStoreParameters paramCertStoreParameters)
throws InvalidAlgorithmParameterException
{
super(paramCertStoreParameters);
if (!(paramCertStoreParameters instanceof CollectionCertStoreParameters)) {
throw new InvalidAlgorithmParameterException("parameters must be CollectionCertStoreParameters");
}
Collection localCollection = ((CollectionCertStoreParameters)paramCertStoreParameters).getCollection();
if (localCollection == null) {
throw new InvalidAlgorithmParameterException("Collection must not be null");
}
buildIndex(localCollection);
}
private void buildIndex(Collection<?> paramCollection)
{
certSubjects = new HashMap();
crlIssuers = new HashMap();
otherCertificates = null;
otherCRLs = null;
Iterator localIterator = paramCollection.iterator();
while (localIterator.hasNext())
{
Object localObject = localIterator.next();
if ((localObject instanceof X509Certificate))
{
indexCertificate((X509Certificate)localObject);
}
else if ((localObject instanceof X509CRL))
{
indexCRL((X509CRL)localObject);
}
else if ((localObject instanceof Certificate))
{
if (otherCertificates == null) {
otherCertificates = new HashSet();
}
otherCertificates.add((Certificate)localObject);
}
else if ((localObject instanceof CRL))
{
if (otherCRLs == null) {
otherCRLs = new HashSet();
}
otherCRLs.add((CRL)localObject);
}
}
if (otherCertificates == null) {
otherCertificates = Collections.emptySet();
}
if (otherCRLs == null) {
otherCRLs = Collections.emptySet();
}
}
private void indexCertificate(X509Certificate paramX509Certificate)
{
X500Principal localX500Principal = paramX509Certificate.getSubjectX500Principal();
Object localObject1 = certSubjects.put(localX500Principal, paramX509Certificate);
if (localObject1 != null)
{
Object localObject2;
if ((localObject1 instanceof X509Certificate))
{
if (paramX509Certificate.equals(localObject1)) {
return;
}
localObject2 = new ArrayList(2);
((List)localObject2).add(paramX509Certificate);
((List)localObject2).add((X509Certificate)localObject1);
certSubjects.put(localX500Principal, localObject2);
}
else
{
localObject2 = (List)localObject1;
if (!((List)localObject2).contains(paramX509Certificate)) {
((List)localObject2).add(paramX509Certificate);
}
certSubjects.put(localX500Principal, localObject2);
}
}
}
private void indexCRL(X509CRL paramX509CRL)
{
X500Principal localX500Principal = paramX509CRL.getIssuerX500Principal();
Object localObject1 = crlIssuers.put(localX500Principal, paramX509CRL);
if (localObject1 != null)
{
Object localObject2;
if ((localObject1 instanceof X509CRL))
{
if (paramX509CRL.equals(localObject1)) {
return;
}
localObject2 = new ArrayList(2);
((List)localObject2).add(paramX509CRL);
((List)localObject2).add((X509CRL)localObject1);
crlIssuers.put(localX500Principal, localObject2);
}
else
{
localObject2 = (List)localObject1;
if (!((List)localObject2).contains(paramX509CRL)) {
((List)localObject2).add(paramX509CRL);
}
crlIssuers.put(localX500Principal, localObject2);
}
}
}
public Collection<? extends Certificate> engineGetCertificates(CertSelector paramCertSelector)
throws CertStoreException
{
if (paramCertSelector == null)
{
localObject1 = new HashSet();
matchX509Certs(new X509CertSelector(), (Collection)localObject1);
((Set)localObject1).addAll(otherCertificates);
return (Collection<? extends Certificate>)localObject1;
}
Object localObject2;
if (!(paramCertSelector instanceof X509CertSelector))
{
localObject1 = new HashSet();
matchX509Certs(paramCertSelector, (Collection)localObject1);
localObject2 = otherCertificates.iterator();
while (((Iterator)localObject2).hasNext())
{
localObject3 = (Certificate)((Iterator)localObject2).next();
if (paramCertSelector.match((Certificate)localObject3)) {
((Set)localObject1).add(localObject3);
}
}
return (Collection<? extends Certificate>)localObject1;
}
if (certSubjects.isEmpty()) {
return Collections.emptySet();
}
Object localObject1 = (X509CertSelector)paramCertSelector;
Object localObject3 = ((X509CertSelector)localObject1).getCertificate();
if (localObject3 != null) {
localObject2 = ((X509Certificate)localObject3).getSubjectX500Principal();
} else {
localObject2 = ((X509CertSelector)localObject1).getSubject();
}
if (localObject2 != null)
{
localObject4 = certSubjects.get(localObject2);
if (localObject4 == null) {
return Collections.emptySet();
}
if ((localObject4 instanceof X509Certificate))
{
localObject5 = (X509Certificate)localObject4;
if (((X509CertSelector)localObject1).match((Certificate)localObject5)) {
return Collections.singleton(localObject5);
}
return Collections.emptySet();
}
Object localObject5 = (List)localObject4;
HashSet localHashSet = new HashSet(16);
Iterator localIterator = ((List)localObject5).iterator();
while (localIterator.hasNext())
{
X509Certificate localX509Certificate = (X509Certificate)localIterator.next();
if (((X509CertSelector)localObject1).match(localX509Certificate)) {
localHashSet.add(localX509Certificate);
}
}
return localHashSet;
}
Object localObject4 = new HashSet(16);
matchX509Certs((CertSelector)localObject1, (Collection)localObject4);
return (Collection<? extends Certificate>)localObject4;
}
private void matchX509Certs(CertSelector paramCertSelector, Collection<Certificate> paramCollection)
{
Iterator localIterator1 = certSubjects.values().iterator();
while (localIterator1.hasNext())
{
Object localObject1 = localIterator1.next();
Object localObject2;
if ((localObject1 instanceof X509Certificate))
{
localObject2 = (X509Certificate)localObject1;
if (paramCertSelector.match((Certificate)localObject2)) {
paramCollection.add(localObject2);
}
}
else
{
localObject2 = (List)localObject1;
Iterator localIterator2 = ((List)localObject2).iterator();
while (localIterator2.hasNext())
{
X509Certificate localX509Certificate = (X509Certificate)localIterator2.next();
if (paramCertSelector.match(localX509Certificate)) {
paramCollection.add(localX509Certificate);
}
}
}
}
}
public Collection<CRL> engineGetCRLs(CRLSelector paramCRLSelector)
throws CertStoreException
{
if (paramCRLSelector == null)
{
localObject1 = new HashSet();
matchX509CRLs(new X509CRLSelector(), (Collection)localObject1);
((Set)localObject1).addAll(otherCRLs);
return (Collection<CRL>)localObject1;
}
if (!(paramCRLSelector instanceof X509CRLSelector))
{
localObject1 = new HashSet();
matchX509CRLs(paramCRLSelector, (Collection)localObject1);
localObject2 = otherCRLs.iterator();
while (((Iterator)localObject2).hasNext())
{
localObject3 = (CRL)((Iterator)localObject2).next();
if (paramCRLSelector.match((CRL)localObject3)) {
((Set)localObject1).add(localObject3);
}
}
return (Collection<CRL>)localObject1;
}
if (crlIssuers.isEmpty()) {
return Collections.emptySet();
}
Object localObject1 = (X509CRLSelector)paramCRLSelector;
Object localObject2 = ((X509CRLSelector)localObject1).getIssuers();
if (localObject2 != null)
{
localObject3 = new HashSet(16);
Iterator localIterator1 = ((Collection)localObject2).iterator();
while (localIterator1.hasNext())
{
X500Principal localX500Principal = (X500Principal)localIterator1.next();
Object localObject4 = crlIssuers.get(localX500Principal);
if (localObject4 != null)
{
Object localObject5;
if ((localObject4 instanceof X509CRL))
{
localObject5 = (X509CRL)localObject4;
if (((X509CRLSelector)localObject1).match((CRL)localObject5)) {
((HashSet)localObject3).add(localObject5);
}
}
else
{
localObject5 = (List)localObject4;
Iterator localIterator2 = ((List)localObject5).iterator();
while (localIterator2.hasNext())
{
X509CRL localX509CRL = (X509CRL)localIterator2.next();
if (((X509CRLSelector)localObject1).match(localX509CRL)) {
((HashSet)localObject3).add(localX509CRL);
}
}
}
}
}
return (Collection<CRL>)localObject3;
}
Object localObject3 = new HashSet(16);
matchX509CRLs((CRLSelector)localObject1, (Collection)localObject3);
return (Collection<CRL>)localObject3;
}
private void matchX509CRLs(CRLSelector paramCRLSelector, Collection<CRL> paramCollection)
{
Iterator localIterator1 = crlIssuers.values().iterator();
while (localIterator1.hasNext())
{
Object localObject1 = localIterator1.next();
Object localObject2;
if ((localObject1 instanceof X509CRL))
{
localObject2 = (X509CRL)localObject1;
if (paramCRLSelector.match((CRL)localObject2)) {
paramCollection.add(localObject2);
}
}
else
{
localObject2 = (List)localObject1;
Iterator localIterator2 = ((List)localObject2).iterator();
while (localIterator2.hasNext())
{
X509CRL localX509CRL = (X509CRL)localIterator2.next();
if (paramCRLSelector.match(localX509CRL)) {
paramCollection.add(localX509CRL);
}
}
}
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\security\provider\certpath\IndexedCollectionCertStore.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
| true
|
12945e0b1ba48d449c1e849cb1cc57c95e98a519
|
Java
|
lichao20000/resflow-master
|
/flow-master0925---处理/flow-master0925/flow/flow-server/src/main/java/com/zres/project/localnet/portal/cloudNetworkFlow/tacheWoOrder/UplinkConfigWaitRateTache.java
|
UTF-8
| 7,673
| 1.789063
| 2
|
[] |
no_license
|
package com.zres.project.localnet.portal.cloudNetworkFlow.tacheWoOrder;
import com.alibaba.fastjson.JSON;
import com.zres.project.localnet.portal.cloudNetworkFlow.dao.TacheWoOrderDao;
import com.zres.project.localnet.portal.common.CommonWoOrderDealServiceIntf;
import com.zres.project.localnet.portal.common.ToOrderDealTacheWoOrderIntf;
import com.zres.project.localnet.portal.common.util.TacheIdEnum;
import com.zres.project.localnet.portal.flowdealinfo.data.dao.OrderDealDao;
import com.zres.project.localnet.portal.util.OrderTrackOperType;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @Classname UplinkConfigWaitRateTache
* @Description 上联设备业务配置环节--本地移机
* @Author tang.hl
* @Date 2020/11/5 16:42
*/
@Service
public class UplinkConfigWaitRateTache implements ToOrderDealTacheWoOrderIntf {
Logger logger = LoggerFactory.getLogger(UplinkConfigWaitRateTache.class);
@Autowired
private CommonWoOrderDealServiceIntf commonWoOrderDealServiceIntf;
@Autowired
private OrderDealDao orderDealDao;
@Autowired
private TacheWoOrderDao tacheWoOrderDao;
private final String configAZ = "specialtyConfig";
private final String configA = "specialtyConfig_A";
private final String configZ = "specialtyConfig_Z";
private final String YZW_OPTICAL = "YZW_OPTICAL";
private final String YZW_IPRAN = "YZW_IPRAN";
private final String YZW_A = "localA";
private final String YZW_Z = "localZ";
private final String YZW_B = "B";
/*
* 上联设备业务配置环节到单处理逻辑:需要启上联设备业务配置处理子流程,按照AZ区域派发
* 功能点:
* 1,跨域业务,上联设备业务配置只派单端,
* 2.本地业务,上联设备业务配置需要派单给AZ处理,
* 关于AZ派单,首先,查询新开单派发的区域,若没有,则查询电路属性对应AZ端的区域
* 3,修改主流程环节状态;
*
* @author tang.hl
* @date 2020/11/5
*
*/
@Override
public Map<String, Object> toOrderTacheDoSomething(Map<String, Object> toOrderTacheDoSomeMap) throws Exception {
logger.info("-----------到单处理--------升降速--上联设备业务配置环节-----------------------");
String orderId = MapUtils.getString(toOrderTacheDoSomeMap, "orderId");
String woId = MapUtils.getString(toOrderTacheDoSomeMap, "woId");
String tacheCode = MapUtils.getString(toOrderTacheDoSomeMap, "tacheCode");
// 区域
List<String> areaList = new ArrayList<>();
List<String> areaAList = new ArrayList<>();
List<String> areaZList = new ArrayList<>();
Map<String, Object> qryMap = new HashMap<>();
qryMap.put("orderId", orderId);
// todo :查询新开单的orderId
Map<String,Object> orderInfo = tacheWoOrderDao.qryNewOpenOrderInfo(qryMap);
if(MapUtils.isNotEmpty(orderInfo) && (!"".equals(MapUtils.getString(orderInfo,"ORDER_ID","")))){
Map<String, String> qryParamMap = new HashMap<>();
qryParamMap.put("orderId",MapUtils.getString(orderInfo,"ORDER_ID"));
// 查询新开单配置的ipran专业的对应的AZ区域
Map<String, Object> dispSpecialtyMap = orderDealDao.getDispSpecialtyObj(qryParamMap);
Object specialtyInfoObject = MapUtils.getObject(dispSpecialtyMap, "SPECIALTY_INFO");
Map<String, Object> specialtyInfoMap = JSON.parseObject(specialtyInfoObject.toString(), Map.class);
/*
*{"specialtyConfig_A":{"YZW_OPTICAL":86230,"YZW_MCPE":55391,"YZW_IPRAN":55378},
"specialtyConfig_Z":{"YZW_OPTICAL":55391,"YZW_MCPE":55378,"YZW_IPRAN":55391}}
*/
if(MapUtils.isNotEmpty(specialtyInfoMap) && specialtyInfoMap.keySet().contains(configA)){
Map<String, Object> specConfig = MapUtils.getMap(specialtyInfoMap,configA);
String areaIdValue = MapUtils.getString(specConfig, YZW_IPRAN);
if (!StringUtils.isEmpty(areaIdValue)){
String areaValue = StringUtils.strip(areaIdValue, "[]");
areaAList = Arrays.asList(areaValue.split(","));
}
}
if(MapUtils.isNotEmpty(specialtyInfoMap) && specialtyInfoMap.keySet().contains(configZ)){
Map<String, Object> specConfig = MapUtils.getMap(specialtyInfoMap,configZ);
String areaIdValue = MapUtils.getString(specConfig, YZW_IPRAN);
if (!StringUtils.isEmpty(areaIdValue)){
String areaValue = StringUtils.strip(areaIdValue, "[]");
areaZList = Arrays.asList(areaValue.split(","));
}
}
}
if(CollectionUtils.isEmpty(areaAList)){
// 电路属性:A端城市
qryMap.put("attrCode", "20000234");
String areaA = tacheWoOrderDao.qryCity(qryMap);
if(!StringUtils.isEmpty(areaA)){
areaAList.add(areaA);
}
}
if(CollectionUtils.isEmpty(areaZList)){
// 电路属性:Z端城市
qryMap.put("attrCode", "20000235");
String areaA = tacheWoOrderDao.qryCity(qryMap);
if(!StringUtils.isEmpty(areaA)){
areaList.add(areaA);
}
}
Map<String,Object> flagMap = tacheWoOrderDao.qryAZFlag(qryMap);
String flag = MapUtils.getString(flagMap,"PARALLEL_FLAG","");
if(YZW_A.equals(flag)){
areaList.addAll(areaAList);
} else if(YZW_Z.equals(flag)){
areaList.addAll(areaZList);
} else {
areaList.addAll(areaAList);
areaList.addAll(areaZList);
}
if(CollectionUtils.isNotEmpty(areaList)){
orderDealDao.updateWoStateByWoId(woId, OrderTrackOperType.WO_ORDER_STATE_10);
try {
String ordPsid = TacheIdEnum.YZW_UPEQUIP_BUSICONFIG_CHILDFLOW;
for(String areaId : areaList) {
Map<String, Object> startChildMap = new HashMap<>();
startChildMap.put("ordPsid", ordPsid);
startChildMap.put("parentOrderId", orderId);
startChildMap.put("parentOrderCode", tacheCode);
startChildMap.put("ORDER_TITLE", "上联设备业务配置子流程");
startChildMap.put("AREA", "350002000000000042766408");
startChildMap.put("ORDER_CONTENT", "子流程");
//startChildMap.put("requFineTime", requFineTime);
Map<String, String> attr = new HashMap<>();
attr.put("REGION_ID", areaId); // 区域
/*attr.put("SPECIALTY_CODE", YZW_IPRAN); // 专业
attr.put("ACT_TYPE", operActType); // 操作+动作
attr.put("PRODUCT_TYPE", productType); //产品编码*/
startChildMap.put("attr", attr);
commonWoOrderDealServiceIntf.createOrderService(startChildMap);
}
}
catch (Exception e) {
throw e;
}
}else {
throw new Exception("上联设备业务配置启子流程,没有查到区域数据!!");
}
return null;
}
}
| true
|
f0f6a31f6e6ca068d27f9abd7993206691520aa4
|
Java
|
vipul-zambare006/medipal-android-app
|
/app/src/main/java/sg/edu/nus/medipalapplication/activity/CategoryEditActivity.java
|
UTF-8
| 4,525
| 2.359375
| 2
|
[] |
no_license
|
package sg.edu.nus.medipalapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import sg.edu.nus.medipalapplication.R;
import sg.edu.nus.medipalapplication.database.CategoryDAO;
/**
* Created by Govardhan on 20/3/2017.
*/
public class CategoryEditActivity extends AppCompatActivity {
Spinner spinner;
EditText editcode, editcategory, editdescription;
Button categotyupdate;
SwitchCompat categoryreminder;
View mview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_edit);
mview=getLayoutInflater().inflate(R.layout.activity_category, null);
Intent intent = getIntent();
final int id = intent.getExtras().getInt("Id");
final String code = intent.getExtras().getString("Code");
final String name = intent.getExtras().getString("Category");
final String description = intent.getExtras().getString("Description");
final String reminder = intent.getExtras().getString("Reminder");
editcode = (EditText) findViewById(R.id.EditCode);
editcategory = (EditText) findViewById(R.id.EditCategory);
editdescription = (EditText) findViewById(R.id.EditDesription);
categoryreminder = (SwitchCompat) findViewById(R.id.AddCategoryRemind);
categoryreminder.setOnCheckedChangeListener(onCheckedChanged());
/*
if (name.equals("CHRONIC")
|| name.equals("INCIDENTAL")
|| name.equals("COMPLETE COURSE")) {
categoryreminder.setClickable(false);
} else {
categoryreminder.setClickable(true);
}*/
editcode.setText(code);
editcategory.setText(name);
editdescription.setText(description);
categoryreminder.setText(reminder);
categotyupdate = (Button) findViewById(R.id.Categoryupdatebutton);
categotyupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update(id, editcode.getText().toString(), editcategory.getText().toString(), editdescription.getText().toString(),categoryreminder.getText().toString());
}
});
}
private void update(int id, String newcategotycode, String newcategoryname, String newcategorydescription,String newcategoryreminder) {
CategoryDAO categoryDatabase = new CategoryDAO(this);
categoryDatabase.openDb();
long result = categoryDatabase.categoryUpdate(id, newcategotycode, newcategoryname, newcategorydescription,newcategoryreminder);
Log.v("ResultValues", Long.toString(result));
if (result > 0) {
editcode.setText(newcategotycode);
editcategory.setText(newcategoryname);
editdescription.setText(newcategorydescription);
categoryreminder.setText(newcategoryreminder);
Toast.makeText(getApplicationContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(), "Not Updated", Toast.LENGTH_SHORT).show();
}
categoryDatabase.close();
}
private CompoundButton.OnCheckedChangeListener onCheckedChanged() {
return new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.AddCategoryRemind:
setButtonState(isChecked);
break;
}
}
};
}
private void setButtonState(boolean state) {
if (state) {
mview.setEnabled(true);
//Toast.makeText(CategoryEditActivity.this, "Button enabled!", Toast.LENGTH_SHORT).show();
} else {
mview.setEnabled(false);
//Toast.makeText(CategoryEditActivity.this, "Button disabled!", Toast.LENGTH_SHORT).show();
}
}
}
| true
|
ebd2a8d67986a32cf02406af667655fac4d89394
|
Java
|
vcano5/Annihilation_boss
|
/src/com/gmail/eduardokanp/anniboss/listener/KillWither.java
|
UTF-8
| 1,029
| 2.3125
| 2
|
[] |
no_license
|
package com.gmail.eduardokanp.anniboss.listener;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
public class KillWither implements Listener {
ItemStack Star = com.gmail.eduardokanp.anniboss.Main.star();
@EventHandler
public void onWitherDeath(EntityDeathEvent e) {
if(e.getEntity().getType() == EntityType.WITHER) {
e.getDrops().clear();
e.setDroppedExp(0);
Location loc = e.getEntity().getLocation();
e.getEntity().getWorld().dropItemNaturally(loc, Star);
for (int i = 0; i < 50; i += 1) {
for(Player p: Bukkit.getOnlinePlayers()) {
Location lc2 = loc;
String lc = "0." + i;
Double lcd = Double.parseDouble(lc);
lc2.add(lcd, 0, lcd);
p.getWorld().spigot().playEffect(lc2, Effect.FLAME);
}
}
}
}
}
| true
|
d1e398bc9870e35565c2e3e1f3277a6aef5a64e7
|
Java
|
remikr/CauseEffectChains
|
/test/bs/ChallengeExceptionTest.java
|
WINDOWS-1250
| 367
| 2.390625
| 2
|
[] |
no_license
|
package bs;
import static org.junit.Assert.*;
import org.junit.Test;
public class ChallengeExceptionTest {
@Test
public void ChallengeException() {
ChallengeException c = new ChallengeException(1, "Pas de challenge trouv", "");
assertEquals(1, c.lineNumber);
assertEquals("Pas de challenge trouv", c.textCause);
assertEquals("", c.message);
}
}
| true
|
94c841b2ce200caa20ef821cb24eb378e1c9b52c
|
Java
|
mvkdldj24/UploadTest
|
/ex_project/src/main/java/com/ex_project/controller/Ex_Controller.java
|
UTF-8
| 5,115
| 2.1875
| 2
|
[] |
no_license
|
package com.ex_project.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.ex_project.service.Ex_Service;
@org.springframework.stereotype.Controller
@RequestMapping("/ctr")
public class Ex_Controller {
@Autowired
Ex_Service es;
@RequestMapping("/home")
public String home() {
System.out.println("여기냐");
return "redirect/webapp/index.jsp";
}
/* test */
@RequestMapping("/ex")
public String daotestGet2(Model m) {
m.addAttribute("message", "HELLO");
return "/showMessage";
}
// 회원 가입
@RequestMapping(value = "/sign_up", method = RequestMethod.POST)
public String signup(@RequestParam Map<String, String> pm) {
System.out.println("CTR" + pm);
es.insert(pm);
return "redirect:/view/files/login.jsp";
}
// 상품 판매
@RequestMapping(value = "/sale_insert", method = RequestMethod.POST)
public String saleinsert(@RequestParam Map<String, String> pm) {
System.out.println("slae_insert" + pm);
es.sale_insert(pm);
return "redirect:sale_list";
}
// 회원목록
@RequestMapping(value = "/mbrlist", method = RequestMethod.GET)
public ModelAndView mbrlist(Model m) {
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.mbr_select(m);
mv.addObject("list", list);
mv.setViewName("/files/Mblist");
return mv;
}
// 판매목록
@RequestMapping(value = "sale_list", method = RequestMethod.GET)
public ModelAndView salelist(Model m) {
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.sale_select(m);
mv.addObject("list", list);
mv.setViewName("files/Sale_list");
return mv;
}
// 회원명, 상품명 조회
@RequestMapping(value = "m_g_select", method = RequestMethod.GET)
public ModelAndView mgselect(Model m) {
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> m_list = es.mselect(m);
ArrayList<HashMap<String, String>> g_list = es.gselect(m);
mv.addObject("mlist", m_list);
mv.addObject("glist", g_list);
mv.setViewName("files/sale_insert");
return mv;
}
// 회원 상세 조회
@RequestMapping(value = "mbr_dt", method = RequestMethod.GET)
public ModelAndView mbrdt(String mbr_no) {
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.mbr_dt(mbr_no);
mv.addObject("list", list);
System.out.println("가지고왔니?" + mv);
System.out.println("list는?" + list);
mv.setViewName("/files/mbr_dt");
return mv;
}
// 상품 상세 조회
@RequestMapping(value = "/goods_dt", method = RequestMethod.GET)
public ModelAndView goodsdt(String goods_no) {
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.goods_dt(goods_no);
mv.addObject("list", list);
System.out.println("상품상세조회" + mv);
mv.setViewName("/files/goods_dt");
return mv;
}
// 상품 등록
@RequestMapping(value = "/g_insert", method = RequestMethod.GET)
public String ginsert(@RequestParam Map<String, String> d) {
System.out.println("상품등록 ct" + d);
es.g_insert(d);
return "redirect:goods_list";
}
// 상품리스트
@RequestMapping(value="/goods_list", method=RequestMethod.GET)
public ModelAndView goodslist(){
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.goodslist();
System.out.println(list);
mv.addObject("list", list);
mv.setViewName("/files/goods_list");
return mv;
}
//로그인
@RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView login(String mbr_nm, String mbr_pw) {
System.out.println(mbr_nm);
System.out.println(mbr_pw);
ModelAndView mv = new ModelAndView();
ArrayList<HashMap<String, String>> list = es.login(mbr_nm);
System.out.println("돌아오는" + list);
mv.addObject("list", list);
mv.setViewName("files/extest");
return mv;
}
//로그인 확인
@RequestMapping(value="/login_ch", method=RequestMethod.GET)
public ModelAndView loginch(String mbr_id, String mbr_pw) {
ModelAndView mv = new ModelAndView();
System.out.println(mbr_id);
System.out.println(mbr_pw);
return mv;
}
//이동 컨트롤러
@RequestMapping(value = "/mv_goods", method = RequestMethod.GET)
public String mv_goods() {
return "redirect:/view/files/goods_insert.jsp";
}
@RequestMapping(value = "/mv_login", method = RequestMethod.GET)
public String mv_login() {
return "redirect:/view/files/login.jsp";
}
@RequestMapping(value = "/mv_signup", method = RequestMethod.GET)
public String mv_signup() {
return "redirect:/view/files/signup.jsp";
}
}
| true
|
198a33ffd0d16f77f4ee924fa7c837940c64c761
|
Java
|
chongzizil/Banqi-SMG
|
/src/org/banqi/graphics/BanqiImages.java
|
UTF-8
| 3,916
| 2.21875
| 2
|
[] |
no_license
|
package org.banqi.graphics;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface BanqiImages extends ClientBundle {
// Back Piece images
@Source("images/pieces/back.png")
ImageResource back();
// Normal Piece images
@Source("images/pieces/black_general.png")
ImageResource bgen();
@Source("images/pieces/red_general.png")
ImageResource rgen();
@Source("images/pieces/black_advisor.png")
ImageResource badv();
@Source("images/pieces/red_advisor.png")
ImageResource radv();
@Source("images/pieces/black_elephant.png")
ImageResource bele();
@Source("images/pieces/red_elephant.png")
ImageResource rele();
@Source("images/pieces/black_chariot.png")
ImageResource bcha();
@Source("images/pieces/red_chariot.png")
ImageResource rcha();
@Source("images/pieces/black_horse.png")
ImageResource bhor();
@Source("images/pieces/red_horse.png")
ImageResource rhor();
@Source("images/pieces/black_cannon.png")
ImageResource bcan();
@Source("images/pieces/red_cannon.png")
ImageResource rcan();
@Source("images/pieces/black_soldier.png")
ImageResource bsol();
@Source("images/pieces/red_soldier.png")
ImageResource rsol();
// HL Piece images
@Source("images/pieces/black_general_hl.png")
ImageResource bgenHL();
@Source("images/pieces/red_general_hl.png")
ImageResource rgenHL();
@Source("images/pieces/black_advisor_hl.png")
ImageResource badvHL();
@Source("images/pieces/red_advisor_hl.png")
ImageResource radvHL();
@Source("images/pieces/black_elephant_hl.png")
ImageResource beleHL();
@Source("images/pieces/red_elephant_hl.png")
ImageResource releHL();
@Source("images/pieces/black_chariot_hl.png")
ImageResource bchaHL();
@Source("images/pieces/red_chariot_hl.png")
ImageResource rchaHL();
@Source("images/pieces/black_horse_hl.png")
ImageResource bhorHL();
@Source("images/pieces/red_horse_hl.png")
ImageResource rhorHL();
@Source("images/pieces/black_cannon_hl.png")
ImageResource bcanHL();
@Source("images/pieces/red_cannon_hl.png")
ImageResource rcanHL();
@Source("images/pieces/black_soldier_hl.png")
ImageResource bsolHL();
@Source("images/pieces/red_soldier_hl.png")
ImageResource rsolHL();
// Target HL Piece images
@Source("images/pieces/black_general_target_hl.png")
ImageResource bgenTargetHL();
@Source("images/pieces/red_general_target_hl.png")
ImageResource rgenTargetHL();
@Source("images/pieces/black_advisor_target_hl.png")
ImageResource badvTargetHL();
@Source("images/pieces/red_advisor_target_hl.png")
ImageResource radvTargetHL();
@Source("images/pieces/black_elephant_target_hl.png")
ImageResource beleTargetHL();
@Source("images/pieces/red_elephant_target_hl.png")
ImageResource releTargetHL();
@Source("images/pieces/black_chariot_target_hl.png")
ImageResource bchaTargetHL();
@Source("images/pieces/red_chariot_target_hl.png")
ImageResource rchaTargetHL();
@Source("images/pieces/black_horse_target_hl.png")
ImageResource bhorTargetHL();
@Source("images/pieces/red_horse_target_hl.png")
ImageResource rhorTargetHL();
@Source("images/pieces/black_cannon_target_hl.png")
ImageResource bcanTargetHL();
@Source("images/pieces/red_cannon_target_hl.png")
ImageResource rcanTargetHL();
@Source("images/pieces/black_soldier_target_hl.png")
ImageResource bsolTargetHL();
@Source("images/pieces/red_soldier_target_hl.png")
ImageResource rsolTargetHL();
// Empty cell
@Source("images/other/empty_cell.gif")
ImageResource eemp();
@Source("images/other/empty_cell_target_hl.gif")
ImageResource eempTargetHL();
// Banqi board
@Source("images/other/board.gif")
ImageResource board();
//Banqi board for mobile
// @Source("images/other/board_mobile.gif")
// ImageResource board();
}
| true
|
da0a2cad97aa8a63fbcd2a65fe7f0a9d44e1f31e
|
Java
|
bregnvig/F2007
|
/web/src/main/java/dk/bregnvig/formula1/client/validation/AbstractRule.java
|
UTF-8
| 1,863
| 2.5
| 2
|
[] |
no_license
|
package dk.bregnvig.formula1.client.validation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public abstract class AbstractRule implements Rule {
private Widget field;
private Label labelProperty;
private String property;
private AbstractRule(Widget field) {
if (field == null) {
throw new IllegalArgumentException("the field must be set");
}
this.field = field;
}
public AbstractRule(Widget field, Label labelProperty) {
this(field);
if (labelProperty == null) {
throw new IllegalArgumentException("The property label must be set");
}
this.labelProperty = labelProperty;
this.property = labelProperty.getText();
}
public AbstractRule(Widget field, String property) {
this(field);
if (property == null) {
throw new IllegalArgumentException("The property must be set");
}
this.property = property;
}
/*
* Default validation continues.
* @see dk.bregnvig.formula1.client.validation.Rule#supendValidation()
*/
public boolean supendValidation() {
return false;
}
protected Widget getField() {
return field;
}
protected Label getLabelProperty() {
return labelProperty;
}
protected String getProperty() {
return property;
}
protected List<Issue> getIssue() {
String issueText = getErrorMessage().replaceAll("\\{0\\}", getProperty());
Issue issue = new Issue(field, issueText, labelProperty, property);
List<Issue> issues = new ArrayList<Issue>(1);
issues.add(issue);
return issues;
}
public Set<Widget> getFields() {
Set<Widget> fields = new HashSet<Widget>(2);
fields.add(field);
return fields;
}
protected abstract String getErrorMessage();
}
| true
|
e78a84851e2911c3850dcb4130bbff43ce8f9d28
|
Java
|
horaceking/GuiMi
|
/src/com/guimi/Tab2Fragment.java
|
UTF-8
| 14,732
| 1.78125
| 2
|
[] |
no_license
|
package com.guimi;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.guimi.entities.Item;
import com.guimi.myadapters.TypeButtonAdapter;
import com.guimi.myviews.HorizontalListView;
import com.guimi.myviews.MyDrawerLayout;
import com.guimi.sqlite.GuiMiDB;
import com.guimi.util.DensityUtil;
import com.guimi.util.LocalAsyncImageLoader;
import com.guimi.util.LocalAsyncImageLoader.ImageCallback;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ViewSwitcher.ViewFactory;
public class Tab2Fragment extends Fragment implements ViewFactory {
private MyDrawerLayout mDrawer;
private HorizontalListView list;
private ImageSwitcher clothesSwitcher;
private Gallery coatDallery;
// private List<Item>
private GuiMiDB dbOperation;
private GridView bookShelf;
private View movingView;
private List<Item> singleItems=null;
private RadioGroup group;
private LinearLayout loadBar;
private Handler UIhandler;
private LocalAsyncImageLoader imageLoader;
boolean[] checkFlag = {true,true,true,true,true,true};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2_fragment, container, false);
// 初始化数据库
dbOperation = GuiMiDB.getInstance(getActivity());
singleItems = new ArrayList<Item>();
//albumHelper = AlbumHelper.getHelper();
// 数据库获取所有单品
loadBar = (LinearLayout) view.findViewById(R.id.load_status);
loadBar.setVisibility(View.VISIBLE);
// 初始化抽屉
mDrawer = (MyDrawerLayout) view.findViewById(R.id.mydrawer);
mDrawer.initDrawer();
// generate the list of type buttons
list = (HorizontalListView) view.findViewById(R.id.type_buttons);
list.setAdapter(new TypeButtonAdapter(list, view.getContext()));
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int pos,
long arg3) {
// TODO Auto-generated method stub
((TypeButtonAdapter) list.getAdapter()).turn(pos);
int lastPos = -1;
for(int i = 0; i < checkFlag.length; i++){
if (!checkFlag[i]) {
lastPos = i;
break;
}
}
checkFlag[pos]= !checkFlag[pos];
if(lastPos == pos){
pos = -1;
}else if(lastPos != -1){
((TypeButtonAdapter) list.getAdapter()).turn(lastPos);
checkFlag[lastPos]= !checkFlag[lastPos];
}
switch (pos) {
case 0:
singleItems = (dbOperation.getItemsByType(3));
break;
case 1:
singleItems = dbOperation.getItemsByType(5);
break;
case 2:
singleItems = dbOperation.getItemsByType(1);
break;
case 3:
singleItems = dbOperation.getItemsByType(4);
break;
case 4:
singleItems = dbOperation.getItemsByType(0);
break;
case 5:
singleItems = dbOperation.getItemsByType(2);
break;
default:
singleItems = dbOperation.getItems();
break;
}
((ShlefAdapter)(bookShelf.getAdapter())).notifyDataSetChanged();
coatDallery.getOnItemSelectedListener().onItemSelected(coatDallery, null, 0, 0);
((ImageAdapter)(coatDallery.getAdapter())).notifyDataSetChanged();
}
});
// 初始化列表模式及轮播模式
bookShelf = (GridView) view.findViewById(R.id.clothingShelf);
clothesSwitcher = (ImageSwitcher) view.findViewById(R.id.switcher);
coatDallery = (Gallery) view.findViewById(R.id.coat_gallery);
movingView = view.findViewById(R.id.movingView);
initViewByList();
initViewByMoving();
group = (RadioGroup) view.findViewById(R.id.view_ways);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int radioButtonId = group.getCheckedRadioButtonId();
if (radioButtonId == R.id.mode_list) {
//initViewByList();
movingView.setVisibility(View.GONE);
bookShelf.setVisibility(
View.VISIBLE);
} else {
//initViewByMoving();
bookShelf.setVisibility(
View.GONE);
movingView.setVisibility(
View.VISIBLE);
}
}
});
imageLoader = new LocalAsyncImageLoader();
UIhandler = new Handler(){
@Override
public void dispatchMessage(Message msg) {
// TODO Auto-generated method stub
if(singleItems==null||singleItems.size() == 0){
// Toast toast = Toast.makeText(getActivity(),
// "您的衣柜暂无单品,赶快去添加吧!^^", Toast.LENGTH_SHORT);
// toast.show();
}else{
((ShlefAdapter)(bookShelf.getAdapter())).notifyDataSetChanged();
((ImageAdapter)(coatDallery.getAdapter())).notifyDataSetChanged();
loadBar.setVisibility(View.GONE);
}
}
};
// Thread loadData = new Thread(new Runnable(){
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// try {
// singleItems = dbOperation.getItems();
// } catch (Exception e) {
// e.printStackTrace();
// }
// UIhandler.sendMessage(UIhandler.obtainMessage());
//
// }
//
// });
// loadData.start();
int viewId = group.getCheckedRadioButtonId();
if(viewId == R.id.mode_list){
movingView.setVisibility(View.GONE);
bookShelf.setVisibility(
View.VISIBLE);
}
else{
bookShelf.setVisibility(View.GONE);
movingView.setVisibility(
View.VISIBLE);
}
return view;
}
public void initViewByMoving() {
// this.getActivity().setContentView(R.layout.tab2_fragment_moving);
clothesSwitcher.setFactory(this);
clothesSwitcher.setInAnimation(AnimationUtils.loadAnimation(
this.getActivity(), android.R.anim.fade_in));
clothesSwitcher.setOutAnimation(AnimationUtils.loadAnimation(
this.getActivity(), android.R.anim.fade_out));
//coatDallery.setUnselectedAlpha(0.3f);
coatDallery.setAdapter(new ImageAdapter(this.getActivity()));
coatDallery.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (singleItems != null&&singleItems.size() != 0) {
String url = singleItems.get(position).getItemUrl();
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(url, options);
options.inSampleSize = LocalAsyncImageLoader
.computeSampleSize(options, -1, 512 * 512);
options.inJustDecodeBounds = false;
Bitmap singleBitmap = BitmapFactory
.decodeFile(url, options);
Drawable drawable = new BitmapDrawable(singleBitmap);
clothesSwitcher.setImageDrawable(drawable);
clothesSwitcher.setTag(position);
}else{
clothesSwitcher.setImageResource(android.R.color.transparent);
clothesSwitcher.setTag(-1);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
clothesSwitcher.setImageResource(R.drawable.null_image_icon);
clothesSwitcher.setTag(-1);
}
});
clothesSwitcher.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
int pos = (Integer) clothesSwitcher.getTag();
if (pos >= 0) {
Item item = singleItems.get(pos);
Intent itemIntent = new Intent(getActivity(),
ShowItemInfoActivity.class);
itemIntent.putExtra("item", item);
startActivity(itemIntent);
}
}
});
}
public void initViewByList() {
ShlefAdapter adapter = new ShlefAdapter();
bookShelf.setAdapter(adapter);
bookShelf.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Item item = singleItems.get(pos);
Intent itemIntent = new Intent(getActivity(), ShowItemInfoActivity.class);
itemIntent.putExtra("item", item);
startActivity(itemIntent);
}
});
}
@Override
public View makeView() {
ImageView i = new ImageView(this.getActivity());
//???????????
i.setBackgroundColor(0xFFFFFF);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return i;
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
if (singleItems == null) {
return 0;
} else {
return singleItems.size();
}
}
public Object getItem(int position) {
return singleItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image = null;
if(convertView == null){
convertView = new LinearLayout(mContext);
convertView.setTag("container"+position);
image = new ImageView(mContext);
image.setTag(position);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(150,LayoutParams.MATCH_PARENT);
lp.setMargins(5, 5, 5, 5);
image.setLayoutParams(lp);
image.setAdjustViewBounds(true);
image.setScaleType(ScaleType.FIT_CENTER);
((LinearLayout)convertView).addView(image);
convertView.setBackgroundResource(R.drawable.select_image_bg);
}else{
image = (ImageView) convertView.findViewWithTag(position);
}
//Uri singleUri = Uri.parse(singleItems.get(position).getItemUrl());
image.setTag(position);
Drawable drawable = imageLoader.loadDrawable(position, singleItems.get(position).getItemUrl(),
new ImageCallback() {
@Override
public void imageLoaded(Drawable imageDrawable, int pos) {
// TODO Auto-generated method stub
ImageView image = null;
try {
image = (ImageView) coatDallery.findViewWithTag(pos);
} catch (Exception e) {
}
if(image != null ){
image.setImageDrawable(imageDrawable);
}
}
});
if(drawable == null ){
image.setImageResource(R.drawable.null_image_icon);
}else{
image.setImageDrawable(drawable);
}
return convertView;
}
private Context mContext;
}
class ShlefAdapter extends BaseAdapter {
@Override
public int getCount() {
if (singleItems == null) {
return 0;
} else {
return singleItems.size();
}
}
@Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return singleItems.get(pos);
}
@Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
return pos;
}
@Override
public View getView(int position, View contentView, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView image = null;
if (contentView == null) {
contentView = LayoutInflater.from(
getActivity().getApplicationContext()).inflate(
R.layout.item1, null);
image = (ImageView) contentView
.findViewById(R.id.clothesView);
image.setBackgroundResource(R.drawable.shelf_bg);
image.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, DensityUtil.dip2px(
getActivity(), 150)));
}else{
image = (ImageView) contentView
.findViewById(R.id.clothesView);
}
image.setTag(position);
Drawable drawable = imageLoader.loadDrawable(position, singleItems.get(position).getItemUrl(),
new ImageCallback() {
@Override
public void imageLoaded(Drawable imageDrawable, int pos) {
// TODO Auto-generated method stub
ImageView image = null;
try {
image = (ImageView) bookShelf.findViewWithTag(pos);
} catch (Exception e) {
}
if(image != null ){
image.setImageDrawable(imageDrawable);
}
}
});
if(drawable == null ){
image.setImageResource(R.drawable.null_image_icon);
}else{
image.setImageDrawable(drawable);
}
return contentView;
}
}
@Override
public void onResume() {
// TODO Auto-generated method stub
int lastPos = -1;
for(int i = 0; i < checkFlag.length; i++){
if (!checkFlag[i]) {
lastPos = i;
break;
}
}
switch (lastPos) {
case 0:
singleItems = (dbOperation.getItemsByType(3));
break;
case 1:
singleItems = dbOperation.getItemsByType(5);
break;
case 2:
singleItems = dbOperation.getItemsByType(1);
break;
case 3:
singleItems = dbOperation.getItemsByType(4);
break;
case 4:
singleItems = dbOperation.getItemsByType(0);
break;
case 5:
singleItems = dbOperation.getItemsByType(2);
break;
default:
singleItems = dbOperation.getItems();
break;
}
((ShlefAdapter)(bookShelf.getAdapter())).notifyDataSetChanged();
coatDallery.getOnItemSelectedListener().onItemSelected(coatDallery, null, 0, 0);
((ImageAdapter)(coatDallery.getAdapter())).notifyDataSetChanged();
loadBar.setVisibility(View.GONE);
super.onResume();
}
}
| true
|
59dbf8d5d2a60b598e5c95c7d972f679656b43cf
|
Java
|
dmendelsohn/6.005
|
/final-proj/src/shared/Pair.java
|
UTF-8
| 794
| 3.640625
| 4
|
[] |
no_license
|
package shared;
/**
* A Pair is a grouping of two Objects.
*/
public class Pair<U, V> {
private final U first;
private final V second;
/**
* Creates a Pair with first object
* U and second object V.
* @param first The pair's first object.
* @param second The pair's second object.
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
/**
* Package-protected access to a Pair's first object.
* @return The pair's first object.
*/
protected U getFirst() {
return first;
}
/**
* Package-protected access a Pair's second object.
* @return The pair's second object.
*/
protected V getSecond() {
return second;
}
}
| true
|
5cbe97d65c05302103d318a0cec3255276dd202e
|
Java
|
JumperYu/bradypod
|
/bradypod.shop/shop.search/shop.search.impl/src/main/java/com/bradypod/search/lucene/service/ItemIndexService.java
|
UTF-8
| 6,670
| 2.328125
| 2
|
[] |
no_license
|
package com.bradypod.search.lucene.service;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queries.mlt.MoreLikeThisQuery;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.SortField.Type;
import org.apache.lucene.search.TopDocs;
import bradypod.framework.lucene.LuceneCallback;
import bradypod.framework.lucene.LuceneManager;
import com.bradypod.bean.bo.PageData;
import com.bradypod.search.lucene.bo.ItemIndex;
import com.bradypod.shop.item.center.po.ItemInfo;
import com.bradypod.util.array.ArrayUtil;
/**
* 索引服务
*
* @author zengxm<http://github.com/JumperYu>
*
* @date 2015年12月28日 下午5:28:47
*/
public class ItemIndexService {
private LuceneManager luceneManager;
public ItemIndexService() {
luceneManager = new LuceneManager(INDEX_PATH);
}
/**
* 创建索引
*
* @param itemIndex
* @throws IOException
*/
public void createIndex(ItemIndex itemIndex) {
IndexWriter writer = luceneManager.getWriter();
Document document = new Document();
document.add(new LongField("id", itemIndex.getId(), Field.Store.YES));
document.add(new LongField("ctgId", itemIndex.getCtgId(),
Field.Store.YES));
document.add(new TextField("title", itemIndex.getTitle(),
Field.Store.YES));
// 只做评分和排序
document.add(new NumericDocValuesField("createTime", itemIndex
.getCreateTime().getTime()));
// 添加并且提交
try {
writer.addDocument(document);
writer.commit();
} catch (IOException e) {
}
}
/**
* 搜索索引
*
* @param itemIndex
*/
public PageData<ItemInfo> searchIndex(ItemIndex itemIndex) {
PageData<ItemInfo> pageData = new PageData<ItemInfo>();
String queryField = "title";
Analyzer analyzer = luceneManager.getAnalyzer();
QueryParser queryParser = new QueryParser(queryField, analyzer);
try {
TokenStream ts = analyzer.tokenStream("", new StringReader(
itemIndex.getTitle()));
ts.reset(); // required set to begin
CharTermAttribute cta = ts.addAttribute(CharTermAttribute.class);
Set<String> words = new HashSet<String>();
while (ts.incrementToken()) {
words.add("+" + cta.toString());
}
String queryValue = ArrayUtil.join(words, " ");
ts.end(); // required set to final
ts.close();
Query query = queryParser.parse(queryValue);
// 排序true正序, false和默认是倒序
Sort sort = new Sort();
sort.setSort(new SortField(itemIndex.getSortField(), Type.LONG,
itemIndex.isDescending()));
// 内部获取search对象进行实时查询
luceneManager.search(new LuceneCallback<Void>() {
@Override
public Void executeQuery(IndexSearcher searcher) {
TopDocs results;
try {
results = searcher.search(
query,
itemIndex.getPageSize() * itemIndex.getPageNO(),
sort);
ScoreDoc[] scores = results.scoreDocs;// 这里是全部的集合
int begin = itemIndex.getPageSize()
* (itemIndex.getPageNO() - 1);
int end = Math.min(begin + itemIndex.getPageSize(),
scores.length);
pageData.setPageSize(itemIndex.getPageSize());
pageData.setTotalNum(results.totalHits);
List<ItemInfo> itemInfos = new ArrayList<ItemInfo>();
for (int i = begin; i < end; i++) {
// output
Document doc = searcher.doc(scores[i].doc);
ItemInfo itemInfo = new ItemInfo();
itemInfo.setId(Long.parseLong(doc.get("id")));
itemInfo.setTitle(doc.get("title"));
itemInfos.add(itemInfo);
}// --> end for
pageData.setList(itemInfos);
} catch (IOException e) {
}
return null;
}
});
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pageData;
}
public void moreLikeThis(String title) {
String[] moreLikeFields = { "title" }; // { "Name" ,"Info"};
MoreLikeThisQuery query = new MoreLikeThisQuery(title, moreLikeFields,
luceneManager.getAnalyzer(), "title");
// 设置停用词
// query.setStopWords(getStopWords(reader));
// 最少的词频
// Sets the frequency below which terms will be ignored in the source
// doc.
query.setMinTermFrequency(1);
// 最多的查询词数目
// Sets the maximum number of query terms that will be included in any
// generated query.
query.setMaxQueryTerms(5);
// 词至少在这么多篇文档中出现
// Ignore words which do not occur in at least this many docs.
// DEFAULT_MIN_DOC_FREQ = 5
query.setMinDocFreq(1);
System.out.println("搜索条件:" + query.toString());
long start = System.currentTimeMillis();
luceneManager.search(new LuceneCallback<Void>() {
@Override
public Void executeQuery(IndexSearcher searcher) {
try {
TopDocs tDocs = searcher.search(query, 10);
ScoreDoc sDocs[] = tDocs.scoreDocs;
int len = sDocs.length;
for (int i = 0; i < len; i++) {
ScoreDoc tScore = sDocs[i];
// 从Lucene3.0开始已经不能通过 tScore.score 这样来得到些文档的得分了
int docId = tScore.doc;
Explanation exp = searcher.explain(query, docId);
Document tDoc = searcher.doc(docId);
String title = tDoc.get("title");
float score = exp.getValue();
// System.out.println(exp.toString());
// //如果需要打印文档得分的详细信息则可以通过此方法
System.out.println("DocId:" + docId + "\tScore:"
+ score + "\ttitle:" + title);
}
} catch (Exception e) {
}
return null;
}
});
Long end = System.currentTimeMillis();
System.out.println("搜索用时:" + (end - start) + "ms");
}
// close
public void close() {
luceneManager.closeWriter();
}
private static final String INDEX_PATH = "E://index";
}
| true
|
eac667c2647714c57bb9f0ba5edaea0815e209d6
|
Java
|
itarocha/betesda
|
/src/main/java/br/com/itarocha/betesda/controller/TipoServicoController.java
|
UTF-8
| 2,328
| 2.46875
| 2
|
[] |
no_license
|
package br.com.itarocha.betesda.controller;
import br.com.itarocha.betesda.model.TipoServico;
import br.com.itarocha.betesda.service.TipoServicoService;
import br.com.itarocha.betesda.util.validation.ItaValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/app/tipo_servico")
public class TipoServicoController {
@Autowired
private TipoServicoService service;
@RequestMapping
@PreAuthorize("hasAnyRole('USER','ADMIN','ROOT')")
public ResponseEntity<?> listar() {
List<TipoServico> lista = service.findAll();
return new ResponseEntity<List<TipoServico>>(lista, HttpStatus.OK);
}
@RequestMapping(value="{id}")
@PreAuthorize("hasAnyRole('ADMIN','ROOT')")
public ResponseEntity<?> getById(@PathVariable("id") Long id) {
try {
TipoServico model = service.find(id);
if (model != null) {
return new ResponseEntity<>(model, HttpStatus.OK);
} else {
return new ResponseEntity<>("Tipo de SErviço não existe", HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ADMIN','ROOT')")
public ResponseEntity<?> gravar(@RequestBody TipoServico model) {
ItaValidator<TipoServico> v = new ItaValidator<TipoServico>(model);
v.validate();
if (!v.hasErrors() ) {
return new ResponseEntity<>(v.getErrors(), HttpStatus.BAD_REQUEST);
}
try {
TipoServico saved = null;
saved = service.create(model);
return new ResponseEntity<TipoServico>(saved, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value="{id}", method = RequestMethod.DELETE)
@PreAuthorize("hasAnyRole('ADMIN','ROOT')")
public ResponseEntity<?> excluir(@PathVariable("id") Long id) {
try {
service.remove(id);
return new ResponseEntity<String>("sucesso", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| true
|
17cf7f2b3f8dd2f11832cb5bf377e09f3240ad0c
|
Java
|
saikumarsuvanam/CodingProblems
|
/CareerCup:Google/anonymous/sum_of_all_weights_of_each_path_between_two_node_in_undirected_non_cyclic_graph.java
|
UTF-8
| 3,579
| 3.8125
| 4
|
[] |
no_license
|
/* google-interview-questions
Given a undirected graph with weights, return the sum of the weight of each path between two nodes
(shortest path between two vertices). Assume there are no cycles.
Example:
Input:
A
| 1
B
2 / \ 3
C D
Output:
18
since
A to B has weight 1
A to C has weight 3
A to D has weight 4
B to C has weight 2
B to D has weight 3
C to D has weight 5
Edit: Thanks, wangchenClark0512, forgot about C to D
Edit2: @Lukas, The question is just the sum of the shortest paths between two vertices.
Also, all edges are positive.
Edit3: Assume the graph has no cycles, did not get to the follow-up,
but follow-up probably is probably change your algorithm so that is works for cycles
The problem can be solved in O(n) time where n is the number of nodes.
Since the graph has no cycle, an edge e divides the graph into two sub graphs.
For any path between the two graphs, the edge is always used exactly once.
And there are (n1 * n2) number of possible paths between the sub-graphs (n1 is the number of nodes in
sub-graph 1 and n2 is the number of the nodes in sub-graph 2).
Therefore, the amount of value that the edge contributes to the final sum is 'w * n1 * n2,
where w is the weight of the edge.
So, we basically calculate w * n1 * n2 for all edges and sum them up.
Then how do we calculate n1 and n2? It is obvious that n1 + n2 = n, where n is the number of all
nodes in the graph. So we need to only calculate either n1 or n2.
At this point, let's treat the graph as a tree by taking an arbitrary node as root.
Note that this possible since the graph does not have any cycle.
Then, we can solve the problem by traversing the tree and sum up (w * size of a sub-tree * (n - size of a sub-tree) when visiting a node.
*/
import java.util.*;
public class sum_of_all_weights_of_each_path_between_two_node_in_undirected_non_cyclic_graph {
class nTree{
int weights;
List<nTree> children;
int size;
nTree (int data){
this.weights=data;
this.children=new ArrayList<nTree>();
}
}
/*
E F
4 \ / 5
A
1 |
B
2 / \ 3
C D
Answer is 1*3*3 + 2*1*5 + 3*1*5 + 4*1*5 + 5*1*5 = 79
*/
public static void main(String[] args){
sum_of_all_weights_of_each_path_between_two_node_in_undirected_non_cyclic_graph t=new sum_of_all_weights_of_each_path_between_two_node_in_undirected_non_cyclic_graph();
//lets start with A node in the above graph
nTree p=t.new nTree(0);//A
p.children.add(t.new nTree(1));//B
p.children.add(t.new nTree(4));//E
p.children.add(t.new nTree(5));//F
p.children.get(0).children.add(t.new nTree(3));//D
p.children.get(0).children.add(t.new nTree(2));//C
int totalnodes=6;//we can program this also
result r=t. new result(); //Instead of using static here i am using a result class
find_sum_of_all_weights(p,totalnodes,r);
System.out.println(r.sum);
}
class result{
int sum=0;
}
static int find_sum_of_all_weights(nTree p,int totalnodes,result r){
int size = 1;
if(p.children.size()==0){
return size;
}
else{
for(int i=0; i<p.children.size(); i++){
int s=find_sum_of_all_weights(p.children.get(i), totalnodes,r);
r.sum=r.sum+p.children.get(i).weights*s*(totalnodes-s);
size=size+s;
}
return size;
}
}
}
| true
|
83ecd07d99170b8d2cf631035656e478b55f7709
|
Java
|
dustclear/workorder_prj
|
/workorder_project/src/com/wos/dao/mapper/EmployeeMapper.java
|
UTF-8
| 1,597
| 1.890625
| 2
|
[] |
no_license
|
package com.wos.dao.mapper;
import com.wos.pojo.Employee;
public interface EmployeeMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
int deleteByPrimaryKey(String cguid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
int insert(Employee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
int insertSelective(Employee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
Employee selectByPrimaryKey(String cguid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
int updateByPrimaryKeySelective(Employee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table dbo.cm_employee
*
* @mbggenerated Sun Jan 04 16:50:19 CST 2015
*/
int updateByPrimaryKey(Employee record);
}
| true
|
cd9b68c1d3afe5b04546f6a30678f237dd80236e
|
Java
|
Donwaztok/Rei-Leao
|
/src/reileao/Mobs/Hyena.java
|
UTF-8
| 5,592
| 2.625
| 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 reileao.Mobs;
import java.awt.Image;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import reileao.Sounds;
/**
*
* @author igord
*/
public class Hyena {
private BufferedImage[] moving,turning,dying;
private int frame,cframe,sx,x,y,mov=300;
private String state="Moving";
private boolean front=true,gameOver=false,alive=true;
public Hyena() throws IOException{
moving = new BufferedImage[11];
turning = new BufferedImage[11];
dying = new BufferedImage[10];
BufferedImage Sprite;
Sprite = ImageIO.read(new File("Data/Texture/hyena.png"));
for(int i=0; i<11; i++) moving [i]=Sprite.getSubimage(i*142, 0, 142, 108);
for(int i=0; i<11; i++) turning[i]=Sprite.getSubimage(i*142, 108, 142, 102);
for(int i=0; i<10; i++) dying [i]=Sprite.getSubimage(i*172, 210, 172, 126);
this.x = 2900;
this.y = 665;
this.sx= 2600;
}
public Image getImage(){
if(gameOver){
if(front) return dying[9]; else {
//Invert Image
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-dying[9].getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage a = op.filter(dying[9], null);
return a;
}
}
//Bugs
if(this.frame<0)this.frame=0;
//Moving
if(state.equals("Moving")){
if(frame>moving.length-1)frame=0;
if(front) return moving[frame]; else {
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-moving[frame].getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage a = op.filter(moving[frame], null);
return a;
}
}
//Dying
if(this.state.equals("Dying")){
if(frame>dying.length-1){
if(!gameOver){
gameOver=true;
JOptionPane.showMessageDialog(null, "You won!!");
System.exit(0);
}
}
if(front) return dying[frame]; else {
//Invert Image
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-dying[frame].getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage a = op.filter(dying[frame], null);
return a;
}
}
//Turning
if(state.equals("Turning")){
if(frame>=turning.length-1){
this.state="Moving";
if(this.front) this.x+=1; else this.x-=1;
}
if(!front) return turning[frame]; else {
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-turning[frame].getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage a = op.filter(turning[frame], null);
return a;
}
}
else return moving[0];
}
public void move(){
if(!this.state.equals("Dying")){
String a = this.state;
if(this.x<sx+mov-1 && this.x>this.sx) this.state="Moving";
else if(this.x==sx+mov && !this.state.equals("Turning")){
this.state="Turning";
this.front=false;
}
else if(this.x==this.sx){
this.state="Turning";
this.front=true;
}
stateChange(a);
if(!this.state.equals("Turning")){
if(this.front) this.x+=1; else this.x-=1;
}
}
this.nextFrame();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x=x;
}
public void setY(int y) {
this.y=y;
}
public boolean isAlive(){
return this.alive;
}
public String isOver(Point p){
if(p.x>this.x && p.x<this.x+moving[0].getWidth()){
if(p.y<=this.y && p.y>=this.y-(moving[0].getHeight()/2)) return "Down";
else if(p.y<=this.y-(moving[0].getHeight()/2) && p.y>=this.y-moving[0].getHeight()) return "Up";
}
return "No";
}
public void nextFrame(){
this.cframe++;
if(this.cframe>2 && !this.state.equals("Dying")){
this.cframe=0;
this.frame++;
}
if(this.cframe>10 && this.state.equals("Dying")){
this.cframe=0;
this.frame++;
}
}
public void die() throws Exception{
this.alive=false;
Sounds.hyenaSound();
this.state="Dying";
this.frame=-1;
}
public void stateChange(String s){
if(!this.state.equals(s))frame=-1;
}
}
| true
|
d6ceb434aa61edce1fe7209b09d0706024283d64
|
Java
|
hzr958/myProjects
|
/scmv6/center-task1/src/main/java/com/smate/center/task/psn/model/PsnScoreDetail.java
|
UTF-8
| 1,641
| 2.03125
| 2
|
[] |
no_license
|
package com.smate.center.task.psn.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* 人员信息完整度计分详情.
*
* @author chenxiangrong
*
*/
@Entity
@Table(name = "PSN_SCORE_DETAIL")
public class PsnScoreDetail implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7376133624100968600L;
private Long id;
private Long psnId;
private int typeId;
private String typeValue;
private int scoreNum;
@Id
@Column(name = "ID")
@SequenceGenerator(name = "SEQ_STORE", sequenceName = "SEQ_PSN_SCORE_DETAIL", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "PSN_ID")
public Long getPsnId() {
return psnId;
}
public void setPsnId(Long psnId) {
this.psnId = psnId;
}
@Column(name = "TYPE_ID")
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
@Column(name = "TYPE_VALUE")
public String getTypeValue() {
return typeValue;
}
public void setTypeValue(String typeValue) {
this.typeValue = typeValue;
}
@Column(name = "SCORE_NUM")
public int getScoreNum() {
return scoreNum;
}
public void setScoreNum(int scoreNum) {
this.scoreNum = scoreNum;
}
}
| true
|
e5bb713fd0ca37f425533a04fd4b1e7e7a85db17
|
Java
|
alileohe/jingwei-all
|
/jingwei-common/src/test/java/com/taobao/jingwei/common/node/tasks/SyncTaskNodeTest.java
|
UTF-8
| 1,295
| 2.15625
| 2
|
[] |
no_license
|
package com.taobao.jingwei.common.node.tasks;
import com.taobao.jingwei.common.node.tasks.SyncTaskNode.GroupingSetting;
import org.json.JSONException;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @desc
*
* @author ˷�� <a href="mailto:shuohai.lhl@taobao.com"> shuohailhl</a>
*
* @date Aug 24, 2012 9:18:15 AM
*/
public class SyncTaskNodeTest {
// test extractor grouping setting
@Test
@Ignore
public void testGrouping() {
SyncTaskNode node = new SyncTaskNode();
List<GroupingSetting> groupingSettings = new ArrayList<GroupingSetting>();
List<String> fileds = new ArrayList<String>();
fileds.add("field");
for (int i = 0; i < 3; i++) {
GroupingSetting setting = new GroupingSetting();
setting.setSchemaReg("schema");
setting.setTableReg("table");
groupingSettings.add(setting);
}
node.setGroupingSettings(groupingSettings);
SyncTaskNode other = new SyncTaskNode();
try {
String jsonStr = node.toJSONString();
other.jsonStringToNodeSelf(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
assertEquals(other.getGroupingSettings().size(), 3);
assertEquals(other.getGroupingSettings().get(0).getFields(), "field");
}
}
| true
|
562913028055c5559491046d03d2244732419fee
|
Java
|
kabrick/android_proof_of_concept
|
/app/src/main/java/com/website/health/adapters/PatientVitalsAdapter.java
|
UTF-8
| 2,161
| 2.203125
| 2
|
[] |
no_license
|
package com.website.health.adapters;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkError;
import com.android.volley.TimeoutError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import com.website.health.R;
import com.website.health.helpers.DataRouter;
import com.website.health.helpers.HelperFunctions;
import com.website.health.models.PatientVitals;
import com.website.health.patients.ViewPatientVitalsActivity;
public class PatientVitalsAdapter extends RecyclerView.Adapter<PatientVitalsAdapter.MyViewHolder> {
private List<PatientVitals> vitalsList;
class MyViewHolder extends RecyclerView.ViewHolder {
TextView vitals_hr, vitals_rr, vitals_temp;
MyViewHolder(View view) {
super(view);
vitals_hr = view.findViewById(R.id.vitals_hr);
vitals_rr = view.findViewById(R.id.vitals_rr);
vitals_temp = view.findViewById(R.id.vitals_temp);
}
}
public PatientVitalsAdapter(List<PatientVitals> vitalsList) {
this.vitalsList = vitalsList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_item_vitals, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
final PatientVitals vital = vitalsList.get(position);
holder.vitals_hr.setText(vital.getHeartRate());
holder.vitals_rr.setText(vital.getRespRate());
holder.vitals_temp.setText(vital.getTemp());
}
@Override
public int getItemCount() {
return vitalsList.size();
}
}
| true
|
2f3909e27f359e3868c9e8c0563cc36cdc8ad60b
|
Java
|
alexly25/RP
|
/src/com/alex/RP/statistic/GroupActivity.java
|
UTF-8
| 1,391
| 2.015625
| 2
|
[] |
no_license
|
package com.alex.rp.statistic;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import com.alex.rp.MyString;
import com.alex.rp.R;
import com.alex.rp.db.Vars;
import com.alex.rp.group.Group;
import com.alex.rp.semester.Semester;
import com.alex.rp.tables.GroupTable;
import com.alex.rp.tables.Table;
import java.util.Date;
/**
* Created by alex on 08.06.2014.
*/
public class GroupActivity extends ActionBarActivity {
private final static String LOG = "GroupActivity";
private TableLayout tl;
private Date date;
private Table table;
private Semester semester;
private Group group;
public void onCreate(Bundle savedInstanceState) {
Log.d(LOG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.week);
semester = (Semester) getIntent().getSerializableExtra(Vars.FIELD_SEMESTER);
group = (Group) getIntent().getSerializableExtra(Vars.FIELD_GROUP);
tl = (TableLayout) findViewById(R.id.tl_week);
tl.setStretchAllColumns(true);
tl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
table = new GroupTable(this, tl, semester);
}
}
| true
|
fe670b30f286a7f57d0a2d7dfdf5555a9d1d315e
|
Java
|
ashishb888/spring-boot-2.3-poc
|
/dates-timestamp-in-database/src/main/java/poc/springboot/DatesTimestampInDatabaseApplication.java
|
UTF-8
| 1,673
| 2.421875
| 2
|
[] |
no_license
|
package poc.springboot;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import lombok.extern.slf4j.Slf4j;
import poc.springboot.domain.Employee;
import poc.springboot.repos.EmployeeRepository;
@Slf4j
@SpringBootApplication
public class DatesTimestampInDatabaseApplication {
@Autowired
private EmployeeRepository er;
public static void main(String[] args) {
SpringApplication.run(DatesTimestampInDatabaseApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ac) {
return args -> {
log.debug("commandLineRunner sevice");
DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
long millis = System.currentTimeMillis();
er.save(new Employee(1, "A", new Date(millis), new Timestamp(millis)));
er.save(new Employee(2, "B", new Date(millis), new Timestamp(millis)));
er.save(new Employee(3, "C", new Date(millis), new Timestamp(millis)));
er.save(new Employee(4, "C", new Date(millis), Timestamp.valueOf(timestampFormatter
.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault())))));
er.findAll().forEach(e -> {
log.debug("e: " + e);
});
};
}
}
| true
|
8b5cfbb246776a7c4289e6d793e73bad0f99accd
|
Java
|
McLeodMoores/starling
|
/projects/analytics/src/test/java/com/opengamma/analytics/financial/provider/curve/directforward/UsdDirectForward3mLiborTest.java
|
UTF-8
| 17,692
| 1.515625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.provider.curve.directforward;
import static com.opengamma.analytics.financial.provider.curve.CurveBuildingTestUtils.assertFiniteDifferenceSensitivities;
import static com.opengamma.analytics.financial.provider.curve.CurveBuildingTestUtils.assertNoSensitivities;
import static com.opengamma.analytics.financial.provider.curve.CurveBuildingTestUtils.curveConstructionTest;
import static org.testng.Assert.assertEquals;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.annotations.Test;
import org.threeten.bp.Period;
import org.threeten.bp.ZonedDateTime;
import com.mcleodmoores.analytics.financial.curve.interestrate.curvebuilder.DirectForwardMethodCurveBuilder;
import com.mcleodmoores.analytics.financial.curve.interestrate.curvebuilder.DirectForwardMethodCurveSetUp;
import com.mcleodmoores.analytics.financial.index.Index;
import com.mcleodmoores.date.CalendarAdapter;
import com.mcleodmoores.date.WeekendWorkingDayCalendar;
import com.mcleodmoores.date.WorkingDayCalendar;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.index.GeneratorAttributeIR;
import com.opengamma.analytics.financial.instrument.index.GeneratorDepositIbor;
import com.opengamma.analytics.financial.instrument.index.GeneratorDepositON;
import com.opengamma.analytics.financial.instrument.index.GeneratorInstrument;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIbor;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIborMaster;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedON;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedONMaster;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.index.IndexON;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlock;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingTests;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderForward;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.interpolation.factory.FlatExtrapolator1dAdapter;
import com.opengamma.analytics.math.interpolation.factory.LinearInterpolator1dAdapter;
import com.opengamma.analytics.math.interpolation.factory.NamedInterpolator1dFactory;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.timeseries.precise.zdt.ImmutableZonedDateTimeDoubleTimeSeries;
import com.opengamma.timeseries.precise.zdt.ZonedDateTimeDoubleTimeSeries;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
import com.opengamma.util.tuple.Pair;
/**
* Builds and tests discounting and 3m USD LIBOR curves, with the LIBOR curve using forward rates directly rather than pseudo discount factors. The discounting
* curve is built first and then used when constructing the LIBOR curve. This means that the LIBOR curve has sensitivities to both discounting and LIBOR market
* data, but the discounting curve only has sensitivities to the discounting curve.
* <p>
* The discounting curve contains the overnight deposit rate and OIS swaps. The LIBOR curve contains the 3m LIBOR rate and 3m LIBOR / 6m fixed swaps.
*/
@Test(groups = TestGroup.UNIT)
public class UsdDirectForward3mLiborTest extends CurveBuildingTests {
/** The interpolator used for both curves */
private static final Interpolator1D INTERPOLATOR = NamedInterpolator1dFactory.of(LinearInterpolator1dAdapter.NAME,
FlatExtrapolator1dAdapter.NAME);
/** A calendar containing only Saturday and Sunday holidays */
private static final WorkingDayCalendar NYC = WeekendWorkingDayCalendar.SATURDAY_SUNDAY;
/** The base FX matrix */
private static final FXMatrix FX_MATRIX = new FXMatrix(Currency.USD);
/** Generates OIS swaps for the discounting curve */
private static final GeneratorSwapFixedON GENERATOR_OIS_USD = GeneratorSwapFixedONMaster.getInstance().getGenerator("USD1YFEDFUND", NYC);
/** Fed funds index */
private static final IndexON FED_FUNDS_INDEX = GENERATOR_OIS_USD.getIndex();
/** Generates the overnight deposit */
private static final GeneratorDepositON GENERATOR_DEPOSIT_ON_USD = new GeneratorDepositON("USD Deposit ON", Currency.USD, NYC,
FED_FUNDS_INDEX.getDayCount());
/** Generates the 3m LIBOR / 6m fixed swaps */
private static final GeneratorSwapFixedIbor USD6MLIBOR3M = GeneratorSwapFixedIborMaster.getInstance().getGenerator("USD6MLIBOR3M", NYC);
/** 3m USD LIBOR index */
private static final IborIndex USD_3M_LIBOR_INDEX = USD6MLIBOR3M.getIborIndex();
/** Generates the 3m LIBOR instrument */
private static final GeneratorDepositIbor GENERATOR_USDLIBOR3M = new GeneratorDepositIbor("GENERATOR_USDLIBOR3M", USD_3M_LIBOR_INDEX,
NYC);
/** The curve construction date */
private static final ZonedDateTime NOW = DateUtils.getUTCDate(2011, 9, 28);
/** The previous day */
private static final ZonedDateTime PREVIOUS = NOW.minusDays(1);
/** Fed funds fixing series after today's fixing */
private static final ZonedDateTimeDoubleTimeSeries TS_ON_USD_WITH_TODAY = ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
new ZonedDateTime[] { PREVIOUS, NOW },
new double[] { 0.07, 0.08 });
/** Fed funds fixing series before today's fixing */
private static final ZonedDateTimeDoubleTimeSeries TS_ON_USD_WITHOUT_TODAY = ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
new ZonedDateTime[] { PREVIOUS },
new double[] { 0.07 });
/** 3m LIBOR fixing series after today's fixing */
private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_USD3M_WITH_TODAY = ImmutableZonedDateTimeDoubleTimeSeries
.ofUTC(new ZonedDateTime[] { PREVIOUS, NOW }, new double[] { 0.0035, 0.0036 });
/** 3m LIBOR fixing series before today's fixing */
private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_USD3M_WITHOUT_TODAY = ImmutableZonedDateTimeDoubleTimeSeries
.ofUTC(new ZonedDateTime[] { PREVIOUS }, new double[] { 0.0035 });
/** Fixing time series created before the valuation date fixing is available */
private static final Map<Index, ZonedDateTimeDoubleTimeSeries> FIXING_TS_WITHOUT_TODAY = new HashMap<>();
/** Fixing time series created after the valuation date fixing is available */
private static final Map<Index, ZonedDateTimeDoubleTimeSeries> FIXING_TS_WITH_TODAY = new HashMap<>();
static {
FIXING_TS_WITHOUT_TODAY.put(FED_FUNDS_INDEX, TS_ON_USD_WITHOUT_TODAY);
FIXING_TS_WITHOUT_TODAY.put(USD_3M_LIBOR_INDEX, TS_IBOR_USD3M_WITHOUT_TODAY);
FIXING_TS_WITH_TODAY.put(FED_FUNDS_INDEX, TS_ON_USD_WITH_TODAY);
FIXING_TS_WITH_TODAY.put(USD_3M_LIBOR_INDEX, TS_IBOR_USD3M_WITH_TODAY);
}
/** The discounting curve name */
private static final String CURVE_NAME_DSC_USD = "USD Dsc";
/** The LIBOR curve name */
private static final String CURVE_NAME_FWD3_USD = "USD Fwd 3M";
/** The curve builder */
private static final DirectForwardMethodCurveSetUp BUILDER_FOR_TEST = DirectForwardMethodCurveBuilder.setUp()
.buildingFirst(CURVE_NAME_DSC_USD)
.using(CURVE_NAME_DSC_USD).forDiscounting(Currency.USD).forIndex(FED_FUNDS_INDEX.toOvernightIndex()).withInterpolator(INTERPOLATOR)
.thenBuilding(CURVE_NAME_FWD3_USD)
.using(CURVE_NAME_FWD3_USD).forIndex(USD_3M_LIBOR_INDEX.toIborTypeIndex()).withInterpolator(INTERPOLATOR);
/** Market values for the discounting curve */
private static final double[] DSC_USD_MARKET_QUOTES = new double[] { 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400,
0.0400, 0.0400, 0.0400,
0.0400 };
/** Vanilla instrument generators for the discounting curve */
private static final GeneratorInstrument[] DSC_USD_GENERATORS = new GeneratorInstrument[] { GENERATOR_DEPOSIT_ON_USD, GENERATOR_OIS_USD,
GENERATOR_OIS_USD, GENERATOR_OIS_USD,
GENERATOR_OIS_USD, GENERATOR_OIS_USD, GENERATOR_OIS_USD, GENERATOR_OIS_USD, GENERATOR_OIS_USD, GENERATOR_OIS_USD,
GENERATOR_OIS_USD, GENERATOR_OIS_USD };
/** Attribute generators for the discounting curve */
private static final GeneratorAttributeIR[] DSC_USD_ATTR;
static {
final Period[] discountingTenors = new Period[] { Period.ofDays(0), Period.ofMonths(1), Period.ofMonths(2), Period.ofMonths(3),
Period.ofMonths(6),
Period.ofMonths(9), Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5),
Period.ofYears(10) };
DSC_USD_ATTR = new GeneratorAttributeIR[discountingTenors.length];
for (int i = 0; i < discountingTenors.length; i++) {
DSC_USD_ATTR[i] = new GeneratorAttributeIR(discountingTenors[i]);
BUILDER_FOR_TEST.addNode(CURVE_NAME_DSC_USD,
DSC_USD_GENERATORS[i].generateInstrument(NOW, DSC_USD_MARKET_QUOTES[i], 1, DSC_USD_ATTR[i]));
}
}
/** Market values for the 3m LIBOR curve */
private static final double[] FWD3_USD_MARKET_QUOTES = new double[] { 0.0420, 0.0420, 0.0420, 0.0430, 0.0470, 0.0540, 0.0570, 0.0600 };
/** Vanilla instrument generators for the 3m LIBOR curve */
private static final GeneratorInstrument[] FWD3_USD_GENERATORS = new GeneratorInstrument[] { GENERATOR_USDLIBOR3M, USD6MLIBOR3M,
USD6MLIBOR3M, USD6MLIBOR3M, USD6MLIBOR3M, USD6MLIBOR3M,
USD6MLIBOR3M, USD6MLIBOR3M };
/** Attribute generators for the 3m LIBOR curve */
private static final GeneratorAttributeIR[] FWD3_USD_ATTR;
static {
final Period[] libor3mTenors = new Period[] { Period.ofMonths(0), Period.ofMonths(6), Period.ofYears(1), Period.ofYears(2),
Period.ofYears(3),
Period.ofYears(5), Period.ofYears(7), Period.ofYears(10) };
FWD3_USD_ATTR = new GeneratorAttributeIR[libor3mTenors.length];
for (int i = 0; i < libor3mTenors.length; i++) {
FWD3_USD_ATTR[i] = new GeneratorAttributeIR(libor3mTenors[i]);
BUILDER_FOR_TEST.addNode(CURVE_NAME_FWD3_USD,
FWD3_USD_GENERATORS[i].generateInstrument(NOW, FWD3_USD_MARKET_QUOTES[i], 1, FWD3_USD_ATTR[i]));
}
}
/** Curves constructed before today's fixing */
private static final Pair<MulticurveProviderForward, CurveBuildingBlockBundle> BEFORE_TODAYS_FIXING;
/** Curves constructed after today's fixing */
private static final Pair<MulticurveProviderForward, CurveBuildingBlockBundle> AFTER_TODAYS_FIXING;
static {
BEFORE_TODAYS_FIXING = BUILDER_FOR_TEST.copy().getBuilder().buildCurves(NOW, FIXING_TS_WITHOUT_TODAY);
AFTER_TODAYS_FIXING = BUILDER_FOR_TEST.copy().getBuilder().buildCurves(NOW, FIXING_TS_WITH_TODAY);
}
/**
* The discounting curve is constructed first, then used the construct a 3m LIBOR curve. The inverse Jacobian for the discounting curve should be a square
* matrix, as it is decoupled from the LIBOR curve, and the inverse Jacobian for the LIBOR curve should contain sensitivities to both the LIBOR and
* discounting curve.
*/
@Override
@Test
public void testJacobianSize() {
final CurveBuildingBlockBundle fullJacobian = BEFORE_TODAYS_FIXING.getSecond();
final Map<String, Pair<CurveBuildingBlock, DoubleMatrix2D>> fullJacobianData = fullJacobian.getData();
assertEquals(fullJacobianData.size(), 2);
final DoubleMatrix2D discountingJacobianMatrix = fullJacobianData.get(CURVE_NAME_DSC_USD).getSecond();
assertEquals(discountingJacobianMatrix.getNumberOfRows(), DSC_USD_MARKET_QUOTES.length);
assertEquals(discountingJacobianMatrix.getNumberOfColumns(), DSC_USD_MARKET_QUOTES.length);
final DoubleMatrix2D liborJacobianMatrix = fullJacobianData.get(CURVE_NAME_FWD3_USD).getSecond();
assertEquals(liborJacobianMatrix.getNumberOfRows(), FWD3_USD_MARKET_QUOTES.length);
assertEquals(liborJacobianMatrix.getNumberOfColumns(), FWD3_USD_MARKET_QUOTES.length + DSC_USD_MARKET_QUOTES.length);
}
@Override
@Test
public void testInstrumentsInCurvePriceToZero() {
Map<String, List<InstrumentDefinition<?>>> definitions = BUILDER_FOR_TEST.copy()
.getBuilder()
.getNodes();
curveConstructionTest(definitions.get(CURVE_NAME_DSC_USD), BEFORE_TODAYS_FIXING.getFirst(),
PresentValueDiscountingCalculator.getInstance(),
FIXING_TS_WITHOUT_TODAY, FX_MATRIX, NOW, Currency.USD);
curveConstructionTest(definitions.get(CURVE_NAME_FWD3_USD), BEFORE_TODAYS_FIXING.getFirst(),
PresentValueDiscountingCalculator.getInstance(), FIXING_TS_WITHOUT_TODAY, FX_MATRIX, NOW, Currency.USD);
definitions = BUILDER_FOR_TEST.copy()
.getBuilder()
.getNodes();
curveConstructionTest(definitions.get(CURVE_NAME_DSC_USD), AFTER_TODAYS_FIXING.getFirst(),
PresentValueDiscountingCalculator.getInstance(),
FIXING_TS_WITH_TODAY, FX_MATRIX, NOW, Currency.USD);
curveConstructionTest(definitions.get(CURVE_NAME_FWD3_USD), AFTER_TODAYS_FIXING.getFirst(),
PresentValueDiscountingCalculator.getInstance(),
FIXING_TS_WITH_TODAY, FX_MATRIX, NOW, Currency.USD);
}
@Override
@Test
public void testFiniteDifferenceSensitivities() {
testDiscountingCurveSensitivities(BEFORE_TODAYS_FIXING.getSecond(), FIXING_TS_WITHOUT_TODAY);
testDiscountingCurveSensitivities(AFTER_TODAYS_FIXING.getSecond(), FIXING_TS_WITH_TODAY);
test3mLiborCurveSensitivities(BEFORE_TODAYS_FIXING.getSecond(), FIXING_TS_WITHOUT_TODAY);
test3mLiborCurveSensitivities(AFTER_TODAYS_FIXING.getSecond(), FIXING_TS_WITH_TODAY);
}
/**
* Tests the sensitivities of the discounting curve to changes in the market data points used in the discounting curve. There are no sensitivities to the
* LIBOR curve.
*
* @param fullInverseJacobian
* analytic sensitivities
* @param fixingTs
* the fixing time series
*/
private static void testDiscountingCurveSensitivities(final CurveBuildingBlockBundle fullInverseJacobian,
final Map<Index, ZonedDateTimeDoubleTimeSeries> fixingTs) {
// sensitivities to discounting
assertFiniteDifferenceSensitivities(fullInverseJacobian, fixingTs, BUILDER_FOR_TEST, CURVE_NAME_DSC_USD, CURVE_NAME_DSC_USD, NOW,
DSC_USD_GENERATORS,
DSC_USD_ATTR, DSC_USD_MARKET_QUOTES, false);
// sensitivities to 3m LIBOR should not have been calculated
assertNoSensitivities(fullInverseJacobian, CURVE_NAME_DSC_USD, CURVE_NAME_FWD3_USD);
}
/**
* Tests the sensitivities of the LIBOR curve to changes in the market data points used in the discounting and LIBOR curve.
*
* @param fullInverseJacobian
* analytic sensitivities
* @param fixingTs
* the fixing time series
*/
private static void test3mLiborCurveSensitivities(final CurveBuildingBlockBundle fullInverseJacobian,
final Map<Index, ZonedDateTimeDoubleTimeSeries> fixingTs) {
// sensitivities to discounting
assertFiniteDifferenceSensitivities(fullInverseJacobian, fixingTs, BUILDER_FOR_TEST, CURVE_NAME_FWD3_USD, CURVE_NAME_DSC_USD, NOW,
DSC_USD_GENERATORS,
DSC_USD_ATTR, DSC_USD_MARKET_QUOTES, false);
// sensitivities to 3m LIBOR
assertFiniteDifferenceSensitivities(fullInverseJacobian, fixingTs, BUILDER_FOR_TEST, CURVE_NAME_FWD3_USD, CURVE_NAME_FWD3_USD, NOW,
FWD3_USD_GENERATORS,
FWD3_USD_ATTR, FWD3_USD_MARKET_QUOTES, false);
}
/**
* Only one set of curves is constructed, so no tests are possible.
*/
@Override
@Test
public void testSameCurvesDifferentMethods() {
return;
}
/**
* Prints out the forward curve.
*/
@Test(enabled = false)
public void forwardAnalysis() {
final MulticurveProviderInterface marketDsc = BEFORE_TODAYS_FIXING.getFirst();
final int jump = 1;
final int startIndex = 0;
final int nbDate = 2750;
ZonedDateTime startDate = ScheduleCalculator.getAdjustedDate(NOW, USD_3M_LIBOR_INDEX.getSpotLag() + startIndex * jump, NYC);
final double[] rateDsc = new double[nbDate];
final double[] startTime = new double[nbDate];
try (FileWriter writer = new FileWriter("fwd-dsc.csv")) {
for (int i = 0; i < nbDate; i++) {
startTime[i] = TimeCalculator.getTimeBetween(NOW, startDate);
final ZonedDateTime endDate = ScheduleCalculator.getAdjustedDate(startDate, USD_3M_LIBOR_INDEX, NYC);
final double endTime = TimeCalculator.getTimeBetween(NOW, endDate);
final double accrualFactor = USD_3M_LIBOR_INDEX.getDayCount().getDayCountFraction(startDate, endDate, CalendarAdapter.of(NYC));
rateDsc[i] = marketDsc.getSimplyCompoundForwardRate(USD_3M_LIBOR_INDEX, startTime[i], endTime, accrualFactor);
startDate = ScheduleCalculator.getAdjustedDate(startDate, jump, NYC);
writer.append(0.0 + "," + startTime[i] + "," + rateDsc[i] + "\n");
}
writer.flush();
writer.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
| true
|
ea5f150f9b7c26c93f486fc6ca0d3255566b54fa
|
Java
|
zhanghwei/zhanghengwei-hgshop
|
/hgshop-goods-service/src/main/java/com/zhangwei/hgshop/dao/SpecDao.java
|
UTF-8
| 509
| 1.84375
| 2
|
[] |
no_license
|
package com.zhangwei.hgshop.dao;
import java.util.List;
import com.zhangwei.hgshop.pojo.Spec;
import com.zhangwei.hgshop.pojo.SpecOption;
public interface SpecDao {
List<Spec> list(String name);
int addSpec(Spec spec);
int addOptions(SpecOption specOption);
int updateSpec(Spec spec);
int deleteSpecOptions(int id);
int deleteSpec(int id);
Spec get(int id);
int deleteSpecOptionsBatch(int[] id);
int deleteSpecBatch(int[] id);
List<Spec> listAll();
}
| true
|