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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fa202b3955d8e25ed1c0231031393a403d37c6d4 | Java | rbaljinder/ui-presenter | /presenter/presenter-core/src/main/java/org/baljinder/presenter/util/ReflectionUtils.java | UTF-8 | 1,451 | 2.734375 | 3 | [] | no_license | /**
*
*/
package org.baljinder.presenter.util;
import java.lang.reflect.Field;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
/**
* @author Baljinder Randhawa
*
*/
public class ReflectionUtils {
public static Class<?> getFieldTypeOfClass(Class<?> clazz, String fieldName) {
Class<?> typeToReturn = null;
try {
Field field = clazz.getDeclaredField(fieldName);
typeToReturn = field.getType();
} catch (Throwable th) {
throw new RuntimeException("Field [" + fieldName + "] does not exist in Class[" + clazz + "]");
}
return typeToReturn;
}
public static void setFieldValue(Object object, String fieldName, Object value) {
try {
PropertyUtils.setSimpleProperty(object, fieldName, value);
} catch (Throwable th) {
throw new RuntimeException("Could not set field[" + fieldName + "] on Object[" + object + "]");
}
}
public static Object getFieldValue(Object object, String fieldName) {
Object value = null;
try {
value = PropertyUtils.getSimpleProperty(object, fieldName);
} catch (Throwable th) {
throw new RuntimeException("Could not get field[" + fieldName + "] of Object[" + object + "]");
}
return value;
}
public static String getFieldAsString(Object object, String fieldName) {
Object value = getFieldValue(object, fieldName);
return value != null?value.toString(): StringUtils.EMPTY;
}
}
| true |
5f59b8601a5c8bb36d358d8a9e37e9bef8acef86 | Java | korantengNanaYaw/sokoPayOne | /app/src/main/java/com/worldsoko/sokopay/Activities/Register.java | UTF-8 | 2,179 | 2.015625 | 2 | [] | no_license | package com.worldsoko.sokopay.Activities;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.worldsoko.sokopay.Application.SokoApp;
import com.worldsoko.sokopay.R;
import com.worldsoko.sokopay.Utility.Typefacer;
import info.hoang8f.widget.FButton;
public class Register extends AppCompatActivity {
Button SignUpButton;
Typefacer typefacer;
TextView link_login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
typefacer=new Typefacer();
SetLabels();
fingerPrint();
}
private void fingerPrint(){
FingerprintManager fingerprintManager = (FingerprintManager) SokoApp.getAppContext().getSystemService( SokoApp.getAppContext().FINGERPRINT_SERVICE);
if(fingerprintManager.isHardwareDetected()){
Log.d("sokopay","yes finger detected");
}else{
Log.d("sokopay","No finger detected");
}
}
private void SetLabels(){
link_login=(TextView)findViewById(R.id.link_login);
link_login.setTypeface(typefacer.squareLight());
link_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Register.this,LoginPad.class);
startActivity(intent);
}
});
SignUpButton=(Button)findViewById(R.id.SignUpButton);
// SignUpButton.setButtonColor(R.color.colorPrimary);
SignUpButton.setTypeface(typefacer.squareLight());
SignUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Register.this,FirstActivity.class);
startActivity(intent);
}
});
}
}
| true |
3ac973b40db6c845d06463b7bef0d55243d91f33 | Java | son5941/java2104 | /FirstJava/src/com/example/third/Array.java | UTF-8 | 1,454 | 4.09375 | 4 | [] | no_license | package com.example.third;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
//배열 선언
//
//.자료형 [ ] 배열의 이름 = new 자료형[배열의 크기, 갯수 ]
//
//.자료형 배열이름[ ] = new 자료형 [배열 크기, 갯수 ]
//
//int [ ] arrey = new int [ 3 ] //arrey이름으로 arrey 1, arrey2, arrey 3로 만들어짐
//arrey[0] = 1; 배열의 첫번째를 1으로 주겠다.
//arrey[2] = 2; 배열의 3번째를 2로 주겠다.
//
//int arrey[ ] = new int[3]; //위에것과 같은것
//
//
////배열 선언과 동시에 초기화는 방법
//
//int [ ] arrey = new int [ ]{ 직접 데이터값을 넣을 수 있다;
//예를 들어 int [ ] arrey = new int [ ]{ 1,2,3,4,5} 는 [가로 안에 5개 변수를 넣을 수 있다.
Scanner read = new Scanner(System.in);
// 배열 선언 후 초기화
//
// int [] arr = new int[5];
// for(int i=0; i<5; i++ ) {
// System.out.println(i+1 + "번째 숫자를 입력하세요");
// arr[i] = read.nextInt();
// //System.out.println(arr[i]); //배열 선언과 동시에 1~5까지 집어 넣어 주는것.
// }
//배열 선언과 동시에 초기화
int[] arr = new int[] {1,2,3,4,5, 1,1 ,1};
for(int i = 0; i < arr.length ; i++) { //arr.length - 어레이의 랜스만큼.
System.out.printf("%d", arr[i]);
}
System.out.println();
}
}
| true |
4e871fb537e511e149cb2c901a75f1cacdfb898d | Java | ash311/PS1 | /src/pkgMain/Rectangle.java | UTF-8 | 307 | 3.15625 | 3 | [] | no_license | package pkgMain;
public class Rectangle {
public static void main (String[] args)
{
double Length = 4.6;
double Width = 8.7;
double area = Length*Width;
// TODO Implement Area() function with the correct formula
System.out.println("The area for the rectangle is "+area);
}
}
| true |
0a80812c1420ca2350fcc59fbb64246ec6ba7359 | Java | spreadshirt/dialogflow-client | /src/main/java/com/dialogflow/client/model/WebhookResponse.java | UTF-8 | 740 | 1.773438 | 2 | [
"MIT"
] | permissive | package com.dialogflow.client.model;
import com.dialogflow.client.EventInput;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class WebhookResponse {
@JsonProperty
String fulfillmentText;
@JsonProperty
HashMap<String, Object> payload = new HashMap<>();
@JsonProperty
List<Context> outputContexts = new ArrayList<>();
@JsonProperty
EventInput followupEventInput;
@JsonIgnore
final
GoogleResponse googleResponse;
public WebhookResponse() {
googleResponse = new GoogleResponse();
payload.put("google", googleResponse);
}
}
| true |
c0a7db09a801d2842e0927978722de8e8a2af760 | Java | cheriduk/spring-boot-ajax | /spring-boot-ajax/src/main/java/com/dk/ajax/demo/service/UserService.java | UTF-8 | 5,334 | 2.5 | 2 | [] | no_license | package com.dk.ajax.demo.service;
import com.dk.ajax.demo.dao.UserDao;
import com.dk.ajax.demo.dao.mapper.UserMapper;
import com.dk.ajax.demo.model.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Cheri
* @title: UserService
* @projectName spring-boot-ajax
* @description: TODO
* @date 2019/4/2018:28
*/
@Service
public class UserService {
@Autowired
UserDao userDao;
@Autowired
UserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;
public List<User> queryAllUser(){
return userDao.getAllUser();
}
public User queryUserById(String id){
return userDao.getUserById(id);
}
public User findUserById(int id){
// 从缓存中获取信息
String key = "user_" + id;
ValueOperations<String, User> operations = redisTemplate.opsForValue();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
User user = operations.get(key);
System.out.println("==========从缓存中获取了用户 >>"+user);
return user;
}else {
User user =userMapper.findUserById(id);
System.out.println("==========从数据表中获得数据>>>"+user);
// 插入缓存
if(user!=null){
operations.set(key, user, 30, TimeUnit.SECONDS);
}
return user;
}
}
/**
* 获取用户策略:先从缓存中获取用户,没有则取数据表中 数据,再将数据写入缓存
* @param id
* @return
*/
public User queryUserById(int id){
String key = "user_" + id;
ValueOperations<String, User> operations = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
long start = System.currentTimeMillis();
User user = operations.get(key);
System.out.println("==========从缓存中获得数据=========");
System.out.println(user.getName());
System.out.println("==============================");
long end = System.currentTimeMillis();
System.out.println("查询redis花费的时间是:" + (end - start)+"s");
return user;
}else{
long start = System.currentTimeMillis();
User user = userMapper.selectUserById(id);
System.out.println("==========从数据表中获得数据=========");
System.out.println(user.getName());
System.out.println("==============================");
// 写入缓存
operations.set(key, user, 5, TimeUnit.HOURS);
long end = System.currentTimeMillis();
System.out.println("查询mysql花费的时间是:" + (end - start)+"s");
return user;
}
}
public User login(String userName, String passWord) {
return userMapper.login(userName,passWord);
}
public int register(User user) {
return userMapper.register(user);
}
public PageInfo findAllUser(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.selectAllUser();
PageInfo<User> userList = new PageInfo<>(users);
return userList;
}
public List<User> findAllUserByName(String name){
List<User> userList = userMapper.selectAllUserByName(name);
return userList;
}
public int addUser(User user){
return userMapper.insertUser(user);
}
/**
* 更新用户策略:先更新数据表,成功之后,删除原来的缓存,再更新缓存
* @param user
* @return
*/
public int updateUser(User user) {
ValueOperations<String, User> operations = redisTemplate.opsForValue();
int result = userMapper.updateUser(user);
if (result != 0) {
String key = "user_" + user.getId();
boolean haskey = redisTemplate.hasKey(key);
if (haskey) {
redisTemplate.delete(key);
System.out.println("删除缓存中的key=========>" + key);
}
// 再将更新后的数据加入缓存
User userNew = userMapper.selectUserById(user.getId());
if (userNew != null) {
operations.set(key, userNew, 3, TimeUnit.HOURS);
}
}
return result;
}
/**
* 删除用户策略:删除数据表中数据,然后删除缓存
* @param id
* @return
*/
public int deleteUserById(int id) {
int result = userMapper.deleteUserById(id);
String key = "user_" + id;
if (result != 0) {
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
System.out.println("删除了缓存中的key:" + key);
}
}
return result;
}
}
| true |
b1478e196c31d1559eabbab9ffb9486755ed0a62 | Java | zasadna/QAJavaSpring2021 | /HW6-advanced-level/src/main/java/com/epam/test/automation/java/practice6/SalesPerson.java | UTF-8 | 1,005 | 3.015625 | 3 | [] | no_license | package com.epam.test.automation.java.practice6;
import java.math.BigDecimal;
public class SalesPerson extends Employee {
private int percentOfSalesTargetsPlan;
public SalesPerson(String lastName, BigDecimal salary, int percentOfSalesTargetsPlan) {
super(lastName, salary);
this.percentOfSalesTargetsPlan = percentOfSalesTargetsPlan;
}
public void setPercentOfSalesTargetsPlan(int percentOfSalesTargetsPlan) {
this.percentOfSalesTargetsPlan = percentOfSalesTargetsPlan;
}
@Override
public void setBonus(BigDecimal bonus) {
if (bonus != null &&
bonus.intValue() > 0) {
if (this.percentOfSalesTargetsPlan > 200) {
this.bonus = bonus.multiply(BigDecimal.valueOf(3));
} else if (this.percentOfSalesTargetsPlan > 100) {
this.bonus = bonus.multiply(BigDecimal.valueOf(2));
} else this.bonus = bonus;
} else throw new IllegalArgumentException();
}
}
| true |
d0034506738764b5463f1b8dfce09e8737faaea1 | Java | ZhongDaPan/zdpApplication | /Doctor/app/src/main/java/com/newdjk/doctor/views/DisplayUtil.java | UTF-8 | 1,364 | 2.375 | 2 | [] | no_license | package com.newdjk.doctor.views;
import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Field;
import static android.util.Log.w;
/**
* Created by EDZ on 2018/10/16.
*/
public class DisplayUtil {
public DisplayUtil() {
}
public static int px2dip(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5F);
}
public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5F);
}
public static int dp2px(Context context, int dp) {
return (int)TypedValue.applyDimension(1, (float)dp, context.getResources().getDisplayMetrics());
}
public static int px2sp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int)(pxValue / fontScale + 0.5F);
}
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int)(spValue * fontScale + 0.5F);
}
}
| true |
11d90872f3812c914bc11d1b5e2fd84c197d4a41 | Java | NCU-Anti-Java/Marjio | /Application/src/main/java/io/github/antijava/marjio/window/WindowMessage.java | UTF-8 | 1,725 | 2.5 | 2 | [] | no_license | package io.github.antijava.marjio.window;
import io.github.antijava.marjio.common.IApplication;
import io.github.antijava.marjio.common.IInput;
import io.github.antijava.marjio.common.graphics.IBitmap;
import io.github.antijava.marjio.common.input.Key;
import io.github.antijava.marjio.constant.GameConstant;
import io.github.antijava.marjio.scene.MainScene;
import org.jetbrains.annotations.NotNull;
import static io.github.antijava.marjio.common.graphics.Color.WHITE;
import static io.github.antijava.marjio.common.graphics.IBitmap.TextAlign.CENTER;
/**
* @author Davy
*/
public class WindowMessage extends WindowBase {
private final String mMessage;
public WindowMessage(@NotNull IApplication application, final String message, final int width) {
super(application, width, WINDOW_LINE_HEIGHT + 32);
mMessage = message;
setX((GameConstant.GAME_WIDTH - width) / 2);
setY((GameConstant.GAME_HEIGHT - getHeight()) / 2);
refresh();
}
private void refresh() {
final IBitmap content = getContent();
content.clear();
content.drawText(mMessage, 0, 0, content.getWidth(), WINDOW_LINE_HEIGHT, WHITE, CENTER);
dirty();
}
@Override
public void update() {
super.update();
final IInput input = getApplication().getInput();
if (!isActive())
return;
if (input.isPressed(Key.ENTER)) {
setActive(false);
super.update();
getApplication().getSceneManager().translationTo(new MainScene(getApplication()));
}
}
@Override
public void setActive(final boolean v) {
super.setActive(v);
setOpacity(v ? 0 : 255);
}
}
| true |
35708d18fe280d49896f81cc070ac129c8b70cd3 | Java | samuelvazcal/Java-RelearningSessions-Exercises | /Section16/src/com/samuelvazquez/mix/example2/Main2.java | UTF-8 | 4,028 | 3.828125 | 4 | [] | no_license | package src.com.samuelvazquez.mix.example2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main2 {
public static void main(String[] args) {
Employee jim = new Employee("Jim",28,500);
Employee pam = new Employee("Pam",26,350);
Employee michael = new Employee("Michael",33,800);
Employee dwight = new Employee("Dwight",30,450);
List<Employee> employees = new ArrayList<>();
employees.add(jim);
employees.add(pam);
employees.add(michael);
employees.add(dwight);
// sorting via anonymous class implementation
// Collections.sort(employees, new Comparator<Employee>() {
// @Override
// public int compare(Employee o1, Employee o2) {
// return o1.getName().compareTo(o2.getName());
// }
// });
Collections.sort(employees, Comparator.comparing(Employee::getName));
//Collections.sort(employees, Comparator.comparing(employee -> employee.getName()));
//Collections.sort(employees,(e1,e2) -> e1.getName().compareTo(e2.getName()));
//prints out: Dwight, Jim, Michael, Pam
//Collections.sort(employees,Comparator.comparing(Employee::getName));
// ComparatorName comparator = new ComparatorName();
// Collections.sort(employees);
printList(employees);
// String sillyString = doStringStuff(new UpperConcat() {
// @Override
// public String upperAndConcat(String s1, String s2) {
// return s1.toUpperCase() + s2.toUpperCase();
// }
// },employees.get(0).getName(),employees.get(1).getName());
// System.out.println(sillyString);
UpperConcat uc = (s1,s2) -> s1.toUpperCase() + s2.toUpperCase();
String sillyString = doStringStuff(uc, employees.get(0).getName(),employees.get(1).getName());
System.out.println(sillyString);
AnotherClass anotherClass = new AnotherClass();
String s = anotherClass.doSomething();
System.out.println(s);
}
public final static String doStringStuff(UpperConcat uc,String s1, String s2) {
return uc.upperAndConcat(s1, s2);
}
public static void printList(List<Employee> list) {
for(Employee x : list) {
System.out.println(x.getName());
}
}
}
class Employee implements Comparable<Employee>{
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
@Override
public int compareTo(Employee o) {
return Double.compare(this.getSalary(), o.getSalary());
}
}
interface UpperConcat {
public String upperAndConcat(String s1, String s2);
}
class AnotherClass {
// public String doSomething() {
// System.out.println("The AnotherClass's name is: " + getClass().getSimpleName());
// return Main2.doStringStuff(new UpperConcat() {
// @Override
// public String upperAndConcat(String s1, String s2) {
// System.out.println("The anonymous class's name is: " + getClass().getSimpleName());
// return s1.toUpperCase() + s2.toUpperCase();
// }
// },"String1","String2");
// }
public String doSomething() {
UpperConcat uc = (s1,s2) -> {
System.out.println("The lambda expression's class is: " + getClass().getSimpleName());
String result = s1.toUpperCase() + s2.toUpperCase();
return result;
};
System.out.println("The AnotherClass's name is: " + getClass().getSimpleName());
return Main2.doStringStuff(uc,"String1","String2");
}
}
| true |
972ccc35bb189ca75f844596f853e77a634833dd | Java | tassianebarros/EDA | /EDA - Lista de Prioridades/EDAAlunos/src/br/ufc/quixada/eda/hash/Elemento.java | UTF-8 | 494 | 2.78125 | 3 | [] | no_license | package br.ufc.quixada.eda.hash;
public class Elemento {
private int valor;
private int indiceProximo;
public Elemento(){
indiceProximo = -1;
}
public Elemento(int valor){
this.valor = valor;
indiceProximo = -1;
}
public int getValor() {
return valor;
}
public void setValor(int valor) {
this.valor = valor;
}
public int getIndiceProximo() {
return indiceProximo;
}
public void setIndiceProximo(int indiceProximo) {
this.indiceProximo = indiceProximo;
}
}
| true |
81ea0ec772add5a98251c7fba6604a5f0dea9850 | Java | Mrlang/code | /src/ThinkInJava/Topic_21_Thread/class_21_4_2_interrupt.java | UTF-8 | 816 | 3.234375 | 3 | [] | no_license | package ThinkInJava.Topic_21_Thread;
import org.junit.Test;
/**
* Created by Mr_liang on 2017/2/21 using IDEA.
*/
public class class_21_4_2_interrupt {
public static void main(String args[]) {
new Thread(){public void run(){new test().f1(10);}}.start();
}
@Test
public void test(){
int a=1;
if(a-- >0)
System.out.println("asdfas");
System.out.println(a);
}
}
class test {
public synchronized void f1(int count) {
if (count-- > 0) {
System.out.println("f1() calling f2() with count :" + count);
f2(count);
}
}
public synchronized void f2(int count) {
if (count-- > 0) {
System.out.println("f2() calling fi() with count :" + count);
f1(count);
}
}
}
| true |
ff9d26469d51ba0b5855b4047b2244de7336696a | Java | aamattos/GMF-Tooling-Visual-Editor | /org.msl.simple.gmfmap.model/src-gen/org/msl/simple/gmfmap/simplemappings/SimpleMapping.java | UTF-8 | 5,730 | 1.789063 | 2 | [] | no_license | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.msl.simple.gmfmap.simplemappings;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.gmf.gmfgraph.Canvas;
import org.eclipse.gmf.mappings.Mapping;
import org.eclipse.gmf.tooldef.Palette;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Simple Mapping</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getCanvas <em>Canvas</em>}</li>
* <li>{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getPalette <em>Palette</em>}</li>
* <li>{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getMapping <em>Mapping</em>}</li>
* <li>{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getDomainModel <em>Domain Model</em>}</li>
* <li>{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getDomainMetaElement <em>Domain Meta Element</em>}</li>
* </ul>
* </p>
*
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping()
* @model
* @generated
*/
public interface SimpleMapping extends SimpleParentNode {
/**
* Returns the value of the '<em><b>Canvas</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Canvas</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Canvas</em>' reference.
* @see #setCanvas(Canvas)
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping_Canvas()
* @model
* @generated
*/
Canvas getCanvas();
/**
* Sets the value of the '{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getCanvas <em>Canvas</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Canvas</em>' reference.
* @see #getCanvas()
* @generated
*/
void setCanvas(Canvas value);
/**
* Returns the value of the '<em><b>Palette</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Palette</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Palette</em>' reference.
* @see #setPalette(Palette)
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping_Palette()
* @model
* @generated
*/
Palette getPalette();
/**
* Sets the value of the '{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getPalette <em>Palette</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Palette</em>' reference.
* @see #getPalette()
* @generated
*/
void setPalette(Palette value);
/**
* Returns the value of the '<em><b>Mapping</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Mapping</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Mapping</em>' reference.
* @see #setMapping(Mapping)
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping_Mapping()
* @model
* @generated
*/
Mapping getMapping();
/**
* Sets the value of the '{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getMapping <em>Mapping</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Mapping</em>' reference.
* @see #getMapping()
* @generated
*/
void setMapping(Mapping value);
/**
* Returns the value of the '<em><b>Domain Model</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Domain Model</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Domain Model</em>' reference.
* @see #setDomainModel(EPackage)
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping_DomainModel()
* @model
* @generated
*/
EPackage getDomainModel();
/**
* Sets the value of the '{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getDomainModel <em>Domain Model</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Domain Model</em>' reference.
* @see #getDomainModel()
* @generated
*/
void setDomainModel(EPackage value);
/**
* Returns the value of the '<em><b>Domain Meta Element</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Domain Meta Element</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Domain Meta Element</em>' reference.
* @see #setDomainMetaElement(EClass)
* @see org.msl.simple.gmfmap.simplemappings.SimplemappingsPackage#getSimpleMapping_DomainMetaElement()
* @model
* @generated
*/
EClass getDomainMetaElement();
/**
* Sets the value of the '{@link org.msl.simple.gmfmap.simplemappings.SimpleMapping#getDomainMetaElement <em>Domain Meta Element</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Domain Meta Element</em>' reference.
* @see #getDomainMetaElement()
* @generated
*/
void setDomainMetaElement(EClass value);
} // SimpleMapping
| true |
8e02ec4c50ecb2f253ae29aef6e330367bbaf3d5 | Java | VassilisSoum/wad | /src/main/java/wad/App.java | UTF-8 | 3,003 | 2.328125 | 2 | [
"MIT"
] | permissive |
package wad;
import com.airhacks.wad.boundary.WADFlow;
import com.airhacks.wad.control.Configurator;
import com.airhacks.wad.control.WarNameProvider;
import com.airhacks.wad.control.WatchPathsProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import static com.airhacks.wad.control.PreBuildChecks.pomExists;
import static com.airhacks.wad.control.PreBuildChecks.validateDeploymentDirectories;
/**
*
* @author airhacks.com
*/
public class App {
static Path addTrailingSlash(String path) {
if (!path.endsWith(File.separator)) {
return Paths.get(path, File.separator);
}
return Paths.get(path);
}
static void printWelcomeMessage() throws IOException {
try (InputStream resourceAsStream = App.class.
getClassLoader().
getResourceAsStream("META-INF/maven/com.airhacks/wad/pom.properties")) {
Properties properties = new Properties();
properties.load(resourceAsStream);
String wad = properties.getProperty("artifactId");
String version = properties.getProperty("version");
System.out.println(wad + " " + version);
}
}
static List<Path> convert(String[] args) {
return Arrays.stream(args)
.filter(arg -> !arg.startsWith("watchPaths="))
.map(App::addTrailingSlash)
.collect(Collectors.toList());
}
static List<Path> addWarName(Set<Path> deploymentDirectories, String warName) {
return deploymentDirectories.
stream().
map(path -> path.resolve(warName)).
collect(Collectors.toList());
}
public static void main(String[] args) throws IOException {
printWelcomeMessage();
if (args.length < 1 && !Configurator.userConfigurationExists()) {
System.out.println("Invoke with java -jar wad.jar [DEPLOYMENT_DIR1,DEPLOYMENT_DIR1] or create ~/.wadrc");
System.exit(-1);
}
pomExists();
Path currentPath = Paths.get("").toAbsolutePath();
Path pomXml = currentPath.resolve("pom.xml");
String thinWARName = WarNameProvider.getCustomWarName(pomXml);
Path thinWARPath = Paths.get("target", thinWARName);
Set<Path> deploymentDirs = Configurator.getConfiguredFolders(convert(args));
validateDeploymentDirectories(deploymentDirs);
List<Path> deploymentTargets = addWarName(deploymentDirs, thinWARName);
List<Path> sourceCodeDirs = WatchPathsProvider.get(args);
System.out.printf("WAD is watching %s, deploying %s to %s \n", sourceCodeDirs, thinWARPath, deploymentTargets);
WADFlow wadFlow = new WADFlow(sourceCodeDirs, thinWARPath, deploymentTargets);
}
}
| true |
6dceb9c23fec54b8926ac32e6bcd34219056ded5 | Java | alejo85/miprimerproyecto13 | /Client/src/ClasesLogicas/Subronda.java | UTF-8 | 1,281 | 2.890625 | 3 | [] | no_license | package ClasesLogicas;
public class Subronda {
private Encuentro [] encuentros;
private int idSubronda;
private boolean estado;
public Subronda() {
super();
}
public Subronda(Encuentro[] encuentros, int idSubronda) {
super();
this.encuentros = encuentros;
this.idSubronda = idSubronda;
}
public Subronda(Encuentro[] encuentros) {
super();
this.encuentros = encuentros;
}
public void setEncuentros(Encuentro[] encuentros) {
this.encuentros = encuentros;
}
public Encuentro[] getEncuentros() {
return encuentros;
}
public void setIdSubronda(int idSubronda) {
this.idSubronda = idSubronda;
}
public int getIdSubronda() {
return idSubronda;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
public boolean getEstado() {
return estado;
}
public void remplazarEncuentro(Encuentro unEncuentro){
for(int i =0; i<this.encuentros.length;i++)
{
if(this.encuentros[i].getIdEncuentro()==unEncuentro.getIdEncuentro())
this.encuentros[i]=unEncuentro;
}
}
}
| true |
ce7c3af13bf4d625c6a62e97b7b392b293c808a5 | Java | Kelvin023/QSMarmitex | /src/java/model/Marmita.java | UTF-8 | 1,124 | 2.21875 | 2 | [] | no_license | package model;
import java.util.Date;
public class Marmita {
private int cd_nr_marmita;
private String ds_ingredientes;
private Float preco;
private String nomeMarmita;
private int st_cardapio;
public int getCd_nr_marmita() {
return cd_nr_marmita;
}
public void setCd_nr_marmita(int cd_nr_marmita) {
this.cd_nr_marmita = cd_nr_marmita;
}
public String getDs_ingredientes() {
return ds_ingredientes;
}
public void setDs_ingredientes(String ds_ingredientes) {
this.ds_ingredientes = ds_ingredientes;
}
public Float getPreco() {
return preco;
}
public void setPreco(Float preco) {
this.preco = preco;
}
public String getNomeMarmita() {
return nomeMarmita;
}
public void setNomeMarmita(String nomeMarmita) {
this.nomeMarmita = nomeMarmita;
}
public int getSt_cardapio() {
return st_cardapio;
}
public void setSt_cardapio(int st_cardapio) {
this.st_cardapio = st_cardapio;
}
} | true |
838c745635e1ca6e2e6a23a85f88368d7755b667 | Java | ezhov-da/quick-hints-desktop-app | /src/main/java/ru/ezhov/note/variable/domain/Variable.java | UTF-8 | 980 | 2.625 | 3 | [] | no_license | package ru.ezhov.note.variable.domain;
import ru.ezhov.note.domain.NoteId;
import java.util.Objects;
public class Variable {
private NoteId noteId;
private VariableName name;
private VariableValue value;
public Variable(NoteId noteId, VariableName name, VariableValue value) {
this.noteId = noteId;
this.name = name;
this.value = value;
}
public NoteId noteId() {
return noteId;
}
public VariableName name() {
return name;
}
public VariableValue value() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Variable variable = (Variable) o;
return Objects.equals(noteId, variable.noteId) &&
Objects.equals(name, variable.name);
}
@Override
public int hashCode() {
return Objects.hash(noteId, name);
}
}
| true |
93ac3045af595d9c0a18cc8ef0985808fd6b0599 | Java | sscheiner/COSC436Assignment4 | /src/project/TaxComputationClasses/ForNameTest.java | UTF-8 | 1,374 | 3.3125 | 3 | [] | no_license | package project.TaxComputationClasses;
import java.util.HashMap;
public class ForNameTest {
private static HashMap taxCompClasses = new HashMap<String, Class>();
public static void main(String[] args) {
Class tax_class;
try{
tax_class = Class.forName("TaxComputationClasses.MD_TaxComputation");
populateTaxCompHashTable();
tax_class = (Class) taxCompClasses.get("MD");
TaxComputation t = (TaxComputation) tax_class.newInstance();
System.out.println(t.getSalesTax());
}
catch(ClassNotFoundException e){
System.out.println("Class Not Found");
}
catch(InstantiationException e){
System.out.println("Class Instantiation Error");
}
catch(IllegalAccessException e){
System.out.println("Illegal Access Error");
}
}
private static void populateTaxCompHashTable(){
String pkg = "TaxComputationClasses.";
try{
taxCompClasses.put("MD", Class.forName(pkg + "MD_TaxComputation"));
taxCompClasses.put("CA", Class.forName(pkg + "CA_TaxComputation"));
// etc.
}
catch(ClassNotFoundException e){
System.out.println("Tax Computation Class Error");
}
}
}
| true |
a90a9bd53c87f98ff56f80399689b4d303f6727f | Java | reed07/MyPreferencePal | /jadx-MFP/src/main/java/com/inmobi/commons/core/configs/d.java | UTF-8 | 201 | 1.5625 | 2 | [] | no_license | package com.inmobi.commons.core.configs;
/* compiled from: ConfigError */
final class d {
int a;
String b;
public d(int i, String str) {
this.a = i;
this.b = str;
}
}
| true |
bb9b4c3b4b32dc9b07155acc2904455493119126 | Java | zqianyi/coffeeserve1 | /src/com/city/coffeeserve/admin/business/impl/FoodImpl.java | UTF-8 | 1,860 | 2.3125 | 2 | [] | no_license | package com.city.coffeeserve.admin.business.impl;
import java.util.ArrayList;
import java.util.List;
import com.city.coffeeserve.admin.business.IFood;
import com.city.coffeeserve.admin.dao.IFooddao;
import com.city.coffeeserve.admin.dao.impl.FoodDaoImpl;
import com.city.coffeeserve.admin.factory.DaoFactory;
import com.city.coffeeserve.note.value.FoodValue;
public class FoodImpl implements IFood{
public void addFood(int fid,String fname,String ftype,String fprice,String fshock)throws Exception{
FoodValue fv=new FoodValue();
fv.setFid(fid);
fv.setFname(fname);
fv.setFtype(ftype);
fv.setFprice(fprice);
fv.setFshock(fshock);
IFooddao fdo=DaoFactory.createFoodDao();
fdo.createFood(fv);
}
public void savephoto(String id,String filepath,String photofilename,String photocontenttype)throws Exception{
IFooddao fdo=DaoFactory.createFoodDao();
fdo.savephoto(id,filepath,photofilename,photocontenttype);
}
public List getFoodListValueBySearch()throws Exception{
List fList =new ArrayList();
FoodValue fv=new FoodValue();
IFooddao fdo=DaoFactory.createFoodDao();
fv=fdo. getFoodValueBySearch();
fList.add(fv);
return fList;
}
public List getFoodList(int i)throws Exception{
List fList =new ArrayList();
FoodValue fv=new FoodValue();
IFooddao fdo=DaoFactory.createFoodDao();
fv=fdo. getFoodValue(i);
fList.add(fv);
return fList;
}
public void deletefood(String id) throws Exception{
IFooddao fdo=DaoFactory.createFoodDao();
fdo.deletefood(id);
}
public void modify(int fid,String fname, String ftype, String fprice,String fshock) throws Exception{
FoodValue fv=new FoodValue();
fv.setFid(fid);
fv.setFname(fname);
fv.setFprice(fprice);
fv.setFshock(fshock);
fv.setFtype(ftype);
System.out.println(fv.getFname());
FoodDaoImpl fdi=new FoodDaoImpl();
fdi.update(fv);
}
}
| true |
422b1dff797a80402220b98327a60f64fa34df75 | Java | john77eipe/SpringSecurityDrills | /securestore-web-with-db-auth-4/src/main/java/com/securestore/config/AuthenticationSuccessHandlerImpl.java | UTF-8 | 1,618 | 2.328125 | 2 | [] | no_license | package com.securestore.config;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
/**
* @author John Eipe
*
*/
@Component("authenticationSuccessHandler")
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/adminPage");
break;
} else {
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/userPage");
break;
}
}
}
}
| true |
2329e40f2dda1bf077a41e9c7c233c8da79e7ea1 | Java | maxdos28/magmeweb | /src/main/java/cn/magme/web/action/widget/WidgetSearchAction.java | UTF-8 | 4,459 | 1.976563 | 2 | [] | no_license | /**
* Copyright ® 2010 Shanghai Magme Co. Ltd.
* All right reserved.
*/
package cn.magme.web.action.widget;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import cn.magme.constants.PojoConstant.SORT;
import cn.magme.pojo.Issue;
import cn.magme.pojo.Sort;
import cn.magme.service.IssueService;
import cn.magme.service.LuceneService;
import cn.magme.service.SortService;
import cn.magme.util.NumberUtil;
import cn.magme.util.PageInfo;
import cn.magme.util.SearchIssueSorter;
import cn.magme.util.StringUtil;
import cn.magme.web.action.BaseAction;
/**
* @author qiaowei
* @date 2011-7-14
* @version $id$
*/
@Results({ @Result(name = "searchSuccess", location = "/WEB-INF/pages/widget/widgetSearch.ftl") })
public class WidgetSearchAction extends BaseAction {
private final static String MAGZINE = "magzine";
private String pageTitle;
private String queryStr;
private List<Sort> sortList;
private Long sortId = -1l;
private String xx;
@Resource
private IssueService issueService;
@Resource
private LuceneService luceneService;
@Resource
private SortService sortService;
private PageInfo magPageInfo = new PageInfo();
private static final long serialVersionUID = 272332340363998948L;
private static final Logger log = Logger.getLogger(WidgetSearchAction.class);
private static final String SEARCH_SUCCESS = "searchSuccess";
public String execute() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("Cache-Control", "max-age=" + systemProp.getPageCacheTimeout());
try {
sortList = sortService.getListByGroup(SORT.GROUP_COMPUTER);
if (StringUtil.isBlank(queryStr)) {
log.error("搜索关键词为空");
return SEARCH_SUCCESS;
}
queryStr = queryStr.trim();
Long[] objIds = luceneService.seacher(queryStr, "Issue", null);
objIds = NumberUtil.longFilter(objIds);
List<Issue> magList = null;
if (objIds != null && objIds.length > 0) {
magList = new ArrayList<Issue>();
for (Long objId : objIds) {
Issue issue = this.issueService.queryById(objId);
if (issue != null) {
magList.add(issue);
}
}
magList = SearchIssueSorter.sort(magList, StringUtil.containsNumber(queryStr));
int totalSize = magList.size();
magPageInfo.setData(magList);
magPageInfo.setCurPage(1);
magPageInfo.setLimit(15);
magPageInfo.setTotal(totalSize);
int totalPage = 0;
if (totalSize % 15 == 0) {
totalPage = totalSize / 15;
} else if (totalSize % 15 > 0) {
totalPage = totalSize / 15 + 1;
}
magPageInfo.setTotalPage(totalPage);
}
pageTitle = MAGZINE;
} catch (Exception e) {
log.error("", e);
}
return SEARCH_SUCCESS;
}
public String getQueryStr() {
return queryStr;
}
public void setQueryStr(String queryStr) {
this.queryStr = queryStr;
}
public PageInfo getMagPageInfo() {
return magPageInfo;
}
public void setMagPageInfo(PageInfo magPageInfo) {
this.magPageInfo = magPageInfo;
}
public List<Sort> getSortList() {
return sortList;
}
public void setSortList(List<Sort> sortList) {
this.sortList = sortList;
}
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
public Long getSortId() {
return sortId;
}
public void setSortId(Long sortId) {
this.sortId = sortId;
}
/**
* @param xx the xx to set
*/
public void setXx(String xx) {
this.xx = xx;
}
/**
* @return the xx
*/
public String getXx() {
return xx;
}
}
| true |
a5d98745213b476d3bfcd91cc0f3010ce1b363ba | Java | AndreasVikke-School/CPH-Business-ExamPrep2 | /Backend/src/main/java/entities/Category.java | UTF-8 | 1,155 | 2.3125 | 2 | [] | no_license | package entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
/**
*
* @author Andreas Vikke
*/
@Entity
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "categories")
private List<Request> requests;
public Category() {
}
public Category(String name, List<Request> requests) {
this.name = name;
this.requests = requests;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Request> getRequests() {
return requests;
}
public void setRequests(List<Request> requests) {
this.requests = requests;
}
}
| true |
a271000f063df030322a405bee4ec0668f39e187 | Java | YueniLiu/bus | /plannist/Network.java | UTF-8 | 15,589 | 2.546875 | 3 | [] | no_license |
package plannist;
import java.util.Calendar;
import java.util.Random;
import java.util.Vector;
import java.math.*;
public class Network {
static Vector<Bus> buses1 = new Vector<Bus>();
static Vector<Bus> buses2 = new Vector<Bus>();
static String tripID1;
static String tripID2;
static int miniRestTime;
static Calendar startTime;
static Calendar endTime;
static double weight1;
static double weight2;
static double weight3;
static Session ses;
static double updateTimes = 0;
/**
* @param buses
* update trip information for each bus
* @return true: network update successfully
*/
public static String calendarToString(Calendar c) {
return "(" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE) + "|"
+ c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ")";
}
public static boolean update(Vector<Bus> buses, String tripId) {
updateTimes++;
for (int i = 0; i < buses.size(); i++) {
Bus b = buses.get(i);
// b.setTripStartTime(b.departureTime);
Calendar start = b.getTripStartTime();
Vector<Stop> trip = b.getTrip();
Vector<Stop> utrip = PredictionHandler.updateTrip(tripId, start, trip, ses, false);
Vector<Stop> ntrip = new Vector<Stop>();
for (int j = 0; j < utrip.size(); j++) {
ntrip.add(utrip.get(j).clone());
}
b.setTrip(ntrip);
}
// if(updateTimes==5){
// for (int i = 0; i < buses.size(); i++) {
// Bus b = buses.get(i);
// System.out.println("bus id: "+b.busId+" - "+" shift: "+b.shift+"
// "+b.getTrip().get(0));
// }
// }
Random rnd = new Random();
// update travel time using (k,k+1,P)
for (int i = 0; i + 1 < buses.size(); i++) {
Bus b1 = buses.get(i);
Bus b2 = buses.get(i + 1);
// if(updateTimes>5){
// System.out.println(calendarToString(b1.getTrip().get(0).departureTime));
// System.out.println(calendarToString(b2.getTrip().get(0).departureTime));
// }
Vector<Stop> trip1 = b1.getTrip();
Vector<Stop> trip2 = b2.getTrip();
for (int j = 0; j + 1 < trip1.size(); j++) {
// s_tripId_stopId
Stop s_1_1 = trip1.get(j);
// System.out.println(calendarToString(trip1.get(0).departureTime));
Stop s_2_1 = trip2.get(j);
// System.out.println(calendarToString(trip2.get(0).departureTime));
// System.out.println(s_1_1+" "+s_2_1);
// System.out.println(calendarToString(s_1_1.departureTime));
// System.out.println(calendarToString(s_2_1.departureTime));
Calendar pTime = getPtime(s_1_1.departureTime, s_2_1.departureTime);
// if(updateTimes>5){
// System.out.println(calendarToString(pTime));
// }
// System.out.println(s_2_1.departureTime.HOUR_OF_DAY+"-"+s_2_1.departureTime.MINUTE+"-"+s_2_1.departureTime.SECOND);
if (i == 0) {
Stop s_1_2 = trip1.get(j + 1);
Calendar departureTime_1_1 = (Calendar) s_1_1.getDepartureTime().clone();
int travelTime = (int) PredictionHandler.getStats_TTS_k2K_(tripId, s_1_1.getStopId(),
s_1_2.getStopId(), pTime, ses);
// System.out.println(tripId+" "+s_1_1.getStopId()+"
// "+s_1_2.getStopId()+" "+calendarToString(pTime));
// System.out.println(travelTime);
if (travelTime == 0) {
// travelTime=120;
travelTime = rnd.nextInt(120) % (120 - 60 + 1) + 60;
}
departureTime_1_1.add(Calendar.SECOND, travelTime);
// System.out.println("=========="+(int)
// PredictionHandler.getStats_TTS_k2K_(tripId,
// s_1_1.getStopId(), s_1_2.getStopId(),
// pTime, ses));
s_1_2.setDepartureTime(departureTime_1_1);
Stop s_2_2 = trip2.get(j + 1);
Calendar departureTime_2_1 = (Calendar) s_2_1.getDepartureTime().clone();
int travelTime2 = (int) PredictionHandler.getStats_TTS_k2K_(tripId, s_2_1.getStopId(),
s_2_2.getStopId(), pTime, ses);
// System.out.println(calendarToString(pTime));
// System.out.println(s_2_1.getStopId()+" "+
// s_2_2.getStopId()+" "+travelTime2);
if (travelTime2 == 0) {
// travelTime2=120;
travelTime2 = rnd.nextInt(120) % (120 - 60 + 1) + 60;
}
departureTime_2_1.add(Calendar.SECOND, travelTime2);
s_2_2.setDepartureTime(departureTime_2_1);
} else {
// if(updateTimes>5){
// System.out.println("here!");
// }
Stop s_2_2 = trip2.get(j + 1);
Calendar departureTime_2_1 = (Calendar) s_2_1.getDepartureTime().clone();
int travelTime3 = (int) PredictionHandler.getStats_TTS_k2K_(tripId, s_2_1.getStopId(),
s_2_2.getStopId(), pTime, ses);
// System.out.println(s_2_1.getStopId()+" "+
// s_2_2.getStopId()+" "+travelTime3+"
// "+pTime.HOUR_OF_DAY+"-"+pTime.MINUTE+"-"+pTime.SECOND);
if (travelTime3 == 0) {
// travelTime3=120;
travelTime3 = rnd.nextInt(120) % (120 - 60 + 1) + 60;
}
departureTime_2_1.add(Calendar.SECOND, travelTime3);
s_2_2.setDepartureTime(departureTime_2_1);
}
}
}
// long t1 = Calendar.getInstance().getTime().getTime();
// System.out.println("Time for updateTrip:" + (t1-t0) + "sec");
// check minRestTime constraint
// if (satisfyMinRestTime(buses) == false) {
// return false;
// }
// update headways
for (int i = 0; i + 1 < buses.size(); i++) {
Bus b = buses.get(i);
Vector<Stop> trip = b.getTrip();
Bus b1 = buses.get(i + 1);
Vector<Stop> trip1 = b1.getTrip();
if (i == 0) {
for (int j = 0; j < trip1.size(); j++) {
int headway = (int) ((trip1.get(j).getDepartureTime().getTimeInMillis()
- trip.get(j).getDepartureTime().getTimeInMillis()) / 1000);// s
trip1.get(j).setHeadWay(headway);
trip.get(j).setHeadWay(headway);
}
} else {
for (int j = 0; j < trip1.size(); j++) {
int headway = (int) ((trip1.get(j).getDepartureTime().getTimeInMillis()
- trip.get(j).getDepartureTime().getTimeInMillis()) / 1000);// s
trip1.get(j).setHeadWay(headway);
}
}
}
// long t2 = Calendar.getInstance().getTime().getTime();
// System.out.println("Time for update headways:" + (t2-t1) + "sec");
// update loads
for (int i = 0; i < buses.size(); i++) {
Bus b = buses.get(i);
Vector<Stop> trip = b.getTrip();
for (int j = 0; j + 1 < trip.size(); j++) {
Stop s1 = trip.get(j);// k-1
Stop s2 = trip.get(j + 1);// to be updated k
int load = (int) (s2.getHeadWay() * s2.getArrivalRate() + s1.getLoad()
- s2.getHeadWay() * s2.getAlightingRate());
// if(updateTimes>5){
// System.out.println(load);
// }
if (load < 0) {
load = 0;
}
s2.setLoad(load);
}
}
// long t3 = Calendar.getInstance().getTime().getTime();
// System.out.println("Time for update loads:" + (t3-t2) + "sec");
// System.out.println("Time for update all:" + (t3-t0) + "sec");
// Bus bus=null;
// for(int i=0;i<buses.size();i++){
// System.out.println(buses.get(i));
// bus=buses.get(i);
// Vector<Stop> stops=new Vector<Stop>();
// for(int j=0;j<stops.size();j++){
// System.out.println(stops.get(j));
//
// }
// }
return true;
}
// return: true-satisfy false-not..
private static boolean satisfyMinRestTime(Vector<Bus> buses) {
int firstShiftIndex = 1;//
boolean satisfyMiniRestTime = true;
// abuses list: basic buses without duplicating by shifts
Vector<Bus> abuses = new Vector<Bus>();
for (int i = 0; i < buses.size(); i++) {
Bus b = buses.get(i);
// System.out.println(b.busId+" "+b.shift);
if (b.getShift() == firstShiftIndex) {
abuses.add(b);
}
}
// for (int i = 0; i < abuses.size(); i++) {
// Bus b=abuses.get(i);
// System.out.println(b.busId+" "+b.shift);
// }
// sbuses list: classify buses by shifts
Vector<Vector<Bus>> sbuses = new Vector<Vector<Bus>>();
for (int i = 0; i < abuses.size(); i++) {
Vector<Bus> tbuses = new Vector<Bus>();
Bus b = abuses.get(i);
String busId = b.getBusId();
tbuses.add(b);
for (int j = 0; j < buses.size(); j++) {
Bus b1 = buses.get(j);
String busId1 = b1.getBusId();
int shift = b1.getShift();
if (busId.equals(busId1) && shift > firstShiftIndex) {
tbuses.add(b1);
}
}
if (tbuses.size() > 1) {// a bus work for only 1 shift do not have
// to consider miniRestTime
sbuses.add(tbuses);
}
}
// for(int i=0;i<sbuses.size();i++){
// Vector<Bus> thebuses=sbuses.get(i);
// for(int j=0;j<thebuses.size();j++){
// Bus b=thebuses.get(j);
// System.out.print("|"+b.busId+" "+b.shift);
// }
// System.out.println();
// }
// verify miniRestTime Constraint
for (int i = 0; i < sbuses.size(); i++) {
Vector<Bus> asbuses = sbuses.get(i);
for (int j = 0; j + 1 < asbuses.size(); j++) {
Bus b1 = asbuses.get(j);
Bus b2 = asbuses.get(j + 1);
// System.out.println(b1.busId+" shift "+b1.shift+" "+b2.busId+"
// shift "+b2.shift);
// System.out.println(b1.getTrip().get(0)+"
// "+b2.getTrip().get(0));
// System.out.println(b1.getTrip().get(35)+"
// "+b2.getTrip().get(35));
Calendar formerEnd = b1.getTripEndTime();
Calendar latterStart = b2.getTripStartTime();
int plannedRestTime = (int) ((latterStart.getTimeInMillis() - formerEnd.getTimeInMillis()) / 1000);
// System.out.println(plannedRestTime);
if (plannedRestTime < miniRestTime) {
satisfyMiniRestTime = false;// check!
break;
}
}
}
return satisfyMiniRestTime;
}
/**
* @param buses1
* @param buses2
* @return both vectors have to be updated
*/
public double getObjectiveValue(Vector<Bus> buses1, Vector<Bus> buses2) {
return 0;
}
/**
* @param buses
* @return only one vector has to be updated
*/
public static double getObjectiveValue1(Vector<Bus> buses) {// Tianxiang
double O1 = 0.0;
for (int i = 0; i < buses.size(); i++) {
// for(Vector<Bus>::iterator it= buses.begin(); it != buses.end();
// it++ )
Bus b = buses.get(i);
int d = b.getDirection();
if (d == 1) {
Vector<Stop> stop = b.getTrip();
for (int k = 0; k < stop.size(); k++) {
Stop st = stop.get(k);
double ar = st.getArrivalRate();
// System.out.println(ar);
int g = st.getHeadWay();
if (b.getTripStartTime().before(endTime)) {// check!//////////
st.setObjective1(ar * g * g / 2);
O1 = O1 + ar * g * g / 2;
} else {
st.setObjective1(ar * g * g / 2);
}
}
}
if (d == 2) {
Vector<Stop> stop = b.getTrip();
for (int s = 0; s < stop.size(); s++) {
Stop st = stop.get(s);
double ar = st.getArrivalRate();
int g = st.getHeadWay();
if (b.getTripStartTime().before(endTime)) {
st.setObjective1(ar * g * g / 2);
O1 = O1 + ar * g * g / 2;
} else {
st.setObjective1(ar * g * g / 2);
}
}
}
}
return O1;
}
public static double getObjectiveValue2(Vector<Bus> buses) {
double O2 = 0.0;
for (int i = 0; i < buses.size(); i++) {
Bus b = buses.get(i);
int d = b.getDirection();
if (d == 1) {
Vector<Stop> stop = b.getTrip();
for (int k = 0; k + 1 < stop.size(); k++) {
Stop st = stop.get(k);
Stop stAfter = stop.get(k + 1);
Calendar t = st.getDepartureTime();
Calendar tAfter = stAfter.getDepartureTime();
double TripTime = (tAfter.getTimeInMillis() - t.getTimeInMillis()) / 1000;
double ar = st.getArrivalRate();
double al = st.getAlightingRate();
int c = b.getCapacity();
int l = st.getLoad();
int g = st.getHeadWay();
double TempCompare = ar * g + (1 - al) * l - c;
// System.out.println(TempCompare);
if (TempCompare >= 0 && b.getTripStartTime().before(endTime)) {
// if (TempCompare >= 0) {
st.setObjective2(TripTime * TempCompare);
O2 = O2 + TripTime * TempCompare;
} else {
st.setObjective2(TripTime * TempCompare);
}
}
}
if (d == 2) {
Vector<Stop> stop = b.getTrip();
for (int s = 0; s + 1 < stop.size(); s++) {
Stop st = stop.get(s);
Stop stAfter = stop.get(s + 1);
Calendar t = st.getDepartureTime();
Calendar tAfter = stAfter.getDepartureTime();
double TripTime = (tAfter.getTimeInMillis() - t.getTimeInMillis()) / 1000;
double ar = st.getArrivalRate();
double al = st.getAlightingRate();
int c = b.getCapacity();
int l = st.getLoad();
int g = st.getHeadWay();
double TempCompare = ar * g + (1 - al) * l - c;
if (TempCompare >= 0 && b.getTripStartTime().before(endTime)) {
st.setObjective2(TripTime * TempCompare);
O2 = O2 + TripTime * TempCompare;
} else {
st.setObjective2(TripTime * TempCompare);
}
}
}
}
return O2;
}
public static double getObjectiveValue3(Vector<Bus> buses) {
double O3 = 0.0;
for (int i = 0; i < buses.size(); i++) {
Bus b = buses.get(i);
int d = b.getDirection();
if (d == 1) {
Vector<Stop> stop = b.getTrip();
for (int k = 0; k < stop.size(); k++) {
double fee = b.getCost();////////////////////cost is the fee of single stop?
if (b.getTripStartTime().before(endTime)) {
O3 = O3 + fee;
}
}
}
if (d == 2) {
Vector<Stop> stop = b.getTrip();
for (int s = 0; s < stop.size(); s++) {
double fee = b.getCost();
if (b.getTripStartTime().before(endTime)) {
O3 = O3 + fee;
}
}
}
}
return O3;
}
public static Solution getObjectiveValue(int[] gaps, Vector<Bus> buses, String tripId) {
Vector<Bus> updatedbuses = gapsToBuses(gaps, buses);
boolean feasible = update(updatedbuses, tripId);
double TotalObj = 0.0;
double w1 = weight1;
double w2 = weight2;
double w3 = weight3;
// check satisfyMinRestTime +penalty
double o1 = getObjectiveValue1(buses);////////////////////why buses, not updatedbuses?
double o2 = getObjectiveValue2(buses);
double o3 = getObjectiveValue3(buses);
TotalObj = w1 * o1 + w2 * o2 + w3 * o3;
// add penalty if some constraints are not satisfied.
if (!feasible) {
TotalObj += 1000000;
}
Solution s = new Solution(o1, o2, o3, TotalObj, updatedbuses);
// System.out.println("TotalObj:"+TotalObj);
return s;
}
public static double getObjectiveValue(int[] gaps) {
return 0;
}
/**
* @param gaps
* gaps maintained by GA.
* @param buses
* bus list to be updated
* @return updated buses list
*/
public static Vector<Bus> gapsToBuses(int[] gaps, Vector<Bus> buses) {
// create a new gaps2, first element is set to 0
int[] gaps2 = new int[gaps.length + 1];
gaps2[0] = 0;
for (int i = 0; i < gaps.length; i++) {
gaps2[i + 1] = gaps[i];
}
// update buses according to gaps
int gapSum = 0;
// for (int i = 0; i < buses.size(); i++) {
for (int i = 0; i < gaps2.length; i++) {
gapSum += gaps2[i];
Bus b = buses.get(i);
Calendar c = (Calendar) startTime.clone();
c.add(Calendar.MINUTE, gapSum);
b.setTripStartTime(c);
}
return buses;
}
public static Calendar getPtime(Calendar c1, Calendar c2) {
Calendar c = (Calendar) c1.clone();
int gap = (int) ((c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000);
c.add(Calendar.SECOND, gap / 2);
return c;
}
}
| true |
55a13dae87bdd8b2fe3a83ea054ffc0303ef3e40 | Java | AndersonS001/iPet | /src/test/java/com/mycompany/myapp/domain/RemediosTest.java | UTF-8 | 697 | 2.21875 | 2 | [] | no_license | package com.mycompany.myapp.domain;
import static org.assertj.core.api.Assertions.assertThat;
import com.mycompany.myapp.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class RemediosTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Remedios.class);
Remedios remedios1 = new Remedios();
remedios1.setId(1L);
Remedios remedios2 = new Remedios();
remedios2.setId(remedios1.getId());
assertThat(remedios1).isEqualTo(remedios2);
remedios2.setId(2L);
assertThat(remedios1).isNotEqualTo(remedios2);
remedios1.setId(null);
assertThat(remedios1).isNotEqualTo(remedios2);
}
}
| true |
105fabd5cdfa2a6abc847cd5f049f55176b37e35 | Java | huoxiaoyao/P2pRocks | /SimpleP2P/app/src/main/java/ch/ethz/inf/vs/a4/simplep2p/MainActivity.java | UTF-8 | 1,211 | 2.3125 | 2 | [] | no_license | package ch.ethz.inf.vs.a4.simplep2p;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton alarmButton;
private P2PMaster master;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmButton = (ToggleButton) findViewById(R.id.alarmButton);
master = P2PMaster.createP2PMaster( this );
master.acceptAlarms();
alarmButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
master.invokeAlarm();
} else {
master.revokeAlarm();
}
}
});
}
public void test(View view) {
Intent i = new Intent(this, ArrowActivity.class);
startActivity(i);
}
}
| true |
d5473aeae6750125ffc1a5718686d4ea1b7b270a | Java | leeho203/PagingPractice | /src/main/java/com/myproject/vo/SearchPageVO.java | UTF-8 | 405 | 2.0625 | 2 | [] | no_license | package com.myproject.vo;
public class SearchPageVO extends PageVO {
String searchType;
String keyword;
/* getter */
public String getSearchType() {
return searchType;
}
public String getKeyword() {
return keyword;
}
/* setter */
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
| true |
7b51570d230e28c0ff9579f1cbef6e9be26b5c34 | Java | annicoletti/avm-sdk | /src/main/java/br/com/cpqd/avm/sdk/v1/model/to/ResponseAvmErrorTO.java | UTF-8 | 601 | 1.71875 | 2 | [] | no_license | package br.com.cpqd.avm.sdk.v1.model.to;
@Deprecated
public class ResponseAvmErrorTO extends ResponseAvmTO {
private static final long serialVersionUID = -4588269257222094048L;
private String code;
private String message;
public ResponseAvmErrorTO(String requestId) {
super.requestId = requestId;
super.status = false;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| true |
4398cc827dcb101e9eb862b8177bcefb99d1e216 | Java | 18338739892/parserHtml | /src/main/java/com/pkk/test/menutest/EnumTest3_1.java | UTF-8 | 519 | 3.203125 | 3 | [] | no_license | package com.pkk.test.menutest;
/**
* Created by peikunkun on 2017/11/4 0004.
*/
public enum EnumTest3_1 {
MALE("男"), FEMAIL("女");
private final String name;
private EnumTest3_1(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class EnumTest3_2 {
public static void main(String[] args) {
EnumTest3_1 e3 = EnumTest3_1.valueOf(EnumTest3_1.class, "MALE");
System.out.println(e3 + "代表的是:" + e3.getName());
}
} | true |
43547389ef96243a9d0dd8dfdbd02eca67f61134 | Java | jijianfeng/gtsafe | /gtsafe/src/main/java/com/zlzkj/app/service/LogImageService.java | UTF-8 | 370 | 1.71875 | 2 | [] | no_license | package com.zlzkj.app.service;
import java.util.Map;
import com.zlzkj.app.model.Docs;
import com.zlzkj.app.model.LogImage;
public interface LogImageService {
public int add(LogImage LogImage);
public int update(LogImage logImage);
public void del(int id);
public Map<String, Object> getLogImageList(Map<String, Object> where,Map<String, String> pageParams);
}
| true |
b256af0a00687bfae67d87237beb26a9f10166bc | Java | putyatinskii/lab-2 | /Offer_Service/src/main/java/org/offer_service/OfferServiceApplication.java | UTF-8 | 1,418 | 2.296875 | 2 | [] | no_license | package org.offer_service;
import org.offer_service.entities.Category;
import org.offer_service.entities.Characteristic;
import org.offer_service.entities.Offer;
import org.offer_service.repositories.CategoryRepository;
import org.offer_service.repositories.CharacteristicRepository;
import org.offer_service.repositories.OfferRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class OfferServiceApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(OfferServiceApplication.class);
OfferRepository offerRepository = context.getBean(OfferRepository.class);
CharacteristicRepository characteristicRepository = context.getBean(CharacteristicRepository.class);
CategoryRepository categoryRepository = context.getBean(CategoryRepository.class);
Characteristic characteristic = new Characteristic("name", "description");
Category category = new Category("NewCategory");
Offer offer = new Offer("NewOffer", 10, 1);
characteristicRepository.save(characteristic);
categoryRepository.save(category);
offer.setCategory(category);
offerRepository.save(offer);
context.close();
}
}
| true |
9a453ea724459a9a55ca64717c2a230295f04012 | Java | a-craciun/Test | /src/com/company/RemoveIntFromArray.java | UTF-8 | 718 | 3.75 | 4 | [] | no_license | package com.company;
import java.util.Arrays;
public class RemoveIntFromArray {
//Write a program to remove all occurrences of a specified value in a given array of integers and return the new array. There can be duplicates in the array.
public static int[] removeElements(int[] arr, int key)
{
int index = 0;
for (int i=0; i < arr.length; i++)
if (arr[i] != key)
arr[index++] = arr[i];
return Arrays.copyOf(arr, index);
}
public static void main(String[] args)
{
int[] array = { 1, 4, 6, 2, 4, 4, 4 };
int key = 4;
array = removeElements(array, key);
System.out.println(Arrays.toString(array));
}
}
| true |
4289c8f2fe46f4a890d8680bde60c57f7eb92a31 | Java | opelayoa/ticket_doctor_express_old | /app/src/main/java/com/tiendas3b/ticketdoctor/services/SyncCatalogsServices.java | UTF-8 | 24,372 | 1.601563 | 2 | [] | no_license | package com.tiendas3b.ticketdoctor.services;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.tiendas3b.ticketdoctor.GlobalState;
import com.tiendas3b.ticketdoctor.R;
import com.tiendas3b.ticketdoctor.db.dao.Access;
import com.tiendas3b.ticketdoctor.db.dao.Branch;
import com.tiendas3b.ticketdoctor.db.dao.BranchType;
import com.tiendas3b.ticketdoctor.db.dao.Category;
import com.tiendas3b.ticketdoctor.db.dao.Diagnostic;
import com.tiendas3b.ticketdoctor.db.dao.ImpCause;
import com.tiendas3b.ticketdoctor.db.dao.PossibleOrigin;
import com.tiendas3b.ticketdoctor.db.dao.Profile;
import com.tiendas3b.ticketdoctor.db.dao.ProjectStatus;
import com.tiendas3b.ticketdoctor.db.dao.Provider;
import com.tiendas3b.ticketdoctor.db.dao.StandardSolution;
import com.tiendas3b.ticketdoctor.db.dao.Symptom;
import com.tiendas3b.ticketdoctor.db.dao.SymptomDiagnostic;
import com.tiendas3b.ticketdoctor.db.dao.TicketStatus;
import com.tiendas3b.ticketdoctor.db.dao.Type;
import com.tiendas3b.ticketdoctor.db.dao.TypeSymptom;
import com.tiendas3b.ticketdoctor.db.dao.User;
import com.tiendas3b.ticketdoctor.db.manager.DatabaseManager;
import com.tiendas3b.ticketdoctor.db.manager.IAccessManager;
import com.tiendas3b.ticketdoctor.db.manager.IBranchManager;
import com.tiendas3b.ticketdoctor.db.manager.IBranchTypeManager;
import com.tiendas3b.ticketdoctor.db.manager.ICategoryManager;
import com.tiendas3b.ticketdoctor.db.manager.IDiagnosticManager;
import com.tiendas3b.ticketdoctor.db.manager.IImpCauseManager;
import com.tiendas3b.ticketdoctor.db.manager.IPossibleOriginManager;
import com.tiendas3b.ticketdoctor.db.manager.IProfileManager;
import com.tiendas3b.ticketdoctor.db.manager.IProjectStatusManager;
import com.tiendas3b.ticketdoctor.db.manager.IProviderManager;
import com.tiendas3b.ticketdoctor.db.manager.IStandardSolutionManager;
import com.tiendas3b.ticketdoctor.db.manager.ISymptomDiagnosticManager;
import com.tiendas3b.ticketdoctor.db.manager.ISymptomManager;
import com.tiendas3b.ticketdoctor.db.manager.ITicketStatusManager;
import com.tiendas3b.ticketdoctor.db.manager.ITypeSymptomManager;
import com.tiendas3b.ticketdoctor.db.manager.IUserManager;
import com.tiendas3b.ticketdoctor.http.TicketDoctorService;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class SyncCatalogsServices extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.tiendas3b.ticketdoctor.services.action.FOO";
private static final String ACTION_BAZ = "com.tiendas3b.ticketdoctor.services.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.tiendas3b.ticketdoctor.services.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.tiendas3b.ticketdoctor.services.extra.PARAM2";
private static final String TAG = "SyncCatalogsServices";
private TicketDoctorService ticketDoctorService;
public SyncCatalogsServices() {
super("SyncCatalogsServices");
}
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, SyncCatalogsServices.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, SyncCatalogsServices.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
// final String action = intent.getAction();
// if (ACTION_FOO.equals(action)) {
// final String param1 = intent.getStringExtra(EXTRA_PARAM1);
// final String param2 = intent.getStringExtra(EXTRA_PARAM2);
// handleActionFoo(param1, param2);
// } else if (ACTION_BAZ.equals(action)) {
// final String param1 = intent.getStringExtra(EXTRA_PARAM1);
// final String param2 = intent.getStringExtra(EXTRA_PARAM2);
// handleActionBaz(param1, param2);
// }
GlobalState context = (GlobalState) getApplicationContext();
ticketDoctorService = context.getHttpServiceWithAuth();
downloadStatusCat(context);
downloadUsersCat(context);
downloadCategoryCat(context);
downloadTypesCat(context);
downloadProjectStatusCat(context);
downloadSymptomCat(context);
downloadDiagnosticCat(context);
downloadTypeSymptomCat(context);
downloadSymptomDiagnosticCat(context);
downloadImpCauseCat(context);
downloadBranchTypeCat(context);
downloadBranchCat(context);
downloadStandardSolutionCat(context);
downloadPossibleOriginCat(context);
downloadProviderCat(context);
downloadProfileCat(context);
downloadAccessCat(context);
}
}
private void downloadAccessCat(final GlobalState context) {
Call<List<Access>> call = ticketDoctorService.getAccessCatalog();
call.enqueue(new Callback<List<Access>>() {
@Override
public void onResponse(Call<List<Access>> call, Response<List<Access>> response) {
if (response.isSuccessful()) {
saveAccess(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Access>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_provider));
}
});
}
private void saveAccess(List<Access> accesses, GlobalState context) {
IAccessManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxAccesses(accesses.toArray(new Access[accesses.size()]));
databaseManager.closeDbConnections();
}
private void downloadProfileCat(final GlobalState context) {
Call<List<Profile>> call = ticketDoctorService.getProfileCatalog();
call.enqueue(new Callback<List<Profile>>() {
@Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
if (response.isSuccessful()) {
saveProfile(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_provider));
}
});
}
private void saveProfile(List<Profile> profiles, GlobalState context) {
IProfileManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxProfiles(profiles.toArray(new Profile[profiles.size()]));
databaseManager.closeDbConnections();
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
private void downloadProviderCat(final GlobalState context) {
Call<List<Provider>> call = ticketDoctorService.getProviderCatalog();
call.enqueue(new Callback<List<Provider>>() {
@Override
public void onResponse(Call<List<Provider>> call, Response<List<Provider>> response) {
if (response.isSuccessful()) {
saveProvider(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Provider>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_provider));
}
});
}
private void saveProvider(List<Provider> providers, GlobalState context) {
IProviderManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxProvider(providers.toArray(new Provider[providers.size()]));
databaseManager.closeDbConnections();
}
private void downloadPossibleOriginCat(final GlobalState context) {
Call<List<PossibleOrigin>> call = ticketDoctorService.getPossibleOriginCatalog();
call.enqueue(new Callback<List<PossibleOrigin>>() {
@Override
public void onResponse(Call<List<PossibleOrigin>> call, Response<List<PossibleOrigin>> response) {
if (response.isSuccessful()) {
savePossibleOrigin(response.body(), context);
}
}
@Override
public void onFailure(Call<List<PossibleOrigin>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_possible_origin));
}
});
}
private void savePossibleOrigin(List<PossibleOrigin> possibleOrigins, GlobalState context) {
IPossibleOriginManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxPossibleOrigin(possibleOrigins.toArray(new PossibleOrigin[possibleOrigins.size()]));
databaseManager.closeDbConnections();
}
private void downloadStandardSolutionCat(final GlobalState context) {
Call<List<StandardSolution>> call = ticketDoctorService.getStandardSolutionCatalog();
call.enqueue(new Callback<List<StandardSolution>>() {
@Override
public void onResponse(Call<List<StandardSolution>> call, Response<List<StandardSolution>> response) {
if (response.isSuccessful()) {
saveStandardSolution(response.body(), context);
}
}
@Override
public void onFailure(Call<List<StandardSolution>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_standard_solution));
}
});
}
private void saveStandardSolution(List<StandardSolution> standardSolutions, GlobalState context) {
IStandardSolutionManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxStandardSolution(standardSolutions.toArray(new StandardSolution[standardSolutions.size()]));
databaseManager.closeDbConnections();
}
private void downloadBranchCat(final GlobalState context) {
Call<List<Branch>> call = ticketDoctorService.getBranchCatalog();
call.enqueue(new Callback<List<Branch>>() {
@Override
public void onResponse(Call<List<Branch>> call, Response<List<Branch>> response) {
if (response.isSuccessful()) {
saveBranch(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Branch>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_branch));
}
});
}
private void saveBranch(List<Branch> branches, GlobalState context) {
IBranchManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxBranch(branches.toArray(new Branch[branches.size()]));
databaseManager.closeDbConnections();
}
private void downloadBranchTypeCat(final GlobalState context) {
Call<List<BranchType>> call = ticketDoctorService.getBranchTypeCatalog();
call.enqueue(new Callback<List<BranchType>>() {
@Override
public void onResponse(Call<List<BranchType>> call, Response<List<BranchType>> response) {
if (response.isSuccessful()) {
saveBranchType(response.body(), context);
}
}
@Override
public void onFailure(Call<List<BranchType>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_branch_type));
}
});
}
private void saveBranchType(List<BranchType> branchTypes, GlobalState context) {
IBranchTypeManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxBranchType(branchTypes.toArray(new BranchType[branchTypes.size()]));
databaseManager.closeDbConnections();
}
private void downloadImpCauseCat(final GlobalState context) {
Call<List<ImpCause>> call = ticketDoctorService.getImpCauseCatalog();
call.enqueue(new Callback<List<ImpCause>>() {
@Override
public void onResponse(Call<List<ImpCause>> call, Response<List<ImpCause>> response) {
if (response.isSuccessful()) {
saveImpCause(response.body(), context);
}
}
@Override
public void onFailure(Call<List<ImpCause>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_imp_cause));
}
});
}
private void saveImpCause(List<ImpCause> impCauses, GlobalState context) {
IImpCauseManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxImpCause(impCauses.toArray(new ImpCause[impCauses.size()]));
databaseManager.closeDbConnections();
}
private void downloadSymptomDiagnosticCat(final GlobalState context) {
Log.i("TAG", "downloadSymptomDiagnosticCat");
Call<List<SymptomDiagnostic>> call = ticketDoctorService.getSymptomDiagnosticCatalog();
call.enqueue(new Callback<List<SymptomDiagnostic>>() {
@Override
public void onResponse(Call<List<SymptomDiagnostic>> call, Response<List<SymptomDiagnostic>> response) {
if (response.isSuccessful()) {
saveSymptomDiagnostics(response.body(), context);
}
}
@Override
public void onFailure(Call<List<SymptomDiagnostic>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_symptom_diagnostic));
}
});
}
private void saveSymptomDiagnostics(List<SymptomDiagnostic> symptomDiagnostics, GlobalState context) {
ISymptomDiagnosticManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxSymptomDiagnostic(symptomDiagnostics.toArray(new SymptomDiagnostic[symptomDiagnostics.size()]));
databaseManager.closeDbConnections();
}
private void downloadTypeSymptomCat(final GlobalState context) {
Call<List<TypeSymptom>> call = ticketDoctorService.getTypeSymptomCatalog();
call.enqueue(new Callback<List<TypeSymptom>>() {
@Override
public void onResponse(Call<List<TypeSymptom>> call, Response<List<TypeSymptom>> response) {
if (response.isSuccessful()) {
saveTypeSymptoms(response.body(), context);
}
}
@Override
public void onFailure(Call<List<TypeSymptom>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_type_symptoms));
}
});
}
private void saveTypeSymptoms(List<TypeSymptom> typeSymptoms, GlobalState context) {
ITypeSymptomManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxTypeSymptom(typeSymptoms.toArray(new TypeSymptom[typeSymptoms.size()]));
databaseManager.closeDbConnections();
}
private void downloadDiagnosticCat(final GlobalState context) {
Call<List<Diagnostic>> call = ticketDoctorService.getDiagnosticCatalog();
call.enqueue(new Callback<List<Diagnostic>>() {
@Override
public void onResponse(Call<List<Diagnostic>> call, Response<List<Diagnostic>> response) {
if (response.isSuccessful()) {
saveDiagnostics(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Diagnostic>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_diagnostics));
}
});
}
private void saveDiagnostics(List<Diagnostic> diagnostics, GlobalState context) {
IDiagnosticManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxDiagnostic(diagnostics.toArray(new Diagnostic[diagnostics.size()]));
databaseManager.closeDbConnections();
}
private void downloadSymptomCat(final GlobalState context) {
Call<List<Symptom>> call = ticketDoctorService.getSymptomCatalog();
call.enqueue(new Callback<List<Symptom>>() {
@Override
public void onResponse(Call<List<Symptom>> call, Response<List<Symptom>> response) {
if (response.isSuccessful()) {
saveSymptoms(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Symptom>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_symptoms));
}
});
}
private void saveSymptoms(List<Symptom> symptoms, GlobalState context) {
ISymptomManager databaseManager = new DatabaseManager(context);
databaseManager.insertOrReplaceInTxSymptom(symptoms.toArray(new Symptom[symptoms.size()]));
databaseManager.closeDbConnections();
}
private void downloadStatusCat(final GlobalState context) {
Log.i("TAG", "downloadStatusCat");
Call<List<TicketStatus>> call = ticketDoctorService.getTicketStatusCatalog();
call.enqueue(new Callback<List<TicketStatus>>() {
@Override
public void onResponse(Call<List<TicketStatus>> call, Response<List<TicketStatus>> response) {
if (response.isSuccessful()) {
saveTicketStatus(response.body(), context);
}
}
@Override
public void onFailure(Call<List<TicketStatus>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_ticket_status));
}
});
}
private void saveTicketStatus(List<TicketStatus> ticketStatuses, GlobalState context) {
ITicketStatusManager databaseManager = new DatabaseManager(context);
// for (TicketStatus ticketStatus : ticketStatuses){
// databaseManager.insertTicketStatus(ticketStatus);
databaseManager.insertOrReplaceInTxTicketStatus(ticketStatuses.toArray(new TicketStatus[ticketStatuses.size()]));
// }
databaseManager.closeDbConnections();
}
private void downloadUsersCat(final GlobalState context) {
Call<List<User>> call = ticketDoctorService.getUsersCatalog();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()) {
saveUsers(response.body(), context);
}
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_users));
}
});
}
private void saveUsers(List<User> users, Context context) {
IUserManager databaseManager = new DatabaseManager(context);
// for (User user : users){
// databaseManager.insertUser(user);
databaseManager.insertOrReplaceInTxUser(users.toArray(new User[users.size()]));
// }
databaseManager.closeDbConnections();
}
private void downloadCategoryCat(final GlobalState context) {
Call<List<Category>> call = ticketDoctorService.getCategoriesCatalog();
call.enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
if (response.isSuccessful()) {
saveCategories(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_categories));
}
});
}
private void saveCategories(List<Category> categories, GlobalState context) {
ICategoryManager databaseManager = new DatabaseManager(context);
// for (Category category : categories){
databaseManager.insertOrReplaceInTxCategory(categories.toArray(new Category[categories.size()]));
// }
databaseManager.closeDbConnections();
}
private void downloadTypesCat(final GlobalState context) {
Call<List<Type>> call = ticketDoctorService.getTypesCatalog();
call.enqueue(new Callback<List<Type>>() {
@Override
public void onResponse(Call<List<Type>> call, Response<List<Type>> response) {
if (response.isSuccessful()) {
saveTypes(response.body(), context);
}
}
@Override
public void onFailure(Call<List<Type>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_categories));
}
});
}
private void saveTypes(List<Type> types, GlobalState context) {
DatabaseManager databaseManager = new DatabaseManager(context);
// for (Type type : types){
databaseManager.insertOrReplaceInTxType(types.toArray(new Type[types.size()]));
// }
databaseManager.closeDbConnections();
}
private void downloadProjectStatusCat(final GlobalState context) {
Call<List<ProjectStatus>> call = ticketDoctorService.getProjectStatusCatalog();
call.enqueue(new Callback<List<ProjectStatus>>() {
@Override
public void onResponse(Call<List<ProjectStatus>> call, Response<List<ProjectStatus>> response) {
if (response.isSuccessful()) {
saveProjectStatus(response.body(), context);
}
}
@Override
public void onFailure(Call<List<ProjectStatus>> call, Throwable t) {
Log.e(TAG, context.getString(R.string.error_login_categories));
}
});
}
private void saveProjectStatus(List<ProjectStatus> projectStatuses, GlobalState context) {
IProjectStatusManager databaseManager = new DatabaseManager(context);
// for (ProjectStatus projectStatus : projectStatuses){
databaseManager.insertOrReplaceInTxProjectStatus(projectStatuses.toArray(new ProjectStatus[projectStatuses.size()]));
// }
databaseManager.closeDbConnections();
}
}
| true |
2bbe9adbd6353cd8ff8a33d97027fdbe27c5cc10 | Java | dattap1977/WorkflowEngine | /src/com/util/Constants.java | UTF-8 | 210 | 1.59375 | 2 | [] | no_license | package com.util;
public class Constants {
public static final String USERNAME = "root";
public static final String PASSWORD = "krispass2019";
public static final String DBNAME = "workflowengine";
}
| true |
cf160ec5ec5151f6efdcb113f992f10b774b8002 | Java | purustech/CoreJava | /com/purustech/learning/threads/ThreadExampleUsingThread.java | UTF-8 | 1,538 | 3.984375 | 4 | [] | no_license | package com.purustech.learning.threads;
public class ThreadExampleUsingThread {
public static void main(String[] args) {
System.out.println("In main thread");
System.out.println(Thread.currentThread().getName());
// using Thread class
MyThread myThreadUsingThread = new MyThread();
myThreadUsingThread.setName("UsingThreadClass");
myThreadUsingThread.setPriority(Thread.MIN_PRIORITY);
myThreadUsingThread.start();
// using Runnable Interface
MyThreadRunnable myThreadUsingRunnable = new MyThreadRunnable();
// myThreadUsingRunnable.run(); // this will cause the code to execute in the same main thread.
Thread threadRunnable = new Thread(myThreadUsingRunnable);
threadRunnable.setName("UsingRunnable");
threadRunnable.setPriority(Thread.MAX_PRIORITY);
threadRunnable.start();
}
}
class MyThread extends Thread {
public void run(){
try {
System.out.println("sleeping for 5s");
// Thread.yield();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("MyThread running using Thread class");
System.out.println(Thread.currentThread().getName());
}
}
class MyThreadRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyThread running using runnable interface");
System.out.println(Thread.currentThread().getName());
}
} | true |
df1880843a7ed0325486a25a089a8dcb8ba88f57 | Java | msmtmsmt123/jadx-1 | /f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/com/aide/ui/build/android/b.java | UTF-8 | 19,873 | 1.625 | 2 | [] | no_license | package com.aide.ui.build.android;
import android.os.Handler;
import com.aide.common.m;
import com.aide.engine.SyntaxError;
import com.aide.ui.build.d;
import com.aide.ui.build.packagingservice.b.a;
import com.aide.ui.e;
import com.aide.ui.h;
import it;
import it$a;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import ok;
import pc$a;
import qh;
public class b implements com.aide.ui.build.b, it {
private a DW;
private boolean EQ;
private d FH;
private n Hw;
private String J0;
private String J8;
private List<String> Mr;
private String QX;
private boolean U2;
private String VH;
private String Ws;
private String XL;
private boolean Zo;
private String aM;
private int gn;
private String j3;
private AaptService j6;
private boolean tp;
private int u7;
private String v5;
private boolean we;
class 1 implements pc$a {
final /* synthetic */ b j6;
1(b bVar) {
this.j6 = bVar;
}
public void Mr() {
if (this.j6.Zo) {
this.j6.U2();
}
}
public void DW(String str) {
if (this.j6.Zo) {
this.j6.U2();
}
}
}
class 2 extends a {
final /* synthetic */ b j6;
class 1 implements Runnable {
final /* synthetic */ 2 DW;
final /* synthetic */ boolean j6;
class 1 implements Runnable {
final /* synthetic */ 1 j6;
1(1 1) {
this.j6 = 1;
}
public void run() {
if (!e.u7().j6()) {
m.j6(e.u7(), "Export APK", "APK file " + this.j6.DW.j6.Ws + " has been exported and can be published.\n\nThe APK has been signed with your key in " + this.j6.DW.j6.QX + ". Make sure to keep this file for future updates.", null);
}
}
}
1(2 2, boolean z) {
this.DW = 2;
this.j6 = z;
}
public void run() {
this.DW.j6.v5 = this.DW.j6.EQ();
if (this.DW.j6.v5 != null) {
if (this.j6) {
this.DW.j6.U2 = false;
}
this.DW.j6.gn();
return;
}
this.DW.j6.j6(null, 0, false);
this.DW.j6.U2 = true;
if (this.DW.j6.we) {
Runnable 1 = new 1(this);
if (this.DW.j6.J8()) {
m.j6(e.tp(), "Warning", "Your app supports only ARM. It may work with reduced performance on Intel Architecture based devices.", 1);
return;
} else {
1.run();
return;
}
}
this.DW.j6.we();
}
}
class 2 implements Runnable {
final /* synthetic */ 2 DW;
final /* synthetic */ String j6;
2(2 2, String str) {
this.DW = 2;
this.j6 = str;
}
public void run() {
this.DW.j6.FH(this.j6);
}
}
class 3 implements Runnable {
final /* synthetic */ 2 j6;
3(2 2) {
this.j6 = 2;
}
public void run() {
this.j6.j6.FH("Packaging was interrupted!");
}
}
class 4 implements Runnable {
final /* synthetic */ int DW;
final /* synthetic */ 2 FH;
final /* synthetic */ String j6;
4(2 2, String str, int i) {
this.FH = 2;
this.j6 = str;
this.DW = i;
}
public void run() {
this.FH.j6.j6(this.j6, this.DW, false);
}
}
2(b bVar) {
this.j6 = bVar;
}
public void j6(boolean z) {
e.j6(new 1(this, z));
}
public void j6(String str) {
e.j6(new 2(this, str));
}
public void j6() {
e.j6(new 3(this));
}
public void j6(String str, int i) {
e.j6(new 4(this, str, i));
}
}
class 3 implements e {
final /* synthetic */ b j6;
class 1 implements Runnable {
final /* synthetic */ 3 j6;
1(3 3) {
this.j6 = 3;
}
public void run() {
this.j6.j6.FH("aapt was interrupted!");
}
}
class 2 implements Runnable {
final /* synthetic */ 3 j6;
2(3 3) {
this.j6 = 3;
}
public void run() {
this.j6.j6.FH("aapt failed!");
}
}
class 3 implements Runnable {
final /* synthetic */ 3 DW;
final /* synthetic */ boolean j6;
3(3 3, boolean z) {
this.DW = 3;
this.j6 = z;
}
public void run() {
if (this.j6) {
this.DW.j6.U2 = false;
}
if (!this.DW.j6.tp) {
this.DW.j6.QX();
} else if (this.DW.j6.Mr == null || !this.DW.j6.Mr.isEmpty()) {
this.DW.j6.j6("Running aidl...", 10, false);
this.DW.j6.DW.j6(this.DW.j6.Mr);
} else {
e.u7().g3();
this.DW.j6.j3();
this.DW.j6.j6(null, 0, false);
}
}
}
class 4 implements Runnable {
final /* synthetic */ 3 DW;
final /* synthetic */ Map j6;
4(3 3, Map map) {
this.DW = 3;
this.j6 = map;
}
public void run() {
this.DW.j6.j6("aapt", this.j6);
this.DW.j6.Mr();
}
}
3(b bVar) {
this.j6 = bVar;
}
public void j6() {
e.j6(new 1(this));
}
public void DW() {
e.j6(new 2(this));
}
public void j6(boolean z) {
e.j6(new 3(this, z));
}
public void j6(Map<String, List<SyntaxError>> map) {
e.j6(new 4(this, map));
}
}
class 4 implements f {
final /* synthetic */ b j6;
class 1 implements Runnable {
final /* synthetic */ 4 j6;
1(4 4) {
this.j6 = 4;
}
public void run() {
this.j6.j6.FH("aidl was interrupted!");
}
}
class 2 implements Runnable {
final /* synthetic */ 4 j6;
2(4 4) {
this.j6 = 4;
}
public void run() {
this.j6.j6.FH("aidl failed!");
}
}
class 3 implements Runnable {
final /* synthetic */ 4 j6;
3(4 4) {
this.j6 = 4;
}
public void run() {
e.u7().g3();
if (this.j6.j6.tp) {
this.j6.j6.j3();
this.j6.j6.j6(null, 0, false);
return;
}
this.j6.j6.aM();
}
}
class 4 implements Runnable {
final /* synthetic */ 4 DW;
final /* synthetic */ Map j6;
4(4 4, Map map) {
this.DW = 4;
this.j6 = map;
}
public void run() {
this.DW.j6.j6("aidl", this.j6);
this.DW.j6.Mr();
}
}
4(b bVar) {
this.j6 = bVar;
}
public void j6() {
e.j6(new 1(this));
}
public void DW() {
e.j6(new 2(this));
}
public void FH() {
e.j6(new 3(this));
}
public void j6(Map<String, List<SyntaxError>> map) {
e.j6(new 4(this, map));
}
}
class 5 implements g {
final /* synthetic */ b j6;
class 1 implements Runnable {
final /* synthetic */ 5 j6;
1(5 5) {
this.j6 = 5;
}
public void run() {
this.j6.j6.FH("NDK build was interrupted!");
}
}
class 2 implements Runnable {
final /* synthetic */ 5 j6;
2(5 5) {
this.j6 = 5;
}
public void run() {
this.j6.j6.FH("NDK build failed!");
}
}
class 3 implements Runnable {
final /* synthetic */ 5 DW;
final /* synthetic */ boolean j6;
3(5 5, boolean z) {
this.DW = 5;
this.j6 = z;
}
public void run() {
if (this.j6) {
this.DW.j6.U2 = false;
}
this.DW.j6.j6(this.DW.j6.v5, this.DW.j6.J0);
}
}
class 4 implements Runnable {
final /* synthetic */ 5 DW;
final /* synthetic */ Map j6;
4(5 5, Map map) {
this.DW = 5;
this.j6 = map;
}
public void run() {
this.DW.j6.j6("NDK", this.j6);
this.DW.j6.Mr();
}
}
5(b bVar) {
this.j6 = bVar;
}
public void j6() {
e.j6(new 1(this));
}
public void DW() {
e.j6(new 2(this));
}
public void j6(boolean z) {
e.j6(new 3(this, z));
}
public void j6(Map<String, List<SyntaxError>> map) {
e.j6(new 4(this, map));
}
}
class 6 implements k.a {
final /* synthetic */ String DW;
final /* synthetic */ b FH;
final /* synthetic */ String j6;
6(b bVar, String str, String str2) {
this.FH = bVar;
this.j6 = str;
this.DW = str2;
}
public void j6(String str, String str2, String str3, String str4) {
this.FH.j6(this.j6, this.DW, str, str2, str3, str4);
}
}
class 7 implements k.a {
final /* synthetic */ String DW;
final /* synthetic */ String FH;
final /* synthetic */ b Hw;
final /* synthetic */ boolean j6;
7(b bVar, boolean z, String str, String str2) {
this.Hw = bVar;
this.j6 = z;
this.DW = str;
this.FH = str2;
}
public void j6(String str, String str2, String str3, String str4) {
this.Hw.j6(this.j6, this.DW, this.FH, str, str2, str3, str4);
}
}
class 8 implements Runnable {
final /* synthetic */ b j6;
8(b bVar) {
this.j6 = bVar;
}
public void run() {
this.j6.gn();
}
}
class 9 implements Runnable {
final /* synthetic */ b DW;
final /* synthetic */ String j6;
9(b bVar, String str) {
this.DW = bVar;
this.j6 = str;
}
public void run() {
e.u7().j6(this.DW.Ws, this.j6);
}
}
public b() {
this.Ws = "";
this.QX = "";
this.XL = "";
this.aM = "";
this.j3 = "";
}
public void j6(boolean z) {
if (z) {
this.U2 = false;
}
j3();
if (e.aM().Hw(".java")) {
Mr();
} else {
XL();
}
}
public void j6(String str) {
FH("Compilation failed: " + str);
}
public void Zo() {
if (this.Zo) {
aM();
}
}
public void Hw() {
this.U2 = false;
}
public void v5() {
this.U2 = false;
this.j6.j6(e.a8().v5());
}
public void FH() {
e.aM().j6(new 1(this));
this.Hw = new n();
this.Hw.j6(new 2(this));
this.j6 = new AaptService(e.gn());
this.j6.j6(new 3(this));
this.DW = new a();
this.DW.j6(new 4(this));
this.FH = new d();
this.FH.j6(new 5(this));
}
public void j6(String str, String str2, String str3) {
e.SI().j6(str3, ok.DW(e.a8().u7(), "release", str), new 6(this, str, str2));
}
private void j6(String str, String str2, String str3, String str4, String str5, String str6) {
this.EQ = false;
this.we = true;
this.U2 = false;
this.J8 = "release";
this.J0 = str;
this.Ws = str2;
this.j6.j6(str);
j6(str3, str4, str5, str6);
}
public void j6(boolean z, String str, String str2) {
e.j3().j6(false, false);
if (ok.QX()) {
j6(z, str, str2, e.Ws().DW(), "xxxxxx", "weardebug", "xxxxxx");
} else if (e.VH() || (ok.DW(e.a8().u7(), null) != null && ok.DW(e.a8().u7(), null).startsWith("com.aide.trainer."))) {
j6(z, "debug", null, "", "", "", "");
} else {
e.SI().j6(h.Mr(), ok.DW(e.a8().u7(), str, str2), new 7(this, z, str, str2));
}
}
private void j6(boolean z, String str, String str2, String str3, String str4, String str5, String str6) {
this.EQ = z;
this.we = false;
this.J8 = str;
this.J0 = str2;
if (z) {
this.U2 = false;
}
this.Ws = ok.er(e.a8().u7());
j6(str3, str4, str5, str6);
}
private void j6(String str, String str2, String str3, String str4) {
e.aM().u7();
ok.Ws();
this.tp = false;
this.Mr = null;
this.QX = str;
this.XL = str2;
this.aM = str3;
this.j3 = str4;
this.v5 = u7();
j6("Building...", 0, false);
e.sG().j6((it) this);
e.U2().j6(this, e.sG().j6());
new Handler().postDelayed(new 8(this), 100);
}
private void gn() {
j6("Building...", 0, false);
Ws();
}
public void j6(boolean z, List<String> list) {
if (this.VH != null) {
return;
}
if (z || list == null || !list.isEmpty()) {
e.aM().u7();
ok.Ws();
this.v5 = null;
e.U2().j6(this, true);
this.Mr = list;
this.EQ = false;
this.tp = true;
this.J0 = e.a8().v5();
if (z) {
j6("Running aapt...", 10, false);
this.j6.DW(this.J0);
} else if (list != null && !list.isEmpty()) {
j6("Running aidl...", 10, false);
this.DW.j6((List) list);
}
}
}
private String u7() {
List tp = e.a8().tp();
return (String) tp.get(tp.size() - 1);
}
private boolean tp() {
return u7().equals(this.v5);
}
private String EQ() {
List tp = e.a8().tp();
int indexOf = tp.indexOf(this.v5);
if (indexOf > 0) {
return (String) tp.get(indexOf - 1);
}
return null;
}
private void j6(String str, Map<String, List<SyntaxError>> map) {
e.aM().j6(str, (Map) map);
e.u7().g3();
}
private void j6(String str, String str2) {
if (this.U2) {
this.Hw.j6();
return;
}
Map EQ = e.a8().EQ(str);
String er = ok.er(str);
String j6 = ok.j6(str, "debug-aide".equals(this.J8));
String gW = ok.gW(str);
String yS = ok.yS(str);
String rN = ok.rN(str);
String[] j62 = ok.j6(EQ, "debug-aide".equals(this.J8));
String[] j63 = ok.j6(EQ, this.J8, str2);
String[] j64 = ok.j6(EQ, str2);
String[] j65 = ok.j6(EQ);
boolean v5 = ok.v5(str, str2);
if (str.equals(e.a8().u7())) {
er = this.Ws;
}
this.Hw.j6(j6, j62, j64, j65, gW, yS, rN, j63, er, this.QX, this.XL, this.aM, this.j3, this.EQ, h.v5(), v5);
this.Hw.DW();
}
public it$a DW() {
return it$a.ANDROID;
}
public void VH() {
e.u7().dx();
we();
}
public int j6() {
return 17;
}
private void we() {
if (this.VH == null && !e.sG().v5() && !e.sG().FH()) {
J0();
}
}
private void J0() {
if (!this.EQ) {
String u7 = e.a8().u7();
String DW = ok.DW(u7, e.a8().v5());
if (e.VH()) {
e.QX().j6(this.Ws, DW);
} else if (h.Hw(u7) || !J8()) {
e.u7().j6(this.Ws, DW);
} else {
h.v5(u7);
m.j6(e.tp(), "Warning", "Your app supports only ARM. It may work with reduced performance on Intel Architecture based devices.", new 9(this, DW));
}
}
}
private boolean J8() {
for (String str : ok.j6(e.a8().EQ(e.a8().u7()), null, e.a8().v5())) {
boolean z = DW(new StringBuilder().append(str).append("/armeabi").toString()) || DW(str + "/armeabi-v7a");
if (z && !DW(str + "/x86")) {
return true;
}
}
return false;
}
private boolean DW(String str) {
if (qh.VH(str)) {
try {
for (String endsWith : qh.QX(str)) {
if (endsWith.endsWith(".so")) {
return true;
}
}
} catch (IOException e) {
}
}
return false;
}
private void Ws() {
j6("Running aapt...", 10, false);
String BT = ok.BT(this.v5);
if (new File(BT).exists() || new File(BT).mkdirs()) {
if (this.EQ) {
for (String BT2 : ok.FH(e.a8().EQ(this.v5), this.J0).keySet()) {
try {
qh.j3(BT2);
} catch (IOException e) {
FH("Deleting gen dir '" + BT2 + "' failed.");
}
}
}
this.j6.j6(this.v5, this.J8, this.J0, this.EQ, "release".equals(this.J8), tp());
return;
}
FH("Could not create target dir " + BT2);
}
private void QX() {
j6("Running aidl...", 10, false);
this.DW.j6(this.v5, this.EQ, tp());
}
private void XL() {
j6("Building native code...", 80, false);
this.FH.j6(this.EQ);
}
private void aM() {
j6("Compiling...", 20, true);
String j6 = ok.j6(this.v5, "debug-aide".equals(this.J8));
if (!new File(j6).exists() && !new File(j6).mkdirs()) {
FH("Could not create destination dir " + j6);
} else if (this.EQ) {
e.XL().we();
} else {
e.XL().EQ();
}
}
private void j3() {
e.nw().DW(new ArrayList(ok.gn(e.a8().EQ(), null).keySet()));
}
private void Mr() {
FH("Your project contains errors. Please fix them before running the app.");
}
private void FH(String str) {
this.VH = null;
e.U2().j6(str);
}
private void U2() {
int Zo = e.aM().Zo();
this.u7 = Zo == 0 ? 100 : (e.aM().v5() * 100) / Zo;
e.U2().j6(this.v5, this.VH, this.gn, this.u7);
}
private void j6(String str, int i, boolean z) {
this.VH = str;
this.gn = i;
this.u7 = 0;
this.Zo = z;
e.U2().j6(this.v5, str, i, this.u7);
}
}
| true |
9cd6626b5edfe046c1b482ba7ea571e8da790002 | Java | umitzngn/testng | /src/main/java/org/testng/xml/IFileParser.java | UTF-8 | 215 | 1.664063 | 2 | [
"Apache-2.0"
] | permissive | package org.testng.xml;
import org.testng.TestNGException;
import java.io.InputStream;
public interface IFileParser<T> {
T parse(String filePath, InputStream is, boolean loadClasses) throws TestNGException;
}
| true |
cdceaa97dfc9207726c141be748b9c53b358cf86 | Java | zj-jason/OmniGraph | /src/main/java/com/todense/viewmodel/algorithm/TestTask.java | UTF-8 | 284 | 1.867188 | 2 | [] | no_license | package com.todense.viewmodel.algorithm;
import javafx.concurrent.Task;
public class TestTask extends Task<Void> {
@Override
protected Void call() throws Exception {
return null;
}
@Override
protected void running() {
super.running();
}
}
| true |
b5b0cab3d464aeb1f41f05a4432bea76c1b1f733 | Java | rupeshpatil/springboot | /SpringbootJPA/src/main/java/com/capgemini/demo/controller/EmployeeController.java | UTF-8 | 1,205 | 2.53125 | 3 | [] | no_license | package com.capgemini.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.capgemini.demo.dao.EmployeeDAO;
import com.capgemini.demo.model.Employee;
@Controller
public class EmployeeController {
@Autowired
EmployeeDAO empdao;
@RequestMapping("/")
public String home() {
return "home.jsp";
}
@RequestMapping("/addEmployee")
public String addEmployee(Employee emp) {
empdao.save(emp);
return "home.jsp";
}
@RequestMapping("/getEmployee")
public ModelAndView getEmployee(@RequestParam int empid) {
ModelAndView mv= new ModelAndView("showEmployee.jsp");
/*We can write query like below example*/
System.out.println(empdao.findByGender("male"));
System.out.println(empdao.findByGenderSorted("male"));
/** Below code is returning value by id */
Employee employee = new Employee();
employee = empdao.findById(empid).orElse(employee);
mv.addObject(employee);
return mv;
}
}
| true |
11b7ef3b2d01cb1b2109f0a709c5a5cfe415424f | Java | acujwal/SpringBootFizzBuzz | /src/main/java/com/example/fizzbuzz/HomeController.java | UTF-8 | 1,342 | 2.671875 | 3 | [] | no_license | package com.example.fizzbuzz;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
import java.util.ArrayList;
@Controller
public class HomeController {
@GetMapping("/") /*-- load the fizzbuzz page --*/
public String loadfizzBuzz(Model model) {
model.addAttribute("fizzbuzz", new fizzBuzz());
return "fizzbuzz";
}
@PostMapping("/process")
/*---validating and getting values entered by the user using @ModelAttribute---*/
public String processFizzBuzz(@Valid @ModelAttribute("fizzbuzz") fizzBuzz fizzbuzz, BindingResult resultError, Model model) {
/*---if the validation error is true the error message is printed---*/
if (resultError.hasErrors()) {
return "fizzbuzz";
}
else {
ArrayList<String> pullvalue = fizzbuzz.buzz(fizzbuzz.getStart(), fizzbuzz.getEnd());
model.addAttribute("print", pullvalue);
return "result";
}
}
}
| true |
062c081151b376f66a309831bbb5423a175e1d9a | Java | miyantara7/SpringsParkiran | /src/main/java/com/lawencon/springparkiran/dao/impl/jpa/KendaraanDaoImpl.java | UTF-8 | 1,538 | 2.09375 | 2 | [] | no_license | package com.lawencon.springparkiran.dao.impl.jpa;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.lawencon.springparkiran.dao.KendaraanDao;
import com.lawencon.springparkiran.model.Kendaraan;
@Repository("ken_repo_jpa")
public class KendaraanDaoImpl implements KendaraanDao {
@Autowired
private KendaraanRepo kendaraanRepos;
@Override
public void insertKendaraan(Kendaraan kendaraan, String user, String pass) throws Exception {
kendaraanRepos.save(kendaraan);
}
@Override
public Kendaraan validKendaraanCheckIn(Kendaraan kendaraan) throws Exception {
return kendaraanRepos.findByjenisKendaraan(kendaraan.getNoPlat().toLowerCase());
}
@Override
public void insertCheckoutKendaraan(Kendaraan kendaraan, String user, String pass) throws Exception {
kendaraanRepos.save(kendaraan);
}
@Override
public List<Kendaraan> viewKendaraanCheckIn(String user, String pass) throws Exception {
return kendaraanRepos.findBytanggalKeluar();
}
@Override
public List<Kendaraan> viewKendaraanCheckOut(String user, String pass) throws Exception {
return kendaraanRepos.findAlltanggalMasuk();
}
@Override
public Kendaraan cekKendaraan(Kendaraan kendaraan) throws Exception {
return kendaraanRepos.fingBynoPlat(kendaraan.getNoPlat().toLowerCase());
}
@Override
public Kendaraan cekOutKendaraan(Kendaraan kendaraan) throws Exception {
return kendaraanRepos.fingBynoPlat(kendaraan.getNoPlat().toLowerCase());
}
}
| true |
3ca868bc3e4dbc037783fbdd68e117f73ef9ca0e | Java | ralts00/twwing | /TechCrunch/Server/TCSInterface/src/twi/tcsi/rest/IStatus.java | UTF-8 | 177 | 1.796875 | 2 | [] | no_license | package twi.tcsi.rest;
import java.util.List;
public interface IStatus {
static List<Status> statusInstance = null;
public List<Status> getStatusInstance();
}
| true |
82ccf508feb817c7bf46b749c0d165cbe4c3651f | Java | AlexandrKananadze/My_projects | /src/_Lessons_Basic/src/Comparator/newclass (2021_05_17 11_23_30 UTC).java | UTF-8 | 1,598 | 3.046875 | 3 | [] | no_license | package Comparator;
import javax.swing.text.html.parser.Entity;
import java.util.*;
import java.util.Map.Entry;
public class newclass {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String str = console.nextLine();
String [] st = str.split(" ");
Map<String, Integer > s = new HashMap<>();
for (int i = 0; i < st.length; i++){
s.put(st[i], st[i].length());
}
String rot = console.nextLine();
System.out.println(ma(s, rot));
}
public static Map<String,Integer> ma(Map<String,Integer> i, String rot) {
Set<Entry<String,Integer>> k = i.entrySet();
List<Entry<String,Integer>> t= new ArrayList<>(k);
if (rot.equals("left")) {
t.sort(new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue()-o2.getValue();
}
});
}
else if (rot.equals("right")) {
t.sort(new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue()-o1.getValue();
}
});
}
Map<String,Integer> g = new LinkedHashMap<String,Integer>();
for (Entry <String, Integer> y: t ) {
g.put(y.getKey(), y.getValue());
}
return g;
}
}
| true |
2b4be5f3314af7041382b50f62059c64d72a15f2 | Java | bellmit/mall-2 | /gulimall-thrid-party/src/test/java/com/example/gulimall/thridparty/GulimallThridPartyApplicationTests.java | UTF-8 | 1,651 | 2.375 | 2 | [] | no_license | package com.example.gulimall.thridparty;
import com.aliyun.oss.OSS;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
@SpringBootTest
class GulimallThridPartyApplicationTests {
@Test
void contextLoads() {
}
/**
* 文件上传测试
* @throws FileNotFoundException
*/
// @Test
// public void uploadFile() throws FileNotFoundException {
//// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
// String endpoint = "oss-cn-shenzhen.aliyuncs.com";
//// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
// String accessKeyId = "LTAI4G9Vnxr9gR8eUwt2EyUk";
// String accessKeySecret = "Aejv6j7rqiKLCiO8i1DuwozR2yuJxN";
//
//// 创建OSSClient实例。
// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//// 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
// InputStream inputStream = new FileInputStream("D:\\软件下载\\360\\360zip\\config\\zcomment\\skin\\skin4.jpg");
//// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
// ossClient.putObject("gulimall-xubangzhu", "Skin4.jpg", inputStream);
//
//// 关闭OSSClient。
// ossClient.shutdown();
// }
}
| true |
77c17569bd14a550320935a4384e8b82ecf340e1 | Java | qiaopeichen/EffectiveJava | /9.覆盖equals时总要覆盖hashCode.java | UTF-8 | 3,642 | 3.671875 | 4 | [] | no_license | // 考虑一下PhoneNumber类,它的equals方法是根据第8条中给出的“诀窍”构造出来的
public final class PhoneNumber {
private final short areaCode;
private final short prefix;
private final short lineNumber;
public PhoneNumber(int areaCode, int prefix, int lineNumber) {
rangeCheck(areaCode, 999, "area code");
rangeCheck(prefix, 999, "prefix");
rangeCheck(lineNumber, 9999, "line number");
this.areaCode = (short) areaCode;
this.prefix = (short) prefix;
this.lineNumber = (short) lineNumber;
}
private static void rangeCheck(int arg, int max, string name) {
if (arg < 0 || arg > max)
throw new IllegalArgumentException(name + ": " + arg);
}
// 这里一定要有@override注解,或参数为Object o ,否则从语法角度上无法重写父类的equals。
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof PhoneNumber))
return false;
PhoneNumber pn = (PhoneNumber)o;
return pn.lineNumber == lineNumber
&& pn.prefix == prefix
&& pn.areaCode == areaCode;
}
// Broken - no hashCode method!
... // Remainder omitted
}
// 假设你企图将这个类与HashMap一起使用:
Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
m.put(new PhoneNumber(707, 867, 5309), "Jenny");
// 这时候你可能期望m.get(new PhoneNumber(707, 867, 5309))会返回 "Jenny",
// 但它实际上返回的是null。
// 由于PhoneNumber类没有覆盖hashCode方法,从而导致两个相等的实例具有不相等的散列码。
// 修正这个问题,需要为PhoneNumber类提供一个适当的hashCode方法。
// 下面给出简单的解决办法:
/*
1.把某个非零的常数值,比如说17,保存在一个名为result的int类型的变量中。
2.对于对象中的每个关键域f(指equals方法中涉及的每个域),完成以下步骤:
a.为该域计算int类型的散列码c
i.如果该域是boolean类型,则计算(f ? 1 : 0)。
ii.如果该域是byte/char/shot/或者int类型,则计算(int)f。
iii.如果该域是long类型,则计算(int)(f ^ f(>>>32))。
iv.如果该域是float类型,则计算Float.floatToIntBits(f)。
v.如果该域是double类型,则计算Double.doubleToLongBits(f),然后按照步骤2.a.iii,为得到的long类型值计算散列值。
vi.如果该域是一个对象引用,并且该类的equals方法通过递归地调用equals的方式来比较这个域,
则同样为这个域递归地调用hashCode。如果需要更复杂的比较,则为这个域计算一个“范式”,然后针对这个范式调用hashCode。
如果这个域的值为null,则返回0(或者其他某个常数,但通常是0)。
vii.如果该域是一个数组,则吧每一个元素当作单独的域来处理。也就是说,递归地应用上述规则,对每个重要的元素计算一个散列码,
然后根据2.b中的做法把这些散列值组合起来。如果数组域中的每个元素都很重要,可以利用发行版本1.5种增加到其中一个Arrays.hashCode方法。
b.按照下面的公式,把步骤2.a中计算得到的散列码c合并到result中:
result = 31 * result + c;
3.返回result。
4.写完了hashCode方法之后,问问自己“相等的实例是否都具有相等的散列码”。
*/
// 现在我们要把上述的解决办法用到PhoneNumber中。它有三个关键域,都是short类型:
@Override
public int hashCode() {
int result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
return result;
}
| true |
4d7b3d2ea3f305f7a39bdb42062983afd4846316 | Java | RobertHSchmidt/jedit | /plugins/FTP/tags/release-0-7-9/ftp/FtpPlugin.java | UTF-8 | 4,378 | 1.960938 | 2 | [] | no_license | /*
* FtpPlugin.java - Main class of FTP plugin
* :tabSize=8:indentSize=8:noTabs=false:
* :folding=explicit:collapseFolds=1:
*
* Copyright (C) 2000, 2003 Slava Pestov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package ftp;
//{{{ Imports
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.gjt.sp.jedit.Buffer;
import org.gjt.sp.jedit.EditPlugin;
import org.gjt.sp.jedit.GUIUtilities;
import org.gjt.sp.jedit.MiscUtilities;
import org.gjt.sp.jedit.OperatingSystem;
import org.gjt.sp.jedit.View;
import org.gjt.sp.jedit.jEdit;
import org.gjt.sp.jedit.browser.VFSBrowser;
import org.gjt.sp.jedit.io.VFSManager;
import org.gjt.sp.util.Log;
//}}}
public class FtpPlugin extends EditPlugin
{
//{{{ start() method
public void start()
{
ConnectionManager.loadPasswords();
} //}}}
//{{{ stop() method
public void stop()
{
DirectoryCache.clearAllCachedDirectories();
ConnectionManager.savePasswords();
} //}}}
//{{{ showOpenFTPDialog() method
public static void showOpenFTPDialog(View view, boolean secure)
{
if(secure && !OperatingSystem.hasJava14())
{
GUIUtilities.error(view,"vfs.sftp.no-java14",null);
return;
}
String path = ((FtpVFS)VFSManager.getVFSForProtocol(
secure ? "sftp" : "ftp"))
.showBrowseDialog(new Object[1],view);
if(path != null)
{
String[] files = GUIUtilities.showVFSFileDialog(
view,path,VFSBrowser.OPEN_DIALOG,true);
if(files == null)
return;
Buffer buffer = null;
for(int i = 0; i < files.length; i++)
{
Buffer _buffer = jEdit.openFile(null,files[i]);
if(_buffer != null)
buffer = _buffer;
}
if(buffer != null)
view.setBuffer(buffer);
}
} //}}}
//{{{ showSaveFTPDialog() method
public static void showSaveFTPDialog(View view, boolean secure)
{
if(secure && !OperatingSystem.hasJava14())
{
GUIUtilities.error(view,"vfs.sftp.no-java14",null);
return;
}
String path = ((FtpVFS)VFSManager.getVFSForProtocol(
secure ? "sftp" : "ftp"))
.showBrowseDialog(new Object[1],view);
if(path != null)
{
String[] files = GUIUtilities.showVFSFileDialog(
view,path,VFSBrowser.SAVE_DIALOG,false);
if(files == null)
return;
view.getBuffer().save(view,files[0],true);
}
} //}}}
//{{{ initSshtoolsHome() method
public static void initSshtoolsHome()
{
String path = MiscUtilities.constructPath(
jEdit.getSettingsDirectory(),"sshtools");
System.getProperties().put("sshtools.home",path);
String[] files = new String[] {
"authorization.xml",
"automation.xml",
"sshtools.xml"
};
File dir = new File(path,"conf");
dir.mkdirs();
try
{
for(int i = 0; i < files.length; i++)
{
File file = new File(dir,files[i]);
if(!file.exists())
{
copy(FtpPlugin.class.getResourceAsStream(
"/conf/" + files[i]),
new FileOutputStream(
file));
}
}
RollingFileAppender log = new RollingFileAppender(
new PatternLayout(),
MiscUtilities.constructPath(path,"ssh.log"),
true);
log.setMaxFileSize("100KB");
BasicConfigurator.configure(log);
}
catch(IOException io)
{
Log.log(Log.ERROR,FtpPlugin.class,io);
}
} //}}}
//{{{ Private members
//{{{ copy() method
private static void copy(InputStream in, OutputStream out) throws IOException
{
try
{
byte[] buf = new byte[4096];
int count;
while((count = in.read(buf,0,buf.length)) != -1)
{
out.write(buf,0,count);
}
}
finally
{
in.close();
out.close();
}
} //}}}
//}}}
}
| true |
0726815cc69996adef18fbfede58f2951cd6f5bd | Java | weipengyi123/java_base | /src/com/thread/Thread_test3.java | UTF-8 | 1,179 | 3.8125 | 4 | [] | no_license | package com.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread3 implements Callable<Object> {
@Override
public Integer call() throws Exception {
int i = 0;
while (i++ < 15) {
System.out.println(Thread.currentThread().getName() + "的run()方法在运行");
}
return i;
}
}
public class Thread_test3 {
public static void main(String[] args) throws Exception, ExecutionException {
// 创建MyThread实例对象
MyThread3 mt1 = new MyThread3();
FutureTask<Object> ft1 = new FutureTask<Object>(mt1);
Thread t1 = new Thread(ft1, "线程1");
// 调用start()方法启动线程
t1.start();
MyThread3 mt2 = new MyThread3();
FutureTask<Object> ft2 = new FutureTask<Object>(mt2);
Thread t2 = new Thread(ft2, "线程2");
// 调用start()方法启动线程
t2.start();
//通过FutureTask对象的方法管理返回值
new Thread(new FutureTask<Object>(new MyThread3()), "线程3").start();
System.out.println("线程1返回结果" + ft1.get());
System.out.println("线程2返回结果" + ft2.get());
}
}
| true |
d0387145f4f438aeb15f5f3602e1d14c10c286ef | Java | 76260865/usedcar | /src/com/jason/usedcar/fragment/CarMilesChooseFragment.java | UTF-8 | 1,654 | 2.234375 | 2 | [] | no_license | package com.jason.usedcar.fragment;
import java.util.ArrayList;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.jason.usedcar.R;
import com.jason.usedcar.model.data.FilterEntity;
import java.util.List;
public class CarMilesChooseFragment extends SearchConditionChooseFragment {
public CarMilesChooseFragment(List<FilterEntity> filters) {
super(filters);
}
private CarMilesChooseDialogListener mChooseListener;
public interface CarMilesChooseDialogListener {
void onCarMilesSelected(FilterEntity filter);
}
public void setCarMilesChooseDialogListener(
CarMilesChooseDialogListener listener) {
mChooseListener = listener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle("价格");
return dialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
ListView listView = (ListView) view.findViewById(R.id.listView_seriers);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (mChooseListener != null) {
mChooseListener.onCarMilesSelected((FilterEntity) mAdapter
.getItem(position));
}
}
});
return view;
}
}
| true |
101be7b3e0e8b7da941e2eb3763e6c762909e1e7 | Java | agjacome/httpserver-web-test | /src/main/java/com/github/agjacome/httpserver/server/http/HttpResponse.java | UTF-8 | 418 | 2.109375 | 2 | [
"MIT"
] | permissive | package com.github.agjacome.httpserver.server.http;
import java.io.OutputStream;
import java.util.Optional;
import com.github.agjacome.httpserver.util.CaseInsensitiveString;
public interface HttpResponse {
public HttpStatusCode getStatusCode();
public long getContentLength();
public Optional<HttpHeader> getHeader(final CaseInsensitiveString key);
public OutputStream getBodyOutputStream();
}
| true |
8da0e8e9a56d86607f737c42fd84bd947ccdd19d | Java | ferro-sudo/Java | /src/Repl/q182_CleanString.java | UTF-8 | 160 | 2.1875 | 2 | [] | no_license | package Repl;
public class q182_CleanString {
public static String clean (String text ,String badWord) {
return text.replace(badWord, "");
}
}
| true |
29615846eb21d0229bedbad07a8859b547948eb2 | Java | felipe-barata/puc_ASD | /consultoria/src/main/java/br/com/sigo/consultoria/dtos/ListaArquivosContratosDTO.java | UTF-8 | 352 | 1.609375 | 2 | [] | no_license | package br.com.sigo.consultoria.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ListaArquivosContratosDTO implements Serializable {
private int id;
private String nomeArquivo;
}
| true |
c7ebf56030650cbef1e50f7597904899f628bbf4 | Java | rincostante/impresionGel | /src/main/java/ar/gob/ambiente/aplicaciones/entities/Inmueble.java | UTF-8 | 7,313 | 1.882813 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ar.gob.ambiente.aplicaciones.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Collection;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Administrador
*/
@Entity
@Table(name = "inmueble")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Inmueble.findAll", query = "SELECT i FROM Inmueble i")})
public class Inmueble implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "latitud")
private Double latitud;
@Column(name = "longitud")
private Double longitud;
@Size(max = 100)
@Column(name = "nomcatastral")
private String nomcatastral;
@Size(max = 20)
@Column(name = "partinmob")
private String partinmob;
@Column(name = "personalfabrica")
private Integer personalfabrica;
@Column(name = "personaloficina")
private Integer personaloficina;
@Column(name = "radioservido")
private Boolean radioservido;
@Column(name = "supcubierta")
private Double supcubierta;
@Column(name = "suplibre")
private Double suplibre;
@Size(max = 100)
@Column(name = "callefactibilidad")
private String callefactibilidad;
@Column(name = "idrupdom")
private BigInteger idrupdom;
@Size(max = 255)
@Column(name = "calle")
private String calle;
@Size(max = 20)
@Column(name = "dpto")
private String dpto;
@Size(max = 255)
@Column(name = "localidad")
private String localidad;
@Size(max = 10)
@Column(name = "numero")
private String numero;
@Size(max = 10)
@Column(name = "piso")
private String piso;
@Size(max = 50)
@Column(name = "provincia")
private String provincia;
@Size(max = 50)
@Column(name = "departamento")
private String departamento;
@OneToMany(mappedBy = "inmuebleId")
private Collection<Establecimiento> establecimientoCollection;
public Inmueble() {
}
public Inmueble(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getLatitud() {
return latitud;
}
public void setLatitud(Double latitud) {
this.latitud = latitud;
}
public Double getLongitud() {
return longitud;
}
public void setLongitud(Double longitud) {
this.longitud = longitud;
}
public String getNomcatastral() {
return nomcatastral;
}
public void setNomcatastral(String nomcatastral) {
this.nomcatastral = nomcatastral;
}
public String getPartinmob() {
return partinmob;
}
public void setPartinmob(String partinmob) {
this.partinmob = partinmob;
}
public Integer getPersonalfabrica() {
return personalfabrica;
}
public void setPersonalfabrica(Integer personalfabrica) {
this.personalfabrica = personalfabrica;
}
public Integer getPersonaloficina() {
return personaloficina;
}
public void setPersonaloficina(Integer personaloficina) {
this.personaloficina = personaloficina;
}
public Boolean getRadioservido() {
return radioservido;
}
public void setRadioservido(Boolean radioservido) {
this.radioservido = radioservido;
}
public Double getSupcubierta() {
return supcubierta;
}
public void setSupcubierta(Double supcubierta) {
this.supcubierta = supcubierta;
}
public Double getSuplibre() {
return suplibre;
}
public void setSuplibre(Double suplibre) {
this.suplibre = suplibre;
}
public String getCallefactibilidad() {
return callefactibilidad;
}
public void setCallefactibilidad(String callefactibilidad) {
this.callefactibilidad = callefactibilidad;
}
public BigInteger getIdrupdom() {
return idrupdom;
}
public void setIdrupdom(BigInteger idrupdom) {
this.idrupdom = idrupdom;
}
public String getCalle() {
return calle;
}
public void setCalle(String calle) {
this.calle = calle;
}
public String getDpto() {
return dpto;
}
public void setDpto(String dpto) {
this.dpto = dpto;
}
public String getLocalidad() {
return localidad;
}
public void setLocalidad(String localidad) {
this.localidad = localidad;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getPiso() {
return piso;
}
public void setPiso(String piso) {
this.piso = piso;
}
public String getProvincia() {
return provincia;
}
public void setProvincia(String provincia) {
this.provincia = provincia;
}
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
@XmlTransient
public Collection<Establecimiento> getEstablecimientoCollection() {
return establecimientoCollection;
}
public void setEstablecimientoCollection(Collection<Establecimiento> establecimientoCollection) {
this.establecimientoCollection = establecimientoCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Inmueble)) {
return false;
}
Inmueble other = (Inmueble) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "ar.gob.ambiente.aplicaciones.entities.Inmueble[ id=" + id + " ]";
}
}
| true |
5bc68945df432d2dc9c1993a77947d2cdb5f79a2 | Java | NguyenVanAnh1989/restaurant | /src/main/java/com/restaurant/c1603g/Constant/ManageQueries.java | UTF-8 | 1,359 | 1.8125 | 2 | [] | no_license | package com.restaurant.c1603g.Constant;
public class ManageQueries {
// SQL for Receptionist
public static final String GET_RECEPTIONIST = "SELECT * FROM tblReceptionist WHERE id = ?";
public static final String GET_RECEPTIONIST_BY_NAME = "SELECT * FROM tblReceptionist WHERE name LIKE ?";
public static final String INSERT_RECEPTIONIST = "INSERT INTO tblReceptionist VALUES (?,?,?,?)";
public static final String UPDATE_RECEPTIONIST = "UPDATE tblReceptionist SET name =? , phone =? ,activated =? WHERE id = ?";
public static final String DELETE_RECEPTIONIST = "UPDATE tblReceptionist SET activated = 0 WHERE id = ?";
// SQL for Addmin
public static final String GET_ADMIN = "SELECT * FROM tblAdmin WHERE id = ?";
public static final String GET_ADMIN_BY_NAME = "SELECT * FROM tblAdmin WHERE userName LIKE ?";
public static final String CHECK_EXIT_ADMIN = "SELECT * FROM tblAdmin WHERE userName = ?";
public static final String CHECK_ADMIN_ACOUNT = "SELECT * FROM tblAdmin WHERE userName = ? AND password = ?";
public static final String INSERT_ADMIN = "INSERT INTO tblAdmin VALUES (?,?,?,?,?)";
public static final String UPDATE_ADMIN = "UPDATE tblddmin SET userName = ? , password = ? ,permission = ?, activated = ? WHERE id = ?";
public static final String DELETE_ADMIN = "UPDATE tblAdmin SET activated = 0 WHERE id = ?";
}
| true |
b21e781eaed12bd7dd9f6e0716fbfe8d78d5d40d | Java | mehdishz11/BoomBoom | /app/src/main/java/psb/com/kidpaint/competition/leaderBoard/adapter/Adapter_LeaderShip.java | UTF-8 | 1,178 | 2.109375 | 2 | [] | no_license | package psb.com.kidpaint.competition.leaderBoard.adapter;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import psb.com.kidpaint.R;
import psb.com.kidpaint.competition.leaderBoard.PLeaderShip;
/**
* Created by morteza on 7/18/2018 AD.
*/
public class Adapter_LeaderShip extends RecyclerView.Adapter<ViewHolder_LeaderShip> {
private PLeaderShip pPaints;
public Adapter_LeaderShip(PLeaderShip pPaints) {
this.pPaints = pPaints;
}
@Override
public ViewHolder_LeaderShip onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_all_users, parent, false);
ViewHolder_LeaderShip recViewHolderNews = new ViewHolder_LeaderShip(view);
return recViewHolderNews;
}
@Override
public void onBindViewHolder(ViewHolder_LeaderShip holder, int position) {
pPaints.onBindViewHolder_GetLeaderShip(holder, position);
}
@Override
public int getItemCount() {
return pPaints.getArrSizeGetLeaderShip();
}
}
| true |
8436fc2dfe06d1e58d7d1241ee2c9a5fe172e1a6 | Java | jyesares/firma_digital | /src/model/Potencia.java | UTF-8 | 838 | 2.84375 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.math.BigInteger;
/**
*
* @author javiyesares
*/
public class Potencia {
public static BigInteger calculaPotencia(BigInteger a,BigInteger m,BigInteger n)
{
BigInteger b = new BigInteger("1");
while(!m.equals(BigInteger.valueOf(1))){
if((m.mod(BigInteger.valueOf(2))).equals(BigInteger.valueOf(1))){
b = b.multiply(a);
b = b.mod(n);
}
a = a.pow(2);
a = a.mod(n);
m = m.divide(BigInteger.valueOf(2));
}
b = a.multiply(b);
b = b.mod(n);
return b;
}
}
| true |
82a30402dc92edab7e6fb5a6a70d67efa3bc2bf3 | Java | PetroAndrushchak/EpamFinal | /ITMount/src/com/epam/project/controller/faq/IndexFaq.java | UTF-8 | 925 | 2.015625 | 2 | [] | no_license | package com.epam.project.controller.faq;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.epam.project.command.Action;
import com.epam.project.db.model.Article;
import com.epam.project.db.model.FaqCategory;
import com.epam.project.db.service.ArticleService;
import com.epam.project.db.service.FaqCategoryService;
public class IndexFaq implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<FaqCategory> categories = FaqCategoryService.getAllCategoriesWithQA();
request.setAttribute("categories", categories);
request.getRequestDispatcher("/WEB-INF/faq/index.jsp").forward(request, response);
}
@Override
public String getName() {
return "index";
}
}
| true |
e28a37c0c1e16123548ea819b681457ec174a649 | Java | Bhagyashri2000/LeetCode-June | /1: Invert Binary Tree/Solution.java | UTF-8 | 1,435 | 3.734375 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.*;
class Solution {
public TreeNode invertTree(TreeNode root)
{
Queue<TreeNode> q = new LinkedList<>(); //queue to store noes levelwise
q.add(root);
while(q.isEmpty()==false)
{
int cnt=q.size();
while(cnt>0)
{
cnt--;
TreeNode temp=q.remove();
if(temp!=null)
{
if(temp.right!=null)
{
q.add(temp.right);
}
if(temp.left!=null)
{
q.add(temp.left);
}
TreeNode temp1 = temp.left; //swap the left-child and right-child of node
temp.left=temp.right;
temp.right=temp1;
}
}
}
return root;
}
}
| true |
2ae8129463419ce30ca19b5ce1b479a14faff104 | Java | Ning-chuan/LearnJava | /BankingSystem_Mysql/src/dao/AtmDao.java | UTF-8 | 3,307 | 2.671875 | 3 | [] | no_license | package dao;
import domain.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class AtmDao {
private String className = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/atm?serverTimezone=CST";
private String name = "root";
private String password = "root";
//删除一条信息
public int delete(String aname){
int result = 0;
try {
String sql = "DELETE FROM USERS WHERE ANAME=?";
Class.forName(className);
Connection conn = DriverManager.getConnection(url,name,password);
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,aname);
result = pstat.executeUpdate();
pstat.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//更新一条信息
public int update(User user){
int result = 0;
try {
String sql = "UPDATE USERS SET APASSWORD=?,ABALANCE=? WHERE ANAME=?";
Class.forName(className);
Connection conn = DriverManager.getConnection(url,name,password);
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,user.getApassword());
pstat.setFloat(2,user.getAbalance());
pstat.setString(3,user.getAname());
result = pstat.executeUpdate();
pstat.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//新增一条记录
public int insert(User user){
int result = 0;
try {
String sql = "INSERT INTO USERS VALUES(?,?,?)";
Class.forName(className);
Connection conn = DriverManager.getConnection(url,name,password);
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,user.getAname());
pstat.setString(2,user.getApassword());
pstat.setFloat(3,user.getAbalance());
result = pstat.executeUpdate();
pstat.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//选中一条记录 返回User对象
public User selectOne(String aname){
User user = null;
try {
String sql = "SELECT ANAME,APASSWORD,ABALANCE FROM USERS WHERE ANAME=?";
Class.forName(className);
Connection conn = DriverManager.getConnection(url,name,password);
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,aname);
ResultSet rs = pstat.executeQuery();
if(rs.next()){
user = new User();
user.setAname(rs.getString("aname"));
user.setApassword(rs.getString("apassword"));
user.setAbalance(rs.getFloat("abalance"));
rs.close();
pstat.close();
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
| true |
070ee9e275fb271fb2f444fde3c70d1f4e113361 | Java | D-Yip/spike | /src/main/java/com/ysj/spike/service/impl/SpikeServiceImpl.java | UTF-8 | 2,527 | 2.296875 | 2 | [] | no_license | package com.ysj.spike.service.impl;
import com.ysj.spike.domain.OrderInfo;
import com.ysj.spike.domain.SpikeOrder;
import com.ysj.spike.redis.RedisService;
import com.ysj.spike.redis.impl.SpikeKey;
import com.ysj.spike.service.GoodsService;
import com.ysj.spike.service.OrderService;
import com.ysj.spike.service.SpikeService;
import com.ysj.spike.utils.MD5Util;
import com.ysj.spike.utils.UUIDUtil;
import com.ysj.spike.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SpikeServiceImpl implements SpikeService {
@Autowired
private GoodsService goodsService;
@Autowired
private OrderService orderService;
@Autowired
private RedisService redisService;
@Override
@Transactional
public OrderInfo spike(long userId, GoodsVO goodsVO) {
// 减库存 下订单 写入秒杀订单
boolean succcess = goodsService.reduceStock(goodsVO);
if (succcess) {
OrderInfo orderInfo = orderService.createOrder(userId,goodsVO);
return orderInfo;
} else {
setGoodsOver(goodsVO.getId());
return null;
}
}
@Override
public long getSpikeResult(Long id, long goodsId) {
SpikeOrder spikeOrder = orderService.getSpikeOrderByUserIdGoodsId(id, goodsId);
if (spikeOrder != null) {
return spikeOrder.getOrderId();
} else {
boolean isOver = getGoodsOver(goodsId);
if (isOver) {
return -1;
} else {
return 0;
}
}
}
@Override
public boolean checkPath(long userId, long goodsId, String path) {
String pathOld = redisService.get(SpikeKey.getSpikePath, "" + userId + "_" + goodsId, String.class);
return path.equals(pathOld);
}
@Override
public String createSpikePath(long userId, long goodsId) {
String str = MD5Util.md5(UUIDUtil.uuid()+"123456");
redisService.set(SpikeKey.getSpikePath, ""+userId+"_"+goodsId,str);
return str;
}
private void setGoodsOver(Long goodsId) {
redisService.set(SpikeKey.isGoodsOver,""+goodsId,true);
}
private boolean getGoodsOver(Long goodsId) {
boolean exists = redisService.exists(SpikeKey.isGoodsOver, "" + goodsId);
if (exists) {
return true;
}
return false;
}
}
| true |
e0a908d8673bf9f5a70753aaa5ba4620ee7a8094 | Java | evanluo1988/risk-management | /user_model/src/main/java/com/springboot/mapper/BaseDaoImpl.java | UTF-8 | 1,017 | 2.34375 | 2 | [] | no_license | package com.springboot.mapper;
import org.apache.ibatis.session.SqlSession;
import javax.annotation.Resource;
/**
* Created by zx on 2020/7/24.
*/
public class BaseDaoImpl<T> implements BaseDao<T> {
@Resource(name="mybatisSqlSessionTemplate")
private SqlSession session;
private final String path = "com.springboot.dao.";
private String getMethodPath(String methodType){
return path + this.getClass().getSimpleName() + "." + methodType;
}
@Override
public void save(T obj) {
session.insert(getMethodPath("save"), obj);
}
@Override
public void delete(T obj) {
session.delete(getMethodPath("delete"), obj);
}
@Override
public void delete(Long id) {
session.delete(getMethodPath("deleteById"), id);
}
@Override
public void update(T obj) {
session.update(getMethodPath("update"), obj);
}
@Override
public T get(Long id) {
return session.selectOne(getMethodPath("getById"), id);
}
}
| true |
11ab57de832525baa738b9f523463393aaf6ea2a | Java | Gaurav-Kumar1308/WizCart | /E Commerce/elasticSearch/src/main/java/com/ecommerce/elasticSearch/controller/ProductController.java | UTF-8 | 1,902 | 2.234375 | 2 | [] | no_license | package com.ecommerce.elasticSearch.controller;
import com.ecommerce.elasticSearch.document.Product;
import com.ecommerce.elasticSearch.search.SearchDTO;
import com.ecommerce.elasticSearch.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/es")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/display")
public String display(){
return "In Elastic Search";
}
@GetMapping("/{id}")
public Product get(@PathVariable(name = "id") Long id){
return productService.get(id);
}
@PostMapping
public Product save(@RequestBody Product product){
return productService.save(product);
}
@PutMapping
public Product update(@RequestBody Product product){
return productService.update(product);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable(name = "id") Long id){
productService.delete(id);
}
@PostMapping("/all")
public void saveAll(@RequestBody List<Product> productList){
productService.saveAll(productList);
}
@PostMapping("/search")
public List<Product> search(@RequestBody SearchDTO searchDTO){
List<String> fields = new ArrayList<>();
fields.add("productName");
fields.add("attributes");
fields.add("category");
fields.add("price");
fields.add("description");
searchDTO.setFields(fields);
System.out.println(searchDTO);
return productService.search(searchDTO);
}
@GetMapping("/getMerchant/{id}")
public List<Product> findByMerchantId(@PathVariable(name = "id") Long merchantId){
return productService.findByMerchantId(merchantId);
}
}
| true |
f235932697e83dd53ac21708cd14eb9d984b2e20 | Java | data-integrations/database-plugins | /mysql-plugin/src/e2e-test/java/io/cdap/plugin/mysql/locators/MySQLPropertiesPage.java | UTF-8 | 1,254 | 1.757813 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
* Copyright © 2023 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.mysql.locators;
import io.cdap.e2e.utils.SeleniumDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
/**
* MySQL source - Properties page - Locators.
*/
public class MySQLPropertiesPage {
@FindBy(how = How.XPATH, using = "//div[@data-cy='connector-MySQL']")
public static WebElement connectorMysql;
public static WebElement mySQLConnection(String connectionName) {
return SeleniumDriver.getDriver().findElement(
By.xpath("//div[contains(text(),'" + connectionName + "')]"));
}
}
| true |
9c708b623940de01399481d82cadca43ce1bd75e | Java | BunchesOfLife/Platformer | /src/GameObjects/Player.java | UTF-8 | 4,142 | 2.875 | 3 | [] | no_license | package GameObjects;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.LinkedList;
import src.Framework;
import src.Handler;
import src.ObjectId;
import src.Framework.GameState;
public class Player extends DynamicObject{
private int width = Framework.unit, height = Framework.unit*2, health = 100;
private Handler handler;
public Player(float x, float y, Handler handler, ObjectId id) {
super(x, y, id);
this.handler = handler;
}
public void draw(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect((int)x, (int)y, width, height);
}
public void update(LinkedList<GameObject> object){
x += dx;
dy += gravity;
y += dy;
if(dy > MAX_SPEED){
dy = MAX_SPEED;
}
collide(object);
if(health <= 0){
Framework.gameState = GameState.GameOver;
}
}
private void collide(LinkedList<GameObject> object){
for(int i=0; i < handler.size(); i++){
GameObject tempObject = handler.get(i);
if(tempObject.getId() == ObjectId.Ground){
if(getBoundsBot().intersects(tempObject.getBounds())){
dy = 0;
setJumping(false);
setFalling(false);
y = tempObject.getY() - height;
}else
setFalling(true);
if(getBoundsTop().intersects(tempObject.getBounds())){
dy = 0;
y = tempObject.getY() + 32;
}
if(getBoundsLeft().intersects(tempObject.getBounds())){
x = tempObject.getX() - width;
}
if(getBoundsRight().intersects(tempObject.getBounds())){
x = tempObject.getX() + 32;
}
}
if(tempObject.getId() == ObjectId.MovingEnemy){
if(getBoundsBot().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDy(-10);
}
if(getBoundsTop().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDy(8);
}
if(getBoundsLeft().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDx(-8);
}
if(getBoundsRight().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDx(8);
}
}
if(tempObject.getId() == ObjectId.DamageBlock){
if(getBoundsBot().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDy(-10);
}
if(getBoundsTop().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDy(8);
}
if(getBoundsLeft().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDx(-8);
}
if(getBoundsRight().intersects(tempObject.getBounds())){
setHealth(health - 5);
setDx(8);
}
}
if(tempObject.getId() == ObjectId.BounceBlock){
if(getBoundsBot().intersects(tempObject.getBounds())){
setDy(-15);
}
if(getBoundsTop().intersects(tempObject.getBounds())){
setDy(8);
}
if(getBoundsLeft().intersects(tempObject.getBounds())
&& !getBoundsBot().intersects(tempObject.getBounds()) &&
!getBoundsTop().intersects(tempObject.getBounds())){
setDx(-8);
}
if(getBoundsRight().intersects(tempObject.getBounds())
&& !getBoundsBot().intersects(tempObject.getBounds()) &&
!getBoundsTop().intersects(tempObject.getBounds())){
setDx(8);
}
}
if(tempObject.getId() == ObjectId.LevelBottom){
if(getBoundsBot().intersects(tempObject.getBounds())){
Framework.gameState = GameState.GameOver;
}
}
if(tempObject.getId() == ObjectId.End){
if(getBoundsBot().intersects(tempObject.getBounds())){
Framework.gameState = GameState.GameWin;
}
}
}
}
public Rectangle getBoundsBot(){
return new Rectangle((int)x+(width/2)-(width/4), (int)y+(height/2), width/2, height/2);
}
public Rectangle getBoundsTop(){
return new Rectangle((int)x+(width/2-(width/4)), (int)y, width/2, height/2);
}
public Rectangle getBoundsLeft(){
return new Rectangle((int)x+width/2, (int)y+5, width/2, height-10);
}
public Rectangle getBoundsRight(){
return new Rectangle((int)x, (int)y+5, width/2, height-10);
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
}
| true |
1587f2697c2461d3577365a5948bb3473ead83ab | Java | WeiWenTao/HeartJump | /app/src/main/java/com/cucr/myapplication/activity/fuli/FragmentFuLi.java | UTF-8 | 5,943 | 1.84375 | 2 | [] | no_license | package com.cucr.myapplication.activity.fuli;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import com.cucr.myapplication.R;
import com.cucr.myapplication.activity.MessageActivity;
import com.cucr.myapplication.activity.TestWebViewActivity;
import com.cucr.myapplication.adapter.RlVAdapter.FuLiAdapter;
import com.cucr.myapplication.app.MyApplication;
import com.cucr.myapplication.bean.Home.HomeBannerInfo;
import com.cucr.myapplication.bean.fuli.ActiveInfo;
import com.cucr.myapplication.constants.Constans;
import com.cucr.myapplication.constants.HttpContans;
import com.cucr.myapplication.constants.SpConstant;
import com.cucr.myapplication.core.fuLi.FuLiCore;
import com.cucr.myapplication.fragment.BaseFragment;
import com.cucr.myapplication.listener.RequersCallBackListener;
import com.cucr.myapplication.utils.SpUtil;
import com.cucr.myapplication.widget.refresh.swipeRecyclerView.SwipeRecyclerView;
import com.cucr.myapplication.widget.stateLayout.MultiStateView;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.rest.Response;
import java.util.List;
/**
* Created by cucr on 2017/9/1.
*/
public class FragmentFuLi extends BaseFragment implements RequersCallBackListener, SwipeRecyclerView.OnLoadListener {
//活动福利
@ViewInject(R.id.rlv_fuli)
private SwipeRecyclerView rlv_fuli;
//状态布局
@ViewInject(R.id.multiStateView)
private MultiStateView multiStateView;
private Gson mGson;
private FuLiCore mCore;
private int page;
private boolean isRefresh;
private int rows;
private FuLiAdapter activeAdapter;
private Intent mIntent;
@Override
protected void initView(View childView) {
page = 1;
rows = 10;
mGson = new Gson();
mIntent = new Intent(MyApplication.getInstance(), TestWebViewActivity.class);
mCore = new FuLiCore();
ViewUtils.inject(this, childView);
initRLV();
onRefresh();
}
@Override
public int getContentLayoutRes() {
return R.layout.fragment_fuli;
}
//是否需要头部
@Override
protected boolean needHeader() {
return false;
}
private void initRLV() {
mCore.QueryFuLiBanner(this);
rlv_fuli.getRecyclerView().setLayoutManager(new LinearLayoutManager(MyApplication.getInstance()));
activeAdapter = new FuLiAdapter();
rlv_fuli.setAdapter(activeAdapter);
rlv_fuli.setOnLoadListener(this);
activeAdapter.setOnItemListener(new FuLiAdapter.OnItemListener() {
@Override
public void OnItemClick(View view, int activeId, String title, String url,String picUrl) {
//跳转到福利活动详情
if (TextUtils.isEmpty(url)) {
url = HttpContans.IMAGE_HOST + HttpContans.ADDRESS_FULI_ACTIVE_DETIAL
+ "?activeId=" + activeId + "&userId=" + SpUtil.getParam(SpConstant.USER_ID, -1);
}
mIntent.putExtra("url", url);
mIntent.putExtra("activeId", activeId);
mIntent.putExtra("activeTitle", title);
mIntent.putExtra("activePic", picUrl);
startActivity(mIntent);
}
});
}
@Override
public void onRequestSuccess(int what, Response<String> response) {
if (what == Constans.TYPE_TWO) {
ActiveInfo infos = mGson.fromJson(response.get(), ActiveInfo.class);
if (infos.isSuccess()) {
if (isRefresh) {
if (infos.getTotal() == 0) {
multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
} else {
multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
activeAdapter.setDate(infos.getRows());
}
} else {
activeAdapter.addDate(infos.getRows());
}
if (infos.getTotal() <= page * rows) {
rlv_fuli.onNoMore("没有更多了");
} else {
rlv_fuli.complete();
}
}
} else if (what == Constans.TYPE_FORE) {
HomeBannerInfo infos = mGson.fromJson(response.get(), HomeBannerInfo.class);
List<HomeBannerInfo.ObjBean> obj = infos.getObj();
activeAdapter.setBanner(obj);
}
}
@Override
public void onRequestStar(int what) {
}
@Override
public void onRequestError(int what, Response<String> response) {
if (isRefresh && response.getException() instanceof NetworkError) {
multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
}
}
@Override
public void onRequestFinish(int what) {
if (what == Constans.TYPE_TWO) {
if (rlv_fuli.isRefreshing()) {
rlv_fuli.getSwipeRefreshLayout().setRefreshing(false);
}
}
}
//查询福利活动
//刷新
@Override
public void onRefresh() {
isRefresh = true;
page = 1;
rlv_fuli.getSwipeRefreshLayout().setRefreshing(true);
mCore.QueryHuoDong(page, rows, this);
}
//查询福利活动
//加载
@Override
public void onLoadMore() {
isRefresh = false;
page++;
rlv_fuli.onLoadingMore();
mCore.QueryHuoDong(page, rows, this);
}
//跳转到消息界面
@OnClick(R.id.iv_header_msg)
public void goMsg(View view) {
startActivity(new Intent(MyApplication.getInstance(), MessageActivity.class));
}
}
| true |
fae39eb6d62ed04ce27f62be514777371df5ceda | Java | vikram264/java-problem-set | /src/com/examples/io/arrays/RemoveDuplicatesSortedArray.java | UTF-8 | 712 | 3.53125 | 4 | [] | no_license | package com.examples.io.arrays;
import java.util.Arrays;
public class RemoveDuplicatesSortedArray {
public static void main(String[] args) {
RemoveDuplicatesSortedArray removeDuplicatesSortedArray = new RemoveDuplicatesSortedArray();
int [] nums = {1,1,2,2,2,3,3,4,5,5};
removeDuplicatesSortedArray.removeDuplicates(nums);
}
public void removeDuplicates(int[] arr) {
int len = arr.length;
int j = 0;
for(int i = 0 ; i < len-1;i++) {
if(arr[i]!=arr[i+1]) {
arr[j++] = arr[i];
}
}
arr[j++] = arr[len-1];
for(int k =0;k<j;k++) {
System.out.println(arr[k]);
}
}
}
| true |
d694622977cef6866688f9bdf30091d939afeb75 | Java | zia0405/JavaTestng_0519 | /src/test/java/Academy/BeforeTestExample.java | UTF-8 | 510 | 2.390625 | 2 | [] | no_license | package Academy;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class BeforeTestExample {
@BeforeTest
public void initialize() {
System.out.println("Before Test");
}
@Test
public void method1() {
System.out.println("method/Test 1");
}
@Test
public void method2() {
System.out.println("method/Test 2");
}
@AfterTest
public void teardown() {
System.out.println("after Test");
}
}
| true |
ae020ed5fca8fc63b44ae3e42ec4f4a32c5aa2f0 | Java | yaomajor/Rose-Video | /src/main/java/com/javacv/video/vo/Success.java | UTF-8 | 709 | 2.296875 | 2 | [] | no_license | package com.javacv.video.vo;
/**
* @ClassName Success
* @Description TODO
* @Author 86133
* @Date 2020/6/16 10:14
* @Version 1.0
**/
public class Success {
private Boolean success;
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "Success{" +
"success=" + success +
", message='" + message + '\'' +
'}';
}
}
| true |
e2eb0d431dc7d6c6a1dfa1b7fcb29cb391bdc40c | Java | leftpter/Java | /interview/Demo/tst/com/peter/left/interview/epi/chapter8/t1/SolutionTest.java | UTF-8 | 1,902 | 3.171875 | 3 | [] | no_license | package com.peter.left.interview.epi.chapter8.t1;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class SolutionTest
{
private Solution solution = new Solution();
private Node buildList(final int ...values)
{
final Node head = new Node(0);
Node o = head;
for (final int value : values)
{
o.next = new Node(value);
o = o.next;
}
return head.next;
}
private void checkList(final Node head, final int ...values)
{
Node o = head;
for (final int value : values)
{
assertThat(o, notNullValue());
assertThat(o.value, equalTo(value));
o = o.next;
}
assertThat(o, nullValue());
}
@Test
public void testTwoNullArray_itShouldReturn_Null()
{
assertThat(solution.merge(null, null), nullValue());
}
@Test
public void testOneNullArray_itShouldReturn_OtherArray()
{
final Node list = buildList(1, 2, 3, 4, 5, 6, 7, 8);
checkList(solution.merge(list, null), 1, 2, 3, 4, 5, 6, 7, 8);
checkList(solution.merge(null, list), 1, 2, 3, 4, 5, 6, 7, 8);
}
@Test
public void testOneAfterOther_itShouldReturn_expected()
{
final Node list1 = buildList(1, 2, 3, 4, 5, 6, 7, 8);
final Node list2 = buildList(0);
checkList(solution.merge(list1, list2), 0, 1, 2, 3, 4, 5, 6, 7, 8);
}
@Test
public void testDuplicated_itShouldReturn_expected()
{
final Node list1 = buildList(1, 2, 3, 4, 5, 6, 7, 8);
final Node list2 = buildList(1, 2, 3, 4, 5, 6, 7, 8);
checkList(solution.merge(list1, list2), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8);
}
@Test
public void testTwoNormal_itShouldReturn_expected()
{
final Node list1 = buildList(1, 3, 5, 7);
final Node list2 = buildList(2, 4, 6, 8);
checkList(solution.merge(list1, list2), 1, 2, 3, 4, 5, 6, 7, 8);
}
}
| true |
3ffe06c8e1d7ff59235b06c9bc2dfa176553e916 | Java | ZeeshanHayat2020/RecoverDeletedMessages | /app/src/main/java/com/messages/recovery/deleted/messages/recovery/fragments/FragmentBase.java | UTF-8 | 3,140 | 1.992188 | 2 | [] | no_license | package com.messages.recovery.deleted.messages.recovery.fragments;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.fragment.app.Fragment;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.messages.recovery.deleted.messages.recovery.R;
public class FragmentBase extends Fragment {
public InterstitialAd mInterstitialAd;
private AdView adView;
public void setUpStatusBar(int color) {
if (Build.VERSION.SDK_INT >= 21) {
Window window = getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(color);
}
}
public void reqNewInterstitial(Context context) {
mInterstitialAd = new InterstitialAd(context);
mInterstitialAd.setAdUnitId(context.getResources().getString(R.string.interstitial_Id));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
public void requestBanner(FrameLayout bannerContainer) {
adView = new AdView(getContext());
adView.setAdUnitId(getString(R.string.banner_Id));
bannerContainer.addView(adView);
loadBanner();
}
private void loadBanner() {
AdRequest adRequest =
new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = getAdSize();
adView.setAdSize(adSize);
adView.loadAd(adRequest);
}
public AdSize getAdSize() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float widthPixels = outMetrics.widthPixels;
float density = outMetrics.density;
int adWidth = (int) (widthPixels / density);
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(getContext(), adWidth);
}
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnectedOrConnecting())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnectedOrConnecting())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
| true |
d2d161ac2ae6b770ef053c851446fc6ff27535a8 | Java | puneetsinghania/PersonalCode | /KMC/SizeOfBTreeWithoutRecursion.java | UTF-8 | 964 | 3.5 | 4 | [] | no_license | package KMC;
import java.util.LinkedList;
import java.util.Queue;
public class SizeOfBTreeWithoutRecursion {
public static void main(String[] args) {
Node94 root = new Node94(2);
root.left = new Node94(7);
root.right = new Node94(5);
root.left.right = new Node94(6);
root.left.right.left = new Node94(1);
root.left.right.right = new Node94(11);
root.right.right = new Node94(9);
root.right.right.left = new Node94(4);
//important method here
int size = size(root);
System.out.println(size);
}
public static int size(Node94 root) {
int size = 0;
Queue<Node94> q= new LinkedList<>();
q.offer(root);
while(!q.isEmpty())
{
Node94 temp= q.poll();
size++;
if(temp.left!=null)
q.offer(temp.left);
if(temp.right!=null)
q.offer(temp.right);
}
return size;
}
}
class Node94
{
int data;
Node94 left;
Node94 right;
Node94(int data)
{
this.data=data;
this.left=null;
this.right=null;
}
}
| true |
76264dbfaacd089286bb08ca7c97accb79bd9d74 | Java | ankeshsomani/CreditCardFraudDetection | /Code/FraudDetection/fraudanalytics-common/src/main/java/com/masteklabs/frauddetection/common/CommonUtils.java | UTF-8 | 1,467 | 2.578125 | 3 | [] | no_license | package com.masteklabs.frauddetection.common;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.masteklabs.frauddetection.exception.ObjectMappingException;
public class CommonUtils {
/** The Constant OBJECT_MAPPER. */
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/** The Constant DD_MMM_YYYY. */
public static final String YYYYMMDDHHMMSSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public static <T> Object fromJsonUnchecked(String jsonAsString,
Class<T> pojoClass) throws ObjectMappingException {
TimeZone.setDefault(TimeZone.getTimeZone(CommonConstants.TimeZoneConstants.LONDONTIMEZONE));
final DateFormat df = new SimpleDateFormat(YYYYMMDDHHMMSSZ);
df.setTimeZone(TimeZone.getTimeZone(CommonConstants.TimeZoneConstants.UTCTIMEZONE));
OBJECT_MAPPER.setDateFormat(df);
try {
return OBJECT_MAPPER.readValue(jsonAsString, pojoClass);
} catch (Exception e) {
throw new ObjectMappingException(
"Error in fromJsonUnchecked() for class="
+ pojoClass.getName() + " and source="
+ jsonAsString, e);
}
}
public static String getStringFromDateTime(String dateFormat,Long dateTime) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String dtString =sdf.format(dateTime);
return dtString;
}
}
| true |
1616d3bf8187e54aa958688ca550b939286f93e3 | Java | ouhi2008/DubboDemo | /DubboProvider/src/com/unj/dubbotest/provider/CalcService.java | UTF-8 | 110 | 1.640625 | 2 | [] | no_license | package com.unj.dubbotest.provider;
public interface CalcService {
public long factorial (int num) ;
}
| true |
80cff3c0b41e55d3cadf48ff943c5f4fe232f08c | Java | ramtej/Qi4j.Feature.Spatial | /samples/swing/src/main/java/org/qi4j/lib/swing/binding/SwingAdapter.java | UTF-8 | 2,618 | 1.59375 | 2 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | /*
* Copyright 2008 Niclas Hedhman. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.lib.swing.binding;
import java.util.Set;
import javax.swing.JComponent;
import org.qi4j.api.association.Association;
import org.qi4j.api.association.ManyAssociation;
import org.qi4j.api.association.NamedAssociation;
import org.qi4j.api.property.Property;
public interface SwingAdapter
{
Set<Capabilities> canHandle();
void fromSwingToProperty( JComponent component, Property<?> property );
void fromPropertyToSwing( JComponent component, Property<?> property );
void fromSwingToAssociation( JComponent component, Association<?> property );
void fromAssociationToSwing( JComponent component, Association<?> property );
void fromSwingToSetAssociation( JComponent component, ManyAssociation<?> property );
void fromSetAssociationToSwing( JComponent component, ManyAssociation<?> property );
void fromSwingToNamedAssociation( JComponent component, NamedAssociation<?> namedAssociation );
void fromNamedAssociationToSwing( JComponent component, NamedAssociation<?> namedAssociation );
public class Capabilities
{
public final Class<? extends JComponent> component;
public final Class<?> type;
public final boolean property;
public final boolean association;
public final boolean listAssociation;
public final boolean setAssociation;
public final boolean namedAssociation;
public Capabilities( Class<? extends JComponent> component, Class<?> type,
boolean property, boolean association, boolean setAssociation,
boolean listAssociation, boolean namedAssociation )
{
this.component = component;
this.type = type;
this.property = property;
this.association = association;
this.listAssociation = listAssociation;
this.setAssociation = setAssociation;
this.namedAssociation = namedAssociation;
}
}
}
| true |
2ba3887ef277d36559bc669a73a40858af323e04 | Java | idoari/Test_Automation | /src/main/java/pageObjects/OrangeHRM/AdminTopMenu.java | UTF-8 | 592 | 1.90625 | 2 | [] | no_license | package pageObjects.OrangeHRM;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class AdminTopMenu {
@FindBy(how = How.ID, using = "menu_admin_Job")
public WebElement lnk_admin;
@FindBy(how = How.ID, using = "menu_admin_jobCategory")
public WebElement lnk_jobCategory;
@FindBy(how = How.ID, using = "menu_admin_viewPayGrades")
public WebElement lnk_payGrades;
@FindBy(how = How.ID, using = "menu_admin_workShift")
public WebElement lnk_workShifts;
}
| true |
547c2adc157168de0a1a35d5138a5480d195a5a7 | Java | elastic/apm-agent-java | /apm-agent-plugins/apm-aws-sdk/apm-aws-sdk-1-plugin/src/test/java/co/elastic/apm/agent/awssdk/v1/S3ClientIT.java | UTF-8 | 5,709 | 1.625 | 2 | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.0",
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.apm.agent.awssdk.v1;
import co.elastic.apm.agent.awssdk.common.AbstractAwsClientIT;
import co.elastic.apm.agent.impl.transaction.Transaction;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.localstack.LocalStackContainer;
import javax.annotation.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testcontainers.containers.localstack.LocalStackContainer.Service.S3;
public class S3ClientIT extends AbstractAwsClientIT {
private AmazonS3 s3;
@BeforeEach
public void setupClient() {
s3 = AmazonS3Client.builder()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(localstack.getEndpointOverride(LocalStackContainer.Service.S3).toString(), localstack.getRegion()))
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(localstack.getAccessKey(), localstack.getSecretKey())))
.build();
}
@Test
public void testS3Client() {
Transaction transaction = startTestRootTransaction("s3-test");
newTest(() -> s3.createBucket(BUCKET_NAME))
.operationName("CreateBucket")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.execute();
newTest(() -> s3.createBucket(NEW_BUCKET_NAME))
.operationName("CreateBucket")
.entityName(NEW_BUCKET_NAME)
.otelAttribute("aws.s3.bucket", NEW_BUCKET_NAME)
.execute();
newTest(() -> s3.listBuckets())
.operationName("ListBuckets")
.execute();
newTest(() -> s3.putObject(BUCKET_NAME, OBJECT_KEY, "This is some Object content"))
.operationName("PutObject")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.otelAttribute("aws.s3.key", OBJECT_KEY)
.execute();
newTest(() -> s3.listObjects(BUCKET_NAME))
.operationName("ListObjects")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.execute();
newTest(() -> s3.getObject(BUCKET_NAME, OBJECT_KEY))
.operationName("GetObject")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.otelAttribute("aws.s3.key", OBJECT_KEY)
.execute();
newTest(() -> s3.copyObject(BUCKET_NAME, OBJECT_KEY, NEW_BUCKET_NAME, NEW_OBJECT_KEY))
.operationName("CopyObject")
.entityName(NEW_BUCKET_NAME)
.otelAttribute("aws.s3.bucket", NEW_BUCKET_NAME)
.otelAttribute("aws.s3.key", NEW_OBJECT_KEY)
.otelAttribute("aws.s3.copy_source", BUCKET_NAME + "/" + OBJECT_KEY)
.execute();
newTest(() -> {
s3.deleteObject(BUCKET_NAME, OBJECT_KEY);
return null;
})
.operationName("DeleteObject")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.otelAttribute("aws.s3.key", OBJECT_KEY)
.execute();
newTest(() -> {
s3.deleteBucket(BUCKET_NAME);
return null;
})
.operationName("DeleteBucket")
.entityName(BUCKET_NAME)
.otelAttribute("aws.s3.bucket", BUCKET_NAME)
.execute();
newTest(() -> s3.putObject(BUCKET_NAME + "-exception", OBJECT_KEY, "This is some Object content"))
.operationName("PutObject")
.entityName(BUCKET_NAME + "-exception")
.otelAttribute("aws.s3.bucket", BUCKET_NAME + "-exception")
.otelAttribute("aws.s3.key", OBJECT_KEY)
.executeWithException(AmazonS3Exception.class);
assertThat(reporter.getSpans()).hasSize(10);
transaction.deactivate().end();
assertThat(reporter.getNumReportedErrors()).isEqualTo(1);
assertThat(reporter.getFirstError().getException()).isInstanceOf(AmazonS3Exception.class);
}
@Override
protected String awsService() {
return "S3";
}
@Override
protected String type() {
return "storage";
}
@Override
protected String subtype() {
return "s3";
}
@Nullable
@Override
protected String expectedTargetName(@Nullable String entityName) {
return entityName; //entityName is BUCKET_NAME
}
@Override
protected LocalStackContainer.Service localstackService() {
return S3;
}
}
| true |
91f5c2ffc9b2e83b7a6f2d65c3ad0c3a1087bd2f | Java | n1ko12333/A20-BlackBoxTest | /GewichtTest.java | UTF-8 | 761 | 2.1875 | 2 | [] | no_license | package A20;
import org.junit.*;
import weiser.GewichtException;
import weiser.LKW;
import static org.junit.Assert.*;
//git@github.com:n1ko12333/A20-BlackBoxTest.git
public class GewichtTest {
LKW l1;
@Before
public void testBefore(){
l1 = new LKW("KGNW23", 5000, 450, 3);
}
@Test
public void testAufladen1(){
l1.aufladen(1800);
}
@Test(expected=GewichtException.class)
public void testAufladen2(){
l1.aufladen(80000);
}
@Test(expected=GewichtException.class)
public void testEntladen1(){
l1.entladen(1700);
}
@Test(expected=GewichtException.class)
public void testEntladen2(){
l1.entladen(80000);
}
@Test
public void testHoechstZulaessigesGesamtGewicht(){
assertEquals(5000, l1.getHoechstZulaessigesGesamtGewicht());
}
}
| true |
d6dc31a63548dc92ef9d254c193d7559f768e378 | Java | jiachao23/delivery | /delivery-goods/src/main/java/com/delivery/service/IDeliveryCardService.java | UTF-8 | 1,207 | 2.046875 | 2 | [] | no_license | package com.delivery.service;
import java.util.List;
import com.delivery.domain.DeliveryCard;
/**
* 卡劵Service接口
*
* @author jcohy
* @date 2020-09-17
*/
public interface IDeliveryCardService {
/**
* 查询卡劵
*
* @param id 卡劵ID
* @return 卡劵
*/
public DeliveryCard selectDeliveryCardById(Long id);
/**
* 查询卡劵
*
* @param cardNo 卡劵编号
* @return 卡劵
*/
public DeliveryCard selectDeliveryCardByCardNo(String cardNo);
/**
* 查询卡劵列表
*
* @param deliveryCard 卡劵
* @return 卡劵集合
*/
public List<DeliveryCard> selectDeliveryCardList(DeliveryCard deliveryCard);
/**
* 新增卡劵
*
* @param deliveryCard 卡劵
* @return 结果
*/
public int insertDeliveryCard(DeliveryCard deliveryCard);
/**
* 修改卡劵
*
* @param deliveryCard 卡劵
* @return 结果
*/
public int updateDeliveryCard(DeliveryCard deliveryCard);
/**
* 批量删除卡劵
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteDeliveryCardByIds(String ids);
/**
* 删除卡劵信息
*
* @param id 卡劵ID
* @return 结果
*/
public int deleteDeliveryCardById(Long id);
}
| true |
fea9ac1ea9fa0f278691357e4f9b9a3caa71ffd5 | Java | skurochkin/Java_TDD | /src/main/java/p1/Fraction.java | UTF-8 | 1,060 | 3.390625 | 3 | [] | no_license | package p1;
/**
* Created by VKurochkin on 5/5/2016.
*/
public class Fraction {
private final int numerator;
private final int denominator;
public Fraction(int integerValue){
this(integerValue, 1);
}
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction plus(Fraction that){
return new Fraction(this.numerator + that.numerator, denominator);
}
@Override
public String toString(){
return String.format("%d/%d", numerator, denominator);
}
@Override
public boolean equals(Object other){
if(other instanceof Fraction){
Fraction that = (Fraction) other;
return this.numerator == that.numerator
&& this.denominator == that.denominator;
}
return false; // To change body of overridden methods use File | Settings | File
}
@Override
public int hashCode(){
return numerator*19 + denominator;
}
}
| true |
3a8019c86b42e9ae49b459a19b88900f9d92cebf | Java | danysantiago/mod | /app/src/icom5016/modstore/resources/ConstantClass.java | UTF-8 | 5,721 | 1.929688 | 2 | [] | no_license | package icom5016.modstore.resources;
public class ConstantClass {
//FILENAMES Strings
public final static String CATEGORIES_FILE = "categoriesFile.ini";
public final static String USER_FILE = "userFile.ini";
public final static String APP_PREFERENCES_FILE = "appPreferences.ini";
//Categories File Variable Keys
public static class CategoriesFile
{
public final static String ALL_CAT_JSON_KEY = "allCatJsonKey";
public final static String LOAD_BOOLEAN_KEY = "loadBooleanKey";
public final static int ALL_CATEGORIES = -2;
}
//Drawer Lists
public final static String[] DRAWER_GUEST_LIST = new String[]{"Home","Shop By Category" ,"About", "Log in","Register",};
public final static String[] DRAWER_USER_LIST = new String[]{"Home", "Shop By Category", "My Store", "Sell Product", "My Account", "About", "Log Out"};
public final static String[] DRAWER_ADMIN_LIST = new String[]{"Home", "Shop By Category", "My Store", "Sell Product", "My Account", "About", "Log Out", "Admin Menu"};
public static final String[] DRAWER_MYORDERS = new String[]{"Orders", "Bidding", "Selling"};
//LogIn/Out Constant
public final static String USER_IS_LOGIN = "userLogStatus";
public final static String USER_USERNAME_KEY = "userUsername";
public final static String USER_FIRSTNAME_KEY = "userFirstName";
public final static String USER_MIDDLENAME_KEY = "userMiddleName";
public final static String USER_LASTNAME_KEY = "userLastName";
public final static String USER_EMAIL_KEY = "userEmail";
public final static String USER_IS_ADMIN_KEY = "userIsAdmin";
public final static String USER_GUID_KEY = "userGUID";
//Search Constants
public final static String SEARCH_FRAGMENT_BOOL_KEY = "searchBool";
public final static String SEARCH_FRAGMENT_QUERY_KEY = "searchQuery";
//Category Constants
public final static String CATEGORY_LIST_PARENT_KEY = "categoryListParentKey";
//Log-In Register Key
public final static String LOGINREGISTER_FLAG = "loginOrRegister";
//MainActivity FRAGEMENT Key-Value
public final static String MAINACTIVITY_FRAGMENT_KEY = "mainActivityKey";
public final static int MAINACTIVITY_FRAGMENT_CATEGORY = 0;
public final static int MAINACTIVITY_FRAGMENT_MY_ITEMS = 1;
public final static int MAINACTIVITY_FRAGMENT_ITEMS_FOR_SALE = 3;
public final static int MAINACTIVITY_FRAGMENT_ITEMS_SOLD = 4;
//ForgotLogIn
public final static String FORGOT_TAG = "forgotUserNameOrPassword";
public final static String FORGOT_TYPE_KEY = "forgotTypeKey";
public final static int FORGOT_TYPE_USERNAME = 0;
public final static int FORGOT_TYPE_PASSWORD = 1;
//SEARCH FILTER
public final static String SEARCH_FILTER_DIALOG_TAG = "searchFilterDialogTag";
public final static String[] SEARCH_FILTER_SORT = new String[]{"Best Match","Price: Low to High", "Price: High to Low", "Time: ending soonest", "Time: newly listed"};
public static final String[] SEARCH_FILTER_RATING = new String[]{"Any", "5 Stars or More", "4 Stars or More", "3 Stars or More", "2 Stars or More", "1 Stars or More" };
public static final String[] SEARCH_FILTER_CONDITION = new String[]{"Any", "Both", "Buy It Now", "Bid Only"};
public static final String[] SEARCH_FILTER_SORT_URL_PARMS = new String[]{"best", "price_asc", "price_desc", "time_asc", "time_desc"};
public static final String[] SEARCH_FILTER_CONDITION_URL_PARMS = new String[]{"all", "both", "buy", "bid"};
//Dialog Keys
public static final String SEARCH_DIALOG_SORT_KEY = "dialogSortKey";
public static final String SEARCH_DIALOG_CATEGORIES_INDEX_KEY = "dialogCategoriesKey";
public static final String SEARCH_DIALOG_CATEGORIES_ID_KEY = "dialogCategoriesIdKey";
public static final String SEARCH_DIALOG_RATING_KEY = "dialogRatingKey";
public static final String SEARCH_DIALOG_CONDITION_KEY = "dialogConditionKey";
public static final String SEARCH_DIALOG_START_PRICE_KEY = "dialogStartPriceKey";
public static final String SEARCH_DIALOG_END_PRICE_KEY = "dialogEndPriceKey";
//ProductList Constant
public static final String PRODUCT_LIST_CATEGORY_KEY ="productListCategoryKey";
//My Orders Constants
public static final String[] BUYING_SPINNER = new String[]{"All Lists", "Bidding", "Didn't Win"};
public static final String[] SELLING_SPINNER = new String[]{"All Lists", "Active","Sold", "Not Sold"};
public static final String ORDERID_KEY = "orderIdKey";
public static final String SELLING_ACTIVE = "activeKey";
public static final String SELLING_SOLD = "soldKey";
public static final String SELLING_NOTSOLD = "notSoldKey";
public static final String SELLING_TYPE_VIEW_KEY = "sellingTypeViewKey";
public static final String BUYING_BIDDING = "biddingKey";
public static final String BUYING_NOTWIN = "didNotWinKey";
//Credit Card Constant
public static final String[] CREDITCARD_LIST = new String[]{
"Visa", "MasterCard", "AmericanExpress","Discover", "Ebay", "Google Wallet", "Paypal"
};
//Bidding, Selling, Product Keys
public static final String PRODUCT_KEY = "productFragKey";
public static final String PRODUCT_NOTIFICATION_KEY = "productNotificationKey";
//Selling Viewer Activity
public static final String SELLINGVIEWERACTIVITY_ITEM_KEY = "sellingViwerActivityKey";
public final static int SELLINGVIEWERACTIVITY_FRAGMENT_SELL_ITEMS = 2;
//Sell Product Fragment
public static final String PRODUCT_SELL_PROD_KEY = "productObj";
public static final String SELLER_KEY = "sellerId";
public static final String[] CART_DIALOG_OPTIONS = new String[]{"View", "Change Quantity", "Remove"};
//Checkout Vars
public static final String CHECKOUT_TYPE_KEY = "checkoutTypeKey";
public static final int CHECKOUT_TYPE_BUY = 1;
public static final int CHECKOUT_TYPE_CART = 2;
}
| true |
1f985c06b663c67866cf2ce0a82e91323ad3d115 | Java | zhihzhang/leetcode | /src/com/lee/math/Pow50.java | UTF-8 | 1,030 | 3.640625 | 4 | [] | no_license | package com.lee.math;
import java.util.HashMap;
import java.util.Map;
public class Pow50 {
public static void main(String[] args) {
Pow50 obj = new Pow50();
double t = obj.myPow(2, 3);
System.out.println(t);
}
Map<Long, Double> map = new HashMap<Long, Double>();
public double myPow(double x, int n) {
return myPowLong(x, new Long(n));
}
public double myPowLong(double x, long n) {
if (x == 0) {
return 0;
}
if (x == 1) {
return 1;
}
if (x == -1) {
long w = Math.abs(n);
if (w % 2 == 0) {
return 1;
} else {
return -1;
}
}
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if (map.containsKey(n)) {
return map.get(n);
}
if (n > 0) {
double temp = x;
if (n % 2 == 0) {
temp = myPowLong(x, n / 2) * myPowLong(x, n / 2);
} else {
temp = myPowLong(x, n / 2) * myPowLong(x, n / 2) * x;
}
map.put(n, temp);
return temp;
} else {
double temp = x;
long w = -n;
temp = myPowLong(x, w);
return 1 / temp;
}
}
}
| true |
6327ff4f5ef7b21ce0d95d641e0cd52e077ceb42 | Java | shuiyou/cashdesk | /src/test/java/com/weihui/cashdesk/action/PayTypeOpt.java | UTF-8 | 1,736 | 1.90625 | 2 | [] | no_license | package com.weihui.cashdesk.action;
import org.openqa.selenium.WebDriver;
import com.weihui.cashdesk.utils.BasePage;
public class PayTypeOpt {
private WebDriver driver = null;
private BasePage cashdeskHomPage = null;
public PayTypeOpt(WebDriver driver) {
this.driver = driver;
}
public void basicAccountPayType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("普通账户");
}
public void savindPotPayType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("存钱罐账户");
}
public void quickPayType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("快捷支付");
}
public void cardPayType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("绑卡支付");//*[@id="J-tabs"]/li[4]
}
public void onlineBankType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("网银支付");
}
public void bankAccountType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
// cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("银行账户");
}
public void transferPayType() {
cashdeskHomPage = new BasePage(driver, "收银台主页");
//cashdeskHomPage.clickNext("广告窗");
cashdeskHomPage.click("转账");
}
}
| true |
50f6c12b6fa6a93b7c4108f28c92bc3f79736f8e | Java | DanielGibbsNZ/Whiley | /modules/wycs/src/wycs/transforms/ConstraintInline.java | UTF-8 | 9,537 | 2.34375 | 2 | [
"BSD-3-Clause"
] | permissive | package wycs.transforms;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static wybs.lang.SyntaxError.*;
import wybs.lang.Attribute;
import wybs.lang.Builder;
import wybs.lang.NameID;
import wybs.lang.Transform;
import wybs.util.Pair;
import wybs.util.ResolveError;
import wybs.util.Triple;
import wycs.builders.Wyal2WycsBuilder;
import wycs.core.Code;
import wycs.core.SemanticType;
import wycs.core.WycsFile;
import wycs.core.SemanticType.Function;
import wycs.syntax.*;
public class ConstraintInline implements Transform<WycsFile> {
/**
* Determines whether constraint inlining is enabled or not.
*/
private boolean enabled = getEnable();
private final Wyal2WycsBuilder builder;
private String filename;
// ======================================================================
// Constructor(s)
// ======================================================================
public ConstraintInline(Builder builder) {
this.builder = (Wyal2WycsBuilder) builder;
}
// ======================================================================
// Configuration Methods
// ======================================================================
public static String describeEnable() {
return "Enable/disable constraint inlining";
}
public static boolean getEnable() {
return true; // default value
}
public void setEnable(boolean flag) {
this.enabled = flag;
}
// ======================================================================
// Apply Method
// ======================================================================
public void apply(WycsFile wf) {
if(enabled) {
this.filename = wf.filename();
for(WycsFile.Declaration s : wf.declarations()) {
transform(s);
}
}
}
private void transform(WycsFile.Declaration s) {
if(s instanceof WycsFile.Function) {
WycsFile.Function sf = (WycsFile.Function) s;
transform(sf);
} else if(s instanceof WycsFile.Macro) {
WycsFile.Macro sf = (WycsFile.Macro) s;
transform(sf);
} else if(s instanceof WycsFile.Assert) {
transform((WycsFile.Assert)s);
} else {
internalFailure("unknown declaration encountered (" + s + ")",
filename, s);
}
}
private void transform(WycsFile.Function s) {
if(s.constraint != null) {
s.constraint = transformCondition(s.constraint);
}
}
private void transform(WycsFile.Macro s) {
s.condition = transformCondition(s.condition);
}
private void transform(WycsFile.Assert s) {
s.condition = transformCondition(s.condition);
}
private Code transformCondition(Code e) {
if (e instanceof Code.Variable || e instanceof Code.Constant) {
// do nothing
return e;
} else if (e instanceof Code.Unary) {
return transformCondition((Code.Unary)e);
} else if (e instanceof Code.Binary) {
return transformCondition((Code.Binary)e);
} else if (e instanceof Code.Nary) {
return transformCondition((Code.Nary)e);
} else if (e instanceof Code.Quantifier) {
return transformCondition((Code.Quantifier)e);
} else if (e instanceof Code.FunCall) {
return transformCondition((Code.FunCall)e);
} else if (e instanceof Code.Load) {
return transformCondition((Code.Load)e);
} else {
internalFailure("invalid boolean expression encountered (" + e
+ ")", filename, e);
return null;
}
}
private Code transformCondition(Code.Unary e) {
switch(e.opcode) {
case NOT:
return Code.Unary(e.type, e.opcode,
transformCondition(e.operands[0]), e.attributes());
default:
internalFailure("invalid boolean expression encountered (" + e
+ ")", filename, e);
return null;
}
}
private Code transformCondition(Code.Binary e) {
switch (e.opcode) {
case EQ:
case NEQ:
case LT:
case LTEQ:
case IN:
case SUBSET:
case SUBSETEQ: {
ArrayList<Code> assumptions = new ArrayList<Code>();
transformExpression(e, assumptions);
if (assumptions.size() > 0) {
return implies(assumptions,e);
} else {
return e;
}
}
default:
internalFailure("invalid boolean expression encountered (" + e
+ ")", filename, e);
return null;
}
}
private Code transformCondition(Code.Nary e) {
switch(e.opcode) {
case AND:
case OR: {
Code[] e_operands = new Code[e.operands.length];
for(int i=0;i!=e_operands.length;++i) {
e_operands[i] = transformCondition(e.operands[i]);
}
return Code.Nary(e.type, e.opcode, e_operands, e.attributes());
}
default:
internalFailure("invalid boolean expression encountered (" + e
+ ")", filename, e);
return null;
}
}
private Code transformCondition(Code.Quantifier e) {
ArrayList<Code> assumptions = new ArrayList<Code>();
e = Code.Quantifier(e.type, e.opcode,
transformCondition(e.operands[0]), e.types, e.attributes());
if (assumptions.size() > 0) {
return implies(assumptions,e);
} else {
return e;
}
}
private Code transformCondition(Code.FunCall e) {
ArrayList<Code> assumptions = new ArrayList<Code>();
Code r = e;
try {
WycsFile module = builder.getModule(e.nid.module());
// module should not be null if TypePropagation has already passed.
Object d = module.declaration(e.nid.name());
if(d instanceof WycsFile.Function) {
WycsFile.Function fn = (WycsFile.Function) d;
if(fn.constraint != null) {
HashMap<Integer,Code> binding = new HashMap<Integer,Code>();
binding.put(1, e.operands[0]);
binding.put(0, e);
// FIXME: need to instantiate generic types here
assumptions.add(fn.constraint.substitute(binding));
}
} else if(d instanceof WycsFile.Macro){ // must be WycsFile.Macro
WycsFile.Macro m = (WycsFile.Macro) d;
HashMap<Integer,Code> binding = new HashMap<Integer,Code>();
binding.put(0, e.operands[0]);
// FIXME: need to instantiate generic types here
r = m.condition.substitute(binding);
} else {
internalFailure("cannot resolve as function or macro call",
filename, e);
}
} catch(Exception ex) {
internalFailure(ex.getMessage(), filename, e, ex);
}
transformExpression(e.operands[0], assumptions);
if (assumptions.size() > 0) {
return implies(assumptions,e);
} else {
return r;
}
}
private Code transformCondition(Code.Load e) {
return Code.Load(e.type, transformCondition(e.operands[0]), e.index,
e.attributes());
}
private void transformExpression(Code e, ArrayList<Code> constraints) {
if (e instanceof Code.Variable || e instanceof Code.Constant) {
// do nothing
} else if (e instanceof Code.Unary) {
transformExpression((Code.Unary)e,constraints);
} else if (e instanceof Code.Binary) {
transformExpression((Code.Binary)e,constraints);
} else if (e instanceof Code.Nary) {
transformExpression((Code.Nary)e,constraints);
} else if (e instanceof Code.Load) {
transformExpression((Code.Load)e,constraints);
} else if (e instanceof Code.FunCall) {
transformExpression((Code.FunCall)e,constraints);
} else {
internalFailure("invalid expression encountered (" + e
+ ", " + e.getClass().getName() + ")", filename, e);
}
}
private void transformExpression(Code.Unary e, ArrayList<Code> constraints) {
switch (e.opcode) {
case NOT:
case NEG:
case LENGTH:
transformExpression(e.operands[0],constraints);
break;
default:
internalFailure("invalid unary expression encountered (" + e
+ ")", filename, e);
}
}
private void transformExpression(Code.Binary e, ArrayList<Code> constraints) {
switch (e.opcode) {
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
case EQ:
case NEQ:
case LT:
case LTEQ:
case IN:
case SUBSET:
case SUBSETEQ:
transformExpression(e.operands[0],constraints);
transformExpression(e.operands[1],constraints);
break;
default:
internalFailure("invalid binary expression encountered (" + e
+ ")", filename, e);
}
}
private void transformExpression(Code.Nary e, ArrayList<Code> constraints) {
switch(e.opcode) {
case AND:
case OR:
case SET:
case TUPLE: {
Code[] e_operands = e.operands;
for(int i=0;i!=e_operands.length;++i) {
transformExpression(e_operands[i],constraints);
}
break;
}
default:
internalFailure("invalid nary expression encountered (" + e
+ ")", filename, e);
}
}
private void transformExpression(Code.Load e, ArrayList<Code> constraints) {
transformExpression(e.operands[0],constraints);
}
private void transformExpression(Code.FunCall e,
ArrayList<Code> constraints) {
transformExpression(e.operands[0],constraints);
try {
WycsFile module = builder.getModule(e.nid.module());
// module should not be null if TypePropagation has already passed.
WycsFile.Function fn = module.declaration(e.nid.name(),WycsFile.Function.class);
if(fn.constraint != null) {
HashMap<Integer,Code> binding = new HashMap<Integer,Code>();
binding.put(1, e.operands[0]);
binding.put(0, e);
// FIXME: need to instantiate generic types here
constraints.add(fn.constraint.substitute(binding));
}
} catch(Exception ex) {
internalFailure(ex.getMessage(), filename, e, ex);
}
}
private Code implies(ArrayList<Code> assumptions, Code to) {
Code lhs = Code.Nary(SemanticType.Bool, Code.Nary.Op.AND,
assumptions.toArray(new Code[assumptions.size()]));
lhs = Code.Unary(SemanticType.Bool, Code.Op.NOT, lhs);
return Code.Nary(SemanticType.Bool, Code.Op.OR, new Code[] { lhs, to });
}
}
| true |
cde61eb5a8f380128a92575ce0e0659ebce2597d | Java | D-a-r-e-k/Code-Smells-Detection | /Preparation/processed-dataset/data-class_2_144/1.java | UTF-8 | 59 | 1.796875 | 2 | [] | no_license | public double getBranchCount() {
return branchCount;
}
| true |
492cfd9cb9880a93e607479475a1be48a944d82a | Java | narfman0/GDXWorld | /src/main/java/com/blastedstudios/gdxworld/plugin/quest/manifestation/dialog/DialogManifestationPlugin.java | UTF-8 | 787 | 2 | 2 | [
"Beerware"
] | permissive | package com.blastedstudios.gdxworld.plugin.quest.manifestation.dialog;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.blastedstudios.gdxworld.plugin.mode.quest.IQuestComponent.IQuestComponentManifestation;
import com.blastedstudios.gdxworld.world.quest.ICloneable;
@PluginImplementation
public class DialogManifestationPlugin implements IQuestComponentManifestation{
@Override public String getBoxText() {
return "Dialog";
}
@Override public ICloneable getDefault() {
return DialogManifestation.DEFAULT;
}
@Override public Table createTable(Skin skin, Object object) {
return new DialogManifestationTable(skin, (DialogManifestation) object);
}
}
| true |
e72ac0555010babc8b86b77bb1923909fd9e5d61 | Java | tied/ac | /components/core/src/main/java/com/atlassian/plugin/connect/plugin/auth/applinks/ConnectApplinkUtil.java | UTF-8 | 1,128 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.atlassian.plugin.connect.plugin.auth.applinks;
import com.atlassian.applinks.api.ApplicationLink;
import com.atlassian.plugin.connect.modules.beans.AuthenticationType;
import com.atlassian.plugin.connect.plugin.auth.AuthenticationMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
public final class ConnectApplinkUtil {
private static final Logger log = LoggerFactory.getLogger(ConnectApplinkUtil.class);
public static Optional<AuthenticationType> getAuthenticationType(ApplicationLink applink) {
Object authMethod = applink.getProperty(AuthenticationMethod.PROPERTY_NAME);
if (AuthenticationMethod.JWT.toString().equals(authMethod)) {
return Optional.of(AuthenticationType.JWT);
} else if (AuthenticationMethod.NONE.toString().equals(authMethod)) {
return Optional.of(AuthenticationType.NONE);
} else if (authMethod != null) {
log.warn("Unknown authType encountered: " + authMethod);
return Optional.of(AuthenticationType.NONE);
}
return Optional.empty();
}
}
| true |
10fbe0f7e91dbfd98260632c56580bc262cb1b4e | Java | saeed85416009/MyDoctor | /app/src/main/java/com/example/saeed_pc/mydoctor/test/InternetTest/net/Register_push_netTest.java | UTF-8 | 1,480 | 2.265625 | 2 | [] | no_license | package com.example.saeed_pc.mydoctor.test.InternetTest.net;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by saeed on 05/08/2016.
*/
public class Register_push_netTest extends AsyncTask<String, String, String> {
private Context context;
public Register_push_netTest(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... params) {
String s = "";
try {
URL url = new URL("http://192.168.1.2/mySite/register.php?username="+params[0]+"&password="+params[1]+"&role="+params[2]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
s = reader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
}
}
| true |
6fdaec063c751859162fe91af3d891bebff4a349 | Java | moutainhigh/ims-master | /ims-server/ims-server-process/ims-server-process-interface/src/main/java/com/yianju/ims/server/process/service/core/dynamic/DynamicClassLoaderManager.java | UTF-8 | 2,137 | 2.53125 | 3 | [] | no_license | package com.yianju.ims.server.process.service.core.dynamic;
import org.springframework.stereotype.Service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/***
* 动态类加载器管理
*/
@Service
public class DynamicClassLoaderManager {
/**
* classLoader集合
*/
private volatile Map<String, DynamicClassLoader> classLoaderMap = new ConcurrentHashMap<String, DynamicClassLoader>();
private static DynamicClassLoaderManager instance = new DynamicClassLoaderManager();
private DynamicClassLoaderManager(){}
public static DynamicClassLoaderManager getInstance(){
return instance;
}
public Map<String, DynamicClassLoader> getClassLoaderMap() {
return classLoaderMap;
}
/**
* 添加
* @param key
* @param dynamicClassLoader
*/
public void addClassLoader(String key,DynamicClassLoader dynamicClassLoader) {
classLoaderMap.put(key,dynamicClassLoader);
}
/**
* 删除
* @param key
*/
public void removeClassLoader(String key){
DynamicClassLoader dynamicClassLoader = classLoaderMap.get(key);
if(dynamicClassLoader ==null){
return;
}
classLoaderMap.remove(key);
}
/**
* 获取类加载器
* @param key
* @return
*/
public DynamicClassLoader getDynamicClassLoader(String key){
return classLoaderMap.get(key);
}
/**
* 部署
* @param key
* @param jarUrl
*/
public void deploy(String key,String jarUrl) throws MalformedURLException {
try {
DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(new URL[]{new URL("file:" + jarUrl)},this.getClass().getClassLoader());
this.classLoaderMap.put(key,dynamicClassLoader);
} catch (MalformedURLException e) {
e.printStackTrace();
throw e;
}
}
/**
* 解除部署
* @param key
*/
public void unDeploy(String key){
this.classLoaderMap.remove(key);
}
}
| true |
617d3ec54752d1a91385c0b7e0a82ba40717911d | Java | hodalma/icy-steps | /src/modules/Map.java | UTF-8 | 1,721 | 3.15625 | 3 | [] | no_license | package modules;
import java.util.ArrayList;
public class Map
{
private GameController gameController;
private ArrayList<Tile> tiles = new ArrayList<Tile>();
public Map(GameController gc)
{
gameController = gc;
}
public void generateStorm()
{
Logger.LogFunctionCall(this.toString() + "generateStorm was called");
chooseStormTiles();
Logger.LogFunctionReturn("return");
}
public void addTile(int newTileId, Tile newTile)
{
Logger.LogFunctionCall(this.toString() + "addTile was called with param: " + newTile.toString());
for (Tile tile : tiles)
if (tile.getId() == newTile.getId())
return;
tiles.add(newTile);
Logger.LogFunctionReturn("return");
}
private Tile[] chooseStormTiles ()
{
Logger.LogFunctionCall(this.toString() + "chooseStormTiles was called");
Tile[] tiles1 = {};
for (Tile t : tiles) {
t.onStorm();
}
Logger.LogFunctionReturn("return with list of tiles.");
return tiles1;
}
public Tile getTile(int Id)
{
Logger.LogFunctionCall(this.toString() + "getTile was called");
for (Tile tile : tiles)
if (tile.getId() == Id) {
Logger.LogFunctionReturn("return with " + tile.toString());
return tile;
}
Logger.LogFunctionReturn("return with NULL");
return null;
}
public GameController getGameController()
{
Logger.LogFunctionCall(this.toString() + "getGameController was called");
Logger.LogFunctionReturn("return with gameController");
return gameController;
}
}
| true |
aa0092b940d8747c494e719c2c787d1d5f157d5a | Java | ibrowiz/Hospital-Management-System | /src/org/calminfotech/system/boInterface/CategoryBo.java | UTF-8 | 417 | 1.882813 | 2 | [] | no_license | package org.calminfotech.system.boInterface;
import java.util.List;
import org.calminfotech.system.models.GlobalItemCategory;
public interface CategoryBo {
public List<GlobalItemCategory> fetchAll();
public GlobalItemCategory getCategoryById(int id);
public void save(GlobalItemCategory category);
public void update(GlobalItemCategory category);
public void delete(GlobalItemCategory category);
}
| true |
848306fde8f94b868b1a5f8c7493e4a9a3dedd66 | Java | Mario23junior/API-Produtos | /src/main/java/com/project/produto/dto/Client_ProdutoDTO.java | UTF-8 | 625 | 2.03125 | 2 | [] | no_license | package com.project.produto.dto;
public class Client_ProdutoDTO {
private Integer CliId;
private String nome;
private String email;
private String telefone;
public Integer getCliId() {
return CliId;
}
public void setCliId(Integer cliId) {
CliId = cliId;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
| true |
bc6b18a0f1a385bbbafd6b32f248cd951db11f21 | Java | jevonalexis/Comp3275project | /app/src/main/java/com/jevon/studentrollrecorder/pojo/Session.java | UTF-8 | 761 | 2.6875 | 3 | [] | no_license | package com.jevon.studentrollrecorder.pojo;
import java.util.HashMap;
/**
* Created by jevon on 14-Apr-16.
*/
/*Not really a session object. More of an entry of a student for a session. Class necessary for FB
to map data*/
public class Session{
HashMap<String, Attendee> attendees;
String date;
public Session() {
}
public Session(HashMap<String, Attendee> attendees) {
// attendees= new HashMap();
this.attendees = attendees;
this.date = "";
}
public HashMap<String, Attendee> getAttendees() {
return attendees;
}
public void setAttendees(HashMap<String, Attendee> attendees) {
this.attendees = attendees;
}
public String getDate(){
return date;
}
} | true |
b506ae04d670ade323e0a0d1b7953605b757800a | Java | meloveayu/TMNT-1.0 | /app/src/main/java/com/example/tmnt_10/MainFragment.java | UTF-8 | 3,928 | 2.421875 | 2 | [] | no_license | package com.example.tmnt_10;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class MainFragment extends Fragment {
private MediaPlayer mMediaPlayer;
private static String TAG = "MainFragment";
private char flag = 0;
private ImageButton mImageButton;
private TextView mTextView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMediaPlayer = MediaPlayer.create(getActivity(),R.raw.tmnt_theme);
Log.d(TAG,"MF.onCreate() called");
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG,"MF.onCreateView() called");
View v = inflater.inflate(R.layout.fragment_main,container,false);
RadioGroup radioGroup = v.findViewById(R.id.rediobutton_name);
mImageButton = v.findViewById(R.id.turtles_image);
mTextView = v.findViewById(R.id.textview_nameshow);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//i is RadioButton's id
pickTurtle(i);
}
});
mImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickTurtleImage();
}
});
return v;
}
@Override
public void onResume() {
super.onResume();
if (mMediaPlayer != null) {
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
Log.d(TAG,"MF.onResume() called");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG,"MF.onStop() called");
mMediaPlayer.stop();
//改成pause的话,就可以实现续播的功能了
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"MF.onDestroy() called");
mMediaPlayer.release();
}
private void onClickTurtleImage(){
//show full name on TextView
switch (flag){
default:
break;
case 'd':
mTextView.setText(R.string.Don);
break;
case 'l':
mTextView.setText(R.string.Leo);
break;
case 'm':
mTextView.setText(R.string.Mikey);
break;
case 'r':
mTextView.setText(R.string.Raph);
break;
}
}
private void pickTurtle(int i){
//choose turtle by RadioButton
switch (i){
case R.id.radiobutton_leo:
mImageButton.setImageResource(R.drawable.tmntleo);
mTextView.setText("");
flag = 'l';
break;
case R.id.radiobutton_don:
mImageButton.setImageResource(R.drawable.tmntdon);
mTextView.setText("");
flag = 'd';
break;
case R.id.radiobutton_mikey:
mImageButton.setImageResource(R.drawable.tmntmike);
mTextView.setText("");
flag = 'm';
break;
case R.id.radiobutton_raph:
mImageButton.setImageResource(R.drawable.tmntraph);
mTextView.setText("");
flag = 'r';
break;
}
}
}
| true |
38623f0efbee734b007eaa3274c89bbd2e22ed49 | Java | thyjxcf/learn | /base/trunk/src/java/net/zdsoft/eis/frame/action/SortAction.java | UTF-8 | 1,516 | 2.375 | 2 | [] | no_license | package net.zdsoft.eis.frame.action;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.MethodUtils;
public class SortAction<V> extends BaseAction {
private static final long serialVersionUID = 3386001045340454925L;
private String sortColumn;
private String sortType;
protected void sort(List<V> list) {
if (StringUtils.isNotBlank(sortColumn)) {
Collections.sort(list, new Comparator<V>() {
@Override
public int compare(V o1, V o2) {
int ret = 0;
try {
String methodName = "get"
+ sortColumn.substring(0, 1).toUpperCase()
+ sortColumn.substring(1);
String c1 = String.valueOf(MethodUtils
.invokeExactMethod(o1, methodName, null));
String c2 = String.valueOf(MethodUtils
.invokeExactMethod(o2, methodName, null));
if (sortType.equals("1"))
ret = c1.compareTo(c2);
else
ret = c2.compareTo(c1);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return ret;
}
});
}
}
public String getSortColumn() {
return sortColumn;
}
public void setSortColumn(String sortColumn) {
this.sortColumn = sortColumn;
}
public String getSortType() {
return sortType;
}
public void setSortType(String sortType) {
this.sortType = sortType;
}
}
| true |
154267869f372f68438be4334a67d2cd6785cc78 | Java | hyunhyukCho/VOLA | /vitcon_web/src/main/java/com/vitcon/core/password/Password.java | UTF-8 | 2,709 | 3.40625 | 3 | [] | no_license | package com.vitcon.core.password;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Password {
/**
* <p>
* 입력한 데이터(바이트 배열)을 SHA1 알고리즘으로 처리하여 해쉬값을 도출한다.
* </p>
*
* <pre>
* getHash([0x68, 0x61, 0x6e]) = [0x4f, 0xf6, 0x15, 0x25, 0x34, 0x69, 0x98, 0x99, 0x32, 0x53, 0x2e, 0x92, 0x60, 0x06, 0xae, 0x5c, 0x99, 0x5e, 0x5d, 0xd6]
* </pre>
*
* @param input 입력 데이터(<code>null</code>이면 안된다.)
* @return 해쉬값
*/
public static byte[] getHash(byte[] input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
return md.digest(input);
} catch (NoSuchAlgorithmException e) {
// 일어날 경우가 없다고 보지만 만약을 위해 Exception 발생
throw new RuntimeException("SHA1" + " Algorithm Not Found", e);
}
}
private static String toHexString(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuffer result = new StringBuffer();
for (byte b : bytes) {
result.append(Integer.toString((b & 0xF0) >> 4, 16));
result.append(Integer.toString(b & 0x0F, 16));
}
return result.toString();
}
/**
* <p>
* MySQL 의 PASSWORD() 함수.
* </p>
*
* <pre>
* MySqlFunction.password(null) = null
* MySqlFunction.password("mypassword".getBytes()) = "*FABE5482D5AADF36D028AC443D117BE1180B9725"
* </pre>
*
* @param input
* @return
*/
public static String password(byte[] input) {
byte[] digest = null;
// Stage 1
digest = getHash(input);
// Stage 2
digest = getHash(digest);
StringBuilder sb = new StringBuilder(1 + digest.length);
sb.append("*");
sb.append(toHexString(digest).toUpperCase());
return sb.toString();
}
/**
* <p>
* MySQL 의 PASSWORD() 함수.
* </p>
*
* <pre>
* MySqlFunction.password(null) = null
* MySqlFunction.password("mypassword") = "*FABE5482D5AADF36D028AC443D117BE1180B9725"
* </pre>
*
* @param input
* @return
* @throws NoSuchAlgorithmException
*/
public static String password(String input) {
if (input == null) {
return null;
}
return password(input.getBytes());
}
/**
* <p>
* MySQL 의 PASSWORD() 함수.
* </p>
*
* <pre>
* MySqlFunction.password(null, *) = null
* MySqlFunction.password("mypassword", "ISO-8859-1") = "*FABE5482D5AADF36D028AC443D117BE1180B9725"
* </pre>
*
* @param input
* @param charsetName
* @return
* @throws UnsupportedEncodingException
*/
public static String password(String input, String charsetName) throws UnsupportedEncodingException {
if (input == null) {
return null;
}
return password(input.getBytes(charsetName));
}
} | true |
d71738c4697d5b189b6ac242e76c33aaa982c957 | Java | lanshanxiao/Head-First-Design-Pattern | /1.策略模式(StrategyPattern)讲解代码/简单实现/Duck.java | GB18030 | 967 | 3.78125 | 4 | [
"Apache-2.0"
] | permissive | public abstract class Duck{//Ѽ
/*ӿڶ*/
FlyBehavior flyBehavior;//
QuackBehavior quackBehavior;//ɽ
public Duck(){
}
//ȥ
/*public void fly(){//Ϊ
System.out.println("I'm flying!");
}
public void quack(){//Ϊɽ
System.out.println("Gua Gua!");
}*/
/*ǽDuckΪίиӿڶʵ*/
public void performFly(){//fly()ίиflyBehaviorʵ
flyBehavior.fly();
}
public void performQuack(){//quack()ίиquackBehaviorʵ
quackBehavior.quack();
}
/*·Զ̬ĸı仯*/
public void setFlyBehavior(FlyBehavior fb){
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb){
quackBehavior = qb;
}
public void swim(){//ΪӾ
System.out.println("I'm swimming!");
}
} | true |
9da199e286324452b8a8a3a348b30840b0d6de9d | Java | kyych/EMPMANAGER | /src/front/MenuBar.java | UTF-8 | 2,477 | 2.734375 | 3 | [] | no_license | package front;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class MenuBar extends JMenuBar {
private final JFileChooser fileChooser;
private MainViewController mainViewController;
public MenuBar() {
fileChooser = new JFileChooser();
JMenuItem openFile = new JMenuItem("Open File");
JMenuItem addDataFromFile = new JMenuItem("Add Data");
JMenuItem saveFile = new JMenuItem("Save");
addDataFromFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
addDataFromFile.addActionListener(e -> {
int code = fileChooser.showOpenDialog(this.getRootPane().getContentPane());
if (code == JFileChooser.APPROVE_OPTION) {
String path = fileChooser.getSelectedFile().getPath();
mainViewController.readDataFromFile(path);
} else {
JOptionPane.showMessageDialog(this.getRootPane().getContentPane(), "U have to choose data file!");
}
});
openFile.addActionListener(e -> {
int code = fileChooser.showOpenDialog(this.getRootPane().getContentPane());
if (code == JFileChooser.APPROVE_OPTION) {
String path = fileChooser.getSelectedFile().getPath();
mainViewController.replaceDataFromFile(path);
} else {
JOptionPane.showMessageDialog(this.getRootPane().getContentPane(), "U have to choose data file!");
}
});
saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
saveFile.addActionListener(e -> {
int code = fileChooser.showOpenDialog(this.getRootPane().getContentPane());
if (code == JFileChooser.APPROVE_OPTION) {
String path = fileChooser.getSelectedFile().getPath();
mainViewController.saveDataToFile(path);
} else {
JOptionPane.showMessageDialog(this.getRootPane().getContentPane(), "U have to choose data file!");
}
});
JMenu menu = new JMenu("File");
menu.add(openFile);
menu.addSeparator();
menu.add(addDataFromFile);
menu.addSeparator();
menu.add(saveFile);
this.add(menu);
}
public void setController(MainViewController mainViewController) {
this.mainViewController = mainViewController;
}
} | true |
4a9a4b18a61b8bcba4ad8e83f0c280478305593f | Java | sushiomsky/example-lock-app | /app/src/main/java/com/lockapp/fragments/FragmentUtils.java | UTF-8 | 2,684 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.lockapp.fragments;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lockapp.MainActivity;
import com.lockapp.R;
/**
* Created by Andrei on 30/01/2015.
*/
public abstract class FragmentUtils {
public static final String SHARED_ELEMENT_NAME = "button";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mLockDeviceComponent;
private LocalBroadcastManager mLocalBroadcastManager;
private Handler mHandler = new Handler();
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void putFragment (Activity activity, Fragment fragment) {
activity.getFragmentManager().beginTransaction()
.replace(R.id.content, fragment)
.commit();
}
public static void putFragment (final FragmentActivity activity, android.support.v4.app.Fragment fragment){
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment)
.commit();
}
public void init(Activity activity) {
mDevicePolicyManager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
mLockDeviceComponent = new ComponentName(activity, MainActivity.LockAppDeviceAdmin.class);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(activity);
}
public DevicePolicyManager getPolicyManager() {
return mDevicePolicyManager;
}
public ComponentName getLockName() {
return mLockDeviceComponent;
}
public void swapFragmentDelayed() {
mHandler.postDelayed(new Runnable(){
public void run() {
swapFragment();
}
},555);
}
public LocalBroadcastManager getBroadcastManager() {
return mLocalBroadcastManager;
}
public abstract View onCreateView(Activity activity, LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState);
public abstract void onResume();
public abstract void onPause();
public abstract void swapFragment();
public abstract View getSharedElement();
public abstract void checkStatus();
}
| true |
f4efd88b1cc94c6e3b3c1eddb8faeda7f298b3c6 | Java | georgesafta/Metro | /src/classes/Adresa.java | UTF-8 | 294 | 2.78125 | 3 | [] | no_license | package classes;
public class Adresa {
private String strada;
private String numar;
public Adresa(String strada, String numar) {
super();
this.strada = strada;
this.numar = numar;
}
public String getStrada() {
return strada;
}
public String getNumar() {
return numar;
}
}
| true |
8256aff84eac0b25d87728c97b03c61926f0f192 | Java | WJimbo/TeamWorker-Android | /app/src/main/java/cn/chestnut/mvvm/teamworker/module/checkattendance/PhotoActivity.java | UTF-8 | 1,483 | 1.914063 | 2 | [] | no_license | package cn.chestnut.mvvm.teamworker.module.checkattendance;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import cn.chestnut.mvvm.teamworker.R;
import cn.chestnut.mvvm.teamworker.databinding.ActivityPhoneDirectoryBinding;
import cn.chestnut.mvvm.teamworker.databinding.ActivityPhotoBinding;
import cn.chestnut.mvvm.teamworker.http.HttpUrls;
import cn.chestnut.mvvm.teamworker.main.common.BaseActivity;
import cn.chestnut.mvvm.teamworker.utils.CommonUtil;
import cn.chestnut.mvvm.teamworker.utils.GlideLoader;
/**
* Copyright (c) 2018, Chestnut All rights reserved
* Author: Chestnut
* CreateTime:at 2018/4/23 16:17:42
* Description:
* Email: xiaoting233zhang@126.com
*/
public class PhotoActivity extends BaseActivity {
private ActivityPhotoBinding binding;
private float screenWidth;
@Override
protected void setBaseTitle(TextView titleView) {
titleView.setText("图片");
}
@Override
protected void addContainerView(ViewGroup viewGroup, LayoutInflater inflater) {
binding = DataBindingUtil.inflate(inflater, R.layout.activity_photo, viewGroup, true);
}
@Override
protected void initData() {
screenWidth = CommonUtil.getScreenWidth(this);
}
@Override
protected void initView() {
GlideLoader.displayImage(this, HttpUrls.GET_PHOTO + getIntent().getStringExtra("photoUri"), binding.ivPhoto);
}
}
| true |
7a8c4aa7c8327ede0203efd4814447e0cc42be61 | Java | GoldenMoonByr/AiAacdemy | /DeptManager/src/manager/DeptManager.java | UTF-8 | 3,626 | 2.96875 | 3 | [] | no_license | package manager;
import java.sql.Connection;
import java.sql.SQLException;
public class DeptManager {
DeptDao dao = new DeptDao();
public void deptEdit() {
Connection conn = null;
try {
conn = ConnectionProvider.getConnetion();
conn.setAutoCommit(false); // 자동 커밋 : 기본값은 true;
// 수정하고자 하는 데이터 유무 확인 -> 사용자로부터 데이터 받아서 전달
System.out.println("수정하고자 하는 부서 이름 :");
Main.sc.nextLine();
String searchName = Main.sc.nextLine();
// 1. 수정하고자 하는 데이터 유무 확인
int rowCnt = dao.deptSearchCount(searchName, conn);
if (rowCnt > 0) {
Dept dept = dao.deptSearchName(searchName, conn);
if (dept == null) {
System.out.println("찾으시는 이름의 정보가 존재하지 않습니다.");
return;
}
// 사용자 입력정보 변수
System.out.println("부서 정보를 입력해주세요.");
System.out.println("부서 번호 : " + dept.getDeptno());
System.out.println("부서 번호는 수정되지 않습니다.");
System.out.println("부서 이름 :" + dept.getDname());
System.out.println(">>");
String dname = Main.sc.nextLine();
System.out.println("지역 이름 :" + dept.getLoc());
System.out.println(">>");
String loc = Main.sc.nextLine();
// 공백 입력에 대한 예외처리가 있어야 하나 이번 버전에서는 모두 잘 입력 된 것으로 처리.
Dept newDept = new Dept(dept.getDeptno(), dname, loc);
int resultCnt = dao.deptEdit(newDept, conn);
if (resultCnt > 0) {
System.out.println("정상적으로 수정 되었습니다.");
System.out.println(resultCnt + "행이 수정되었습니다.");
} else {
System.out.println("수정이 되지 않았습니다. 확인 후 재시도 해주세요.");
}
} else {
System.out.println("찾으시는 이름의 정보가 존재하지 않ㅅ습니다.");
}
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deptInsert() {
System.out.println("부서 정보를 입력해주세요.");
System.out.println("부서 번호 :");
int deptno = Main.sc.nextInt();
System.out.println("부서 이름 :");
String dname = Main.sc.nextLine();
System.out.println("부서 위치 :");
String loc = Main.sc.nextLine();
Dept dept = new Dept(deptno, dname, loc);
int resultCnt = dao.deptInsert(dept);
if (resultCnt > 0 ) {
System.out.println("정상적으로 입력 되었습니다.");
System.out.println(resultCnt + "행이 입력 되었습니다.");
}else {
System.out.println("입력이 되지 않았습니다. 확인 후 재시도해주세요.");
}
}
public void deptDelete() {
System.out.println("삭제하고자 하는 부서이름 :");
Main.sc.nextLine();
String searchName=Main.sc.nextLine();
int resultCnt = dao.deptDelete(searchName);
}
public void deptSearch() {
System.out.println("검색하고자 하는 부서이름 :");
Main.sc.nextLine();
String searchName = Main.sc.nextLine();
List<Dept> list = dao.deptSearch(searchName);
System.out.println("검색 결과");
System.out.println("=======================");
for(Dept d : list) {
System.out.printf("%5s", d.getDeptno() + "\t");
System.out.printf("%12s",d.getDname()+ "\t");
System.out.printf("%12s", d.getLoc()+"\t");
}
System.out.println("=======================");
}
public void deptList() {
List<Dept> deptList = dao.deptList();
}
} | true |