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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
18500acda474347d1c72ebc54de60131ff76c167
|
Java
|
someth2say/FaultTolerantHi
|
/src/main/java/com/someth2say/FaultTolerantHi.java
|
UTF-8
| 2,355
| 2.703125
| 3
|
[] |
no_license
|
package com.someth2say;
import org.eclipse.microprofile.faulttolerance.CircuitBreaker;
import org.eclipse.microprofile.faulttolerance.Fallback;
import org.eclipse.microprofile.faulttolerance.Retry;
import org.eclipse.microprofile.faulttolerance.Timeout;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hi")
public class FaultTolerantHi {
AtomicInteger counter = new AtomicInteger(1);
int failChance = 0;
int delayChance = 0;
int delay = 0;
@GET
@Path("/fail/{chance}")
@Produces(MediaType.TEXT_PLAIN)
public String fail(final int chance){
this.failChance=chance;
return "Fail chance set to "+this.failChance;
}
@GET
@Path("/delay/{chance}/{delay}")
@Produces(MediaType.TEXT_PLAIN)
public String delayChance(final int chance, final int delay){
this.delayChance=chance;
this.delay=delay;
return "Delay chance set to "+this.delayChance+" with "+this.delay+" milis";
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Retry(maxRetries = 2)
@Path("/retry")
public String retry(){
return hello();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Fallback(fallbackMethod = "fallbackHello")
@Path("/fallback")
public String fallback(){
return hello();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Timeout(100)
@Path("/timeout100")
public String timeout100(){
return hello();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@CircuitBreaker(requestVolumeThreshold = 4)
@Path("/circuitbreaker")
public String circuitBreaker(){
return hello();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
var count = counter.getAndIncrement();
if (failChance>0 && count%failChance == 0){
throw new RuntimeException("Hello Failure.");
}
if (delayChance>0 && count%delayChance == 0){
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException("Hello Interrupted!");
}
}
return "Hello";
}
public String fallbackHello() {
return "Hello Fallback";
}
}
| true
|
a0d5d5b66489097289801ffdae10048507f53491
|
Java
|
clockworm/Java_review
|
/src/day3/Machelloe.java
|
UTF-8
| 1,052
| 3.15625
| 3
|
[] |
no_license
|
package day3;
//if else if判断
public class Machelloe{
public static void main(String[] args) {
int a1 = 6; //商品
int b = 51; //投币金额
int c = b-a1;
if(b==100)
System.out.println("投入为"+b+"找你零钱"+c);
else if (b==50)
System.out.println("投入为"+b+"找你零钱"+c);
else if (b==20)
System.out.println("投入为"+b+"找你零钱"+c);
else if (b==10)
System.out.println("投入为"+b+"找你零钱"+c);
else if (b==1)
System.out.println("余额不足,请继续投币");
else
System.out.println("不能识别,请重新投入人民币");
long tel = 18523916072l;
if (tel>9999999999l&&tel<20000000000l)
System.out.println("是手机号码");
else
System.out.println("不是手机号码");
int a = 18;
if(a<18)
System.out.println("此角色还未开放,无法选择!");
else if(a>22)
System.out.println("大师兄");
else if(a>20)
System.out.println("小师弟");
else
System.out.println("小师妹");
}
}
| true
|
9314879abfd9be7000b716bb0bc45a5cb99c246b
|
Java
|
MichalakJ/zpi3
|
/mod2/src/main/java/EncryptionUtils.java
|
UTF-8
| 3,315
| 2.96875
| 3
|
[] |
no_license
|
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Author Mateusz Wieczorek on 11/14/16.
*/
public class EncryptionUtils {
private static final String RANDOM_INIT_VECTOR = "RandomInitVector";
private static final String ALGORITHM = "AES/CBC/PKCS5PADDING";
private static final String ENCRYPTION_TYPE = "AES";
private static final String CHARACTER_ENCODING = "UTF-8";
public static File encrypt(File file, String key) {
try {
List<String> values = readFile(file);
List<String> encryptedValues = new ArrayList<>();
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CHARACTER_ENCODING), ENCRYPTION_TYPE);
IvParameterSpec iv = new IvParameterSpec(RANDOM_INIT_VECTOR.getBytes(CHARACTER_ENCODING));
for (String s : values) {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(s.getBytes());
encryptedValues.add(Base64.encodeBase64String(encrypted));
}
saveToFile(encryptedValues, file);
return file;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static File decrypt(File file, String key) {
try {
List<String> values = readFile(file);
List<String> originalValues = new ArrayList<>();
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CHARACTER_ENCODING), ENCRYPTION_TYPE);
IvParameterSpec iv = new IvParameterSpec(RANDOM_INIT_VECTOR.getBytes(CHARACTER_ENCODING));
for (String s : values) {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(s));
originalValues.add(new String(original));
}
saveToFile(originalValues, file);
return file;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static List<String> readFile(File file) {
try (Stream<String> stream = Files.lines(Paths.get(file.getAbsolutePath()))) {
return stream.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void saveToFile(List<String> values, File file) {
for (String s : values) {
try {
Files.write(Paths.get(file.getAbsolutePath()), s.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String key = "Bar12345Bar12345"; // 128 bit key
File file = new File("someFile.txt");
encrypt(file, key);
//decrypt(file, key);
}
}
| true
|
f3f1911a119cd7c7631557972f21d58245edc87e
|
Java
|
greatypine/GASM
|
/src/com/cnpc/pms/base/common/action/DispatcherAction.java
|
UTF-8
| 15,272
| 1.953125
| 2
|
[] |
no_license
|
package com.cnpc.pms.base.common.action;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cnpc.pms.base.audit.annotation.Audit;
import com.cnpc.pms.base.audit.entity.AuditLog;
import com.cnpc.pms.base.common.model.ClientRequestObject;
import com.cnpc.pms.base.common.model.ClientResponseObject;
import com.cnpc.pms.base.exception.DispatcherException;
import com.cnpc.pms.base.exception.PMSManagerException;
import com.cnpc.pms.base.exception.UtilityException;
import com.cnpc.pms.base.exception.ValidationException;
import com.cnpc.pms.base.manager.IManager;
import com.cnpc.pms.base.manager.core.DynamicType;
import com.cnpc.pms.base.security.SessionManager;
import com.cnpc.pms.base.security.UserSession;
import com.cnpc.pms.base.util.SpringHelper;
import com.cnpc.pms.base.util.StrUtil;
/**
* <p>
* <b>Action Dispatcher</b>
* </p>
* Action dispatcher is in charged to handle request and response between server side and client side.<br/>
* Copyright(c) 2011 China National Petroleum Corporation , http://www.cnpc.com.cn
*
* @author lushu
* @author Zhou zaiqing
* @since 2010/10/29
*/
public class DispatcherAction extends HttpServlet {
/** Serial Version UID. */
private static final long serialVersionUID = 1L;
/** The Constant log. */
protected Logger log = LoggerFactory.getLogger(this.getClass());
protected static final String REQUEST_STRING = "requestString";
private boolean auditEnabled = false;
private IManager auditLogManager;
protected final Map<String, IManager> BUSINESS_INSTANCE_CACHE = new HashMap<String, IManager>();
protected final Map<String, MethodAgent> methodAgents = new HashMap<String, MethodAgent>();
// protected final Map<String, Method> BUSINESS_METHOD_CACHE = new HashMap<String, Method>();
// protected final Map<String, Class<?>[]> PARAMETER_TYPES = new HashMap<String, Class<?>[]>();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// request.setCharacterEncoding("UTF-8");// 2013.6.9 Not necessary, already set in CharacterEncodingFilter
String repeatable = request.getParameter("repeatable");
if (repeatable != null && repeatable.equals("false")) {
String token = UUID.randomUUID().toString().replace("-", "");
request.getSession().setAttribute("token", token);
response.getWriter().write("{\"result\":true,\"token\":\"" + token + "\"}");
} else {
// response.getWriter().write(execute(request));
execute(request, response);
}
}
/**
* <h3>Dispatcher Action Executer</h3> The very handler to handle main http request from client.
*
* Json String to invoke server side managers.
* @param request
* the req
* @return ResponseString in Json format
* @throws IOException
*/
protected void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
String requestString = request.getParameter(REQUEST_STRING);// for log
System.err.println("***********************************打印请求过来的字符串requestString***********************************");
System.out.println("打印 requestString 的值:"+requestString);
System.out.println("打印 requestString 的值:"+requestString);
System.out.println("打印 requestString 的值:"+requestString);
System.out.println("打印 requestString 的值:"+requestString);
System.out.println("***********************************打印请求过来的字符串requestString***********************************");
ClientResponseObject responseObj = new ClientResponseObject();
try {
ClientRequestObject requestObj = getClientRequestObject(request);
prepareInvokeTarget(requestObj);
// Verify token;
if (true == StrUtil.isNotEmpty(requestObj.getToken())) {
if (request.getSession().getAttribute("token") != null
&& request.getSession().getAttribute("token").equals(requestObj.getToken())) {
request.getSession().setAttribute("token", "");
} else {
// TODO: all info needs deal with i18n message
log.warn("Repeat submit: {}", requestString);
throw new DispatcherException("Repeat submit.");
}
}
Object resultValue = doJob(requestObj, responseObj);
// TODO: optimize this API to remove requestObj?
afterInvoke(resultValue, responseObj, request, requestObj);
} catch (Exception e) {
//find* result
responseObj.setResult(false);
responseObj.setMessage(e.getMessage());
if (e instanceof DispatcherException == false) {
log.error("Unhandle exception in dispatcher action servlet. Check this: {}", e.getMessage(), e);
}
}
// return responseObj.toJSON();
doResponse(responseObj, response);
}
/**
* Get the client request object from the Http Request.
*
* @param request
* the HttpServletRequest
* @return the client request object
* @throws DispatcherException
* the dispatcher exception
*/
protected ClientRequestObject getClientRequestObject(HttpServletRequest request) throws DispatcherException {
return getRequestObject(request, ClientRequestObject.class);
}
protected <T> T getRequestObject(HttpServletRequest request, Class<T> clazz) throws DispatcherException {
String clientInvokeString = request.getParameter(REQUEST_STRING);
T requestObj;
try {
requestObj = (T)StrUtil.fromJson(clientInvokeString, clazz);
return requestObj;
} catch (UtilityException e) {
log.error("Malform client invoke String: {}", clientInvokeString);
throw new DispatcherException("Malform client invoke string: " + clientInvokeString, e);
}
}
/**
* Prepare invoke target of the ClientRequestObject
*
* the client invoke string
* @return the client request object
* @throws DispatcherException
* the dispatcher exception
*/
protected final void prepareInvokeTarget(ClientRequestObject requestObj) throws DispatcherException {
if (StrUtil.isBlank(requestObj.getManagerName()) || StrUtil.isBlank(requestObj.getMethodName())) {
log.error("Missing invoke manager or method: {}", requestObj.getKey());
throw new DispatcherException("Missing invoke target: " + requestObj.getKey());
}
String methodKey = requestObj.getKey();
if (!methodAgents.containsKey(methodKey)) {
synchronized (this) {
if (!methodAgents.containsKey(methodKey)) {
registerMethods(requestObj);
}
}
}
}
protected final void registerMethods(ClientRequestObject requestObj) throws DispatcherException {
String methodKey = requestObj.getKey();
String className = requestObj.getManagerName();
String methodName = requestObj.getMethodName();
IManager manager = BUSINESS_INSTANCE_CACHE.get(className);
if (null == manager) {
manager = SpringHelper.getManagerByClass(className);
if (null != manager) {
BUSINESS_INSTANCE_CACHE.put(className, manager);
} else {
log.error("Fail to get manager: {}, request string: \n{}", className, requestObj.toString());
throw new DispatcherException("Incorrect manager invoked: " + methodKey);
}
}
Method method = null;
// Class<?>[] types = new Class<?>[0];
if (true == StrUtil.isNotBlank(methodName)) {
Class<?>[] interfaces = manager.getClass().getInterfaces();
interfaces: for (Class<?> clazz : interfaces) {
for (Method m : clazz.getMethods()) {
if (m.getName().equalsIgnoreCase(methodName)) {
method = m;
MethodAgent agent = new MethodAgent(method);
Class<?>[] types = m.getParameterTypes();
log.debug("Get method[{}] in [{}], with parameters: {}",
new Object[] { methodName, clazz.getSimpleName(), types });
Annotation[][] annos = m.getParameterAnnotations();
for (int i = 0; i < annos.length; i++) {
for (Annotation anno : annos[i]) {
if (anno.annotationType().equals(DynamicType.class)) {
// NOTE: Can specific the method or value here to determine
Class<?> newType = manager.getEntityClass();
log.debug("Replace Original Parameter type {} with {}, index {}", new Object[] {
types[i], newType, i });
types[i] = newType;
break;
}
}
}
agent.setParameterTypes(types);
agent.setAudit(method.getAnnotation(Audit.class));
methodAgents.put(methodKey, agent);
break interfaces;
}
}
}
}
// if (null != method) {
// BUSINESS_METHOD_CACHE.put(methodKey, method);//commented at 2013.8.20
// PARAMETER_TYPES.put(methodKey, types);// added at 2013.8.12//commented at 2013.8.20
// } else {
if (method == null) {
log.error("Fail to get method: {}, request string: \n{}", methodKey, requestObj.toString());
throw new DispatcherException("Incorrect method invoked: " + methodKey);
}
}
protected Object doJob(ClientRequestObject requestObj, ClientResponseObject responseObj) throws DispatcherException {
MethodAgent agent = methodAgents.get(requestObj.getKey());// added at 2013.8.20
Method method = agent.getMethod();// BUSINESS_METHOD_CACHE.get(requestObj.getKey());// commented at 2013.8.20
Class<?>[] parameterTypes = agent.getParameterTypes();// PARAMETER_TYPES.get(requestObj.getKey());//
// method.getParameterTypes();
int requestParametersCount = 0;
if (requestObj.getParameters() != null) {
requestParametersCount = requestObj.getParameters().length;
}
if (parameterTypes.length > requestParametersCount) {
log.error("Missing invoke parameters, need {}, get {}. Request: {} ", new Object[] {
parameterTypes.length, requestObj.getParameters().length, requestObj.toString() });
throw new DispatcherException("Missing invoke parameters, need " + parameterTypes.length + ", get "
+ requestObj.getParameters().length);
}
for (int i = 0; i < parameterTypes.length; i++) {
Object obj = requestObj.getParameters()[i];
if (obj != null) {
Class<?> paraClass = parameterTypes[i];
if (obj.getClass() != paraClass && !(paraClass.isInstance(obj))) {
try {
requestObj.setParameter(StrUtil.fromJson(obj.toString(), paraClass), i);
} catch (UtilityException e) {
log.error(
"Wrong invoke parameter type at {}[0-based] to {}, supposed type is {}, request value is {} ",
new Object[] { i, requestObj.getKey(), paraClass.getSimpleName(), obj });
throw new DispatcherException("Wrong inovke parameter at " + i + " with: "
+ requestObj.toString());
}
}
}
}
// NOTE: optimize SessionManager to move following code to there
boolean needAudit = auditEnabled && agent.isAudit();
AuditLog auditLog = null;
if (needAudit == true) {
Audit audit = agent.getAudit();
auditLog = new AuditLog();
auditLog.setService(requestObj.getManagerName());
auditLog.setMethod(requestObj.getMethodName());
auditLog.setOperationTime(new Date());
auditLog.setStatus(0);
auditLog.setAudit(audit, requestObj.getParameters());
UserSession session = SessionManager.getUserSession();
if (session != null) {
Map<?, ?> map = session.getSessionData();
if (map != null) {
auditLog.setUserName(map.get("userName").toString());
auditLog.setUserCode(map.get("userCode").toString());
}
}
}
Object resultValue = null;
try {
resultValue = method.invoke(BUSINESS_INSTANCE_CACHE.get(requestObj.getManagerName()),
requestObj.getParameters());
} catch (Exception e) {
if (e.getCause() instanceof ValidationException) {
responseObj.setResult(true);
responseObj.setMessage(ValidationException.VALIDATE_MESSAGE_PREFIX + e.getCause().getMessage());
} else {
Throwable t = e;
if (e instanceof InvocationTargetException) {
t = e.getCause();
}
log.error("Exeption in invoke [{}]: {} ", requestObj.getKey(), t.getMessage());
e.printStackTrace();
String message;
if (t instanceof PMSManagerException) {
message = t.getMessage();
} else {
message = "Exception in invoke " + requestObj.getKey() + ", reason: " + t.getMessage();
}
if (needAudit == true) {
auditLog.setStatus(1);
auditLog.setException(message);
}
throw new DispatcherException(message);
}
} finally {
if (needAudit == true) {
auditLogManager.save(auditLog);
}
}
return resultValue;
}
/**
* Do jobs after invoke the requested method.
*
* @param resultValue
* @param responseObj
* @param requestObj
* @throws DispatcherException
*/
protected void afterInvoke(Object resultValue, ClientResponseObject responseObj, HttpServletRequest request,
ClientRequestObject requestObj) throws DispatcherException {
String str;
if (requestObj.getManagerName().toLowerCase().indexOf("treemanager") != -1) {
str = StrUtil.toJsonWithGson(resultValue);
} else {
str = StrUtil.toJson(resultValue);
}
responseObj.setResult(true);
responseObj.setData(str);
}
/**
* Response to the request.
* lty 363
* @param responseObj
* @param response
* @throws IOException
*/
protected void doResponse(ClientResponseObject responseObj, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().write(responseObj.toJSON());
System.out.println("***********************************************");
System.out.println();
System.out.println(responseObj.toJSON());
System.out.println();
System.out.println("***********************************************");
}
@Override
public void init() throws ServletException {
super.init();
String audit = super.getServletConfig().getInitParameter("audit");
if ("true".equalsIgnoreCase(audit) || "on".equalsIgnoreCase(audit) || "yes".equalsIgnoreCase(audit)) {
auditEnabled = true;
auditLogManager = SpringHelper.getManagerByClass("auditLogManager");
}
}
@Override
public void destroy() {
if (auditEnabled == true) {
// NOTE: maybe we should log the audit start&end events.
// Can do this in the specific manager
}
super.destroy();
}
}
class MethodAgent {
private Method method;
private Class<?>[] parameterTypes;
private Audit audit;
private boolean isAudit;
public MethodAgent(Method method) {
super();
this.method = method;
}
public Method getMethod() {
return method;
}
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
public Audit getAudit() {
return audit;
}
public void setAudit(Audit audit) {
this.audit = audit;
this.isAudit = (this.audit != null);
}
public boolean isAudit() {
return this.isAudit;
}
}
| true
|
32d04da1ef7fefb44250290528b8cde174da507a
|
Java
|
Andrea-Arguello/Laboratorio4
|
/Soldado.java
|
UTF-8
| 543
| 2.875
| 3
|
[] |
no_license
|
/**
* Soldado.java
* Andrea Arguello 17801
* 13/10/2017
*/
/**Heredada de Militar
*/
public class Soldado extends Militar
{
/**
@return: horas
*/
public int getHoras()
{
return super.getHoras()*2;
}
/**
@return: salario
*/
public double getSalario()
{
return super.getSalario() - 10000.0;
}
/**
@return: vacaciones
*/
public int getVacaciones()
{
return super.getVacaciones()/2;
}
/** Recibe orden
*/
public void recibeOrden()
{
System.out.println("Ordene mi General");
}
}
| true
|
b3fbf6c52a8b3c6b11c8566484c5338f6b50798c
|
Java
|
scaffeinate/passport-developer-challenge
|
/factory-tree-api/src/main/java/com/passport/project/factory/repositories/FactoriesRepository.java
|
UTF-8
| 322
| 1.59375
| 2
|
[] |
no_license
|
package com.passport.project.factory.repositories;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.passport.project.factory.dto.FactoryDTO;
@Repository
public interface FactoriesRepository extends MongoRepository<FactoryDTO, String> {
}
| true
|
1bef420f22088c9fe99849e7ecac182cc6988967
|
Java
|
anilkilinc/mactakipci
|
/Android/mactakipci/src/main/java/com/anilkilinc/mactakipci/Mactakipci.java
|
UTF-8
| 704
| 2.109375
| 2
|
[] |
no_license
|
package com.anilkilinc.mactakipci;
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* Created by Anil on 19.09.2014.
*/
public class Mactakipci extends Application{
private static Mactakipci singleton;
private RequestQueue requestQuee;
public Mactakipci() {
super();
singleton = this;
}
public Mactakipci getInstance() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
requestQuee = Volley.newRequestQueue(getApplicationContext());
}
public static void increase() {
}
public static void decrease() {
}
}
| true
|
4069aae6eb3ab38c632472bb5da1b19637ec711c
|
Java
|
tddyer/cs487-food-ordering-app
|
/app/src/main/java/com/example/orderquik/MainActivity.java
|
UTF-8
| 10,496
| 2.078125
| 2
|
[] |
no_license
|
package com.example.orderquik;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.accounts.Account;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = "MainActivity";
private List<Item> menuItems = new ArrayList<>();
private List<Item> itemsInCart = new ArrayList<>();
private RecyclerView menuRecycler;
private ItemsAdapter itemsAdapter;
private Bundle bundle;
private User user;
private DatabaseHandler databaseHandler;
static String[] foodNames = {
"Cheeseburger",
"Salad",
"[SPECIAL] Spaghetti and Meatballs",
"Gyros",
"Lasagna",
"Macaroni and Cheese",
"Chicken Fried Rice",
"Sloppy Joes",
"Beef and Broccoli Stir-Fry",
"Sweet & Sour Chicken",
"Lemon Baked Cod"
};
double[] foodPrices = {
10.99,
7.99,
12.99,
14.99,
15.99,
9.99,
11.99,
9.99,
12.99,
13.99,
17.99
};
String[] foodDescriptions = {
"A classic angus burger topped with cheddar cheese, lettuce, tomato, and pickles.",
"Romaine lettuce, baby spinach, carrots, cucumbers, shredded cheese, and your choice of dressing.",
"Classic italian pasta with our chef's specialty marinara sauce and homemade meatballs.",
"A mix of ground beef and ground lamb with onion, garlic, and rosemary with a hot pita.",
"Our signature 4-cheese lasagne topped with a light layer of marinara meat sauce.",
"One-of-a-kind homemade mac-n-cheese with a mixture of 3 cheeses.",
"Two Crispy, fried chicken breasts with a side of mashed potatos and gravy.",
"Ground turkey topped with out Homemade 'joe' sauce",
"Lean beef with steamed broccoli, a mixture of vegetables, and your choice of stir-fry sauce.",
"Our truly sweet and somewhat sour sauce served with a bowl of steamed white rice.",
"Atlantic cod baked with lemon flavor."
};
int[] foodCalories = {
1400,
875,
1450,
1700,
1175,
1350,
1500,
1100,
1200,
1300,
950
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getting login information to determine if a guest or user logged in
bundle = getIntent().getExtras();
// user login or return from account activity
if (bundle != null) {
user = (User) bundle.getSerializable("USER_DATA");
Log.d(TAG, "onCreate: " + user.getDeliveryAddress() + user.getCreditCardInfo());
} else {
// guest login
user = new Guest();
}
menuRecycler = findViewById(R.id.menuRecycler);
itemsAdapter = new ItemsAdapter(menuItems, this);
menuRecycler.setAdapter(itemsAdapter);
menuRecycler.setLayoutManager(new LinearLayoutManager(this));
databaseHandler = new DatabaseHandler(this);
// refresh menu items database when local list is updated - this would be completely different if we
// had a cloud database implemented (menu items wouldn't be editable from a user device)
databaseHandler.flushItems();
// populating recycler with test data - this would be different if we had a cloud database
// implemented (items would be fetched from database and loaded in instead of using a locally
// stored list
for (int i = 0; i < foodNames.length; i++) {
Item it = new Item();
it.setName(foodNames[i]);
it.setPrice(foodPrices[i]);
it.setDescription(foodDescriptions[i]);
it.setCalories(foodCalories[i]);
menuItems.add(it);
databaseHandler.addItem(it);
}
itemsAdapter.notifyDataSetChanged();
}
// implementing functionality for onClick and onLongClick for the view holder
// From OnClickListener
@Override
public void onClick(View v) { // click listener called by ViewHolder clicks
final CharSequence[] amount = {"1","2","3","4","5"};
final String[] tmpIndex = new String[1];
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the amount of dishes.")
.setSingleChoiceItems(amount, -1, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int index){
tmpIndex[0] = null;
tmpIndex[0] = (String) amount[index];
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int pos = menuRecycler.getChildLayoutPosition(v);
Item itemTmp = menuItems.get(pos);
Item it = null;
for(Item ci : itemsInCart){
if(ci.getName().equals(itemTmp.getName())){
it = ci;
break;
}
}
if(it != null){
int position = itemsInCart.indexOf(it);
int newItemAmount = Integer.parseInt(tmpIndex[0]);
int currentItemAmount = it.getItemAmount();
itemsInCart.get(pos).setItemAmount(newItemAmount+currentItemAmount);
}else{
itemTmp.setItemAmount(Integer.parseInt(tmpIndex[0]));
itemsInCart.add(itemTmp);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog dialog = builder.create();
dialog.show();
// int pos = menuRecycler.getChildLayoutPosition(v);
// itemsInCart.add(menuItems.get(pos));
// Toast.makeText(this.getApplicationContext(), menuItems.get(pos).getName()+" added", Toast.LENGTH_SHORT).show();
}
// From OnLongClickListener
@Override
public boolean onLongClick(View v) { // long click listener called by ViewHolder long clicks
// int pos = recyclerView.getChildLayoutPosition(v);
return true;
}
// options menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuCart:
viewCart();
return true;
case R.id.menuProfile:
// TODO: view profile here
viewAccount();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void viewAccount(){
if(getIntent().hasExtra("AccountPageToCheckoutPage")){
user = null;
user = (User) getIntent().getSerializableExtra("AccountPageToCheckoutPage");
}
Intent intent = new Intent(MainActivity.this, AccountActivity.class);
intent.putExtra("UserInFo", (Serializable) user);
startActivity(intent);
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent it = new Intent(this, LoginActivity.class);
startActivity(it);
}
// alert dialogs
public void viewCart() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] itemNames = new CharSequence[itemsInCart.size()];
for (int i = 0; i < itemsInCart.size(); i++){
itemNames[i] = itemsInCart.get(i).getName()+" (amount: "+itemsInCart.get(i).getItemAmount()+")";
}
builder.setPositiveButton("Checkout", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: navigate to checkout activity here
if(itemsInCart.size() == 0){
emptyCartAlert();
}else{
Intent it = new Intent(MainActivity.this, CheckOutActivity.class);
it.putExtra("selectedItems", (Serializable) itemsInCart);
it.putExtra("user", (Serializable) user);
startActivity(it);
}
}
});
builder.setNegativeButton("Continue Shopping", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
builder.setTitle("Your Order");
builder.setItems(itemNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO: remove items here
itemsInCart.remove(which);
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void emptyCartAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Cart is Empty.");
builder.setNegativeButton("Continue Shopping", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
| true
|
4a26862e229b7b106c0fff87b8185b6c2dc129f8
|
Java
|
lijiangjiajun/work
|
/超长整数逆序排列/src/Main.java
|
UTF-8
| 932
| 3.421875
| 3
|
[] |
no_license
|
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
List<BigInteger> list =new ArrayList<>();
int n= scanner.nextInt();
for(int i=0;i<n;i++) {
list.add(scanner.nextBigInteger());
}
Collections.sort(list, new Comparator<BigInteger>() {
@Override
public int compare(BigInteger o1, BigInteger o2) {
if(o1.compareTo(o2)==-1){
return 1;
}
else if(o1.compareTo(o2)==1){
return -1;
}
else{
return 0;
}
}
});
System.out.println(list);
}
}
}
| true
|
7b6b25a8c14414cddeca002911444d62e75aba1d
|
Java
|
RaniTrianiG/minimarket-1
|
/src/main/java/com/market/controller/UserRestController.java
|
UTF-8
| 1,905
| 2.109375
| 2
|
[] |
no_license
|
package com.market.controller;
import com.market.model.User;
import com.market.repository.UserRepository;
import com.market.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/user")
public class UserRestController {
private UserRepository userRepository;
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(value = {"/list", "/list/"}, method = RequestMethod.GET)
public Iterable<User> listUser(){
return userRepository.findAll();
}
@RequestMapping(value = {"/createupdate", "/createupdate/"}, method = RequestMethod.POST)
public Iterable<User> createupdateUser(@RequestBody User user){
userService.saveUser(user);
return userRepository.findAll();
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
public Iterable<User> delete(@PathVariable Integer id){
userRepository.delete(id);
return userRepository.findAll();
}
@RequestMapping(value = "/search/{id}", method = RequestMethod.GET)
public User searchUser(@PathVariable Integer id){
return userRepository.findOne(id);
}
@RequestMapping(value = {"/password", "/password/"}, method = RequestMethod.GET)
@ResponseBody
public void gantiPassword(Integer id, String password){
userService.gantiPassword(id, password);
}
@RequestMapping(value = "/update", method = RequestMethod.GET)
@ResponseBody
public void update(Integer id, String name, String username){
userService.ubahData(id, username, name);
}
}
| true
|
2550e483ba4fcff7310c7c2335fd97bd167d6db2
|
Java
|
moatazelmasry2/ann
|
/src/org/mothenervous/nn/ngas/SOMExample.java
|
UTF-8
| 732
| 2.875
| 3
|
[] |
no_license
|
package blatt7;
public class SOMExample {
public static void main(String[] args) {
int n = 2;
int k = 2;
int fk = 16;
// 0.1 ≤ x1 ≤ 0.2 und a 0.1 ≤ x2 ≤ 0.5 und dem Bereich 0.7 ≤ x1 ≤ 0.9
// und 0.7 ≤ x2 ≤ 0.9
double[][] t1 = Utils.createTrainingPattern(100, 0.1, 0.2, 0.1, 0.5);
double[][] t2 = Utils.createTrainingPattern(100, 0.7, 0.9, 0.7, 0.9);
double[][] training = Utils.joinArrays(t1, t2);
NGAS ngas = new NGAS(n, k, fk, training);
for (int i = 0; i < 20; i++) {
ngas.trainNetwork(1000);
String filename = "pic" + i + ".png";
Utils.drawChart(ngas.lists, filename);
}
}
}
| true
|
97d337050558b657d4bd5c98a33e832aa6a94c6b
|
Java
|
AydinTokuslu/JAVA
|
/src/cesitli_soru_cozumleri/soru42_While.java
|
UTF-8
| 610
| 2.96875
| 3
|
[] |
no_license
|
package cesitli_soru_cozumleri;
import java.util.Scanner;
public class soru42_While {
public static void main(String[] args) {
// INTEGER OLAN PIN kodunuzu kontrol eden bir kod yazınız.
Scanner scan=new Scanner(System.in);
System.out.println("lutfen gecerli bir pin kodu giriniz");
int pinkodu=scan.nextInt();
int gercekpinkodu=6036;
while(pinkodu!=gercekpinkodu) {
System.out.println("*************** Yanlis PIN ****************");
System.out.println("tekrar deneyiniz");
pinkodu=scan.nextInt();
}
System.out.println("basariyla giris yapildi.");
}
}
| true
|
a954a15972a592c4bebaccd89adfa132463f873d
|
Java
|
bitcoinj/bitcoinj
|
/core/src/main/java/org/bitcoinj/base/internal/StreamUtils.java
|
UTF-8
| 1,549
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright by the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.bitcoinj.base.internal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Stream Utilities. Bitcoinj is moving towards functional-style programming, immutable data structures, and
* unmodifiable lists. Since we are currently limited to Java 8, this class contains utility methods that can simplify
* code in many places.
*/
public class StreamUtils {
/**
* Return a collector that collects a {@link Stream} into an unmodifiable list.
* <p>
* Java 10 provides {@code Collectors.toUnmodifiableList()} and Java 16 provides {@code Stream.toList()}.
* If those are not available, use this utility method.
*/
public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
return Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList);
}
}
| true
|
e5f508d8d0d6efb177b090ed658b9fcc633da795
|
Java
|
rkdas28899/capg-bvrit-b1-online-test-management-system
|
/otms-module/src/test/java/com/capg/otms/QuestionControllerTest.java
|
UTF-8
| 2,892
| 2.09375
| 2
|
[] |
no_license
|
package com.capg.otms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.capg.otms.question.model.Question;
import com.capg.otms.question.repository.QuestionRepository;
import com.capg.otms.question.service.QuestionServiceImpl;
public class QuestionControllerTest extends OtmsModuleApplicationTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Autowired
QuestionServiceImpl service;
@Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void testAddQuestion() throws Exception {
String url = "/questions/add";
String json = "{\r\n" + " \r\n" + " \"questionId\":\"990\",\r\n" + " \"questionTitle\":\"3+4\",\r\n"
+ " \"questionOption\":[\"0\",\"7\",\"4\",\"6\"],\r\n" + " \"questionAnswer\":7,\r\n"
+ " \"questionMarks\":5\r\n" + " \r\n" + "}";
mockMvc.perform(
post(url).contentType(MediaType.APPLICATION_JSON).content(json).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
public void testDeleteQuestion() throws Exception {
String url = "/question/delete/id/1011";
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.delete(url)).andReturn();
int status = mvcResult.getResponse().getStatus();
Question expected = service.deleteQuestion(1011);
if(expected!=null) {
assertEquals(status,200);
}
else{
assertEquals(status, 404);
}
}
@Test
public void testUpdateQuestion() throws Exception {
String url = "/question/update";
String json = "{\r\n" + " \r\n" + " \"questionId\":\"999\",\r\n" + " \"questionTitle\":\"3+4\",\r\n"
+ " \"questionOption\":[\"0\",\"7\",\"4\",\"6\"],\r\n" + " \"questionAnswer\":7,\r\n"
+ " \"questionMarks\":5\r\n" + " \r\n" + "}";
mockMvc.perform(
post(url).contentType(MediaType.APPLICATION_JSON).content(json).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void testGetListOfQuestions() {
List<Question> questionList=service.getListOfQuestions();
assertEquals(questionList.size(),10);
}
}
| true
|
4f7567ac0ddf15a075383d25b1a3ea939b716a1e
|
Java
|
Ckobar/TestTask
|
/TestTask/src/main/java/main/MainStartServer.java
|
WINDOWS-1251
| 1,944
| 2.375
| 2
|
[] |
no_license
|
package main;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import servlet.ServletForEntry;
import servlet.ServletForRegistration;
import javax.servlet.Servlet;
/**
* Created by on 22.09.2017.
* @author Alexey V.
*/
/**
* Create and run jetty-server
* on port 8080
*/
public class MainStartServer {
private static int PORT = 8080;
private static UserProfile ADMIN_USER = new UserProfile("admin","admin","anminSOBAKAadmin.ad");
private static UserProfile TEST_USER = new UserProfile("test","test","test@test.test");
public static void main(String[] args) throws Exception {
AccountService accountService = new AccountService();
accountService.addUser("admin",ADMIN_USER);
accountService.addUser("test",TEST_USER);
Servlet servletForEntry = new ServletForEntry(accountService);
Servlet servletForRegistration = new ServletForRegistration(accountService);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(servletForRegistration), "/registration");
context.addServlet(new ServletHolder(servletForEntry), "/entry");
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{"index.html"});
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
Server server = new Server(PORT);
server.setHandler(handlers);
server.start();
server.join();
}
}
| true
|
26bf53ec946b4464dc06627d357e6941159dfe89
|
Java
|
jvkalle/VSpemuellechat1
|
/app/src/main/java/com/example/vspemuellechat/ch/ethz/inf/vs/a3/udpclient/RetrieveTask.java
|
UTF-8
| 2,460
| 2.53125
| 3
|
[] |
no_license
|
package com.example.vspemuellechat.ch.ethz.inf.vs.a3.udpclient;
import android.os.AsyncTask;
import com.example.vspemuellechat.ch.ethz.inf.vs.a3.message.Message;
import com.example.vspemuellechat.ch.ethz.inf.vs.a3.message.MessageComparator;
import com.example.vspemuellechat.ch.ethz.inf.vs.a3.queue.PriorityQueue;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
public class RetrieveTask extends AsyncTask<String,Void, PriorityQueue<Message>> {
@Override
protected PriorityQueue<Message> doInBackground(String... params) {
int numtimeouts = MAX_TIMEOUTS;
String message = params[0];
Message msgReply = null;
JSONObject jsonReply;
byte[] recvBuf = new byte[256];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
byte[] sendBuf = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, ChatHelper.address, NetworkConsts.UDP_PORT);
PriorityQueue<Message> recvQueue = new PriorityQueue<Message>(new MessageComparator());
try {
ChatHelper.socket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
}
while (numtimeouts > 0) {
try {
ChatHelper.socket.receive(recvPacket);
} catch (IOException e) {
e.printStackTrace();
}
//Extract message from packet
String reply = new String(recvPacket.getData());
try {
jsonReply = new JSONObject(reply);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
try {
msgReply = new Message(jsonReply);
} catch (JSONException e) {
e.printStackTrace();
}
recvQueue.add(msgReply);
}
return recvQueue;
}
public interface ResponseHandler{
void HandleResponse(RetrieveTask task);
}
private static final int MAX_TIMEOUTS = 1;
private ResponseHandler callback;
public PriorityQueue<Message> result;
public RetrieveTask(ResponseHandler c){
this.callback = c;
}
@Override
protected void onPostExecute(PriorityQueue<Message> result) {
this.result = result;
this.callback.HandleResponse(this);
}
}
| true
|
a186ac041415c829ad7683554e283cb9f46cedcb
|
Java
|
yuanshuaif/SpringBoot
|
/src/main/java/com/lsj/springboot/rabbitMQ/rabbitMQ/topicExchange/ProducerMQ.java
|
UTF-8
| 1,614
| 2.828125
| 3
|
[] |
no_license
|
package com.lsj.springboot.rabbitMQ.rabbitMQ.topicExchange;
import com.lsj.springboot.rabbitMQ.rabbitMQ.util.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created by Administrator on 2019/2/21.
*/
public class ProducerMQ {
private static final String EXCHANGE_NAME = "ly_mq_exchange";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtil.getConnection();
// 3.从TCP连接里得到通信管道
Channel channel = connection.createChannel(1);
/**
* 4.绑定交换机
* 直连交换机
*/
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC, false);
/**
* 5.将队列绑定到交换机上
* 在RabbitMQ Management中实现绑定
*/
// 6.消息
/*String MessageA = "Hello World A";
String MessageB = "Hello World B";*/
// 7.往交换机里发送消息
channel.basicPublish(EXCHANGE_NAME, "A.C", null, "A.C".getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, "C.C", null, "C.C".getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, "A.B", null, "A.B".getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, "C.B", null, "C.B".getBytes("UTF-8"));
System.out.println("发送成功");
// 8.关闭管道
channel.close();
connection.close();
}
}
| true
|
11b013b74e8fb3c393c41b98c268d31458ba37f9
|
Java
|
babbaj/pepsimod
|
/src/main/java/net/daporkchop/pepsimod/module/impl/player/AutoEatMod.java
|
UTF-8
| 5,835
| 1.828125
| 2
|
[] |
no_license
|
/*
* Adapted from the Wizardry License
*
* Copyright (c) 2017 Team Pepsi
*
* Permission is hereby granted to any persons and/or organizations using this software to copy, modify, merge, publish, and distribute it.
* Said persons and/or organizations are not allowed to use the software or any derivatives of the work for commercial use or any other means to generate income, nor are they allowed to claim this software as their own.
*
* The persons and/or organizations are also disallowed from sub-licensing and/or trademarking this software without explicit permission from Team Pepsi.
*
* Any persons and/or organizations using this software must disclose their source code and have it publicly available, include this license, provide sufficient credit to the original authors of the project (IE: Team Pepsi), as well as provide a link to the original project.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.daporkchop.pepsimod.module.impl.player;
import net.daporkchop.pepsimod.module.ModuleCategory;
import net.daporkchop.pepsimod.module.api.Module;
import net.daporkchop.pepsimod.module.api.ModuleOption;
import net.daporkchop.pepsimod.module.api.OptionCompletions;
import net.daporkchop.pepsimod.module.api.option.ExtensionSlider;
import net.daporkchop.pepsimod.module.api.option.ExtensionType;
import net.daporkchop.pepsimod.util.ReflectionStuff;
import net.daporkchop.pepsimod.util.config.impl.AutoEatTranslator;
import net.minecraft.block.BlockContainer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemAppleGold;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.util.FoodStats;
public class AutoEatMod extends Module {
public static AutoEatMod INSTANCE;
{
INSTANCE = this;
}
public boolean doneEating = true;
public AutoEatMod() {
super("AutoEat");
}
@Override
public void onEnable() {
}
@Override
public void onDisable() {
if (mc.world != null) {
ReflectionStuff.setPressed(mc.gameSettings.keyBindUseItem, false);
}
doneEating = true;
}
@Override
public void tick() {
if (!shouldEat()) {
ReflectionStuff.setPressed(mc.gameSettings.keyBindUseItem, false);
doneEating = true;
return;
}
FoodStats foodStats = mc.player.getFoodStats();
if (foodStats.getFoodLevel() <= AutoEatTranslator.INSTANCE.threshold && shouldEat()) {
doneEating = false;
eatFood();
}
}
@Override
public void init() {
INSTANCE = this;
}
@Override
public ModuleOption[] getDefaultOptions() {
return new ModuleOption[]{
new ModuleOption<>(AutoEatTranslator.INSTANCE.threshold, "threshold", OptionCompletions.FLOAT,
(value) -> {
AutoEatTranslator.INSTANCE.threshold = Math.max(0, value);
return true;
},
() -> {
return AutoEatTranslator.INSTANCE.threshold;
}, "Threshold", new ExtensionSlider(ExtensionType.VALUE_FLOAT, 0f, 19f, 1f))
};
}
public ModuleCategory getCategory() {
return ModuleCategory.PLAYER;
}
private void eatFood() {
for (int slot = 44; slot >= 9; slot--) {
ItemStack stack = mc.player.inventoryContainer.getSlot(slot).getStack();
if (stack != null) {
if (slot >= 36 && slot <= 44) {
if (stack.getItem() instanceof ItemFood
&& !(stack.getItem() instanceof ItemAppleGold)) {
mc.player.inventory.currentItem = slot - 36;
ReflectionStuff.setPressed(mc.gameSettings.keyBindUseItem, true);
return;
}
} else if (stack.getItem() instanceof ItemFood
&& !(stack.getItem() instanceof ItemAppleGold)) {
int itemSlot = slot;
int currentSlot = mc.player.inventory.currentItem + 36;
mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player);
mc.playerController.windowClick(0, currentSlot, 0, ClickType.PICKUP, mc.player);
mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player);
return;
}
}
}
}
private boolean shouldEat() {
if (!mc.player.canEat(false)) {
return false;
}
if (mc.currentScreen != null) {
return false;
}
if (mc.currentScreen == null && mc.objectMouseOver != null) {
Entity entity = mc.objectMouseOver.entityHit;
if (entity instanceof EntityVillager || entity instanceof EntityTameable) {
return false;
}
if (mc.objectMouseOver.getBlockPos() != null && mc.world.getBlockState(mc.objectMouseOver.getBlockPos()).getBlock() instanceof BlockContainer) {
return false;
}
}
return true;
}
}
| true
|
e9e4cfddc6701f33182028ff5322c6b2a750fd4d
|
Java
|
kuxingsen/Reader-Android
|
/app/src/main/java/com/monk/reader/dao/ReadInfoDao.java
|
UTF-8
| 10,124
| 2.125
| 2
|
[] |
no_license
|
package com.monk.reader.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.monk.reader.dao.bean.ReadInfo;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "READ_INFO".
*/
public class ReadInfoDao extends AbstractDao<ReadInfo, Long> {
public static final String TABLENAME = "READ_INFO";
/**
* Properties of entity ReadInfo.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property BookId = new Property(1, Long.class, "bookId", false, "BOOK_ID");
public final static Property BookName = new Property(2, String.class, "bookName", false, "BOOK_NAME");
public final static Property BookAuthor = new Property(3, String.class, "bookAuthor", false, "BOOK_AUTHOR");
public final static Property BookSize = new Property(4, Long.class, "bookSize", false, "BOOK_SIZE");
public final static Property BookIntroduction = new Property(5, String.class, "bookIntroduction", false, "BOOK_INTRODUCTION");
public final static Property BookPicture = new Property(6, String.class, "bookPicture", false, "BOOK_PICTURE");
public final static Property CategoryName = new Property(7, String.class, "categoryName", false, "CATEGORY_NAME");
public final static Property Start = new Property(8, Long.class, "start", false, "START");
public final static Property Duration = new Property(9, Long.class, "duration", false, "DURATION");
public final static Property UpdateTime = new Property(10, Long.class, "updateTime", false, "UPDATE_TIME");
public final static Property UserId = new Property(11, Long.class, "userId", false, "USER_ID");
}
public ReadInfoDao(DaoConfig config) {
super(config);
}
public ReadInfoDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"READ_INFO\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"BOOK_ID\" INTEGER," + // 1: bookId
"\"BOOK_NAME\" TEXT," + // 2: bookName
"\"BOOK_AUTHOR\" TEXT," + // 3: bookAuthor
"\"BOOK_SIZE\" INTEGER," + // 4: bookSize
"\"BOOK_INTRODUCTION\" TEXT," + // 5: bookIntroduction
"\"BOOK_PICTURE\" TEXT," + // 6: bookPicture
"\"CATEGORY_NAME\" TEXT," + // 7: categoryName
"\"START\" INTEGER," + // 8: start
"\"DURATION\" INTEGER," + // 9: duration
"\"UPDATE_TIME\" INTEGER," + // 10: updateTime
"\"USER_ID\" INTEGER);"); // 11: userId
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"READ_INFO\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, ReadInfo entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
Long bookId = entity.getBookId();
if (bookId != null) {
stmt.bindLong(2, bookId);
}
String bookName = entity.getBookName();
if (bookName != null) {
stmt.bindString(3, bookName);
}
String bookAuthor = entity.getBookAuthor();
if (bookAuthor != null) {
stmt.bindString(4, bookAuthor);
}
Long bookSize = entity.getBookSize();
if (bookSize != null) {
stmt.bindLong(5, bookSize);
}
String bookIntroduction = entity.getBookIntroduction();
if (bookIntroduction != null) {
stmt.bindString(6, bookIntroduction);
}
String bookPicture = entity.getBookPicture();
if (bookPicture != null) {
stmt.bindString(7, bookPicture);
}
String categoryName = entity.getCategoryName();
if (categoryName != null) {
stmt.bindString(8, categoryName);
}
Long start = entity.getStart();
if (start != null) {
stmt.bindLong(9, start);
}
Long duration = entity.getDuration();
if (duration != null) {
stmt.bindLong(10, duration);
}
Long updateTime = entity.getUpdateTime();
if (updateTime != null) {
stmt.bindLong(11, updateTime);
}
Long userId = entity.getUserId();
if (userId != null) {
stmt.bindLong(12, userId);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, ReadInfo entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
Long bookId = entity.getBookId();
if (bookId != null) {
stmt.bindLong(2, bookId);
}
String bookName = entity.getBookName();
if (bookName != null) {
stmt.bindString(3, bookName);
}
String bookAuthor = entity.getBookAuthor();
if (bookAuthor != null) {
stmt.bindString(4, bookAuthor);
}
Long bookSize = entity.getBookSize();
if (bookSize != null) {
stmt.bindLong(5, bookSize);
}
String bookIntroduction = entity.getBookIntroduction();
if (bookIntroduction != null) {
stmt.bindString(6, bookIntroduction);
}
String bookPicture = entity.getBookPicture();
if (bookPicture != null) {
stmt.bindString(7, bookPicture);
}
String categoryName = entity.getCategoryName();
if (categoryName != null) {
stmt.bindString(8, categoryName);
}
Long start = entity.getStart();
if (start != null) {
stmt.bindLong(9, start);
}
Long duration = entity.getDuration();
if (duration != null) {
stmt.bindLong(10, duration);
}
Long updateTime = entity.getUpdateTime();
if (updateTime != null) {
stmt.bindLong(11, updateTime);
}
Long userId = entity.getUserId();
if (userId != null) {
stmt.bindLong(12, userId);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public ReadInfo readEntity(Cursor cursor, int offset) {
ReadInfo entity = new ReadInfo( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1), // bookId
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // bookName
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // bookAuthor
cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // bookSize
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // bookIntroduction
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // bookPicture
cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // categoryName
cursor.isNull(offset + 8) ? null : cursor.getLong(offset + 8), // start
cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9), // duration
cursor.isNull(offset + 10) ? null : cursor.getLong(offset + 10), // updateTime
cursor.isNull(offset + 11) ? null : cursor.getLong(offset + 11) // userId
);
return entity;
}
@Override
public void readEntity(Cursor cursor, ReadInfo entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setBookId(cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1));
entity.setBookName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setBookAuthor(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setBookSize(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
entity.setBookIntroduction(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setBookPicture(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setCategoryName(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7));
entity.setStart(cursor.isNull(offset + 8) ? null : cursor.getLong(offset + 8));
entity.setDuration(cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9));
entity.setUpdateTime(cursor.isNull(offset + 10) ? null : cursor.getLong(offset + 10));
entity.setUserId(cursor.isNull(offset + 11) ? null : cursor.getLong(offset + 11));
}
@Override
protected final Long updateKeyAfterInsert(ReadInfo entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(ReadInfo entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(ReadInfo entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
| true
|
74e73ac8dea6fb6d25443c819f793e58d468bda3
|
Java
|
iuri-mardegan/readfile
|
/src/main/java/com/br/readfile/modelo/Venda.java
|
UTF-8
| 582
| 2.546875
| 3
|
[] |
no_license
|
package com.br.readfile.modelo;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class Venda implements Comparable<Venda> {
private Integer saleId;
private List<Item> itemList;
private String salesmanName;
@Override
public int compareTo(Venda o) {
return (this.itemList.stream().map(i -> i.getPrice())
.reduce(0.0, Double::sum)
.compareTo(
o.getItemList().stream().map(i -> i.getPrice())
.reduce(0.0, Double::sum)));
}
}
| true
|
2f76c9225e6b7086875c904c57e2c09b3ccd9946
|
Java
|
zpf996/Online_Education
|
/src/dao/imp/UsersDaoImp.java
|
UTF-8
| 2,842
| 2.703125
| 3
|
[] |
no_license
|
package dao.imp;
import bean.Users;
import dao.UsersDao;
import util.DBconn;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UsersDaoImp implements UsersDao {
@Override
public boolean login(String name, String pwd) {
boolean flag = false;
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from users where User_ID='"+name+"' and password='"+pwd+"'");
while(rs.next()){
if(rs.getString("User_ID").equals(name) && rs.getString("password").equals(pwd)){
flag = true;
}
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
@Override
public boolean register(Users user) {
boolean flag = false;
DBconn.init();
int i =DBconn.addUpdDel("insert into users (User_ID,Password,User_Type,Full_Name,User_Email,User_ContactNumber) "+
"values('"+user.getId()+"" +
"','"+user.getPassword()+"" +
"','"+user.getUser_type()+"" +
"','"+user.getName()+"" +
"','"+user.getEmail()+"" +
"','"+user.getPhone()+""+
"')");
if(i>0){
flag = true;
}
else{
System.out.println("insert error");
}
DBconn.closeConn();
return flag;
}
@Override
public List<Users> getUserAll() {
List<Users> list = new ArrayList<Users>();
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from users");
while(rs.next()){
Users users=new Users();
users.setId(rs.getString("User_ID"));
users.setPassword(rs.getString("Password"));
users.setUser_type(rs.getString("User_Type"));
users.setName(rs.getString("Full_Name"));
users.setEmail(rs.getString("User_Email"));
users.setPhone(rs.getString("User_ContactNumber"));
list.add(users);
}
DBconn.closeConn();
return list;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public boolean delete(String id) {
boolean flag = false;
DBconn.init();
String sql = "delete from users where User_ID="+id;
int i =DBconn.addUpdDel(sql);
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
@Override
public boolean update(String id, String pwd, String type, String name, String email, String phone) {
return false;
}
}
| true
|
238beb742b109edccb35fd82ba77caf45e2930d8
|
Java
|
ccchp/Projects
|
/LexAccountingApp/src/com/lex/accounting/xmlparser/CategoryXmlPullParser.java
|
UTF-8
| 4,118
| 2.328125
| 2
|
[] |
no_license
|
package com.lex.accounting.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.lex.accounting.entity.ParentCategoryEntity;
import com.lex.accounting.entity.SubCategoryEntity;
import android.content.Context;
import android.util.Log;
import android.util.Xml;
public class CategoryXmlPullParser {
public static List<ParentCategoryEntity> getDefaultIncomeCategoryList(Context context){
XmlPullParser parser = Xml.newPullParser();
InputStream is;
List<ParentCategoryEntity> parentList = null;
List<SubCategoryEntity> subList = null;
String parentName = "";
ParentCategoryEntity parentEntity = null;
SubCategoryEntity subEntity = null;
try {
is = context.getAssets().open("default_income_category.xml");
parser.setInput(is, "UTF-8");
int event = parser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if(parser.getName().equals("income")){
parentList = new ArrayList<ParentCategoryEntity>();
}else if(parser.getName().equals("parent")){
parentEntity = new ParentCategoryEntity();
parentName = parser.getAttributeValue(0);
Log.i("lex", "parentName = " + parentName);
parentEntity.setName(parentName);
subList = new ArrayList<SubCategoryEntity>();
}else if(parser.getName().equals("sub")){
subEntity = new SubCategoryEntity();
subEntity.setName(parser.nextText());
Log.i("lex", "subName = " + subEntity.getName());
subList.add(subEntity);
event = parser.next();
}
break;
case XmlPullParser.END_TAG:
if(parser.getName().equals("parent")){
parentEntity.setSubList(subList);
parentList.add(parentEntity);
subList = null;
parentEntity = null;
}else if(parser.getName().equals("income")){
}
break;
default:
break;
}
event = parser.next();
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return parentList;
}
public static List<ParentCategoryEntity> getDefaultExpenditureCategoryList(Context context){
XmlPullParser parser = Xml.newPullParser();
InputStream is;
List<ParentCategoryEntity> parentList = null;
List<SubCategoryEntity> subList = null;
String parentName = "";
ParentCategoryEntity parentEntity = null;
SubCategoryEntity subEntity = null;
try {
is = context.getAssets().open("default_expenditure_category.xml");
parser.setInput(is, "UTF-8");
int event = parser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if(parser.getName().equals("expenditure")){
parentList = new ArrayList<ParentCategoryEntity>();
}else if(parser.getName().equals("parent")){
parentEntity = new ParentCategoryEntity();
parentName = parser.getAttributeValue(0);
Log.i("lex", "parentName = " + parentName);
parentEntity.setName(parentName);
subList = new ArrayList<SubCategoryEntity>();
}else if(parser.getName().equals("sub")){
subEntity = new SubCategoryEntity();
subEntity.setName(parser.nextText());
Log.i("lex", "subName = " + subEntity.getName());
subList.add(subEntity);
event = parser.next();
}
break;
case XmlPullParser.END_TAG:
if(parser.getName().equals("parent")){
parentEntity.setSubList(subList);
parentList.add(parentEntity);
subList = null;
parentEntity = null;
}else if(parser.getName().equals("expenditure")){
}
break;
default:
break;
}
event = parser.next();
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return parentList;
}
}
| true
|
69c72e68c5f0adb0db305acabd3bba2db05cfe48
|
Java
|
subagarw/digitalbanking-paymentsservice
|
/src/main/java/com/capg/paymentservices/service/PaymentService.java
|
UTF-8
| 311
| 1.953125
| 2
|
[] |
no_license
|
package com.capg.paymentservices.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.capg.paymentservices.model.Biller;
import com.capg.paymentservices.model.Customer;
@Service
public interface PaymentService {
public List<Biller> getBillers(Customer customer);
}
| true
|
a94933930d1e3375e289e2cf8a41f6ddcfef3c34
|
Java
|
dmitrygorsky/InstaTest
|
/src/main/java/service/DialogService.java
|
UTF-8
| 1,291
| 2.3125
| 2
|
[] |
no_license
|
package service;
import page.AccountPage;
import org.openqa.selenium.NoSuchElementException;
public class DialogService extends BaseService {
private AccountPage accountPage;
private static final String notifications = "Turn on Notifications";
public boolean isNotificationsDialogDisplayed() {
accountPage = new AccountPage();
try {
accountPage.getDialogWindow();
} catch (NoSuchElementException nsee) {
return false;
}
return true;
}
public boolean isThisDialogNotifications() {
accountPage = new AccountPage();
if(isNotificationsDialogDisplayed()) {
if (accountPage.getDialogWindowText().equalsIgnoreCase(notifications)) {
return true;
}
}
return false;
}
public boolean isBlockerDialogClickable() {
accountPage = new AccountPage();
try {
accountPage.clickBlockerDialogWindowOKButton();
} catch (NoSuchElementException nsee) {
return false;
}
return true;
}
public void skipNoticiationsDialog() {
accountPage = new AccountPage();
if (isThisDialogNotifications()) {
accountPage.clickNotNowButton();
}
}
}
| true
|
adab49464d63ec473792855a45b976d9360d91a7
|
Java
|
gcVulpes/java_practise
|
/server/src/main/com/vulpes/base/commonsLogging.java
|
UTF-8
| 578
| 2.453125
| 2
|
[] |
no_license
|
package vulpes.base;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
/**
* commonsLogging 是 apache commons类库中的一员 可提供基本的日志功能 并能灵活的选择使用jdk默认的日志 或是 log4j提供的日志
* Created by kadokawa on 25/10/17.
*/
public class commonsLogging {
private static Log log = LogFactory.getLog(commonsLogging.class);
@Test
public void test(){
log.debug("debug()...");
log.error("error()...");
log.info("info()...");
}
}
| true
|
6936dbb33d7eb531c6182361446b684de3732abe
|
Java
|
ShreckYe/Huawei-Code-Craft-2019
|
/Preliminary/code/CodeCraft-2019/src/main/java/com/huawei/data/CarAnswer.java
|
UTF-8
| 324
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.huawei.data;
public class CarAnswer {
private Car car;
private Answer answer;
public CarAnswer(Car car, Answer answer) {
this.car = car;
this.answer = answer;
}
public Car getCar() {
return car;
}
public Answer getAnswer() {
return answer;
}
}
| true
|
ec3b45e4a30118d3a6506c3f095938bbac9a1bd3
|
Java
|
Julia-Khramyshkina/homeworks
|
/numerical analysis second semester/task1/src/task1.java
|
UTF-8
| 7,046
| 2.625
| 3
|
[] |
no_license
|
import java.lang.Math;
/**
* Created by Юлия on 08.03.2016.
*/
public class task1
{
static double[][] A = {
{3.278164e-8, 1.046583, -1.378574, -0.527466},
{1.046583, 2.975937, 0.934251, 2.526877},
{-1.378574, 0.934251, 4.836173, 5.165441}};
static double[][] A1 = {
{3.278164e-8, 1.046583, -1.378574, -0.527466},
{1.046583, 2.975937, 0.934251, 2.526877},
{-1.378574, 0.934251, 4.836173, 5.165441}};
static double[][] D = {
{7.35272, 0.88255, -2.270052, 1, 0, 0},
{0.88255, 5.58351, 0.528167, 0, 1, 0},
{-2.27005, 0.528167, 4.430329, 0, 0, 1}};
static double[][] D1 = {
{7.35272, 0.88255, -2.270052, 1, 0, 0},
{0.88255, 5.58351, 0.528167, 0, 1, 0},
{-2.27005, 0.528167, 4.430329, 0, 0, 1}};
static double[][] check = {
{1, 2, 3},
{4, 5, 6}, {7, 8, 9}};
static double[][] C = {{7.35272, 0.88255, -2.270052, 1},
{0.88255, 5.58351, 0.528167, 0},
{-2.27005, 0.528167, 4.430329, 0}};
static double eps = 0.000001;
static double[][] Gauss1(double[][] m, int size)
{
for (int k = 0; k < size; k++)
{
double a = m[k][k];
if (Math.abs(a) < eps)
{
System.out.println("Too small " + k + " : " + a);
}
for (int j = k; j < size + 1; j++)
{
m[k][j] /= a;
}
for (int j = k + 1; j < size + 1; j++)
{
for (int i = 0; i < k; i++)
m[k][i] = 0;
for (int i = k + 1; i < size; i++)
m[i][j] -= m[k][j] * m[i][k];
}
}
return m;
}
static double[][] Gauss2(double[][] m, int size)
{
int[] changList = new int[size];
for (int k = 0; k < size; k++)
{
int numRow = findMaxInRow(m, k, size);
change(m, k, numRow, size);
changList[k] = numRow;
double a = m[k][k];
if (Math.abs(a) < eps)
{
System.out.println("Too small " + k + " : " + a);
}
for (int j = k; j < size + 1; j++)
{
m[k][j] /= a;
}
for (int j = k + 1; j < size + 1; j++)
{
for (int i = 0; i < k; i++)
m[k][i] = 0;
for (int i = k + 1; i < size; i++)
m[i][j] -= m[k][j] * m[i][k];
}
}
return m;
}
static double [][] inverse(double[][] m, int size)
{
for (int k = 0; k < size; k++)
{
double a = m[k][k];
if (Math.abs(a) < eps)
{
System.out.println("Too small " + k + " : " + a);
}
for (int j = k; j < size * 2; j++)
{
m[k][j] /= a;
}
for (int j = k + 1; j < size * 2; j++)
{
for (int i = 0; i < k; i++)
m[k][i] = 0;
for (int i = k + 1; i < size; i++)
m[i][j] -= m[k][j] * m[i][k];
}
}
return m;
}
static double[] resolve(double[][] m, int size)
{
double[] res = new double[size];
for (int i = size - 1; i >= 0; i--)
{
res[i] = m[i][size];
for (int j = i + 1; j < size; j++)
{
res[i] -= m[i][j] * res[j];
}
}
return res;
}
static double[][] otherMatrix(double[][] m, int size)
{
double [][] matrix = new double[size][size + 1];
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
matrix[i][j] = m[i][j];
}
}
return matrix;
}
static double[] otherResolve(double[][] newM, double[][] old, int size, int count)
{
for (int i = 0; i < size; ++i)
{
newM[i][size] = old[i][count];
}
double [] result = resolve(newM, 3);
return result;
}
static void inversePrint(double [][]m, int size)
{
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
System.out.print(m[j][i] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
// System.out.println("A:");
// print(A, 3);
// print(Gauss2(A, 3), 3);
// double[] res = resolve(A, 3);
// System.out.println("Result:");
// print(res, 3);
//
// System.out.println("Dif:");
// print(minus(res2, A1, 3), 3);
print(D, 3);
double [][] matrix = inverse(D, 3);
otherPrint(matrix, 3, 6);
double [][] newMatrix = otherMatrix(matrix, 3);
double [][]inverseMatrix = new double[3][3];
for (int i = 0 ; i < 3; ++i)
{
inverseMatrix[i] = otherResolve(newMatrix, matrix, 3, i + 3);
}
inversePrint(inverseMatrix, 3);
}
static void print(double[][] m, int size)
{
for (int j = 0; j < size; j++)
{
for (int i = 0; i < size * 2; i++)
{
System.out.print(m[j][i] + " ");
}
System.out.println();
}
System.out.println();
}
static void otherPrint(double[][] m, int one, int two)
{
for (int i = 0; i < one; i++)
{
for (int j = 0; j < two; j++)
{
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
static void print(double[] m, int size)
{
for (int j = 0; j < size; j++)
{
System.out.print(m[j] + " ");
}
System.out.println();
System.out.println();
}
static int findMaxInRow(double[][] m, int k, int size)
{
double max = Math.abs(m[k][k]);
int res = k;
for (int i = k + 1; i < size; i++)
{
if (max != Math.max(max, Math.abs(m[k][i])))
{
res = i;
max = Math.abs(Math.max(max, m[k][i]));
}
}
return res;
}
static double[] mult(double[][] m, double[] mul, int size) {
double[] res = new double[size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
res[i] += m[i][j] * mul[j];
}
}
return res;
}
static void change(double[][] m, int k, int numRow, int size)
{
for (int i = 0; i < size + 1; i++)
{
double a = m[k][i];
m[k][i] = m[numRow][i];
m[numRow][i] = a;
}
}
static double[] minus(double[] m, double[][] res, int size)
{
for (int i = 0; i < size; i++)
{
m[i] = m[i] - res[i][size];
}
return m;
}
}
| true
|
2215ca8de23100dac00502677f94f989db003c82
|
Java
|
HeMarchioni/Personal_API_Rest_DIO
|
/src/test/java/one/digitalInovation/personaApi/utils/PersonUtils.java
|
UTF-8
| 1,318
| 2.34375
| 2
|
[] |
no_license
|
package one.digitalInovation.personaApi.utils;
import one.digitalInovation.personaApi.model.dto.request.PersonDTO;
import one.digitalInovation.personaApi.model.entity.person.Person;
import java.time.LocalDate;
import java.util.Collections;
public class PersonUtils {
private static final String FIRST_NAME = "Rodrigo";
private static final String LAST_NAME = "Peleias";
private static final String CPF_NUMBER = "369.333.878-79";
private static final long PERSON_ID = 1L;
public static final LocalDate BIRTH_DATE = LocalDate.of(2010, 10, 1);
public static PersonDTO createFakeDTO() {
return PersonDTO.builder()
.nm_FirstName(FIRST_NAME)
.nm_LastName(LAST_NAME)
.cd_Cpf(CPF_NUMBER)
.dt_BirthDate("04-04-2010")
.phones(Collections.singletonList(PhoneUtils.createFakeDTO()))
.build();
}
public static Person createFakeEntity() {
return Person.builder()
.cd_Person(PERSON_ID)
.nm_FirstName(FIRST_NAME)
.nm_LastName(LAST_NAME)
.cd_Cpf(CPF_NUMBER)
.dt_BirthDate(BIRTH_DATE)
.phones(Collections.singletonList(PhoneUtils.createFakeEntity()))
.build();
}
}
| true
|
6ddb72fca7823931865cf8299bbf708fcd860f8f
|
Java
|
Ernestooo/workspace
|
/ECTS/src/ECTS.java
|
UTF-8
| 62
| 1.773438
| 2
|
[] |
no_license
|
public class ECTS {
private int ECTS;
private int number
}
| true
|
9ae99ac30e6855fa22298ae19548062aef20aa91
|
Java
|
inur93/pop-booking
|
/pop-booking-api/src/dk/knet/pop/booking/exceptions/BadloginException.java
|
UTF-8
| 163
| 1.929688
| 2
|
[] |
no_license
|
package dk.knet.pop.booking.exceptions;
public class BadloginException extends Throwable {
public BadloginException(String msg) {
super(msg);
}
}
| true
|
1e3b2dcd98346846ebfc6a88ff860a0152caac23
|
Java
|
PertsevRoman/kafka-viewer
|
/backend/kafka-producer/src/test/java/com/kafka/viewer/producer/MessageSenderTest.java
|
UTF-8
| 3,533
| 2.1875
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
package com.kafka.viewer.producer;
import com.kafka.viewer.generator.OrderGenerator;
import com.kafka.viewer.generator.RecordGenerator;
import com.kafka.viewer.generator.loader.GeneratorLoader;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.LongSerializer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test message sending
*/
class MessageSenderTest {
private final LongSerializer longSerializer = new LongSerializer();
private final AvroSerializer<SpecificRecordBase> avroSerializer =
new AvroSerializer<>();
// Records count
private Long count = 100L;
// ID boundary
private Long idMin = 0L;
// Timestamp boundary
private Long timestampMin = 10000L;
private Long timestampMax = 50000L;
// Orders stream
private Stream<? extends SpecificRecordBase> ordersStream;
private MockProducer<Long, SpecificRecordBase> producer;
private List<ProducerRecord<Long, SpecificRecordBase>> history;
private String topicName = "orders-topic";
private String generatorClass;
private RecordGenerator avroRecordsGenerator;
private Stream<? extends ProducerRecord<Long, SpecificRecordBase>> producerRecordStream;
@BeforeEach
void setUp() throws IllegalAccessException, InvocationTargetException,
InstantiationException, ClassNotFoundException {
generatorClass = "com.kafka.viewer.generator.OrderGenerator";
avroRecordsGenerator =
GeneratorLoader.loadGenerator(generatorClass);
Properties generatorProperties = new Properties();
generatorProperties.setProperty(OrderGenerator
.OrderGeneratorProperty.ID_MIN, String.valueOf(idMin));
generatorProperties.setProperty(OrderGenerator
.OrderGeneratorProperty.TIMESTAMP_MIN, String.valueOf(timestampMin));
generatorProperties.setProperty(OrderGenerator
.OrderGeneratorProperty.TIMESTAMP_MAX, String.valueOf(timestampMax));
generatorProperties.setProperty(OrderGenerator.OrderGeneratorProperty.COUNT,
String.valueOf(count));
ordersStream = avroRecordsGenerator.generateWith(generatorProperties);
producer = new MockProducer<>(
false,
null,
longSerializer,
avroSerializer
);
AvroRecordsGenerator generator = new AvroRecordsGenerator();
producerRecordStream = generator.recordStream(ordersStream, topicName);
MessageSender.send(producerRecordStream, producer);
history = producer.history();
}
@Test
@DisplayName("Producer send check")
void producerSendCheck() {
final long historySize = history.size();
assertThat(historySize)
.isEqualTo(count);
}
@Test
@DisplayName("Producer content check")
void producerContentCheck() {
history
.stream()
.map(ProducerRecord::topic)
.forEach(recordTopic -> assertThat(recordTopic)
.isEqualTo(topicName));
}
}
| true
|
2ba8b2df57214539606485af90c6bbc96a61fcf5
|
Java
|
zhaonan11/Lan_bridge
|
/day_13.java
|
UTF-8
| 1,314
| 3.53125
| 4
|
[] |
no_license
|
/*01字串
问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。
输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
*/
public class day_13 {
public static void main(String[] args){
int count=0;
for(int a=0;a<=1;a++){
for(int b=0;b<=1;b++){
for(int c=0;c<=1;c++){
for(int d=0;d<=1;d++){
for(int e=0;e<=1;e++){
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
System.out.print(e);
System.out.println();
count++;
}
}
}
}
}
System.out.print(count);
}
}
| true
|
4969f90653d7c13975613abced7fe0d0e2bc5ca6
|
Java
|
jbhushan791/Algorithm
|
/Algorithm/src/main/java/jb/algorithm/arrays/ProductWithoutDivision.java
|
UTF-8
| 1,394
| 3.890625
| 4
|
[] |
no_license
|
package jb.algorithm.arrays;
/**
* @author jbhushan
*/
public class ProductWithoutDivision {
public static void main(String[] args){
int[] arr = {10,20,30,40};
product(arr);
System.out.println();
method2(arr);
}
public static void product(int[] arr) {
int[] leftProduct = new int[arr.length];
leftProduct[0] = 1;
for(int i =1; i< arr.length; i++){
leftProduct[i] = leftProduct[i-1]*arr[i-1];
}
int[] rightProduct = new int[arr.length];
rightProduct[arr.length-1]=1;
for(int i =arr.length-2; i>=0; i--){
rightProduct[i] = rightProduct[i+1] * arr[i+1];
}
for(int i =0; i< arr.length; i++){
arr[i] = rightProduct[i] *leftProduct[i];
}
for(int i =0; i< arr.length; i++){
System.out.print(arr[i] +" ");
}
}
private static int[] method2(int[] nums){
int[] product = new int[nums.length];
product[0]=1;
for(int i=1; i< nums.length; i++){
product[i] = product[i-1] * nums[i-1];
}
int p =1;
for(int i=nums.length-1; i>=0; i--){
product[i] = product[i] * p;
p *= nums[i];
}
for(int i =0; i< nums.length; i++){
System.out.print(nums[i] +" ");
}
return product;
}
}
| true
|
641d3eae6925e9ee53cc6e5f99d95db0f17dedaa
|
Java
|
WuBaoqian1997/MyWareHouse
|
/HomeSys/src/cn/bdqn/HomeSys/dao/impl/RoomtypeDaoImpl.java
|
GB18030
| 3,588
| 2.328125
| 2
|
[] |
no_license
|
/**
* @Title: RoomtypeDaoImpl.java
* @Package cn.bdqn.HomeSys.dao.impl
* @Description: TODO÷Ҫã
* @author A18ccms A18ccms_gmail_com
* @date 2017-7-24 4:14:50
* @version V1.0
*/
package cn.bdqn.HomeSys.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.bdqn.HomeSys.dao.IRoomtypeDao;
import cn.bdqn.HomeSys.entity.Roomtype;
/**
*
* ĿƣHomeSys
* ƣRoomtypeDaoImpl
*
* ˣSun Zhong Tian
* ʱ䣺2017-7-24 4:14:50
* ˣSun Zhong Tian
* ʱ䣺2017-7-24 4:14:50
* ıע
* @version
*
*/
public class RoomtypeDaoImpl extends HibernateDaoSupport implements
IRoomtypeDao {
/**( Javadoc)
* <p>Title: savaRoomtype</p>
* <p>Description(): </p>
* @param roomtype
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#savaRoomtype(cn.bdqn.HomeSys.entity.Roomtype)
*/
@Override
public void savaRoomtype(Roomtype roomtype) {
// TODO Auto-generated method stub
this.getHibernateTemplate().save(roomtype);
}
/**( Javadoc)
* <p>Title: updateRoomtype</p>
* <p>Description(): </p>
* @param roomtype
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#updateRoomtype(cn.bdqn.HomeSys.entity.Roomtype)
*/
@Override
public void updateRoomtype(Roomtype roomtype) {
// TODO Auto-generated method stub
this.getHibernateTemplate().update(roomtype);
}
/**( Javadoc)
* <p>Title: delRoomtype</p>
* <p>Description(): </p>
* @param roomtype
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#delRoomtype(cn.bdqn.HomeSys.entity.Roomtype)
*/
@Override
public void delRoomtype(Roomtype roomtype) {
// TODO Auto-generated method stub
this.getHibernateTemplate().delete(roomtype);
}
/**( Javadoc)
* <p>Title: getRoomtypeById</p>
* <p>Description(): </p>
* @param roomtypeId
* @return
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#getRoomtypeById(java.lang.Integer)
*/
@Override
public Roomtype getRoomtypeById(Integer roomtypeId) {
// TODO Auto-generated method stub
return this.getHibernateTemplate().get(Roomtype.class, roomtypeId);
}
/**( Javadoc)
* <p>Title: getRoomtypeList</p>
* <p>Description(): </p>
* @return
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#getRoomtypeList()
*/
@Override
public List<Roomtype> getRoomtypeList() {
// TODO Auto-generated method stub
Session session = this.getSession();
String hql="from Roomtype";
return session.createQuery(hql).list();
}
/**( Javadoc)
* <p>Title: getRoomtypeList</p>
* <p>Description(): </p>
* @return
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#getRoomtypeList()
*/
@Override
public List<Roomtype> getRoomtypeList(int first,int size) {
// TODO Auto-generated method stub
DetachedCriteria dc = DetachedCriteria.forClass(Roomtype.class);
return this.getHibernateTemplate().findByCriteria(dc, first, size);
}
/**
* ( Javadoc)
* <p>Title: getRoomtypeCount</p>
* <p>Description(): </p>
* @return
* @see cn.bdqn.HomeSys.dao.IRoomtypeDao#getRoomtypeCount()
*/
@Override
public int getRoomtypeCount() {
// TODO Auto-generated method stub
return ((Number)this.getHibernateTemplate().find("select count(*) from Roomtype").listIterator().next()).intValue();
}
@Override
public List<Roomtype> getAllRoomType() {
// TODO Auto-generated method stub
return this.getSession().createQuery("from Roomtype").list();
}
}
| true
|
d22fde17f5cd150525af114839b4dbfcfadf1261
|
Java
|
sival19/Mystudies
|
/OOP2/Lagersystem/src/Inventory.java
|
UTF-8
| 892
| 3.515625
| 4
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Date;
public class Inventory {
//inventory attribute
private ArrayList<Item>items;
Inventory (ArrayList<Item> items) {
this.items=items;
}
Inventory() {
this(new ArrayList<Item>());
}
//item adder
public void addItem (Item item) {
if (!items.contains(item)) {
items.add(item);
}
}
// item remover
public void removeItem (Item item) {
items.remove(item);
}
//get total inventory value
public double getInventoryValue() {
double total = 0.0;
for(Item item : items) {
total += item.getPrice();
}
return total;
}
public void printInventory(){
System.out.println("Inventory");
for (Item item : items) {
System.out.println(" - " + item);
}
}
}
| true
|
648c99c1718459a9ebb1061609cd5b9fdedcda10
|
Java
|
mattfrancis888/Airbnb
|
/app/src/main/java/com/example/toshiba/airbnb/Explore/POJO/POJOListingData.java
|
UTF-8
| 11,390
| 2.046875
| 2
|
[] |
no_license
|
package com.example.toshiba.airbnb.Explore.POJO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by TOSHIBA on 18/09/2017.
*/
public class POJOListingData {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("user_id")
@Expose
private Integer user_id;
@SerializedName("property_ownership")
@Expose
private String propertyOwnership;
@SerializedName("property_type")
@Expose
private String propertyType;
@SerializedName("total_guest")
@Expose
private String totalGuest;
@SerializedName("total_bedrooms")
@Expose
private String totalBedrooms;
@SerializedName("total_beds")
@Expose
private String totalBeds;
@SerializedName("total_bathrooms")
@Expose
private String totalBathrooms;
@SerializedName("bathroom_type")
@Expose
private String bathroomType;
@SerializedName("country")
@Expose
private String country;
@SerializedName("street")
@Expose
private String street;
@SerializedName("extra_place_details")
@Expose
private String extraPlaceDetails;
@SerializedName("city")
@Expose
private String city;
@SerializedName("state")
@Expose
private String state;
@SerializedName("lng")
@Expose
private String lng;
@SerializedName("lat")
@Expose
private String lat;
@SerializedName("essentials")
@Expose
private Integer essentials;
@SerializedName("internet")
@Expose
private Integer internet;
@SerializedName("shampoo")
@Expose
private Integer shampoo;
@SerializedName("hangers")
@Expose
private Integer hangers;
@SerializedName("tv")
@Expose
private Integer tv;
@SerializedName("heating")
@Expose
private Integer heating;
@SerializedName("air_conditioning")
@Expose
private Integer airConditioning;
@SerializedName("breakfast")
@Expose
private Integer breakfast;
@SerializedName("kitchen")
@Expose
private Integer kitchen;
@SerializedName("laundry")
@Expose
private Integer laundry;
@SerializedName("parking")
@Expose
private Integer parking;
@SerializedName("elevator")
@Expose
private Integer elevator;
@SerializedName("pool")
@Expose
private Integer pool;
@SerializedName("gym")
@Expose
private Integer gym;
@SerializedName("place_description")
@Expose
private String placeDescription;
@SerializedName("place_title")
@Expose
private String placeTitle;
@SerializedName("suitable_for_children")
@Expose
private Integer suitableForChildren;
@SerializedName("suitable_for_infants")
@Expose
private Integer suitableForInfants;
@SerializedName("suitable_for_pets")
@Expose
private Integer suitableForPets;
@SerializedName("smoking_allowed")
@Expose
private Integer smokingAllowed;
@SerializedName("parties_allowed")
@Expose
private Integer partiesAllowed;
@SerializedName("additional_rules")
@Expose
private String additionalRules;
@SerializedName("listing_length")
@Expose
private String listingLength;
@SerializedName("arrive_after")
@Expose
private String arriveAfter;
@SerializedName("leave_before")
@Expose
private String leaveBefore;
@SerializedName("min_stay")
@Expose
private String minStay;
@SerializedName("max_stay")
@Expose
private String maxStay;
@SerializedName("price")
@Expose
private String price;
@SerializedName("date_listed")
@Expose
private String dateListed;
@SerializedName("image_data")
@Expose
private List<POJOListingImageData> imageData = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return user_id;
}
public void setUserId(Integer user_id) {
this.user_id = user_id;
}
public String getPropertyOwnership() {
return propertyOwnership;
}
public void setPropertyOwnership(String propertyOwnership) {
this.propertyOwnership = propertyOwnership;
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public String getTotalGuest() {
return totalGuest;
}
public void setTotalGuest(String totalGuest) {
this.totalGuest = totalGuest;
}
public String getTotalBedrooms() {
return totalBedrooms;
}
public void setTotalBedrooms(String totalBedrooms) {
this.totalBedrooms = totalBedrooms;
}
public String getTotalBeds() {
return totalBeds;
}
public void setTotalBeds(String totalBeds) {
this.totalBeds = totalBeds;
}
public String getTotalBathrooms() {
return totalBathrooms;
}
public void setTotalBathrooms(String totalBathrooms) {
this.totalBathrooms = totalBathrooms;
}
public String getBathroomType() {
return bathroomType;
}
public void setBathroomType(String bathroomType) {
this.bathroomType = bathroomType;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getExtraPlaceDetails() {
return extraPlaceDetails;
}
public void setExtraPlaceDetails(String extraPlaceDetails) {
this.extraPlaceDetails = extraPlaceDetails;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public Integer getEssentials() {
return essentials;
}
public void setEssentials(Integer essentials) {
this.essentials = essentials;
}
public Integer getInternet() {
return internet;
}
public void setInternet(Integer internet) {
this.internet = internet;
}
public Integer getShampoo() {
return shampoo;
}
public void setShampoo(Integer shampoo) {
this.shampoo = shampoo;
}
public Integer getHangers() {
return hangers;
}
public void setHangers(Integer hangers) {
this.hangers = hangers;
}
public Integer getTv() {
return tv;
}
public void setTv(Integer tv) {
this.tv = tv;
}
public Integer getHeating() {
return heating;
}
public void setHeating(Integer heating) {
this.heating = heating;
}
public Integer getAirConditioning() {
return airConditioning;
}
public void setAirConditioning(Integer airConditioning) {
this.airConditioning = airConditioning;
}
public Integer getBreakfast() {
return breakfast;
}
public void setBreakfast(Integer breakfast) {
this.breakfast = breakfast;
}
public Integer getKitchen() {
return kitchen;
}
public void setKitchen(Integer kitchen) {
this.kitchen = kitchen;
}
public Integer getLaundry() {
return laundry;
}
public void setLaundry(Integer laundry) {
this.laundry = laundry;
}
public Integer getParking() {
return parking;
}
public void setParking(Integer parking) {
this.parking = parking;
}
public Integer getElevator() {
return elevator;
}
public void setElevator(Integer elevator) {
this.elevator = elevator;
}
public Integer getPool() {
return pool;
}
public void setPool(Integer pool) {
this.pool = pool;
}
public Integer getGym() {
return gym;
}
public void setGym(Integer gym) {
this.gym = gym;
}
public String getPlaceDescription() {
return placeDescription;
}
public void setPlaceDescription(String placeDescription) {
this.placeDescription = placeDescription;
}
public String getPlaceTitle() {
return placeTitle;
}
public void setPlaceTitle(String placeTitle) {
this.placeTitle = placeTitle;
}
public Integer getSuitableForChildren() {
return suitableForChildren;
}
public void setSuitableForChildren(Integer suitableForChildren) {
this.suitableForChildren = suitableForChildren;
}
public Integer getSuitableForInfants() {
return suitableForInfants;
}
public void setSuitableForInfants(Integer suitableForInfants) {
this.suitableForInfants = suitableForInfants;
}
public Integer getSuitableForPets() {
return suitableForPets;
}
public void setSuitableForPets(Integer suitableForPets) {
this.suitableForPets = suitableForPets;
}
public Integer getSmokingAllowed() {
return smokingAllowed;
}
public void setSmokingAllowed(Integer smokingAllowed) {
this.smokingAllowed = smokingAllowed;
}
public Integer getPartiesAllowed() {
return partiesAllowed;
}
public void setPartiesAllowed(Integer partiesAllowed) {
this.partiesAllowed = partiesAllowed;
}
public String getAdditionalRules() {
return additionalRules;
}
public void setAdditionalRules(String additionalRules) {
this.additionalRules = additionalRules;
}
public String getListingLength() {
return listingLength;
}
public void setListingLength(String listingLength) {
this.listingLength = listingLength;
}
public String getArriveAfter() {
return arriveAfter;
}
public void setArriveAfter(String arriveAfter) {
this.arriveAfter = arriveAfter;
}
public String getLeaveBefore() {
return leaveBefore;
}
public void setLeaveBefore(String leaveBefore) {
this.leaveBefore = leaveBefore;
}
public String getMinStay() {
return minStay;
}
public void setMinStay(String minStay) {
this.minStay = minStay;
}
public String getMaxStay() {
return maxStay;
}
public void setMaxStay(String maxStay) {
this.maxStay = maxStay;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDateListed() {
return dateListed;
}
public void setDateListed(String dateListed) {
this.dateListed = dateListed;
}
public List<POJOListingImageData> getImageData() {
return imageData;
}
public void setImageData(List<POJOListingImageData> imageData) {
this.imageData = imageData;
}
}
| true
|
0160cc04949ae0b98ea3087ce1b27a78ebe31d99
|
Java
|
Dhjune/manage
|
/manage-modle/src/main/java/com/fanfan/manage/modle/base/Device.java
|
UTF-8
| 2,074
| 2.171875
| 2
|
[] |
no_license
|
package com.fanfan.manage.modle.base;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.DynamicInsert;
@Entity
@Table(name="APP_BASE_DEVICE")
@DynamicInsert(true)
public class Device {
@Id
@Column(name="DEVICE_KEY")
private String key;
@Column(name="DEVICE_NAME")
private String name;
@Column(name="DEVICE_OS")
private String os;
@Column(name="OS_VERSION")
private String osVersion;
@Column(name="MEMORY_SIZE")
private int memorySize;
@Column(name="HAS_CRACK")
private int hasCrack;
@Column(name="SCREEN_WIDTH")
private int screenWidth;
@Column(name="SCREEN_HEIGHT")
private int screenHeight;
@Column(name="CREATE_TIME",updatable=false)
@Temporal(TemporalType.TIME)
private Date createTime;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getOsVersion() {
return osVersion;
}
public void setOsVersion(String osVersion) {
this.osVersion = osVersion;
}
public int getMemorySize() {
return memorySize;
}
public void setMemorySize(int memorySize) {
this.memorySize = memorySize;
}
public int getHasCrack() {
return hasCrack;
}
public void setHasCrack(int hasCrack) {
this.hasCrack = hasCrack;
}
public int getScreenWidth() {
return screenWidth;
}
public void setScreenWidth(int screenWidth) {
this.screenWidth = screenWidth;
}
public int getScreenHeight() {
return screenHeight;
}
public void setScreenHeight(int screenHeight) {
this.screenHeight = screenHeight;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| true
|
a196bcc97a9abb877f0d6e4fef031e8927ac27b6
|
Java
|
fulyacetin/PhoneContactRecovery
|
/app/src/main/java/com/fulya/phonecontactrecovery/MainActivity.java
|
UTF-8
| 10,490
| 2.1875
| 2
|
[] |
no_license
|
package com.fulya.phonecontactrecovery;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView Contact_listView;
//first-look
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<ContactInformation> contactList=new ArrayList<ContactInformation>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?", new String[]{id}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new ContactInformation(name, phoneNumber));
}
}
Contact_listView = (ListView) findViewById(R.id.listView_Contact);
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter = new MyAdapter(this, R.layout.listview_item, contactList);
Contact_listView.setAdapter(adapter);
}
//Clicking listview_item
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent callActivity = new Intent(Intent.ACTION_DIAL, Uri.parse("tel: " + ((TextView) view.findViewById(R.id.contactPhoneNumber))
.getText().toString()));
startActivity(callActivity);
}
//chosing radio buttons
public void onRadioButtonClicked(View view) {
int id = view.getId();
List<ContactInformation> specialList=new ArrayList<>();
List<ContactInformation> contactList=new ArrayList<ContactInformation>();
ContentResolver ContentResolver = getContentResolver();
Cursor cursor = ContentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String idx = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = ContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?", new String[]{idx}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new ContactInformation(name, phoneNumber));
}
}
switch (id) {
case R.id.radioButtonAvea:
for(ContactInformation person:contactList){
if(person.getContactPhoneNumber().startsWith("+9055")||person.getContactPhoneNumber().startsWith("055")||
person.getContactPhoneNumber().startsWith("+9050")||person.getContactPhoneNumber().startsWith("050"))
specialList.add(person);
}
Contact_listView = (ListView) findViewById(R.id.listView_Contact);
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter1 = new MyAdapter(this, R.layout.listview_item, specialList);
Contact_listView.setAdapter(adapter1);
break;
case R.id.radioButtonTurkcell:
for (ContactInformation person : contactList) {
if (person.getContactPhoneNumber().startsWith("+9053")||person.getContactPhoneNumber().startsWith("053"))
specialList.add(person);
}
Contact_listView = (ListView) findViewById(R.id.listView_Contact);
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter = new MyAdapter(this, R.layout.listview_item, specialList);
Contact_listView.setAdapter(adapter);
break;
case R.id.radioButtonVodafone:
for(ContactInformation person:contactList){
if(person.getContactPhoneNumber().startsWith("+9054")||person.getContactPhoneNumber().startsWith("054"))
specialList.add(person);
}
Contact_listView = (ListView) findViewById(R.id.listView_Contact);
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter2 = new MyAdapter(this, R.layout.listview_item, specialList);
Contact_listView.setAdapter(adapter2);
break;
case R.id.radioButtonAll:
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter3 = new MyAdapter(this, R.layout.listview_item, contactList);
Contact_listView.setAdapter(adapter3);
break;
default:
break;
}
}
//backup
public void backUp(View view) throws FileNotFoundException {
List<ContactInformation> aList=new ArrayList<ContactInformation>();
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String idx = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?", new String[]{idx}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
aList.add(new ContactInformation(name, phoneNumber));
}
}
Contact_listView = (ListView) findViewById(R.id.listView_Contact);
Contact_listView.setOnItemClickListener(this);
MyAdapter adapter3 = new MyAdapter(this, R.layout.listview_item, aList);
Contact_listView.setAdapter(adapter3);
PrintStream printStream = new PrintStream(openFileOutput("backUp.txt", MODE_PRIVATE));
for (ContactInformation person :aList ) {
printStream.println(person.getContactName()+"/t"+person.getContactPhoneNumber());
}
Toast.makeText(this,"Succsesful Back-Up!",Toast.LENGTH_LONG).show();
}
//recovery
public void recover(View view) throws FileNotFoundException {
File file = new File(getFilesDir()+"/backUp.txt");
if (file.exists()==false)
Toast.makeText(this,"Back-up file is not found",Toast.LENGTH_LONG).show();
else {
Scanner scanner = new Scanner(openFileInput("backUp.txt"));
while (scanner.hasNextLine()) {
String personInformation[] = scanner.nextLine().split("/t");
String person_name = personInformation[0];
String person_phone = personInformation[1];
ArrayList<ContentProviderOperation> list = new ArrayList<ContentProviderOperation>();
list.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
if (person_name != null) {
list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, person_name).build());
}
if (person_phone != null) {
list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, person_phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
}
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, list);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Exception", Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(this,"Succsesful! You can go to Contacts",Toast.LENGTH_LONG).show();
}
}
}
| true
|
2aaf5845462d657ddf37c813e540a7dea6f8b382
|
Java
|
suriyanarayanan42/example
|
/src/test/java/com/studentpaymentapp/TestStaffValidate.java
|
UTF-8
| 583
| 2.015625
| 2
|
[] |
no_license
|
package com.studentpaymentapp;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestStaffValidate {
@Test
public void testMobNo() {
Staff.dispalyStaffList();
boolean isvalid=Staff.mobNoValidater("9500500452");
assertEquals(true,isvalid);
}
@Test
public void testPassword() {
boolean isvalid=Staff.passwordValidater("Harish1#");
assertEquals(true,isvalid);
}
@Test
public void testStudentValidate() {
boolean isvalid=Staff.validate("9003750359","Harish1#");
assertEquals(true,isvalid);
}
}
| true
|
270151a748813960d4b8657805dbe262eda3b6b6
|
Java
|
ManishaRana1195/AlgorithmsAndDataStrutures
|
/src/algorithms/graphs/WordLadder.java
|
UTF-8
| 3,787
| 3.703125
| 4
|
[] |
no_license
|
package algorithms.graphs;
import java.util.*;
public class WordLadder {
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
String[] dict = {"hot", "dot", "dog", "lot", "log", "cog"};
// String beginWord = "a";
// String endWord = "c";
// String[] dict = {"a", "b", "c"};
List<String> wordList = new ArrayList<>();
for (String string : dict) {
wordList.add(string);
}
int length = ladderLength(beginWord, endWord, wordList);
System.out.println(length);
}
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashMap<String, List<String>> base = getPatternMap(wordList);
HashMap<String, List<String>> patternStringMap = getPatternStringMap(base);
Map<String, Integer> isVisitedMap = new HashMap<>();
int ladderLength = 0;
isVisitedMap.put(beginWord, 1);
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
while (!queue.isEmpty()) {
String front = queue.poll();
List<String> neighbors = getNeighbor(front, patternStringMap);
for (String element : neighbors) {
if (!isVisitedMap.containsKey(element)) {
if (element.equals(endWord)) {
int currLevel = isVisitedMap.get(front);
return currLevel + 1;
}
queue.add(element);
isVisitedMap.put(element, isVisitedMap.get(front) + 1);
}
}
}
return ladderLength;
}
public static List<String> getNeighbor(String word, HashMap<String, List<String>> patternStringMap) {
List<String> neighbors = new ArrayList<>();
for (int i = 0; i < word.length(); i++) {
// add adjacent element to the list
String wordWithStar = word.substring(0, i) + "*" + word.substring(i + 1);
List<String> matchingPattern = patternStringMap.getOrDefault(wordWithStar, null);
if (matchingPattern != null) {
for (String element : matchingPattern) {
neighbors.add(element);
}
}
}
return neighbors;
}
private static HashMap<String, List<String>> getPatternStringMap(HashMap<String, List<String>> base) {
/*
* Creating map like *ot => dot, hot, got
* */
HashMap<String, List<String>> patternStringMap = new HashMap<>();
for (String key : base.keySet()) {
List<String> patternStrings = base.get(key);
for (String element : patternStrings) {
List<String> list = patternStringMap.getOrDefault(element, null);
if (list == null) {
list = new ArrayList<>();
}
list.add(key);
patternStringMap.put(element, list);
}
}
return patternStringMap;
}
private static HashMap<String, List<String>> getPatternMap(List<String> wordList) {
/*
* Creating map like cot => *ot, c*t, co*
* */
HashMap<String, List<String>> base = new HashMap<>();
for (String word : wordList) {
List<String> currList = base.get(word);
if (currList == null) {
currList = new ArrayList<>();
}
for (int i = 0; i < word.length(); i++) {
String wordWithStar = word.substring(0, i) + "*" + word.substring(i + 1);
currList.add(wordWithStar);
}
base.put(word, currList);
}
return base;
}
}
| true
|
9966fdf40d1c1fd1d379adc75202f2fb66cd6305
|
Java
|
epalace510/pushpin
|
/Pushpin_app/src/com/cloud/pushpin/NewAccount.java
|
UTF-8
| 3,159
| 2.515625
| 3
|
[] |
no_license
|
package com.cloud.pushpin;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class NewAccount extends FragmentActivity implements Serializable
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.accountinfo);
}
//submits info to be created
public void submit(View view) throws IOException
{
Map m;
boolean result;
final EditText savedText =(EditText)findViewById(R.id.message);
final EditText savedText2 =(EditText)findViewById(R.id.message1);
final EditText savedText3 =(EditText)findViewById(R.id.message2);
final EditText savedText4 =(EditText)findViewById(R.id.email);
String name = savedText.getText().toString().trim();
System.out.println(name);
String pass = savedText2.getText().toString().trim();
String repeatPass = savedText3.getText().toString().trim();
String email=savedText4.getText().toString().trim();
//checks to make sure the user has entered info
if(name.equals("") || pass.equals("") || repeatPass.equals(""))
{
Toast.makeText(getBaseContext(),"No information entered!", Toast.LENGTH_SHORT).show();
}
//checks to make sure there has been an email entered
if(savedText2.getText().toString().trim().equals(savedText3.getText().toString().trim()))
{
if(email.equals(""))
{
Toast.makeText(getBaseContext(),"No email entered!", Toast.LENGTH_SHORT).show();
}
//if email entered, checks against blank password/account name fields
else
{
if(savedText2.getText().toString().trim().equals("")||savedText3.getText().toString().trim().equals(""))
Toast.makeText( getBaseContext(),"Please make sure account name and password fields are not blank", Toast.LENGTH_SHORT).show();
else
{
Httpclass test = new Httpclass();
m = test.newlogin(savedText.getText().toString().trim(), savedText2.getText().toString().trim(),savedText4.getText().toString());
result=(Boolean)m.get("boolean");
System.out.println(m.get("access_token"));
if(result == true)
{
Toast.makeText( getBaseContext(),"Successfully made account", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MapActivity.class);
intent.putExtra("access_token", m.get("access_token").toString());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
else
Toast.makeText( getBaseContext(),"Failed to create account", Toast.LENGTH_SHORT).show();
}
}
}
//makes sure passwords are a match
else
{
Toast.makeText( getBaseContext(),"Passwords do not match.", Toast.LENGTH_SHORT).show();
}
}
//returns to login screen
public void cancel(View view) throws IOException
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
| true
|
ecc616c4d8cc98290b27a8538759ab455f2d1d9b
|
Java
|
cenkatahan/ContactList
|
/app/src/main/java/com/example/contactlist/MainActivity.java
|
UTF-8
| 883
| 1.953125
| 2
|
[] |
no_license
|
package com.example.contactlist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements ContactListFragmentT.Listener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void itemClicked(long id) {
//Add intent here to jump second activity
Intent intent = new Intent(this, ContactDetailActivity.class);
intent.putExtra(ContactDetailActivity.EXTRA_CONTACT_ID, (int) id);
startActivity(intent);
}
}
| true
|
d66b2355bcbd1c3003db925bca243ef3614af329
|
Java
|
Sacred27/Task-1
|
/src/java/Work/Factory.java
|
UTF-8
| 760
| 2.734375
| 3
|
[] |
no_license
|
package Work;
import Baza.Product;
public class Factory {
private static ProductW product = null;
private static StoreW store = null;
private static TranzactionW tranzaction = null;
private static Factory instance = null;
public static synchronized Factory getInstance(){
if (instance == null){
instance = new Factory();
}
return instance;
}
public ProductW getProductW(){
if (product == null){
product = new ProductW();
}
return product;
}
public StoreW getStoreW(){
if (store == null){
store = new StoreW();
}
return store;
}
public TranzactionW getTranzactionW(){
if (tranzaction == null){
tranzaction = new TranzactionW();
}
return tranzaction;
}
}
| true
|
ffeb3d1516c06ab9b54c16a05e2677f3ba26bb29
|
Java
|
BrunoHoffmann15/trab-lp-3-jpa
|
/MiniProjeto/src/Dominio/Bebida.java
|
UTF-8
| 928
| 2.4375
| 2
|
[] |
no_license
|
package Dominio;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "bebida")
public class Bebida {
private Long codBebida;
private String nome;
private double valor;
@Id
@GeneratedValue(generator = "inc")
@GenericGenerator(name = "inc", strategy = "increment")
@Column(name = "cod_bebida")
public Long getCodBebida() {
return codBebida;
}
public void setCodBebida(Long codBebida) {
this.codBebida = codBebida;
}
@Column(name = "nome", nullable = false)
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Column(name = "valor", nullable = false)
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
}
| true
|
b888a004dd9738c98042f347d7797f9f56d32766
|
Java
|
fengys1996/Nio
|
/Concurrency/src/main/java/com/mmall/concurrency/example/singleton/SingletonExample5.java
|
UTF-8
| 2,661
| 3.859375
| 4
|
[] |
no_license
|
package com.mmall.concurrency.example.singleton;
import com.mmall.concurrency.annoations.ThreadSafe;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* 懒汉模式 -》 双重同步锁单例模式
* 单例实例在第一次使用时进行创建
*/
@ThreadSafe
public class SingletonExample5 implements Serializable{
// 私有构造函数
private SingletonExample5() {
}
// 1、memory = allocate() 分配对象的内存空间
// 2、ctorInstance() 初始化对象
// 3、instance = memory 设置instance指向刚分配的内存
// 单例对象 volatile + 双重检测机制 -> 禁止指令重排
//volatitle 可见性 修饰的变量修改之后会被及时刷回主存中
private volatile static SingletonExample5 instance = null;
// 静态的工厂方法
public static SingletonExample5 getInstance() {
if (instance == null) { // 双重检测机制 // B
synchronized (SingletonExample5.class) { // 同步锁
if (instance == null) {
instance = new SingletonExample5(); // A - 3
}
}
}
return instance;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, ClassNotFoundException
{
//private constructor not safe
SingletonExample5 singleton1 = SingletonExample5.getInstance();
SingletonExample5 singleton2 = SingletonExample5.getInstance();
//return true
System.out.println(singleton1 == singleton2);
Constructor<SingletonExample5> constructor = SingletonExample5.class.getDeclaredConstructor();
constructor.setAccessible(true);
SingletonExample5 singletonReflect = constructor.newInstance();
//return false
//所以私有构造函数并不安全,可以通过反射进行对构造函数的访问
System.out.println(singleton1 == singletonReflect);
SingletonExample5 s = SingletonExample5.getInstance();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SerSingleton.obj"));
oos.writeObject(s);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("SerSingleton.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
SingletonExample5 s1 = (SingletonExample5)ois.readObject();
ois.close();
System.out.println(s+"\n"+s1);
System.out.println("序列化前后两个是否同一个:"+(s==s1));
}
}
| true
|
02750bbea7990c2aa8b10d232ee4347bbc95b22f
|
Java
|
GnomeGnoir/enjin-java-sdk
|
/sdk/src/main/java/com/enjin/sdk/ProjectClient.java
|
UTF-8
| 2,682
| 1.992188
| 2
|
[
"Apache-2.0"
] |
permissive
|
/* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enjin.sdk;
import com.enjin.sdk.schemas.project.ProjectSchema;
import com.enjin.sdk.utils.LoggerProvider;
import lombok.NonNull;
import okhttp3.OkHttpClient;
import java.util.concurrent.ExecutorService;
/**
* Client for using the project schema.
*
* @see EnjinHosts
*/
public final class ProjectClient extends ProjectSchema implements IClient {
/**
* Constructs a client with the targeted URL and default settings.
*
* @param baseUrl the base URL
*/
public ProjectClient(@NonNull String baseUrl) {
this(baseUrl, false);
}
/**
* Constructs a client with the targeted URL, debugging state.
*
* @param baseUrl the base URL
* @param debug whether debugging is enabled
*/
public ProjectClient(@NonNull String baseUrl, boolean debug) {
this(baseUrl, debug, null);
}
/**
* Constructs a client with the targeted settings.
*
* @param baseUrl the base URL
* @param debug whether debugging is enabled
* @param loggerProvider the logger provider
*/
public ProjectClient(@NonNull String baseUrl, boolean debug, LoggerProvider loggerProvider) {
super(new TrustedPlatformMiddleware(baseUrl, debug), loggerProvider);
}
@Override
public void auth(String token) {
middleware.getTrustedPlatformInterceptor().setToken(token);
}
@Override
public void close() {
OkHttpClient httpClient = middleware.getHttpClient();
ExecutorService executorService = httpClient.dispatcher().executorService();
if (!executorService.isShutdown()) {
executorService.shutdown();
httpClient.connectionPool().evictAll();
}
}
@Override
public boolean isAuthenticated() {
return middleware.getTrustedPlatformInterceptor().isAuthenticated();
}
@Override
public boolean isClosed() {
return middleware.getHttpClient()
.dispatcher()
.executorService()
.isShutdown();
}
}
| true
|
42ddeeaf129e08fe55859de93932046cdaa085cb
|
Java
|
jhpotter123/pilot_fish
|
/src/main/java/com/example/demo/xml/FishType.java
|
UTF-8
| 959
| 2.84375
| 3
|
[] |
no_license
|
package com.example.demo.xml;
/**
* Enumeration created for the Fish type. Note the specification
* doesn't call to write this to the database but I think this
* might have been an error. I wanted to stick to the speification
* but make the code extendable later and cliearly document where
* it would be added. See FishService.
*
* @author jeff
*/
public enum FishType {
Shark("Shark"),
Ray("Ray"),
Eel("Eel"),
Herring("Herring"),
SalmonTroutPike("Salmon/Trout/Pike"),
Carp("Carp"),
Catfish("Catfish"),
LanternFish("Lantern Fish"),
Cod("Cod"),
FlyingFish("Flying Fish"),
SquirrelFish("Squirrel Fish"),
PipefishSeahorse("Pipefish/Seahorse"),
Stonefish("Stonefish"),
FlatFish("Flat Fish"),
Puffer("Puffer"),
Perciforms("Perciforms");
public final String value;
private FishType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| true
|
142eeb407cbf08cf6f74d6f9aadca679a006f6cb
|
Java
|
heyams/opentelemetry-java-instrumentation
|
/instrumentation/apache-dubbo-2.7/library-autoconfigure/src/main/java/io/opentelemetry/instrumentation/apachedubbo/v2_7/internal/DubboNetServerAttributesGetter.java
|
UTF-8
| 1,120
| 1.757813
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.apachedubbo.v2_7.internal;
import io.opentelemetry.instrumentation.apachedubbo.v2_7.DubboRequest;
import io.opentelemetry.instrumentation.api.instrumenter.net.InetSocketAddressNetServerAttributesGetter;
import java.net.InetSocketAddress;
import javax.annotation.Nullable;
/**
* This class is internal and is hence not for public use. Its APIs are unstable and can change at
* any time.
*/
public final class DubboNetServerAttributesGetter
extends InetSocketAddressNetServerAttributesGetter<DubboRequest> {
@Nullable
@Override
public String getHostName(DubboRequest request) {
return null;
}
@Nullable
@Override
public Integer getHostPort(DubboRequest request) {
return null;
}
@Override
@Nullable
protected InetSocketAddress getPeerSocketAddress(DubboRequest request) {
return request.remoteAddress();
}
@Nullable
@Override
protected InetSocketAddress getHostSocketAddress(DubboRequest request) {
return request.localAddress();
}
}
| true
|
8863f592111cb5528b22f6f45f00a13103914ab1
|
Java
|
BrunoLoirim/ProjetosAndroids
|
/Exercicio4BrunoDias/app/src/main/java/faculdadedelta/edu/exercicio4brunodias/ValidacaoActivity.java
|
UTF-8
| 3,461
| 2.609375
| 3
|
[] |
no_license
|
package faculdadedelta.edu.exercicio4brunodias;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.text.ParseException;
public class ValidacaoActivity extends AppCompatActivity {
private TextView tvProduto;
private TextView tvValor;
private TextView tvFornecedor;
private TextView tvQuantidade;
private String produto;
private String valor;
private String fornecedor;
private String quantidade;
public static final int RESULT_CODE_SUCESS = 1;
public static final int RESULT_CODE_ERROR = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_validacao);
tvProduto = findViewById(R.id.tvProduto);
tvValor = findViewById(R.id.tvValor);
tvFornecedor = findViewById(R.id.tvFornecedor);
tvQuantidade = findViewById(R.id.tvQuantidade);
Intent intent = getIntent();
if (intent != null) {
produto = intent.getStringExtra("produtoParam");
valor = intent.getStringExtra("valorParam");
fornecedor = intent.getStringExtra("fornecedorParam");
quantidade = intent.getStringExtra("quantidadeParam");
tvProduto.setText("Produto: " + produto);
tvValor.setText("Valor: " + valor);
tvFornecedor.setText("Fornecedor: " + fornecedor);
tvQuantidade.setText("Quantidade: " + quantidade);
}
}
public String validarCampos() {
String mensagemErro = "";
if (produto.equals("")) {
mensagemErro = "Campo 'Produto' é obrigatório!";
}
if (valor.equals("")) {
mensagemErro += "\nCampo 'Valor' é obrigatório!";
}
if (fornecedor.equals("")) {
mensagemErro += "\nCampo 'Fornecedor' é obrigatório!";
}
if (quantidade.equals("")) {
mensagemErro += "\nCampo 'Produto' é obrigatório!";
}
return mensagemErro;
}
public void validar(View view) {
String mensagemValidacao = validarCampos();
double valorConvertido = 0;
long quantidadeConvertida = 0;
try {
valorConvertido = Double.parseDouble(valor);
quantidadeConvertida = Long.parseLong(quantidade);
} catch (NumberFormatException e){
e.printStackTrace();
}
if (mensagemValidacao.equals("")) {
if (valorConvertido < 500) {
mensagemValidacao = "O campo 'Valor' deve ser maior que 500";
}
else if (produto.length() <= 15) {
mensagemValidacao += "\nO campo 'Produto' deve ter mais de 15 caracters";
}
else if (fornecedor.length() <= 11) {
mensagemValidacao += "\nO campo 'Fornecedor' deve ter mais de 11 caracters";
}
else if (quantidadeConvertida <= 0) {
mensagemValidacao += "\nO campo 'Quantidade' deve ser maior que 0 (ZERO)";
} else {
mensagemValidacao = "Dados inseridos corretamentes!";
}
}
Intent intent = new Intent();
intent.putExtra("mensagemValidacao", mensagemValidacao);
setResult(RESULT_CODE_SUCESS, intent);
finish();
}
}
| true
|
884f0f799b882d70874e128da54d08ffceca755e
|
Java
|
chaitanya-sule/Chess
|
/chess-module/src/mainData/ChessFactory.java
|
UTF-8
| 1,902
| 3.390625
| 3
|
[] |
no_license
|
package mainData;
import java.util.List;
public class ChessFactory {
public static void main(String[] args) {
WhitePlayer whitePlayer = new WhitePlayer();
BlackPlayer blackPlayer = new BlackPlayer();
printChessBoard(whitePlayer, blackPlayer);
}
private static void printChessBoard(WhitePlayer whitePlayer, BlackPlayer blackPlayer) {
ChessBoard chessBoard = new ChessBoard();
placePlayerPiece(whitePlayer, blackPlayer, chessBoard);
chessBoard.print();
}
private static void placePlayerPiece(WhitePlayer whitePlayer, BlackPlayer blackPlayer, ChessBoard chessBoard) {
placeWhitePlayer(whitePlayer, chessBoard);
placeBlackPlayer(blackPlayer, chessBoard);
}
private static void placeBlackPlayer(BlackPlayer blackPlayer, ChessBoard chessBoard) {
blackPlayer.getBlackKing().placePiece(chessBoard);
blackPlayer.getBlackQueen().placePiece(chessBoard);
placeArrayOfPiece(blackPlayer.getBlackRooks(), chessBoard);
placeArrayOfPiece(blackPlayer.getBlackBishops(), chessBoard);
placeArrayOfPiece(blackPlayer.getBlackKnights(), chessBoard);
placeArrayOfPiece(blackPlayer.getBlackPawns(), chessBoard);
}
private static void placeWhitePlayer(WhitePlayer whitePlayer, ChessBoard chessBoard) {
whitePlayer.getWhiteQueen().placePiece(chessBoard);
whitePlayer.getWhiteKing().placePiece(chessBoard);
placeArrayOfPiece(whitePlayer.getWhiteRooks(), chessBoard);
placeArrayOfPiece(whitePlayer.getWhiteBishops(), chessBoard);
placeArrayOfPiece(whitePlayer.getWhiteKnights(), chessBoard);
placeArrayOfPiece(whitePlayer.getWhitePawns(), chessBoard);
}
private static void placeArrayOfPiece(List<? extends Piece> pieces, ChessBoard chessBoard) {
pieces.forEach(piece -> piece.placePiece(chessBoard));
}
}
| true
|
80cf851089b988a9994e4d72ba53dce8027b274d
|
Java
|
Aaron1375/my-Java-servlet
|
/Poly.Asg_Servlet/src/edu/poly/dao/ShareDAO.java
|
UTF-8
| 864
| 2.3125
| 2
|
[] |
no_license
|
package edu.poly.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import edu.poly.domain.ShareReport;
import edu.poly.model.Share;
public class ShareDAO extends AbstractEntityDAO<Share>{
public ShareDAO() {
super(Share.class);
}
public List<ShareReport> ReportShareByVideo(String videoId){
String jpql = "select new edu.poly.domain.ShareReport(s.user.username, s.user.email, s.video.videoId, s.sharedDate) "
+ "from Share s where s.video.videoId=:videoId ";
EntityManager em = JpaUtils.getEntityManager();
List<ShareReport> list = null;
try {
TypedQuery<ShareReport> query = em.createQuery(jpql, ShareReport.class);
query.setParameter("videoId", videoId);
list = query.getResultList();
} finally {
em.close();
}
return list;
}
}
| true
|
ca06947a7edf260030b484342ae6c03c76b9950b
|
Java
|
dmoore09/AdventureTime
|
/src/cs2114/adventure/PlayableRoomTest.java
|
UTF-8
| 1,884
| 3.390625
| 3
|
[] |
no_license
|
package cs2114.adventure;
/**
* // -------------------------------------------------------------------------
/**
* tests the PlayableRoom class
*
* @author dmoore09
* @version Jan 31, 2013
*/
public class PlayableRoomTest
extends student.TestCase
{
//fields for playable room and item to be used in testing
private PlayableRoom room;
private Item item;
/**
* initialize the fields
*/
public void setUp()
{
room = new PlayableRoom("Room for Testing", "TestRoom");
item = new Item("rock", 1.0, "small rock");
}
/**
* test the getName method
*/
public void testGetName()
{
assertEquals("TestRoom", room.getName());
}
/**
* test get items method
*/
public void testGetItems()
{
assertEquals(0, room.returnItems().size());
}
/**
* test add item by making sure an item can be added to the array
* items
*/
public void testAddItem()
{
room.addItem(item);
assertEquals(1, room.returnItems().size());
}
/**
* test remove item to make sure it works by adding an item then removing
* it
*/
public void testRemoveItem()
{
room.addItem(item);
room.removeItem("rock");
assertEquals(0, room.returnItems().size());
}
/**
* test remove item to make sure it works when searching for an item the is
* not present
*/
public void testRemoveItemF()
{
room.addItem(item);
room.removeItem("ball");
assertEquals(1, room.returnItems().size());
}
/**
* test getLonDescription() to make sure the right message is returned
*/
public void testGetLongDescription()
{
String expected = room.getLongDescription();
assertEquals(expected, room.getLongDescription());
}
}
| true
|
a8aff5eec01b2b0cadf67bc13877c0d3d85772ed
|
Java
|
NegreaVlad/StravaZpot-Android
|
/lib/src/main/java/com/sweetzpot/stravazpot/stream/request/GetRouteStreamsRequest.java
|
UTF-8
| 749
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sweetzpot.stravazpot.stream.request;
import com.sweetzpot.stravazpot.stream.api.StreamAPI;
import com.sweetzpot.stravazpot.stream.model.Stream;
import com.sweetzpot.stravazpot.stream.rest.StreamRest;
import java.util.List;
import retrofit2.Call;
public class GetRouteStreamsRequest {
private final int routeID;
private final StreamRest restService;
private final StreamAPI api;
public GetRouteStreamsRequest(int routeID, StreamRest restService, StreamAPI api) {
this.routeID = routeID;
this.restService = restService;
this.api = api;
}
public List<Stream> execute() {
Call<List<Stream>> call = restService.getRouteStreams(routeID);
return api.execute(call);
}
}
| true
|
6c6a554641e32ae95a8fd4920147f943183bf209
|
Java
|
vam-see/Phriend
|
/app/src/main/java/vamsee/phriend/Main.java
|
UTF-8
| 1,179
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package vamsee.phriend;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends AppCompatActivity {
Button btnStartSer, btnStopSer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartSer = (Button) findViewById(R.id.btnStartService);
btnStopSer = (Button) findViewById(R.id.btnStopService);
btnStartSer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), OverlayService.class);
intent.putExtra("BR","0");
startService(intent);
}
});
btnStopSer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), OverlayService.class);
stopService(intent);
}
});
}
}
| true
|
086cfffdfa27594fead1979e34145e3fd2349b6e
|
Java
|
BryanGF0822/Bumasoft-2.0
|
/src/model/Apartments.java
|
UTF-8
| 1,926
| 2.484375
| 2
|
[] |
no_license
|
package model;
import java.io.*;
public class Apartments implements Serializable {
private String realStateRegistration;
private String apartmentNumber;
private String tower;
private String ownerId;
private String state;
private int population;
private String residentType;
public Apartments(String realStateRegistration, String apartmentNumber, String tower, String ownerId, String state, int population, String residentType) throws FileNotFoundException {
this.realStateRegistration = realStateRegistration;
this.apartmentNumber = apartmentNumber;
this.tower = tower;
this.ownerId = ownerId;
this.state = state;
this.population = population;
}
public String getRealStateRegistration() {
return realStateRegistration;
}
public void setRealStateRegistration(String realStateRegistration) {
this.realStateRegistration = realStateRegistration;
}
public String getApartmentNumber() {
return apartmentNumber;
}
public void setApartmentNumber(String apartmentNumber) {
this.apartmentNumber = apartmentNumber;
}
public String getTower() {
return tower;
}
public void setTower(String tower) {
this.tower = tower;
}
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getResidentType() {
return residentType;
}
public void setResidentType(String residentType) {
this.residentType = residentType;
}
}
| true
|
0805dcd85aac244c70e9b140a82cdc7cff7d422c
|
Java
|
Wings1986/Bookfusion-Android
|
/app/src/main/java/com/bookfusion/android/reader/model/request/message/SendMessageRequestEntity.java
|
UTF-8
| 924
| 2.203125
| 2
|
[] |
no_license
|
package com.bookfusion.android.reader.model.request.message;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
public class SendMessageRequestEntity {
@JsonProperty("device")
private String device;
@JsonProperty("token")
private String token;
@JsonProperty("recipient_id")
private String recipientId;
@JsonProperty("text")
private String text;
@JsonCreator
public SendMessageRequestEntity(String device, String token, String recipientId, String text) {
this.device = device;
this.token = token;
this.recipientId = recipientId;
this.text = text;
}
public String getDevice() {
return device;
}
public String getToken() {
return token;
}
public String getRecipientId() { return recipientId; }
public String getText() {
return text;
}
}
| true
|
0e2ce3c0a4e8c6225c30021fbcdf70170f7dac18
|
Java
|
dimitar9/dreamfactory
|
/src/main/java/org/giddap/dreamfactory/fundamentals/datastructure/CircularBuffer.java
|
UTF-8
| 262
| 1.640625
| 2
|
[] |
no_license
|
package org.giddap.dreamfactory.fundamentals.datastructure;
/**
* http://www.museful.net/2012/software-development/circulararraylist-for-java
* http://bradforj287.blogspot.com/2010/11/efficient-circular-buffer-in-java.html
*/
public class CircularBuffer {
}
| true
|
285de4772f2eb13c39f9c396cc6756a0ea7959aa
|
Java
|
rcenvironment/rce-test
|
/de.rcenvironment.core.gui.workflow/src/main/java/de/rcenvironment/core/gui/workflow/EndpointContentProvider.java
|
UTF-8
| 3,893
| 2.4375
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2006-2014 DLR, Germany
*
* All rights reserved
*
* http://www.rcenvironment.de/
*/
package de.rcenvironment.core.gui.workflow;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import de.rcenvironment.core.component.model.endpoint.api.EndpointDescription;
import de.rcenvironment.core.component.workflow.model.api.WorkflowDescription;
import de.rcenvironment.core.component.workflow.model.api.WorkflowNode;
import de.rcenvironment.core.datamodel.api.EndpointType;
/**
* Content Provider taking a WorkflowDescription as root and displaying all componets with either
* their inputs or outputs.
*
* @author Heinrich Wendel
* @author Doreen Seider
* @author Sascha Zur
*/
public class EndpointContentProvider implements ITreeContentProvider {
private EndpointType type;
/**
* @param type Display input or output endpoints?
*/
public EndpointContentProvider(EndpointType type) {
this.type = type;
}
@Override
public Object[] getChildren(Object element) {
if (element instanceof WorkflowDescription) {
List<WorkflowNode> items = ((WorkflowDescription) element).getWorkflowNodes();
Collections.sort(items);
return items.toArray();
} else if (element instanceof WorkflowNode) {
List<EndpointItem> items = new ArrayList<EndpointItem>();
items.addAll(EndpointHandlingHelper.getEndpoints((WorkflowNode) element, type));
Collections.sort(items);
return items.toArray();
} else {
List<EndpointItem> items = new ArrayList<EndpointItem>();
Collections.sort(items);
return items.toArray();
}
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return (getChildren(element) != null && getChildren(element).length > 0);
}
@Override
public Object[] getElements(Object element) {
return getChildren(element);
}
@Override
public void dispose() {}
@Override
public void inputChanged(Viewer view, Object object1, Object object2) {
}
/**
* Class representing one item in the endpoint tree.
*
* @author Doreen Seider
*/
public static class EndpointItem implements Serializable, Comparable<EndpointItem> {
private static final long serialVersionUID = 777733457712592306L;
private String name;
private EndpointDescription endpointDesc;
public EndpointItem(EndpointDescription endpointDesc) {
this.endpointDesc = endpointDesc;
name = endpointDesc.getName();
}
public String getName() {
return name;
}
public EndpointDescription getEndpointDescription() {
return endpointDesc;
}
public String getShortName() {
return name;
}
@Override
public int compareTo(EndpointItem o) {
return name.compareTo(o.getName());
}
}
/**
* Class representing one endpoint.
*
* @author Heinrich Wendel
*/
public static class Endpoint extends EndpointItem {
private static final long serialVersionUID = 1633769598091968303L;
private WorkflowNode parent;
public Endpoint(WorkflowNode parent, EndpointDescription endpointDesc) {
super(endpointDesc);
this.parent = parent;
}
public WorkflowNode getWorkflowNode() {
return parent;
}
}
}
| true
|
969bbad57adce9f307e1565276abb05d2de0d845
|
Java
|
kleber-maia/iobjects-security-service
|
/src/java/securityservice/ui/entity/PapelRelacaoMestreEntityGridEventListener.java
|
ISO-8859-1
| 5,406
| 2.203125
| 2
|
[
"MIT"
] |
permissive
|
/*
The MIT License (MIT)
Copyright (c) 2008 Kleber Maia de Andrade
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package securityservice.ui.entity;
import java.sql.*;
import iobjects.*;
import iobjects.entity.*;
import iobjects.ui.entity.*;
import iobjects.util.*;
import securityservice.entity.*;
/**
* Utilitrio para maniputalar eventos do Grid de PapelRelacaoMestre.
*/
public class PapelRelacaoMestreEntityGridEventListener implements EntityGrid.EventListener {
private Facade facade = null;
private PapelRelacaoMestre papelRelacaoMestre = null;
/**
* Construtor padro.
* @param facade Facade Fachada.
*/
public PapelRelacaoMestreEntityGridEventListener(Facade facade) {
try {
// guarda nossos valores
this.facade = facade;
// instncia de PapelRelacaoMestre
papelRelacaoMestre = (PapelRelacaoMestre) facade.getEntity(
PapelRelacaoMestre.CLASS_NAME);
}
catch (Exception e) {
throw new RuntimeException(e);
} // try-catch
}
/**
* Faz um lookup para a tabela de relao mestre e retorna o valor do primeiro
* campo de exibio referente a 'masterRelationValue'.
* @param masterRelationValue String Valor da relao mestre para se fazer o
* lookup.
* @throws Exception Em caso de exceo na tentativa de acesso ao banco de
* dados.
* @return String Faz um lookup para a tabela de relao mestre e retorna o
* valor do primeiro campo de exibio referente a 'masterRelationValue'.
*/
private String lookupMasterRelation(String masterRelationValue) throws Exception {
// valores da relao mestre para pesquisar
String[] values = masterRelationValue.split(";");
// expresso de filtro
String where = "";
// loop nos campos chave da relao mestre
for (int i=0; i<facade.masterRelationInformation().getReturnFieldNames().length; i++) {
if (!where.equals(""))
where += " AND ";
where += "(" + facade.masterRelationInformation().getReturnFieldNames()[i] + "=" + values[i] + ")";
} // for
// prepara o Select
PreparedStatement preparedStatement =
SqlTools.prepareSelect(papelRelacaoMestre.getConnection(),
facade.masterRelationInformation().getTableName(),
facade.masterRelationInformation().getDisplayFieldNames(),
new String[0],
where);
// pega o ResultSet
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getResultSet();
try {
// retorna o primeiro campo
resultSet.next();
return resultSet.getString(1);
}
finally {
// libera recursos
if (resultSet != null) {
resultSet.getStatement().close();
resultSet.close();
} // if
}
}
/**
* Responde ao evento onAddCell do EntityGrid de PapelRelacaoMestre. Se a
* clula que estiver sendo adicionada for referente a FIELD_RELACAO_MESTRE
* ser feito um lookup para a tabela da relao mestre e retornado o
* primeiro campo de exibio configuado.
* @param entityInfo EntityInfo
* @param entityField EntityField
* @param value String
* @return String Responde ao evento onAddCell do EntityGrid de PapelRelacaoMestre.
*/
public String onAddCell(EntityInfo entityInfo,
EntityField entityField,
EntityLookup entityLookup,
String value) {
try {
// se o campo Relao Mestre...
if ((entityField != null) && (entityField == PapelRelacaoMestre.FIELD_RELACAO_MESTRE)) {
// pega o valor da relao mestre
String masterRelationValue = entityField.getFormatedFieldValue(entityInfo);
// retorna o valor apropriado para ser exibido
return "<img src='" + papelRelacaoMestre.extension().imageList().getImageUrl("relacaomestre16x16.gif") + "' align='absmiddle' /> "
+ lookupMasterRelation(masterRelationValue);
}
// se outro campo...
else
return value;
}
catch (Exception e) {
throw new RuntimeException(e);
} // try-catch
}
}
| true
|
9c47008c4d7fd47493b98f6d78fb54e1d11ea798
|
Java
|
Sin0117/AgileDev
|
/spark-web/src/main/java/com/baidu/spark/util/.svn/text-base/IdentityHashSet.java.svn-base
|
UTF-8
| 1,087
| 2.734375
| 3
|
[] |
no_license
|
package com.baidu.spark.util;
import java.util.AbstractSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
public class IdentityHashSet<E> extends AbstractSet<E> {
private static final long serialVersionUID = -6952572717595730869L;
private final IdentityHashMap<E, Object> map = new IdentityHashMap<E, Object>();
private static final Object PRESENT = new Object();
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean contains(Object o) {
return map.containsKey(o);
}
@Override
public boolean add(E t) {
int size = size();
map.put(t, PRESENT);
return size != size();
}
@Override
public boolean remove(Object o) {
return map.remove(o) == PRESENT;
}
@Override
public void clear() {
map.clear();
}
@Override
public Object clone() {
throw new UnsupportedOperationException("Clone operation is not supported yet.");
}
}
| true
|
99c72d05ea1636180447111a8cb3daf527330f59
|
Java
|
pascalkania/elitebet
|
/src/main/java/de/kania/elitebet/web/admin/AdminController.java
|
UTF-8
| 1,777
| 2.09375
| 2
|
[] |
no_license
|
package de.kania.elitebet.web.admin;
import de.kania.elitebet.database.BenutzerTipp;
import de.kania.elitebet.service.BenutzerTippService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.security.RolesAllowed;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping("/admin")
public class AdminController {
private static final Log LOGGER = LogFactory.getLog(AdminController.class);
@Autowired
private ApplicationContext context;
@Autowired
private BenutzerTippService benutzerTippService;
@ModelAttribute("alleBenutzerTipps")
public List<BenutzerTipp> leseAlleBenutzerTipps(){
return benutzerTippService.holeAlleBenutzerTipps();
}
@RequestMapping
@RolesAllowed("ADMIN")
public String handleAdminRequest(Model model) {
List<String> beans = Arrays.asList(context.getBeanDefinitionNames());
model.addAttribute("beans", beans);
return "admin";
}
@PostMapping("/tippFreigeben")
public String tippFreigeben(@ModelAttribute("benutzerId") String benutzerId, BindingResult errors, Model model){
LOGGER.info("Tipp freigeben für: "+ benutzerId);
benutzerTippService.tippFreigebenFuerBenutzerId(benutzerId);
return "redirect:/admin";
}
}
| true
|
2ce6fa2ea4977ab88e2bf8863fe274d6777439b0
|
Java
|
pushker-git/LeetCodeTopInterviewQuestions
|
/kickstart/Google Code Jam Qualification2021/ReverSort.java
|
UTF-8
| 2,240
| 3.453125
| 3
|
[] |
no_license
|
import java.util.*;
public class ReverSort {
public static long findCost(int [] nums) {
int sum = 0;
// int [] temp = nums.clone();
// Arrays.sort(temp);
// for (int number : temp)
// System.out.println(number);
int regularity = 0;
for (int i=0; i<nums.length; i++) {
if (i+1 == nums[i])
regularity += 1;
}
if (regularity == nums.length)
return nums.length - 1;
// if (regularity == 1)
// return (nums.length - 1) * 2;
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
map.put(nums[i], i);
}
for (int i=0; i<nums.length - 1; i++) {
int index = map.get(i+1);
int mid = (index - i + 1) / 2;
for (int j=0; j<mid; j++) {
int temp = nums[i+j];
nums[i+j] = nums[index - j];
nums[index - j] = temp;
map.replace(nums[i+j], i+j);
map.replace(nums[index - j], index - j);
}
// for (int j=i; j<=index/2; j++) {
// int temp = nums[j];
// nums[j] = nums[index / 2 + 1];
// nums[index / 2 + 1] = temp;
// map.replace(nums[j], j);
// map.replace(nums[index / 2 + 1], index / 2 + 1);
// }
//System.out.print(nums[i] + " ");
// for (int key : map.keySet()) {
// System.out.println(key + "->" + map.get(key));
// }
sum += index - i + 1;
}
// for (int number : nums)
// System.out.print(number + " ");
return sum;
// for (int i=0; i<nums.length; i++) {
// int currentMin = i + 1;
// int currentIndex = map.get(currentMin);
// sum += (currentIndex + 1) - (i + 1) + 1;
// }
// return sum + regularity * 2;
// for (int i=0; i<nums.length; i++) {
// if (nums[i] != temp[i])
// irregularity += 1;
// }
// if (irregularity == nums.length) {
// return (irregularity - 1) * 2;
// }
// if (irregularity == 0) {
// return 1;
// }
// if (irregularity == 1)
// return irregularity * 2;
// return irregularity * nums.length;
}
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for (int t=1; t<=test; t++) {
int n = sc.nextInt();
int [] nums = new int[n];
for (int i=0; i<n; i++) {
nums[i] = sc.nextInt();
}
System.out.println("Case #" + t + ": " + findCost(nums));
}
}
}
| true
|
8e60ceea89bf1650dc2172a3f3cf654f597cb0e7
|
Java
|
JenisseN/InsPedralbesTesting
|
/src/test/java/PageObjects/Projectes/QualitatPage.java
|
UTF-8
| 559
| 2.359375
| 2
|
[] |
no_license
|
package PageObjects.Projectes;
import PageObjects.PageBase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class QualitatPage extends PageBase {
private String qualitatTitle = "Qualitat";
private By locatorTitleQualitat= By.className("page-title");
public QualitatPage(WebDriver driver) {
super(driver);
}
public boolean qualitatPageisDisplayed() throws Exception {
return this.isDisplayed(locatorTitleQualitat) && this.readInTextField(locatorTitleQualitat).equals(qualitatTitle);
}
}
| true
|
d5e32368ac601264c2cf6cd7cce9a45079f709dd
|
Java
|
Diegoramosdrp/MyOwnProject-TEMP
|
/MyOwnProject/src/controller/NoteController.java
|
UTF-8
| 1,591
| 2.296875
| 2
|
[] |
no_license
|
package controller;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import DAO.ProjectsDAO;
import model.Note;
import model.Project;
import util.ControllerInterface;
import util.Validation;
@ManagedBean(name = "NoteController")
@SessionScoped
public class NoteController implements ControllerInterface<Note>{
private Note note = new Note();
private final ProjectsDAO<Project> projectsDAO = new ProjectsDAO<Project>();
private final Validation validation = new Validation();
private ArrayList<Note> notes;
private Project project = new Project();
public NoteController() {
}
public Note getNote() {
return note;
}
public void setNote(Note note) {
this.note = note;
}
public ArrayList<Note> getNotes() {
return notes;
}
public void setNotes(ArrayList<Note> notes) {
this.notes = notes;
}
@Override
public void save() {
note.setDescription(validation.firstCharToUpperCase(note.getDescription()));
if(note.getId() == null) {
projectsDAO.manipulationData(note, "saveNote");
} else {
projectsDAO.manipulationData(note, "update");
}
note = new Note();
}
public void save(Integer id) {
if (!validation.isNULL(note)) {
project = projectsDAO.findById(id);
note.setProject(project);
save();
}
}
@Override
public void remove(Note entity) {
projectsDAO.manipulationData(entity, "remove");
note = new Note();
}
@Override
public void edit(Note entity) {
this.note = entity;
}
@Override
public void list() {
// TODO Auto-generated method stub
}
}
| true
|
bde54a8fd0fbc64a59d70bae8b4257a4cc7fa3d6
|
Java
|
areebakhtar89/BE-Project
|
/Location_based_offer_App/Location_based_offer_App/app/src/main/java/com/example/chintan/myapplication/Data/selectrange.java
|
UTF-8
| 269
| 2.109375
| 2
|
[] |
no_license
|
package com.example.chintan.myapplication.Data;
public class selectrange {
public static double range;
public static double getRange() {
return range;
}
public static void setRange(double range) {
selectrange.range = range;
}
}
| true
|
3112f8a82eb83ba93a49a4de2178b9795d159e68
|
Java
|
adityaom927/JobMafiaa
|
/app/src/main/java/com/app/finalcode/getjob/getjob/activity/Comapny_Profile.java
|
UTF-8
| 7,585
| 1.625
| 2
|
[] |
no_license
|
package com.app.finalcode.getjob.getjob.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.app.finalcode.getjob.getjob.R;
import com.app.finalcode.getjob.getjob.classes.Adds;
import com.app.finalcode.getjob.getjob.classes.Certificate;
import com.app.finalcode.getjob.getjob.classes.Company;
import com.app.finalcode.getjob.getjob.classes.Education;
import com.app.finalcode.getjob.getjob.classes.Experience;
import com.app.finalcode.getjob.getjob.classes.Fav_Job;
import com.app.finalcode.getjob.getjob.classes.FetchDataListener;
import com.app.finalcode.getjob.getjob.classes.Job_Post_class;
import com.app.finalcode.getjob.getjob.classes.LoginClass;
import com.app.finalcode.getjob.getjob.classes.Skills;
import com.app.finalcode.getjob.getjob.classes.User;
import com.app.finalcode.getjob.getjob.classes.User_Apply;
import com.app.finalcode.getjob.getjob.classes.User_applied;
import com.app.finalcode.getjob.getjob.utility.AsyncTaskClass;
import com.app.finalcode.getjob.getjob.utility.ImageLoader;
import java.util.ArrayList;
public class Comapny_Profile extends AppCompatActivity implements FetchDataListener
{
LoginClass l=new LoginClass();
TextView company_p_name,user_p_city,company_p_email,company_p_phone,user_p_dob,company_p_hometown,user_p_pin,user_p_address,user_p_resume,tool_text;
ImageView name_icon,edit_profile_basic,edit_personal,edit_resume;
android.support.v7.widget.CardView logo_card;
ProgressDialog p;
@Override
protected void onStart()
{
super.onStart();
}
public void onBackPressed()
{
super.onBackPressed();
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.company__profile);
name_icon=(ImageView)findViewById(R.id.name_icon);
edit_profile_basic=(ImageView)findViewById(R.id.edit_profile_basic);
edit_personal=(ImageView)findViewById(R.id.edit_personal);
edit_resume=(ImageView)findViewById(R.id.edit_resume);
tool_text=(TextView)findViewById(R.id.tool_text);
user_p_resume=(TextView)findViewById(R.id.user_p_resume);
company_p_name=(TextView)findViewById(R.id.company_p_name);
user_p_city=(TextView)findViewById(R.id.user_p_city);
company_p_email=(TextView)findViewById(R.id.company_p_email);
company_p_phone=(TextView)findViewById(R.id.company_p_phone);
user_p_dob=(TextView)findViewById(R.id.user_p_dob);
company_p_hometown=(TextView)findViewById(R.id.company_p_hometown);
user_p_pin=(TextView)findViewById(R.id.user_p_pin);
user_p_address=(TextView)findViewById(R.id.user_p_address);
logo_card=(android.support.v7.widget.CardView)findViewById(R.id.logo_card);
edit_profile_basic.setVisibility(View.INVISIBLE);
edit_personal.setVisibility(View.INVISIBLE);
edit_resume.setVisibility(View.INVISIBLE);
Intent in=getIntent();
l=(LoginClass)in.getSerializableExtra("loginclass");
Log.e("email=>", "" + l.getEmail());
AsyncTaskClass profile_task=new AsyncTaskClass(this);
p=new ProgressDialog(Comapny_Profile.this);
p.show();
p.setCancelable(false);
String cpom_email=in.getStringExtra("comp_email");
if(l.getType().equals("user"))
{
profile_task.execute("company_details", cpom_email);
//name_icon.setVisibility(View.INVISIBLE);
edit_profile_basic.setVisibility(View.INVISIBLE);
edit_personal.setVisibility(View.INVISIBLE);
edit_resume.setVisibility(View.INVISIBLE);
logo_card.setVisibility(View.INVISIBLE);
}
else if(l.getType().equals("company"))
{
profile_task.execute("company_details", l.getEmail());
}
}
@Override
public void onFetchComplete_resume_check(int result1) {
}
@Override
public void onFetchComplete_fav(ArrayList<Fav_Job> data)
{
}
@Override
public void onFetchComplete_profile_edit(String s)
{
}
@Override
public void onFetchComplete_skill_add(String s)
{
}
@Override
public void onFetchComplete_skill(ArrayList<String> s) {
}
@Override
public void onFetchComplete_edit_exp(String str) {
}
@Override
public void onFetchComplete_skill_delete(String s)
{
}
@Override
public void onFetchComplete_edit_work(String s) {
}
@Override
public void onFetchComplete_delete_exp(String result) {
}
@Override
public void onFetchComplete_add_exp(String s) {
}
@Override
public void onFetchComplete_adds(ArrayList<Adds> ads) {
}
@Override
public void onFetchComplete_delete_certi(String s) {
}
@Override
public void onFetchComplete_companies(ArrayList<String> companies) {
}
@Override
public void onFetchComplete_company_details(Company c)
{
Log.e("completed", "" + c);
p.dismiss();
//company_p_name,user_p_city,company_p_email,company_p_phone,user_p_dob,company_p_hometown,user_p_pin,user_p_address
company_p_name.setText(c.getCompany_name());
String t=c.getCompany_city()+", "+c.getCompany_state();
user_p_city.setText(t);
company_p_email.setText(c.getCompany_email());
company_p_phone.setText(c.getCompany_contact());
if(c.getCompany_start().equals("0000-00-00"))
user_p_dob.setText("No Start Date Mentioned");
else
user_p_dob.setText(c.getCompany_start());
company_p_hometown.setText(c.getCompany_city());
user_p_pin.setText(c.getCompany_zip());
user_p_address.setText(c.getCompany_address());
user_p_resume.setText(c.getCompany_logo());
int loader = R.drawable.mcd_logo;
String image_url = "http://jobmafiaa.com//assets/uploads/"+c.getCompany_logo();
ImageLoader imgLoader = new ImageLoader(Comapny_Profile.this);
imgLoader.DisplayImage(image_url, loader, name_icon);
}
@Override
public void onFetchComplete_location(ArrayList<String> al) {
}
@Override
public void onFetchComplete_add_post(String s) {
}
@Override
public void onFetchComplete_jobs_posted(ArrayList<Job_Post_class> j) {
}
@Override
public void onFetchComplete_field(ArrayList<String> al) {
}
@Override
public void onFetchComplete_user_applied(ArrayList<User_applied> j) {
}
@Override
public void onFetchComplete_edu_edit(String s)
{
}
@Override
public void onFetchComplete_edu_delete(String s)
{
}
@Override
public void onFetchComplete_edu_add(String s)
{
}
@Override
public void onFetchComplete_apply(ArrayList<User_Apply> data)
{
}
@Override
public void onFetchComplete_profile(ArrayList<User> u, ArrayList<Experience> ex, ArrayList<Education> ed, ArrayList<Skills> sk, ArrayList<Certificate> ct)
{
}
@Override
public void onFetchComplete_job(ArrayList<Job_Post_class> data)
{
}
@Override
public void onFetchFailure(String msg)
{
}
@Override
public void onFetchComplete_all_seekers(ArrayList<User> result) {
}
}
| true
|
72dc31e4c2332f9f7e53839ec6fb6953b5f02f55
|
Java
|
slokostic3212/class-notes
|
/src/day28_Recap/MultiD_Practice3.java
|
UTF-8
| 1,686
| 3.65625
| 4
|
[] |
no_license
|
package day28_Recap;
import java.util.Arrays;
public class MultiD_Practice3 {
public static void main(String[] args) {
//
int[][] arr2D = { {1, 2, 3, }, {4, 5, 6} };
// 0 1
// 0 1 0 1
int[][][] arr3D = { {{1, 2, 3, }, {4, 5, 6}} , {{6, 7, 8}, {9, 10} } };
// 0 1
System.out.println(Arrays.deepToString(arr3D));
// {{6, 7, 8}, {9, 10} }
System.out.println( Arrays.deepToString(arr3D[1]) );// 6 7 8 9 10
System.out.println( Arrays .toString( arr3D[0][1]) );//456
System.out.println(arr3D[1][0][2]);//8
System.out.println("========================================");
/* for (int i = 0; i<= arr3D.length-1; i++){//i is index num of 2D arrays
int[][] each2D = arr3D[i];
for (int j = 0; j <= each2D.length-1; j++){// j is index of 1D array
int[] each1D = each2D[j];
for (int k = 0; k <= each1D.length-1; k++ ){// k is endex of elements from each array
System.out.print(each1D[k]+" ");
}
// System.out.println();
}
System.out.println();
*/
System.out.println("=======================================");
for (int [][] each2D : arr3D){
for ( int[] each1D : each2D){
for (int eachElement : each1D ){
System.out.print(eachElement+" ");
}
}
}
}
}
| true
|
564b222998f961db1e6e453d26aeaedf3fcc5777
|
Java
|
lisa5555/gametest
|
/src/main/java/com/lisa/gametest/service/impl/TAnswerServiceImpl.java
|
UTF-8
| 2,554
| 1.789063
| 2
|
[] |
no_license
|
package com.lisa.gametest.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lisa.gametest.common.ChangeListToArray;
import com.lisa.gametest.dao.TAnswerMapper;
import com.lisa.gametest.entity.TAnswer;
import com.lisa.gametest.entity.TJudge;
import com.lisa.gametest.service.ITAnswerService;
import com.lisa.gametest.vo.AnswerExam;
import com.lisa.gametest.vo.MyAnswer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TAnswerServiceImpl implements ITAnswerService {
@Autowired(required = false)
private TAnswerMapper tAnswerMapper;
@Override
public int deleteByTAnswerId(Integer aid) {
return tAnswerMapper.deleteByTAnswerId(aid);
}
@Override
public int deleteTAnswerByIds(String[] arr) {
return tAnswerMapper.deleteTAnswerByIds(arr);
}
@Override
public int insert(TAnswer tAnswer) {
return tAnswerMapper.insert(tAnswer);
}
@Override
public int insertSomeAnswer(List<TAnswer> list) {
return tAnswerMapper.insertSomeAnswer(list);
}
@Override
public TAnswer selectTAnswerById(Integer aid) {
return tAnswerMapper.selectTAnswerById(aid);
}
@Override
public int updateTAnswer(TAnswer tAnswer) {
return tAnswerMapper.updateTAnswer(tAnswer);
}
@Override
public int findTAnswerCount(Integer tid) {
return tAnswerMapper.findTAnswerCount(tid);
}
@Override
public String createTAnswerExams(Integer tid, Integer aNum) {
List<Integer> list = tAnswerMapper.createTAnswerExams(tid, aNum);
return ChangeListToArray.create(list);
}
@Override
public Map<String, Object> selectBySearch(Integer page, Integer limit, Integer tid, String searchName, Integer score) {
PageHelper.startPage(page,limit);
List<MyAnswer> list = tAnswerMapper.selectBySearch(tid,searchName,score);
// 获取总记录数
long total = ((Page) list).getTotal();
// 获取总页数
int pages = ((Page) list).getPages();
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("msg", "");
map.put("count", total);
map.put("data", list);
return map;
}
@Override
public List<AnswerExam> findAnswer(Integer qid) {
return tAnswerMapper.findAnswerExamList(qid);
}
}
| true
|
e6abedc10038051ba56b7ece92672c7fe7420474
|
Java
|
AyrtonPereira1996/task-schedule-appweb
|
/src/main/java/br/com/treinaweb/twgerenciadortarefas/controllers/TarefasController.java
|
UTF-8
| 4,987
| 2.421875
| 2
|
[] |
no_license
|
package br.com.treinaweb.twgerenciadortarefas.controllers;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import br.com.treinaweb.twgerenciadortarefas.model.Tarefa;
import br.com.treinaweb.twgerenciadortarefas.model.Usuario;
import br.com.treinaweb.twgerenciadortarefas.repositorios.RepositorioTarefa;
import br.com.treinaweb.twgerenciadortarefas.servicos.ServicoUsuario;
@Controller // anotação que permite a configuração de uma classe em um controller
@RequestMapping("/tarefas") // para puder aceder qualque metodo/actions deste controller apenas poderei em
// /tarefas
public class TarefasController {
@Autowired
private RepositorioTarefa rt;
@Autowired
private ServicoUsuario su;
@GetMapping("/listar") // usarei o verbo get do http porque precisarei pegar algo da
// aplicacao(servidor) e devolver ao usuario, se eu quiser pegar a minha lista
// de tarefas terei que estar em tarefas/listar
public ModelAndView listar(HttpServletRequest request) {// actions de listar
// toda a requisicao para uma aplicao web java e feita pela interface
// httpservelerequest
ModelAndView mv = new ModelAndView();
mv.setViewName("tarefas/listar");// nome da view ou documento html
String emailUsuario = request.getUserPrincipal().getName();// na configuracao do spring security ja foi
// configurado que o nome do usario e o seu email
mv.addObject("tarefas", rt.carregarTarefasPorUsuario(emailUsuario));// adicionamos um oobjecto tarefas, com o
// valor repositorio pegando tods
// os dados com um select *
return mv;// retorna o objecto
}
@GetMapping("/inserir")
public ModelAndView inserir() {
ModelAndView mv = new ModelAndView();
mv.setViewName("tarefas/inserir");
mv.addObject("tarefa", new Tarefa());
return mv;
}
@PostMapping("/inserir")
public ModelAndView inserir(@Valid Tarefa tarefa, BindingResult result, HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
if (tarefa.getDataExpiracao() == null) {
result.rejectValue("dataExpiracao", "tarefa.dataExpiracaoInvalida", "A data de expiração obrigatória.");
} else {
if (tarefa.getDataExpiracao().before(new Date())) {
result.rejectValue("dataExpiracao", "tarefa.dataExpiracaoInvalida",
"A data de expiração não pode ser anterior à data actual.");
}
}
if (result.hasErrors()) {
mv.setViewName("tarefas/inserir");
mv.addObject(tarefa);
} else {
String emailUsuario = request.getUserPrincipal().getName();// ira pegar as informações do usuario mais
// especificamente o email como esta configurado
// no spring security
Usuario usuarioLogado = su.encontrarPorEmail(emailUsuario);//pegará o usuario que esta actualmente conectado
tarefa.setUsuario(usuarioLogado);//antes de salval ira setar
rt.save(tarefa);//ao salvar ja tem usuario setado
mv.setViewName("redirect:/tarefas/listar");
}
return mv;
}
@GetMapping("/alterar/{id}")
public ModelAndView alterar(@PathVariable Long id) {
ModelAndView mv = new ModelAndView();
Tarefa tarefa = rt.getOne(id);
mv.addObject("tarefa", tarefa);
mv.setViewName("tarefas/alterar");
return mv;
}
@PostMapping("/alterar")
public ModelAndView alterar(@Valid Tarefa tarefa, BindingResult result) {
ModelAndView mv = new ModelAndView();
if (tarefa.getDataExpiracao() == null) {
result.rejectValue("dataExpiracao", "tarefa.dataExpiracaoInvalida", "A data de expiração obrigatória.");
} else {
if (tarefa.getDataExpiracao().before(new Date())) {
result.rejectValue("dataExpiracao", "tarefa.dataExpiracaoInvalida",
"A data de expiração não pode ser anterior à data actual.");
}
}
if (result.hasErrors()) {
mv.setViewName("tarefas/alterar");
mv.addObject(tarefa);
} else {
mv.setViewName("redirect:/tarefas/listar");
rt.save(tarefa);
}
return mv;
}
@GetMapping("/excluir/{id}") // o id seja passado para o id do parametro
public String excluir(@PathVariable("id") Long id) {// ira receber o id da tarefa a ser excluida, pathvariable
// porque o id vem da url
rt.deleteById(id);
return "redirect:/tarefas/listar";
}
@GetMapping("/concluir/{id}")
public String concluir(@PathVariable("id") Long id) {
Tarefa tarefa = rt.getOne(id); // ira pegar apenas um valor de um respectivo campo
tarefa.setConcluida(true);
rt.save(tarefa);
return "redirect:/tarefas/listar";
}
}
| true
|
61c5f3817e175264a54a3c63437ea2d7c415f194
|
Java
|
JetBrains/intellij-community
|
/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesRetrieverImpl.java
|
UTF-8
| 1,505
| 1.96875
| 2
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.stubs.StubUpdatingIndex;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class PushedFilePropertiesRetrieverImpl implements PushedFilePropertiesRetriever {
@NotNull
@Override
public List<String> dumpSortedPushedProperties(@NotNull VirtualFile file) {
if (file.isDirectory()) {
throw new IllegalArgumentException("file " + file + " is expected to be a regular file");
}
if (!StubUpdatingIndex.USE_SNAPSHOT_MAPPINGS) {
return Collections.emptyList();
}
List<String> properties = null;
for (FilePropertyPusher<?> extension : FilePropertyPusher.EP_NAME.getExtensionList()) {
Object property;
VirtualFile vfsObject;
if (extension.pushDirectoriesOnly()) {
vfsObject = file.getParent();
}
else {
vfsObject = file;
}
property = extension.getFilePropertyKey().getPersistentValue(vfsObject);
if (property != null) {
if (properties == null) {
properties = new ArrayList<>();
}
properties.add(property.toString());
}
}
if (properties == null) {
return Collections.emptyList();
}
properties.sort(null);
return properties;
}
}
| true
|
37fab8d5a27a1dbe48dbfd2178297c1003208b7f
|
Java
|
YasuoKatou/Java
|
/spring_boot_demo/src/test/java/yksolution/demo/DaoTestBase.java
|
UTF-8
| 921
| 1.570313
| 2
|
[] |
no_license
|
package yksolution.demo;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DbUnitConfiguration;
import yksolution.demo.test.common.CsvDataSetLoader;
@Transactional
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@DbUnitConfiguration(dataSetLoader = CsvDataSetLoader.class)
public class DaoTestBase extends TestBase {
}
| true
|
3fdc74d89b4ae3f4bf7179aecaa8db82d0942aed
|
Java
|
gao5712975/Tarvel
|
/src/test/socket/Client.java
|
UTF-8
| 834
| 2.703125
| 3
|
[] |
no_license
|
package test.socket;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端
* Created by Yuan on 2015/8/9.
*/
public class Client {
public static void main(String[] args){
try {
Socket socket = new Socket("127.0.0.1",8888);
OutputStream outputStream = socket.getOutputStream();
IOUtils.write("1234567".getBytes(),outputStream);
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
String info = IOUtils.toString(inputStream);
System.out.println(info);
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
a864c2223fba1541b515a20642c81a7c5415bd41
|
Java
|
Mudhasir/testser
|
/.svn/pristine/6d/6dfa211ee58844e046a64bce56ae1a86a5163b6d.svn-base
|
UTF-8
| 1,109
| 1.898438
| 2
|
[] |
no_license
|
package com.agaram.eln.primary.model.usermanagement;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "LSuserteammapping")
public class LSuserteammapping {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Basic(optional = false)
@Column(name = "userteammapcode")
private Integer userteammapcode;
private Integer teamcode;
@ManyToOne
private LSuserMaster lsuserMaster;
public Integer getUserteammapcode() {
return userteammapcode;
}
public void setUserteammapcode(Integer userteammapcode) {
this.userteammapcode = userteammapcode;
}
public LSuserMaster getLsuserMaster() {
return lsuserMaster;
}
public void setLsuserMaster(LSuserMaster lsuserMaster) {
this.lsuserMaster = lsuserMaster;
}
public Integer getTeamcode() {
return teamcode;
}
public void setTeamcode(Integer teamcode) {
this.teamcode = teamcode;
}
}
| true
|
870b1f3bd75c86d635cfc32397c74290460a59c0
|
Java
|
dawidm/exchangeutils
|
/src/main/java/pl/dmotyka/exchangeutils/poloniex/PoloniexChartInfo.java
|
UTF-8
| 5,299
| 2.140625
| 2
|
[
"MIT"
] |
permissive
|
/*
* Cryptonose
*
* Copyright © 2019-2021 Dawid Motyka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package pl.dmotyka.exchangeutils.poloniex;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.logging.Logger;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.poloniex.PoloniexExchange;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexChartData;
import org.knowm.xchange.poloniex.service.PoloniexChartDataPeriodType;
import org.knowm.xchange.poloniex.service.PoloniexMarketDataService;
import pl.dmotyka.exchangeutils.chartinfo.ChartCandle;
import pl.dmotyka.exchangeutils.chartinfo.ChartTimePeriod;
import pl.dmotyka.exchangeutils.chartinfo.ExchangeChartInfo;
import pl.dmotyka.exchangeutils.exceptions.ConnectionProblemException;
import pl.dmotyka.exchangeutils.exceptions.ExchangeCommunicationException;
import pl.dmotyka.exchangeutils.pairsymbolconverter.PairSymbolConverter;
/**
* Created by dawid on 12/16/17.
*/
public class PoloniexChartInfo implements ExchangeChartInfo {
private static final Logger logger = Logger.getLogger(PoloniexChartInfo.class.getName());
private Exchange poloniex;
private PoloniexMarketDataService poloniexMarketDataService;
private final PairSymbolConverter pairSymbolConverter = new PoloniexPairSymbolConverter();
@Override
public ChartCandle[] getCandles(String symbol, long timePeriodSeconds, long beginTimestampSeconds, long endTimestampSeconds) throws ExchangeCommunicationException, ConnectionProblemException {
if(poloniex==null | poloniexMarketDataService==null) {
poloniex = ExchangeFactory.INSTANCE.createExchange(PoloniexExchange.class.getName());
poloniexMarketDataService = (PoloniexMarketDataService) poloniex.getMarketDataService();
}
try {
PoloniexChartDataPeriodType poloniexChartDataPeriodType = periodSecondsToPoloniexPeriodType((int)timePeriodSeconds);
if(poloniexChartDataPeriodType==null)
throw new ExchangeCommunicationException("error getting PoloniexChartDataPeriodType for " + timePeriodSeconds);
PoloniexChartData poloniexChartData[] = poloniexMarketDataService.getPoloniexChartData(
new CurrencyPair(pairSymbolConverter.apiSymbolToBaseCurrencySymbol(symbol), pairSymbolConverter.apiSymbolToCounterCurrencySymbol(symbol)),
beginTimestampSeconds,
endTimestampSeconds,
poloniexChartDataPeriodType);
return Arrays.stream(poloniexChartData).map(poloniexChartCandle -> new ChartCandle(poloniexChartCandle.getHigh().doubleValue(),
poloniexChartCandle.getLow().doubleValue(),
poloniexChartCandle.getOpen().doubleValue(),
poloniexChartCandle.getClose().doubleValue(),
poloniexChartCandle.getDate().getTime()/1000)).
filter(candle -> candle.getTimestampSeconds() != 0).
toArray(ChartCandle[]::new);
} catch (UnknownHostException e) {
throw new ConnectionProblemException("when getting poloniex candles for: "+symbol);
}
catch (IOException e) {
throw new ExchangeCommunicationException("when getting poloniex candles for: "+symbol);
}
}
private PoloniexChartDataPeriodType periodSecondsToPoloniexPeriodType(int periodSeconds) {
for (PoloniexChartDataPeriodType poloniexChartDataPeriodType : PoloniexChartDataPeriodType.values()) {
if(poloniexChartDataPeriodType.getPeriod()==periodSeconds)
return poloniexChartDataPeriodType;
}
return null;
};
@Override
public ChartTimePeriod[] getAvailablePeriods() {
return new ChartTimePeriod[] {
new ChartTimePeriod("5m",5*60,null),
new ChartTimePeriod("15m",15*60,null),
new ChartTimePeriod("30m",30*60,null),
new ChartTimePeriod("2h",2*60*60,null),
new ChartTimePeriod("4h",4*60*60,null),
new ChartTimePeriod("1d",24*60*60,null),
};
}
}
| true
|
3b9f506b206969abfc793fa53b324bb6a4bcdd0f
|
Java
|
Horrarndoo/YiZhi
|
/app/src/main/java/com/zyw/horrarndoo/yizhi/contract/home/tabs/BaseTabsContract.java
|
UTF-8
| 1,756
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.zyw.horrarndoo.yizhi.contract.home.tabs;
import com.zyw.horrarndoo.sdk.base.BasePresenter;
import com.zyw.horrarndoo.sdk.base.IBaseFragment;
import com.zyw.horrarndoo.sdk.base.IBaseModel;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by Horrarndoo on 2017/9/20.
* <p>
*/
public interface BaseTabsContract {
abstract class BaseTabsPresenter<M extends IBaseTabsModel, V extends IBaseTabsView, T>
extends BasePresenter<M, V> {
/**
* 加载最新的list
*/
public abstract void loadLatestList();
/**
* 加载更多list
*/
public abstract void loadMoreList();
/**
* item点击事件
*
* @param position position
* @param item item
*/
public abstract void onItemClick(int position, T item);
}
interface IBaseTabsModel extends IBaseModel {
/**
* 记录item已阅到数据库
*
* @param key key(item.id值作为key)
*/
Observable<Boolean> recordItemIsRead(String key);
}
interface IBaseTabsView<L> extends IBaseFragment {
/**
* 更新界面list
*
* @param list list
*/
void updateContentList(List<L> list);
/**
* 点击事件后,刷新item
*
* @param position position
*/
void itemNotifyChanged(int position);
/**
* 显示网络错误
*/
void showNetworkError();
/**
* 显示加载更多错误
*/
void showLoadMoreError();
/**
* 显示没有更多数据
*/
void showNoMoreData();
}
}
| true
|
5ef610977e85312e24f358ff96f2defcc098d8c7
|
Java
|
CoolSpy3/VPT
|
/java/VPT/test/test/CreateAdmin.java
|
UTF-8
| 3,295
| 2.546875
| 3
|
[] |
no_license
|
//Depricated
//package test;
//
//import common.SerializableImage;
//import common.Utils;
//import common.user.UserAttributeType;
//import java.io.File;
//import java.lang.reflect.Field;
//import java.security.KeyPair;
//import java.security.PrivateKey;
//import java.security.PublicKey;
//import java.util.ArrayList;
//import java.util.HashMap;
//import javax.imageio.ImageIO;
//import server.serialization.BackupSerialization;
//import server.serialization.EncryptionSerialization;
//import server.serialization.MacSerialization;
//import server.services.LoginService;
//import server.user.SingleDataAttribute;
//import server.user.User;
//import server.user.UserAttribute;
//
///**
// * Code creating a default administrator user
// */
//public class CreateAdmin {
//
// public static void main(String[] args) throws Exception {
// //Mark this thread as a system thread and disable user security
// Field systemThreadField = LoginService.class.getDeclaredField("isSystemThread");
// systemThreadField.setAccessible(true);
// ((ThreadLocal<Boolean>)systemThreadField.get(null)).set(true);
//
// //Create User
// User user = new User("admin", "password".getBytes(), true, true);
//
// //Load Attributes
// ArrayList<UserAttribute> attributes = new ArrayList<>();
// attributes.add(new SingleDataAttribute.StringSearch<>(UserAttributeType.USERNAME, "admin", user));
// attributes.add(new SingleDataAttribute.NoSearch<>(UserAttributeType.USERICON, new SerializableImage(
// ImageIO.read(new File("../../cpp/GraphicFrameWork/GraphicFrameWork/projects/VPT/DefaultProfilePicture.png"))), user));
// attributes.forEach(user::addAttribute);
// HashMap<String, ArrayList<UserAttribute>> publicAttributes = new HashMap<>();
// publicAttributes.put(user.userId, user.getAttributes());
// BackupSerialization.serialize(publicAttributes, "Users/attributes.attrs");
//
// //Load User Keys
// KeyPair publicFileKeys = Utils.createPseudoRandomAsymetricKey();
// user.setKey("USER_FILE_PRIVATE_KEY", publicFileKeys.getPrivate());
// user.setKey("USER_FILE_PUBLIC_KEY", publicFileKeys.getPublic());
// user.setKey("ADMIN_SECRET_KEY", Utils.createPseudoRandomSecretKey());
// KeyPair adminKeys = Utils.createPseudoRandomAsymetricKey();
// user.setKey("ADMIN_PRIVATE_KEY", adminKeys.getPrivate());
// BackupSerialization.serialize(adminKeys.getPublic(), "Users/ADMIN_PUBLIC.key");
// HashMap<String, PublicKey> userPublicKeys = new HashMap<>();
// userPublicKeys.put(user.userId, publicFileKeys.getPublic());
// BackupSerialization.serialize(userPublicKeys, "Users/publickeys.pks");
//
// //Save User
// EncryptionSerialization.serialize(user, "Users/" + Utils.hash(user.userId) + ".usr", user.getKey("USER_FILE_SECRET_KEY"));
// MacSerialization.serialize(user.toNetPublicUser(), "Users/" + Utils.hash(user.userId) + ".usr.pub", (PrivateKey)user.getKey("USER_FILE_PRIVATE_KEY"));
// EncryptionSerialization.serialize(user.getKey("USER_FILE_SECRET_KEY"), "Users/" + Utils.hash(user.userId) + ".usr.key", adminKeys.getPublic());
// }
//
//}
| true
|
c040fb290a491ed72e2b2d949db0d7382c2a2c4d
|
Java
|
SaiAyshwaryaLakshmi/DesignPatterns
|
/Ravichandran_SaiAyshwaryaLakshmi/CS586_SaiAyshwaryLakshmi/src/strategyPattern/setPrice/SetPrice.java
|
UTF-8
| 118
| 2.375
| 2
|
[] |
no_license
|
package strategyPattern.setPrice;
public abstract class SetPrice {
public abstract void setPrice(int gasType);
}
| true
|
7e6226141dfd58d47c459f905b76bbad7bf1a965
|
Java
|
Zachory0907/yy
|
/myapps/src/main/java/vip/zgt/app/util/ExecutExcel.java
|
UTF-8
| 8,214
| 3.078125
| 3
|
[] |
no_license
|
package vip.zgt.app.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 通过POI方式操作Excel文件 往已存在的excel里面读、写内容
*
* @author 赵郭桃
*
*/
public class ExecutExcel {
public static void main(String[] args) {
}
/**
* 往单一页签里写
* <table border="1" cellspacing="0">
* <tr>
* <td>srcFile</td>
* <td>往哪儿写</td>
* </tr>
* <tr>
* <td>sheetNum</td>
* <td>往第几个页签里写(0开始)</td>
* </tr>
* <tr>
* <td>rowStart</td>
* <td>从第几行开始往里写(0开始)</td>
* </tr>
* <tr>
* <td>colStart</td>
* <td>从第几列开始往里写(0开始)</td>
* </tr>
* <tr>
* <td>content</td>
* <td>想要写的内容,注意是排好顺序的List<List<String>></td>
* </tr>
* </table>
*
* @author 赵郭桃
*/
public static boolean writeToSingleExcel(String srcFile, int sheetNum, int rowStart, int colStart,
List<List<String>> content) {
File file = new File(srcFile);
try {
InputStream inputStream = new FileInputStream(file);
HSSFWorkbook xssfWorkbook = new HSSFWorkbook(inputStream);
HSSFSheet sheet = xssfWorkbook.getSheetAt(sheetNum); // 拿到第sheetNum个sheet
if (content.isEmpty()) {
return false;
}
int rowCount = content.size();
List<String> list = content.get(0);
if (list.isEmpty()) {
return false;
}
int colCount = list.size();
// i, j 是表格循环; x, y 是List<>循环
for (int i = rowStart, m = rowCount + rowStart, x = 0; i < m; i++, x++) {
for (int j = colStart, n = colCount + colStart, y = 0; j < n; j++, y++) {
try {
String con = content.get(x).get(y);
sheet.getRow(i).getCell(j).setCellValue(con);
String v = sheet.getRow(i).getCell(j).getStringCellValue();
System.out.println("(" + i + ", " + j + "):" + v);
} catch (Exception e) {
continue;
}
}
}
FileOutputStream fos = new FileOutputStream(srcFile);
xssfWorkbook.write(fos);
return true;
} catch (FileNotFoundException e) {
System.out.println("文件未找到!");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("写入Excel异常!");
e.printStackTrace();
return false;
}
}
/**
* 从单一页签里读
* <table border="1" cellspacing="0">
* <tr>
* <td>srcFile</td>
* <td>要读的文件</td>
* </tr>
* <tr>
* <td>sheetNum</td>
* <td>读第几个页签(0开始)</td>
* </tr>
* <tr>
* <td>rowStart</td>
* <td>从第几行开始读(0开始)</td>
* </tr>
* <tr>
* <td>colStart</td>
* <td>从第几列开始读(0开始)</td>
* </tr>
* <tr>
* <td>headList</td>
* <td>表头信息</td>
* </tr>
* </table>
*
* @author 赵郭桃
*/
public static List<List<Map<String, Object>>> readFromSingleExcel(String srcFile, int sheetNum, int rowStart,
int colStart, String[] headList) {
File file = new File(srcFile);
String filenane = file.getName();
if (filenane.indexOf("xlsx") > 0) {
return readFromSingleExcelXlsx(srcFile, sheetNum, rowStart, colStart, headList);
} else {
return readFromSingleExcelXls(srcFile, sheetNum, rowStart, colStart, headList);
}
}
public static List<List<Map<String, Object>>> readFromSingleExcelXlsx(String srcFile, int sheetNum, int rowStart,
int colStart, String[] headList) {
File file = new File(srcFile);
try {
InputStream inputStream = new FileInputStream(file);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = xssfWorkbook.getSheetAt(sheetNum); // 拿到第sheetNum个sheet
List<List<Map<String, Object>>> results = new ArrayList<List<Map<String, Object>>>();
for (Row row : sheet) {
List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
if (row.getRowNum() < rowStart) {
continue;
}
for (Cell hssfCell : row) {
if (hssfCell.getColumnIndex() < colStart) {
continue;
}
Object cont = null;
Map<String, Object> map = new HashMap<String, Object>();
if (headList == null || headList.length == 0) {
// 说明没有HeadList
if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cont = hssfCell.getBooleanCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cont = hssfCell.getNumericCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_STRING) {
cont = hssfCell.getStringCellValue();
}
map.put(String.valueOf(hssfCell.getColumnIndex()), cont);
} else {
if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cont = hssfCell.getBooleanCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cont = hssfCell.getNumericCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_STRING) {
cont = hssfCell.getStringCellValue();
}
String key = null;
try {
key = headList[(hssfCell.getColumnIndex() - colStart)];
} catch (Exception e) {
key = String.valueOf(hssfCell.getColumnIndex());
}
if (key == null) {
key = String.valueOf(hssfCell.getColumnIndex());
}
map.put(key, cont);
}
content.add(map);
}
results.add(content);
}
return results;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static List<List<Map<String, Object>>> readFromSingleExcelXls(String srcFile, int sheetNum, int rowStart,
int colStart, String[] headList) {
File file = new File(srcFile);
try {
InputStream inputStream = new FileInputStream(file);
HSSFWorkbook xssfWorkbook = new HSSFWorkbook(inputStream);
HSSFSheet sheet = xssfWorkbook.getSheetAt(sheetNum); // 拿到第sheetNum个sheet
List<List<Map<String, Object>>> results = new ArrayList<List<Map<String, Object>>>();
for (Row row : sheet) {
List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
if (row.getRowNum() < rowStart) {
continue;
}
for (Cell hssfCell : row) {
if (hssfCell.getColumnIndex() < colStart) {
continue;
}
Object cont = null;
Map<String, Object> map = new HashMap<String, Object>();
if (headList == null || headList.length == 0) {
// 说明没有HeadList
if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cont = hssfCell.getBooleanCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cont = hssfCell.getNumericCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_STRING) {
cont = hssfCell.getStringCellValue();
}
map.put(String.valueOf(hssfCell.getColumnIndex()), cont);
} else {
if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cont = hssfCell.getBooleanCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cont = hssfCell.getNumericCellValue();
} else if (hssfCell.getCellType() == Cell.CELL_TYPE_STRING) {
cont = hssfCell.getStringCellValue();
}
String key = null;
try {
key = headList[(hssfCell.getColumnIndex() - colStart)];
} catch (Exception e) {
key = String.valueOf(hssfCell.getColumnIndex());
}
if (key == null) {
key = String.valueOf(hssfCell.getColumnIndex());
}
map.put(key, cont);
}
content.add(map);
}
results.add(content);
}
return results;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| true
|
641e65ee6df9d66da23a94d77fd497f155afba67
|
Java
|
rocketriot/game
|
/app/test/bham/bioshock/minigame/physics/SpeedVectorTests.java
|
UTF-8
| 2,788
| 2.859375
| 3
|
[] |
no_license
|
package bham.bioshock.minigame.physics;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SpeedVectorTests {
@Test
public void testApply() {
SpeedVector v = new SpeedVector();
v.apply(0, 10);
assertEquals(0, v.dX(), 2);
assertEquals(10, v.dY(), 2);
v.apply(180, 10);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(90, 100);
assertEquals(100, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(270, 100);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(45, 100);
assertEquals(v.dY(), v.dX());
v.apply(45, -100);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(360, 80);
assertEquals(0, v.dX(),2);
assertEquals(80, v.dY(),2);
v.apply(540, 80);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(0, 200);
v.apply(90, 200);
assertEquals(200, v.dX(),2);
assertEquals(200, v.dY(),2);
}
@Test
public void testSpeedAngle() {
SpeedVector v = new SpeedVector();
v.apply(0, 200);
assertEquals(0, v.getSpeedAngle(),2);
v.apply(90, 200);
assertEquals(45, v.getSpeedAngle(),2);
v.apply(270, 200);
assertEquals(0, v.getSpeedAngle(),2);
v.apply(180, 200);
v.apply(180, 10);
assertEquals(180, v.getSpeedAngle(),2);
v.apply(270, 10);
assertEquals(225, v.getSpeedAngle(),2);
}
@Test
public void testStop() {
SpeedVector v = new SpeedVector();
v.apply(0, 200);
v.stop(0);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(45, 100);
v.stop(0);
assertEquals(70, v.dX(),2);
assertEquals(0, v.dY(),2);
v.stop(90);
assertEquals(0, v.dX(),2);
assertEquals(0, v.dY(),2);
v.apply(270, 100);
v.stop(225);
assertEquals(-50, v.dX(),2);
assertEquals(50, v.dY(),2);
SpeedVector v2 = new SpeedVector();
v2.apply(0, 200);
v2.stop(180);
assertEquals(200, v2.dY(),2);
}
@Test
public void testBasicCollisions() {
SpeedVector v1 = new SpeedVector();
SpeedVector v2 = new SpeedVector();
// opposite directions
v1.apply(90, 100);
assertEquals(100, v1.dX(),2);
v2.apply(90, -100);
assertEquals(-100, v2.dX(),2);
// elastic collision = should swap directions
// v1.collide(v2, 1);
// assertEquals(-100, v1.dX());
// assertEquals(100, v2.dX());
//
// v1.stop(270);
// assertEquals(0, v1.dX());
//
// // elastic collision - one speed is 0
// v1.collide(v2, 1);
// assertEquals(100, v1.dX());
// assertEquals(0, v2.dX());
v1.stop(v1.getSpeedAngle());
assertEquals(0, v1.dX(),2);
}
@Test
public void testCollisionsDirections() {
}
}
| true
|
000c423c343e56ae2b304e966506672f0ec41b5c
|
Java
|
freeman9998/MyCoding
|
/Itwill/06.WEB/3.JSP/2.배포컨텐트/99.쇼핑몰/2.카트/projectShop/src/com/itwill/shop/cart/CartService.java
|
UTF-8
| 864
| 2.375
| 2
|
[] |
no_license
|
package com.itwill.shop.cart;
import java.util.ArrayList;
public class CartService {
private CartDao cartDao;
public CartService() throws Exception {
cartDao=new CartDao();
}
/*
* 카트추가 or 수정
*/
public int addCart(String sUserId,int p_no,int cart_qty)throws Exception {
if(cartDao.isProductExist(sUserId, p_no)) {
return cartDao.update(sUserId, p_no, cart_qty);
}else {
return cartDao.add(sUserId, p_no, cart_qty);
}
}
/*
* 카트보기
*/
public ArrayList<Cart> getCartList(String sUserId) throws Exception{
return cartDao.getCartList(sUserId);
}
/*
* 카트아이템1개삭제
*/
public int deleteCartItem(int cart_no) throws Exception{
return cartDao.deleteCartByNo(cart_no);
}
/*
* 카트삭제
*/
public int deleteCart(String sUserId)throws Exception {
return cartDao.deleteCart(sUserId);
}
}
| true
|
d133d5279d2104fb30b84949392d0dd969ce1f2d
|
Java
|
amit8800/conx2share-solved
|
/app/src/main/java/com/conx2share/conx2share/ui/sign_up/BusinessSignUpWebActivity.java
|
UTF-8
| 11,195
| 1.609375
| 2
|
[] |
no_license
|
package com.conx2share.conx2share.ui.sign_up;
import com.conx2share.conx2share.BuildConfig;
import com.conx2share.conx2share.R;
import com.conx2share.conx2share.ui.discover.DiscoverActivity;
import com.conx2share.conx2share.util.ForegroundUtil;
import com.conx2share.conx2share.util.MediaUploadUtil;
import com.conx2share.conx2share.util.PreferencesUtil;
import com.conx2share.conx2share.util.Statics;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.inject.Inject;
import roboguice.RoboGuice;
import roboguice.activity.RoboActivity;
public class BusinessSignUpWebActivity extends RoboActivity {
public static final String TAG = BusinessSignUpWebActivity.class.getSimpleName();
public static final String BUSINESS_USER_ID = "business_user_id";
private final static int FILECHOOSER_CODE = 1;
private final static int FILECHOOSER_LOLLIPOP_CODE = 2;
private ValueCallback<Uri> mUploadMessage;
// after business information is entered, we are redirected to a url like businesses/35
public static final String BUSINESS_SETUP_COMPLETE_URL = Statics.BASE_URL + "/businesses/[0-9]+";
// the '#' in this string will be replaced with the user's id, the authtoken will be appended
private static final String BUSINESS_SIGNUP_URL = Statics.BASE_URL + "/businesses/new?user_id=#&auth_token=";
@Inject
private PreferencesUtil mPreferencesUtil;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
private AlertDialog mDialog;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
RoboGuice.getInjector(this).injectMembersWithoutViews(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_web_signup);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.loadUrl(makeUrl());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "onPageStarted: " + url);
super.onPageStarted(view, url, favicon);
boolean override = url.matches(BUSINESS_SETUP_COMPLETE_URL);
if (override) {
progressBar.setVisibility(View.VISIBLE);
startDiscoverActivity();
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, String.format("onReceivedError {errorCode: %d, description: '%s', failingUrl: '%s'}", errorCode, description, failingUrl));
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "shouldOverrideUrlLoading: " + url);
return url.matches(BUSINESS_SETUP_COMPLETE_URL);
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_CODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_CODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser( i, "File Chooser" ), FILECHOOSER_CODE );
}
// For Android 5.0 - had to do a lot of research, look at:
// - http://stackoverflow.com/questions/5907369/file-upload-in-webview
// - https://gauntface.com/blog/2014/10/17/what-you-need-to-know-about-the-webview-in-l
// - Logic based off of/taken from example here https://github.com/GoogleChrome/chromium-webview-samples/blob/master/input-file-example/app/src/main/java/inputfilesample/android/chrome/google/com/inputfilesample/MainFragment.java
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if(mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
Log.e(TAG, "Unable to create Image File", ex);
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if(takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_CODE);
return true;
}
});
}
@Override
protected void onResume() {
super.onResume();
ForegroundUtil.setAppInForeground(true);
}
@Override
protected void onPause() {
super.onPause();
ForegroundUtil.setAppInForeground(false);
}
@Override
public void onBackPressed() {
if (mDialog != null) {
return;
}
mDialog = new AlertDialog.Builder(this)
.setMessage(getString(R.string.abort_business_details_confirmation))
.setPositiveButton(R.string.abort, (dialog, which) -> {
mDialog = null;
startDiscoverActivity();
})
.setNegativeButton(R.string.cancel, (dialog, which) -> {
mDialog = null;
dialog.dismiss();
})
.setCancelable(false)
.show();
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
private void startDiscoverActivity() {
Intent intent = new Intent(this, DiscoverActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
startActivity(intent);
}
private String makeUrl() {
int businessId = getIntent().getIntExtra(BUSINESS_USER_ID, -1);
if (businessId == -1) {
throw new RuntimeException("Expected a business_user_id extra");
}
return BUSINESS_SIGNUP_URL.replaceFirst("#", String.valueOf(businessId)) + mPreferencesUtil.getAuthToken();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == FILECHOOSER_CODE) {
if (null == mUploadMessage) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else if (requestCode == FILECHOOSER_LOLLIPOP_CODE) {
Uri[] results = null;
if(resultCode == Activity.RESULT_OK) {
if(data == null) {
if(mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| true
|
675891ad79963b91c7ce2888f30f87733cdb425b
|
Java
|
dukererenst/SegmentDialogFX
|
/src/main/java/com/dansoftware/sgmdialog/Segment.java
|
UTF-8
| 2,522
| 2.875
| 3
|
[] |
no_license
|
package com.dansoftware.sgmdialog;
import javafx.scene.Node;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.MissingResourceException;
import java.util.Objects;
import java.util.ResourceBundle;
/**
* A {@link Segment} object represents a 'slide' of a {@link SegmentDialog}.
*
* <p>
* A {@link Segment} is not a GUI element itself, but it should create a {@link Node}
* with the {@link #getContent()} method.
*
* <p>
* Every segment has a <b>name</b> that will appear in the label-area in the top of the {@link SegmentDialog}.
* <i>It can be internationalized using the constructor that accepts a ResourceBundle</i>
*
* @author Daniel Gyorffy
*/
public abstract class Segment {
private ResourceBundle resourceBundle;
private final String name;
public Segment(@NotNull String name) {
this.name = Objects.requireNonNull(name);
}
public Segment(@Nullable ResourceBundle resourceBundle,
@NotNull String name) {
this.resourceBundle = resourceBundle;
this.name = getI18nValue(resourceBundle, Objects.requireNonNull(name));
}
protected final ResourceBundle getResourceBundle() {
return resourceBundle;
}
public String getName() {
return name;
}
/**
* Called when the particular {@link Segment} is left, and a new segment is shown.
*
* @param segmentDialog the owner {@link SegmentDialog}
*/
protected void onSegmentHidden(@NotNull SegmentDialog segmentDialog) {
}
/**
* Called when the particular {@link Segment} is shown to the user.
*
* @param segmentDialog the owner {@link SegmentDialog}
*/
protected void onSegmentFocused(@NotNull SegmentDialog segmentDialog) {
}
/**
* Called when the user skips the particular {@link Segment}.
*
* @param segmentDialog the owner {@link SegmentDialog}
*/
protected void onSegmentSkipped(@NotNull SegmentDialog segmentDialog) {
}
/**
* This method is called when the particular segment is on focus, and a
* GUI element is needed.
*
* @return the {@link Node} content; shouldn't be null
*/
@NotNull
protected abstract Node getContent();
static String getI18nValue(ResourceBundle resourceBundle, String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException | NullPointerException e) {
return key;
}
}
}
| true
|
5afbeb71d6f0c46f9f8399a915423f818f7e645b
|
Java
|
kirke-ashton/tesco-vending-machine
|
/vm/src/main/java/com/tesco/vm/money/Money.java
|
UTF-8
| 1,518
| 2.875
| 3
|
[] |
no_license
|
package com.tesco.vm.money;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import com.tesco.vm.dao.coin.CoinDao;
import com.tesco.vm.model.coin.Coin;
public class Money {
public static final int UNKNOWN_COIN = 0;
@Inject
private CoinDao coinDao;
private List<Coin> acceptedCoins = new ArrayList<>(0);
private int totalValue = 0;
public Money() {
}
public void getAcceptedCoins() {
List<Coin> coins = coinDao.getCoins();
if (coins != null) {
for (Coin coin : coins) {
if (coin.isAccepted()) {
acceptedCoins.add(coin);
}
}
}
}
public boolean isCoinAccepted(int value) {
boolean accepted = false;
if (!acceptedCoins.isEmpty()) {
for (Coin coin : acceptedCoins) {
if (coin.getValue() == value) {
accepted = true;
}
}
}
return accepted;
}
/*
* A return of false, indicates that the coin is invalid
*/
public boolean coinEntered(int value) {
boolean validCoin = false;
if ((UNKNOWN_COIN != value) && (isCoinAccepted(value))) {
setValueEntered(value);
validCoin = true;
}
return validCoin;
}
public int setValueEntered(int value) {
if (isCoinAccepted(value)) {
totalValue = totalValue + value;
}
return totalValue;
}
public int getTotalValueEntered() {
return totalValue;
}
public void clearTotalValueEntered() {
totalValue = 0;
}
}
| true
|
3ce32c5d79f04c4571757b9546bcb0864539f16d
|
Java
|
wildfly/quickstart
|
/websocket-endpoint/src/main/java/org/jboss/quickstarts/websocket/BidWebSocketEndpoint.java
|
UTF-8
| 4,217
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.quickstarts.websocket;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import jakarta.annotation.PostConstruct;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.jboss.quickstarts.websocket.model.Bid;
import org.jboss.quickstarts.websocket.model.Bidding;
import org.jboss.quickstarts.websocket.model.BiddingFactory;
/**
* WebSocket server endpoint example
* <p/>
*
* This class produces a Websocket endpoint to receive messages from clients.
*
* @author <a href="mailto:benevides@redhat.com">Rafael Benevides</a>
*
*/
@ServerEndpoint(value = "/bidsocket", encoders = { BiddingEncoder.class }, decoders = { MessageDecoder.class })
public class BidWebSocketEndpoint {
private Logger logger = Logger.getLogger(getClass().getName());
private static Set<Session> clients = Collections.synchronizedSet(new HashSet<>());
private Runnable intervalNotifier;
// It starts a Thread that notifies all sessions each second
@PostConstruct
public void startIntervalNotifier() {
logger.info("Starting interval notifier");
intervalNotifier = new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
notifyAllSessions(BiddingFactory.getBidding());
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(intervalNotifier).start();
}
// store the session once that it's opened
@OnOpen
public void onOpen(Session session) {
logger.info("New websocket session opened: " + session.getId());
clients.add(session);
}
// remove the session after it's closed
@OnClose
public void onClose(Session session) {
logger.info("Websoket session closed: " + session.getId());
clients.remove(session);
}
// This method receives a Message that contains a command
// The Message object is "decoded" by the MessageDecoder class
@OnMessage
public void onMessage(Session session, Message message) throws IOException, EncodeException {
if (message.getCommand().equals("newBid")) {
Bidding bidding = BiddingFactory.getBidding();
bidding.addBid(new Bid(session.getId(), message.getBidValue()));
}
if (message.getCommand().equals("buyItNow")) {
Bidding bidding = BiddingFactory.getBidding();
bidding.buyItNow();
}
if (message.getCommand().equals("resetBid")) {
BiddingFactory.resetBidding();
}
notifyAllSessions(BiddingFactory.getBidding());
}
// Exception handling
@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
}
// This method sends the same Bidding object to all opened sessions
private void notifyAllSessions(Bidding bidding) throws EncodeException, IOException {
for (Session s : clients) {
s.getBasicRemote().sendObject(bidding);
}
}
}
| true
|
53c734e5ad4e50ac58a7c2a70916c2d9b960e51a
|
Java
|
formularrr/ThinkingInJava
|
/src/Factory/UnicycleFactory.java
|
UTF-8
| 136
| 2.484375
| 2
|
[] |
no_license
|
package Factory;
public class UnicycleFactory implements CycleFactory{
public Cycle getCycle(){
return (Cycle) new Unicycle();
}
}
| true
|
2f97f4e2fc5dbfc1193ad9f3a1126babd8443ae7
|
Java
|
ahsan2010/sequence-tagger
|
/src/edu/jhu/nlp/sequence/classify/OutputCallback.java
|
UTF-8
| 232
| 1.679688
| 2
|
[
"Apache-2.0"
] |
permissive
|
package edu.jhu.nlp.sequence.classify;
import cc.mallet.types.Sequence;
/**
*
* @author Delip Rao
*
*/
public interface OutputCallback {
@SuppressWarnings("unchecked")
public void process(Sequence input, Sequence output);
}
| true
|
64dc733de092daa9bf6c327cf4a1e4d1693e152f
|
Java
|
google-code/big-data-process-and-information-integration
|
/MetadataServiceClient/Sources/com/agilis/SDMXRegistry/beans/LinkedMetadataFlowBean.java
|
UTF-8
| 3,187
| 2.53125
| 3
|
[] |
no_license
|
package com.agilis.SDMXRegistry.beans;
import java.util.List;
import com.agilis.SDMXRegistry.web.Constants;
/**
* JavaBean Class representing a linked Metadata flow bean.
* This type of objects is used for linking categories with
* either data or metadata flows.
*/
public class LinkedMetadataFlowBean {
private String metadataId;
private String metadataVersion;
private String metadataAgencyId;
// duplicate variables unfortunately for backward compatibility
private String agencyID;
private String metadataflowID;
private String version;
// end
public String getMetadataAgencyId() {
return metadataAgencyId;
}
public void setMetadataAgencyId(String metadataAgencyId) {
this.metadataAgencyId = metadataAgencyId;
this.agencyID = metadataAgencyId;
}
public String getMetadataId() {
return metadataId;
}
public void setMetadataId(String metadataId) {
this.metadataId = metadataId;
this.metadataflowID = metadataId;
}
public String getMetadataVersion() {
return metadataVersion;
}
public void setMetadataVersion(String metadataVersion) {
this.metadataVersion = metadataVersion;
this.version = metadataVersion;
}
// duplicate methods unfortunately for backward compatibility
public String getAgencyID() {
return agencyID;
}
public void setAgencyID(String agencyID) {
this.agencyID = agencyID;
this.metadataAgencyId = agencyID;
}
public String getMetadataflowID() {
return metadataflowID;
}
public void setMetadataflowID(String metadataflowID) {
this.metadataflowID = metadataflowID;
this.metadataId = metadataflowID;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
this.metadataVersion = version;
}
// end
// override equals() and hashCode() methods for comparison reasons
public boolean equals(Object obj) {
if(this.metadataflowID == null ||
this.version == null ||
this.agencyID == null) return super.equals(obj);
if (this == obj) return true;
if (!(obj instanceof LinkedMetadataFlowBean)) return false;
LinkedMetadataFlowBean mdf = (LinkedMetadataFlowBean)obj;
return ((this.metadataflowID.equals(mdf.getMetadataflowID())) &&
(this.version.equals(mdf.getVersion())) &&
(this.agencyID.equals(mdf.getAgencyID())));
}
// override equals() and hashCode() methods for comparison reasons
public int hashCode() {
if(this.metadataflowID == null ||
this.version == null ||
this.agencyID == null) return super.hashCode();
return (31 + this.metadataflowID.hashCode() +
this.version.hashCode() +
this.agencyID.hashCode());
}
public StringBuffer toXML() {
StringBuffer result = new StringBuffer(Constants.NEW_LINE);
result.append("<s:MetadataflowRef>").append(Constants.NEW_LINE)
.append("<s:AgencyID>").append(this.agencyID).append("</s:AgencyID>").append(Constants.NEW_LINE)
.append("<s:MetadataflowID>").append(this.metadataflowID).append("</s:MetadataflowID>").append(Constants.NEW_LINE)
.append("<s:Version>").append(this.getVersion()).append("</s:Version>").append(Constants.NEW_LINE)
.append("</s:MetadataflowRef>");
return result;
}
}
| true
|
3189a8af291004ab636ce145c635cdd68d76f674
|
Java
|
JetBrains/intellij-plugins
|
/flex/tools/flexmojos-flex-configs-generator/idea-configurator/src/com/intellij/flex/maven/IdeaConfigurator.java
|
UTF-8
| 11,933
| 1.734375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.intellij.flex.maven;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.project.MavenProject;
import org.sonatype.flexmojos.compiler.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
public class IdeaConfigurator implements FlexConfigGenerator {
protected static final String PATH_ELEMENT = "path-element";
protected static final String FILE_SPECS = "file-specs";
protected static final String LOCAL_FONTS_SNAPSHOT = "local-fonts-snapshot";
private static final String FONTS_SER = "fonts.ser";
protected final MavenSession session;
protected final StringBuilder out;
private Build build;
private String classifier;
protected final File outputDirectory;
@SuppressWarnings("StaticNonFinalField")
protected static File sharedFontsSer;
@SuppressWarnings("StaticNonFinalField")
protected static String sharedFontsSerPath;
private boolean staticLinkRuntimeSharedLibrariesSpecified;
public IdeaConfigurator(MavenSession session, File outputDirectory) {
this.session = session;
this.outputDirectory = outputDirectory;
out = new StringBuilder(8192);
out.append("<flex-config xmlns=\"http://www.adobe.com/2006/flex-config\">");
}
@Override
public void generate(Mojo configuration, File sourceFile) throws Exception {
build(configuration, ICommandLineConfiguration.class, "\n\t", null);
out.append("\n\t<file-specs>\n");
writeTag("\t", PATH_ELEMENT, sourceFile.getAbsolutePath(), FILE_SPECS);
out.append("\n\t</file-specs>");
}
@Override
public void generate(Mojo configuration) throws Exception {
build(configuration, ICompcConfiguration.class, "\n\t", null);
}
@Override
public void preGenerate(MavenProject project, String classifier) throws IOException {
this.classifier = classifier;
build = project.getBuild();
}
@Override
public String postGenerate(MavenProject project) throws IOException {
if (!staticLinkRuntimeSharedLibrariesSpecified) {
out.append("\n<static-link-runtime-shared-libraries>false</static-link-runtime-shared-libraries>");
}
out.append("\n</flex-config>");
final String configFile = getConfigFilePath(project, classifier);
Utils.write(out, new File(outputDirectory, configFile));
return configFile;
}
protected String getConfigFilePath(MavenProject project, String classifier) {
// artifact id is first in path - it is convenient for us
StringBuilder pathBuilder = new StringBuilder(32).append(project.getArtifactId()).append('-').append(project.getGroupId());
if (classifier != null) {
pathBuilder.append('-').append(classifier);
}
return pathBuilder.append(".xml").toString();
}
@SuppressWarnings("ConstantConditions")
private <E> void build(E configuration, Class<?> configClass, String indent, String configurationName) throws Exception {
boolean parentTagWritten = configurationName == null;
final Method[] methods = configClass.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
@Override
public int compare(Method o1, Method o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Method method : methods) {
method.setAccessible(true);
if (method.getParameterTypes().length != 0) {
continue;
}
final String methodName = method.getName();
if (methodName.equals("getLoadConfig") || methodName.equals(
"getDumpConfig") || "metadata".equals(configurationName) && methodName.equals("getDate")) {
continue;
}
final Object value = method.invoke(configuration);
if (value == null) {
continue;
}
if ((methodName.equals("getFixedLiteralVector") || methodName.equals("getHeadlessServer")) && !((Boolean)value)) {
continue;
}
// https://youtrack.jetbrains.com/issue/IDEA-108572
if (!staticLinkRuntimeSharedLibrariesSpecified && methodName.equals("getStaticLinkRuntimeSharedLibraries")) {
staticLinkRuntimeSharedLibrariesSpecified = true;
}
if (!parentTagWritten) {
parentTagWritten = true;
out.append(indent, 0, indent.length() - 1).append('<').append(configurationName).append('>');
}
final Class<?> returnType = method.getReturnType();
final String name = camelCaseToSnake(methodName, true);
if (value instanceof IFlexConfiguration) {
build(value, returnType, indent + '\t', name.substring(0, name.length() - 14));
}
else if (configuration instanceof IASDocConfiguration && "footer".equals(name)) {
// todo
throw new UnsupportedOperationException();
}
else if (value instanceof IRuntimeSharedLibraryPath || value instanceof IRuntimeSharedLibraryPath[]) {
final IRuntimeSharedLibraryPath[] values;
if (returnType.isArray()) {
//noinspection ConstantConditions
values = (IRuntimeSharedLibraryPath[])value;
}
else {
//noinspection ConstantConditions
values = new IRuntimeSharedLibraryPath[]{(IRuntimeSharedLibraryPath)value};
}
for (IRuntimeSharedLibraryPath arg : values) {
out.append("\n\t<").append(name).append(">\n\t\t<path-element>").append(arg.pathElement()).append("</path-element>");
//noinspection unchecked
for (Map.Entry<String, String> entry : (Set<Map.Entry<String, String>>)arg.rslUrl().entrySet()) {
out.append("\n\t\t<rsl-url>").append(entry.getKey()).append("</rsl-url>");
if (entry.getValue() != null) {
out.append("\n\t\t<policy-file-url>").append(entry.getValue()).append("</policy-file-url>");
}
}
out.append("\n\t</").append(name).append('>');
}
}
else if (value instanceof IFlexArgument || value instanceof IFlexArgument[]) {
IFlexArgument[] values;
Class<?> type = returnType;
if (type.isArray()) {
//noinspection ConstantConditions
values = (IFlexArgument[])value;
type = returnType.getComponentType();
}
else {
//noinspection ConstantConditions
values = new IFlexArgument[]{(IFlexArgument)value};
type = returnType;
}
String[] order = (String[])type.getField("ORDER").get(returnType);
for (IFlexArgument iFlexArgument : values) {
out.append(indent).append('<').append(name).append('>');
for (String argMethodName : order) {
Object argValue = type.getDeclaredMethod(argMethodName).invoke(iFlexArgument);
if (argValue instanceof Collection<?> || argValue.getClass().isArray()) {
Object[] subValues = argValue.getClass().isArray() ? (Object[])argValue : ((Collection<?>)argValue).toArray();
for (Object subArgValue : subValues) {
writeTag(indent, argMethodName, subArgValue.toString(), name);
}
}
else if (argValue instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) argValue;
for (Object argValue1 : map.entrySet()) {
@SuppressWarnings("unchecked")
Map.Entry<String, ?> entry = (Map.Entry<String, ?>) argValue1;
if (entry.getValue() != null) {
writeTag(indent, entry.getKey(), entry.getValue().toString(), name);
}
}
}
else if (argValue != null) {
// IDEA-109745
String xmlSrgMethodName;
if (argMethodName.equals("serialNumber") || name.equals("default-script-limits")) {
xmlSrgMethodName = camelCaseToSnake(argMethodName, false);
}
else {
xmlSrgMethodName = argMethodName;
}
writeTag(indent, xmlSrgMethodName, (String)argValue, name);
}
}
out.append(indent).append("</").append(name).append('>');
}
}
else if (name.equals("load-externs") ||
configuration instanceof IMetadataConfiguration &&
(name.equals("language") || name.equals("creator") || name.equals("publisher") || name.equals("contributor"))) {
for (String v : (String[])value) {
out.append(indent).append('<').append(name).append('>').append(v).append("</").append(name).append('>');
}
}
else if (returnType.isArray() || value instanceof Collection<?>) {
Object[] values = returnType.isArray() ? (Object[])value : ((Collection<?>)value).toArray();
// ability to compile pure AS3 project without themes - node must be present, but empty (relevant only for "theme")
if (values.length == 0) {
if (name.equals("theme") || name.equals("locale")) {
out.append(indent).append('<').append(name).append("/>");
}
}
else {
out.append(indent).append('<').append(name).append('>');
String childTagName = Utils.CHILD_TAG_NAME_MAP.get(name);
if (childTagName == null) {
childTagName = PATH_ELEMENT;
}
for (Object v : values) {
if (v == null) {
System.out.print('\n' + childTagName + " child value for " + name + " is null\n");
}
else {
writeTag(indent, childTagName, v.toString(), name);
}
}
out.append(indent).append("</").append(name).append('>');
}
}
else {
out.append(indent).append('<').append(name).append('>');
processValue(value.toString(), name);
out.append("</").append(name).append('>');
}
}
if (parentTagWritten && configurationName != null) {
out.append(indent, 0, indent.length() - 1).append("</").append(configurationName).append('>');
}
}
protected void processValue(String value, String name) throws IOException {
// http://juick.com/develar/1363289
if (name.equals(LOCAL_FONTS_SNAPSHOT)) {
final File fontsSer = new File(build.getOutputDirectory(), FONTS_SER);
String defaultPath;
// the same as flexmojos does
try {
defaultPath = fontsSer.getCanonicalPath();
}
catch (IOException e) {
defaultPath = fontsSer.getAbsolutePath();
}
if (value.equals(defaultPath)) {
if (sharedFontsSerPath == null) {
sharedFontsSer = new File(outputDirectory, FONTS_SER);
//noinspection NonThreadSafeLazyInitialization
sharedFontsSerPath = sharedFontsSer.getPath();
if (!sharedFontsSer.exists()) {
Utils.copyFile(fontsSer, sharedFontsSer);
}
}
value = sharedFontsSerPath;
}
}
out.append(value);
}
protected void writeTag(String indent, String name, String value, String parentName) throws IOException {
out.append(indent).append("\t<").append(name).append('>').append(value).append("</").append(name).append('>');
}
private static String camelCaseToSnake(final String s, boolean removePrefix) {
StringBuilder builder = new StringBuilder(s.length() + 4 /* probable max hyphen count */);
for (int i = removePrefix ? removePrefix(s) : 0, n = s.length(); i < n; i++) {
char c = s.charAt(i);
if (Character.isUpperCase(c)) {
builder.append('-').append(Character.toLowerCase(c));
}
else {
builder.append(c);
}
}
return builder.substring(builder.charAt(0) == '-' ? 1 : 0);
}
private static int removePrefix(String s) {
int cut = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
cut = i;
break;
}
}
return cut;
}
}
| true
|
a998d5f14bc79caa5fb4d3e60ccca6922d70e3bc
|
Java
|
a2en/Zenly_re
|
/src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/app/zenly/locator/p208y/C6294e.java
|
UTF-8
| 698
| 1.664063
| 2
|
[] |
no_license
|
package app.zenly.locator.p208y;
import app.zenly.locator.p208y.C6288c.C6292d;
import kotlin.NoWhenBranchMatchedException;
import kotlin.jvm.internal.C12932j;
import p213co.znly.core.romutils.Resolution;
/* renamed from: app.zenly.locator.y.e */
public final class C6294e {
/* renamed from: a */
public static final C6292d m17353a(Resolution resolution) {
C12932j.m33818b(resolution, "$this$toStepType");
int i = C6293d.f15811a[resolution.getId().ordinal()];
if (i == 1 || i == 2) {
return C6292d.AUTO_STARTUP;
}
if (i == 3) {
return C6292d.ENERGY_SAVING;
}
throw new NoWhenBranchMatchedException();
}
}
| true
|
3755dfe152c2b370fc698903a84e81ee58c89b36
|
Java
|
ogorifuwe/ds-and-algorithms
|
/compositions/com/oi/algo/array/TwoSumII.java
|
UTF-8
| 796
| 3.84375
| 4
|
[] |
no_license
|
/**
*
*/
package com.oi.algo.array;
class TwoSumII {
public static void main(String[] args) {
int[] numbers = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(numbers, target);
System.out.println("result: " + java.util.Arrays.toString(result));
}
/**
* Two pointers
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
protected static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
int low = 0, high = numbers.length-1;
while (low < high) {
int summation = numbers[low] + numbers[high];
if (target == summation) {
result[0] = low + 1;
result[1] = high + 1;
break;
} else if (summation < target)
++low;
else
--high;
}
return result;
}
}
| true
|
011886843b4ffab0f3d573585a6048f5e90a1ee4
|
Java
|
TakuSemba/RetrofitDownloader
|
/app/src/main/kotlin/com/takusemba/retrofitdownloader/SeriesThemeColor.java
|
UTF-8
| 7,187
| 2.078125
| 2
|
[] |
no_license
|
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: api/media.proto at 233:1
package tv.abema.protos;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireField;
import com.squareup.wire.internal.Internal;
import java.io.IOException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import okio.ByteString;
/**
* / テーマカラー
*/
public final class SeriesThemeColor extends Message<SeriesThemeColor, SeriesThemeColor.Builder> {
public static final ProtoAdapter<SeriesThemeColor> ADAPTER = new ProtoAdapter_SeriesThemeColor();
private static final long serialVersionUID = 0L;
public static final String DEFAULT_PRIMARY = "";
public static final String DEFAULT_SECONDARY = "";
public static final String DEFAULT_DETAIL = "";
public static final String DEFAULT_BACKGROUND = "";
/**
* / プライマリ
*/
@WireField(
tag = 1,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String primary;
/**
* / セカンダリ
*/
@WireField(
tag = 2,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String secondary;
/**
* / ディティール
*/
@WireField(
tag = 3,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String detail;
/**
* / 背景
*/
@WireField(
tag = 4,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String background;
public SeriesThemeColor(String primary, String secondary, String detail, String background) {
this(primary, secondary, detail, background, ByteString.EMPTY);
}
public SeriesThemeColor(String primary, String secondary, String detail, String background, ByteString unknownFields) {
super(ADAPTER, unknownFields);
this.primary = primary;
this.secondary = secondary;
this.detail = detail;
this.background = background;
}
@Override
public Builder newBuilder() {
Builder builder = new Builder();
builder.primary = primary;
builder.secondary = secondary;
builder.detail = detail;
builder.background = background;
builder.addUnknownFields(unknownFields());
return builder;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof SeriesThemeColor)) return false;
SeriesThemeColor o = (SeriesThemeColor) other;
return Internal.equals(unknownFields(), o.unknownFields())
&& Internal.equals(primary, o.primary)
&& Internal.equals(secondary, o.secondary)
&& Internal.equals(detail, o.detail)
&& Internal.equals(background, o.background);
}
@Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = unknownFields().hashCode();
result = result * 37 + (primary != null ? primary.hashCode() : 0);
result = result * 37 + (secondary != null ? secondary.hashCode() : 0);
result = result * 37 + (detail != null ? detail.hashCode() : 0);
result = result * 37 + (background != null ? background.hashCode() : 0);
super.hashCode = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (primary != null) builder.append(", primary=").append(primary);
if (secondary != null) builder.append(", secondary=").append(secondary);
if (detail != null) builder.append(", detail=").append(detail);
if (background != null) builder.append(", background=").append(background);
return builder.replace(0, 2, "SeriesThemeColor{").append('}').toString();
}
public static final class Builder extends Message.Builder<SeriesThemeColor, Builder> {
public String primary;
public String secondary;
public String detail;
public String background;
public Builder() {
}
/**
* / プライマリ
*/
public Builder primary(String primary) {
this.primary = primary;
return this;
}
/**
* / セカンダリ
*/
public Builder secondary(String secondary) {
this.secondary = secondary;
return this;
}
/**
* / ディティール
*/
public Builder detail(String detail) {
this.detail = detail;
return this;
}
/**
* / 背景
*/
public Builder background(String background) {
this.background = background;
return this;
}
@Override
public SeriesThemeColor build() {
return new SeriesThemeColor(primary, secondary, detail, background, buildUnknownFields());
}
}
private static final class ProtoAdapter_SeriesThemeColor extends ProtoAdapter<SeriesThemeColor> {
ProtoAdapter_SeriesThemeColor() {
super(FieldEncoding.LENGTH_DELIMITED, SeriesThemeColor.class);
}
@Override
public int encodedSize(SeriesThemeColor value) {
return (value.primary != null ? ProtoAdapter.STRING.encodedSizeWithTag(1, value.primary) : 0)
+ (value.secondary != null ? ProtoAdapter.STRING.encodedSizeWithTag(2, value.secondary) : 0)
+ (value.detail != null ? ProtoAdapter.STRING.encodedSizeWithTag(3, value.detail) : 0)
+ (value.background != null ? ProtoAdapter.STRING.encodedSizeWithTag(4, value.background) : 0)
+ value.unknownFields().size();
}
@Override
public void encode(ProtoWriter writer, SeriesThemeColor value) throws IOException {
if (value.primary != null) ProtoAdapter.STRING.encodeWithTag(writer, 1, value.primary);
if (value.secondary != null) ProtoAdapter.STRING.encodeWithTag(writer, 2, value.secondary);
if (value.detail != null) ProtoAdapter.STRING.encodeWithTag(writer, 3, value.detail);
if (value.background != null) ProtoAdapter.STRING.encodeWithTag(writer, 4, value.background);
writer.writeBytes(value.unknownFields());
}
@Override
public SeriesThemeColor decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1;) {
switch (tag) {
case 1: builder.primary(ProtoAdapter.STRING.decode(reader)); break;
case 2: builder.secondary(ProtoAdapter.STRING.decode(reader)); break;
case 3: builder.detail(ProtoAdapter.STRING.decode(reader)); break;
case 4: builder.background(ProtoAdapter.STRING.decode(reader)); break;
default: {
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
@Override
public SeriesThemeColor redact(SeriesThemeColor value) {
Builder builder = value.newBuilder();
builder.clearUnknownFields();
return builder.build();
}
}
}
| true
|
7ba5db7a1f1a7822642d9528b63187dc60b59874
|
Java
|
Elovard/transcationExtractor
|
/src/main/java/extractor/command/PrintAllTransactionsCommand.java
|
UTF-8
| 614
| 2.5625
| 3
|
[] |
no_license
|
package extractor.command;
import extractor.entity.Transaction;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class PrintAllTransactionsCommand extends Command implements BeanPostProcessor {
@Override
public void execute(final List<Transaction> transactions) {
System.out.println("Here's the list of transactions: ");
transactions.forEach(System.out::println);
}
@Override
public String getCommandDescription() {
return "Print all transactions";
}
}
| true
|
89402feb8f68228f4e8f51869d7e86113afc2351
|
Java
|
lonmong/AppSTLP-Android-
|
/app/src/main/java/stlpapp/finalproject/app/com/appstlp/controller/ApproveRequestController.java
|
UTF-8
| 3,327
| 2.234375
| 2
|
[] |
no_license
|
package stlpapp.finalproject.app.com.appstlp.controller;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import stlpapp.finalproject.app.com.appstlp.R;
import stlpapp.finalproject.app.com.appstlp.model.CenterModel;
import stlpapp.finalproject.app.com.appstlp.model.RequestForHelpModel;
import stlpapp.finalproject.app.com.appstlp.task.WSTask;
public class ApproveRequestController {
private static ApproveRequestController wsManager;
private Context context;
public interface ApproveRequestControllerListener {
void onComplete(Object response);
void onError(String err);
}
public ApproveRequestController(Context context) {
this.context = context;
}
public static ApproveRequestController getWsManager(Context context) {
if (wsManager == null)
wsManager = new ApproveRequestController(context);
return wsManager;
}
public void listRequestByTelCenter(String telcenter,final ApproveRequestControllerListener listener) {
WSTask task = new WSTask(this.context,new WSTask.WSTaskListener() {
@Override
public void onComplete(String response) {
RequestForHelpModel requestForHelpModel = new RequestForHelpModel(response);
listener.onComplete(requestForHelpModel);
}
@Override
public void onError(String err) {
listener.onError(err);
}
});
Gson gson = new GsonBuilder().create();
String telcenterjson= gson.toJson(telcenter);
task.execute(context.getString(R.string.getRequestByTelCenter_url),telcenterjson);
}
public void detailRequestByUsername(String username, final ApproveRequestControllerListener listener) {
WSTask task = new WSTask(this.context,new WSTask.WSTaskListener() {
@Override
public void onComplete(String response) {
RequestForHelpModel requestForHelpModel = new RequestForHelpModel(response);
listener.onComplete(requestForHelpModel);
}
@Override
public void onError(String err) {
listener.onError(err);
}
});
Gson gson = new GsonBuilder().create();
String usernamejson= gson.toJson(username);
task.execute(context.getString(R.string.getdetailrequestbyusername_url), usernamejson);
}
public void setApproveRequestStatus(Object object,final ApproveRequestControllerListener listener) {
if (!(object instanceof RequestForHelpModel)) {
return;
}
final RequestForHelpModel requestForHelpModel = (RequestForHelpModel) object;
WSTask task = new WSTask(this.context,new WSTask.WSTaskListener() {
@Override
public void onComplete(String response) {
RequestForHelpModel requestForHelpModel1 = new RequestForHelpModel(response);
listener.onComplete(requestForHelpModel1);
}
@Override
public void onError(String err) {
listener.onError(err);
}
});
task.execute(context.getString(R.string.approve_request_url),requestForHelpModel.toJSONString());
}
}
| true
|
a479d1754e76a6bd1ae92c3278f036460de80ef0
|
Java
|
OMARIHAMZA/quizmaker
|
/app/src/main/java/hamza/quizmaker/view/adapters/HomeAdapter.java
|
UTF-8
| 3,941
| 2.25
| 2
|
[] |
no_license
|
package hamza.quizmaker.view.adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import hamza.quizmaker.R;
import hamza.quizmaker.api.MyRequests;
import hamza.quizmaker.models.Category;
import hamza.quizmaker.models.Question;
import hamza.quizmaker.parsers.QuizParser;
import hamza.quizmaker.utils.Dialogs;
import hamza.quizmaker.view.QuizActivity;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
private ArrayList<Category> categories;
private Activity mActivity;
private Dialog mLoadingDialog;
public HomeAdapter(Activity mActivity) {
this.mActivity = mActivity;
categories = new ArrayList<>();
categories.add(new Category("1", "Sport", R.mipmap.football));
categories.add(new Category("2", "Technology", R.mipmap.desktop));
categories.add(new Category("3", "Maths", R.mipmap.calculation));
categories.add(new Category("4", "Music", R.mipmap.acoustic_guitar));
mLoadingDialog = Dialogs.getLoadingDialog(mActivity);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_card, parent, false);
int screenWidth = getScreenWidth(mActivity);
itemView.getLayoutParams().width = screenWidth / 2;
itemView.getLayoutParams().height = screenWidth / 2;
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.categoryTitleTextView.setText(categories.get(position).getCategoryName());
holder.categoryImageView.setImageResource(categories.get(position).getCategoryImageResource());
holder.cardView.setOnClickListener(view -> {
mLoadingDialog.show();
MyRequests.getQuizzes(String.valueOf(position + 1), mActivity, response -> {
mLoadingDialog.dismiss();
ArrayList<Question> questions = QuizParser.ParseQuiz(response);
Intent intent = new Intent(mActivity, QuizActivity.class);
intent.putExtra("questions", questions);
mActivity.startActivity(intent);
}, error -> {
mLoadingDialog.dismiss();
Toast.makeText(mActivity, "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
});
});
}
@Override
public int getItemCount() {
return categories.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView categoryImageView;
TextView categoryTitleTextView;
CardView cardView;
View itemView;
MyViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
categoryImageView = itemView.findViewById(R.id.category_imageView);
categoryTitleTextView = itemView.findViewById(R.id.category_title_textView);
cardView = itemView.findViewById(R.id.cardView);
}
}
private int getScreenWidth(Activity mActivity) {
WindowManager windowManager = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
Display mDisplay = windowManager.getDefaultDisplay();
Point size = new Point();
mDisplay.getSize(size);
return size.x;
}
}
| true
|
c26e10a9fc3dcc6cceb10e98afe54889e7b7e01e
|
Java
|
213gml/Quiz3
|
/Quiz3/src/test/java/base/Quiz3Test.java
|
UTF-8
| 1,165
| 2.96875
| 3
|
[] |
no_license
|
package base;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class Quiz3Test {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
Triangle t1 = new Triangle(5, 8, 4);
assertTrue(t1.getArea(t1) == 8.18);
}
@Test
public void test2() {
Triangle t2 = new Triangle(6, 4, 3);
assertTrue(t2.getArea(t2) == 5.33);
assertTrue(t2.getPerimeter(t2) == 18);
}
@Test
public void test3() {
Triangle t1 = new Triangle(5, 8, 4);
assertTrue(t1.getPerimeter(t1) == 17);
}
@Test
public void test4() {
Triangle t3 = new Triangle(1, 2, 1);
assertTrue(t3.ToString(t3) == "Area: " + t3.getArea(t3) +
"\nPerimeter: " + t3.getPerimeter(t3));
}
private void assertTrue(boolean b) {
}
}
| true
|
d581437191f475ca392c9109cec5a506390575fd
|
Java
|
gabrielromagnoli1987/springboot
|
/src/main/java/backend/dao/CarDao.java
|
UTF-8
| 238
| 1.671875
| 2
|
[] |
no_license
|
package backend.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import backend.entities.Car;
@Repository
public interface CarDao extends CrudRepository<Car, Long> {
}
| true
|
875d2a369fc4d1d6ae462f50066ce4d0d908707f
|
Java
|
tamerm655/ContriesAndCities_Assignment2_Lab1
|
/CountriesAndCities/src/countriesandcities/Cities.java
|
UTF-8
| 2,147
| 3.0625
| 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 countriesandcities;
/**
*
* @author Dubai
*/
public class Cities {
private String city;
private String country;
private String continent;
private String capital;
private int pop;
private boolean isCapital;
public Cities(){}
public Cities(String city, String country, String continent, String capital, int pop, boolean isCapital){
this.city = city;
this.country = country;
this.continent = continent;
this.capital = capital;
this.pop = pop;
this.isCapital = isCapital;
}
public void set_City(String city){
this.city = city;
}
public String get_City(){
return this.city;
}
public void set_Country(String country){
this.country = country;
}
public String get_Country(){
return this.country;
}
public void set_Continent(String continent){
this.continent = continent;
}
public String get_Continent(){
return this.continent;
}
public void set_Capital(String capital){
this.capital = capital;
}
public String get_Capital(){
return this.capital;
}
public void set_isCapital(boolean isCapital){
if(capital.equals("primary")){
this.isCapital = true;
}
}
public boolean get_isCapital(){
if(capital.equals("primary")){
this.isCapital = true;
}else{
this.isCapital = true;
}
return this.isCapital;
}
public void set_Population(int pop){
this.pop = pop;
}
public int get_Population(){
return this.pop;
}
@Override
public String toString() {
return "Cities{" + "city=" + this.city + ", pop=" + this.pop + '}';
}
}
| true
|
e896715f79d85d606b43c6a9506618e84a6b3b69
|
Java
|
Nikolai-Sedun/webDriverTestProject
|
/src/main/java/com/itacademy/tests/cloud/FileTest.java
|
UTF-8
| 1,492
| 2.359375
| 2
|
[] |
no_license
|
package com.itacademy.tests.cloud;
import com.itacademy.models.User;
import com.itacademy.service.cloud.LoginPageService;
import com.itacademy.service.cloud.MainPageService;
import com.itacademy.tests.BaseTest;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class FileTest extends BaseTest {
private static final String TEST_FILE_PATH = "./src/main/java/resources/TestFile.txt";
private static final String TEST_FILE_NAME = "TestFile.txt";
private LoginPageService loginPageService = new LoginPageService();
private MainPageService mainPageService = new MainPageService();
private User user = new User();
@BeforeClass
public void setUp() {
loginPageService.openCloudLoginPage();
loginPageService.loginToMainPage(user.getLogin(), user.getPassword());
}
@AfterClass
private void tearDown() {
mainPageService.doLogout();
}
@Test
public void uploadingFileTest() {
mainPageService.uploadFileToRoot(TEST_FILE_PATH);
Assert.assertTrue(mainPageService.isFirstElementNameEqualsGiven(TEST_FILE_NAME),
"file uploading failed");
}
@Test(dependsOnMethods = "uploadingFileTest")
public void dragAndDropFileTest() {
mainPageService.createNewFolder();
mainPageService.moveFileToFolderAndOpen();
Assert.assertTrue(mainPageService.isFirstElementNameEqualsGiven(TEST_FILE_NAME),
"file drag and drop failed");
}
}
| true
|
af7d4e9d444c5dab81e4d2ca938bcf7563f4c190
|
Java
|
Moorose/onlineshop
|
/src/main/java/net/thumbtack/onlineshop/controller/SessionController.java
|
UTF-8
| 2,179
| 2.046875
| 2
|
[] |
no_license
|
package net.thumbtack.onlineshop.controller;
import net.thumbtack.onlineshop.dto.EmptyResponse;
import net.thumbtack.onlineshop.dto.user.AdminRegistrationResponse;
import net.thumbtack.onlineshop.dto.user.ClientRegistrationResponse;
import net.thumbtack.onlineshop.dto.user.LoginRequest;
import net.thumbtack.onlineshop.dto.user.LoginResponse;
import net.thumbtack.onlineshop.exeption.OnlineShopException;
import net.thumbtack.onlineshop.service.interfaces.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import static net.thumbtack.onlineshop.OnlineShopServer.COOKIE_NAME;
@RestController
@RequestMapping("/api")
public class SessionController {
@Autowired
private RegistrationService registrationService;
@PostMapping("/sessions")
public ResponseEntity login(@Valid @RequestBody LoginRequest loginRequest, HttpServletResponse response) throws OnlineShopException {
LoginResponse loginResponse = registrationService.loginUser(loginRequest);
if (loginResponse.getAdminRegistrationResponse() != null) {
AdminRegistrationResponse adminRegistrationResponse = loginResponse.getAdminRegistrationResponse();
response.addCookie(new Cookie(COOKIE_NAME, loginResponse.getAdminRegistrationResponse().getJavaSessionId()));
return ResponseEntity.ok().body(adminRegistrationResponse);
} else {
ClientRegistrationResponse clientRegistrationResponse = loginResponse.getClientRegistrationResponse();
response.addCookie(new Cookie(COOKIE_NAME, loginResponse.getClientRegistrationResponse().getJavaSessionId()));
return ResponseEntity.ok().body(clientRegistrationResponse);
}
}
@DeleteMapping("/sessions")
public ResponseEntity logout(@CookieValue(COOKIE_NAME) String javaSessionId) {
registrationService.logoutUser(javaSessionId);
return ResponseEntity.ok().body(new EmptyResponse());
}
}
| true
|
5e3343a2fa7bedf75d9550d4854d720560dde739
|
Java
|
teiid/teiid
|
/connectors/couchbase/translator-couchbase/src/main/java/org/teiid/translator/couchbase/CouchbaseQueryExecution.java
|
UTF-8
| 4,605
| 1.710938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.translator.couchbase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.teiid.couchbase.CouchbaseConnection;
import org.teiid.language.QueryExpression;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.translator.DataNotAvailableException;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.ResultSetExecution;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.TypeFacility;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;
public class CouchbaseQueryExecution extends CouchbaseExecution implements ResultSetExecution {
private QueryExpression command;
private Class<?>[] expectedTypes;
private N1QLVisitor visitor;
private Iterator<N1qlQueryRow> results;
public CouchbaseQueryExecution(
CouchbaseExecutionFactory executionFactory,
QueryExpression command, ExecutionContext executionContext,
RuntimeMetadata metadata, CouchbaseConnection connection) {
super(executionFactory, executionContext, metadata, connection);
this.command = command;
this.expectedTypes = command.getColumnTypes();
}
@Override
public void execute() throws TranslatorException {
this.visitor = this.executionFactory.getN1QLVisitor();
this.visitor.append(this.command);
String n1ql = this.visitor.toString();
LogManager.logDetail(LogConstants.CTX_CONNECTOR, CouchbasePlugin.Util.gs(CouchbasePlugin.Event.TEIID29001, n1ql));
executionContext.logCommand(n1ql);
N1qlQueryResult queryResult = connection.execute(n1ql);
this.results = queryResult.iterator();
}
@Override
public List<?> next() throws TranslatorException, DataNotAvailableException {
if (this.results == null || !this.results.hasNext()) {
return null;
}
N1qlQueryRow queryRow = this.results.next();
if(queryRow == null) {
return null;
}
List<Object> row = new ArrayList<>(expectedTypes.length);
JsonObject json = queryRow.value();
for(int i = 0 ; i < expectedTypes.length ; i ++){
String columnName = this.visitor.getSelectColumns().get(i);
Object value = null;
Class<?> type = expectedTypes[i];
//retrieve as the specific value type since couchbase can mix
//TODO: this could be moved into retrieve value if used in more than 1 place
if (type == TypeFacility.RUNTIME_TYPES.STRING) {
value = json.getString(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.INTEGER) {
value = json.getInt(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.LONG) {
value = json.getLong(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.DOUBLE) {
value = json.getDouble(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.BOOLEAN) {
value = json.getBoolean(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.BIG_INTEGER) {
value = json.getNumber(columnName);
} else if (type == TypeFacility.RUNTIME_TYPES.BIG_DECIMAL) {
value = json.getNumber(columnName);
} else {
value = json.get(columnName);
}
row.add(this.executionFactory.retrieveValue(type, value));
}
return row;
}
@Override
public void close() {
this.results = null;
}
@Override
public void cancel() throws TranslatorException {
}
}
| true
|