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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fe51ecfbdc3249123ca4c5c4457c12810bf48ef5
|
Java
|
sukhdeepsingh9/ChatApp
|
/ChatApp/src/client/Listener.java
|
UTF-8
| 1,465
| 2.703125
| 3
|
[] |
no_license
|
package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import ui.LetsStart;
import ui.MainFrame;
public class Listener extends Thread
{
Socket socket;
DataInputStream streamIn;
DataOutputStream streamOut;
Client client;
public Listener(Client client)
{
try {
this.client=client;
socket=client.getSocket();
//socket=new Socket(client.getIp(),22222);
System.out.println("Connected");
streamIn=new DataInputStream(socket.getInputStream());
streamOut=new DataOutputStream(socket.getOutputStream());
start();
} catch (IOException e) {
System.out.println("Error connecting "+client.getIp()+" :22222");
e.printStackTrace();
}
}
public void run()
{
while(true)
{
try {
System.out.println("listening");
System.out.println(client.getSocket());
String msg=streamIn.readUTF();
System.out.println("reciving message");
LetsStart.messageRecieved(msg, client);
} catch (IOException e) {
System.out.println(client.getIp()+" : disconnected");
MainFrame.removeUser(client);
try {
client.getStreamIn().close();
client.getSocket().close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}
| true
|
8ec20d1f39b2fcaaa2af1b8279e4648a628d23b2
|
Java
|
dincolonur/Spring_Projects
|
/Spring-Simple-DB/src/main/java/com/onur/spring/implementation/UserImpl.java
|
UTF-8
| 968
| 2.140625
| 2
|
[] |
no_license
|
package com.onur.spring.implementation;
import com.onur.spring.dao.TicketDao;
import com.onur.spring.dao.UserDao;
import com.onur.spring.domain.User;
import com.onur.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class UserImpl implements UserService {
@Autowired private UserDao userDao;
@Autowired private TicketDao ticketDao;
@Override
public User getUserByEmail(String email) {
return userDao.getUserByEmail(email);
}
@Override
public User getById(Long id) {
return userDao.getUserById(id);
}
@Override
public boolean saveUser(User user) {
return userDao.insertUser(user);
}
@Override
public boolean removeUser(User user) {
return userDao.removeUser(user) && ticketDao.removeTickets(user.getTickets());
}
@Override
public Set<User> getAll() {
return userDao.getAll();
}
}
| true
|
62adf8a2c3f20bf2ce1a48b349a06a2005e96f23
|
Java
|
natlehmann/catalogo-con-newsletter
|
/src/main/java/ar/com/almaDeJazmin/website/domain/TextFileFormat.java
|
UTF-8
| 648
| 2.515625
| 3
|
[] |
no_license
|
package ar.com.almaDeJazmin.website.domain;
public enum TextFileFormat {
TXT ("text/plain"),
PDF ("application/pdf"),
DOC ("application/msword"),
DOCX ("document");
private String formatName;
private TextFileFormat(String formatName) {
this.formatName = formatName;
}
public String getFormatName() {
return formatName;
}
public static TextFileFormat getFromString(String format) {
TextFileFormat result = null;
for (TextFileFormat fileFormat : TextFileFormat.values()) {
if (format.toLowerCase().contains(fileFormat.formatName.toLowerCase())) {
result = fileFormat;
}
}
return result;
}
}
| true
|
cf6752e94d03a42ea806cf0cc9ceae941eadf0fc
|
Java
|
venwhere/amrProject
|
/amrProject/src/main/java/com/sun/amr/action/AdminAction.java
|
UTF-8
| 4,559
| 2.4375
| 2
|
[] |
no_license
|
package com.sun.amr.action;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.sun.amr.adapter.AbstractActionAdapter;
import com.sun.amr.service.IAdminService;
import com.sun.amr.vo.Dept;
import com.sun.amr.vo.Emp;
import com.sun.amr.vo.Level;
import com.sun.util.MD5Code;
import com.sun.util.SplitUtil;
@Controller
@RequestMapping("pages/admin/*")
public class AdminAction extends AbstractActionAdapter {
@Resource
private IAdminService adminService;
@RequestMapping("checkEid")
public void checkEid(Integer eid,HttpServletResponse response) {
try {
super.print(response, this.adminService.checkEid(eid));
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping("addPre")
public ModelAndView addPre(HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
if (super.isAuth(1, request)) {// 对权限1进行验证
try {
Map<String, Object> map = this.adminService.addPre();
// 保存的是雇员的级别信息
mav.addObject("allLevels", map.get("allLevels"));
} catch (Exception e) {
e.printStackTrace();
}
// 跳转到/pages/admin/admin_add.jsp
mav.setViewName(super.getMsg("admin.add.page"));
}else {
//如果没有权限跳转到错误页面
mav.setViewName(super.getMsg("errors"));
}
return mav;
}
@RequestMapping("add")
public ModelAndView add(Emp vo,MultipartFile pic,HttpServletRequest request) {
ModelAndView mav=new ModelAndView();
if(super.isAuth(2, request)) {//验证当前用户是否有权限
//spring-mvc可以自动赋值不用这样赋值
vo.setDept(new Dept());
vo.getDept().setDid(1);//指定雇员所在部门为1号部门
vo.setLevel(new Level());
vo.getLevel().setLid(Integer.parseInt(request.getParameter("level.lid")));
vo.setHeid(super.getEid(request));//设置操作人员的编号
vo.setPassword(new MD5Code().getMD5ofStr(vo.getPassword()));//密码的加密处理
vo.setAflag(2);
vo.setPhoto(super.createSingleFileName(pic));//图片的名称需要保存到数据库
System.out.println(pic);
System.out.println(vo.getPhoto());
try {
if(this.adminService.add(vo, super.getEid(request))) {//调用业务层的方法进行数据的增加操作
super.saveUploadFile(pic, vo.getPhoto(), request);//添加成功则将照片保存到服务器
super.setMsgAndUrl("vo.add.success", "admin.add.action", mav);//定义提示信息和跳转路径
}else {
super.setMsgAndUrl("vo.add.failure", "admin.add.action", mav);
}
} catch (Exception e) {
super.setMsgAndUrl("vo.add.failure", "admin.add.action", mav);
e.printStackTrace();
}
mav.setViewName(super.getMsg("forward.page"));
}else {
mav.setViewName(super.getMsg("errors.page"));
}
return mav;
}
@RequestMapping("list")
public ModelAndView list(HttpServletRequest request){
ModelAndView mav=new ModelAndView();
if(super.isAuth(3, request)) {//权限验证
//创建一个分页参数处理的工具类,this表示当前的对象,传递这个的目的是取得子类中给出一些参数
SplitUtil split=new SplitUtil(this);
//调用父类的方法进行客户端传递参数的处理,request负责在父类中取得参数,split在父类中处理参数
super.handleSplit(request, split);
try {
Map<String, Object> map=this.adminService.list(super.getEid(request),
split.getColumn(),split.getKeyword(),
split.getCurrentPage(), split.getLineSize());
//保存的是查看管理员的路径,需要在分页的时候使用到(比如上一页)
map.put("url", super.getMsg("admin.list.action"));
super.setPageMsg(map, mav);
} catch (Exception e) {
e.printStackTrace();
}
//跳转到管理员的列表页面(/pages/admin/admin_list.jsp)
mav.setViewName(super.getMsg("admin.list.page"));
}else {
mav.setViewName(super.getMsg("error.page"));
}
return mav;
}
@Override
public String getColumnData() {
return "雇员姓名:name|雇员编号:eid|雇员电话:phone";
}
@Override
public String getFlag() {
return "管理员";
}
@Override
public String getSaveFileDiv() {
return "/upload/emp/";
}
@Override
public String getDefaultColumn() {
return "name";
}
}
| true
|
a7d56f5041e2cf74533037c195b7a92ae81ff6b4
|
Java
|
OlgaMarkarova/BC-14-Morning.Java
|
/src/day25/HW23.java
|
UTF-8
| 1,989
| 3.328125
| 3
|
[] |
no_license
|
package day25;
public class HW23 {
public static void main(String[] args) {
System.out.println(repeatSeparator("Word", "X", 3));// → "WordXWordXWord"
System.out.println(repeatSeparator("This", "And", 2));// → "ThisAndThis"
System.out.println(repeatSeparator("This", "And", 1));// → "This"
System.out.println(getSandwich("breadjambread"));// → "jam"
System.out.println(getSandwich("xxbreadjambreadyy"));// → "jam"
System.out.println(getSandwich("xxbreadyy"));// ""
System.out.println(zipZap("zipXzap"));// → "zpXzp"
System.out.println(zipZap("zopzop"));// → "zpzp"
System.out.println(zipZap("zzzopzop"));// → "zzzpzp"
}
private static String zipZap(String str) {
String output = str;
for (int i = 1; i < output.length() - 1; i++) {
if (output.charAt(i - 1) == 'z' && output.charAt(i + 1) == 'p') {
output = output.substring(0, i) + output.substring(i + 1);
}
}
return output;
}
private static String zipZapRegX(String str) {
String output = "";
output = str.replaceAll("z.p", "zp");
return output;
}
private static String repeatSeparator(String str1, String str2, int numer) {
String outputStr = "";
for (int i = 0; i < numer - 1; i++) {
outputStr += str1 + str2;
}
outputStr += str1;
return outputStr;
}
private static String getSandwich(String str) {
String output = "";
int indexStart = 0;
String bread = "bread";
indexStart = str.indexOf(bread);
// System.out.println("indexStart= "+str.indexOf(bread));
int indexEnd = str.lastIndexOf(bread);
//System.out.println("indexend= "+indexEnd);
if (indexEnd != indexStart) {
output = str.substring(indexStart + bread.length(), indexEnd);
}
return output;
}
}
| true
|
f72586f902b77f99553ecc052f433d9b2064e5d1
|
Java
|
shinow/tjec
|
/src/com/freework/base/formula/customMethod/ConversionDay.java
|
UTF-8
| 2,206
| 2.59375
| 3
|
[] |
no_license
|
package com.freework.base.formula.customMethod;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
/**
* conversionDay{yyyymmdd,var,aaa}
* @author Administrator
*
*/
public class ConversionDay implements CustomMethod {
/**
*
*/
private static final long serialVersionUID = 7379151339989605047L;
SimpleDateFormat dateFormatter =null;
boolean isVariable=true;
boolean isNowDate=false;
String value=null;
public ConversionDay(){}
public ConversionDay(String[] info) {
if(info.length<2){
isNowDate=true;
return;
}
if(!info[0].equals(""))
dateFormatter= new SimpleDateFormat(info[0]);
value=info[1];
if(value.length()>2){
if(value.charAt(0)=='\''&&value.charAt(value.length()-1)=='\''){
value=value.substring(1, value.length()-1);
isVariable=false;
}
}else if(value.equals("")){
isNowDate=true;
}
}
public String getMethodName() {
return "toDay";
}
public BigDecimal getValue(Object obj1) {
Date date=null;
if(isNowDate){
date=new Date();
}else
if(isVariable){
Object obj=null;
if(obj1 instanceof Map){
obj= ((Map)obj1).get(value);
}else{
try {
obj= PropertyUtils.getProperty(obj1,(String) value);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(obj instanceof Date)
date=(Date) obj;
else
try {
date=dateFormatter.parse(obj.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}else{
try {
date=dateFormatter.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
return new BigDecimal (date.getTime()/1000/ 60 / 60 / 24);
}
public CustomMethod newCustomMethod(String[] info) {
return new ConversionDay(info);
}
}
| true
|
694f306aa054d8a6d161fe6ac98e86cf5093c863
|
Java
|
jwoods02/uni-clinical-questionnaires
|
/src/main/java/com/nsa/clinical/entities/Option.java
|
UTF-8
| 893
| 2.265625
| 2
|
[] |
no_license
|
package com.nsa.clinical.entities;
import lombok.Data;
import javax.persistence.*;
/**
* Created by c1571078 on 17/11/2017.
*/
@Data
@Entity
@Table(name = "options")
public class Option {
@Id
@Column(name = "option_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long optionId;
@Column(name = "option_description")
private String optionDescription;
@Column(name = "option_order")
private Integer optionOrder;
@ManyToOne
@JoinColumn(name="question_id",referencedColumnName="question_id")
private Question question;
public Option(String optionDescription, Integer optionOrder, Question question) {
this.optionDescription = optionDescription;
this.optionOrder = optionOrder;
this.question = question;
}
public Option() {
}
public String toString() {
return "";
}
}
| true
|
68f56574b6bd4620087154538dccf6e52baa7dc0
|
Java
|
mumuzsl/dpta
|
/dpta-web/src/main/java/com/cqjtu/dpta/web/security/UserCheckException.java
|
UTF-8
| 308
| 1.875
| 2
|
[] |
no_license
|
package com.cqjtu.dpta.web.security;
import com.cqjtu.dpta.common.exception.BaseException;
/**
* author: mumu
* date: 2021/4/26
*/
public class UserCheckException extends BaseException {
public UserCheckException() {}
public UserCheckException(String message) {
super(message);
}
}
| true
|
0959fef0c01a2db7a59e2a9c2282ccd565ad7218
|
Java
|
javadeveloperandlearning/mistia
|
/mistia-ejb/src/main/java/pe/com/eb/commons/TripleDES.java
|
UTF-8
| 2,968
| 2.953125
| 3
|
[] |
no_license
|
package pe.com.eb.commons;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDES {
private static Cipher _ecipher;
private static Cipher _dcipher;
private static String semilla = "ABCDEABCDEABCDEABCDE";
public static String encrypt(final String string) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(semilla.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec params = new IvParameterSpec(new byte[8]);
_ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
_ecipher.init(Cipher.ENCRYPT_MODE, key, params);
// Encode the string into bytes using utf-8
final byte[] bytes = string.getBytes("UTF-8");
// Encrypt
final byte[] enc = _ecipher.doFinal(bytes);
// Encode bytes to base64 to get a string
return bytesToHex(enc);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public static String decrypt(final String str) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(semilla.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec params = new IvParameterSpec(new byte[8]);
_dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
_dcipher.init(Cipher.DECRYPT_MODE, key, params);
// Decode base64 to get bytes
final byte[] dec = hexToBytes(str);
// Decrypt
final byte[] utf8 = _dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (final Exception e) {
return null;
}
}
private static String bytesToHex(final byte[] bytes) {
final StringBuilder buf = new StringBuilder(bytes.length * 2);
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
buf.append("0");
}
buf.append(hex);
}
return buf.toString();
}
private static byte[] hexToBytes(final String hex) {
final byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
}
| true
|
12912fe545dde0f235f47077b92d022e33847e88
|
Java
|
nathantippy/GreenLightning
|
/greenlightning/src/main/java/com/javanut/gl/api/HTTPResponseListener.java
|
UTF-8
| 318
| 1.773438
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package com.javanut.gl.api;
import com.javanut.gl.impl.http.server.HTTPResponseListenerBase;
/**
* Functional interface for HTTP responses returned from outgoing
* HTTP requests.
*
* @author Nathan Tippy
*/
@FunctionalInterface
public interface HTTPResponseListener extends Behavior, HTTPResponseListenerBase {
}
| true
|
4382c60d2585a5c979dd065ad6723604a5a25728
|
Java
|
sroebuck/datahelix
|
/orchestrator/src/test/java/com/scottlogic/deg/orchestrator/cucumber/testframework/utils/InMemoryOutputTarget.java
|
UTF-8
| 1,604
| 2.46875
| 2
|
[
"Apache-2.0",
"CC0-1.0"
] |
permissive
|
package com.scottlogic.deg.orchestrator.cucumber.testframework.utils;
import com.scottlogic.deg.common.profile.ProfileFields;
import com.scottlogic.deg.common.output.GeneratedObject;
import com.scottlogic.deg.output.writer.DataSetWriter;
import com.scottlogic.deg.output.outputtarget.SingleDatasetOutputTarget;
import java.util.List;
import java.util.stream.Collectors;
/**
* Defines an output target which stores the output data into the test state.
*/
public class InMemoryOutputTarget implements SingleDatasetOutputTarget {
private final CucumberTestState testState;
InMemoryOutputTarget(CucumberTestState testState) {
this.testState = testState;
}
@Override
public DataSetWriter openWriter(ProfileFields fields) {
return new DummyWriter(fields, testState.generatedObjects);
}
private class DummyWriter implements DataSetWriter {
private final ProfileFields fields;
private final List<List<Object>> listToAppendTo;
DummyWriter(ProfileFields fields, List<List<Object>> listToAppendTo) {
this.fields = fields;
this.listToAppendTo = listToAppendTo;
}
@Override
public void writeRow(GeneratedObject row) {
if (row == null) {
throw new IllegalStateException("GeneratedObject is null");
}
List<Object> values = fields.stream()
.map(row::getFormattedValue)
.collect(Collectors.toList());
listToAppendTo.add(values);
}
@Override
public void close() {}
}
}
| true
|
99a6676ddcb38607b8c8ed91faa16d223bf89479
|
Java
|
AlbertSnow/git_workspace
|
/TestMemory/admobapk/src/main/java/fx.java
|
UTF-8
| 680
| 1.914063
| 2
|
[] |
no_license
|
import java.io.UnsupportedEncodingException;
public class fx extends ev
{
private final fb l;
public fx(int paramInt, String paramString, fb paramfb, fa paramfa)
{
super(paramInt, paramString, paramfa);
this.l = paramfb;
}
protected final ez a(et paramet)
{
try
{
str = new String(paramet.a, fs.a(paramet.b));
return ez.a(str, fs.a(paramet));
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
String str = new String(paramet.a);
}
}
}
/* Location: C:\Program Files\APK反编译\classes_dex2jar.jar
* Qualified Name: fx
* JD-Core Version: 0.6.0
*/
| true
|
fec819db844d3b6338d97eaf5581ede735c7e909
|
Java
|
rksystems/CoreJava
|
/CoreJava/src/com/unnatisoft/jdbc/ResultSetForwardOnly.java
|
UTF-8
| 1,146
| 2.796875
| 3
|
[] |
no_license
|
package com.unnatisoft.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetForwardOnly {
public static void main(String[] args) {
Connection con = JDBCConnectionUtil.getConnection();
Statement stmt = null;
try {
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
ResultSet upfrs = stmt.executeQuery("SELECT * FROM Student");
upfrs.next();
System.out.print(upfrs.getInt(1)+" ");
System.out.print(upfrs.getString(2)+" ");
System.out.print(upfrs.getString(3)+" ");
System.out.println(upfrs.getString(4));
upfrs.next();
//upfrs.beforeFirst();
//upfrs.afterLast();
System.out.print(upfrs.getInt(1)+" ");
System.out.print(upfrs.getString(2)+" ");
System.out.print(upfrs.getString(3)+" ");
System.out.println(upfrs.getString(4));
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
| true
|
1a8f56b27bece5f9139907b53a50d52954e18f76
|
Java
|
sebaspasker/Prac4-java-minecraft
|
/personalTest/model/persistence/P_test_PlayerAdapter.java
|
UTF-8
| 781
| 2.65625
| 3
|
[] |
no_license
|
package model.persistence;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import model.Inventory;
import model.ItemStack;
import model.Material;
import model.World;
import model.entities.Player;
public class P_test_PlayerAdapter {
PlayerAdapter pa;
@Test
public void constructor_comprobation() {
World w = new World(20, 20, "World", "Juan");
Player p = w.getPlayer();
try {
p.addItemsToInventory(new ItemStack(Material.BEEF, 20));
p.addItemsToInventory(new ItemStack(Material.SAND, 11));
} catch (Exception e) {
fail("");
}
Inventory i = p.getInventory();
IInventory ii = new InventoryAdapter(i);
pa = new PlayerAdapter(p);
assertEquals(ii.getSize(), pa.getInventory().getSize());
}
}
| true
|
a7b42e751e047d861e463d34b201903204c230d0
|
Java
|
fascalsj/spring-api-services
|
/src/main/java/com/fascal/apiservices/entity/Provinsi.java
|
UTF-8
| 1,040
| 1.914063
| 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 com.fascal.apiservices.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author fascal
*/
@Setter
@Getter
@Entity
public class Provinsi {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nama")
private String nama;
@Column(name = "negara_id")
private String countryId;
@JoinColumn (name="negara_id", insertable = false, updatable = false, referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Negara negara;
}
| true
|
c53f3f2dc200df4372f7b4779d709dac6fe9cfcc
|
Java
|
dawidkotarba/pet_blog_learning_frontend
|
/src/main/java/com/dawidkotarba/blog/facade/PostFacade.java
|
UTF-8
| 4,380
| 2.21875
| 2
|
[] |
no_license
|
package com.dawidkotarba.blog.facade;
import com.dawidkotarba.blog.converters.impl.PostInConverter;
import com.dawidkotarba.blog.converters.impl.PostOutConverter;
import com.dawidkotarba.blog.exceptions.NotFoundException;
import com.dawidkotarba.blog.model.dto.impl.PostInDto;
import com.dawidkotarba.blog.model.dto.impl.PostOutDto;
import com.dawidkotarba.blog.model.entities.impl.AuthorEntity;
import com.dawidkotarba.blog.model.entities.impl.PostEntity;
import com.dawidkotarba.blog.repository.CacheableAuthorRepository;
import com.dawidkotarba.blog.repository.CacheablePostRepository;
import com.google.common.base.Preconditions;
import io.vavr.collection.Seq;
import io.vavr.collection.Set;
import io.vavr.control.Option;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import javax.inject.Inject;
import javax.inject.Named;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Objects;
@Named
public class PostFacade {
private final CacheablePostRepository cacheablePostRepository;
private final CacheableAuthorRepository cacheableAuthorRepository;
private final PostOutConverter postOutConverter;
private final PostInConverter postInConverter;
@Inject
PostFacade(final CacheablePostRepository cacheablePostRepository, final CacheableAuthorRepository
cacheableAuthorRepository,
final PostOutConverter postOutConverter, final PostInConverter postInConverter) {
this.cacheablePostRepository = cacheablePostRepository;
this.cacheableAuthorRepository = cacheableAuthorRepository;
this.postOutConverter = postOutConverter;
this.postInConverter = postInConverter;
}
public Set<PostOutDto> findAll() {
return cacheablePostRepository.findAllSeq()
.map(postOutConverter::convert)
.toSet();
}
public Page<PostOutDto> findAll(final Pageable pageable) {
return cacheablePostRepository.findAll(pageable).map(postOutConverter::convert);
}
public Option<PostOutDto> findBySubject(final String subject) {
Preconditions.checkNotNull(subject);
final PostEntity bySubject = cacheablePostRepository.findBySubject(subject);
if (Objects.isNull(bySubject)) {
return Option.none();
}
return Option.some(postOutConverter.convert(bySubject));
}
public PostOutDto findById(final Long id) {
Preconditions.checkNotNull(id);
final PostEntity post = cacheablePostRepository.findById(id).get();
return postOutConverter.convert(post);
}
public Set<PostOutDto> findMonthlyByDayOfAMonth(final LocalDate dayOfAMonth) {
Preconditions.checkNotNull(dayOfAMonth);
final LocalDate startDate = dayOfAMonth.withDayOfMonth(1);
final LocalDate endDate = dayOfAMonth.withDayOfMonth(dayOfAMonth.lengthOfMonth());
return findFromDateToDate(LocalDateTime.of(startDate, LocalTime.MIDNIGHT), LocalDateTime.of(endDate,
LocalTime.MAX));
}
public Set<PostOutDto> findFromDateToDate(final LocalDateTime fromDate, final LocalDateTime toDate) {
Preconditions.checkNotNull(fromDate);
Preconditions.checkNotNull(toDate);
final Set<PostEntity> bySubject = cacheablePostRepository.findByPublishedBetween(fromDate, toDate);
return bySubject.map(postOutConverter::convert).toSet();
}
@PreAuthorize("hasAuthority('administrate') or hasAuthority('write')")
public void add(final PostInDto postInDto) {
Preconditions.checkNotNull(postInDto);
final Seq<AuthorEntity> authors = getAuthors(postInDto);
final PostEntity entity = postInConverter.convert(postInDto);
entity.setAuthors(authors.toJavaSet());
cacheablePostRepository.save(entity);
}
private Seq<AuthorEntity> getAuthors(final PostInDto postInDto) {
final Set<Long> authorIds = postInDto.getAuthors();
final Seq<AuthorEntity> authors = cacheableAuthorRepository.findAllByIdSeq(authorIds);
if (authors.isEmpty()) {
throw new NotFoundException(
"Author(s) " + authorIds + " not found. Please add valid author(s).");
}
return authors;
}
}
| true
|
4d5364d6e14edbba5e1836a23e7b6060636b4244
|
Java
|
jbrockman-emu/sandbox
|
/java-examples/src/org/jbrockman_emu/java_examples/ScannerExamples.java
|
UTF-8
| 1,872
| 3.140625
| 3
|
[] |
no_license
|
package org.jbrockman_emu.java_examples;
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class ScannerExamples {
void fish() {
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
}
void matchFish() {
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
}
void matchThreadletOp() {
String input = " ( op 7 33 )";
Scanner s = new Scanner(input);
s.findInLine("\\(\\s*op\\s+(\\d+)\\s+(\\d+)\\s*\\)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
}
void scanTraceFile() {
BufferedReader inputStream = null;
String line = null;
Scanner s = null;
try {
inputStream = new BufferedReader(new FileReader("trace.txt"));
while ((line = inputStream.readLine()) != null) {
s = new Scanner(line);
s.findInLine("\\(\\s*op\\s+(\\d+)\\s+(\\d+)\\s*\\)");
MatchResult result = s.match();
System.out.println(result.group(1) + " " + result.group(2));
}
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
void scanStdin() {
Scanner stdin = new Scanner(System.in);
String input = stdin.nextLine();
String[] splitInput = input.split("-", -1);
for (String s : splitInput) {
System.out.println(s);
}
stdin.close();
}
}
| true
|
c2eb15515f36d98f501828848bcd744fbf372a90
|
Java
|
andreasackermann/PopularMovies
|
/app/src/main/java/de/andreasackermann/popularmovies/DetailFragment.java
|
UTF-8
| 13,396
| 1.914063
| 2
|
[] |
no_license
|
package de.andreasackermann.popularmovies;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import de.andreasackermann.popularmovies.data.MoviesContract;
import de.andreasackermann.popularmovies.json.ReviewJsonHelper;
import de.andreasackermann.popularmovies.json.TrailerJsonHelper;
/**
* Created by Andreas on 07.01.2017.
*/
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
static final String DETAIL_URI = "URI";
private static final String LOG_TAG = DetailFragment.class.getName();
private static final int LOADER_MOVIES = 0;
private static final int LOADER_REVIEWS = 1;
private static final int LOADER_TRAILERS = 2;
private ShareActionProvider mShareActionProvider;
private LinearLayout mReviewsContainer;
private LinearLayout mTrailersContainer;
private ImageView mImageView;
private ImageView mFavoriteToggle;
private TextView mOriginalTitleView;
private TextView mOverviewView;
private TextView mReleaseDateView;
private TextView mVoteAverageView;
private Uri mUri;
private HttpFetcher mHttpFetcher;
public DetailFragment() {
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = null;
Bundle arguments = getArguments();
if (arguments != null) {
root = inflater.inflate(R.layout.fragment_detail, container, false);
mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
mHttpFetcher = new HttpFetcher();
mHttpFetcher.execute(MoviesContract.getMovieIdFromUri(mUri));
mImageView = (ImageView)root.findViewById(R.id.moviePoster);
mOriginalTitleView = (TextView)root.findViewById(R.id.movieTitle);
mOverviewView = (TextView)root.findViewById(R.id.overview);
mReleaseDateView = (TextView)root.findViewById(R.id.publishDate);
mVoteAverageView = (TextView)root.findViewById(R.id.voteAverage);
mReviewsContainer = (LinearLayout) root.findViewById(R.id.reviews);
mTrailersContainer = (LinearLayout) root.findViewById(R.id.trailers);
mFavoriteToggle = (ImageView) root.findViewById(R.id.toggleFavorite);
return root;
}
return null;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detail, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Not my first choice where to init loaders but as the webservices are pretty fast I ran into
// many situations having a response from loader when mShareActionProvider was not ready.
getLoaderManager().initLoader(LOADER_MOVIES, null, this);
getLoaderManager().initLoader(LOADER_REVIEWS, null, this);
getLoaderManager().initLoader(LOADER_TRAILERS, null, this);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mHttpFetcher!=null) {
mHttpFetcher.cancel(true);
}
if (mShareActionProvider!=null) {
mShareActionProvider.setShareIntent(null);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if ( null != mUri ) {
switch (id) {
case LOADER_MOVIES:
return new CursorLoader(
getActivity(),
mUri,
null,
null,
null,
null
);
case LOADER_REVIEWS:
return new CursorLoader(
getActivity(),
MoviesContract.ReviewEntry.CONTENT_URI.buildUpon().appendPath(MoviesContract.getMovieIdFromUri(mUri)).build(),
null,
null,
null,
null
);
case LOADER_TRAILERS:
return new CursorLoader(
getActivity(),
MoviesContract.TrailerEntry.CONTENT_URI.buildUpon().appendPath(MoviesContract.getMovieIdFromUri(mUri)).build(),
null,
null,
null,
null
);
}
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case LOADER_MOVIES:
if (data != null && data.moveToFirst()) {
String path = data.getString(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_IMAGE));
Picasso picasso = Picasso.with(getContext());
picasso.load(new File(path)).into(mImageView);
String originalTitle = data.getString(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE));
mOriginalTitleView.setText(originalTitle);
String overview = data.getString(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_OVERVIEW));
mOverviewView.setText(overview);
String releaseDate = formatReleaseDate(data.getString(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_RELEASED)));
mReleaseDateView.setText(releaseDate);
String voteAvg = formatVoteAverage(data.getString(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_VOTE_AVG)));
mVoteAverageView.setText(voteAvg);
final int isFavoriteAction = data.getInt(data.getColumnIndex(MoviesContract.MovieEntry.COLUMN_CAT_FAVORITE))==0?1:0;
if (isFavoriteAction==0) {
mFavoriteToggle.setImageResource(R.drawable.ic_favorite_border_black_24px);
mFavoriteToggle.setContentDescription(getString(R.string.action_unmark_favorite));
} else {
mFavoriteToggle.setImageResource(R.drawable.ic_favorite_black_24px);
mFavoriteToggle.setContentDescription(getString(R.string.action_mark_favorite));
}
mFavoriteToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues val = new ContentValues();
val.put(MoviesContract.MovieEntry.COLUMN_CAT_FAVORITE, isFavoriteAction);
Log.d(LOG_TAG, "updating " + mUri.toString());
getContext().getContentResolver().update(mUri,val,null,null);
}
});
}
break;
case LOADER_REVIEWS:
mReviewsContainer.removeAllViews();
if (data.getCount()>0) {
while (data.moveToNext()) {
View row = LayoutInflater.from(getActivity()).inflate(R.layout.review_row, null);
((TextView) row.findViewById(R.id.reviewAuthor)).setText(data.getString(data.getColumnIndex(MoviesContract.ReviewEntry.COLUMN_AUTHOR)));
((TextView) row.findViewById(R.id.reviewContent)).setText(data.getString(data.getColumnIndex(MoviesContract.ReviewEntry.COLUMN_CONTENT)));
mReviewsContainer.addView(row);
}
} else {
TextView noResult = new TextView(getContext());
noResult.setText(getString(R.string.label_reviews_unavailable));
mReviewsContainer.addView(noResult);
}
break;
case LOADER_TRAILERS:
mTrailersContainer.removeAllViews();
if (data.getCount()>0) {
while (data.moveToNext()) {
View row = LayoutInflater.from(getActivity()).inflate(R.layout.trailer_row, null);
final String key = data.getString(data.getColumnIndex(MoviesContract.TrailerEntry.COLUMN_KEY));
final String url = getString(R.string.youtube_base_url) + key;
row.findViewById(R.id.trailerPlayIcon).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
watchYoutubeVideo(key);
}
});
row.findViewById(R.id.trailerShareIcon).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shareYoutubeVideo(url);
}
});
if (data.isFirst()) {
mShareActionProvider.setShareIntent(getShareYouTubeVideoIntent(url));
}
((TextView) row.findViewById(R.id.trailerName)).setText(data.getString(data.getColumnIndex(MoviesContract.TrailerEntry.COLUMN_NAME)));
mTrailersContainer.addView(row);
}
} else {
TextView noResult = new TextView(getContext());
noResult.setText(getString(R.string.label_trailers_unavailable));
mTrailersContainer.addView(noResult);
}
break;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) { }
private String formatReleaseDate(String unformatted) {
DateFormat parser = new SimpleDateFormat("yyyy-mm-dd");
DateFormat formatter = new SimpleDateFormat("yyyy");
try {
Date date = parser.parse(unformatted);
return formatter.format(date);
} catch (ParseException pe) {
return unformatted; // better than not returning anything
}
}
private String formatVoteAverage(String voteAverage) {
return voteAverage + "/10";
}
private class HttpFetcher extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String[] params) {
return new ReviewJsonHelper(getActivity(), params[0]).updateDb()
&& new TrailerJsonHelper(getActivity(), params[0]).updateDb();
}
@Override
protected void onPostExecute(Boolean online) {
if (!this.isCancelled() && !online) {
Snackbar snackbar = Snackbar
.make(DetailFragment.this.getView(), DetailFragment.this.getString(R.string.warn_no_internet), Snackbar.LENGTH_LONG);
snackbar.show();
}
}
}
// solution from http://stackoverflow.com/questions/574195/android-youtube-app-play-video-intent
private void watchYoutubeVideo(String key){
Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + key));
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(getString(R.string.youtube_base_url) + key));
try {
startActivity(appIntent);
} catch (ActivityNotFoundException ex) {
startActivity(webIntent);
}
}
private Intent getShareYouTubeVideoIntent(String url) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.intro_share) + url);
shareIntent.setType("text/plain");
return shareIntent;
}
private void shareYoutubeVideo(String url){
startActivity(getShareYouTubeVideoIntent(url));
}
}
| true
|
524ba4ef0fd8b54b78f81bcd6a21cf4b37990faa
|
Java
|
nkalyani1821/Continents
|
/src/main/java/com/continents/bean/Continent.java
|
UTF-8
| 422
| 2.390625
| 2
|
[] |
no_license
|
package com.continents.bean;
import java.util.List;
public class Continent {
String continent;
private List<Country> countries;
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
| true
|
4559efe9a9cd5ffafd4d79d36852c6f1d7417cd2
|
Java
|
deepakpandey1234/automation
|
/Product/src/main/java/PageObject/MerchantPanel/Home/AboutPayment.java
|
UTF-8
| 543
| 1.992188
| 2
|
[] |
no_license
|
package PageObject.MerchantPanel.Home;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import Utils.Browser;
import Utils.Config;
public class AboutPayment {
private Config testConfig;
@FindBy(linkText="New to Payments")
private WebElement newToPayments;
public AboutPayment(Config testConfig)
{
this.testConfig = testConfig;
PageFactory.initElements(this.testConfig.driver, this);
Browser.waitForPageLoad(testConfig, newToPayments);
}
}
| true
|
50a3fa940a7362eab4909af90a4f1ca0a5f35787
|
Java
|
galeanov/tucanchape
|
/app/src/main/java/com/example/amador/tucanchape/model/Reserva.java
|
UTF-8
| 1,089
| 2.4375
| 2
|
[] |
no_license
|
package com.example.amador.tucanchape.model;
import java.io.Serializable;
public class Reserva implements Serializable{
private String fecha;
private String reservado;
private String siglas;
public Reserva() {
}
public Reserva(String fecha, String reservado, String siglas) {
this.fecha = fecha;
this.reservado = reservado;
this.siglas = siglas;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getReservado() {
return reservado;
}
public void setReservado(String reservado) {
this.reservado = reservado;
}
public String getSiglas() {
return siglas;
}
public void setSiglas(String siglas) {
this.siglas = siglas;
}
@Override
public String toString() {
return "Reserva{" +
"fecha='" + fecha + '\'' +
", reservado='" + reservado + '\'' +
", siglas='" + siglas + '\'' +
'}';
}
}
| true
|
558a1083c2bc474c3b2b84b922811be2c875344e
|
Java
|
kevinkerry/dada
|
/dada/sports-app/sports-app-soa/src/main/java/com/youyisi/app/soa/application/wallet/WalletService.java
|
UTF-8
| 5,664
| 1.90625
| 2
|
[] |
no_license
|
package com.youyisi.app.soa.application.wallet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.youyisi.app.soa.application.annual.AnnualYieldService;
import com.youyisi.app.soa.application.experience.ExperienceAccountService;
import com.youyisi.app.soa.application.user.UserService;
import com.youyisi.app.soa.exception.SoaException;
import com.youyisi.app.soa.infrastructure.persist.annual.AnnualYieldDetailRepository;
import com.youyisi.app.soa.infrastructure.persist.wallet.WalletRepository;
import com.youyisi.app.soa.remote.wallet.WalletServiceRemote;
import com.youyisi.lang.Page;
import com.youyisi.sports.domain.annual.AnnualYield;
import com.youyisi.sports.domain.annual.AnnualYieldDetail;
import com.youyisi.sports.domain.experience.ExperienceAccount;
import com.youyisi.sports.domain.orders.Orders;
import com.youyisi.sports.domain.user.User;
import com.youyisi.sports.domain.wallet.Wallet;
import com.youyisi.sports.domain.wallet.WalletDetail;
import com.youyisi.sports.utils.ArithHelper;
import com.youyisi.sports.utils.DateUtil;
/**
* @author shuye
* @time 2016-05-12
*/
@Service
@Transactional
public class WalletService implements WalletServiceRemote {
@Autowired
private WalletRepository repository;
@Autowired
private WalletDetailService walletDetailService;
@Autowired
private ExperienceAccountService experienceAccountService;
@Autowired
private AnnualYieldDetailRepository annualYieldDetailRepository;
@Autowired
private UserService userService;
@Autowired
private AnnualYieldService annualYieldService;
@Override
public Wallet get(Long id) throws SoaException {
return repository.get(id);
}
@Override
public Wallet save(Wallet entity) throws SoaException {
return repository.save(entity);
}
@Override
public Integer delete(Wallet entity) throws SoaException {
return repository.delete(entity);
}
@Override
public Integer update(Wallet entity) throws SoaException {
return repository.update(entity);
}
@Override
public Page<Wallet> queryPage(Page<Wallet> page) throws SoaException {
return repository.queryPage(page);
}
@Override
public Wallet getByUserId(Long userId) throws SoaException {
return repository.getByUserId(userId);
}
@Override
public void recharge(Orders order) throws SoaException {
// TODO Auto-generated method stub
WalletDetail walletDetail = new WalletDetail();
walletDetail.setCreateTime(System.currentTimeMillis());
walletDetail.setDate(DateUtil.currentDateForDay());
walletDetail.setMoney(order.getPayAmount());
walletDetail.setType(1);
walletDetail.setUserId(order.getUserId());
Wallet wallet = repository.getByUserId(order.getUserId());
wallet.setTotalAsset(ArithHelper.add(wallet.getTotalAsset(),order.getPayAmount()));
wallet.setPrincipal(ArithHelper.add(wallet.getPrincipal(),order.getPayAmount()));
walletDetail.setResult(wallet.getTotalAsset());
walletDetailService.save(walletDetail);
repository.update(wallet);
ExperienceAccount experienceAccount = experienceAccountService.getByUserId(order.getUserId());
User user = userService.get(order.getUserId());
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.DATE, -5);
if(experienceAccount.getLevel()!=null&&experienceAccount.getLevel().intValue()==0&&user.getRegisterTime()!=null&&user.getRegisterTime().longValue()>calendar.getTime().getTime()){
lengthenExperience(experienceAccount);
}
if(wallet.getPrincipal()>=100){
changeAnnualYield(order);
}
}
private void lengthenExperience(ExperienceAccount experienceAccount)
throws SoaException {
Calendar calendar = new GregorianCalendar();
if(experienceAccount.getExpiryTime()>System.currentTimeMillis()){
calendar.setTime(new Date(experienceAccount.getExpiryTime()));
}else{
calendar.setTime(new Date());
}
calendar.add(Calendar.DATE, 5);
experienceAccount.setExpiryTime(calendar.getTime().getTime());
experienceAccount.setLevel(1);
experienceAccountService.update(experienceAccount);
}
private void changeAnnualYield(Orders order) throws SoaException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", DateUtil.currentDateForDay());
map.put("userId", order.getUserId());
map.put("type", 9);
AnnualYieldDetail annualYieldDetail = annualYieldDetailRepository.getCurrentDay(map);
if(annualYieldDetail==null){
AnnualYield annualYield = annualYieldService.getByUserIdAndDate(order.getUserId());
if(annualYield.getBaseAnnualYield()==4.0){
annualYield.setBaseAnnualYield(6.0);
annualYield.setAnnualYield(ArithHelper.add(annualYield.getAnnualYield(), 2.0));
annualYieldService.update(annualYield);
annualYieldDetail = new AnnualYieldDetail();
annualYieldDetail.setUserId(order.getUserId());
annualYieldDetail.setType(9);
annualYieldDetail.setDate(DateUtil.currentDateForDay());
annualYieldDetail.setAnnualYieldIncrease(2.0);
annualYieldDetail.setCreateTime(System.currentTimeMillis());
annualYieldDetailRepository.save(annualYieldDetail);
}
}
}
public int updateByVersion(Wallet wallet, Double totalAsset) {
// TODO Auto-generated method stub
return repository.updateByVersion(wallet, totalAsset);
}
}
| true
|
5f70546f3aea6ff0972e54c1f208bfb3d3506390
|
Java
|
TsukiZombina/eCommerce
|
/src/java/mx/uam/azc/modelo/dao/mysql/MySQLUsuarioDAO.java
|
UTF-8
| 8,621
| 2.546875
| 3
|
[] |
no_license
|
package mx.uam.azc.modelo.dao.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ThreadLocalRandom;
import mx.uam.azc.modelo.EcommerceException;
import mx.uam.azc.modelo.Sal;
import mx.uam.azc.modelo.beans.Usuario;
import mx.uam.azc.modelo.dao.UsuarioDAO;
/**
*
* @author Zelzin Marcela Márquez Navarrete
* @author Ernesto García Maldonado
* @version 1.0
*/
public class MySQLUsuarioDAO implements UsuarioDAO {
private final String INSERT = "INSERT INTO tb_usuario(nombre, apellidoP, apellidoM, username, password, sal, contactoTel, contactoCorreo, saldo) VALUES (?, ?, ?, ?, MD5(?), ?, ?, ?, ? )";
private final String DELETE = "DELETE FROM tb_usuario WHERE id_usuario = ?";
private final String UPDATE = "UPDATE tb_usuario SET nombre=?, apellidoP=?, apellidoM=?, username=?, contactoTel=?, contactoCorreo=? WHERE id_usuario=?";
private final String GETONE = "SELECT * FROM tb_usuario WHERE id_usuario = ?";
private final String CHECK_PASSWORD = "SELECT verificarContrasenia(?, ?)";
private final String USERNAME = "SELECT id_usuario FROM tb_usuario WHERE username= ? ";
@Override
public void insertar(Usuario unUsuario) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
ps = con.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, unUsuario.getNombre());
ps.setString(2, unUsuario.getApellidoP());
ps.setString(3, unUsuario.getApellidoM());
ps.setString(4, unUsuario.getUsername());
String sal = new Sal().generarSal();
ps.setString(5, sal + unUsuario.getPassword());
ps.setString(6, sal);
ps.setString(7, unUsuario.getContactoTel());
ps.setString(8, unUsuario.getContactoCorreo());
ps.setDouble(9, generarSaldo());
if (ps.executeUpdate() == 0) {
throw new EcommerceException("Puede ser que no se haya guardado");
}
rs = ps.getGeneratedKeys();
if (rs.next()) {
unUsuario.setIdUsuario(rs.getLong(1));
} else {
throw new EcommerceException("Puede ser que no se haya asignada un ID");
}
System.out.println("Inserción de usuario exitosa");
} catch (SQLException ex) {
throw new EcommerceException("Error en SQL: " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, rs, con);
}
}
@Override
public void modificar(Usuario unUsuario) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
ps = con.prepareStatement(UPDATE);
ps.setString(1, unUsuario.getNombre());
ps.setString(2, unUsuario.getApellidoP());
ps.setString(3, unUsuario.getApellidoM());
ps.setString(4, unUsuario.getUsername());
ps.setString(5, unUsuario.getContactoTel());
ps.setString(6, unUsuario.getContactoCorreo());
ps.setLong(7, unUsuario.getIdUsuario());
if (ps.executeUpdate() == 0) {
throw new EcommerceException("No se pudo modificar el usuario " + unUsuario.getIdUsuario());
}
} catch (SQLException ex) {
throw new EcommerceException("Error en SQL : " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, con);
}
}
@Override
public void eliminar(Long id) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
ps = con.prepareStatement(DELETE);
ps.setLong(1, id);
if (ps.executeUpdate() == 0) {
throw new EcommerceException("No se pudo eliminiar el usuario" + id);
}
} catch (SQLException ex) {
throw new EcommerceException("Error en SQL : " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, con);
}
}
public Usuario convertir(ResultSet rs) throws SQLException {
Long id_usuario = rs.getLong("id_usuario");
String nombre = rs.getString("nombre");
String apellidoP = rs.getString("apellidoP");
String apellidoM = rs.getString("apellidoM");
String username = rs.getString("username");
String sal = rs.getString("sal");
String contactoTel = rs.getString("contactoTel");
String contactoCorreo = rs.getString("contactoCorreo");
double saldo = rs.getDouble("saldo");
Usuario usuario = new Usuario();
usuario.setIdUsuario(id_usuario);
usuario.setNombre(nombre);
usuario.setApellidoP(apellidoP);
usuario.setApellidoM(apellidoM);
usuario.setUsername(username);
usuario.setSal(sal);
usuario.setContactoTel(contactoTel);
usuario.setContactoCorreo(contactoCorreo);
usuario.setSaldo(saldo);
return usuario;
}
@Override
public Usuario obtener(Long id) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
Usuario usuario = null;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
ps = con.prepareStatement(GETONE);
ps.setLong(1, id);
rs = ps.executeQuery();
if (rs.next()) {
usuario = convertir(rs);
} else {
throw new EcommerceException("No se encontró el usuario con id " + id);
}
} catch (SQLException ex) {
throw new EcommerceException("Error SQL : " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, rs, con);
}
return usuario;
}
@Override
public double generarSaldo() {
double saldo = ThreadLocalRandom.current().nextInt(100, 1000 + 1);
return saldo;
}
@Override
public boolean validarUsuario(Long id, String password) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
Usuario unUsuario = null;
boolean verifica = false;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
unUsuario = obtener(id);
if (unUsuario == null) {
throw new EcommerceException("No se pudo obtener la persona con id: " + id);
}
ps = con.prepareStatement(CHECK_PASSWORD);
ps.setLong(1, unUsuario.getIdUsuario());
ps.setString(2, unUsuario.getSal() + password);
rs = ps.executeQuery();
if (rs.next()) {
verifica = rs.getBoolean(1);
} else {
throw new EcommerceException("No se pudo validar la contraseña");
}
} catch (SQLException ex) {
throw new EcommerceException("Error SQL : " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, rs, con);
}
return verifica;
}
@Override
public Long buscarUsername(String username) throws EcommerceException {
Connection con = DataBaseManager.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
Long id;
if (con == null) {
throw new EcommerceException("No hay conexión a la BD");
}
try {
ps = con.prepareStatement(USERNAME);
ps.setString(1, username);
rs = ps.executeQuery();
if (rs.next()) {
id = rs.getLong("id_usuario");
} else {
id = -1L;
}
} catch (SQLException ex) {
throw new EcommerceException("Error SQL : " + ex.getMessage());
} finally {
MySQLUtils.cerrar(ps, rs, con);
}
return id;
}
}
| true
|
30cb66608b42d055fe404f5f3c6ae925ba4719da
|
Java
|
ash018/FotonApp
|
/app/src/main/java/com/mis/smakash/fotonapp/Utility.java
|
UTF-8
| 2,526
| 2.515625
| 3
|
[] |
no_license
|
package com.mis.smakash.fotonapp;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Utility {
public static final int NETWORK_STATUS_NOT_CONNECTED = 0, NETWORK_STAUS_WIFI = 1, NETWORK_STATUS_MOBILE = 2;
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = Utility.getConnectivityStatus(context);
int status = 0;
if (conn == Utility.TYPE_WIFI) {
status = NETWORK_STAUS_WIFI;
} else if (conn == Utility.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == Utility.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
public Boolean isConnected(Context context) {
Boolean status = false;
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInf = conMgr.getAllNetworkInfo();
for (NetworkInfo inf : netInf) {
if (inf != null) {
if (inf.getTypeName().toUpperCase().contains("WIFI")
|| inf.getTypeName().toUpperCase().contains("MOBILE")) {
if (inf.getState() == NetworkInfo.State.CONNECTED) {
status = true;
break;
}
}
}
}
return status;
}
public static void showOkDialog(Context context, String title, String message) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
alert.setCancelable(true);
alert.setMessage(message);
alert.setPositiveButton("OK", null);
alert.show();
}
}
| true
|
36246e94fb56a177b3aa2c10ca0c53c917969608
|
Java
|
DimaVovchuk/LvivPortal
|
/src/main/java/com/lab/epam/dao/imp/MySqlWayDao.java
|
UTF-8
| 17,416
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package com.lab.epam.dao.imp;
import com.lab.epam.dao.AbstractJDBCDao;
import com.lab.epam.dao.PersistException;
import com.lab.epam.entity.Way;
import com.lab.epam.helper.ClassName;
import com.lab.epam.persistant.ConnectionManager;
import com.lab.epam.persistant.ConnectionPool;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Admin on 10.06.2015.
*/
public class MySqlWayDao extends AbstractJDBCDao<Way, Integer> {
ConnectionPool connection = ConnectionManager.getConnection();
private static final Logger loger = LogManager.getLogger(ClassName.getCurrentClassName());
private static final String GET_WAY_BY_USER_ID = "SELECT w.id, w.rating, w.name, w.visible, w.way_days, w.way_time, w.date_begin, w.date_end, w.deleted, w.recomended, w.is_recommend FROM way AS w JOIN user_way AS uw JOIN user AS u WHERE uw.user_id = u.id AND uw.way_id = w.id AND uw.deleted='false' AND u.id = ?";
private static final String GET_WAY_BY_WAY_ID = "SELECT w.id, w.rating, w.name, w.visible, w.way_days, w.way_time, w.date_begin, w.date_end, w.deleted, w.recomended, w.is_recommend FROM way AS w JOIN user_way AS uw JOIN user AS u WHERE uw.user_id = u.id AND uw.way_id = w.id AND uw.deleted='false' AND uw.way_id = ?";
private static final String DELETE_WAY_BY_USER_ID_WAY_ID = "UPDATE user_way SET deleted = true WHERE user_id = ? AND way_id = ?";
private static final String GET_LAST_ADDED = "SELECT * FROM way ORDER BY id DESC LIMIT 0,1";
private static final String CREATE_USER_WAY = "INSERT INTO user_way (user_id, way_id, way_days) VALUES (?,?,?);";
private static final String UPDATE_WAY_DAY = "UPDATE user_way SET way_days = ? WHERE user_id = ? AND way_id = ?";
private static final String UPDATE_WAY_BEGIN_DATE = "UPDATE way SET date_begin = ? WHERE id = ?";
private static final String UPDATE_WAY_END_DATE = "UPDATE way SET date_end = ? WHERE id = ?";
private static final String UPDATE_WAY_RATING = "UPDATE way SET rating = ? WHERE id = ?";
private static final String UPDATE_WAY_ISRECOMENDED = "UPDATE way SET is_recommend = false WHERE id = ?";
private static final String DELETE_WAY_ISRECOMENDED = "UPDATE way SET recomended = false WHERE id = ?";
private static final String UPDATE_CONFIRM_WAY_ISRECOMENDED = "UPDATE way SET is_recommend = false, recomended = true WHERE id = ?";
private static final String GET_WAY_RECOMENDED = "SELECT * FROM way WHERE recomended=true AND deleted=false AND visible=true";
private static final String SET_WAY_IS_RECOMMENDED = "UPDATE way SET is_recommend = true WHERE id = ?";
private static final String GET_ALL_CONFIRM_RECOMMENDED_WAY = "SELECT * FROM way AS w WHERE w.deleted=false AND w.visible=true AND w.recomended=false AND w.is_recommend=true";
private class PersistGroup extends Way {
public void setId(int id) {
super.setId(id);
}
}
public MySqlWayDao() {
}
public Class getClassModel() {
return Way.class;
}
public void updateConfirmWayRecommended(Integer way_id) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_CONFIRM_WAY_ISRECOMENDED)) {
statement.setInt(1, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateConfirmWayRecommended method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void updateWayIsRecommended(Integer way_id) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_WAY_ISRECOMENDED)) {
statement.setInt(1, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateWayIsRecommended method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void deleteWayIsRecommended(Integer way_id) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(DELETE_WAY_ISRECOMENDED)) {
statement.setInt(1, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("deleteWayIsRecommended method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public List<Way> getWaysByUserId(Integer user_id) throws PersistException {
List<Way> list;
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(GET_WAY_BY_USER_ID)) {
statement.setInt(1, user_id);
ResultSet rs = statement.executeQuery();
//loger.info("Get ways from user with id" + user_id + " is succesfull " + rs);
list = parseResultSet(rs);
//loger.info("Parse result with Transformer is succesfull list = " + list);
if (list.size() <= 0) {
loger.info("DB has any ways from user with " + user_id + " user_id");
return null;
}
} catch (Exception e) {
loger.warn("Cant get ways from user with " + user_id + " user_id");
throw new PersistException(e);
} finally {
connection.putback(conn);
}
loger.info("getWaysByUserId method");
return list;
}
public List<Way> getAllConfirmRecommendedWay() throws PersistException {
List<Way> wayList = new ArrayList<>();
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(GET_ALL_CONFIRM_RECOMMENDED_WAY)) {
ResultSet rs = statement.executeQuery();
// loger.info("Get last way is succesfull ");
wayList = parseResultSet(rs);
//loger.info("Parse result with Transformer is succesfull");
if (wayList.size() <= 0) {
loger.info("DB has any ways");
return null;
}
if (wayList.size() > 1) {
loger.info("DB has more than one last way");
}
} catch (Exception e) {
loger.warn("Can not get all confirm recommended way.");
throw new PersistException(e);
}
loger.info("getAllConfirmRecommendedWay method");
return wayList;
}
public List<Way> getWaysByWayId(Integer way_id) throws PersistException {
List<Way> list;
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(GET_WAY_BY_WAY_ID)) {
statement.setInt(1, way_id);
ResultSet rs = statement.executeQuery();
list = parseResultSet(rs);
if (list.size() <= 0) {
loger.info("DB has any ways from way with " + way_id + " way_id");
return null;
}
} catch (Exception e) {
loger.warn("Cant get ways from way with " + way_id + " way_id");
throw new PersistException(e);
} finally {
connection.putback(conn);
}
loger.info("getWaysByWayId method");
return list;
}
public void create(Connection conn, Way way) throws PersistException {
String sql = prepareStatementForInsert(way);//getCreateQuery();
try (PreparedStatement statement = conn.prepareStatement(sql)) {
// prepareStatementForInsert(statement, object);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
loger.info("Create is succesfule");
}
loger.info("create method");
} catch (Exception e) {
throw new PersistException(e);
}
}
public void deleteWaysByUserIdWayId(Integer user_id, Integer way_id) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(DELETE_WAY_BY_USER_ID_WAY_ID)) {
try {
statement.setObject(1, user_id);
statement.setObject(2, way_id);
} catch (Exception e) {
throw new PersistException(e);
}
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On delete modify more then 1 record: " + count);
}
loger.info("deleteWaysByUserIdWayId method");
} catch (Exception e) {
loger.warn("Cant delete way from user with " + user_id + " user_id and " + way_id + " way_id");
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public Way getLastAdded() throws PersistException {
List<Way> list;
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(GET_LAST_ADDED)) {
ResultSet rs = statement.executeQuery();
loger.info("Get last way is succesfull ");
list = parseResultSet(rs);
loger.info("Parse result with Transformer is succesfull");
if (list.size() <= 0) {
loger.info("DB has any ways");
return null;
}
if (list.size() > 1) {
loger.info("DB has more than one last way");
}
} catch (Exception e) {
loger.warn("Cant last way");
throw new PersistException(e);
} finally {
connection.putback(conn);
}
loger.info("getLastAdded method");
return list.iterator().next();
}
public Way getLastAdded(Connection conn) throws PersistException {
List<Way> list;
try (PreparedStatement statement = conn.prepareStatement(GET_LAST_ADDED)) {
ResultSet rs = statement.executeQuery();
// loger.info("Get last way is succesfull ");
list = parseResultSet(rs);
//loger.info("Parse result with Transformer is succesfull");
if (list.size() <= 0) {
loger.info("DB has any ways");
return null;
}
if (list.size() > 1) {
loger.info("DB has more than one last way");
}
} catch (Exception e) {
loger.warn("Cant last way");
throw new PersistException(e);
}
loger.info("getLastAdded method");
return list.iterator().next();
}
public void createUserWay(Integer user_id, Integer way_id, Integer day) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(CREATE_USER_WAY)) {
statement.setInt(1, user_id);
statement.setInt(2, way_id);
statement.setInt(3, day);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
loger.info("Create is successful");
}
loger.info("createUserWay method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void createUserWay(Connection conn, Integer user_id, Integer way_id, Integer day) throws PersistException {
try (PreparedStatement statement = conn.prepareStatement(CREATE_USER_WAY)) {
statement.setInt(1, user_id);
statement.setInt(2, way_id);
statement.setInt(3, day);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
loger.info("Create is successful");
}
loger.info("createUserWay method");
} catch (Exception e) {
throw new PersistException(e);
}
}
public void updateWayDay(Integer user_id, Integer way_id, Integer day) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_WAY_DAY)) {
statement.setInt(2, user_id);
statement.setInt(3, way_id);
statement.setInt(1, day);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateWayDay method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void updateWayBeginDate(Integer way_id, Date beginDate) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_WAY_BEGIN_DATE)) {
statement.setDate(1, beginDate);
statement.setInt(2, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateWayBeginDate method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void updateWayEndDate(Integer way_id, Date endDate) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_WAY_END_DATE)) {
statement.setDate(1, endDate);
statement.setInt(2, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateWayEndDate method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public void updateWayRating(Integer way_id, Integer rating) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(UPDATE_WAY_RATING)) {
statement.setInt(1, rating);
statement.setInt(2, way_id);
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On persist modify more then 1 record: " + count);
} else {
}
loger.info("updateWayRating method");
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
public List<Way> getAllWayRecomended() throws PersistException {
List<Way> list;
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(GET_WAY_RECOMENDED)) {
ResultSet rs = statement.executeQuery();
list = parseResultSet(rs);
} catch (Exception e) {
throw new PersistException(e);
} finally {
connection.putback(conn);
}
loger.info("getAllWayRecomended method");
return list;
}
public void setWayIsRecommended(Integer way_id) throws PersistException {
Connection conn = connection.retrieve();
try (PreparedStatement statement = conn.prepareStatement(SET_WAY_IS_RECOMMENDED)) {
try {
statement.setInt(1, way_id);
} catch (Exception e) {
throw new PersistException(e);
}
int count = statement.executeUpdate();
if (count != 1) {
throw new PersistException("On insert modify more then 1 record: " + count);
}
loger.info("setWayIsRecommended method");
} catch (Exception e) {
loger.warn("Cant set is recommended from " + way_id + " way_id");
throw new PersistException(e);
} finally {
connection.putback(conn);
}
}
}
| true
|
c2bbe60f2c62634a88202222a9a514f3615f3b4f
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/2/2_774e33f0eb96ea47d67d32496f8927cffb1ec02a/ParameterTest/2_774e33f0eb96ea47d67d32496f8927cffb1ec02a_ParameterTest_t.java
|
UTF-8
| 3,335
| 1.945313
| 2
|
[] |
no_license
|
package uk.ac.starlink.ttools.task;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.xml.sax.SAXException;
import uk.ac.starlink.task.Parameter;
import uk.ac.starlink.task.Task;
import uk.ac.starlink.ttools.Formatter;
import uk.ac.starlink.ttools.Stilts;
import uk.ac.starlink.ttools.mode.ProcessingMode;
import uk.ac.starlink.util.LoadException;
import uk.ac.starlink.util.ObjectFactory;
public class ParameterTest extends TestCase {
private Formatter formatter_ = new Formatter();
private Collection noDefaults = new HashSet( Arrays.asList( new String[] {
"protocol", "database", "newtable",
"matcher", "values", "values1", "values2", "valuesN", "params",
"in", "in1", "in2", "nin", "inN",
"expression",
"cols", "binsizes",
"serviceurl", "ra", "dec", "sr",
"tapurl", "joburl", "adql", "uploadN",
"query",
"cache", "href",
"db", "dbtable", "dbra", "dbdec",
"ra1", "dec1", "ra2", "dec2", "error",
"select", "assign", "sql",
// plotting
"out", "ofmt",
"legend",
"xdataN", "ydataN", "zdataN", "auxdataN",
"subsetNS", "colourNS", "shapeNS", "transparencyNS",
} ) );
public ParameterTest( String name ) {
super( name );
}
public void testParams() throws LoadException, SAXException {
Task[] tasks = getTasks();
for ( int i = 0; i < tasks.length; i++ ) {
checkParams( tasks[ i ].getParameters() );
}
ProcessingMode[] modes = getModes();
for ( int i = 0; i < modes.length; i++ ) {
checkParams( modes[ i ].getAssociatedParameters() );
}
}
private void checkParams( Parameter[] params ) throws SAXException {
for ( int i = 0; i < params.length; i++ ) {
checkParam( params[ i ] );
}
}
private void checkParam( Parameter param ) throws SAXException {
assertTrue( param.getName(),
param.getDefault() != null ||
param.isNullPermitted() ||
noDefaults.contains( param.getName() ) );
formatter_.formatXML( param.getDescription(), 0 );
}
private ProcessingMode[] getModes() throws LoadException {
ObjectFactory fact = Stilts.getModeFactory();
List nameList = new ArrayList( Arrays.asList( fact.getNickNames() ) );
List modeList = new ArrayList();
for ( Iterator it = nameList.iterator(); it.hasNext(); ) {
modeList.add( fact.createObject( (String) it.next() ) );
}
return (ProcessingMode[]) modeList.toArray( new ProcessingMode[ 0 ] );
}
private Task[] getTasks() throws LoadException {
ObjectFactory fact = Stilts.getTaskFactory();
List nameList = Arrays.asList( fact.getNickNames() );
List taskList = new ArrayList();
for ( Iterator it = nameList.iterator(); it.hasNext(); ) {
taskList.add( fact.createObject( (String) it.next() ) );
}
return (Task[]) taskList.toArray( new Task[ 0 ] );
}
}
| true
|
5eef8070085f9d1dd23dc0a00122fc29db49fd7b
|
Java
|
MOSjens/TelematicsCourse
|
/GameClient/Client/src/main/java/StateMachine/Selector.java
|
UTF-8
| 1,293
| 2.703125
| 3
|
[] |
no_license
|
package StateMachine;
import Message.CategorySelectionMessage;
import Message.Message;
import Message.QuestionMessage;
import MessageType.InGameMessageType;
public class Selector extends AbstractState{
public Selector (StateEnum stateEnum) {
super(stateEnum);
}
@Override
public IState sendMessage(Context context) {
return Context.SELECTOR;
}
@Override
public IState receiveMessage(Context context) {
Message message = context.getInputMessage();
switch(message.getGroup().getValue()) {
case 0:{ break;}
case 1:{
if(message.getType() == InGameMessageType.QUESTION) {
QuestionMessage questionMessage = (QuestionMessage)message;
context.setQuestion(questionMessage.getQuestion());
context.setAnswer(questionMessage.getAnswer());
return Context.RE_QUESTION;
}
}
case 2: {
IState nextState = Context.END_GAME;
return nextState;
}
case 3: {
System.out.println(context.getInputMessage().getMessageBody().toString());
}
}
return Context.SELECTOR;
}
}
| true
|
9d878f99f3593ed5df5513e181fb58959c3c6044
|
Java
|
lisahua/rase
|
/Rase/changeassistant-clonereduction/src/changeassistant/clonereduction/manipulate/data/ExpressionInfo.java
|
UTF-8
| 803
| 2.15625
| 2
|
[] |
no_license
|
package changeassistant.clonereduction.manipulate.data;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Expression;
import changeassistant.changesuggestion.expression.representation.Term;
public class ExpressionInfo {
public String name;
public String type;
public String content;
public String abstractName;
public List<String> otherKeys;
public ExpressionInfo(String name, ASTNode astNode, String abstractName){
this.abstractName = abstractName;
this.name = name;
if(astNode != null){
this.type = ((Expression)astNode).resolveTypeBinding().getName();
this.content = astNode.toString();
}
}
@Override
public String toString(){
return name + "(" + content + ")";
}
}
| true
|
7f0d2243ac6ae1b341a443901aef42bf2dcaeb7b
|
Java
|
zchLee/DesignPatternsProject
|
/patterns/src/com/lea/pattern_11_decorator/common/Decorator.java
|
UTF-8
| 361
| 2.6875
| 3
|
[] |
no_license
|
package com.lea.pattern_11_decorator.common;
/**
* @author lzc
* @create 2020-11-19 10:42
*/
public abstract class Decorator extends Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void baseOperate() {
this.component.baseOperate();
}
}
| true
|
399ffa0435008ab0a553af021880001cdea27f9f
|
Java
|
jjunio01/saudegaranhuns
|
/src/test/java/br/edu/ifpe/garanhuns/sg/model/ConsultaTest.java
|
UTF-8
| 3,053
| 2.203125
| 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 br.edu.ifpe.garanhuns.sg.model;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author Jose Junio
*/
public class ConsultaTest {
/**
* Test of validarConsultaJson method, of class Consulta.
*/
@Test
public void testValidarConsultaJsonValido() {
String consultaTest = "{\"id\":0,\"especialidade\":\"GERAL\",\"prioridade\":\"IDOSO\",\"status\":\"AGENDADO\",\"dataSolicitacao\":{\"year\":2017,\"month\":12,\"day\":28},\"dataAgendamento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"paciente\":{\"id\":0,\"nome\":\"Paciente Test\",\"cartaoSus\":\"0001\",\"dataNascimento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"postoSaude\":{\"id\":0,\"nome\":\"Posto Teste\","
+ "\"endereco\":{\"id\":0,\"numero\":\"007\",\"logradouro\":\"Rua Aqui\","
+ "\"bairro\":{\"id\":0,\"nome\":\"Centro\"}}},"
+ "\"usuario\":{\"id\":0,\"login\":\"t\",\"senha\":\"123\",\"perfilUsuario\":\"PACIENTE\"}}}";
Assert.assertTrue(Consulta.validarConsultaJson(consultaTest));
}
@Test
public void testValidarConsultaJsonFormatoInvalido() {
String consultaTest = "\"id\":0,\"especialidade\":\"GERAL\",\"prioridade\":\"IDOSO\",\"status\":\"AGENDADO\",\"dataSolicitacao\":{\"year\":2017,\"month\":12,\"day\":28},\"dataAgendamento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"paciente\":{\"id\":0,\"nome\":\"Paciente Test\",\"cartaoSus\":\"0001\",\"dataNascimento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"postoSaude\":{\"id\":0,\"nome\":\"Posto Teste\","
+ "\"endereco\":{\"id\":0,\"numero\":\"007\",\"logradouro\":\"Rua Aqui\","
+ "\"bairro\":{\"id\":0,\"nome\":\"Centro\"}}},"
+ "\"usuario\":{\"id\":0,\"login\":\"t\",\"senha\":\"123\",\"perfilUsuario\":\"PACIENTE\"}}}";
Assert.assertFalse(Consulta.validarConsultaJson(consultaTest));
}
@Test
public void testValidarConsultaJsonCampoEspecialidadeInvalido() {
String consultaTest = "{\"id\":0,\"especialidad\":\"GERAL\",\"prioridade\":\"IDOSO\",\"status\":\"AGENDADO\",\"dataSolicitacao\":{\"year\":2017,\"month\":12,\"day\":28},\"dataAgendamento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"paciente\":{\"id\":0,\"nome\":\"Paciente Test\",\"cartaoSus\":\"0001\",\"dataNascimento\":{\"year\":2017,\"month\":12,\"day\":28},"
+ "\"postoSaude\":{\"id\":0,\"nome\":\"Posto Teste\","
+ "\"endereco\":{\"id\":0,\"numero\":\"007\",\"logradouro\":\"Rua Aqui\","
+ "\"bairro\":{\"id\":0,\"nome\":\"Centro\"}}},"
+ "\"usuario\":{\"id\":0,\"login\":\"t\",\"senha\":\"123\",\"perfilUsuario\":\"PACIENTE\"}}}";
Assert.assertFalse(Consulta.validarConsultaJson(consultaTest));
}
}
| true
|
abf1adad381123f1b260ade4a9e4e38788577f91
|
Java
|
DoraemonSCL/NextGenPOS
|
/NextGenPOS/src/com/foo/nextgen/domain/NestGenPOS.java
|
UTF-8
| 377
| 1.835938
| 2
|
[] |
no_license
|
package com.foo.nextgen.domain;
import com.foo.nextgen.ui.UI;
public class NestGenPOS
{
public static void main(String []args)
{
Store store = new Store() ;
Register register = store.getRegister() ;
register.initialize();
UI ui = new UI() ;
Adapter adapter = new Adapter(ui , register) ;
ui.createFrame();
adapter.process();
}
}
| true
|
9a71a0f523c35f19fa9ee8a605f07e0b6ccdab79
|
Java
|
EGo14T/LeetCodeEveryDay
|
/src/LeetCode/FourSum.java
|
UTF-8
| 2,007
| 3.671875
| 4
|
[] |
no_license
|
package LeetCode;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author 王富昕
* Created by EGo1ST
* Date:Created in 2019/12/9 8:51
* Description:
*
* 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
*
* 注意:
*
* 答案中不可以包含重复的四元组。
*
* 示例:
*
* 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
*
* 满足要求的四元组集合为:
* [
* [-1, 0, 0, 1],
* [-2, -1, 1, 2],
* [-2, 0, 0, 2]
* ]
*
*
*
*/
public class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
int len = nums.length;
if(nums==null||nums.length<4){
return ans;
}
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
if (i>0 && nums[i] == nums[i-1]) continue;
for (int j = i+1; j<len-1;j++){
if (j > i+1 && nums[j] == nums[j-1]) continue;
int L = j+1;
int R = len-1;
while (L<R){
int sum = nums[i] + nums[j] + nums[L] + nums[R];
if (sum == target){
ans.add(Arrays.asList(nums[i], nums[j],nums[L],nums[R]));
while (L<R-1 && nums[L]==nums[L+1]) L++;
while (R<len-1 && nums[R]==nums[R+1]) R--;
L++;
R--;
}
else if(sum<target) L++;
else if(sum>target) R--;
}
}
}
return ans;
}
@Test
public void test(){
int[] nums = {1, 0, -1, 0, -2, 2};
System.out.println(fourSum(nums,0));
}
}
| true
|
70918c23469714ac0fb39f4b702de618a824021d
|
Java
|
AminaHub/SyntaxRepo
|
/src/com/class4/NestedIf.java
|
UTF-8
| 691
| 3.734375
| 4
|
[] |
no_license
|
package com.class4;
public class NestedIf {
public static void main(String[] args) {
/*
* write a program to check or eligibility
* if user is younger than <16 --> not allowed t work
* otherwise -->allowed to work. If user younger than 64--> go to work
* otherwise --> enjoy your life
*/
int age = 65;
int eligibleAge=16;
int retirenmentAge=64;
if (age<eligibleAge) {
System.out.println("You are too young, no work for yuo");
}else {
System.out.println("You are eligible to work");
if (age<retirenmentAge) {
System.out.println("Go work hard");
}else {
System.out.println("Please enjoy your life, you don't need to work");
}
}
}
}
| true
|
c4700a45d28133f78b5b31023b36cbcb3f97434d
|
Java
|
lyqwhmh2015/jfoenix
|
/src/main/java/com/hzaihua/jfoenix/dao/OctCodeDao.java
|
UTF-8
| 733
| 2.140625
| 2
|
[] |
no_license
|
package com.hzaihua.jfoenix.dao;
import com.hzaihua.jfoenix.entity.OctCode;
import java.util.Date;
import java.util.List;
public interface OctCodeDao {
/**
* 添加一条月统计数据
* */
void insertOctCode(OctCode octCode);
/**
* 根据时间段查询月统计数据
* @startTime 开始时间
* @endTime 结束时间
* */
List<OctCode> queryOctByTime(Date startTime,Date endTime);
/**
* 根据设备编号查询该设备在时间段的月统计数据
* @noiseCode 设备编号
* @startTime 开始时间
* @endTime 结束时间
* */
List<OctCode> queryOctByCodeAndTime(String noiseCode,Date startTime,Date endTime);
OctCode queryAllOct();
}
| true
|
f1f279eba4b319a9a7722e1a3de5bc2ce6ab397e
|
Java
|
Mallaiya/guvi-codekataplayer.github.io
|
/StringAppend.java
|
UTF-8
| 234
| 3.390625
| 3
|
[] |
no_license
|
import java.util.*;
public class StringAppend {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String append = ".";
System.out.println(s.concat(append));
}
}
| true
|
0c35fe847af62c4d95f9cc803042758457c27897
|
Java
|
mars920314/VANET
|
/MPR/src/truck/Configurebuffer.java
|
UTF-8
| 4,228
| 2.140625
| 2
|
[] |
no_license
|
package truck;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import network.check;
public class Configurebuffer {
String ip;
Integer port;
Integer x;
Integer[] links;
// Configurebuffer[] links;
public Configurebuffer(String ip, Integer port, Integer x, Integer[] links){
this.ip=ip;
this.port=port;
this.x=x;
this.links=links;
}
public Configurebuffer(String ip, Integer port, Integer x){
this.ip=ip;
this.port=port;
this.x=x;
}
public static void createconfigure(){
int ii=0, jj=0;
String links=null;
check ck=new check();
int rank=ck.checkrank(Global.selfipadd);
if(rank>-1 && Global.selflineconfigure>-1){
for(int kk=0;kk<Global.size;kk++){
Global.wirelessconnecttable[kk]=null;
}
Global.configurebuffer[Global.selflineconfigure][0]=Global.selfipadd;
Global.configurebuffer[Global.selflineconfigure][1]="10130";
Global.configurebuffer[Global.selflineconfigure][2]=Global.configurefile[rank][1];
for(ii=0;(Global.configurebuffer[ii][0]!=null);ii++){
// System.out.println("configurebuffer"+"+rank+"+Global.configurefile[rank][1]);
// System.out.println("configurebuffer"+"+ii+"+Global.configurebuffer[ii][0]);
if((ii!=Global.selflineconfigure)){
if(Math.abs(Double.parseDouble(Global.configurefile[rank][1])-Double.parseDouble(Global.configurebuffer[ii][2]))<Global.wirelessdistance){
Global.wirelessconnecttable[jj]=Global.configurebuffer[ii][0];
jj++;
if(links==null){
links=Integer.toString(ii);
}
else
links=links.concat(Integer.toString(ii));
}
}
Global.configurebuffer[Global.selflineconfigure][4]=links;
}
}
}
public static void writeconfigure(){
File filew = new File(Global.filepath);
try {
filew.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte writebyte[] = new byte[41];
byte ipbyte[] = new byte[16];
byte portbyte[] = new byte[8];
byte xbyte[] = new byte[8];
byte linkbyte[] = new byte[8];
byte enterbyte[]=new byte[1];
ipbyte=Global.configurebuffer[Global.selflineconfigure][0].getBytes();
System.arraycopy(ipbyte,0,writebyte,0,ipbyte.length);
portbyte=Global.configurebuffer[Global.selflineconfigure][1].getBytes();
System.arraycopy(portbyte,0,writebyte,16,portbyte.length);
xbyte=Global.configurebuffer[Global.selflineconfigure][2].getBytes();
System.arraycopy(xbyte,0,writebyte,24,xbyte.length);
if(Global.configurebuffer[Global.selflineconfigure][4]!=null){
linkbyte=Global.configurebuffer[Global.selflineconfigure][4].getBytes();
System.arraycopy(linkbyte,0,writebyte,32,linkbyte.length);
}
enterbyte="\n".getBytes();
System.arraycopy(enterbyte,0,writebyte,40,enterbyte.length);
/*
try{
FileOutputStream in=new FileOutputStream(file);
try{
in.write("aaaaaaaaaaaaa".getBytes(), 0, "aaaaaaaaaaaaa".getBytes().length);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
RandomAccessFile randomFile = null;
try{
randomFile = new RandomAccessFile(filew, "rws");
try {
if(Global.selflineconfigure!=0){
randomFile.seek(Global.selflineconfigure*41);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
randomFile.write(writebyte,0,writebyte.length);
// System.out.println("Configurebuffer"+"+write+"+writebyte);
randomFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
b357bda71bdcb1d5b7b42b4ed1be3075b2a099c5
|
Java
|
blancrob/prog6-bridge_malgache
|
/bridge/Carte.java
|
UTF-8
| 4,100
| 2.734375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bridge;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javafx.scene.Parent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Carte extends Parent implements Cloneable, Serializable{
int valeur;
int couleur;
boolean visible;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private final double largeur_scene = screenSize.getWidth();
private final double hauteur_scene = screenSize.getHeight();
//final int hauteur_carte = 165;
//final int largeur_carte = 135;
int hauteur_carte = (int)(hauteur_scene/5.45);
int largeur_carte = (int)(largeur_scene/14.223);
static final int V=11;
static final int D=12;
static final int R=13;
static final int AS=14;
static final int PIQUE=4;
static final int COEUR=3;
static final int CARREAU=2;
static final int TREFLE=1;
Rectangle face, dos;
public Carte(){
valeur = 0;
couleur = 0;
visible = false;
}
public Carte(int couleur, int valeur, boolean visible){
this.valeur = valeur;
this.couleur = couleur;
this.visible = visible;
face = new Rectangle(largeur_carte,hauteur_carte,Color.TRANSPARENT);
dos = new Rectangle(largeur_carte,hauteur_carte,Color.TRANSPARENT);
this.getChildren().add(face);
this.getChildren().add(dos);
}
@Override
public Carte clone(){
Carte res = new Carte();
res.valeur = valeur;
res.couleur = couleur;
res.visible = visible;
return res;
}
private void writeObject(final ObjectOutputStream out) throws IOException{
out.writeInt(this.valeur);
out.writeInt(this.couleur);
out.writeBoolean(this.visible);
out.writeInt(this.hauteur_carte);
out.writeInt(this.largeur_carte);
out.writeDouble(face.getArcHeight());
out.writeDouble(face.getArcWidth());
out.writeDouble(face.getHeight());
out.writeDouble(face.getWidth());
out.writeDouble(face.getX());
out.writeDouble(face.getY());
out.writeDouble(dos.getArcHeight());
out.writeDouble(dos.getArcWidth());
out.writeDouble(dos.getHeight());
out.writeDouble(dos.getWidth());
out.writeDouble(dos.getX());
out.writeDouble(dos.getY());
}
/**
* Deserialize this instance from input stream.
*
* @param in Input Stream from which this instance is to be deserialized.
* @throws IOException Thrown if error occurs in deserialization.
* @throws ClassNotFoundException Thrown if expected class is not found.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException
{
face = new Rectangle();
dos = new Rectangle();
this.valeur = in.readInt();
this.couleur = in.readInt();
this.visible = in.readBoolean();
this.hauteur_carte = in.readInt();
this.largeur_carte = in.readInt();
this.face.setArcHeight(in.readDouble());
this.face.setArcWidth(in.readDouble());
this.face.setHeight(in.readDouble());
this.face.setWidth(in.readDouble());
this.face.setX(in.readDouble());
this.face.setY(in.readDouble());
this.dos.setArcHeight(in.readDouble());
this.dos.setArcWidth(in.readDouble());
this.dos.setHeight(in.readDouble());
this.dos.setWidth(in.readDouble());
this.dos.setX(in.readDouble());
this.dos.setY(in.readDouble());
}
void setFill(Color web) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| true
|
b9899df14a1b26ee8c1e8908a374b345bca1c05e
|
Java
|
hpbpad/hpbpad-Android
|
/src/com/justsystems/hpb/pad/CustomFragmentStatePagerAdapter.java
|
UTF-8
| 1,961
| 2.34375
| 2
|
[] |
no_license
|
package com.justsystems.hpb.pad;
import java.lang.ref.WeakReference;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class CustomFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
private final int[] blogIds;
private final WeakReference<SiteThumbnailFragment>[] fragments;
public CustomFragmentStatePagerAdapter(FragmentManager fm, int[] blogIds) {
super(fm);
this.blogIds = blogIds;
this.fragments = (WeakReference<SiteThumbnailFragment>[]) new WeakReference<?>[blogIds.length];
}
@Override
public Fragment getItem(int index) {
WeakReference<SiteThumbnailFragment> reference = fragments[index];
SiteThumbnailFragment fragment;
if (reference == null || (fragment = reference.get()) == null) {
fragment = new SiteThumbnailFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", this.blogIds[index]);
fragment.setArguments(bundle);
this.fragments[index] = new WeakReference<SiteThumbnailFragment>(
fragment);
}
return fragment;
}
@Override
public int getCount() {
return this.blogIds.length;
}
/**
* 指定されたインデックスのブログIDを返します。
*
* @param position
* @return
*/
public int getCurrentBlogId(int position) {
return this.blogIds[position];
}
public void onConfigurationChanged() {
for (int i = 0; i < fragments.length; i++) {
WeakReference<SiteThumbnailFragment> reference = fragments[i];
SiteThumbnailFragment fragment;
if (reference == null || (fragment = reference.get()) == null) {
continue;
}
fragment.optimizeImageSize(-1);
}
}
}
| true
|
58a8f8998ab1ec58aa2f05267093d283203cecb3
|
Java
|
Poorvankbhatia/Data-Structures-In-Java
|
/src/trees/tree/FindPossibleInterpretations.java
|
UTF-8
| 4,664
| 4.375
| 4
|
[] |
no_license
|
/*
Find all possible interpretations of an array of digits
Consider a coding system for alphabets to integers where ‘a’ is represented as 1, ‘b’ as 2, .. ‘z’ as 26.
Given an array of digits (1 to 9) as input, write a function that prints all valid interpretations of input array.
Examples
Input: {1, 1}
Output: ("aa", 'k")
[2 interpretations: aa(1, 1), k(11)]
Input: {1, 2, 1}
Output: ("aba", "au", "la")
[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]
Input: {9, 1, 8}
Output: {"iah", "ir"}
[2 interpretations: iah(9,1,8), ir(9,18)]
Please note we cannot change order of array. That means {1,2,1} cannot become {2,1,1}
On first look it looks like a problem of permutation/combination. But on closer look you will figure out that this is an interesting tree problem.
The idea here is string can take at-most two paths:
1. Proces single digit
2. Process two digits
That means we can use binary tree here. Processing with single digit will be left child and two digits will be right child.
If value two digits is greater than 26 then our right child will be null as we don’t have alphabet for greater than 26.
*/
package trees.tree;
import java.util.Arrays;
public class FindPossibleInterpretations {
private static class StringNode {
public String info;
public StringNode left;
public StringNode right;
public StringNode(String info) {
this(info, null, null);
}
public StringNode(String info, StringNode left, StringNode right) {
this.info = info;
this.left = left;
this.right = right;
}
}
private static final String[] alphabet = {"", "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "v", "z"};
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 1, 3, 4};
printLeaves(createTree(0, "", arr));
}
private static StringNode createTree(int data, String parent, int[] arr) {
if (data > 26) {
return null;
}
String dataString = parent + alphabet[data];
StringNode root = new StringNode(dataString);
if (arr.length != 0) {
data = arr[0];
int[] newArray = Arrays.copyOfRange(arr, 1, arr.length);
root.left = createTree(data, dataString, newArray);
if (arr.length > 1) {
data = arr[0] * 10 + arr[1];
// new array will be from index 2 to end as we
// are consuming first two index with this node
newArray = Arrays.copyOfRange(arr, 2, arr.length);
root.right = createTree(data, dataString, newArray);
}
}
return root;
}
private static void printLeaves(StringNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
System.out.println(root.info + " ");
}
printLeaves(root.left);
printLeaves(root.right);
}
}
//Complexity is O(2^n)
/*
The idea here is string can take at-most two paths:
1. Proces single digit
2. Process two digits
That means we can use binary tree here. Processing with single digit will be left child and two digits will be right child.
If value two digits is greater than 26 then our right child will be null as we don’t have alphabet for greater than 26.
Let’s understand with an example .Array a = {1,2,1}. Below diagram shows that how our tree grows.
“” {1,2,1} Codes used in tree
/ \ "a" --> 1
/ \ "b" --> 2
"a"{2,1} "l"{1} "l" --> 12
/ \ / \
/ \ / \
"ab"{1} "au" "la" null
/ \
/ \
"aba" null
Braces {} contain array still pending for processing. Note that with every level, our array size decreases.
If you will see carefully, it is not hard to find that tree height is always n (array size)
How to print all strings (interpretations)? Output strings are leaf node of tree. i.e for {1,2,1}, output is {aba au la}.
We can conclude that there are mainly two steps to print all interpretations of given integer array.
Step 1: Create a binary tree with all possible interpretations in leaf nodes.
Step 2: Print all leaf nodes from the binary tree created in step 1.
*/
| true
|
e25907050c9fc4da31c9172d873d6dba19db4299
|
Java
|
urusy/news-backend
|
/src/main/java/com/urusy/news/entity/DevToUserEntity.java
|
UTF-8
| 585
| 1.710938
| 2
|
[] |
no_license
|
package com.urusy.news.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class DevToUserEntity {
private String name;
private String username;
@JsonProperty("twitter_username")
private String twitterUsername;
@JsonProperty("github_username")
private String githubUsername;
@JsonProperty("website_url")
private String websiteUrl;
@JsonProperty("profile_image")
private String profileImage;
@JsonProperty("profile_image_90")
private String profileImage90;
}
| true
|
d4668012b37d88e8e1ff7f7c37e34bdd364ff38e
|
Java
|
xeon-ye/gztv
|
/Core/src/main/java/com/dfsx/core/AppApiManager.java
|
UTF-8
| 445
| 1.953125
| 2
|
[] |
no_license
|
package com.dfsx.core;
/**
* Created by liuwb on 2016/9/2.
*/
public class AppApiManager {
private static AppApiManager instance = new AppApiManager();
private AppApi appApi;
private AppApiManager() {
}
public void setAppApi(AppApi api) {
this.appApi = api;
}
public static AppApiManager getInstance() {
return instance;
}
public AppApi getAppApi() {
return appApi;
}
}
| true
|
da8f17eb6dff163282ae69866841a4d4c5b7c34e
|
Java
|
YoungDawnGE/LeetCode
|
/src/A400UP/A416_CanPartition/CanPartition.java
|
UTF-8
| 2,398
| 3.78125
| 4
|
[] |
no_license
|
package A400UP.A416_CanPartition;
import java.util.Arrays;
/**
* Created by GYC
* 2021/8/24 13:12
* 416. 分割等和子集
* 给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
*
*
*
* 示例 1:
*
* 输入:nums = [1,5,11,5]
* 输出:true
* 解释:数组可以分割成 [1, 5, 5] 和 [11] 。
* 示例 2:
*
* 输入:nums = [1,2,3,5]
* 输出:false
* 解释:数组不能分割成两个元素和相等的子集。
*
*
* 提示:
*
* 1 <= nums.length <= 200
* 1 <= nums[i] <= 100
*/
public class CanPartition {
public static void main(String[] args) {
// int[] nums = {1, 5, 11, 5};
int[] nums = {1, 2, 3, 8};
System.out.println(new CanPartition().canPartition(nums));
}
//01背包问题
public boolean canPartition(int[] nums) {
int sum = Arrays.stream(nums).sum();
if (sum % 2 != 0) {
return false;
}
//背包的大小
int volume = sum / 2;
//有nums个物品,从这些物品里面取,使其满足正好装满volume大小的背包
//dp[i][j] 表示在1~j中取物品,放到大小为j的背包里,
// 到最后遍历 dp[i][volume]看看是否有dp[i][volume]==volume,有则return true
//转移方程
// 考虑第i个是否要放入背包
//1、NO
// dp[i][j]=dp[i-1][j]
//2、YES
// dp[i][j]=dp[i-1][j-v[i]]+w[i] 本题中的vi和wi相等的 其中j-v[i]>=0
int[][] dp = new int[nums.length + 1][volume + 1];
//初始化第1行 当前容量是j,
for (int j = 1; j <= volume; j++) {
dp[1][j] = nums[0] > j ? 0 : nums[0];
}
//背包问题
for (int i = 2; i <= nums.length; i++) {
for (int j = 1; j <= volume; j++) {
if (j - nums[i-1] >= 0) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i-1]] + nums[i-1]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
//看看是否有dp[i][volume]==volume
for (int i = 2; i <= nums.length; i++) {
if (dp[i][volume] == volume) {
return true;
}
}
return false;
}
}
| true
|
83f34c926dd2785cb3ff4ae1fe39fcddf76d65bc
|
Java
|
kumarvaithi/EaseOnDeliveryAPI
|
/ProviderServicesAPI/src/main/java/com/unimoni/eod/provider/controller/ProviderContoller.java
|
UTF-8
| 3,019
| 2.03125
| 2
|
[] |
no_license
|
package com.unimoni.eod.provider.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.unimoni.eod.provider.bean.BookingConfirmResponseBean;
import com.unimoni.eod.provider.bean.BookingDetailsListBean;
import com.unimoni.eod.provider.bean.CheckInRequestBean;
import com.unimoni.eod.provider.bean.CheckInResponseBean;
import com.unimoni.eod.provider.bean.CommonResponseBean;
import com.unimoni.eod.provider.bean.ServiceProviderBean;
import com.unimoni.eod.provider.impl.BookingImpl;
import com.unimoni.eod.provider.impl.CheckInImpl;
import com.unimoni.eod.provider.impl.SearchRideImpl;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("provider")
public class ProviderContoller {
@Autowired
@Qualifier("checkIn")
CheckInImpl checkin;
@Autowired
@Qualifier("booking")
BookingImpl bookingImpl;
@Autowired
@Qualifier("searchRide")
SearchRideImpl searchRide;
@PostMapping(value="/accept")
private BookingConfirmResponseBean accept(@RequestBody ServiceProviderBean serviceProviderBean) {
BookingConfirmResponseBean response = bookingImpl.bookingConfirm(serviceProviderBean);
return response;
}
@PostMapping(value="/reject")
private String reject() {
return "Electronic Items waiting for delivery, kindly confirm";
}
@GetMapping(value="/searchRide/{providerID}/{status}")
private BookingDetailsListBean searchRide(@PathVariable int providerID,@PathVariable String status) {
System.out.println("provider id is " + providerID + " status is " + status);
BookingDetailsListBean response = searchRide.searchRide(providerID,status);
return response;
}
@GetMapping(value="/view/{bookingID}")
private BookingDetailsListBean viewBooking(@PathVariable int bookingID) {
BookingDetailsListBean response = searchRide.viewBooking(bookingID);
return response;
}
@PostMapping(value="/checkin")
private CheckInResponseBean checkin(@Valid @RequestBody CheckInRequestBean request) {
checkin.checkIn(request);
return null;
}
@GetMapping(value="/verify/{providerID}/{bookingID}/{userType}/{pin}")
private CommonResponseBean verifyOTP(@PathVariable String userType,@PathVariable int providerID,@PathVariable int bookingID,@PathVariable int pin) {
System.out.println("User Type - " + userType + "otp - " + pin);
CommonResponseBean commonResponse = searchRide.verifyPIN(userType, providerID,bookingID, pin);
return commonResponse;
}
}
| true
|
773a09e7fcc78e80358b6303024c3e8e7a33bd0e
|
Java
|
FilippTurbanov/MyResidence
|
/messenger/api/IMessage.java
|
UTF-8
| 246
| 2.015625
| 2
|
[] |
no_license
|
package messenger.api;
import messenger.User;
import messenger.data.MessageType;
import java.util.Date;
public interface IMessage<Message> {
Message getMessage();
Date getDate();
User getUser();
MessageType getMessageType();
}
| true
|
b67ce37c9e0b9c4cd499a520e9dd1eca25717d40
|
Java
|
fatihyildizhan/mongolastic
|
/src/main/java/com/kodcu/listener/BulkProcessorListener.java
|
UTF-8
| 1,103
| 2.125
| 2
|
[
"MIT"
] |
permissive
|
package com.kodcu.listener;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by Hakan on 5/21/2015.
*/
public class BulkProcessorListener implements BulkProcessor.Listener {
private final Logger logger = LoggerFactory.getLogger(BulkProcessorListener.class);
@Override
public void beforeBulk(long executionId, BulkRequest request) {
}
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
if (response.hasFailures()) {
logger.error(response.buildFailureMessage());
} else {
logger.info(String.format("Data transfer successfully terminated.(%d)", response.getItems().length));
}
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
logger.error("Transfer failed.");
logger.error(failure.getMessage(), failure.fillInStackTrace());
}
}
| true
|
5c3de277bca7d503af1598fa8c2e06765cdc8a58
|
Java
|
yyffish/ArithmeticGenerators
|
/src/com/AG/service/FileService.java
|
UTF-8
| 3,029
| 3.25
| 3
|
[] |
no_license
|
package com.AG.service;
import java.util.ArrayList;
import java.util.List;
import com.AG.dao.FileUtils;
public class FileService {
FileUtils fileUtils = new FileUtils();
/**
* 添加序号->转整数->写入到txt中
*
* @param exercisesList 题目List
* @param filePath 文件路径
* @return 是否成功
*/
public boolean writeTxtFile(List<String> exercisesList, String filePath) {
List<String> list = new ArrayList<>();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < exercisesList.size(); i++) {
stringBuffer.append(i + 1);
stringBuffer.append(": ");
stringBuffer.append(exercisesList.get(i));
// 将 9/1 转为整数 9
while (stringBuffer.indexOf("/1 ") != -1) {
int a = stringBuffer.indexOf("/1 ");
stringBuffer.delete(a, a + 2);
}
// 保证将最后一个 /1 也删掉
int last = stringBuffer.lastIndexOf("/1");
if (last + 2 == stringBuffer.length()) {
stringBuffer.delete(last, last + 2);
}
// 添加到List中
list.add(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
// 写入
if (fileUtils.writeTxtFile(list, filePath)) {
return true;
} else {
return false;
}
}
/**
* 将含有 9/1 的表达式List转为 9 的List 用于前端展示
*
* @param exercisesList 题目List
* @return 含有整数的题目List
*/
public List<String> toInt(List<String> exercisesList) {
List<String> list = new ArrayList<>();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < exercisesList.size(); i++) {
stringBuffer.append(exercisesList.get(i));
// 将 9/1 转为整数 9
while (stringBuffer.indexOf("/1 ") != -1) {
int a = stringBuffer.indexOf("/1 ");
stringBuffer.delete(a, a + 2);
}
// 保证将最后一个 /1 也删掉
int last = stringBuffer.lastIndexOf("/1");
if (last + 2 == stringBuffer.length()) {
stringBuffer.delete(last, last + 2);
}
// 添加到List中
list.add(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
return list;
}
/**
* 读取文件后删除序号
*
* @param filePath 文件路径
* @return
*/
public List<String> readTxtFile(String filePath) {
List<String> txtList = fileUtils.readTxtFile(filePath);
List<String> list = new ArrayList<>();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < txtList.size(); i++) {
stringBuffer.append(txtList.get(i));
stringBuffer.delete(0, stringBuffer.indexOf(":") + 2);
String[] expressArr = stringBuffer.toString().split(" ");
stringBuffer.delete(0, stringBuffer.length());
int length = expressArr.length;
for (int j = 0; j < length; j++) {
if (expressArr[j].matches("^-?\\d+$")) {
expressArr[j] = expressArr[j] + "/1";
}
stringBuffer.append(expressArr[j]);
if (j != (length - 1)) {
stringBuffer.append(" ");
}
}
list.add(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
}
return list;
}
}
| true
|
a7eece2a2c45a7bdc22de43c92acf761d6062d30
|
Java
|
hahan2020/dbrw
|
/dbrw/src/main/java/org/qingshan/dbrw/datamap/FloatPrepare.java
|
UTF-8
| 347
| 2.125
| 2
|
[] |
no_license
|
package org.qingshan.dbrw.datamap;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.eyuanku.web.framework.storage.db.IPrepare;
class FloatPrepare implements IPrepare {
@Override
public void prepare(PreparedStatement ps, int index, Object obj) throws SQLException {
ps.setFloat(index, (Float)obj);
}
}
| true
|
a6fbf41d20233385f85ce1ce8165a55c0be0145b
|
Java
|
MarselAhmetov/DebtCounter
|
/src/main/java/team404/project/service/interfaces/ChatMessageService.java
|
UTF-8
| 271
| 1.851563
| 2
|
[] |
no_license
|
package team404.project.service.interfaces;
import team404.project.model.ChatMessage;
import team404.project.model.User;
import java.util.List;
public interface ChatMessageService {
void save(ChatMessage chatMessage);
List<ChatMessage> getByUser(User user);
}
| true
|
31129ec24a4e146cb9ef8da44db6a37af4987fdc
|
Java
|
liuleiliuzhaoyang/FourStages1
|
/FourStagesController/src/main/java/com/qf/controller/ProjectController.java
|
UTF-8
| 1,390
| 2.015625
| 2
|
[] |
no_license
|
package com.qf.controller;
import com.qf.dto.UserProject;
import com.qf.pojo.Project;
import com.qf.pojo.Userinfo;
import com.qf.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class ProjectController {
@Autowired
ProjectService projectService;
@RequestMapping("sss")
public List<Project> selectBy(){
List<Project> list=projectService.selectByExamplea();
return list;
}
@RequestMapping("ccc")
public List<Project> selectBySong(){
List<Project> list=projectService.selectBySong();
return list;
}
@RequestMapping("bbb")
public List<Project> selectByZhan(){
List<Project> list= projectService.selectByZhan();
return list;
}
@RequestMapping("ddd")
public UserProject selectByPrimaryKey(@RequestParam Integer projectid,HttpSession session){
Project project = projectService.selectByPrimaryKey(projectid);
UserProject userProject = new UserProject();
userProject.setProject(project);
Userinfo userinfo=(Userinfo)session.getAttribute("userinfo");
userProject.setUserinfo(userinfo);
System.out.println(userProject+"===================");
return userProject;
}
}
| true
|
4c6947f99bcdba26307bea892ca6c804237a3a74
|
Java
|
MazeSolverAIR/NJ3M
|
/AndroidMazeSolver1/interfacesAndEnumerators/src/main/java/hr/foi/nj3m/interfaces/sensors/ILineFollower.java
|
UTF-8
| 178
| 1.8125
| 2
|
[] |
no_license
|
package hr.foi.nj3m.interfaces.sensors;
public interface ILineFollower extends ISensors {
boolean rightSideOut();
boolean leftSideOut();
boolean isOnCrossroad();
}
| true
|
352cc1758618c9b19fc35710446fd13427fa2ad0
|
Java
|
ACINO-H2020/network-orchestrator
|
/apps/orchestrator/web/src/main/java/org/onosproject/orchestrator/dismi/validation/SelectorValidator.java
|
UTF-8
| 5,522
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2018 ACINO Consortium
*
* 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.onosproject.orchestrator.dismi.validation;
import org.onosproject.orchestrator.dismi.primitives.Issue;
import org.onosproject.orchestrator.dismi.primitives.Selector;
import org.onosproject.orchestrator.dismi.primitives.Tracker;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import static org.slf4j.LoggerFactory.getLogger;
public class SelectorValidator extends FieldValidator {
String className = "Selector";
private final Logger log = getLogger(getClass());
@Override
public Object validateAndResolve(Object field, Tracker tracker) {
log.info("Validating and resolving Selector list !");
List<Selector> selectorList = null;
if (null == field) {
log.error("Instance of Selector list is null !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.NULLPOINTER,
className);
return null;
}
if (!(field instanceof List)) {
log.error("Invalid instance of Selector list !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.OBJECT_IS_NOT_A_SELECTOR_LIST,
className);
return null;
}
selectorList = (List<Selector>) field;
if (selectorList.size() <= 0) {
log.error("Selector list is empty !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.INVALIDVALUE,
className);
return null;
}
if (null == tracker) {
log.error("Tracker of Selector list is null !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.NULLPOINTER,
className);
return null;
}
//log.info("Selector list validation and resolution process completed !");
return validateAndResolveList(selectorList, tracker);
}
private Selector validateAndResolveSelector(Selector selector, Tracker tracker) {
Selector resolvedSelector;
Vocabulary vocabulary = new Vocabulary();
if (null == selector) {
log.error("Instance of Selector is null !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.NULLPOINTER,
className);
return null;
}
FieldValidator fieldValidator
= vocabulary.getValidator(Vocabulary.SELECTOR, selector.getClass());
if (null == fieldValidator) {
log.error(selector.getClass() + " selector is not registered !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.OBJECTISNOTASELECTOR,
className);
return null;
}
Object resolvedObj = fieldValidator.validateAndResolve(selector, tracker);
if (null == resolvedObj) {
log.error("Invalid selector !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.RESOLUTIONFAILED,
selector.toString());
} else if (!(resolvedObj instanceof Selector)) {
log.error("*Invalid selector !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.OBJECTISNOTACONSTRAINT,
selector.toString());
}
return (Selector) resolvedObj;
}
private List<Selector> validateAndResolveList(List<Selector> selectorList, Tracker tracker) {
List<Selector> selectorListExtended = new ArrayList<Selector>();
Selector resolvedSelector;
if (null == selectorList) {
log.error("Selector list is not valid !");
tracker.addIssue(className,
Issue.SeverityEnum.ERROR,
Issue.ErrorTypeEnum.NULLPOINTER,
"List<Selector>");
return selectorListExtended;
}
for (Selector selector : selectorList) {
resolvedSelector = validateAndResolveSelector(selector, tracker);
if (null != resolvedSelector) {
selectorListExtended.add(resolvedSelector);
} else {
log.error("Invalid validated and resolved Selector list !");
}
}
return selectorListExtended;
}
}
| true
|
a82c31b938db4b287f530afdfdaabd1b0f77d1f5
|
Java
|
scalpovich/TechLarning
|
/src/main/java/com/mastercard/pts/integrated/issuing/pages/agent/channelmanagement/AbstractAgentPage.java
|
UTF-8
| 3,316
| 1.75
| 2
|
[] |
no_license
|
package com.mastercard.pts.integrated.issuing.pages.agent.channelmanagement;
import java.util.Collection;
import java.util.Collections;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import com.mastercard.pts.integrated.issuing.pages.AbstractBasePage;
import com.mastercard.pts.integrated.issuing.utils.WebElementUtils;
import com.mastercard.testing.mtaf.bindings.element.ElementsBase.FindBy;
import com.mastercard.testing.mtaf.bindings.element.MCWebElement;
import com.mastercard.testing.mtaf.bindings.page.PageElement;
public class AbstractAgentPage extends AbstractBasePage {
private static final Logger logger = LoggerFactory.getLogger(AbstractAgentPage.class);
@Value("${default.wait.timeout_in_sec}")
protected long timeoutInSec;
@PageElement(findBy = FindBy.CSS, valueToFind = "div .Title")
protected MCWebElement masterDetailContentTitle;
@PageElement(findBy = FindBy.CSS, valueToFind = "select[id='agencyId']")
protected MCWebElement agencyIdDwn;
@PageElement(findBy = FindBy.CSS, valueToFind = "select[id='branchId']")
protected MCWebElement branchIdDwn;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='Id']")
protected MCWebElement agentIdTxt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='Name']")
protected MCWebElement agentNameTxt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='address1']")
protected MCWebElement address1Txt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='address2']")
protected MCWebElement address2Txt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='address3']")
protected MCWebElement address3Txt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='address4']")
protected MCWebElement address4Txt;
@PageElement(findBy = FindBy.CSS, valueToFind = "select[id='country']")
protected MCWebElement countryDwn;
@PageElement(findBy = FindBy.NAME, valueToFind = "city")
protected MCWebElement cityTxt;
@PageElement(findBy = FindBy.NAME, valueToFind = "state")
protected MCWebElement stateTxt;
@PageElement(findBy = FindBy.NAME, valueToFind = "isdCode")
protected MCWebElement isdCodeDDwn;
@PageElement(findBy = FindBy.NAME, valueToFind = "resPhNo")
protected MCWebElement resPhNoTxt;
@PageElement(findBy = FindBy.NAME, valueToFind = "mobileNo")
protected MCWebElement mobileNoTxt;
@PageElement(findBy = FindBy.NAME, valueToFind = "faxNo")
protected MCWebElement faxNoTxt;
@PageElement(findBy = FindBy.NAME, valueToFind = "offPhNo")
protected MCWebElement offPhNoTxt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='EmailID']")
protected MCWebElement emailIdTxt;
@PageElement(findBy = FindBy.CSS, valueToFind = "input[id='PINCode']")
protected MCWebElement postalCodeTxt;
public String getMasterDetailContentTitleText() {
logger.info("Master Detail Tilte Text: {}");
return new WebDriverWait(driver(), timeoutInSec).until(WebElementUtils.visibilityOf(masterDetailContentTitle)).getText();
}
@Override
protected Collection<ExpectedCondition<WebElement>> isLoadedConditions() {
return Collections.emptyList();
}
}
| true
|
c86b5b6f2ec05c066fabc04085fe14ddad1688cf
|
Java
|
songlovelynn/Demo
|
/src/main/java/com/example/demo/modules/sys/mapper/UserMapper.java
|
UTF-8
| 294
| 1.5
| 2
|
[] |
no_license
|
package com.example.demo.modules.sys.mapper;
import com.example.demo.modules.sys.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Louchen
* @since 2019-03-21
*/
public interface UserMapper extends BaseMapper<User> {
}
| true
|
998b7533d6e2c206dc20fca476dc117252ad47e2
|
Java
|
almidesarrollo/Laguntzaile-Digitala
|
/TestGeo/modulomovil/src/main/java/com/example/dam2_yeray/modulomovil/MainWearActivity.java
|
UTF-8
| 2,695
| 1.820313
| 2
|
[] |
no_license
|
package com.example.dam2_yeray.modulomovil;
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import com.example.dam2_yeray.modulomovil.Asyntask.AsynInsert;
import com.example.dam2_yeray.modulomovil.MySqlNiko.MyFunctions;
import com.example.dam2_yeray.modulomovil.PostPhp.PostArray;
import com.example.dam2_yeray.modulomovil.Servicios.ServiceMainMovil;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class MainWearActivity extends WearableActivity {
private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
new SimpleDateFormat("HH:mm", Locale.ENGLISH);
private Button boton;
private boolean pulsado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wear);
setAmbientEnabled();
boton=(Button)findViewById(R.id.btnAyuda);
pulsado=false;
startService(new Intent(this, ServiceMainMovil.class));
/* mTextView = (TextView) findViewById(R.id.text);*/
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boton.setBackground(getDrawable(R.drawable.colorsitosrojospulsados));
PostArray array = MyFunctions.crearPost("incidencia");
array.setValue("cod_incidencia", MyFunctions.INC_AYUD);
AsynInsert asyn = new AsynInsert(array, MyFunctions.URL_INSERT_LOCATION);
pulsado=true;
asyn.execute();
}
});
}
@Override
public void onEnterAmbient(Bundle ambientDetails) {
super.onEnterAmbient(ambientDetails);
updateDisplay();
}
@Override
public void onUpdateAmbient() {
super.onUpdateAmbient();
updateDisplay();
}
@Override
public void onExitAmbient() {
updateDisplay();
super.onExitAmbient();
}
private void updateDisplay() {
if(!pulsado) {
if (isAmbient()) {
/* mTextView.setTextColor(getResources().getColor(android.R.color.white));*/
boton.setBackground(getDrawable(R.drawable.colorsitosrojosapagador));
} else {
// mTextView.setTextColor(getResources().getColor(android.R.color.black));
boton.setBackground(getDrawable(R.drawable.colorsitosrojos));
}
}else
{
boton.setBackground(getDrawable(R.drawable.colorsitosrojospulsados));
}
}
}
| true
|
1a77edbe7980c39a84759a35eaf14ff7cedc814a
|
Java
|
Sourabh789ss/Capgemini
|
/MVCAssignment/Q4/src/main/java/com/javaexcel/service/UserServiceImpl.java
|
UTF-8
| 475
| 2.09375
| 2
|
[] |
no_license
|
package com.javaexcel.service;
import com.javaexcel.dao.UserDao;
import com.javaexcel.model.Login;
import com.javaexcel.model.User;
import org.springframework.beans.factory.annotation.Autowired;
public class UserServiceImpl implements UserService {
@Autowired
public UserDao userDao;
public int register(User user) {
return userDao.register(user);
}
public User validateUser(Login login) {
return userDao.validateUser(login);
}
}
| true
|
2eae968e34a852d54cc5605d94eac4790fe7508c
|
Java
|
vijaykanth12/LendingTreeRepository
|
/LendingTree_MiniApp/src/com/lendingtree/service/BankServiceImpl.java
|
UTF-8
| 1,375
| 2.125
| 2
|
[] |
no_license
|
package com.lendingtree.service;
import java.util.List;
import javax.ejb.Stateless;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.lendingtree.dao.BankDao;
import com.lendingtree.model.Bank;
//@Service("BankService")
@Stateless
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
public class BankServiceImpl implements BankService {
@Autowired
private BankDao bDao;
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
public void addbank(Bank bank) {
// TODO Auto-generated method stub
bDao.addbank(bank);
}
@Override
public List<Bank> getBanks() {
// TODO Auto-generated method stub
return bDao.getBanks();
}
@Override
public List<Bank> getBankId(int id) {
// TODO Auto-generated method stub
return bDao.getBankId(id);
}
@Override
public void editBank(Bank bank) {
// TODO Auto-generated method stub
bDao.editBank(bank);
}
@Override
public void deleteBank(String id) {
// TODO Auto-generated method stub
bDao.deleteBank(id);
}
@Override
public List<Bank> listBanks() {
// TODO Auto-generated method stub
return bDao.listBanks();
}
}
| true
|
7f7edabe301a185206894384148de8cfcd175506
|
Java
|
Maciej-Poleski/Projekt-Programowanie
|
/src/test/java/manager/files/backup/PicasaBackupImplementationTest.java
|
UTF-8
| 1,865
| 2.390625
| 2
|
[] |
no_license
|
package manager.files.backup;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import manager.files.FileID;
import manager.files.FileNotAvailableException;
import manager.files.OperationInterruptedException;
import manager.files.backup.PicasaBackupImpl;
import manager.files.backup.PrimaryBackup;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class PicasaBackupImplementationTest {
@Test
@Ignore
public void testBackup() throws OperationInterruptedException, FileNotAvailableException {
PrimaryBackup original = mock(PrimaryBackup.class);
Set<FileID> ids = new HashSet<>();
FileID id = new FileID();
ids.add(id);
when(original.getListOfAvailableFiles()).thenReturn(ids);
when(original.getFile(id)).thenReturn(new File("src/test/java/manager/files/picasa/dj2.jpg"));
PicasaBackupImpl bi = new PicasaBackupImpl(
original, "projekt.programowanie", "projekt1234", new File("src/test/java/manager/files/picasa/downloaded"));
bi.updateBackup();
System.out.println(bi.getLastBackupUpdateDate());
}
@Test
@Ignore
public void testRetrieve() throws OperationInterruptedException, FileNotAvailableException {
PrimaryBackup original = mock(PrimaryBackup.class);
Set<FileID> ids = new HashSet<>();
FileID id = new FileID();
ids.add(id);
when(original.getListOfAvailableFiles()).thenReturn(ids);
when(original.getFile(id)).thenReturn(new File("src/test/java/manager/files/picasa/dj2.jpg"));
PicasaBackupImpl bi = new PicasaBackupImpl(
original, "projekt.programowanie", "projekt1234", new File("src/test/java/manager/files/picasa/downloaded"));
bi.updateBackup();
System.out.println(bi.getLastBackupUpdateDate());
System.out.println(bi.getFile(id));
}
}
| true
|
7a19df98cfb030d627403050f6e9a2ce96c2c0ac
|
Java
|
shayounala/System-Architecture
|
/src/evaluation/Evaluation.java
|
UTF-8
| 5,197
| 2.296875
| 2
|
[] |
no_license
|
package evaluation;
import java.util.ArrayList;
import java.util.Random;
import component.DataStore;
import component.RAM;
import component.User;
public class Evaluation {
public static int k2;
public static int k3;
public static int CacheUnit;
public static double increase;
private static double PerA;
private static double PerV;
private static double PerT;
private static double PerR;
public static int CA;
public static int PA;
public static int time;
public static int times;
private static int userNumber;
private static int cacheCapacity;
private static int ramCapacity;
private static int ramNumber;
public static Network network;
private static int datastoreNumber;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
initiateEvaluation();
for (time = 0; time < times; time++) {// t is the current time of
// evaluation
System.out.println("Time: " + time);
ArrayList<Request> requests = generateUserRequests(network
.getUsers());
network.getCache().handle(requests);
if (time % 100 == 0) {
network.getCache().updatefactors();
}
}
saveResutls();
}
private static void saveResutls() {
// TODO Auto-generated method stub
double hitrate = network.getCache().getHitsuccess();
hitrate = hitrate / network.getCache().getHits();
System.out.println("Hit rate of Cache: " + hitrate + " "
+ network.getCache().getHitsuccess() + " "
+ network.getCache().getHits());
double averageratios = 0;
int rationumber = 0;
double averagemoveratio = 0;
int movenumber = 0;
double averagedatamoveratio = 0;
int movedatanumber = 0;
for (int i = 0; i < network.getRams().size(); i++) {
RAM ram = network.getRams().get(i);
for (int j = 0; j < ram.getRatios().size(); j++) {
averageratios += ram.getRatios().get(j);
}
rationumber += ram.getRatios().size();
averagemoveratio += ram.getRelationmove();
movenumber += ram.getRelationadd();
averagedatamoveratio += ram.getDatamove();
movedatanumber += ram.getDataadd();
// System.out.println(ram.getUsers().size());
}
averageratios = averageratios / rationumber;
averagemoveratio = averagemoveratio / movenumber;
averagedatamoveratio = averagedatamoveratio / movedatanumber;
System.out.println("Average Ratio: " + averageratios
+ " Average Relation Move Ratio: " + averagemoveratio
+ "Average Data Move Ratio: " + averagedatamoveratio);
int totalspace = 0;
double averagemoveratio1 = 0;
int movenumber1 = 0;
double averagedatamoveratio1 = 0;
int movedatanumber1 = 0;
for (int i = 0; i < network.getDatastores().size(); i++) {
DataStore store = network.getDatastores().get(i);
totalspace += store.getSpace();
averagemoveratio1 += store.getRelationmove();
movenumber1 += store.getRelationadd();
averagedatamoveratio1 += store.getDatamove();
movedatanumber1 += store.getDataadd();
// System.out.println(store.getSpace());
}
System.out.println("Total Space: " + totalspace
+ " Average Relation Move Ratio: " + averagemoveratio1
+ "Average Data Move Ratio: " + averagedatamoveratio1);
System.out.println(hitrate + " " + network.getCache().getHitsuccess()
+ " " + network.getCache().getHits() + " " + averageratios + " "
+ averagemoveratio + " " + averagedatamoveratio + " "
+ totalspace + " " + averagemoveratio1 + " "
+ averagedatamoveratio1);
}
private static void initiateEvaluation() {
// TODO Auto-generated method stub
{
k2 = 2;
k3 = 3;
CacheUnit = 10;
increase = 1.01;
PerA = 0;
PerV = 0.8;
PerT = 0.95;
PerR = 0.99;
CA = 1;
PA = 0;
userNumber = 10000;
cacheCapacity = 12000;
ramCapacity = 10000;
ramNumber = 100;
datastoreNumber = 100;
times = 100;
network = new Network(userNumber, cacheCapacity, ramCapacity,
ramNumber, datastoreNumber);
network.initiateUserInformation();
}
}
private static ArrayList<Request> generateUserRequests(ArrayList<User> users) {
// TODO Auto-generated method stub
ArrayList<Request> requests = new ArrayList<Request>();
for (int userorder = 0; userorder < users.size(); userorder++) {
Random random = new Random();
double randomdouble = random.nextDouble();
if (randomdouble > Evaluation.PerA) {
randomdouble = random.nextDouble();
if (randomdouble < Evaluation.PerV) {
requests.add(new Request(users.get(userorder).getMainkey(),
0));
} else if (randomdouble < Evaluation.PerT) {
requests.add(new Request(users.get(userorder).getMainkey(),
1));
} else if (randomdouble < Evaluation.PerR) {
if (users.get(userorder).getFriends().size() != 0) {
int index = random.nextInt(users.get(userorder)
.getFriends().size());
int mainkey2 = users.get(userorder).getFriends()
.get(index);
requests.add(new Request(users.get(userorder)
.getMainkey(), mainkey2, 2));
}
}
}
}
return requests;
}
}
| true
|
3a6c8c1c660ae20292a0e027bf1fd678e2582d9e
|
Java
|
gcorre02/Quiz
|
/QuizSys/src/main/launchers/LocalMain.java
|
UTF-8
| 1,173
| 3.15625
| 3
|
[] |
no_license
|
package main.launchers;
import main.LocalUserLaunchers.LaunchPlayerLocalVersion;
import main.LocalUserLaunchers.LaunchUserLocalVersion;
import tools.CollectionTools;
import tools.UserInterface;
/**
* Launches a local version of the Quiz System.
*/
public class LocalMain {
/**
*
* @param args the folder where the quiz file system is. if the folder does not exist or is empty, a new one is created.
*/
public static void main(String[] args) {
UserInterface ui = new UserInterface();
launch(args[0], ui);
}
/*
* method separated from main for testing.
*
*/
public static void launch(String source, UserInterface ui){
String[] strs = {"Go to Player Menus","Go to User Menus"};
String choices = CollectionTools.collectionPrinter('S', CollectionTools.toArrayList(strs));
char choice = ui.getUserAnswer(choices);
if(choice == 'A')
LaunchPlayerLocalVersion.main(new String[]{source});
else if(choice == 'B')
LaunchUserLocalVersion.main(new String[]{source});
else
ui.printToUser("Couldn't understand input. Bye");
}
}
| true
|
4ead7fe990942019e2fc3d37a4be02c6801aebdb
|
Java
|
saberwolaopo/wy
|
/test_02.java
|
UTF-8
| 1,083
| 3.03125
| 3
|
[] |
no_license
|
package cn.ginko.wy;
import java.util.Arrays;
import java.util.Scanner;
public class test_02 {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//苹果堆数;
int a[] = new int[n];//每堆苹果的个数;
for(int i = 0;i<n;i++){
a[i] = sc.nextInt();
}
int m = sc.nextInt();//询问次数;
int q[] = new int[m];//想知道;
for(int i = 0;i<m;i++){
q[i] = sc.nextInt();
}
int []sum = new int[n];
sum[0] = a[0];
for(int i = 1;i<n;i++){
sum[i] = a[i]+sum[i-1];
}
int []result = new int[m];
for(int i =0;i<m;i++){
result[i] = know(n,sum,q[i]);
System.out.println(result[i]);
}
}
private static int know(int n, int[] sum, int q) {
int result = Arrays.binarySearch(sum,q);
if(result>=0){
return result+1;
}else{
return -result;
}
}
}
| true
|
1d7750244f6b1401aee19022f1dc0e0855ca1c06
|
Java
|
varya1441/bsu_by
|
/sem4/lab8Game/src/com/tihonova/game/first/Bullet.java
|
UTF-8
| 202
| 2.34375
| 2
|
[] |
no_license
|
package com.tihonova.game.first;
import java.awt.*;
public class Bullet extends BasicObject {
@Override
public void tick() {
}
@Override
public void render(Graphics g) {
}
}
| true
|
b64c2cfa134e93da2b299c5f3f6c13ea6714e08f
|
Java
|
DrSilence/IrcBot
|
/src/de/drsilence/irclib/IrcConnection.java
|
UTF-8
| 10,632
| 2.578125
| 3
|
[] |
no_license
|
package de.drsilence.irclib;
import java.lang.Runnable;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IrcConnection implements Runnable {
private static final String NEWLINE = "\r\n";
private BufferedWriter _writer = null;
private BufferedReader _reader = null;
private ReentrantLock _lock_writer = new ReentrantLock();
private ReentrantLock _lock_reader = new ReentrantLock();
private ArrayList<IrcActionEvent> _actionHandlers = new ArrayList<IrcActionEvent>();
private Boolean _printDebug = false;
private Pattern pattern = Pattern.compile(
"(?<rawmessage>\\:(?<source>((?<nick>[^!]+)![~]{0,1}(?<user>[^@]+)@)?(?<host>[^\\s]+)) " +
"(?<command>[^\\s]+)( )?(?<parameters>[^:]+){0,1}(:)?(?<text>[^\\r^\\n]+)?)"
);
public void addIrcActionEvent(IrcActionEvent e) {
_actionHandlers.add(e);
}
public void removeIrcActionEvent(IrcActionEvent e) {
_actionHandlers.remove(e);
}
public void connect(String server, String nick, String login, String pass) {
Socket socket;
try {
// Connect directly to the IRC server.
socket = new Socket(server, 6667);
_writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream( ) ) );
_reader = new BufferedReader( new InputStreamReader(socket.getInputStream( ) ) );
} catch ( IOException e ) {
e.printStackTrace();
}
// Log on to the server.
irc_send_raw( "USER " + login + " 8 * : " + NEWLINE );
irc_send_raw( "PASS " + pass + NEWLINE );
irc_send_raw( "NICK " + nick + NEWLINE );
}
public void run() {
String line = null;
// Keep reading lines from the server.
while( (line = irc_read_raw( )) != null ) {
///TODO: Remove Emergency exit.
// Emergency exit.
if ( (line.indexOf("@!quit") > 0) && (line.indexOf("dr_silence") > 0) ) {
irc_send_raw( "QUIT :" + NEWLINE );
}
// Handle raw message:
_handle_raw_message( line );
}
}
private Matcher _parse_raw_message(String msg_raw) {
Matcher m = pattern.matcher(msg_raw);
if( m.matches( ) && _printDebug ) {
_print_raw_matcher(m);
}
return m;
}
private Matcher _print_raw_matcher(Matcher m) {
if( m.matches( ) ) {
System.out.println( "<rawmessage> " + m.group("rawmessage") );
System.out.println( "<source> " + m.group("source") );
System.out.println( "<nick> " + m.group("nick") );
System.out.println( "<user> " + m.group("user") );
System.out.println( "<host> " + m.group("host") );
System.out.println( "<command> " + m.group("command") );
System.out.println( "<parameters> " + m.group("parameters") );
System.out.println( "<text> " + m.group("text") );
System.out.println( "=========================================" );
}
return m;
}
private void _handle_raw_message(String line) {
if(line.startsWith(":")) {
// Server -> Client msg.
///TODO: fix problem with matcher not being able to macht '^' in <text> -> no match in <command>
Matcher matcher = _parse_raw_message( line/*.replaceAll("[\\^]", "X")*/ );
if( !matcher.matches() ) {
System.err.println("Error: Cant match raw line -> '"+line+"'");
return ;
}
String command = matcher.group("command").trim();
if( command.matches("\\d+") ) {
// Reply.
IrcReplies reply = IrcReplies.getEnumByValue( Integer.parseInt( command ) );
_handle_reply( reply, matcher );
} else {
IrcMessages message = IrcMessages.getEnumByValue( command );
_handle_messages( message, matcher );
}
} else {
// PING or Client->Client.
if( line.toUpperCase().startsWith("PING ") ) {
// We must respond to PINGs to avoid being disconnected.
irc_send_raw( "PONG " + line.substring(5) + NEWLINE );
}
};
}
private void _handle_reply(IrcReplies r, Matcher m) {
switch(r) {
case ERR_ALREADYREGISTRED:
case ERR_BADCHANMASK:
case ERR_BADCHANNELKEY:
case ERR_BANNEDFROMCHAN:
case ERR_CANNOTSENDTOCHAN:
case ERR_CANTKILLSERVER:
case ERR_CHANNELISFULL:
case ERR_CHANOPRIVSNEEDED:
case ERR_ERRONEUSNICKNAME:
case ERR_FILEERROR:
case ERR_INVITEONLYCHAN:
case ERR_KEYSET:
case ERR_NEEDMOREPARAMS:
case ERR_NICKCOLLISION:
case ERR_NICKNAMEINUSE:
case ERR_NOADMININFO:
case ERR_NOLOGIN:
case ERR_NOMOTD:
case ERR_NONICKNAMEGIVEN:
case ERR_NOOPERHOST:
case ERR_NOORIGIN:
case ERR_NOPERMFORHOST:
case ERR_NOPRIVILEGES:
case ERR_NORECIPIENT:
case ERR_NOSERVICEHOST:
case ERR_NOSUCHCHANNEL:
case ERR_NOSUCHNICK:
case ERR_NOSUCHSERVER:
case ERR_NOTDEFINED:
case ERR_NOTEXTTOSEND:
case ERR_NOTONCHANNEL:
case ERR_NOTOPLEVEL:
case ERR_NOTREGISTERED:
case ERR_PASSWDMISMATCH:
case ERR_SUMMONDISABLED:
case ERR_TOOMANYCHANNELS:
case ERR_TOOMANYTARGETS:
case ERR_UMODEUNKNOWNFLAG:
case ERR_UNKNOWNCOMMAND:
case ERR_UNKNOWNMODE:
case ERR_USERNOTINCHANNEL:
case ERR_USERONCHANNEL:
case ERR_USERSDISABLED:
case ERR_USERSDONTMATCH:
case ERR_WASNOSUCHNICK:
case ERR_WILDTOPLEVEL:
case ERR_YOUREBANNEDCREEP:
case ERR_YOUWILLBEBANNED:
case RPL_ADMINEMAIL:
case RPL_ADMINLOC1:
case RPL_ADMINLOC2:
case RPL_ADMINME:
case RPL_AWAY:
case RPL_BANLIST:
case RPL_CHANNELMODEIS:
case RPL_CLOSEEND:
case RPL_CLOSING:
case RPL_ENDOFBANLIST:
case RPL_ENDOFINFO:
case RPL_ENDOFLINKS:
case RPL_ENDOFMOTD:
case RPL_ENDOFNAMES:
case RPL_ENDOFSERVICES:
case RPL_ENDOFSTATS:
case RPL_ENDOFUSERS:
case RPL_ENDOFWHO:
case RPL_ENDOFWHOIS:
case RPL_ENDOFWHOWAS:
case RPL_INFO:
case RPL_INFOSTART:
case RPL_INVITING:
case RPL_ISON:
case RPL_KILLDONE:
case RPL_LINKS:
case RPL_LIST:
case RPL_LISTEND:
case RPL_LISTSTART:
case RPL_LUSERCHANNELS:
case RPL_LUSERCLIENT:
case RPL_LUSERME:
case RPL_LUSEROP:
case RPL_LUSERUNKNOWN:
case RPL_MOTD:
case RPL_MOTDSTART:
case RPL_MYPORTIS:
case RPL_NAMREPLY:
case RPL_NONE:
case RPL_NOTOPIC:
case RPL_NOUSERS:
case RPL_NOWAWAY:
case RPL_REHASHING:
case RPL_SERVICE:
case RPL_SERVICEINFO:
case RPL_SERVLIST:
case RPL_SERVLISTEND:
case RPL_STATSCLINE:
case RPL_STATSCOMMANDS:
case RPL_STATSHLINE:
case RPL_STATSILINE:
case RPL_STATSKLINE:
case RPL_STATSLINKINFO:
case RPL_STATSLLINE:
case RPL_STATSNLINE:
case RPL_STATSOLINE:
case RPL_STATSQLINE:
case RPL_STATSUPTIME:
case RPL_STATSYLINE:
case RPL_SUMMONING:
case RPL_TIME:
case RPL_TOPIC:
case RPL_TRACECLASS:
case RPL_TRACECONNECTING:
case RPL_TRACEHANDSHAKE:
case RPL_TRACELINK:
case RPL_TRACELOG:
case RPL_TRACENEWTYPE:
case RPL_TRACEOPERATOR:
case RPL_TRACESERVER:
case RPL_TRACEUNKNOWN:
case RPL_TRACEUSER:
case RPL_UMODEIS:
case RPL_UNAWAY:
case RPL_USERHOST:
case RPL_USERS:
case RPL_USERSSTART:
case RPL_VERSION:
case RPL_WHOISCHANNELS:
case RPL_WHOISCHANOP:
case RPL_WHOISIDLE:
case RPL_WHOISOPERATOR:
case RPL_WHOISSERVER:
case RPL_WHOISUSER:
case RPL_WHOREPLY:
case RPL_WHOWASUSER:
case RPL_YOUREOPER:
default:
for( IrcActionEvent e : _actionHandlers ) {
e.eventNumeric(this, r, m);
e.eventRaw(this, m );
}
break;
}
}
private void _handle_messages(IrcMessages m, Matcher mm) {
switch(m) {
case MSG_UNKNOWN:
case MSG_ADMIN:
case MSG_AWAY:
case MSG_CONNECT:
case MSG_DIE:
case MSG_ERROR:
case MSG_INFO:
case MSG_INVITE:
case MSG_ISON:
case MSG_JOIN:
case MSG_KICK:
case MSG_KILL:
case MSG_LINKS:
case MSG_LIST:
case MSG_LUSERS:
case MSG_MODE:
case MSG_MOTD:
case MSG_NAMES:
case MSG_NICK:
case MSG_NOTICE:
case MSG_OPER:
case MSG_PART:
case MSG_PASS:
case MSG_PING:
case MSG_PONG:
case MSG_PRIVMSG:
case MSG_QUIT:
case MSG_REHASH:
case MSG_RESTART:
case MSG_SERVICE:
case MSG_SERVLIST:
case MSG_SQUERY:
case MSG_SQUIT:
case MSG_STATS:
case MSG_SUMMON:
case MSG_TIME:
case MSG_TOPIC:
case MSG_TRACE:
case MSG_USER:
case MSG_USERHOST:
case MSG_USERS:
case MSG_VERSION:
case MSG_WALLOPS:
case MSG_WHO:
case MSG_WHOIS:
case MSG_WHOWAS:
default:
for( IrcActionEvent e : _actionHandlers ) {
e.eventMsg(this, m, mm);
e.eventRaw(this, mm );
}
break;
}
}
public void irc_send_raw(String msg) {
if( _writer == null) {
return ;
}
_lock_writer.lock();
try {
_writer.write(msg);
_writer.flush( );
} catch (IOException e) {
e.printStackTrace();
}
_lock_writer.unlock();
}
public String irc_read_raw() {
String ret = null;
_lock_reader.lock();
try {
ret = _reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
_lock_reader.unlock();
return ret;
}
// Managing the IRC channels: joining, leaving, inviting
public void irc_cmd_join(String channel) { irc_send_raw( "JOIN " + channel + NEWLINE ); }
public void irc_cmd_part(String channel) { irc_send_raw( "PART " + channel + NEWLINE ); }
// irc_cmd_invite
public void irc_cmd_names(String channel) { irc_send_raw( "NAMES " + channel + NEWLINE); }
// irc_cmd_list
// irc_cmd_topic
// irc_cmd_channel_mode
// irc_cmd_user_mode
public void irc_cmd_kick(String channel, String name, String comment) { irc_send_raw( "KICK " + channel + " " + name + " :" + comment ); }
// Sending the messages, notices, /me messages and working with CTCP
public void irc_cmd_msg(String target, String text) { irc_send_raw( "PRIVMSG " + target + " :" + text + NEWLINE ); }
// irc_cmd_me
// irc_cmd_notice
// irc_cmd_ctcp_request
// irc_cmd_ctcp_reply
// Miscellaneous: library version, changing nick, quitting
// irc_cmd_nick
// irc_cmd_whois
public void irc_cmd_quit(String msg) { irc_send_raw("QUIT :" + msg + NEWLINE); }
// irc_target_get_nick
// irc_target_get_host
// DCC initiating and accepting chat sessions, sending and receiving files
// irc_dcc_chat
// irc_dcc_msg
// irc_dcc_accept
// irc_dcc_decline
// irc_dcc_sendfile
// irc_dcc_destroy
// private static void test() {
//
// // Read lines from the server until it tells us we have connected.
//// String line = null;
//// while ((line = reader.readLine( )) != null) {
//// if (line.indexOf("004") >= 0) {
//// // We are now logged in.
//// break;
//// }
//// else if (line.indexOf("433") >= 0) {
//// System.out.println("Nickname is already in use.");
//// return;
//// }
//// }
//
// }
}
| true
|
8d3f78e7e40a103985c1c959fdea0de7b3cde42c
|
Java
|
helenavan/AnimJJ
|
/app/src/main/java/com/helenacorp/smiley/MainActivity.java
|
UTF-8
| 1,135
| 2.140625
| 2
|
[] |
no_license
|
package com.helenacorp.smiley;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.nacho91.panningview.HorizontalPanning;
import com.nacho91.panningview.PanningView;
import com.thunderrise.animations.FlipAnimation;
import com.thunderrise.animations.PulseAnimation;
import com.thunderrise.animations.RotateAnimation;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HorizontalPanning panning = new HorizontalPanning(HorizontalPanning.LEFT_TO_RIGHT);
PanningView JJ = (PanningView) findViewById(R.id.JJ);
JJ.setPanning(panning);
JJ.start();
//ImageView JJ = (ImageView)findViewById(R.id.JJ);
FlipAnimation.create().with(JJ)
.setRepeatCount(PulseAnimation.INFINITE)
.setDuration(2000)
.start();
RotateAnimation.create().with(JJ)
.setRepeatCount(RotateAnimation.INFINITE)
.start();
}
}
| true
|
383a8ad11a9bebb2dc02b103c1254ecf641a5969
|
Java
|
Sun940201/SpringSpider
|
/files/Spring_Data_for_Apache_Cassandra/DATACASS-242/spring-cql/src/test/java/org/springframework/cassandra/config/PoolingOptionsFactoryBeanUnitTest.java
|
UTF-8
| 3,282
| 2.109375
| 2
|
[] |
no_license
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.config;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link PoolingOptionsFactoryBean}
*
* @author Sumit Kumar
* @author David Webb
*/
public class PoolingOptionsFactoryBeanUnitTest {
private static final int REMOTE_MIN_SIMULTANEOUS_REQUESTS = 111;
private static final int REMOTE_MAX_SIMULTANEOUS_REQUESTS = 127;
private static final int REMOTE_CORE_CONNECTIONS = 110;
private static final int REMOTE_MAX_CONNECTIONS = 210;
private static final int LOCAL_MIN_SIMULTANEOUS_REQUESTS = 97;
private static final int LOCAL_MAX_SIMULTANEOUS_REQUESTS = 99;
private static final int LOCAL_CORE_CONNECTIONS = 100;
private static final int LOCAL_MAX_CONNECTIONS = 200;
/**
* The max values should be set before setting core values. Otherwise the core values will be compared with the
* default max values which is 8. Same for other min-max properties pairs. This test checks the same.
*
* @throws Exception Any unhandled scenarios will result in a test failure.
* @see DATACASS-176
*/
@Test
public void testAfterPropertiesSet() throws Exception {
PoolingOptionsFactoryBean factoryBean = new PoolingOptionsFactoryBean();
factoryBean.setLocalMaxConnections(LOCAL_MAX_CONNECTIONS);
factoryBean.setLocalCoreConnections(LOCAL_CORE_CONNECTIONS);
factoryBean.setLocalMaxSimultaneousRequests(LOCAL_MAX_SIMULTANEOUS_REQUESTS);
factoryBean.setLocalMinSimultaneousRequests(LOCAL_MIN_SIMULTANEOUS_REQUESTS);
factoryBean.setRemoteMaxConnections(REMOTE_MAX_CONNECTIONS);
factoryBean.setRemoteCoreConnections(REMOTE_CORE_CONNECTIONS);
factoryBean.setRemoteMaxSimultaneousRequests(REMOTE_MAX_SIMULTANEOUS_REQUESTS);
factoryBean.setRemoteMinSimultaneousRequests(REMOTE_MIN_SIMULTANEOUS_REQUESTS);
factoryBean.afterPropertiesSet();
Assert.assertEquals(factoryBean.getLocalMaxConnections().intValue(), LOCAL_MAX_CONNECTIONS);
Assert.assertEquals(factoryBean.getLocalCoreConnections().intValue(), LOCAL_CORE_CONNECTIONS);
Assert.assertEquals(factoryBean.getLocalMaxSimultaneousRequests().intValue(), LOCAL_MAX_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getLocalMinSimultaneousRequests().intValue(), LOCAL_MIN_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getRemoteMaxConnections().intValue(), REMOTE_MAX_CONNECTIONS);
Assert.assertEquals(factoryBean.getRemoteCoreConnections().intValue(), REMOTE_CORE_CONNECTIONS);
Assert.assertEquals(factoryBean.getRemoteMaxSimultaneousRequests().intValue(), REMOTE_MAX_SIMULTANEOUS_REQUESTS);
Assert.assertEquals(factoryBean.getRemoteMinSimultaneousRequests().intValue(), REMOTE_MIN_SIMULTANEOUS_REQUESTS);
}
}
| true
|
10fa6635f2483954e0ebdd13e427bed6af55eaa1
|
Java
|
mangalaxy/mango
|
/src/main/java/com/mangalaxy/mango/service/PasswordManagementService.java
|
UTF-8
| 403
| 1.984375
| 2
|
[
"MIT"
] |
permissive
|
package com.mangalaxy.mango.service;
import com.mangalaxy.mango.domain.dto.request.PasswordChangeRequest;
import com.mangalaxy.mango.domain.dto.response.ApiResponse;
public interface PasswordManagementService {
ApiResponse changePassword(Long userId, PasswordChangeRequest passwordPair);
ApiResponse resetPassword(String email);
ApiResponse setPassword(String passwordToken, String password);
}
| true
|
7bb39553ca5d406d3853cc81d33f19676c483ba7
|
Java
|
tumo17th/acbook
|
/acbook-core/src/main/java/com/acbook/common/enums/ExpenseKind.java
|
UTF-8
| 781
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
package com.acbook.common.enums;
public enum ExpenseKind {
/** 変動費 */
FLOAT(0, "変動費"),
/** 固定費 */
FIXED(1, "固定費");
/** 出費種別ID */
private int expenseKindId;
/** 出費種別名称 */
private String name;
// Constructor /////////////////////////////////////////////////////////////////////////////////////////////////////
private ExpenseKind(int expenseKindId, String name) {
this.expenseKindId = expenseKindId;
this.name = name;
}
public int getExpenseKindId() {
return expenseKindId;
}
public String getName() {
return name;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
| true
|
cc0f58700b600e82e1a3635e58faad78cfe80ffd
|
Java
|
LintaoLu/Stock
|
/Stock2/app/src/main/java/llu25/hawk/iit/stock/fragments/FragmentStock.java
|
UTF-8
| 3,972
| 2.046875
| 2
|
[] |
no_license
|
package llu25.hawk.iit.stock.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import llu25.hawk.iit.stock.MainActivity;
import llu25.hawk.iit.stock.R;
import llu25.hawk.iit.stock.SearchActivity;
import llu25.hawk.iit.stock.adpater.RecyclerViewAdapterStock;
import llu25.hawk.iit.stock.adpater.UserStockDBHandler;
import llu25.hawk.iit.stock.info.StockInfo;
import llu25.hawk.iit.stock.threads.DownloadSingleStock;
import llu25.hawk.iit.stock.threads.DownloadStockName;
public class FragmentStock extends Fragment
{
View view;
private RecyclerView myRecyclerView;
private static List<StockInfo> userSavedStock = new ArrayList<>();
private UserStockDBHandler userStockDBHandler;
private RecyclerViewAdapterStock recyclerViewAdapterStock;
private static boolean flag = false;
private ImageView addStock;
private static final String TAG = "FragmentStock";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.stock_fragment, container, false);
userStockDBHandler = new UserStockDBHandler(getActivity());
myRecyclerView = view.findViewById(R.id.stock_recyclerview);
recyclerViewAdapterStock = new RecyclerViewAdapterStock(getContext(), userSavedStock);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(recyclerViewAdapterStock);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(myRecyclerView.getContext(),
((LinearLayoutManager) layoutManager).getOrientation());
myRecyclerView.addItemDecoration(dividerItemDecoration);
//userStockDBHandler.onUpgrade(userStockDBHandler.getWritableDatabase(), 1, 2);
if(!flag)
{
ArrayList<StockInfo> temp = new ArrayList<>();
try { temp.addAll(userStockDBHandler.loadStockInfo()); }
catch (Exception e) { e.printStackTrace(); }
if(temp.size() == 0) new DownloadSingleStock(this, new StockInfo("FB",
"Facebook Inc."), true, true).execute();
else
{
for(StockInfo e : temp)
{
new DownloadSingleStock(this, new StockInfo(e.getStockSymbol(), e.getCompanyName()),
false, true).execute();
}
}
}
flag = true;
addStock = view.findViewById(R.id.addStockImage);
addStock.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra("SearchType", "HashMap");
startActivity(intent);
}
});
return view;
}
public void updateStockInfoList(StockInfo temp, boolean insertDatabase)
{
userSavedStock.add(temp);
if(insertDatabase) userStockDBHandler.addItem(temp.getStockSymbol(), temp.getCompanyName());
recyclerViewAdapterStock.notifyDataSetChanged();
}
public static List<StockInfo> getUserSavedStock() { return userSavedStock; }
}
| true
|
cf07bf8e2941fa3890c34ea7721cfd7fae77bdba
|
Java
|
lmmoreira/onion-arch-jpa-api-rest
|
/business/src/main/java/br/com/ifood/logistics/fleet/common/Paginator.java
|
UTF-8
| 612
| 2.5625
| 3
|
[] |
no_license
|
package br.com.company.logistics.project.common;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor(staticName = "of")
public class Paginator<T> {
private final List<T> content;
private final int page;
private final int size;
private final long total;
public <U> Paginator<U> map(final Function<? super T, ? extends U> converter) {
return Paginator.of(content.stream().map(converter).collect(Collectors.toList()), page, size, total);
}
}
| true
|
e4ee92b60de1316c3ad8c1217b581912d624c754
|
Java
|
NolanCarbin/WordSearch
|
/src/main/java/com/techelevator/Board.java
|
UTF-8
| 7,353
| 3.71875
| 4
|
[] |
no_license
|
package com.techelevator;
import java.util.*;
public class Board {
private int rows;
private int cols;
private List<String> words;
private Set<String> guessedWords;
private int correctWordsCounter;
private List<List<String>> board;
private static final String[] ALPHABET = "abcdefghijklmnopqrstuvwxyz".split("");
private static final String LETTER_HOLDER = "#";
public Board(int size){
this.rows = size;
this.cols = size;
this.words = new ArrayList<String>();
this.guessedWords = new HashSet<String>();
this.correctWordsCounter = 0;
this.board = create2DBoard();
}
private List<List<String>> create2DBoard(){
List<List<String>> board = new ArrayList<List<String>>();
for(int i = 0; i < this.rows; i++){
List<String> temp = new ArrayList<String>();
for(int j = 0; j < this.cols; j++){
temp.add(LETTER_HOLDER);
}
board.add(temp);
}
return board;
}
public void addWordsToBoard(){
for(String word : this.words){
word = word.toLowerCase();
boolean wordAdded = false;
while(!wordAdded){
//Get a random startRow, startCol
int randomStartRow = (int)(Math.random() * this.rows);
int randomStartCol = (int)(Math.random() * this.cols);
//Get a random drow, dcol (-1, 0, +1)
int[] direction = {-1, 0, 1};
int randomDirRow = direction[(int)(Math.random() * 3)];
int randomDirCol = direction[(int)(Math.random() * 3)];
wordAdded = insertWordIntoBoard(word, randomStartRow, randomStartCol, randomDirRow, randomDirCol);
System.out.println(wordAdded);
}
}
//fill the remaining "#" with random letters
fillEmptySlots();
}
//Backtracking Method to add a word onto the board
private boolean insertWordIntoBoard(String word, int row, int col, int drow, int dcol){
if(word.length() == 0){
//return true or indicate that the whole word was added
return true;
}
//check if valid
if(row >= 0 && row < this.rows && col >= 0 && col < this.cols){
//get current letter
String currentLetter = Character.toString(word.charAt(0));
String previousLetter = this.board.get(row).get(col);
if(currentLetter.equals(previousLetter) || previousLetter.equals(LETTER_HOLDER)){
//if valid add the letter to the board
this.board.get(row).set(col, currentLetter);
//call function again with substring(1), new row, new col and set equal to solution
boolean solution = insertWordIntoBoard(word.substring(1), row + drow, col + dcol, drow, dcol);
if (solution){
return true;
}
//undo move by setting it back to "#" or previous letter
this.board.get(row).set(col, previousLetter);
}
}
return false;
}
public void fillEmptySlots(){
for(int i = 0; i < this.rows; i++){
for(int j = 0; j < this.cols; j++){
String letter = this.board.get(i).get(j);
if(letter.equals(LETTER_HOLDER)){
int randomIndex = (int)(Math.random() * ALPHABET.length);
String randomLetter = ALPHABET[randomIndex];
this.board.get(i).set(j, randomLetter);
}
}
}
}
public void showBoard(){
System.out.println();
for(int i = 1; i <= this.cols * 2 - 1; i++){
System.out.print("* ");
}
System.out.println();
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board.get(0).size(); j++){
System.out.print(board.get(i).get(j) + " ");
}
System.out.println();
}
for(int i = 1; i <= this.cols * 2 - 1; i++){
System.out.print("* ");
}
System.out.println();
}
public boolean isGameOver(){
for(String correctWord : this.words){
if(!this.guessedWords.contains(correctWord)){
return false;
}
}
System.out.println("\nCONGRATS YOU FOUND ALL OF THE WORDS!\n");
return true;
}
public void addToGuessedWords(String guessedWord){
if(guessedWords.contains(guessedWord)){
System.out.println("\n"+ guessedWord + " was already guessed please try a new word.");
} else if (this.words.contains(guessedWord)){
System.out.println("\n" + guessedWord + " is correct!");
this.guessedWords.add(guessedWord);
this.correctWordsCounter++;
System.out.println(this.correctWordsCounter + " / " + this.words.size() + " guessed!");
} else {
System.out.println("Sorry \"" + guessedWord + "\" is not a valid option.");
}
}
public void showAllWords(){
System.out.print("Words: " + this.words + "\n");
}
public void showGuessedWords(){
System.out.println("Guessed words: " + this.guessedWords + "\n");
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public List<String> getWords() {
return words;
}
public List<List<String>> getBoard(){
return this.board;
}
public void setWords(List<String> words){
this.words = words;
}
// //Used to check if a word is inside of the board
// public boolean searchForWord(String word){
// for(int row = 0; row < rows; row++){
// for (int col = 0; col < cols; col++){
// String result = searchFromCell(word, row, col);
// if (result != null){
// return true;
// }
// }
// }
// return false;
// }
//
// private String searchFromCell(String word, int startRow, int startCol){
// int[] directions = {-1, 0, +1};
// for (int drow : directions) {
// for (int dcol : directions) {
// if (!(drow == 0 && dcol == 0)) {
// String result = searchInDirection(word, startRow, startCol, drow, dcol);
// if (result != null){
// return result;
// }
// }
// }
// }
// return null;
// }
//
// private String searchInDirection(String word, int startRow, int startCol, int drow, int dcol){
// for (int i = 0; i < word.length(); i++){
// int currentRow = startRow + (i * drow);
// int currentCol = startCol + (i * dcol);
// String currentLetterOfWord = Character.toString(word.charAt(i));
// if(currentRow < 0 || currentRow >= this.rows ||
// currentCol < 0 || currentCol >= this.cols ||
// !(this.board.get(currentRow).get(currentCol)).equals(currentLetterOfWord)){
// return null;
// }
// }
// return word;
// }
}
| true
|
bafbc85a54ecb2ee1df26c5a00286f3570705c6f
|
Java
|
xiaoabai/jimyth
|
/src/main/java/com/qzdatasoft/message/controller/loxController.java
|
UTF-8
| 4,976
| 2.125
| 2
|
[] |
no_license
|
///**Copyright: Copyright (c) 2016, 湖南强智科技发展有限公司*/
//package com.qzdatasoft.message.controller;
//
//import java.util.ArrayList;
//import java.util.List;
//
////import com.qzdatasoft.message.pojo.Lox;
////import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.PageRequest;
//import org.springframework.data.domain.Pageable;
//import org.springframework.data.domain.Sort;
//import org.springframework.data.domain.Sort.Direction;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import com.qzdatasoft.framework.annotation.ApiKey;
//import com.qzdatasoft.framework.common.Constants;
//import com.qzdatasoft.framework.common.ReturnMessageDataList;
//import com.qzdatasoft.framework.common.ReturnMessageInfo;
//import com.qzdatasoft.framework.common.annotation.apiversion.ApiVersion;
//
///**
// * 控制类:这是一个测试类<br>
// * History:<br>
// * . 1.0.0.20160913, com.qzdatasoft.koradji, Added: 增加注释<br>
// * . 1.0.0.20160910, com.qzdatasoft.koradji, Create<br>
// */
//@RestController
//@RequestMapping("/api/{version}/lox")
//public class loxController {
//
// private static final String DEFAULT_SORT_COLUMNS = "";
//
//// @Autowired
//// private LoxService service;
//
// /**
// * 根据id获取记录
// * @param id
// * @return 成功返回记录条数(errorcode)和记录(data)
// */
// @ApiVersion(1)
// @ApiKey(IsNew=false,Version=1,ProjectCode="example",GroupCode="lox",
// ApiCode="lox",ApiDescribe="获取一条数据",URL="/api/{version}/lox/{id}",Method="GET",
// DataHead="{'loxId':'编码','pd':'名称'}",Data="{'loxId':'1','pd':'ddddd'}",Param="id:String:记录唯一ID")
// @RequestMapping(value="/{id}", method=RequestMethod.GET)
// public ReturnMessageInfo detail(/*@PathVariable(value="id")*/ String id){
// ReturnMessageInfo result;
//
// Lox data;
// data= new Lox(); data.setName("zhouzq");data.setRemark("sasql");
// //data= service.get(id);
// ReturnMessageDataList ds=
// new ReturnMessageDataList(0,data);
// result=new ReturnMessageInfo(Constants.ERROE_CODE_SUCCESS, ds);
//
// return result;
// }
//
// /**
// * 列表
// * @param id
// * @return
// */
// @ApiVersion(1)
// @ApiKey(Version=1,ProjectCode="example",GroupCode="lox",
// ApiCode="lox",ApiDescribe="根据给定的条件查询数据,目前只支持单字段排序",URL="/api/{version}/lox/sesrch",Method="GET",
// DataHead="{'loxId':'编码','pd':'名称'}",Data="{'loxId':'1','pd':'ddddd'}",
// Param="conditions:String:查询条件(JSON),pagenumber:Integer:页码,pagesize:Integer:页面大小,derection:String:排序:ASC|DESC,orderby:String:排序字段")
// @RequestMapping(value="/sesrch", method=RequestMethod.POST)
// public ReturnMessageInfo list(
// @RequestParam(value="conditions", defaultValue=Constants.CURRENT_PAGE_DEFAULT_STR) String conditions,
// @RequestParam(value="pagenumber", defaultValue=Constants.CURRENT_PAGE_DEFAULT_STR) int pagenumber,
// @RequestParam(value="pagesize", defaultValue=Constants.PAGESIZE_DEFAULT_STR) int pagesize,
// @RequestParam(value="derection", defaultValue="ASC") int derection,
// @RequestParam(value="orderby", defaultValue=DEFAULT_SORT_COLUMNS) String orderby
// ){
//
// ReturnMessageInfo result;
// try{
// String[] _orderBy=orderby.split(",");
// Sort sort=new Sort(Direction.ASC, _orderBy);
// Pageable pageable = new PageRequest(pagenumber,pagesize,sort);
// //List<Lox> data= service.List(pageable);
// List<Lox> data= new ArrayList<Lox>();
// result=new ReturnMessageInfo(Constants.ERROE_CODE_SUCCESS, data);
// }catch(Exception e) {
// result=new ReturnMessageInfo(e.getClass().getName(), e.getMessage());
// }
//
// return result;
// }
//
// /**
// * 新增一批记录,要么全部成功,要么全部失败
// * @param loxs
// * @return 增加成功的记录数和增加成功的记录(data)
// */
// @RequestMapping(value="/create", method=RequestMethod.POST)
// public ReturnMessageInfo post(List<Lox> loxs){
// return null;
// }
//
// /**
// * 根据唯一ID删除一批记录,要么全部成功,要么全部失败
// * @param ids
// * @return 删除成功的记录条数(errorcode)
// */
// @RequestMapping(value="/delete", method=RequestMethod.POST)
// public ReturnMessageInfo delete(List<String> ids){
// return null;
// }
//
// /**
// * 更新一批记录,要么全部成功,要么全部失败
// * @param loxs
// * @return 更新成功的记录数(errorCode)和更新成功的记录(data)
// */
// @RequestMapping(value="/update", method=RequestMethod.POST)
// public ReturnMessageInfo put(List<Lox> loxs){
// return null;
// }
//
//
//
//}
| true
|
4ce8d93f167f9318865dd1bbcf3361767b7a6515
|
Java
|
qc724857958/shardingjdbc-demo
|
/src/main/java/com/simon/ss/controller/OrderController.java
|
UTF-8
| 1,185
| 1.984375
| 2
|
[] |
no_license
|
package com.simon.ss.controller;
import com.simon.ss.dao.OrderMapper;
import com.simon.ss.entity.Order;
import com.simon.ss.params.OrderRequestBody;
import com.simon.ss.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author Jiajie.Mao
* @date 2019/9/11 13:53
**/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping(value = "/getById", method = RequestMethod.GET)
public Object selectById(@RequestParam("orderId") Long orderId){
return orderService.selectById(orderId);
}
@RequestMapping(value = "/getDetailById", method = RequestMethod.GET)
public Object selectDetailById(@RequestParam("orderId") Long orderId){
return orderService.selectDetailById(orderId);
}
@RequestMapping(value = "/all", method = RequestMethod.GET)
public Object queryAll(){
return orderService.queryAll();
}
@PostMapping(value = "/add")
public Boolean insert(@RequestBody OrderRequestBody body){
return orderService.insert(body);
}
}
| true
|
d276fc9a8293e21ed0d066a5ec6296d6c8e69008
|
Java
|
DM2E/dm2e-oai
|
/src/main/java/eu/dm2e/oai/Dm2eOaiApplication.java
|
UTF-8
| 779
| 1.726563
| 2
|
[] |
no_license
|
package eu.dm2e.oai;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.dm2e.grafeo.jaxrs.GrafeoMessageBodyWriter;
public class Dm2eOaiApplication extends Application {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(Dm2eOaiApplication.class);
static {
// GrafeoImpl.addStaticNamespace("fff", NS.FFF.BASE);
}
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(Dm2eOaiService.class);
s.add(MultiPartFeature.class);
s.add(GrafeoMessageBodyWriter.class);
return s;
}
}
| true
|
d57502fd78e3cd314b4061e6dc3b44dcd4bb0a81
|
Java
|
omeravioz/AnimalSoduku
|
/src/TwoTurtles.java
|
WINDOWS-1252
| 852
| 3.609375
| 4
|
[] |
no_license
|
package assignment2_fatma;
import Turtle.*;
public class TwoTurtles {
public static void main (String [] args){
Turtle messi= new Turtle();
Turtle cristiano=new Turtle();
alef(messi);
beit(cristiano);
}
//this function creates "" shape
public static void alef (Turtle t){
t.tailUp();
t.turnRight(90);
t.moveForward(400);
t.turnLeft(135);
t.tailDown();
t.moveForward(40);
t.turnRight(45);
t.moveForward(80);
t.moveBackward(80);
t.turnLeft(45);
t.moveForward(60);
t.turnLeft(135);
t.moveForward(70);
t.moveBackward(70);
t.turnRight(135);
t.moveForward(30);
}
//this function creates "" shape
public static void beit(Turtle t){
t.tailDown();
t.turnLeft(90);
t.moveForward(150);
t.moveBackward(100);
t.turnRight(90);
t.moveForward(75);
t.turnLeft(90);
t.moveForward(100);
}
}
| true
|
871f2b83bd759cfb289863b28535242b64b1b01f
|
Java
|
hneubert/classbuilder
|
/src/test/java/classbuilder/test/builder/ExceptionTest.java
|
UTF-8
| 958
| 2.171875
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
package classbuilder.test.builder;
import static classbuilder.IClass.*;
import org.junit.Test;
import classbuilder.BuilderException;
import classbuilder.BuilderSyntaxException;
import classbuilder.ClassFactory;
import classbuilder.IClass;
import classbuilder.IMethod;
public class ExceptionTest {
private ClassFactory classFactory = new ClassFactory();
@Test(expected=BuilderException.class)
public void noIterable() throws BuilderException {
IClass cls = classFactory.createClass(PUBLIC, "test", "Test", Object.class);
IMethod m = cls.addMethod(PUBLIC, "foo", int.class);
m.ForEach(m.$("foo"));
}
@Test(expected=BuilderSyntaxException.class)
public void unusedExpression() throws BuilderException {
IClass cls = classFactory.createClass(PUBLIC, "test", "Test", Object.class);
IMethod m = cls.addMethod(PUBLIC, "foo", int.class);
m.$(System.class).get("out");
m.End();
cls.build();
}
}
| true
|
6242f097adf4e178919a7bd57bdec65d0d95e743
|
Java
|
yapengsong/business
|
/src-intf/eayun-virtualization-intf/src/main/java/com/eayun/virtualization/apiservice/SecurityGroupApiService.java
|
UTF-8
| 2,844
| 2.3125
| 2
|
[] |
no_license
|
package com.eayun.virtualization.apiservice;
import java.util.List;
import com.eayun.common.exception.AppException;
import com.eayun.virtualization.model.BaseCloudVmSgroup;
import com.eayun.virtualization.model.CloudSecurityGroup;
import com.eayun.virtualization.model.CloudSecurityGroupRule;
import com.eayun.virtualization.model.CloudVm;
public interface SecurityGroupApiService {
/**
* 云主机加入安全组
* @param cloudvm
* @param cloudSecurityGroup
* @throws AppException
*/
public void instanceJoinSecurityGroup(CloudVm cloudVm, CloudSecurityGroup cloudSecurityGroup) throws AppException;
/**
* 云主机离开安全组
* @param cloudvm
* @param cloudSecurityGroup
* @throws AppException
*/
public void instanceLeaveSecurityGroup(CloudVm cloudVm, CloudSecurityGroup cloudSecurityGroup) throws AppException;
/**
* 根据云主机ID和安全组ID获取云主机和安全组关系实体
* @param instaceId
* @param securityGroupId
* @return -- 当vmId为空时,查询条件只有securityGroupId
* -- 当securityGroupId为空时,查询条件只有vmId
* -- 当vmId和securityGroupId都为空时,返回null对象
* -- 当vmId和securityGroupId都不为空时,查询条件有securityGroupId和vmId
* @throws AppException
*/
public List<BaseCloudVmSgroup> getVmSgroupByVmIdAndSecurityGropId(String vmId, String securityGroupId) throws AppException;
/**
* 根据安全组ID获取安全组信息 -- 用于判断该安全组是否属于某客户
* @param securityGroupId
* @return
*/
public CloudSecurityGroup getSecurityGroupBySgId(String securityGroupId) throws AppException;
/**
* 根据条件查询安全组列表
* @param securityGroupIds -- 安全组IDs,中间用","隔开
* @param searchWord -- 安全组名称,模糊查询
* @param offset -- 偏移量
* @param limit -- 数据限制
* @return -- 如果没有符合条件的结果,则返回null对象
* @throws AppException
*/
public List<CloudSecurityGroup> getGroupList(String dcId, String cusId, String [] securityGroupId, String searchWord,
String offset, String limit) throws AppException;
/**
* 根据安全组ID获取安全组的规则
* @param securityGroupRuleId
* @return -- 如果没有符合条件的结果,则返回null对象
* @throws AppException
*/
public List<CloudSecurityGroupRule> getGroupRuleListByGroupId(String securityGroupRuleId) throws AppException;
/**
* 查询项目下默认安全组类型的安全组<br>
* -------------------------------------
*
* @author zhouhaitao
* @param prjId 项目ID
* @param defaultType 默认类型
* @return
*/
public String querySecurityGroupByDefaultAndPrjId(String prjId,String defaultType);
}
| true
|
7c9aa04be91abd8480cb1941b7938e0413d0e262
|
Java
|
JMechergui/design-pattern
|
/src/tn/design/pattern/Adapter/Test.java
|
UTF-8
| 564
| 2.328125
| 2
|
[] |
no_license
|
package tn.design.pattern.Adapter;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Iphone6 iphone6=new Iphone6();
iphone6.setModel("6s");
iphone6.setColor("White");
iphone6.setStorage("64g");
IphoneCharger4Impl phone4Charger=new IphoneCharger4Impl();
IphoneCharger6Impl charge6=new IphoneCharger6Impl();
Iphone6ChargerAdapter chargerAdapter=new Iphone6ChargerAdapter(phone4Charger);
iphone6.charge(chargerAdapter);
}
}
| true
|
0726a0438ae090dcf4ea78b0df365d061da2c74f
|
Java
|
DivanioSilva/swagger
|
/src/main/java/com/ds/swagger/service/PersonService.java
|
UTF-8
| 804
| 2.28125
| 2
|
[] |
no_license
|
package com.ds.swagger.service;
import com.ds.swagger.entities.Person;
import com.ds.swagger.exceptions.PersonNotFoundException;
import com.ds.swagger.exceptions.ValidationException;
import com.ds.swagger.exceptions.WrongPrimaryKeysException;
import java.util.List;
public interface PersonService {
Person save(Person person) throws ValidationException;
Person update(Long id, Person person) throws PersonNotFoundException, WrongPrimaryKeysException, ValidationException;
Person findById(Long id) throws PersonNotFoundException;
List<Person> findAll();
Person findByName(String personName) throws PersonNotFoundException, ValidationException;
void delete(Person person);
void delete(Long id);
Person findByNameV2(String personName) throws ValidationException;
}
| true
|
c3071e924055913dffdc04796eea863fddaaf199
|
Java
|
ashishejale/EdabitChallengeSolutons
|
/Java/Very Easy/Find the Perimeter of a Rectangle.java
|
UTF-8
| 122
| 2.453125
| 2
|
[] |
no_license
|
public class Challenge {
public static int findPerimeter(int length, int width) {
return (2 * (width + length));
}
}
| true
|
7ff159972c0555b5417f00bc3ff84308747bfbcc
|
Java
|
ntejadharma/sample1
|
/TestArray.java
|
UTF-8
| 322
| 2.921875
| 3
|
[] |
no_license
|
class TestArray
{
public static void main(String args[])
{
int a[][]=new int[2]//declaration and instantiation
a[0]=5;//initialization
a[1]=6;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
| true
|
b05426aa76927c793e21a7d1e921541411b7c3fa
|
Java
|
hoangpham1997/ChanDoi
|
/Project/ebweb2019/src/main/java/vn/softdreams/ebweb/web/rest/cashandbank/MCPaymentDetailInsuranceResource.java
|
UTF-8
| 6,461
| 2.1875
| 2
|
[] |
no_license
|
package vn.softdreams.ebweb.web.rest.cashandbank;
import com.codahale.metrics.annotation.Timed;
import vn.softdreams.ebweb.domain.MCPaymentDetailInsurance;
import vn.softdreams.ebweb.service.MCPaymentDetailInsuranceService;
import vn.softdreams.ebweb.web.rest.errors.BadRequestAlertException;
import vn.softdreams.ebweb.web.rest.util.HeaderUtil;
import vn.softdreams.ebweb.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* REST controller for managing MCPaymentDetailInsurance.
*/
@RestController
@RequestMapping("/api")
public class MCPaymentDetailInsuranceResource {
private final Logger log = LoggerFactory.getLogger(MCPaymentDetailInsuranceResource.class);
private static final String ENTITY_NAME = "mCPaymentDetailInsurance";
private final MCPaymentDetailInsuranceService mCPaymentDetailInsuranceService;
public MCPaymentDetailInsuranceResource(MCPaymentDetailInsuranceService mCPaymentDetailInsuranceService) {
this.mCPaymentDetailInsuranceService = mCPaymentDetailInsuranceService;
}
/**
* POST /m-c-payment-detail-insurances : Create a new mCPaymentDetailInsurance.
*
* @param mCPaymentDetailInsurance the mCPaymentDetailInsurance to create
* @return the ResponseEntity with status 201 (Created) and with body the new mCPaymentDetailInsurance, or with status 400 (Bad Request) if the mCPaymentDetailInsurance has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/m-c-payment-detail-insurances")
@Timed
public ResponseEntity<MCPaymentDetailInsurance> createMCPaymentDetailInsurance(@Valid @RequestBody MCPaymentDetailInsurance mCPaymentDetailInsurance) throws URISyntaxException {
log.debug("REST request to save MCPaymentDetailInsurance : {}", mCPaymentDetailInsurance);
if (mCPaymentDetailInsurance.getId() != null) {
throw new BadRequestAlertException("A new mCPaymentDetailInsurance cannot already have an ID", ENTITY_NAME, "idexists");
}
MCPaymentDetailInsurance result = mCPaymentDetailInsuranceService.save(mCPaymentDetailInsurance);
return ResponseEntity.created(new URI("/api/m-c-payment-detail-insurances/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /m-c-payment-detail-insurances : Updates an existing mCPaymentDetailInsurance.
*
* @param mCPaymentDetailInsurance the mCPaymentDetailInsurance to update
* @return the ResponseEntity with status 200 (OK) and with body the updated mCPaymentDetailInsurance,
* or with status 400 (Bad Request) if the mCPaymentDetailInsurance is not valid,
* or with status 500 (Internal Server Error) if the mCPaymentDetailInsurance couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/m-c-payment-detail-insurances")
@Timed
public ResponseEntity<MCPaymentDetailInsurance> updateMCPaymentDetailInsurance(@Valid @RequestBody MCPaymentDetailInsurance mCPaymentDetailInsurance) throws URISyntaxException {
log.debug("REST request to update MCPaymentDetailInsurance : {}", mCPaymentDetailInsurance);
if (mCPaymentDetailInsurance.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
MCPaymentDetailInsurance result = mCPaymentDetailInsuranceService.save(mCPaymentDetailInsurance);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, mCPaymentDetailInsurance.getId().toString()))
.body(result);
}
/**
* GET /m-c-payment-detail-insurances : get all the mCPaymentDetailInsurances.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of mCPaymentDetailInsurances in body
*/
@GetMapping("/m-c-payment-detail-insurances")
@Timed
public ResponseEntity<List<MCPaymentDetailInsurance>> getAllMCPaymentDetailInsurances(Pageable pageable) {
log.debug("REST request to get a page of MCPaymentDetailInsurances");
Page<MCPaymentDetailInsurance> page = mCPaymentDetailInsuranceService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/m-c-payment-detail-insurances");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /m-c-payment-detail-insurances/:id : get the "id" mCPaymentDetailInsurance.
*
* @param id the id of the mCPaymentDetailInsurance to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the mCPaymentDetailInsurance, or with status 404 (Not Found)
*/
@GetMapping("/m-c-payment-detail-insurances/{id}")
@Timed
public ResponseEntity<MCPaymentDetailInsurance> getMCPaymentDetailInsurance(@PathVariable UUID id) {
log.debug("REST request to get MCPaymentDetailInsurance : {}", id);
Optional<MCPaymentDetailInsurance> mCPaymentDetailInsurance = mCPaymentDetailInsuranceService.findOne(id);
return ResponseUtil.wrapOrNotFound(mCPaymentDetailInsurance);
}
/**
* DELETE /m-c-payment-detail-insurances/:id : delete the "id" mCPaymentDetailInsurance.
*
* @param id the id of the mCPaymentDetailInsurance to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/m-c-payment-detail-insurances/{id}")
@Timed
public ResponseEntity<Void> deleteMCPaymentDetailInsurance(@PathVariable UUID id) {
log.debug("REST request to delete MCPaymentDetailInsurance : {}", id);
mCPaymentDetailInsuranceService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}
| true
|
e90782fc60a51df6c68e6808c64fc56cd8540bfd
|
Java
|
caanzola/prueba
|
/MyApplication/app/src/main/java/com/example/myapplication/CircleList.java
|
UTF-8
| 5,495
| 2.078125
| 2
|
[] |
no_license
|
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class CircleList extends AppCompatActivity {
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference collectionReference = db.collection("circles");
//PopupWindow popupWindowCircles;
//Button button = findViewById(R.id.buttonShow);
List list = new ArrayList();
String content[];
public void loadNotes() {
collectionReference.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
String id = documentSnapshot.getId();
Log.d("tag","ID ES ESTE"+id);
/*Circle circle = documentSnapshot.toObject(Circle.class);
String name = circle.getName();
list.add(name);*/
}
//textViewData.setText(data);
}
});
}
/*public PopupWindow popupWindowCircles(){
PopupWindow popupWindow = new PopupWindow(this);
ListView listViewCircles = new ListView(this);
listViewCircles.setAdapter(dogsAdapter(content));
listViewCircles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = view.getContext();
CircleList circleList = ((CircleList)context);
circleList.popupWindowCircles.dismiss();
String selected = ((TextView)view).getTag().toString();
circleList.button.setText(selected);
}
});
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(listViewCircles);
return popupWindow;
}*/
/*private ArrayAdapter<String> dogsAdapter (String circlesArray[]){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, circlesArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item;
// visual settings for the list item
TextView listItem = new TextView(CircleList.this);
listItem.setText(text);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.GREEN);
return listItem;
}
};
return adapter;
}*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circle_list);
loadNotes();
//content = new String[list.size()];
//list.toArray(content);
//popupWindowCircles = popupWindowCircles();
Button circulo = findViewById(R.id.circulo);
Button historial = findViewById(R.id.historial);
Button objeto = findViewById(R.id.objetos);
Button inicio = findViewById(R.id.inicio);
circulo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(CircleList.this, UserList.class));
}
});
objeto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(CircleList.this, ObjectList.class));
}
});
FloatingActionButton buttonAddUser = findViewById(R.id.button_add);
buttonAddUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(CircleList.this, CircleAdd.class));
}
});
historial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(CircleList.this, Historial.class));
}
});
}
}
| true
|
ccfccd89ac8b8169dc274e6b2c5634ebd1c262aa
|
Java
|
donoi2015/CoreJava
|
/src/trees/EmployeeBST.java
|
UTF-8
| 3,209
| 3.953125
| 4
|
[] |
no_license
|
package trees;
import java.util.ArrayList;
public class EmployeeBST {
/** The tree root. */
private Employee root;
// start with an empty tree
private EmployeeBST() {
root = null;
}
/**
* Prints the values in the nodes of the tree in sorted order.
*/
private void printTree() {
if (root == null)
System.out.println("Empty tree");
else
printTree(root);
}
private int size() {
return (size(root));
}
private int size(Employee node) {
if (node == null)
return (0);
else {
return (size(node.left) + 1 + size(node.right));
}
}
private void printTree(Employee t) {
if (t != null) {
printTree(t.left);
System.out.print(t.salary + " ");
printTree(t.right);
}
}
private ArrayList<Integer> printToList() {
ArrayList<Integer> list = new ArrayList<>();
if (root == null)
System.out.println("Empty tree");
else
printToList(root, list);
return list;
}
private void printToList(Employee t, ArrayList<Integer> list) {
if(t!=null){
printToList(t.left,list);
list.add(t.salary);
printToList(t.right,list);
}
}
private boolean find(Integer x) {
return x != null && find(x, root);
}
private boolean find(Integer x, Employee n) {
if (n == null)
return false;
return n != null && n.salary == x || ((x.compareTo(n.salary) < 0) ? find(x, n.left) : find(x, n.right));
// return find(x,n.left) || find(x,n.right);
}
private void insert(Integer x) {
if (root == null) {
root = new Employee(null, x, null, null);
} else {
Employee n = root;
boolean inserted = false;
while (!inserted) {
if (x.compareTo(n.salary) < 0) {
// space found on the left
if (n.left == null) {
n.left = new Employee(null, x, null, null);
inserted = true;
} else {
n = n.left;
}
}
else if (x.compareTo(n.salary) > 0) {
// space found on the right
if (n.right == null) {
n.right = new Employee(null, x, null, null);
inserted = true;
} else {
n = n.right;
}
}
}
}
}
public static void main(String[] args) {
EmployeeBST bst = new EmployeeBST();
for (int i = 15; i >= 0; --i) {
bst.insert(2 * i);
bst.insert(2 * i - 5);
}
bst.printTree();
System.out.println("Size: " + bst.size());
System.out.println("Is 24 in the tree? " + bst.find(24));
System.out.println("Is 27 in the tree? " + bst.find(27));
ArrayList<Integer> list = bst.printToList();
for(int x:list){
System.out.print(x+", ");
}
}
private class Employee implements Comparable<Employee>{
private String name;
private int salary;
private Employee left;
private Employee right;
// Constructors
Employee(int salary) {
this(null, salary, null, null);
}
Employee(String name, int salary, Employee left, Employee right) {
this.name = name;
this.salary = salary;
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object aObj) {
if(aObj == null || getClass()!=aObj.getClass()) return false;
Employee a = (Employee) aObj;
return (this.salary == a.salary);
}
@Override
public int compareTo(Employee aO) {
int sal2 = aO.salary;
return salary - sal2;
}
}
}
| true
|
6be7929d1956bc178686c76776435baa28465d62
|
Java
|
shinelikeamillion/Ten_thousand_hours
|
/PlaneWar/PlaneWar day2/src/com/liufei/planewar/PlaneWarActivity.java
|
UTF-8
| 336
| 1.765625
| 2
|
[] |
no_license
|
package com.liufei.planewar;
import android.app.Activity;
import android.os.Bundle;
public class PlaneWarActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MenuView menuView = new MenuView(this);
setContentView(menuView);
}
}
| true
|
bdbe376f9e41e705d9bbce8602a44f2355af950b
|
Java
|
buyuju/spring-boot-demo
|
/src/main/java/com/example/demo/exception/GlobalExceptionHandler.java
|
UTF-8
| 2,015
| 2
| 2
|
[] |
no_license
|
package com.example.demo.exception;
import com.example.demo.common.DemoRespCode;
import com.example.demo.model.base.ResultJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
@ApiIgnore
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = ClientException.class)
public Object clientException(HttpServletRequest request, HttpServletResponse response, ClientException e) {
logger.error("----------------- ClientParameterException -------------------");
logger.error("code:{}, message:{}, extra: {}", e.getCode(), e.getMessage(), e.getExtra());
return ResultJson.fail(e.getCode(), e.getMessage(), e.getExtra());
}
@ExceptionHandler(value = ServerException.class)
public Object exception(HttpServletRequest request, HttpServletResponse response, ServerException e) {
logger.error("----------------- ServerException -------------------");
logger.error("code:{}, message:{}", e.getCode(), e.getMessage());
response.setStatus(DemoRespCode._066666.getCode());
return ResultJson.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(value = Throwable.class)
public Object serverException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
logger.error("----------------- Throwable -------------------");
logger.error(e.getMessage(), e);
response.setStatus(DemoRespCode._066666.getCode());
return ResultJson.fail(DemoRespCode._066666.getCode(), e.getMessage());
}
}
| true
|
b50b6769f0c64b5d077c2c25e2be3f3460299ee7
|
Java
|
bigfishman/kite
|
/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemUtil.java
|
UTF-8
| 23,686
| 1.828125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2013 Cloudera 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 org.kitesdk.data.spi.filesystem;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.avro.Schema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.Trash;
import org.kitesdk.compat.DynMethods;
import org.kitesdk.data.DatasetDescriptor;
import org.kitesdk.data.DatasetIOException;
import org.kitesdk.data.Format;
import org.kitesdk.data.Formats;
import org.kitesdk.data.IncompatibleSchemaException;
import org.kitesdk.data.PartitionStrategy;
import org.kitesdk.data.ValidationException;
import org.kitesdk.data.spi.Pair;
import org.kitesdk.data.spi.SchemaUtil;
import org.kitesdk.data.spi.Schemas;
import org.kitesdk.data.spi.partition.ProvidedFieldPartitioner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileSystemUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileSystemUtil.class);
private static final List<Format> SUPPORTED_FORMATS = Lists.newArrayList(
Formats.AVRO, Formats.PARQUET, Formats.JSON, Formats.CSV);
/**
* Creates, if necessary, the given the location for {@code descriptor}.
*
* @param conf A Configuration
* @param descriptor A DatasetDescriptor
* @throws DatasetIOException
* @since 0.13.0
*/
public static void ensureLocationExists(
DatasetDescriptor descriptor, Configuration conf) {
Preconditions.checkNotNull(descriptor.getLocation(),
"Cannot get FileSystem for a descriptor with no location");
Path dataPath = new Path(descriptor.getLocation().toString());
FileSystem fs = null;
try {
fs = dataPath.getFileSystem(conf);
} catch (IOException e) {
throw new DatasetIOException(
"Cannot get FileSystem for descriptor: " + descriptor, e);
}
try {
if (!fs.exists(dataPath)) {
fs.mkdirs(dataPath);
}
} catch (IOException e) {
throw new DatasetIOException("Cannot access data location", e);
}
}
static List<Pair<Path, Path>> stageMove(FileSystem fs, Path src,
Path dest, String ext) {
List<Pair<Path, Path>> staged;
try {
// make sure the destination exists
if (!fs.exists(dest)) {
fs.mkdirs(dest);
}
FileStatus[] stats = fs.listStatus(src);
staged = Lists.newArrayList();
for (FileStatus stat : stats) {
if (stat.isDir()) {
continue;
}
Path srcFile = stat.getPath();
Path dotFile = new Path(dest, "." + srcFile.getName() + "." + ext);
Path destFile = new Path(dest, srcFile.getName());
if (fs.rename(srcFile, dotFile)) {
staged.add(Pair.of(dotFile, destFile));
} else {
throw new IOException(
"Failed to rename " + srcFile + " to " + dotFile);
}
}
} catch (IOException e) {
throw new DatasetIOException(
"Could not move contents of " + src + " to " + dest, e);
}
return staged;
}
static void finishMove(FileSystem fs, List<Pair<Path, Path>> staged) {
try {
for (Pair<Path, Path> pair : staged) {
if (!fs.rename(pair.first(), pair.second())) {
throw new IOException(
"Failed to rename " + pair.first() + " to " + pair.second());
}
}
} catch (IOException e) {
throw new DatasetIOException("Could not finish replacement", e);
}
}
/**
* Replace {@code destination} with {@code replacement}.
* <p>
* If this method fails in any step, recover using these steps:
* <ol>
* <li>If {@code .name.replacement} exists, but {@code name} does not, move
* it to {@code name}</li>
* <li>If {@code .name.replacement} and {@code name} exist, run this method
* again with the same list of additional removals</li>
* </ol>
*
* @param fs the FileSystem
* @param destination a Path
* @param replacement a Path that replaces the destination
* @param removals a List of paths that should also be removed
*/
static void replace(FileSystem fs, Path root, Path destination,
Path replacement, List<Path> removals) {
try {
// Ensure the destination exists because it acts as a recovery signal. If
// the directory exists, then recovery must go through the entire
// replacement process again. If it does not, then the dir can be moved.
if (!fs.exists(destination)) {
fs.mkdirs(destination);
}
Path staged = new Path(destination.getParent(),
"." + destination.getName() + ".replacement");
// First move into the destination folder to ensure moves work. It is
// okay to run this method on the staged path
if (!staged.equals(replacement) && !fs.rename(replacement, staged)) {
throw new IOException(
"Failed to rename " + replacement + " to " + staged);
}
// Remove any additional directories included in the replacement. This
// handles the case where there are multiple directories for the same
// logical partition. For example, dataset/a=2/ and dataset/2/
for (Path toRemove : removals) {
if (toRemove.equals(destination)) {
// destination is deleted last
continue;
}
FileSystemUtil.cleanlyDelete(fs, root, toRemove, false);
}
// remove the directory that will be replaced with a move
fs.delete(destination, true /* recursively */ );
// move the replacement to the final location
if (!fs.rename(staged, destination)) {
throw new IOException(
"Failed to rename " + staged + " to " + destination);
}
} catch (IOException e) {
throw new DatasetIOException(
"Could not replace " + destination + " with " + replacement, e);
}
}
static boolean cleanlyDelete(FileSystem fs, Path root, Path path) {
return cleanlyDelete(fs, root, path, false);
}
static boolean cleanlyMoveToTrash(FileSystem fs, Path root, Path path) {
return cleanlyDelete(fs, root, path, true);
}
private static boolean cleanlyDelete(FileSystem fs, Path root, Path path, boolean useTrash) {
Preconditions.checkNotNull(fs, "File system cannot be null");
Preconditions.checkNotNull(root, "Root path cannot be null");
Preconditions.checkNotNull(path, "Path to delete cannot be null");
try {
boolean deleted;
// attempt to relativize the path to delete
Path relativePath;
if (path.isAbsolute()) {
relativePath = new Path(root.toUri().relativize(path.toUri()));
} else {
relativePath = path;
}
if (relativePath.isAbsolute()) {
// path is not relative to the root. delete just the path
LOG.debug("Deleting path {}", path);
deleted = useTrash ? Trash.moveToAppropriateTrash(fs, path, fs.getConf())
: fs.delete(path, true /* include any files */);
} else {
// the is relative to the root path
Path absolute = new Path(root, relativePath);
LOG.debug("Deleting path {}", absolute);
deleted = useTrash ? Trash.moveToAppropriateTrash(fs, absolute, fs.getConf())
: fs.delete(absolute, true /* include any files */);
// iterate up to the root, removing empty directories
for (Path current = absolute.getParent();
!current.equals(root) && !(current.getParent() == null);
current = current.getParent()) {
final FileStatus[] stats = fs.listStatus(current);
if (stats == null || stats.length == 0) {
// dir is empty and should be removed
LOG.debug("Deleting empty path {}", current);
deleted = fs.delete(current, true) || deleted;
} else {
// all parent directories will be non-empty
break;
}
}
}
return deleted;
} catch (IOException ex) {
throw new DatasetIOException("Could not cleanly delete path:" + path, ex);
}
}
public static Schema schema(String name, FileSystem fs, Path location) throws IOException {
if (!fs.exists(location)) {
return null;
}
return visit(new GetSchema(name), fs, location);
}
public static PartitionStrategy strategy(FileSystem fs, Path location) throws IOException {
if (!fs.exists(location)) {
return null;
}
List<Pair<String, Class<? extends Comparable>>> pairs = visit(
new GetPartitionInfo(), fs, location);
if (pairs == null || pairs.isEmpty() || pairs.size() <= 1) {
return null;
}
PartitionStrategy.Builder builder = new PartitionStrategy.Builder();
// skip the initial partition because it is the containing directory
for (int i = 1; i < pairs.size(); i += 1) {
Pair<String, Class<? extends Comparable>> pair = pairs.get(i);
builder.provided(
pair.first() == null ? "partition_" + i : pair.first(),
ProvidedFieldPartitioner.valuesString(pair.second()));
}
return builder.build();
}
public static Format format(FileSystem fs, Path location) throws IOException {
if (!fs.exists(location)) {
return null;
}
return visit(new GetFormat(), fs, location);
}
private static abstract class PathVisitor<T> {
abstract T directory(FileSystem fs, Path path, List<T> children) throws IOException;
abstract T file(FileSystem fs, Path path) throws IOException;
}
private static <T> T visit(PathVisitor<T> visitor, FileSystem fs, Path path)
throws IOException {
return visit(visitor, fs, path, Lists.<Path>newArrayList());
}
private static final DynMethods.UnboundMethod IS_SYMLINK;
static {
DynMethods.UnboundMethod isSymlink;
try {
isSymlink = new DynMethods.Builder("isSymlink")
.impl(FileStatus.class)
.buildChecked();
} catch (NoSuchMethodException e) {
isSymlink = null;
}
IS_SYMLINK = isSymlink;
}
private static <T> T visit(PathVisitor<T> visitor, FileSystem fs, Path path,
List<Path> followedLinks) throws IOException {
if (fs.isFile(path)) {
return visitor.file(fs, path);
} else if (IS_SYMLINK != null &&
IS_SYMLINK.<Boolean>invoke(fs.getFileStatus(path))) {
Preconditions.checkArgument(!followedLinks.contains(path),
"Encountered recursive path structure at link: " + path);
followedLinks.add(path); // no need to remove
return visit(visitor, fs, fs.getLinkTarget(path), followedLinks);
}
List<T> children = Lists.newArrayList();
FileStatus[] statuses = fs.listStatus(path, PathFilters.notHidden());
for (FileStatus stat : statuses) {
children.add(visit(visitor, fs, stat.getPath()));
}
return visitor.directory(fs, path, children);
}
private static class GetPartitionInfo
extends PathVisitor<List<Pair<String, Class<? extends Comparable>>>> {
private static final Splitter EQUALS = Splitter.on('=').limit(2).trimResults();
@Override
List<Pair<String, Class<? extends Comparable>>> directory(
FileSystem fs, Path path, List<List<Pair<String, Class<? extends Comparable>>>> children)
throws IOException {
// merge the levels under this one
List<Pair<String, Class<? extends Comparable>>> accumulated = Lists.newArrayList();
for (List<Pair<String, Class<? extends Comparable>>> child : children) {
if (child == null) {
continue;
}
for (int i = 0; i < child.size(); i += 1) {
if (accumulated.size() > i) {
Pair<String, Class<? extends Comparable>> pair = merge(
accumulated.get(i), child.get(i));
accumulated.set(i, pair);
} else if (child.get(i) != null) {
accumulated.add(child.get(i));
}
}
}
List<String> parts = Lists.newArrayList(EQUALS.split(path.getName()));
String name;
String value;
if (parts.size() == 2) {
name = parts.get(0);
value = parts.get(1);
} else {
name = null;
value = parts.get(0);
}
accumulated.add(0,
new Pair<String, Class<? extends Comparable>>(name, dataClass(value)));
return accumulated;
}
@Override
List<Pair<String, Class<? extends Comparable>>> file(
FileSystem fs, Path path) throws IOException {
return null;
}
public Pair<String, Class<? extends Comparable>> merge(
Pair<String, Class<? extends Comparable>> left,
Pair<String, Class<? extends Comparable>> right) {
String name = left.first();
if (name == null || name.isEmpty()) {
name = right.first();
}
if (left.second() == String.class) {
return new Pair<String, Class<? extends Comparable>>(name, String.class);
} else if (right.second() == String.class) {
return new Pair<String, Class<? extends Comparable>>(name, String.class);
} else if (left.second() == Long.class) {
return new Pair<String, Class<? extends Comparable>>(name, Long.class);
} else if (right.second() == Long.class) {
return new Pair<String, Class<? extends Comparable>>(name, Long.class);
}
return new Pair<String, Class<? extends Comparable>>(name, Integer.class);
}
public Class<? extends Comparable> dataClass(String value) {
try {
Integer.parseInt(value);
return Integer.class;
} catch (NumberFormatException e) {
// not an integer
}
try {
Long.parseLong(value);
return Long.class;
} catch (NumberFormatException e) {
// not a long
}
return String.class;
}
}
private static class GetFormat extends PathVisitor<Format> {
@Override
Format directory(FileSystem fs, Path path, List<Format> formats) throws IOException {
Format format = null;
for (Format otherFormat : formats) {
if (format == null) {
format = otherFormat;
} else if (!format.equals(otherFormat)) {
throw new ValidationException(String.format(
"Path contains multiple formats (%s, %s): %s",
format, otherFormat, path));
}
}
return format;
}
@Override
Format file(FileSystem fs, Path path) throws IOException {
return formatFromExt(path);
}
}
private static class GetSchema extends PathVisitor<Schema> {
private final String name;
public GetSchema(String name) {
this.name = name;
}
@Override
Schema directory(FileSystem fs, Path path, List<Schema> schemas) {
Schema merged = null;
for (Schema schema : schemas) {
merged = merge(merged, schema);
}
return merged;
}
@Override
Schema file(FileSystem fs, Path path) throws IOException {
String filename = path.getName();
if (filename.endsWith(Formats.AVRO.getExtension())) {
return Schemas.fromAvro(fs, path);
} else if (filename.endsWith(Formats.PARQUET.getExtension())) {
return Schemas.fromParquet(fs, path);
} else if (filename.endsWith(Formats.JSON.getExtension())) {
return Schemas.fromJSON(name, fs, path);
}
return null;
}
}
/**
* Finds potential datasets by crawling a directory tree.
* <p>
* This method looks for any data files and directories appear to form a
* dataset. This deliberately ignores information that may be stored in the
* Hive metastore or .metadata folders.
* <p>
* Recognizes only Avro, Parquet, and JSON data files.
*
* @param fs a FileSystem for the root path
* @param path a root Path that will be searched
* @return a Collection with a DatasetDescriptor for each potential dataset.
* @throws IOException
*/
public static Collection<DatasetDescriptor> findPotentialDatasets(
FileSystem fs, Path path) throws IOException {
List<DatasetDescriptor> descriptors = Lists.newArrayList();
Result result = visit(new FindDatasets(), fs, path);
if (result instanceof Result.Table) {
descriptors.add(descriptor(fs, (Result.Table) result));
} else if (result instanceof Result.Group) {
for (Result.Table table : ((Result.Group) result).tables) {
descriptors.add(descriptor(fs, table));
}
}
return descriptors;
}
private static DatasetDescriptor descriptor(FileSystem fs, Result.Table table)
throws IOException {
// inspect the path to determine the partition strategy
PartitionStrategy strategy = strategy(fs, table.location);
DatasetDescriptor.Builder builder = new DatasetDescriptor.Builder()
.format(table.format)
.schema(table.schema)
.partitionStrategy(strategy)
.location(table.location);
if (table.depth < 0) {
builder.property("kite.filesystem.mixed-depth", "true");
}
return builder.build();
}
private interface Result {
// An unknown data path
class Unknown implements Result {
}
// A table of data
class Table implements Result {
private static final int UNKNOWN_DEPTH = 0;
private static final int MIXED_DEPTH = -1;
private final Path location;
private final Format format;
private final Schema schema;
private final int depth;
public Table(Path location, Format format, Schema schema, int depth) {
this.location = location;
this.format = format;
this.schema = schema;
this.depth = depth;
}
}
// A group of tables
class Group implements Result {
private final List<Table> tables;
private final boolean containsUnknown;
public Group(List<Table> tables, boolean containsUnknown) {
this.tables = tables;
this.containsUnknown = containsUnknown;
}
}
}
private static class FindDatasets extends PathVisitor<Result> {
@Override
Result directory(FileSystem fs, Path path, List<Result> children) throws IOException {
// there are two possible outcomes for this method:
// 1. all child tables are compatible and part of one dataset (Table)
// 2. each valid child is a separate dataset (Group)
boolean allCompatible = true; // assume compatible to start
boolean containsUnknown = false;
// if all are compatible
Schema mergedSchema = null;
Format onlyFormat = null;
int depth = Result.Table.UNKNOWN_DEPTH;
// if all are separate datasets
List<Result.Table> tables = Lists.newArrayList();
for (Result child : children) {
if (child instanceof Result.Unknown) {
// not compatible at this level because a data file is not supported
allCompatible = false;
containsUnknown = true;
} else if (child instanceof Result.Group) {
// not compatible at a lower level
Result.Group group = (Result.Group) child;
containsUnknown |= group.containsUnknown;
if (containsUnknown || !group.tables.isEmpty()) {
// not compatible if there was an unknown or was not empty
allCompatible = false;
}
tables.addAll(group.tables);
} else {
Result.Table table = (Result.Table) child;
tables.add(table); // always add table in case not compatible later
// if all tables are currently compatible, add the latest table
if (allCompatible) {
try {
mergedSchema = merge(mergedSchema, table.schema);
} catch (IncompatibleSchemaException e) {
allCompatible = false;
}
if (onlyFormat == null) {
onlyFormat = table.format;
} else if (onlyFormat != table.format) {
allCompatible = false;
}
if (depth == Result.Table.UNKNOWN_DEPTH) {
depth = table.depth;
} else if (depth != table.depth) {
depth = Result.Table.MIXED_DEPTH;
}
}
}
}
if (allCompatible && tables.size() > 0) {
if (tables.size() == 1) {
// only one, use the existing location rather than higher up the path
return tables.get(0);
} else {
// more than one, use the path at this level
return new Result.Table(path, onlyFormat, mergedSchema, depth);
}
} else {
return new Result.Group(tables, containsUnknown);
}
}
@Override
Result file(FileSystem fs, Path path) throws IOException {
Format format = formatFromExt(path);
Schema schema = null;
if (format == Formats.AVRO) {
schema = Schemas.fromAvro(fs, path);
} else if (format == Formats.PARQUET) {
schema = Schemas.fromParquet(fs, path);
} else if (format == Formats.JSON) {
schema = Schemas.fromJSON("record", fs, path);
}
if (schema == null) {
return new Result.Unknown();
}
return new Result.Table(path, format, schema, path.depth());
}
}
private static final Splitter DOT = Splitter.on('.');
private static Format formatFromExt(Path path) {
String filename = path.getName();
String ext = Iterables.getLast(DOT.split(filename));
for (Format format : SUPPORTED_FORMATS) {
if (ext.equals(format.getExtension())) {
return format;
}
}
return null;
}
private static Schema merge(@Nullable Schema left, @Nullable Schema right) {
if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
return SchemaUtil.merge(left, right);
}
}
/**
* Determine whether a FileSystem that supports efficient file renaming is being used. Two known
* FileSystem implementations that currently lack this feature are S3N and S3A.
*
* @param fsUri the FileSystem URI
* @param conf the FileSystem Configuration
* @return {@code true} if the FileSystem URI or {@link FileSystemProperties#SUPPORTS_RENAME_PROP
* configuration override} indicates that the FileSystem implementation supports efficient
* rename operations, {@code false} otherwise.
*/
public static boolean supportsRename(URI fsUri, Configuration conf) {
String fsUriScheme = fsUri.getScheme();
// Only S3 is known to not support renaming, but allow configuration override.
// This logic is intended as a temporary placeholder solution and should
// be revisited once HADOOP-9565 has been completed.
return conf.getBoolean(FileSystemProperties.SUPPORTS_RENAME_PROP,
!(fsUriScheme.equalsIgnoreCase("s3n") || fsUriScheme.equalsIgnoreCase("s3a")));
}
}
| true
|
6cdf63318f7fce430aa5965c2a6ad658edf1e676
|
Java
|
aishfenton/azkaban2
|
/src/java/azkaban/sla/SlaMailer.java
|
UTF-8
| 2,151
| 2.15625
| 2
|
[
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
package azkaban.sla;
import java.util.List;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
import azkaban.sla.SLA;
import azkaban.utils.AbstractMailer;
import azkaban.utils.EmailMessage;
import azkaban.utils.Props;
public class SlaMailer extends AbstractMailer {
private static Logger logger = Logger.getLogger(SlaMailer.class);
private boolean testMode = false;
public SlaMailer(Props props) {
super(props);
testMode = props.getBoolean("test.mode", false);
}
public void sendSlaEmail(SLA s, String ... extraReasons) {
List<String> emailList = s.getEmails();
if (emailList != null && !emailList.isEmpty()) {
EmailMessage message = super.createEmailMessage("SLA violation on " + getAzkabanName(), "text/html", emailList);
// message.println("<h2 style=\"color:#FF0000\"> Execution '" + s.getExecId() + "' of flow '" + flow.getFlowId() + "' failed to meet SLA on " + azkabanName + "</h2>");
// message.println("<table>");
// message.println("<tr><td>Start Time</td><td>" + flow.getStartTime() +"</td></tr>");
// message.println("<tr><td>End Time</td><td>" + flow.getEndTime() +"</td></tr>");
// message.println("<tr><td>Duration</td><td>" + Utils.formatDuration(flow.getStartTime(), flow.getEndTime()) +"</td></tr>");
// message.println("</table>");
// message.println("");
// String executionUrl = super.getReferenceURL() + "executor?" + "execid=" + execId;
// message.println("<a href='\"" + executionUrl + "\">" + flow.getFlowId() + " Execution Link</a>");
//
// message.println("");
// message.println("<h3>Reason</h3>");
// List<String> failedJobs = findFailedJobs(flow);
// message.println("<ul>");
// for (String jobId : failedJobs) {
// message.println("<li><a href=\"" + executionUrl + "&job=" + jobId + "\">Failed job '" + jobId + "' Link</a></li>" );
// }
for (String reasons: extraReasons) {
message.println("<li>" + reasons + "</li>");
}
message.println("</ul>");
if (!testMode) {
try {
message.sendEmail();
} catch (MessagingException e) {
logger.error("Email message send failed" , e);
}
}
}
}
}
| true
|
01bc51cb4e6c90baad3eb8a90c4ebfc317789e87
|
Java
|
Mooselk/All-In-One-Lobby
|
/src/main/java/me/kate/lobby/modules/toggleplayers/TogglePlayers.java
|
UTF-8
| 759
| 2.671875
| 3
|
[] |
no_license
|
package me.kate.lobby.modules.toggleplayers;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
public class TogglePlayers implements Hideable {
@Override
public void hide(Player player, ConfigurationSection section) {
for (Player online : Bukkit.getOnlinePlayers()) {
player.hidePlayer(online);
}
}
@Override
public void unhide(Player player, ConfigurationSection section) {
for (Player online : Bukkit.getOnlinePlayers()) {
player.showPlayer(online);
}
}
@Override
public void setHidden(boolean hide, Player player) {
for (Player online : Bukkit.getOnlinePlayers()) {
if (hide)
player.hidePlayer(online);
if (!hide)
player.showPlayer(online);
}
}
}
| true
|
711d70aae1e59141a19924d3798b23ea2cc3390d
|
Java
|
bxczp/diarySSH
|
/src/com/bx/action/DiaryTypeAction.java
|
UTF-8
| 1,929
| 1.8125
| 2
|
[] |
no_license
|
package com.bx.action;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import com.bx.entity.DiaryType;
import com.bx.service.DiaryTypeService;
import com.bx.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;
/**
* @date 2016年4月8日 DiaryTypeAction.java
* @author CZP
* @parameter
*/
@Controller
public class DiaryTypeAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<DiaryType> diaryTypeList;
private String mainPage;
private DiaryType diaryType;
private String diaryTypeId;
@Resource
private DiaryTypeService diaryTypeService;
public String list() {
diaryTypeList = diaryTypeService.find();
mainPage = "/diaryType/diaryTypeList.jsp";
return "list";
}
public String preSave() {
if (StringUtil.isNotEmpty(diaryTypeId)) {
diaryType = diaryTypeService.getDiaryTypeById(Integer.parseInt(diaryTypeId));
}
mainPage = "/diaryType/diaryTypeAve.jsp";
return "preSave";
}
public String save() {
diaryTypeService.update(diaryType);
mainPage = "/diaryType/diaryTypeList.jsp";
return "save";
}
public String delete() {
diaryType = diaryTypeService.getDiaryTypeById(Integer.parseInt(diaryTypeId));
diaryTypeService.delete(diaryType);
return "save";
}
public List<DiaryType> getDiaryTypeList() {
return diaryTypeList;
}
public void setDiaryTypeList(List<DiaryType> diaryTypeList) {
this.diaryTypeList = diaryTypeList;
}
public String getMainPage() {
return mainPage;
}
public void setMainPage(String mainPage) {
this.mainPage = mainPage;
}
public DiaryType getDiaryType() {
return diaryType;
}
public void setDiaryType(DiaryType diaryType) {
this.diaryType = diaryType;
}
public String getDiaryTypeId() {
return diaryTypeId;
}
public void setDiaryTypeId(String diaryTypeId) {
this.diaryTypeId = diaryTypeId;
}
}
| true
|
37e701b4d12f9683082048684984574f2bc75607
|
Java
|
energizerishche/java-core-grom
|
/src/lesson11/roomsearchapi/Controller.java
|
UTF-8
| 2,365
| 3.046875
| 3
|
[] |
no_license
|
package lesson11.roomsearchapi;
public class Controller {
private API[] apis;
public Controller(API[] apis) {
this.apis = apis;
}
public Room[] requestRooms(int price, int persons, String city, String hotel) {
int resultLength = 0;
for (API api : apis) {
resultLength += api.getAll().length;
}
Room[] tempResult = new Room[resultLength];
int counter = 0;
for (API api : apis) {
for (Room room : api.findRooms(price, persons, city, hotel)) {
if (room != null) {
boolean needAddRoom = true;
for (Room alreadyAddedRoom : tempResult) {
if (room.equals(alreadyAddedRoom)) {
needAddRoom = false;
}
}
if (needAddRoom) {
tempResult[counter] = room;
counter++;
}
}
}
}
Room[] result = new Room[counter];
for (Room room : tempResult) {
if (room != null) {
result[counter] = room;
} else {
break;
}
}
return result;
}
public Room[] check(API api1, API api2) {
Room[] tempResult = new Room[api1.getAll().length];
int counter = 0;
int resultArraysLength = 0;
for (Room roomFromApi1 : api1.getAll()) {
for (Room roomFromApi2 : api2.getAll()) {
if (roomFromApi2 != null
&& roomFromApi2.equals(roomFromApi1)
&& roomFromApi1.getPersons() > 0
&& roomFromApi1.getCityName() != null
&& roomFromApi1.getPrice() > 0
&& roomFromApi1.getHotelName() != null
) {
tempResult[counter] = roomFromApi1;
resultArraysLength++;
break;
}
}
counter++;
}
counter = 0;
Room[] result = new Room[resultArraysLength];
for (Room room : tempResult) {
if (room != null) {
result[counter] = room;
counter++;
}
}
return result;
}
}
| true
|
14b4f2dc71863e9ecec0af996c0970164e848e8b
|
Java
|
nhcemonkey/nhce-monkey
|
/src/bingomonkey/CheckPanel.java
|
UTF-8
| 3,972
| 2.40625
| 2
|
[] |
no_license
|
package bingomonkey;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import org.tool.LanguageTool;
import bingomonkey.Editor.Word;
public class CheckPanel extends JPanel {
private static final long serialVersionUID = -5677557816301191800L;
JPanel bottomPanel;
JPanel mainPanel;
JButton checkBtn;
JTextPane spellCheckPane, grammarCheckPane;
public int spellCheckWrong = 0, grammarCheckWrong = 0;
public CheckPanel() {
setLayout(new BorderLayout());
bottomPanel = new JPanel();
mainPanel = new JPanel(new GridLayout(1, 0));
checkBtn = new JButton("Check");
spellCheckPane = new JTextPane();
spellCheckPane.setContentType("text/html");
spellCheckPane.setEditable(false);
grammarCheckPane = new JTextPane();
grammarCheckPane.setContentType("text/html");
grammarCheckPane.setEditable(false);
JScrollPane scroll = new JScrollPane(spellCheckPane);
scroll.setBorder(new TitledBorder("Spell Check"));
;
mainPanel.add(scroll);
scroll = new JScrollPane(grammarCheckPane);
scroll.setBorder(new TitledBorder("Grammar Check"));
;
mainPanel.add(scroll);
bottomPanel.add(checkBtn);
add(mainPanel);
add(bottomPanel, BorderLayout.SOUTH);
// grammarCheckPane.getDocument().addDocumentListener(new
// DocumentListener() {
//
// @Override
// public void removeUpdate(DocumentEvent e) {
// }
//
// @Override
// public void insertUpdate(DocumentEvent e) {
// if (grammarCheckPane.getText().contains("</b>")) {
// BGMonkey.bgm.infoPanel.setSelectedIndex(2);
// System.err.println("Grammar Wrong!");
// }
// }
//
// @Override
// public void changedUpdate(DocumentEvent e) {
// }
// });
checkBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
grammarCheckWrong = LanguageTool.getInstance().checkTextAndDisplayResults();
spellCheckWrong = checkSpell();
if (spellCheckWrong > 0 && grammarCheckWrong > 0) {
BGMonkey.bgm.infoPanel.setSelectedIndex(2);
BGMonkey.output.warn("发现有" + spellCheckWrong + "个疑似拼写错误和" + grammarCheckWrong + "个疑似语法错误!");
} else if (spellCheckWrong <= 0 && grammarCheckWrong > 0) {
BGMonkey.bgm.infoPanel.setSelectedIndex(2);
BGMonkey.output.warn("发现有" + grammarCheckWrong + "个疑似语法错误!");
} else if (spellCheckWrong > 0) {
BGMonkey.bgm.infoPanel.setSelectedIndex(2);
BGMonkey.output.warn("发现有" + spellCheckWrong + "个疑似拼写错误!");
}
}
});
}
public int checkSpell() {
StringBuilder sb = new StringBuilder();
int count = 1;
boolean empty = true;
boolean supported = true;
try {
for (Word word : BGMonkey.bgm.editor.getWords()) {
empty = false;
List<String> result = HunspellMain.checkWord(word.getWord());
if (result != null && result.size() > 0) {
sb.append(count + ".<b>可疑单词</b>:<font color=\'red\'>" + word.getWord()
+ "</font><br> <b>候选单词</b>:");
for (String sgw : result)
sb.append(sgw + " ");
sb.append("<br><br>");
count++;
}
}
} catch (Throwable e1) {
supported = false;
e1.printStackTrace();
}
if (!supported)
sb.append("<html><font color=\'red\'>暂不支持您的操作系统!</font></html>");
else if (empty)
sb.append(LanguageTool.HTML_GREY_FONT_START + "没有输入任何文本!" + LanguageTool.HTML_FONT_END);
else if (count <= 1)
sb.append(LanguageTool.HTML_GREY_FONT_START + "没有检测出可疑单词!" + LanguageTool.HTML_FONT_END);
spellCheckPane.setText(sb.toString());
spellCheckPane.setCaretPosition(0);
return count - 1;
}
}
| true
|
504e56f333b065f30251c2bf118ea4f7799dda0c
|
Java
|
KevinWard0910/foundation
|
/handler/src/main/java/com/kevin/handler/framework/IDataBinding.java
|
UTF-8
| 289
| 1.867188
| 2
|
[] |
no_license
|
package com.kevin.handler.framework;
/**
* Created by kevin on 2018/11/29.
* descript: base activity and base fragment 需要实现的接口
*/
public interface IDataBinding<P, VM, B> {
boolean isBound();
P getPresenter();
VM getViewModel();
B getBinding();
}
| true
|
7402e8b37ecb97fb43d9ac06108e16f064aeaef4
|
Java
|
caiger2015/algorithm
|
/src/com/cg/leetcode/stack/MinStack.java
|
UTF-8
| 1,393
| 3.796875
| 4
|
[] |
no_license
|
package com.cg.leetcode.stack;
import java.util.Stack;
class MinStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
if (minStack.empty() || minStack.peek() >= x)// 取 = 是为了防止重复
minStack.push(x);
stack.push(x);
}
public void pop() {
// 或者用if(stack.peek().equals(minStack.peek()))
// peek()返回的是Integer对象,直接比较是比较引用
if (stack.peek().intValue() == minStack.peek().intValue())
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
/*
* 思路错误 class MinStack { private Node<Integer> top; public MinStack(){ this.top
* = null; } public void push(int x) { top = new Node<Integer>(new
* Integer(x),top); }
*
* public void pop() { if(top == null) return; top = top.next; }
*
* public int top() { if (top == null) return -1; return
* this.top.data.intValue(); }
*
* public int getMin() { if (top == null) return -1; Node<Integer> temp = top;
* while(temp.next != null){ if(temp.data<= temp.next.data) temp.next =
* temp.next.next; else temp = temp.next; } return temp.data.intValue(); }
*
* } class Node<T>{ T data; Node<T> next; public Node(T data,Node<T> next){
* this.data = data; this.next = next; } public Node(){ this(null, null); } }
*/
| true
|
0a0572dfe7d833f5536886d0a5db7b17777aec1d
|
Java
|
NeelMakadiya14/ExpenseManager
|
/app/src/main/java/com/nmakadiya/expensemanager/aboutus.java
|
UTF-8
| 1,669
| 2.015625
| 2
|
[] |
no_license
|
package com.nmakadiya.expensemanager;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import mehdi.sakout.aboutpage.AboutPage;
import mehdi.sakout.aboutpage.Element;
public class aboutus extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Element versionElement = new Element();
versionElement.setTitle("Version 1.1.0");
/* Element adsElement = new Element();
adsElement.setTitle("Advertise with us");*/
View aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.mipmap.ic_iconmain1)
.setDescription("Expense Manager \r\nDeveloped by: Neel Makadiya. \r\nThanks for Choosing this app.If you notice an error,a bug,an an incompatibility with your devise or any problem, please contact us.Many users sent us feedback.We appreciate your comment.")
.addItem(versionElement)
// .addItem(adsElement)
.addGroup("Connect with us")
.addEmail("nmakadiya1@gmail.com", "Contact via Email")
.addWebsite("https://sites.google.com/view/expensemanager-privacy-policy/home", "Privacy Policy")
.addFacebook("neel.makadiya.73")
.addTwitter("MakadiyaN")
// .addYoutube("UCdPQtdWIsg7_pi4mrRu46vA")
.addPlayStore("com.nmakadiya.expensemanager")
.addGitHub("201801190", "Follow us on GitHub")
.addInstagram("neel.makadiya")
.create();
setContentView(aboutPage);
}
}
| true
|
93fa8d396daf22e4b081031fdd1969369f59d83e
|
Java
|
ankit-joinwal/sbox
|
/SociallBoxService/src/main/java/com/bitlogic/sociallbox/service/exception/EntityNotFoundException.java
|
UTF-8
| 532
| 2.234375
| 2
|
[] |
no_license
|
package com.bitlogic.sociallbox.service.exception;
public class EntityNotFoundException extends RestException{
private static final long serialVersionUID = 1L;
private Object entityId;
public EntityNotFoundException(){
super();
}
public EntityNotFoundException(Object entityId , RestErrorCodes errorCode , String message){
super(errorCode, message);
this.entityId = entityId;
}
public Object getEntityId() {
return entityId;
}
public void setEntityId(Object entityId) {
this.entityId = entityId;
}
}
| true
|
44e68db8500da1ba6b034517b8066d0ccb08e282
|
Java
|
arnoldbendaa/cppro
|
/src/com/cedar/cp/ejb/impl/dimension/HierarchyEditorEngine$1.java
|
UTF-8
| 1,024
| 1.59375
| 2
|
[] |
no_license
|
// Decompiled by: Fernflower v0.8.6
// Date: 12.08.2012 13:08:24
// Copyright: 2008-2012, Stiver
// Home page: http://www.neshkov.com/ac_decompiler.html
package com.cedar.cp.ejb.impl.dimension;
import com.cedar.cp.api.base.CPException;
import com.cedar.cp.api.base.ValidationException;
import com.cedar.cp.api.dimension.HierarchyEvent;
import com.cedar.cp.dto.dimension.event.InsertHierarchyElementEvent;
import com.cedar.cp.ejb.impl.dimension.HierarchyEditorEngine;
import com.cedar.cp.ejb.impl.dimension.ServerHierarchyEventListener;
class HierarchyEditorEngine$1 implements ServerHierarchyEventListener {
// $FF: synthetic field
final HierarchyEditorEngine this$0;
HierarchyEditorEngine$1(HierarchyEditorEngine var1) {
this.this$0 = var1;
}
public void dispatchEvent(HierarchyEvent e) throws CPException, ValidationException {
HierarchyEditorEngine.accessMethod000(this.this$0, (InsertHierarchyElementEvent)e);
}
}
| true
|
d68b5e895d62474c20542819ef2bbcf9738f87f2
|
Java
|
confident-OH/HUST-JAVA-Homework_Lab
|
/ch11_13homework/homework/src/homework/ch11_13/p2/AchieveTask2.java
|
UTF-8
| 187
| 2.390625
| 2
|
[] |
no_license
|
package homework.ch11_13.p2;
public class AchieveTask2 implements Task{
@Override
public void execute(){
System.out.println("The second method implement Task.");
}
}
| true
|
2e5b9252e8f2bae9616f2d03db9459329080c17f
|
Java
|
nrajv/Selenium_Java_Assignment
|
/DarwinboxDotIn/src/test/java/PageLocators/PageLoc.java
|
UTF-8
| 1,209
| 1.71875
| 2
|
[] |
no_license
|
package PageLocators;
import org.openqa.selenium.By;
public interface PageLoc {
public By EmpId = By.id("UserLogin_username");
public By Pass = By.id("UserLogin_password");
public By SignIn = By.id("login-submit");
public By Attendance = By.id("UserLogin_redirectpage");
public By AttendanceIcon = By.xpath("//a[@href='/attendance']//div[@class='module-icon-wrapper']//img");
public By ApplyButton = By.id("attendance_request");
public By RequestType = By.xpath("(//input[@class='search'])[1]");
public By SelectReq = By.xpath("(//div[text() = 'Attendance Request'])[1]");
public By Reason = By.xpath("(//input[@class='search'])[2]");
public By SelectReason = By.xpath("(//div[text()='Working From Home'])[1]");
public By FromDate = By.id("punchin-date");
public By PickFromDate = By.xpath("//a[text()='7']");
public By ToDate = By.id("punchin-date-to");
public By PickToDate = By.xpath("//a[text()='8']");
public By Location = By.xpath("(//input[@class='search'])[3]");
public By PickLoc = By.xpath("//div[text() ='Home']");
public By Message = By.id("AttendanceRequestForm_message");
public By Submit = By.id("add_request_btn");
}
| true
|
65920822df5e377948ccbbebe793ef36b977076a
|
Java
|
georgi-uchkunov/browsergame
|
/src/main/java/st/pro/browsergame/controllers/TrainingController.java
|
UTF-8
| 382
| 1.835938
| 2
|
[] |
no_license
|
/**
*
*/
package st.pro.browsergame.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Basic view controller to enable reaching training page
* @author GU
*/
@Controller
public class TrainingController {
@GetMapping("/training")
public String redirectToTraining() {
return "training";
}
}
| true
|
424ffbad5d6a01ed377e1f12d2e6c782ac6e385e
|
Java
|
Jo-minkyeong/shoppingnote-project
|
/Shop/src/main/java/com/sharp/ing/exception/CustomJwtRuntimeException.java
|
UTF-8
| 287
| 1.960938
| 2
|
[] |
no_license
|
package com.sharp.ing.exception;
public class CustomJwtRuntimeException extends RuntimeException {
public CustomJwtRuntimeException(){
super(ErrorCode.AUTHENTICATION_FAILED.getMessage());
}
public CustomJwtRuntimeException(Exception ex){
super(ex);
}
}
| true
|
4d9516a50bfc670e5b95f3f41ad31589749922c2
|
Java
|
LeoHYS/caculate-web
|
/src/com/clps/service/LoginService.java
|
UTF-8
| 942
| 2.234375
| 2
|
[] |
no_license
|
/**
* All rights Reserved, Designed By Android_Robot
* @Title: LoginService.java
* @Package com.tjclps.service
* @Description: TODO(用一句话描述该文件做什么)
* @author: Android_Robot
* @date: Sep 4, 2017 1:14:51 PM
* @version V1.0
*/
package com.clps.service;
/**
* @ClassName: LoginService
* @Description:TODO(这里用一句话描述这个类的作用)
* @author: Android_Robot
* @date: Sep 4, 2017 1:14:51 PM
*
*/
import java.util.Iterator;
import java.util.List;
import com.clps.dao.EmployeeInfoDao;
import com.clps.dao.impl.EmployeeInfoDaoImpl;
import com.clps.entity.EmployeeInfo;
public class LoginService {
private EmployeeInfoDao eInfoDao;
public EmployeeInfo vaildate(String username,String password) {
EmployeeInfoDao eDao = new EmployeeInfoDaoImpl();
EmployeeInfo eInfo = eDao.queryEmployInfo(username, password);
return eInfo;
}
}
| true
|