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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
369914ff9e3ebb72bdd9dbc24ba56b53b8b1e83a
|
Java
|
modichetan89/GitDemo
|
/src/ReadDataText.java
|
UTF-8
| 1,025
| 3.59375
| 4
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadDataText {
public static void main(String[] args) throws IOException {
//Approach1 - Using file reader and buffered reader
FileReader fr = new FileReader("D:\\EclipseWorkspace\\FileHanding\\src\\Sample.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
//Approach2 - Using file and scanner class and loop
File fl = new File("D:\\EclipseWorkspace\\FileHanding\\src\\Sample.txt");
Scanner sc = new Scanner(fl);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
sc.close();
//Approach3 - Using file and scanner class and delimiter
File fl1 = new File("D:\\EclipseWorkspace\\FileHanding\\src\\Sample.txt");
Scanner sc1 = new Scanner(fl1);
sc1.useDelimiter("\\Z");
System.out.println(sc1.next());
sc1.close();
}
}
| true
|
89055dc45a6d8d50806c2baadb230848ea2fbd86
|
Java
|
junges521/src_awe
|
/src/main/java/com/ss/android/ugc/aweme/challenge/data/a.java
|
UTF-8
| 648
| 1.929688
| 2
|
[] |
no_license
|
package com.ss.android.ugc.aweme.challenge.data;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
@Dao
public interface a {
@Query("SELECT * FROM localHashTag order by time desc")
List<c> a();
@Query("DELETE FROM localHashTag WHERE time in(SELECT time FROM localHashTag ORDER BY time ASC LIMIT :num)")
void a(int i);
@Insert(onConflict = 4)
void a(c cVar);
@Query("SELECT count(*) FROM localHashTag")
int b();
@Update(onConflict = 4)
void b(c cVar);
}
| true
|
304c48e4a97ecd24367dc73643b024753d3f908d
|
Java
|
orlandoburli/skipthedishes-microservices-challen-ge
|
/services/skipthedishes-orders/src/main/java/com/skipthedishes/orders/exceptions/OrderException.java
|
UTF-8
| 229
| 1.992188
| 2
|
[] |
no_license
|
package com.skipthedishes.orders.exceptions;
public class OrderException extends Exception {
private static final long serialVersionUID = -4971987226756246211L;
public OrderException(String message) {
super(message);
}
}
| true
|
b6cf3cac547e2c4aa74209a5a566e6db51e66196
|
Java
|
seanh737/myproject
|
/src/oo/abstraction/CarTester.java
|
UTF-8
| 995
| 3.09375
| 3
|
[] |
no_license
|
package oo.abstraction;
public class CarTester {
public static void main(String[] args) {
Car c1 = new Car("Toyota", 1800, "Altis", "Sedan");
// c1.brand = "Toyota";
// c1.name = "Altis";
// c1.cc = 1800;
// c1.type = "Sedan";
Car c2 = new Car("HONDA", 2000, "ACCORD", "Sedan");
Car c3 = new Car("Toyota", 2000, "WISH", "Sedan");
int[] n = new int [5];
System.out.println(n[3]);
Car[] cars = new Car[3];
System.out.println(cars[0]);
cars[0] = new Car("Toyota", 1800, "Altis", "Sedan");
cars[1] = new Car("HONDA", 2000, "ACCORD", "Sedan");
cars[2] = new Car("Toyota", 2000, "WISH", "Sedan");
cars[0].id = 301;
cars[1].id = 400;
cars[2].id = 403;
System.out.println(cars[0].name);
int i=0;
for (i=0; i<3; i++){
System.out.println(cars[i].name);
}
System.out.println(i);
for (i=1; i<=9; i=i+2){
System.out.println(i);
}
System.out.println(i);
}
class AA {
}
AA a = new AA();
}
| true
|
8dd412e2167de5f7cd2fa3f3af0909bc9d70aa87
|
Java
|
WANGXin1205/computer
|
/src/main/java/com/growlithe/computer/common/math/BinaryTreeNode.java
|
UTF-8
| 4,211
| 3.578125
| 4
|
[] |
no_license
|
package com.growlithe.computer.common.math;
import java.math.BigDecimal;
/**
* @Author : Growlithe
* @Date : 2018/6/7 19:35
* @Description 二叉树节点
*/
public class BinaryTreeNode {
/**
* 根节点
*/
private Integer root;
/**
* 左节点
*/
private BinaryTreeNode leftNode;
/**
* 右节点
*/
private BinaryTreeNode rightNode;
public BinaryTreeNode() {
}
public BinaryTreeNode(Integer root, BinaryTreeNode leftNode, BinaryTreeNode rightNode) {
this.root = root;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
/**
* 先序遍历
*
* @param binaryTreeNode
*/
public static void preOrder(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode.getRoot() != null) {
System.out.println(binaryTreeNode.getRoot());
}
if (binaryTreeNode.getLeftNode() != null) {
var node = binaryTreeNode.getLeftNode();
preOrder(node);
}
if (binaryTreeNode.getRightNode() != null) {
var node = binaryTreeNode.getRightNode();
preOrder(node);
}
}
/**
* 中序遍历
*
* @param binaryTreeNode
*/
public static void inOrder(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode.getLeftNode() != null) {
var node = binaryTreeNode.getLeftNode();
preOrder(node);
}
if (binaryTreeNode.getRoot() != null) {
System.out.println(binaryTreeNode.getRoot());
}
if (binaryTreeNode.getRightNode() != null) {
var node = binaryTreeNode.getRightNode();
preOrder(node);
}
}
/**
* 后序遍历
*
* @param binaryTreeNode
*/
public static void postOrder(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode.getLeftNode() != null) {
var node = binaryTreeNode.getLeftNode();
preOrder(node);
}
if (binaryTreeNode.getRightNode() != null) {
var node = binaryTreeNode.getRightNode();
preOrder(node);
}
if (binaryTreeNode.getRoot() != null) {
System.out.println(binaryTreeNode.getRoot());
}
}
/**
* 二叉树的保存
*
* @param nodeValue
* @param binaryTreeNode
*/
public static void saveBinaryTree(Integer nodeValue, BinaryTreeNode binaryTreeNode) {
if (nodeValue.equals(binaryTreeNode.getRoot())) {
return;
}
if (nodeValue < binaryTreeNode.getRoot()) {
if (binaryTreeNode.getLeftNode() != null) {
saveBinaryTree(nodeValue, binaryTreeNode.getLeftNode());
}
if (binaryTreeNode.getLeftNode() == null) {
BinaryTreeNode leftBinaryTreeNode = new BinaryTreeNode();
leftBinaryTreeNode.setRoot(nodeValue);
binaryTreeNode.setLeftNode(leftBinaryTreeNode);
}
}
if (nodeValue > binaryTreeNode.getRoot()) {
if (binaryTreeNode.getRightNode() != null) {
saveBinaryTree(nodeValue, binaryTreeNode.getRightNode());
}
if (binaryTreeNode.getRightNode() == null) {
BinaryTreeNode rightBinaryTreeNode = new BinaryTreeNode();
rightBinaryTreeNode.setRoot(nodeValue);
binaryTreeNode.setRightNode(rightBinaryTreeNode);
}
}
}
public Integer getRoot() {
return root;
}
public void setRoot(Integer root) {
this.root = root;
}
public BinaryTreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(BinaryTreeNode leftNode) {
this.leftNode = leftNode;
}
public BinaryTreeNode getRightNode() {
return rightNode;
}
public void setRightNode(BinaryTreeNode rightNode) {
this.rightNode = rightNode;
}
@Override
public String toString() {
return "BinaryTreeNode{" +
"root=" + root +
", leftNode=" + leftNode +
", rightNode=" + rightNode +
'}';
}
}
| true
|
5701da99a4381ac4088f6f0a8efda788b877c6f0
|
Java
|
diegofreitas11/projeto-curso-spring
|
/demo-mvc/src/main/java/com/example/demo/dao/DepartamentoDAO.java
|
UTF-8
| 215
| 1.5
| 2
|
[] |
no_license
|
package com.example.demo.dao;
import org.springframework.stereotype.Repository;
import com.example.demo.domain.Departamento;
@Repository
public class DepartamentoDAO extends AbstractDao<Departamento, Long>{
}
| true
|
ca176d1a8a72f82e3ab61ee463d05a9681cca1b6
|
Java
|
Marco-Fx/Box
|
/src/main/java/marco/zlc/dabl/modules/system/service/impl/TestServiceImpl.java
|
UTF-8
| 653
| 1.859375
| 2
|
[] |
no_license
|
package marco.zlc.dabl.modules.system.service.impl;
import marco.zlc.dabl.modules.system.dao.SysTestMapper;
import marco.zlc.dabl.modules.system.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
*@描述
*@创建人 zlc
*@创建时间 2020/2/8 17:43
*@修改人和其它信息 实现
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
private SysTestMapper sysTestMapper;
@Override
public List<Map> TextSel(String name) {
return sysTestMapper.TextSel(name);
}
}
| true
|
784682ece03829c48b506620a49247c569df7ff7
|
Java
|
pnthang01/RealLifeRealGame
|
/Sources/Utillities/src/main/java/com/rlrg/dataserver/badge/dto/AchievementDTO.java
|
UTF-8
| 1,325
| 2.390625
| 2
|
[] |
no_license
|
package com.rlrg.dataserver.badge.dto;
import java.util.Date;
import com.rlrg.utillities.annotation.JsonDTO;
import com.rlrg.utillities.annotation.JsonExport;
import com.rlrg.utillities.annotation.JsonObject;
@JsonDTO(singularName="Achievement", pluralName="Achievements")
public class AchievementDTO {
@JsonExport(name="ID")
private Long id;
@JsonObject
private BadgeDTO badge;
@JsonExport(name="Username")
private String username;
@JsonExport(name="AchievedTime")
private Date achievedTime;
public AchievementDTO(){
}
public AchievementDTO(Long id, Integer badgeId, String badgeName, String badgeFileName, String badgeDescription, Date achievedTime){
this.id = id;
BadgeDTO dto = new BadgeDTO(badgeId, badgeName, badgeFileName, badgeDescription);
this.badge = dto;
this.achievedTime = achievedTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BadgeDTO getBadge() {
return badge;
}
public void setBadge(BadgeDTO badge) {
this.badge = badge;
}
public Date getAchievedTime() {
return achievedTime;
}
public void setAchievedTime(Date achievedTime) {
this.achievedTime = achievedTime;
}
}
| true
|
8b154d3daa284992b1290b5a5897da9208e23910
|
Java
|
kenMarquez/DevFB13Android
|
/ejercicio3pesosadolares/src/main/java/com/ken/ejercicio3pesosadolares/MainActivity.java
|
UTF-8
| 2,816
| 2.8125
| 3
|
[] |
no_license
|
package com.ken.ejercicio3pesosadolares;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
/**
* Variables globales que vamos a utilizar en varios metodos
*/
private EditText inputPesos;
private EditText inputDolares;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Obtenemos la referencia de las vistas que creamos mediante
* id's y tenemos que castearlas al tipo de vista que creamos
*/
Button btnConvertir = (Button) findViewById(R.id.btn_convertir);
Button btnConvertirPesos = (Button) findViewById(R.id.btn_convertir_a_pesos);
inputPesos = (EditText) findViewById(R.id.input_pesos);
inputDolares = (EditText) findViewById(R.id.tv_dolares);
/**
* Agregamos escuchadores del evento del click
*/
btnConvertir.setOnClickListener(this);
btnConvertirPesos.setOnClickListener(this);
}
/**
* Metodo que se ejecuta cuando el usuario da click en alguna vista
*
* @param view
*/
@Override
public void onClick(View view) {
/**
* Vemos que tipo de vista es a la que le dio click
*/
switch (view.getId()) {
//convertiremos dolares a pesos
case R.id.btn_convertir:
if (!inputPesos.getText().toString().isEmpty()) {
String pesos = inputPesos.getText().toString();
double pesosDouble = Double.parseDouble(pesos);
double dollar = pesosDouble * 20.67098;
inputDolares.setText("" + dollar);
} else {
Toast.makeText(this, "Señor usuario no se puede realizar su acción", Toast.LENGTH_LONG).show();
}
break;
case R.id.btn_convertir_a_pesos:
if (!inputDolares.getText().toString().isEmpty()) {
String pesos = inputDolares.getText().toString();
double pesosDouble = Double.parseDouble(pesos);
double dollar = pesosDouble / 20.67098;
inputPesos.setText("" + dollar);
} else {
Toast.makeText(this, "Señor usuario no se puede realizar su acción", Toast.LENGTH_LONG).show();
}
break;
}
}
public void log(String content) {
Log.d("myLog", content);
}
}
| true
|
6396c153708eea0a60dfd412c88374196d818e96
|
Java
|
shuihuacheng/game-2048
|
/src/com/leo/game/number/utils/BinaryUtils.java
|
UTF-8
| 428
| 3.015625
| 3
|
[] |
no_license
|
package com.leo.game.number.utils;
public class BinaryUtils {
// 检查第nPos位置是否为 0
public static boolean checkBinaryPos(int binary, int nPos) {
boolean bResult = (binary & ((int) Math.pow(2, nPos))) == 0;
return bResult;
}
// 将第nPos位置置为0
public static int setBinaryPosZero(int binary, int nPos) {
int nResult = binary;
nResult = binary ^ ((int) Math.pow(2, nPos));
return nResult;
}
}
| true
|
040001fcc3f96357f01fd28c3cf64742a29035e3
|
Java
|
akashchandra111/IBM_assignments
|
/Java_assignment_17_may_19/FindDateDifference.java
|
UTF-8
| 942
| 3.84375
| 4
|
[] |
no_license
|
import java.time.LocalDate;
import java.time.Period;
class FindDateDifference {
public static void main(String[] args) {
System.out.print("Enter Date to find difference with current date [Format: (DD/MM/YYYY)]: ");
String userDate = new java.util.Scanner(System.in).nextLine();
Integer day, month, year;
boolean errorOccured = false;
do {
try {
day = Integer.parseInt(userDate.split("/")[0]);
month = Integer.parseInt(userDate.split("/")[1]);
year = Integer.parseInt(userDate.split("/")[2]);
Period gap = Period.between(LocalDate.of(year, month, day), LocalDate.now());
System.out.println("Difference between date is: " + gap.getDays()+ " days, " + gap.getMonths() + " months, " + gap.getYears() + " years.");
errorOccured = false;
}
catch(NumberFormatException npe) {
System.out.println("Enter date in given format");
errorOccured = true;
}
} while (errorOccured == true);
}
}
| true
|
c8a6ef6c09d94a7903b3d3c187cb8668d51de3f3
|
Java
|
moutainhigh/asiainfo
|
/rainbow-basic-dao/src/main/java/com/bdx/rainbow/mapper/jc/DrcMapper.java
|
UTF-8
| 3,126
| 1.851563
| 2
|
[] |
no_license
|
package com.bdx.rainbow.mapper.jc;
import com.bdx.rainbow.entity.jc.Drc;
import com.bdx.rainbow.entity.jc.DrcExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface DrcMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int countByExample(DrcExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int deleteByExample(DrcExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int deleteByPrimaryKey(String jgmCode);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int insert(Drc record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int insertSelective(Drc record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
List<Drc> selectByExample(DrcExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
Drc selectByPrimaryKey(String jgmCode);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int updateByExampleSelective(@Param("record") Drc record, @Param("example") DrcExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int updateByExample(@Param("record") Drc record, @Param("example") DrcExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int updateByPrimaryKeySelective(Drc record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
int updateByPrimaryKey(Drc record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table cfda_drc
*
* @mbggenerated Mon Nov 16 14:15:08 CST 2015
*/
void insertBatch(List<Drc> recordLst);
}
| true
|
136075a25dcc6e06614d3bc596753c5f7fd8e3c6
|
Java
|
HouYW/e3mall_Parent
|
/e3mall-manager-web/src/main/java/cn/e3mall/controller/ItemController.java
|
UTF-8
| 1,379
| 2.078125
| 2
|
[] |
no_license
|
package cn.e3mall.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.e3mall.common.EasyUIResult;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.service.ItemService;
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
/**
* @Title: pageQueryItem
* @Description:(商品列表分页查询)
* @time 2017年12月29日下午10:27:42
* @name 黄加耀
*/
// @RequestParam(defaultValue="1") 当值为空的话,给设置一个默认值
@RequestMapping("/item/list")
public EasyUIResult pageQueryItem(@RequestParam(defaultValue="1") Integer page ,@RequestParam(defaultValue="30") Integer rows) throws Exception{
EasyUIResult result = itemService.pageQueryItem(page,rows);
return result;
}
/**
* @Title: findItemById
* @Description:(根据ID查询Item对象)
* @time 2017年12月28日下午2:49:12
* @name 黄加耀
*/
@RequestMapping("/item/{id}")
public TbItem findItemById(@PathVariable Long id) throws Exception{
TbItem item = itemService.findItemById(id);
return item;
}
}
| true
|
8c71d5d2b03ca47da7b655f24ff3ae694fabce46
|
Java
|
zhaoliang-mq/live-
|
/springboot-payment/src/main/java/com/fh/mapper/PaymentMapper.java
|
UTF-8
| 174
| 1.546875
| 2
|
[] |
no_license
|
package com.fh.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fh.model.Payment;
public interface PaymentMapper extends BaseMapper<Payment> {
}
| true
|
fa684955e4e5977dc913caa19ceb5312cbdb6c83
|
Java
|
Managine/simPL-Compiler
|
/src/simpl/typing/TypeVar.java
|
UTF-8
| 1,564
| 2.859375
| 3
|
[] |
no_license
|
package simpl.typing;
import simpl.parser.Symbol;
public class TypeVar extends Type {
private static int tvcnt = 0;
private boolean equalityType;
private Symbol name;
public TypeVar(boolean equalityType) {
this.equalityType = equalityType;
name = Symbol.symbol("tv" + ++tvcnt);
}
@Override
public boolean equalsType(Type t) {
if (!(t instanceof TypeVar))
return false;
return this.name.equals(((TypeVar)t).name);
}
@Override
public boolean isEqualityType() {
return equalityType;
}
@Override
public Substitution unify(Type t) throws TypeCircularityError {
if (!(t instanceof TypeVar))
if (t.contains(this))
throw new TypeCircularityError();
Substitution s=Substitution.of(this, t);
try {
Type tmp=TypeEnv.sub.apply(this);
if (tmp!=this) {
Substitution s2=tmp.unify(t);
return s.compose(s2);
}
}
catch (Exception e) {}
return s;
}
public String toString() {
return "" + name;
}
@Override
public boolean contains(TypeVar tv) {
if ((tv.toString()).equals(this.name.toString()))
return true;
else
return false;
}
@Override
public Type replace(TypeVar a, Type t) {
if (this.contains(a)) {
this.equalityType=t.isEqualityType();
return t;
}
else
return this;
}
}
| true
|
d004d7252505e4983b36038ff3a9f93e9cafb4e4
|
Java
|
SurferJim/BioMight
|
/BioMightWeb/src/biomight/cell/epithelial/EpithelialCell.java
|
UTF-8
| 9,496
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Created on Jul 22, 2006
* Copyright 2006 - Biomight.org
*
* This code is the not to be used without written permission from
* BioMight.org
*
*/
package biomight.cell.epithelial;
import java.lang.reflect.Method;
import java.util.ArrayList;
import biomight.BioMightBase;
import biomight.Constants;
import biomight.cell.CellMembrane;
import biomight.view.BioMightMethodView;
import biomight.view.BioMightPropertyView;
import biomight.view.BioMightTransform;
/**
* Representation of an Epithelial Cell
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class EpithelialCell extends BioMightBase {
protected int viewPerspective;
// Inner Components
//private Choroid choroid;
//private ParsPlana parsPlana;
private CellMembrane cellMembrane;
public EpithelialCell()
{
// Create the base epithelialCell
create(Constants.EpithelialCellRef, null);
}
public EpithelialCell(String parentID)
{
create(parentID, null);
}
public EpithelialCell(String parentID, ArrayList<BioMightMethodView> bioMightMethods)
{
this.parentID = parentID;
create(parentID, bioMightMethods);
}
/************************************************************************************
*
* CREATE EpithelialCell
* @param EpithelialCellReference
***********************************************************************************/
public void create(String parentID, ArrayList<BioMightMethodView> bioMightMethods)
{
this.setImage("images/EpithelialCell.jpg");
viewPerspective = Constants.VIEW_FLOATING;
if (viewPerspective == Constants.VIEW_FLOATING) {
// If we have initialization parameters from the form,
// then apply them before constructing the objects.
if (bioMightMethods != null){
System.out.println("NEED TO EXECUTE EpithelialCell METHODS: " + bioMightMethods.size());
}
cellMembrane = new CellMembrane(parentID, bioMightMethods);
initProperty("CellMembrane", Constants.CellMembrane, Constants.CellMembraneRef, cellMembrane.getComponentID());
System.out.println("EpithelialCell - CellMembrane is created");
}
else if (viewPerspective == Constants.VIEW_INTERNAL) {
//cellMembrane = new CellMembrane(parentID, bioMightMethods);
//initProperty("Pupil", Constants.Chest, Constants.ChestRef, chest.getComponentID());
System.out.println("EpithelialCell - CellMembrane is created");
}
initProperties();
initMethods();
}
public void initProperties() {
properties = new ArrayList<BioMightPropertyView>();
BioMightPropertyView property = new BioMightPropertyView();
property.setPropertyName("MedialCommissure");
property.setCanonicalName(Constants.MedialCommissure);
properties.add(property);
property = new BioMightPropertyView();
property.setPropertyName("BiPolarCell");
property.setCanonicalName(Constants.BiPolarCell);
properties.add(property);
}
public void initMethods() {
methods = new ArrayList<BioMightMethodView>();
BioMightMethodView method = new BioMightMethodView();
method = new BioMightMethodView();
method.setCanonicalName(Constants.EpithelialCell);
method.setMethodName("setMaterial");
method.setDisplayName("Material");
method.setHtmlType(Constants.BIO_DROPDOWN);
method.setDataType(Constants.BIO_TEXT);
method.setValueMap(materialDDMap);
methods.add(method);
method = new BioMightMethodView();
method.setCanonicalName(Constants.EpithelialCell);
method.setMethodName("setTexture");
method.setDisplayName("Texture");
method.setHtmlType(Constants.BIO_DROPDOWN);
method.setDataType(Constants.BIO_TEXT);
method.setValueMap(textureDDMap);
methods.add(method); }
public void redraw(int parentID)
{
viewPerspective = Constants.VIEW_FLOATING;
if (viewPerspective == Constants.VIEW_FLOATING) {
System.out.println("EpithelialCell Redraw");
}
this.setImage("images/LeftEpithelialCell.jpg");
}
/********************************************************************************************************************
* GET X3D
*
* This method will return the X3D for the Cell. It runs through each of its components and collects up their
* representations and then assembles them into one unified X3D model.
*
********************************************************************************************************************/
public String getX3D(boolean snipet) {
// Assembe the EpithelialCell
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.0//EN\" \"http://www.web3d.org/specifications/x3d-3.0.dtd\">\n " +
"<X3D profile='Immersive' >\n" +
"<head>\n" +
"<meta name='BioMightImage' content='EpithelialCell.jpg'/>\n" +
"<meta name='ExportTime' content='7:45:30'/>\n" +
"<meta name='ExportDate' content='08/15/2008'/>\n" +
"<meta name='BioMight Version' content='1.0'/>\n" +
"</head>\n" +
"<Scene>\n" +
"<WorldInfo\n" +
"title='EpithelialCell'\n" +
"info='\"BioMight Generated X3D\"'/>\n";
String body = "";
int view = Constants.VIEW_FLOATING;
if (view == Constants.VIEW_FLOATING)
{
System.out.println("Getting composite X3D for EpithelialCell");
body = cellMembrane.getX3D(true);
}
else
{
body = "";
/*
cone.getX3D(true) +
cornea.getX3D(true);
*/
}
System.out.println("EpithelialCell X3D: " + body);
String footer = "</Scene>" + "</X3D>\n";
if (snipet)
return body;
else
return header + body + footer;
}
/******************************************************************************************
* EXECUTE METHODS
*
******************************************************************************************/
public void executeMethods(ArrayList<String> methodParams) {
// Run through the argument list and executes the
// associated methods
System.out.println("HEAD-Executing Methods");
for (int j=0; j<methodParams.size(); j++){
// Get the parameter from the list and if it is not
// empty execute the associated method using it
String methodParam = methodParams.get(j);
if (methodParam != null) {
if (!methodParam.equals("")) {
String methodName = (String) methods.get(j).getMethodName();
String htmlType = (String) methods.get(j).getHtmlType();
String dataType = (String) methods.get(j).getDataType();
System.out.println("Execute Method " + methodName + " Arg: " + methodParam);
System.out.println("HtmlType " + htmlType + " with DataType: " + dataType);
// Use the DataType parameter to convert the data into its base form
if (dataType.equals("int")) {
try {
System.out.println("Locating Method(Integer)" + methodName);
// Locate the method through introspection
int numElements = Integer.parseInt(methodParam);
Class paramsType[] = {int.class};
Method method = this.getClass().getDeclaredMethod(methodName, paramsType);
System.out.println("Before Execute Method(Integer)" + methodName);
Object result = method.invoke(this, numElements);
System.out.println("Before Execute Method(Integer)" + methodName);
}
catch (NumberFormatException e)
{
System.out.println("Could not Convert to int: " + methodParam);
}
catch (NoSuchMethodException e)
{
System.out.println("Method with int param not found: " + e);
}
catch (Exception e)
{
System.out.println("General Exception occurred: " + e);
}
}
else if (dataType.equals("String")) {
try {
System.out.println("Locating Method(String)");
Class paramsType[] = {String.class};
Method method = this.getClass().getDeclaredMethod(methodName, paramsType );
System.out.println("Method with String Param: " + method.getName());
System.out.println("Before Execute Method(Integer)" + methodName);
Object result = method.invoke(this, methodParam);
System.out.println("After Execute Method(Integer)" + methodName);
}
catch (NoSuchMethodException e)
{
System.out.println("Method with int param not found!");
}
catch (Exception e)
{
System.out.println("General Exception occurred!");
}
}
else if (dataType.equals("double")) {
}
else if (dataType.equals("")) {
}
}
}
}
}
public ArrayList<BioMightMethodView> getMethods() {
return methods;
}
public void setMethods(ArrayList<BioMightMethodView> methods) {
this.methods = methods;
}
public ArrayList<BioMightPropertyView> getProperties() {
return properties;
}
public void setProperties(ArrayList<BioMightPropertyView> properties) {
this.properties = properties;
}
public String getComponentID() {
return componentID;
}
public void setComponentID(String componentID) {
this.componentID = componentID;
}
}
| true
|
35eef1ab73e4af610b7765916dac787e2ffa5e11
|
Java
|
tangchaolibai/mvp
|
/yours-dev-jenkins/mvp-ms-web/src/main/java/com/hsb/mvpmsweb/validator/PictureTypeValidator.java
|
UTF-8
| 608
| 2.34375
| 2
|
[] |
no_license
|
package com.hsb.mvpmsweb.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.web.multipart.MultipartFile;
import com.hsb.mvpmsweb.api.annotation.PictureType;
public class PictureTypeValidator implements ConstraintValidator<PictureType, MultipartFile>{
@Override
public boolean isValid(MultipartFile posterPic, ConstraintValidatorContext context) {
String name = posterPic.getOriginalFilename();
String subffix = name.substring(name.lastIndexOf('.'));
return "jpg".equals(subffix) || "png".equals(subffix);
}
}
| true
|
de0973c82f939e1031be8de9038bdb01d0b4cfb2
|
Java
|
mengduancanxiao/FundCollect
|
/src/main/java/handle/ElasticSearchHandle.java
|
UTF-8
| 7,023
| 2.265625
| 2
|
[] |
no_license
|
package handle;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import model.FundMain2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import util.ClientUtil;
import util.DateUtils;
import util.StringUtils;
@SuppressWarnings({ "unused", "resource" })
public class ElasticSearchHandle {
/**
* 创建一个新的索引:
* curl -XPUT "http://172.16.3.234:9200/blog"
*
* 添加一条文档
* curl -XPUT "http://172.16.3.234:9200/blog/article/1" -d '{"title":"age","content":"18"}'
curl -XPUT "http://172.16.3.234:9200/blog/article/2" -d '{"field":"age","value":"18"}'
*/
private static Logger log = LogManager.getLogger(ElasticSearchHandle.class);
private static final int SIZE = 1500;
private static String ip1 = "172.16.3.234";
private static String ip2 = "127.0.0.1";
private static String ip3 = "172.16.11.113";
public static void main(String[] args) {
// generateIndex(ip3);
// searchByID(ip2);
searchByCondition();
// deleteIndex(ip2);
}
public static TransportClient getClinet(String ip){
TransportClient client = null;
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
try {
//创建client
// client = new PreBuiltTransportClient(settings)
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip), 9300));
} catch (Exception e) {
e.printStackTrace();
}
return client;
}
/**
* 通过ID查找数据
* @param ip
*/
public static void searchByID(String ip){
TransportClient client = getClinet(ip);
//搜索数据
GetResponse response = null;
for (int i = 0; i < 15; i++) {
response = client.prepareGet("fund", "fund_main", (i + "")).execute().actionGet();
//输出结果
System.out.println(response.getSourceAsString());
}
//关闭client
client.close();
}
/**
* 通过条件查找数据
* @param ip
*/
public static void searchByCondition(){
long start = System.currentTimeMillis();
Map<String, List<FundMain2>> map = new HashMap<String, List<FundMain2>>();
TransportClient client = ClientUtil.getClient();
String fundcode[] = new String[]{"519066","000457","110022","020026","001542","001410"};
for (String s : fundcode) {
//搜索数据
QueryBuilder matchQuery = QueryBuilders.matchQuery("fundcode", s);
HighlightBuilder hiBuilder = new HighlightBuilder();
hiBuilder.preTags("<h2>");
hiBuilder.postTags("</h2>");
hiBuilder.field("fundcode");
SearchResponse response = client.prepareSearch("fund").setQuery(matchQuery).highlighter(hiBuilder)
.execute().actionGet();
//获取查询结果集
SearchHits searchHits = response.getHits();
List<FundMain2> list = new ArrayList<FundMain2>();
//遍历结果
for(SearchHit hit : searchHits){
FundMain2 fund = StringUtils.str2FundMain2(hit.getSourceAsString());
list.add(fund);
}
map.put(s, list);
}
//关闭client
client.close();
long end = System.currentTimeMillis();
System.out.println("查询结束,耗时:" + (end - start));
}
/**
* 创建索引,并插入信息
* @param ip
*/
public static void generateIndex(String ip) {
System.out.println("开始插入数据:" + DateUtils.date2string2(new Date()));
long start = System.currentTimeMillis();
//创建client
TransportClient client = getClinet(ip);
for (int i = 0; i < 5000; i++) {
Map<String, Object> json = new HashMap<String, Object>();
json.put("user", "tom_" + i);
json.put("age", i);
json.put("inserttime", DateUtils.date2string(new Date()));
json.put("message", "Hello World! Hello " + "Jack_" + i + ".");
IndexResponse response = client.prepareIndex("bhm", "user", (i + "")).setSource(json).execute().actionGet();
System.out.println("插入完成时间:" + DateUtils.date2string2(new Date()) + " json = " + json);
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
//关闭client
client.close();
}
/**
* 分页遍历数据
*/
public static void scrollQuery() {
long start = System.currentTimeMillis();
int times = 2;
int count = 0;
TransportClient esClient = ClientUtil.getClient();
SearchResponse searchResponse = esClient.prepareSearch("fund")
//实际返回的数量为5*index的主分片格式
.setSize(SIZE)
//这个游标维持多长时间
.setScroll(TimeValue.timeValueMinutes(8))
//添加排序
.addSort("id", SortOrder.ASC)
.execute().actionGet();
//第一次查询,只返回数量和一个scrollId
log.info("共搜到:{}{}", searchResponse.getHits().getTotalHits(), "条结果!");
log.info("本次遍历:{}{}", searchResponse.getHits().hits().length, "条结果");
//第一次运行没有结果
log.info("第 1 次遍历数据------------------------------------------------------------");
for (SearchHit hit : searchResponse.getHits()) {
log.info(hit.getSourceAsString());
}
count+=SIZE;
while(count < searchResponse.getHits().getTotalHits()){
log.info("第 " + times + " 次遍历数据------------------------------------------------------------");
//使用上次的scrollId继续访问
searchResponse = esClient.prepareSearchScroll(searchResponse.getScrollId())
.setScroll(TimeValue.timeValueMinutes(8))
.execute().actionGet();
log.info("本次遍历:" + searchResponse.getHits().hits().length + "条结果");
for (SearchHit hit : searchResponse.getHits()) {
log.info(hit.getSourceAsString());
}
count +=SIZE;
times++;
}
long end = System.currentTimeMillis();
log.info("遍历{}条结果耗时:{}",searchResponse.getHits().hits().length, (end - start));
}
/**
* 删除索引数据对应ID数据
* @param ip
*/
public static void deleteIndex(String ip){
//创建client
TransportClient client = getClinet(ip);
DeleteResponse response = client.prepareDelete("blog", "article", "3").execute().actionGet();
System.out.println(response.getResult().toString());
}
}
| true
|
f48a6f708d067f3162b96960939458a41a4be667
|
Java
|
ioe7th/JAVA_EE
|
/前台商城/src/test/java/ShopcartServiceTest.java
|
UTF-8
| 849
| 2.046875
| 2
|
[] |
no_license
|
import static org.junit.Assert.*;
import java.util.List;
import org.fkit.domain.CartItem;
import org.fkit.service.ShopcartService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class ShopcartServiceTest extends BaseJunitTest {
@Autowired
private ShopcartService shopcartService;
//根据pid进行筛选
@Test
public void testselectCartpid()throws Exception{
CartItem cartItem =shopcartService.selectCart(1);
System.out.println(cartItem);
}
//根据uid进行查询
@Test
public void testselectuid()throws Exception{
List<CartItem> cartItems=shopcartService.selectcartitem(20);
System.out.println(cartItems);
}
//删除购物车记录
@Test
public void testRemove()throws Exception{
shopcartService.remove(2,20);
System.out.println("成功删除");
}
}
| true
|
cac070d4e087c2ac1370309d88a0179c4a254f87
|
Java
|
srihari1204/spring-feature-toggle
|
/src/main/java/com/cubic/controller/EmployeeController.java
|
UTF-8
| 997
| 1.960938
| 2
|
[] |
no_license
|
package com.cubic.controller;
import com.cubic.data.Employee;
import com.cubic.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.togglz.core.manager.FeatureManager;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@Autowired
private FeatureManager featureManager;
@GetMapping("/")
public List<Employee> getEmployees()
{
return employeeService.findAll();
}
@GetMapping("/{id}")
public Employee findEmployeeById(@PathVariable("id") int id)
{
//System.out.println("========"+id);
return employeeService.findEmployeeById(id);
}
}
| true
|
8a400f8bf6208c5c93913e3da7b30d894482c660
|
Java
|
flyFishOK/spring-boot-study
|
/src/main/java/com/minbo/springdemo/web/WebConfig.java
|
UTF-8
| 625
| 2.21875
| 2
|
[] |
no_license
|
package com.minbo.springdemo.web;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 拦截器定义
* @author Minbo.He
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//定义过滤拦截的url名称,例如/hello/**,表示hello下所有的名称请求
registry.addInterceptor(new HttpInterceptor()).addPathPatterns("/hello/**");
}
}
| true
|
07ac2ab08e5522d9c4d6b61662e93bd17d6224da
|
Java
|
woweichongzhen/apollo
|
/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java
|
UTF-8
| 6,122
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
/**
* 抽象的配置文件
*
* @author Jason Song(song_s@ctrip.com)
*/
public abstract class AbstractConfigFile implements ConfigFile, RepositoryChangeListener {
private static final Logger logger = LoggerFactory.getLogger(AbstractConfigFile.class);
/**
* 配置回调更改触发线程池
*/
private static final ExecutorService EXECUTOR_SERVICE;
/**
* 配置仓库
*/
protected final ConfigRepository configRepository;
/**
* 本配置的命名空间
*/
protected final String namespace;
/**
* 配置属性原子引用
*/
protected final AtomicReference<Properties> configProperties;
/**
* 配置文件变更监听器
*/
private final List<ConfigFileChangeListener> listeners = Lists.newCopyOnWriteArrayList();
/**
* 属性实例生产仓库
*/
protected final PropertiesFactory propertiesFactory;
/**
* 配置来源类型
*/
private volatile ConfigSourceType sourceType = ConfigSourceType.NONE;
static {
EXECUTOR_SERVICE = Executors.newCachedThreadPool(
ApolloThreadFactory.create("ConfigFile", true));
}
public AbstractConfigFile(String namespace, ConfigRepository configRepository) {
this.configRepository = configRepository;
this.namespace = namespace;
configProperties = new AtomicReference<>();
propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class);
// 初始化配置文件
this.initialize();
}
/**
* 初始化配置文件
*/
private void initialize() {
try {
// 加载配置,设置配置属性和来源引用
configProperties.set(configRepository.getConfig());
sourceType = configRepository.getSourceType();
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Config File failed - namespace: {}, reason: {}.",
namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
// 注册状态改变监听器
configRepository.addChangeListener(this);
}
}
@Override
public String getNamespace() {
return namespace;
}
/**
* 更新
*
* @param newProperties 新属性
*/
protected abstract void update(Properties newProperties);
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(configProperties.get())) {
return;
}
// 获取旧内容
String oldValue = getContent();
// 更新新属性、内容、来源类型
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
update(newProperties);
sourceType = configRepository.getSourceType();
// 获取新内容
String newValue = getContent();
PropertyChangeType changeType = PropertyChangeType.MODIFIED;
// 如果老内容为空,则是新增,如果新内容为空,则是删除
if (oldValue == null) {
changeType = PropertyChangeType.ADDED;
} else if (newValue == null) {
changeType = PropertyChangeType.DELETED;
}
// 触发配置文件改变事件
this.fireConfigChange(new ConfigFileChangeEvent(this.namespace, oldValue, newValue, changeType));
Tracer.logEvent("Apollo.Client.ConfigChanges", this.namespace);
}
@Override
public void addChangeListener(ConfigFileChangeListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
@Override
public boolean removeChangeListener(ConfigFileChangeListener listener) {
return listeners.remove(listener);
}
@Override
public ConfigSourceType getSourceType() {
return sourceType;
}
/**
* 触发配置文件改变
*
* @param changeEvent 配置文件改变事件
*/
private void fireConfigChange(final ConfigFileChangeEvent changeEvent) {
for (final ConfigFileChangeListener listener : listeners) {
EXECUTOR_SERVICE.submit(new Runnable() {
@Override
public void run() {
String listenerName = listener.getClass().getName();
Transaction transaction = Tracer.newTransaction("Apollo.ConfigFileChangeListener", listenerName);
try {
// 异步触发改变
listener.onChange(changeEvent);
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
Tracer.logError(ex);
logger.error("Failed to invoke config file change listener {}", listenerName, ex);
} finally {
transaction.complete();
}
}
});
}
}
}
| true
|
45fa216005f68a815863aca9699ff90bbfa8543c
|
Java
|
lzj1995822/jrwm-api
|
/src/main/java/com/zkf/mysql/repository/SystemUserRepo.java
|
UTF-8
| 2,670
| 2.03125
| 2
|
[] |
no_license
|
package com.zkf.mysql.repository;
import com.zkf.mysql.entity.SysUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository("systemUserRepo")
public interface SystemUserRepo extends PagingAndSortingRepository<SysUser, Integer> {
// List<SysUser> findAll();
SysUser findByUserId(String userId);
List<SysUser> findByRoleId(String roleId);
SysUser findByUserName(String userName);
@Query("select m from SysUser m order by m.createTime desc")
Page<SysUser> findByTime(Pageable pageAble);
@Query("select m from SysUser m where m.userId = :userName order by m.createTime desc")
Page<SysUser> findByUserName(@Param("userName")String userName, Pageable pageAble);
@Query("select m from SysUser m where m.roleId = :roleId order by m.createTime desc")
Page<SysUser> findByRoleId(@Param("roleId")String roleId, Pageable pageAble);
@Query("select m from SysUser m where m.roleId = :roleId and m.userId = :userName order by m.createTime desc")
Page<SysUser> findByRoleIdAndName(@Param("roleId")String roleId, @Param("userName")String userName, Pageable pageAble);
//
// List<SysUser> findByUserName(String userName);
//
// SysUser findByUserIdAndUserName(String userId, String userName);
//
SysUser findByUserIdAndUserPwd(String userId, String password);
//
// @Transactional
// @Modifying
// @Query("update SysUser set lastLoginTime = ?1, lastLoginIp = ?2 where userId = ?3")
// public int changeLoginTimeAndIp(Timestamp lastLoginTime, String lastLoginIp, String userId);
@Transactional
@Modifying
@Query("update SysUser set userPwd = ?1 where userId = ?2")
public int changeUserPwd(String userPwd, String userId);
// @SuppressWarnings("unchecked")
// public SysUser save(SysUser sysUser);
@Transactional
@Modifying
@Query("update SysUser set userName = ?1, modules = ?2, roleId = ?3 , storesId = ?5 where userId = ?4")
public int changeForSystemManage(String userName, String modules, String roleId, String userId, Integer storesId);
// public void delete(SysUser sysUser);
//
// @Transactional
// @Modifying
// @Query("update SysUser set modules = ?1 where userId = ?2")
// public int changeModules(String modules, String userId);
}
| true
|
20bac8a801a1563f57d432abf089f6d19b600188
|
Java
|
juanmafx/UTN
|
/111Mil/Enuciado1 Resuelto -111Mil/ej5enu1.java
|
UTF-8
| 3,199
| 3.59375
| 4
|
[] |
no_license
|
/*
5 Postulantes a un empleo
Se tienen los datos de tres postulantes a un empleo,
a los que se les realizó un test de capacitación.
Por cada postulante, se tiene entonces la siguiente información:
nombre del postulante, cantidad total de preguntas que se le realizaron
cantidad de preguntas que contestó correctamente.
Se pide confeccionar un programa que lea los datos de los tres postulantes,
informe el nivel de cada uno según los criterios de aprobación que se indican mas abajo, e indique finalmente el nombre del postulante que ganó el puesto. Los criterios de aprobación son los siguientes, en función del porcentaje de respuestas correctas sobre el total de preguntas realizadas a cada postulante:
Nivel Superior: Porcentaje >= 90%
Nivel Medio: 75% <= Porcentaje < 90%
Nivel Regular: 50% <= Porcentaje < 75%
Fuera de Nivel: Porcentaje < 50%
*/
import java.util.*;
public class ej5enu1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double ppc1;
String rango1="";
double ppc2;
String rango2="";
double ppc3;
String rango3="";
System.out.println("Nombre postulante 1:");
String p1 = sc.next();
System.out.println("Cantidad de Preguntas Correctas de "+p1+ " ?");
double pc1 = sc.nextDouble();
System.out.println("Cantidad de preguntas Totals de "+p1+ " ?");
double pt1 = sc.nextDouble();
System.out.println("Nombre postulante 2:");
String p2 = sc.next();
System.out.println("Cantidad de Preguntas Correctas de "+p2+ " ?");
double pc2 = sc.nextDouble();
System.out.println("Cantidad de preguntas Totals de "+p2+ " ?");
double pt2 = sc.nextDouble();
System.out.println("Nombre postulante 3:");
String p3 = sc.next();
System.out.println("Cantidad de Preguntas Correctas de "+p3+ " ?");
double pc3 = sc.nextDouble();
System.out.println("Cantidad de preguntas Totals de "+p3+ " ?");
double pt3 = sc.nextDouble();
ppc1 = (pc1/pt1)*100;
if (ppc1 >= 90)
rango1="superior";
if ((ppc1 >=75) && (ppc1 < 90))
rango1="medio";
if ((ppc1 >= 50) && ( 75 > ppc1))
rango1="regular";
if (ppc1 < 50)
rango1="Fuera de Nivel";
ppc2 = (pc2/pt2)*100;
if (ppc2 >= 90)
rango2="superior";
if ((ppc2 >=75) && (ppc2 < 90))
rango2="medio";
if ((ppc2 >= 50) && ( 75 > ppc2))
rango2="regular";
if (ppc2 < 50)
rango2="Fuera de Nivel";
ppc3 = (pc3/pt3)*100;
if (ppc3 >= 90)
rango3="superior";
if ((ppc3 >=75) && (ppc3 < 90))
rango3="medio";
if ((ppc3 >= 50) && ( 75 > ppc3))
rango3="regular";
if (ppc3 < 50)
rango3="Fuera de Nivel";
if (( ppc1 > ppc2 ) && ( ppc1 > ppc3 ))
System.out.println("El postulante " + p1 + " Es el ganador del puesto.");
if (( ppc2 > ppc1 ) && ( ppc2 > ppc3 ))
System.out.println("El postulante " + p2 + " Es el ganador del puesto.");
if (( ppc3 > ppc1 ) && ( ppc3 > ppc2 ))
System.out.println("El postulante " + p3 + " Es el ganador del puesto.");
System.out.println("El postulante \""+ p1 +"\" posee un nivel "+ rango1 +" con un "+ ppc1 + "% de acierto .");
System.out.println("El postulante \""+ p2 +"\" posee un nivel "+ rango2 +" con un "+ ppc2 + "% de acierto .");
System.out.println("El postulante \""+ p3 +"\" posee un nivel "+ rango3 +" con un "+ ppc3 + "% de acierto .");
}
}
| true
|
5a7a8dc4d1971dee91ed964a9566004412ebd84f
|
Java
|
BSK-Baesick/Java-Activity-Outputs
|
/src/activity/output/ProgramCreation2/JLabelTest.java
|
UTF-8
| 4,378
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
package activity.output.ProgramCreation2;
import javax.swing.*;
/**
*
* <h1> JFrameTest </h1>
*
* <h2>
* A form application in java with the following features:
* 1.The window title must be your name in uppercase.
* 2.Window size is 300 pixels wide and 300 pixels height
* 3.Must be able to automatically terminate the program when closing the window.
* 4.Must have a label with your name on it in lowercase
* </h2>
*
* @author Matthew Johannes C. Balubar
* @version 2020.12.0a1
* @since 2020-7-10
*
* @moduleNumber Module #6
* @moduleWeek Week-6
* @activityNumber Part #1
*
* <Pseudocode>
*
* TODO: Instantiate JFrame (https://www.javatpoint.com/java-jframe)
* TODO: Instantiate JLabel (https://www.geeksforgeeks.org/jlabel-java-swing/)
* TODO: Use the JFrame to display a GUI window with a size of 300x300
* TODO: Use the JLabel to display a label/text inside the GUI Window
* TODO: The window label must be the same as my name
* TODO: Create a method that will terminate the program after closing the window.
* TODO: Refactor Code
*
* </Pseudocode>
*
*/
public class JLabelTest
{
// Configuration Parameters
private static boolean isVisible = true; // specifies whether the window is visible or not
private static String myName = "Matthew Johannes C. Balubar"; // student's name
// Cached Components
// JFrame class is a type of container which inherits the java. awt.
// Frame class. JFrame works like the main window where components like labels, buttons, text fields
// are added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the
// help of setDefaultCloseOperation(int) method.
private static JFrame jFrame;
// JLabel is a class of java Swing. JLabel is used to display a short string or an image icon.
// JLabel can display text, image or both. JLabel is only a display of text or image and it cannot get focus.
// JLabel is inactive to input events such a mouse focus or keyboard focus.
private static JLabel jLabel;
/**
* Main method is called on the frame when the program is enabled just before any of the methods are called the first time.
* @param args - accepts a single argument of type String array
*/
public static void main(String[] args)
{
// Initialize cached components
// Create a new JFrame object and set its title to my name
jFrame = new JFrame(myName);
// Create a new JLabel object and display myName in lowercase inside the GUI Window
jLabel = new JLabel(myName.toLowerCase());
// Setup the window
Setup();
// Open the window
OpenWindow();
}
private static void OpenWindow()
{
// Show the window
jFrame.setVisible(isVisible);
}
private static void Setup()
{
// Set the size of our window
jFrame.setSize(300, 300);
// Specifies what happens when the user closes the frame. The EXIT_ON_CLOSE operation exits the program when
// the user closes the frame. This behavior is appropriate for this program because the program has only one
// frame, and closing the frame makes the program useless.
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the JLabel object to the GUI window
jFrame.add(jLabel);
}
/**
*
* OUTPUT/RESULT:
*
* CONSOLE MESSAGE AT THE START OF THE PROGRAM:
* "C:\Users\my pc\.jdks\openjdk-15\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\lib\idea_rt.jar=5987:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\my pc\Documents\MEGA\Projects\Java\JavaActivityOutputs\out\production\Java" activity.output.ProgramCreation2.JLabelTest
*
* THE GUI WINDOW: See application at https://imgur.com/sFfuB3u
*
* CONSOLE MESSAGE AFTER CLOSING THE PROGRAM:
* "C:\Users\my pc\.jdks\openjdk-15\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\lib\idea_rt.jar=5987:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\my pc\Documents\MEGA\Projects\Java\JavaActivityOutputs\out\production\Java" activity.output.ProgramCreation2.JLabelTest
*
* Process finished with exit code 0
*
*/
}
| true
|
6bc4a13683f872e32c2cc4f6c5b8070217b1f085
|
Java
|
Lavazz/JavaWeb
|
/Day2/src/by/trjava/task02/dao/exception/WrongPathException.java
|
UTF-8
| 276
| 2.265625
| 2
|
[] |
no_license
|
package by.trjava.task02.dao.exception;
public class WrongPathException extends Exception {
public WrongPathException(String message){
super(message);
}
public WrongPathException(String message, Throwable cause) {
super(message, cause);
}
}
| true
|
410143ea01a15d07194d13d86fdea1e886cb0808
|
Java
|
rlaehgns5399/algorithm
|
/baekjoon/1000/Q1793.java
|
UTF-8
| 629
| 3.21875
| 3
|
[] |
no_license
|
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
BigInteger[] dp = new BigInteger[251];
dp[0] = BigInteger.valueOf(1); // 이거 왜 1?
dp[1] = BigInteger.valueOf(1); // 1
dp[2] = BigInteger.valueOf(3); // 3
dp[3] = BigInteger.valueOf(5); // 4
for(int i = 4; i <= 250; i++){
dp[i] = dp[i-1].add(dp[i-2].multiply(BigInteger.valueOf(2)));
}
while(sc.hasNextInt()){
System.out.println(dp[sc.nextInt()]);
}
}
}
| true
|
063350e76362422eae678136764ec32e7e32c5bf
|
Java
|
xiaobaigitb/BlogSystem
|
/src/main/java/com/duan/blogos/exception/internal/InternalIOException.java
|
UTF-8
| 378
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.duan.blogos.exception.internal;
/**
* Created on 2018/1/15.
* lucene IO操作出错
*
* @author DuanJiaNing
*/
public class InternalIOException extends InternalRuntimeException {
public static final int code = 2;
public InternalIOException(Throwable e) {
super(e, code);
}
public InternalIOException() {
super(code);
}
}
| true
|
1fbfa432a45f742f8fe7cbb2b6447150ada6343f
|
Java
|
VladKudryshov/Station
|
/src/main/java/com/epam/training/PhoneStation/service/impl/CallServiceImpl.java
|
UTF-8
| 1,862
| 2.40625
| 2
|
[] |
no_license
|
package com.epam.training.PhoneStation.service.impl;
import com.epam.training.PhoneStation.dao.api.CallDao;
import com.epam.training.PhoneStation.dao.api.UserDao;
import com.epam.training.PhoneStation.entity.CallEntity;
import com.epam.training.PhoneStation.entity.UserEntity;
import com.epam.training.PhoneStation.service.api.CallService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.sql.Time;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
@Service
@Transactional
public class CallServiceImpl implements CallService {
private static final Logger LOGGER = LoggerFactory.getLogger(CallServiceImpl.class);
@Autowired
private CallDao callDao;
@Autowired
private UserDao userDao;
@Override
@Transactional
public CallEntity addCall(String username, Time time) {
Calendar date = new GregorianCalendar();
UserEntity user = userDao.getByUserName(username);
CallEntity call = new CallEntity();
call.setUser(user);
call.setTime(time);
call.setDate(new Date(date.getTimeInMillis()));
call.setCost(123);
LOGGER.debug("Add call: {}",call);
return callDao.save(call);
}
@Override
@Transactional
public CallEntity gedById(long callId) {
return callDao.getById(callId);
}
@Override
@Transactional
public List<CallEntity> getAllByUser(long userId) {
UserEntity user = userDao.getById(userId);
return user.getCallEntities();
}
@Override
@Transactional
public List<CallEntity> getAll() {
return callDao.getAll();
}
}
| true
|
815a958bbdf4c72f90072cf7d8077f80bd31b34a
|
Java
|
erencetinkayaceng/Adisyon-Otomasyonu-Java-
|
/src/AnaEkran.java
|
UTF-8
| 9,460
| 2.15625
| 2
|
[] |
no_license
|
import ekran.KullaniciEkran;
import ekran.YoneticiEkran;
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author Cruz
*/
public class AnaEkran extends javax.swing.JFrame {
private String kAdi="ömer";
private String kSifre="çelik";
/**
* Creates new form Kullanici
*/
public AnaEkran() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
butonKullanici = new javax.swing.JButton();
butonYonetici = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
textKullaniciAdi = new javax.swing.JTextField();
PassTextSifre = new javax.swing.JPasswordField();
butonYoneticiGiris = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Giriş Sayfası");
setMaximumSize(new java.awt.Dimension(637, 469));
setMinimumSize(new java.awt.Dimension(637, 469));
setPreferredSize(new java.awt.Dimension(637, 469));
setResizable(false);
getContentPane().setLayout(null);
jPanel1.setOpaque(false);
butonKullanici.setBackground(new java.awt.Color(0, 0, 102));
butonKullanici.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
butonKullanici.setForeground(new java.awt.Color(255, 255, 255));
butonKullanici.setText("Kullanıcı Girişi");
butonKullanici.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butonKullaniciActionPerformed(evt);
}
});
butonYonetici.setBackground(new java.awt.Color(0, 0, 102));
butonYonetici.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
butonYonetici.setForeground(new java.awt.Color(255, 255, 255));
butonYonetici.setText("Yönetici Girişi");
butonYonetici.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butonYoneticiActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(butonKullanici, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(butonYonetici, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(butonKullanici)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(butonYonetici)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 160, 90);
jPanel2.setOpaque(false);
textKullaniciAdi.setBackground(new java.awt.Color(0, 51, 153));
textKullaniciAdi.setFont(new java.awt.Font("Segoe Print", 1, 14)); // NOI18N
textKullaniciAdi.setForeground(new java.awt.Color(255, 255, 255));
textKullaniciAdi.setText("ömer");
PassTextSifre.setBackground(new java.awt.Color(0, 51, 153));
PassTextSifre.setForeground(new java.awt.Color(255, 255, 255));
PassTextSifre.setText("çelik");
butonYoneticiGiris.setBackground(new java.awt.Color(0, 0, 102));
butonYoneticiGiris.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
butonYoneticiGiris.setForeground(new java.awt.Color(255, 255, 255));
butonYoneticiGiris.setText("Yönetici Giriş");
butonYoneticiGiris.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butonYoneticiGirisActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(butonYoneticiGiris))
.addComponent(PassTextSifre)
.addComponent(textKullaniciAdi, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
.addContainerGap(29, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(textKullaniciAdi, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(PassTextSifre, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(butonYoneticiGiris)
.addContainerGap(20, Short.MAX_VALUE))
);
getContentPane().add(jPanel2);
jPanel2.setBounds(150, 10, 170, 120);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resimler/giris.jpg"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 640, 470);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void butonKullaniciActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butonKullaniciActionPerformed
// TODO add your handling code here:
KullaniciEkran kEkran=new KullaniciEkran();
kEkran.show();
YoneticiEkran yEkran=new YoneticiEkran();
yEkran.show();
this.dispose();
}//GEN-LAST:event_butonKullaniciActionPerformed
private void butonYoneticiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butonYoneticiActionPerformed
// TODO add your handling code here:
jPanel2.setVisible(true);
}//GEN-LAST:event_butonYoneticiActionPerformed
private void butonYoneticiGirisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butonYoneticiGirisActionPerformed
// TODO add your handling code here:
String kontrolKAdi=textKullaniciAdi.getText();
String kontrolKSifre=PassTextSifre.getText();
if(kAdi.equals(kontrolKAdi)&&kSifre.equals(kontrolKSifre)){
YoneticiEkran yEkran =new YoneticiEkran();
yEkran.show();
KullaniciEkran kEkran=new KullaniciEkran();
kEkran.show();
this.dispose();
}
else{
JOptionPane.showMessageDialog(this, "Yanlış Cevap.");
}
}//GEN-LAST:event_butonYoneticiGirisActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AnaEkran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AnaEkran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AnaEkran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AnaEkran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AnaEkran().setVisible(true);
jPanel2.setVisible(false);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPasswordField PassTextSifre;
private javax.swing.JButton butonKullanici;
private javax.swing.JButton butonYonetici;
private javax.swing.JButton butonYoneticiGiris;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private static javax.swing.JPanel jPanel2;
private javax.swing.JTextField textKullaniciAdi;
// End of variables declaration//GEN-END:variables
}
| true
|
885f3cba4405f7d594cf7b6669c047fe6b5c76c5
|
Java
|
notmyfault02/Springboot-RestAPI
|
/api/src/main/java/com/notmyfault02/api/controller/HelloControllor.java
|
UTF-8
| 854
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package com.notmyfault02.api.controller;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloControllor {
@GetMapping(value = "/helloworld/string")
@ResponseBody
public String helloWorldString() {
return "Hello World";
}
@GetMapping(value = "/helloworld/json")
@ResponseBody
public Hello helloWorldJson() {
Hello hello = new Hello();
hello.message = "helloworld";
return hello;
}
@GetMapping(value = "/helloworld/page")
public String helloWorldPage() {
return "helloworld";
}
@Getter
@Setter
public static class Hello {
private String message;
}
}
| true
|
1c2ce3af88cfc8dc221889ba36f0c91f0694c42c
|
Java
|
ronnelreposo/kbas
|
/src/controllers/printing/GradesPrintingTemplate.java
|
UTF-8
| 9,521
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
package controllers.printing;
import functional.core.Tuple;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.collections.ObservableList;
import models.abstractions.IStudentGrade;
import models.database.StudentGradeDatabase;
/**
*
* @author Arya
*/
public final class GradesPrintingTemplate implements Printable
{
private final Tuple<Integer, String> session;
private final int X_INIT;
private final int Y_INIT;
private final int Y_PLUS;
private final int Y_INTERVAL;
private final int X_CENTER_TAB;
private final IndexPropertyStreamer
<String, Integer, ObservableList<IStudentGrade>> subjectCode;
private final IndexPropertyStreamer
<String, Integer, ObservableList<IStudentGrade>> midTerm;
private final IndexPropertyStreamer
<String, Integer, ObservableList<IStudentGrade>> finalTerm;
private final IndexPropertyStreamer
<String, Integer, ObservableList<IStudentGrade>> remark;
private final IndexPropertyStreamer
<String, Integer, ObservableList<IStudentGrade>> teacher;
private final StringDrawer<Graphics2D> drawer;
private GradesPrintingTemplate (Tuple<Integer, String> session)
{
this.session = session;
this.X_INIT = 20;
this.Y_INIT = 20;
this.Y_PLUS = 12;
this.Y_INTERVAL = 15;
this.X_CENTER_TAB = 200;
this.teacher = (i, l) ->
{
return l == null ? "" : l.get(i).getEmployee().getID();
};
this.remark = (i, l) ->
{
return l == null ? "" : l.get(i).getRemark();
};
this.finalTerm = (i, l) ->
{
return l == null ? "" : l.get(i).getFinalTerm();
};
this.midTerm = (i, l) ->
{
return l == null ? "" : l.get(i).getMidTerm();
};
this.subjectCode = (i, l) ->
{
return l == null ? "" : l.get(i).getSubject().getCode();
};
drawer = Drawer.Create();
}
public final static Printable Create (Tuple<Integer, String> session)
{
return new GradesPrintingTemplate(session);
}
@Override public int print (Graphics g, PageFormat pageFormat, int page) throws PrinterException
{
if (page > 0) { return NO_SUCH_PAGE; }
final Graphics2D g2d = (PrintingData.TranslatedGraphics(g, pageFormat));
final Tuple ssu =
(Tuple.Create(("Samar State University"),
(Point.Create((X_CENTER_TAB), (Y_INIT)))));
final Tuple heading =
(Tuple.Create(("Student Grades"),
(PrintingData.NextRowPoint((X_CENTER_TAB + X_INIT),
(Y_INTERVAL), (ssu)))));
final Tuple current_date =
(Tuple.Create("Date : " +
(new SimpleDateFormat("MMMM-dd-yyyy"))
.format((new Date())),
(PrintingData.NextRowPoint((X_INIT),
(Y_INTERVAL), (heading)))));
final String session_data = session.second();
final Tuple student_id =
(Tuple.Create(("Student ID : " + session_data),
(PrintingData.NextRowPoint((X_INIT),
(Y_INTERVAL), (current_date)))));
drawGrades((session_data),
draw((0), (g2d),
(new Tuple[] {
(ssu), (heading), (current_date), (student_id)
})),
(student_id));
return (PAGE_EXISTS);
}
private Graphics2D draw (int i, Graphics2D g2d, Tuple<String, IPoint>[] vector)
{
return ((i) > ((vector.length) - (1))) ? (g2d) :
(draw(((i) + (1)),
(drawer.draw(Tuple.Create((g2d),
(vector[i])))), (vector)));
}
private int lastIndexOf (ObservableList<IStudentGrade> list)
{
return (list == null) ? 0 : (list.size() - 1);
}
private Graphics2D drawValue (Tuple<IPrintingDat<IStudentGrade>, String> t)
{
return (drawer.draw((Tuple.Create((t.first().getGraphics2D()),
(Tuple.Create((t.second()), (t.first().getPoint())))))));
}
private Tuple drawSubjectCodeCol (int i, IPrintingDat<IStudentGrade> dat)
{
return ( i > lastIndexOf(dat.getList()) ) ?
(Tuple.Create((subjectCode.stream((i - 1),
(dat.getList()))),
(dat.getPoint())))
: (drawSubjectCodeCol((i + 1),
(new PrintingDat(
(drawValue(Tuple.Create((dat),
(subjectCode.stream((i),
(dat.getList())))))),
(dat.getPoint().nextAbscissa(Y_PLUS)),
(dat.getList())))));
}
private Tuple drawMidTermCol (int i, IPrintingDat<IStudentGrade> dat)
{
return ( (i) > (lastIndexOf(dat.getList())) ) ?
(Tuple.Create(midTerm.stream((i - 1),
(dat.getList())),
(dat.getPoint())))
: (drawMidTermCol((i + 1),
(new PrintingDat(
(drawValue(Tuple.Create((dat),
(midTerm.stream((i), (dat.getList())))))),
(dat.getPoint().nextAbscissa(Y_PLUS)),
(dat.getList())))));
}
private Tuple drawFinalTermCol (int i, IPrintingDat<IStudentGrade> dat)
{
return ( (i) > (lastIndexOf(dat.getList())) ) ?
(Tuple.Create(
(finalTerm.stream(((i) - (1)),
(dat.getList()))),
(dat.getPoint())))
: (drawFinalTermCol((i + 1),
(new PrintingDat(
(drawValue(Tuple.Create((dat),
(finalTerm.stream((i),
(dat.getList())))))),
(dat.getPoint().nextAbscissa(Y_PLUS)),
(dat.getList())))));
}
private Tuple drawRemarkCol (int i, IPrintingDat<IStudentGrade> dat)
{
return (( (i) > (lastIndexOf(dat.getList())) ) ?
(Tuple.Create((remark.stream(((i) - (1)),
(dat.getList()))),
(dat.getPoint())))
: (drawRemarkCol((i + 1),
(new PrintingDat((drawValue(Tuple.Create((dat),
(remark.stream((i),
(dat.getList())))))),
(dat.getPoint().nextAbscissa(Y_PLUS)),
(dat.getList()))))));
}
private Tuple drawTeacherCol (int i, IPrintingDat<IStudentGrade> dat)
{
return ( i > lastIndexOf(dat.getList()) ) ?
(Tuple.Create((teacher.stream((i - 1),
(dat.getList()))),
(dat.getPoint())))
: (drawTeacherCol((i + 1),
(new PrintingDat(
(drawValue(Tuple.Create((dat),
(teacher.stream((i),
(dat.getList())))))),
(dat.getPoint().nextAbscissa(Y_PLUS)),
(dat.getList())))));
}
private void drawGrades (String studentId, Graphics2D g2d, Tuple t)
{
final ObservableList<IStudentGrade> allGrades =
StudentGradeDatabase.Instance().GetAll(studentId);
drawSubjectCodeCol((0),
(new PrintingDat((g2d),
(PrintingData.NextRowPoint((X_INIT), (Y_INTERVAL), (t))),
(allGrades))));
final int MID_TERM_TAB = 5;
drawMidTermCol((0),
(new PrintingDat((g2d),
(PrintingData.NextRowPoint(((X_INIT) * (MID_TERM_TAB)),
(Y_INTERVAL), (t))), (allGrades))));
final int FINAL_TERM_TAB = nextColumnTab(MID_TERM_TAB);
drawFinalTermCol((0),
(new PrintingDat((g2d),
(PrintingData.NextRowPoint((X_INIT) * (FINAL_TERM_TAB),
(Y_INTERVAL), (t))), (allGrades))));
final int REMARK_TAB = nextColumnTab(FINAL_TERM_TAB);
drawRemarkCol((0),
(new PrintingDat((g2d),
(PrintingData.NextRowPoint(((X_INIT) * (REMARK_TAB)),
(Y_INTERVAL), (t))), (allGrades))));
final int TEACHER_TAB = nextColumnTab(REMARK_TAB);
drawTeacherCol(0,
(new PrintingDat((g2d),
(PrintingData.NextRowPoint(((X_INIT) * (TEACHER_TAB)),
(Y_INTERVAL), (t))), (allGrades))));
}
private int nextColumnTab (int currentTab)
{
return ((currentTab) + (5));
}
}
| true
|
ac34a27e9ca8c7bb44efeedc33ffa93f1b805ef0
|
Java
|
SunaliBandara/Flog-Game
|
/GameClientFx/src/main/java/com/nsbm/controller/GameWindowController.java
|
UTF-8
| 10,624
| 2.3125
| 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.nsbm.controller;
import com.nsbm.common.CommonData;
import static com.nsbm.common.CommonData.username;
import com.nsbm.common.Mouse;
import com.nsbm.common.Validator;
import static com.nsbm.service.PlayerServiceHandler.checkTermination;
import static com.nsbm.service.PlayerServiceHandler.removePlayer;
import static com.nsbm.service.WordServiceHandler.changeLetter;
import static com.nsbm.service.WordServiceHandler.getInitialLetters;
import static com.nsbm.service.WordServiceHandler.getLetters;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* @author Muthu
*/
public class GameWindowController implements Initializable {
private String initialLetters = null;
private static int counter = 10;
private Timer timer = new Timer();
private final TextField[] letterFields = new TextField[10];
private Mouse mouse = new Mouse();
private Validator validate = new Validator();
@FXML
private TextField initialLetterOne, initialLetterTwo;
@FXML
private TextField noOfVowels, noOfConsonants;
@FXML
private AnchorPane letterPane;
@FXML
private Button requestButton;
@FXML
private Button backButton;
@FXML
private Button exitButton;
@FXML
private Button letterChangeButton;
@FXML
private Label timerLabel;
@FXML
private String selectedLetter;
@FXML
private Node selectedNode;
@FXML
private TextField changeLetter;
@FXML
private Pane gamePane;
@FXML
private Label userNameLabel;
@FXML
private Alert alert;
@Override
public void initialize(URL url, ResourceBundle rb) {
String termination = checkTermination();
if (termination.equals(username + " Terminated")) {
Stage stage = new Stage();
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("/fxml/MainMenu.fxml"));
} catch (IOException ex) {
Logger.getLogger(GameWindowController.class.getName()).log(Level.SEVERE, null, ex);
}
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setResizable(false);
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
stage.show();
stage = (Stage) exitButton.getScene().getWindow();
stage.close();
} else {
userNameLabel.setText(CommonData.username);
initialLetters = getInitialLetters();
initialLetterOne.setText(String.valueOf(initialLetters.charAt(0)).toUpperCase());
initialLetterTwo.setText(String.valueOf(initialLetters.charAt(1)).toUpperCase());
gamePane.setOnMousePressed((MouseEvent event) -> {
mouse.setX(event.getX());
mouse.setY(event.getY());
});
gamePane.setOnMouseDragged((MouseEvent event) -> {
gamePane.getScene().getWindow().setX(event.getScreenX() - mouse.getX() - 14);
gamePane.getScene().getWindow().setY(event.getScreenY() - mouse.getY() - 14);
});
}
}
public void getRequiredLetters() {
exitButton.setDisable(true);
if(validate.isNumeric(noOfVowels.getText())&& validate.isNumeric(noOfConsonants.getText())){
if(validate.isInputEmpty(noOfVowels) && validate.isInputEmpty(noOfConsonants)){
int vowelsRequired = Integer.parseInt(noOfVowels.getText());
int consonantsRequired = Integer.parseInt(noOfConsonants.getText());
if (consonantsRequired + vowelsRequired > 10) {
JOptionPane.showMessageDialog(null, "You can not select more than 10");
}
else if(consonantsRequired==0 || vowelsRequired==0 ){
JOptionPane.showMessageDialog(null,"You Have to Select From Both Letter Categories");
}
else {
String letters = getLetters(vowelsRequired, consonantsRequired);
int count = 0;
for (Node node : letterPane.getChildren()) {
if (count == letters.length()) {
break;
}
if (node instanceof TextField) {
((TextField) node).setText(String.valueOf(letters.charAt(count)).toUpperCase());
}
count++;
}
requestButton.setDisable(true);
CommonData.initialLetters = initialLetters;
CommonData.letters = initialLetters + letters;
timer = new Timer();
counter = 10;
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
if (counter == 0) {
timer.cancel();
Stage stage = new Stage();
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("/fxml/GamePlay.fxml"));
} catch (IOException ex) {
Logger.getLogger(GameWindowController.class.getName()).log(Level.SEVERE, null, ex);
}
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setResizable(false);
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
stage.show();
stage = (Stage) requestButton.getScene().getWindow();
stage.close();
} else {
timerLabel.setText(String.valueOf(counter));
if (counter == 10) {
final URL resource = getClass().getResource("/styles/sec10.mp3");
final Media media = new Media(resource.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
} else if (counter == 9 || counter == 8 || counter == 7 || counter == 6 || counter == 5 || counter == 4) {
timerLabel.setStyle("-fx-text-fill:linear-gradient(#66ff66, #00cc00);");
} else {
timerLabel.setStyle("-fx-text-fill: linear-gradient(#ff5400,#be1d00);");
}
counter--;
}
});
}
}, 0, 1000);
}
}
else{
JOptionPane.showMessageDialog(null, "you have to select from both categories");
}
}
else{
JOptionPane.showMessageDialog(null, "Select a numeric value");
}
}
public void getSelectedText() {
for (Node node : letterPane.getChildren()) {
if (node instanceof TextField) {
node.setStyle("-fx-background-color:linear-gradient(to left, #1D976C , #93F9B9);");
if (node.isFocused()) {
selectedNode = node;
node.setStyle("-fx-background-color:linear-gradient(to left, #1A2980 , #26D0CE);");
selectedLetter = ((TextField) node).getText();
}
}
}
}
@FXML
private void letterChangeAction(ActionEvent event) {
String newLetter = changeLetter(selectedLetter);
CommonData.letters = CommonData.letters.replaceFirst(selectedLetter, newLetter);
((TextField) selectedNode).setText(newLetter.toUpperCase());
letterPane.setDisable(true);
}
@FXML
private void backAction(ActionEvent event) throws IOException {
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/fxml/MainMenu.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setResizable(false);
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
stage.show();
stage = (Stage) backButton.getScene().getWindow();
stage.close();
}
@FXML
private void exitAction(ActionEvent event) {
Stage stage = (Stage) exitButton.getScene().getWindow();
stage.close();
removePlayer(CommonData.username);
System.exit(0);
}
}
| true
|
56747315b070ff47d34d9ad663c3250bf1ace0c8
|
Java
|
marcoxu/AndroidApps
|
/myPhone/src/com/snda/myPhone/callLogs.java
|
GB18030
| 10,421
| 2.265625
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2012 Shanda Corporation. All rights reserved.
*
* Created on 2012-01-30.
*/
package com.snda.myPhone;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
//ʾָϵ˵ϸͨ¼
public class callLogs extends Activity {
private static final String TAG = "com.snda.myPhone.call_logs";
private static final ArrayList<HashMap<String, Object>> calllog_array = new ArrayList<HashMap<String, Object>>();
/** ȡϵϸ֯Ϣ */
private HashMap<String, String> getCompanyInfo(String name, String number){
// ϵ˵ID
Cursor nameCursor = dataAccessor.queryContactByName(getApplicationContext(), name);
HashMap<String, String> map = new HashMap<String, String>();
String contactId = null;
if(nameCursor != null && nameCursor.getCount() > 0){
for(int i=0;i<nameCursor.getCount();i++){
nameCursor.moveToPosition(i);
String contact_id = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhoneNumber = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if( (Integer.parseInt(hasPhoneNumber) > 0) )
{
Cursor phoneNumber = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contact_id,
null,
null);
if(phoneNumber != null){
while (phoneNumber.moveToNext())
{
String strPhoneNumber = phoneNumber.getString(phoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//ƥ䣬ҵϵID
if(number.equals(strPhoneNumber)){
contactId = contact_id;
break;
}
}
phoneNumber.close();
}
}
}
nameCursor.close();
if(contactId == null){
map.put("company", "");
map.put("position", "");
map.put("department", "");
map.put("id", "");
return map;
}
}else{
if(nameCursor != null){
nameCursor.close();
}
map.put("company", "");
map.put("position", "");
map.put("department", "");
map.put("id", "");
return map;
}
String filter = ContactsContract.Data.CONTACT_ID+"='"+contactId + "' AND " + Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'";
Log.i(TAG, "contact selection is " + filter);
//organization
Cursor orgCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Organization.COMPANY,
ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
ContactsContract.CommonDataKinds.Organization.TITLE},
filter,
null,
null);
// ȡ֯Ϣ
if(orgCursor != null && orgCursor.getCount() > 0){
if(orgCursor.moveToFirst()){
do{
String company = orgCursor.getString(0);
String position = orgCursor.getString(2);
String department = orgCursor.getString(1);
Log.i(TAG, "˾: "+company+" ְλ: "+position + ": " + department);
if(company != null && company.length() > 0){
map.put("company", company);
}else{
map.put("company", "");
}
if(position != null && position.length() > 0){
map.put("position", position);
}else{
map.put("position", "");
}
if(department != null && department.length() > 0){
map.put("department", department);
}else{
map.put("department", "");
}
map.put("id", contactId);
}while(orgCursor.moveToNext());
}
orgCursor.close();
}else{
map.put("company", "");
map.put("position", "");
map.put("department", "");
map.put("id", contactId);
if(orgCursor != null){
orgCursor.close();
}
}
return map;
}
//ȡϵͨʷ¼
public synchronized void insertCalllogArray(Cursor contact, ArrayList<HashMap<String, Object>> history){
if(contact != null && contact.getCount() > 0){
for(int i=0;i<contact.getCount();i++){
contact.moveToPosition(i);
SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date(Long.parseLong(contact.getString(3)));
String time = sfd.format(date);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("time", time);
map.put("duration", "ͨ:" + contact.getString(4) + "");
Log.i(TAG, "time " + time + ", duration " + "," + contact.getString(4));
if(history != null && history.size() > i){
Log.i(TAG, "ringtime " + history.get(history.size()-i-1).get("ringtime"));
map.put("ringtime", ":" + history.get(history.size()-i-1).get("ringtime") + "");
}else{
// ͨʱδ¼ΪĬֵ0
Log.i(TAG, "ringtime 0");
map.put("ringtime", ":" + "0");
}
calllog_array.add(map);
}
}
}
//ϵ˺ȡͨ¼
private void getCallogDataByNumber(String number){
if(calllog_array != null && !calllog_array.isEmpty()){
calllog_array.clear();
}
Cursor cursor = dataAccessor.getCallLogsByNumber(getApplicationContext(), number);
ArrayList<HashMap<String, Object>> history = myPhoneActivity.dbHandler.quryCallHistory(number);
if(cursor != null){
insertCalllogArray(cursor, history);
cursor.close();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_logs);
String number = getIntent().getStringExtra("callnumber");
String name = getIntent().getStringExtra("name");
if(number != null){
Log.i(TAG, "call number:" + number);
// ʾ뼰Ӧϵ
final TextView display_caller = (TextView) findViewById(R.id.display_name);
if(name != null && name.length() > 0){
display_caller.setText(name + " " + number);
}
// ʾؼ
HashMap<String, Object> location = myPhoneActivity.dbHandler.queryPhoneLocation(number);
if(location != null){
final TextView display_location = (TextView) findViewById(R.id.location);
final TextView display_type = (TextView) findViewById(R.id.type);
display_location.setText(": " + (String)location.get("location"));
display_type.setText(" : " + ((String)location.get("type")));
}
// ʾϵ˵֯Ϣ
HashMap<String, String> map = getCompanyInfo(name, number);
if(map != null){
final TextView display_company = (TextView) findViewById(R.id.company);
final TextView display_department = (TextView) findViewById(R.id.department);
final TextView display_position = (TextView) findViewById(R.id.position);
final ImageView display_img = (ImageView) findViewById(R.id.contactorimg1);
display_company.setText(" ˾: " + map.get("company"));
display_department.setText(" : " + map.get("department"));
display_position.setText("ְ λ: " + map.get("position"));
Cursor contactCursor = dataAccessor.queryContactById(getApplicationContext(), map.get("id"));
if(contactCursor != null && contactCursor.getCount() > 0){
contactCursor.moveToFirst();
Bitmap bitmap = null;
Log.i(TAG, "Get header for " + contactCursor.getString(4));
bitmap = dataAccessor.getContactHead(getApplicationContext(), contactCursor.getString(4));
if(bitmap != null){
display_img.setImageBitmap(bitmap);
}
contactCursor.close();
}
getCallogDataByNumber(number);
ListView contacts = (ListView) findViewById(R.id.calllogList);
//ItemͶ̬ӦԪ
SimpleAdapter listItemAdapter = new SimpleAdapter(this, calllog_array,
R.layout.call_history_item,
new String[] {"time", "ringtime", "duration"},
new int[] {R.id.calltime,R.id.callringtime,R.id.callduration});
//Ӳʾ
if(contacts.getAdapter() == null){
contacts.addHeaderView(new LinearLayout(this));
}
contacts.setAdapter(listItemAdapter);
}
}
}
}
| true
|
456276899a23aafa371b737e83689ee28fdb3bcc
|
Java
|
ngvietan92/blackout_schedule
|
/app/src/main/java/com/ngvietan/blackoutschedule/activities/HomeActivity.java
|
UTF-8
| 1,850
| 2.109375
| 2
|
[] |
no_license
|
package com.ngvietan.blackoutschedule.activities;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ngvietan.blackoutschedule.R;
import com.ngvietan.blackoutschedule.common.CommonMethods;
import com.ngvietan.blackoutschedule.common.CommonVariables;
import com.ngvietan.blackoutschedule.common.Constants;
import com.ngvietan.blackoutschedule.data.ProvinceDao;
import com.ngvietan.blackoutschedule.models.Province;
import com.ngvietan.blackoutschedule.utils.Utils;
import java.util.List;
/**
* Created by NgVietAn on 02/08/2015.
*/
public class HomeActivity extends BaseActivity {
private ListView lvProvince;
private List<Province> provinces;
private ArrayAdapter<Province> adapter;
@Override
protected int getContentViewId() {
return R.layout.activity_home;
}
@Override
protected void initComponents() {
super.initComponents();
lvProvince = (ListView) findViewById(R.id.lvProvince);
provinces = ProvinceDao.getAllProvinces();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, provinces);
lvProvince.setAdapter(adapter);
}
@Override
protected void setListeners() {
super.setListeners();
lvProvince.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CommonVariables.selectedProvince = provinces.get(position);
CommonMethods.saveProvinceIdSharedPref(HomeActivity.this, CommonVariables.selectedProvince);
Utils.gotoActivity(HomeActivity.this, MainActivity.class, true);
}
});
}
}
| true
|
8cf970c40d55792d110a271cb77eb4dfc8f0b0ab
|
Java
|
yizhongliu/SSDPDevice
|
/common/src/main/java/com/iview/common/base/BaseActivity.java
|
UTF-8
| 486
| 1.851563
| 2
|
[] |
no_license
|
package com.iview.common.base;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* 项目父Activity
*/
public class BaseActivity extends AppCompatActivity {
private final static String TAG = "BaseActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "common/BaseActivity");
}
}
| true
|
7070e0fda799040e98586e363fa19f4b07635a5d
|
Java
|
Linliangkung/MobileSafe
|
/src/com/jsako/mobilesafe/NumberAddressQueryActivity.java
|
GB18030
| 2,203
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.jsako.mobilesafe;
import com.jsako.mobilesafe.db.dao.NumberAddressQueryUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class NumberAddressQueryActivity extends Activity {
private static final String TAG = "NumberAddressQueryActivity";
private EditText et_phone;
private TextView tv_result;
private Vibrator vibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_address_query);
et_phone = (EditText) findViewById(R.id.et_phone);
tv_result = (TextView) findViewById(R.id.tv_result);
vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
et_phone.addTextChangedListener(new TextWatcher() {
/**
* ı仯ʱص
*/
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String phone = s.toString();
if(phone.length()>2){
String address = NumberAddressQueryUtils.getAddress(phone);
tv_result.setText(address);
}
}
/**
* ı仯ǰص
*/
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
/**
* ı仯ص
*/
@Override
public void afterTextChanged(Editable s) {
}
});
}
/**
* ѯ
*
* @param view
*/
public void numberAddressQuery(View view) {
String phone = et_phone.getText().toString().trim();
if (TextUtils.isEmpty(phone)) {
Toast.makeText(this, "Ϊ", Toast.LENGTH_SHORT).show();
Animation anim=AnimationUtils.loadAnimation(this,R.anim.shake);
et_phone.startAnimation(anim);
vibrator.vibrate(1000);
return;
}
String address = NumberAddressQueryUtils.getAddress(phone);
tv_result.setText(address);
}
}
| true
|
bae87b5ba461cf85e2e238715d8d415bebd815ef
|
Java
|
jwatters1981/VisualInfrastructure
|
/src/main/java/com/watters/WidgetController.java
|
UTF-8
| 753
| 2.1875
| 2
|
[] |
no_license
|
package com.watters;
import com.watters.infrastructure.model.Database;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by johnwatters on 28/04/2016.
*/
@RequestMapping("/api")
@RestController
public class WidgetController {
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public
@ResponseBody
Database index() {
Database database = new Database();
database.setName("Db Name");
return database;
}
}
| true
|
49fa4dd736f7a572d90fbf14c01f90e2045f7a0f
|
Java
|
charlefire/winnu-pim
|
/winnupim/src/java/winnu/gui/EditUserPanel.java
|
UTF-8
| 13,586
| 2.375
| 2
|
[] |
no_license
|
package winnu.gui;
import javax.swing.JOptionPane;
import winnu.control.WinnuControl;
import winnu.dao.User;
@SuppressWarnings("serial")
public class EditUserPanel extends javax.swing.JPanel {
private WinnuControl control;
private MainForm mainform;
/** Creates new form EditUserPanel */
public EditUserPanel(MainForm mainform) {
this.mainform = mainform;
initComponents();
}
public void setControl(WinnuControl control){
this.control = control;
}
private void initComponents() {
lblEditUserAcct = new javax.swing.JLabel();
lblUsername = new javax.swing.JLabel();
lblFullName = new javax.swing.JLabel();
txtMname = new javax.swing.JTextField();
txtFname = new javax.swing.JTextField();
txtLname = new javax.swing.JTextField();
lblPosition = new javax.swing.JLabel();
txtPosition = new javax.swing.JTextField();
lblAddress = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
lblContactNo = new javax.swing.JLabel();
lblLName = new javax.swing.JLabel();
lblMName = new javax.swing.JLabel();
lblFName = new javax.swing.JLabel();
txtContacts = new javax.swing.JTextField();
lblUsername0 = new javax.swing.JLabel();
btnAccept = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
btnSelectUser = new javax.swing.JButton();
lblEditUserAcct.setFont(new java.awt.Font("MS Reference Sans Serif", 0, 18));
lblEditUserAcct.setText("Edit User Account");
lblUsername.setText("Username:");
lblFullName.setText("Full Name:");
lblPosition.setText("Position:");
lblAddress.setText("Address:");
lblContactNo.setText("Contact Number:");
lblLName.setText("Last");
lblMName.setText("Middle");
lblFName.setText("First");
lblUsername0.setText("<select a user>");
btnAccept.setText("Accept");
btnAccept.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAcceptActionPerformed(evt);
}
});
btnCancel.setText("Cancel");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
btnSelectUser.setText("Select User");
btnSelectUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSelectUserActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblEditUserAcct, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblFullName)
.addComponent(lblAddress)
.addComponent(lblPosition))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPosition, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtAddress)
.addGroup(layout.createSequentialGroup()
.addComponent(txtFname, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtMname, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtLname, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(111, 111, 111)
.addComponent(lblFName)
.addGap(78, 78, 78)
.addComponent(lblMName)
.addGap(72, 72, 72)
.addComponent(lblLName))
.addGroup(layout.createSequentialGroup()
.addComponent(lblContactNo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(btnAccept)
.addGap(5, 5, 5)
.addComponent(btnCancel))
.addComponent(txtContacts, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(lblUsername)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUsername0, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSelectUser))))
.addContainerGap(94, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblEditUserAcct)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblUsername)
.addComponent(lblUsername0))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSelectUser)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFullName)
.addComponent(txtFname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFName)
.addComponent(lblMName)
.addComponent(lblLName))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPosition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblPosition))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblAddress))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblContactNo)
.addComponent(txtContacts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAccept)
.addComponent(btnCancel))
.addGap(44, 44, 44))
);
}// </editor-fold>//GEN-END:initComponents
private void btnAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcceptActionPerformed
String firstname;
String middlename;
String lastname;
String position;
String address;
String contactDetails;
User selectedUser=control.getCurrentSelectedUser();
if(selectedUser != null){
firstname = txtFname.getText();
middlename = txtMname.getText();
lastname = txtLname.getText();
position = txtPosition.getText();
address = txtAddress.getText();
contactDetails = txtContacts.getText();
control.editAccountController.editAccount(selectedUser.getUserId(), selectedUser.getUsername(), selectedUser.getPassword(), firstname, middlename, lastname, position, address, contactDetails, selectedUser.getType());
JOptionPane.showMessageDialog(null, selectedUser.getUsername() + "'s information has been successfully updated.", "Edit Own Account", 1);
mainform.reloadMainMenu();
control.setCurrentSelectedUser(null);
txtFname.setText("");
txtMname.setText("");
txtLname.setText("");
txtPosition.setText("");
txtAddress.setText("");
txtContacts.setText("");
lblUsername0.setText("<select a user>");
}
}
private void btnSelectUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectUserActionPerformed
SearchUserFrame searchUserFrame = new SearchUserFrame(this.control);
control.setCurrentSelectedUser(null);
searchUserFrame.addWindowListener(new java.awt.event.WindowAdapter(){
public void windowClosed(java.awt.event.WindowEvent e){
if(control.getCurrentSelectedUser()!=null) updateView();
}
});
searchUserFrame.setVisible(true);
}
private void updateView(){
User selectedUser = control.getCurrentSelectedUser();
txtAddress.setText(selectedUser.getAddress());
txtContacts.setText(selectedUser.getContactNo());
txtFname.setText(selectedUser.getFirstName());
txtMname.setText(selectedUser.getMiddleName());
txtLname.setText(selectedUser.getLastName());
txtPosition.setText(selectedUser.getPosition());
lblUsername0.setText(selectedUser.getUsername());
}
public void clearFields() {
control.setCurrentSelectedUser(null);
txtFname.setText("");
txtMname.setText("");
txtLname.setText("");
txtPosition.setText("");
txtAddress.setText("");
txtContacts.setText("");
lblUsername0.setText("<select a user>");
}
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
mainform.reloadMainMenu();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAccept;
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnSelectUser;
private javax.swing.JLabel lblEditUserAcct;
private javax.swing.JLabel lblUsername0;
private javax.swing.JLabel lblUsername;
private javax.swing.JLabel lblFullName;
private javax.swing.JLabel lblPosition;
private javax.swing.JLabel lblAddress;
private javax.swing.JLabel lblContactNo;
private javax.swing.JLabel lblLName;
private javax.swing.JLabel lblMName;
private javax.swing.JLabel lblFName;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtContacts;
private javax.swing.JTextField txtFname;
private javax.swing.JTextField txtLname;
private javax.swing.JTextField txtMname;
private javax.swing.JTextField txtPosition;
// End of variables declaration//GEN-END:variables
}
| true
|
21c8af9baa524c3b3ff929b8117b544476dbe2df
|
Java
|
BartoszMiskiewicz/MyProject
|
/src/main/java/pl/sdacademy/sort/SortAlgorithm.java
|
UTF-8
| 911
| 2.703125
| 3
|
[] |
no_license
|
package pl.sdacademy.sort;
public class SortAlgorithm implements ISortAlgorithm {
public SortAlgorithm() {
// TODO Auto-generated constructor stub
}
// TODO Zaimplementuj ponizszy pseudokod
// procedure BubbleSort( var a: array of TItemBubbleSort );
// var
// n, newn, i:integer;
// begin
// n := high( a );
// repeat
// newn := 0;
// for i := 1 to n do
// begin
// if a[ i - 1 ] > a[ i ] then
// begin
// swap( a[ i - 1 ], a[ i ]);
// newn := i ;
// end;
// end ;
// n := newn;
// until n = 0;
// end;
//
// end.
@Override
public void sort(int[] array, boolean ascending) {
int n = array.length;
do {
for (int i = 0; i < array.length - 1; i++) {
if ((array[i] > array[i + 1] && ascending) || (array[i] < array[i + 1] && !ascending)) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
n = n - 1;
} while (n > 1);
}
}
| true
|
c5cb74e4c0a956dda01c16c90881a1254622140d
|
Java
|
lujiango/RefactoringInJava
|
/src/_06/_06_02_InlineMethod.java
|
GB18030
| 613
| 3.5
| 4
|
[] |
no_license
|
package _06;
/**
* Inline Method()<br>
* һıͬ<br>
* ںõ뺯壬ȻƳú<br>
* ҳõļӲ㣬ͬʱЩõļӲȥ
*
* @author lujiang
*
*/
public class _06_02_InlineMethod {
private int numberOfLateDeliveries;
boolean moreThanFiveLateDeliveries() {
return numberOfLateDeliveries > 5;
}
int getRating() {
return (moreThanFiveLateDeliveries()) ? 2 : 1;
}
// Ϊ
int getRatingNew() {
return (numberOfLateDeliveries > 5) ? 2 : 1;
}
}
| true
|
52e3ff11cee4ec0c6166e08c1abaf3bbf98b431c
|
Java
|
BETAJIb/Studious
|
/gameserver/src/main/java/l2s/gameserver/network/l2/c2s/RequestFriendInvite.java
|
UTF-8
| 921
| 2.21875
| 2
|
[] |
no_license
|
package l2s.gameserver.network.l2.c2s;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.World;
import l2s.gameserver.network.l2.components.IBroadcastPacket;
import l2s.gameserver.network.l2.components.SystemMsg;
import org.apache.commons.lang3.StringUtils;
public class RequestFriendInvite extends L2GameClientPacket
{
private String _name;
@Override
protected void readImpl()
{
_name = readS(16);
}
@Override
protected void runImpl()
{
Player activeChar = getClient().getActiveChar();
if(activeChar == null || StringUtils.isEmpty(_name))
return;
if(activeChar.isOutOfControl())
{
activeChar.sendActionFailed();
return;
}
IBroadcastPacket msg = activeChar.getFriendList().requestFriendInvite(World.getPlayer(_name));
if(msg != null)
{
activeChar.sendPacket(msg);
activeChar.sendPacket(SystemMsg.YOU_HAVE_FAILED_TO_ADD_A_FRIEND_TO_YOUR_FRIENDS_LIST);
}
}
}
| true
|
0e87a325b5349028e810f01215d837f3382e4d1d
|
Java
|
kiomnd2/test-driven-code
|
/src/main/java/org/kiomnd2/java/SniperSnapshot.java
|
UTF-8
| 2,043
| 2.921875
| 3
|
[] |
no_license
|
package org.kiomnd2.java;
import com.objogate.exception.Defect;
public class SniperSnapshot {
public final String item ;
public final int lastPrice;
public final int lastBid;
public final SniperState state;
public SniperSnapshot(String item, int lastPrice, int lastBid, SniperState state){
this.item = item;
this.lastPrice = lastPrice;
this.lastBid = lastBid;
this.state = state;
}
public SniperSnapshot bidding(int newLastPrice, int newLastBid) {
return new SniperSnapshot(item, newLastPrice, newLastBid,SniperState.BIDDING);
}
public SniperSnapshot winning(int newLastPrice) {
return new SniperSnapshot(item, newLastPrice, newLastPrice, SniperState.WINNING);
}
public static SniperSnapshot joining(String item) {
return new SniperSnapshot(item, 0, 0, SniperState.JOINING);
}
public SniperSnapshot closed() {
return new SniperSnapshot(item,lastPrice,lastBid, state.whenAuctionClosed());
}
public SniperSnapshot losing(int newLastPrice) {
return new SniperSnapshot(item, newLastPrice,lastBid, SniperState.LOSING);
}
public boolean isForSameItemAs(SniperSnapshot snapshot) {
return snapshot.item == this.item;
}
public enum SniperState {
JOINING {
@Override
public SniperState whenAuctionClosed() {
return LOST;
}
},
BIDDING {
@Override
public SniperState whenAuctionClosed() {
return LOST;
}
},
WINNING {
@Override
public SniperState whenAuctionClosed() {
return WON;
}
},
LOSING {
@Override
public SniperState whenAuctionClosed() {
return LOST;
}
},
LOST,
WON;
public SniperState whenAuctionClosed() {
throw new Defect("Auction is already closed");
}
}
}
| true
|
9763dd374ad8dc779b7a5c818a5b44c26104a2d4
|
Java
|
miikko/Ajanhallinta_projekti
|
/Tietokanta/database/SittingManager.java
|
UTF-8
| 1,378
| 3.171875
| 3
|
[] |
no_license
|
package database;
import java.util.HashSet;
/**This Thread-class is responsible for sending updates concerning the current sitting to the database.
* @author miikk
*
*/
public class SittingManager extends Thread{
private enum TaskType {
CREATE_SITTING,
UPDATE_SITTING,
CREATE_WINDOWTIME,
UPDATE_WINDOWTIME,
NONE,
}
private KayttajaAccessObject userObject;
private SittingAccessObject sittingDAO;
private Kayttaja user;
private Sitting sitting;
private WindowTime wt;
private boolean exit;
private TaskType taskType;
private HashSet<String> progNames;
public SittingManager (Kayttaja user) {
this.user = user;
userObject = new KayttajaAccessObject();
sittingDAO = new SittingAccessObject();
progNames = new HashSet<String>();
this.setDaemon(true);
taskType = TaskType.NONE;
}
@Override
public void run() {
while (!exit) {
switch (taskType) {
}
}
}
public void quit() {
exit = true;
}
public Sitting createSitting(String startDate) {
sitting = new Sitting(user, startDate);
taskType = TaskType.CREATE_SITTING;
return sitting;
}
public Sitting updateSitting() {
return null;
}
public WindowTime createWindowTime(String progName) {
wt = new WindowTime(sitting, progName);
taskType = TaskType.CREATE_WINDOWTIME;
return wt;
}
public void updateWindowTime(WindowTime wt) {
}
}
| true
|
c7dc4293b0d2e491cf5be957b0cc82154bf0218d
|
Java
|
puck-ini/leetcode
|
/src/leetcode/sort/InsertSort.java
|
UTF-8
| 942
| 4.03125
| 4
|
[] |
no_license
|
package leetcode.sort;
/**
* 插入排序
* 将数据分为两部分,左边为有序的部分,右边为无序部分,从右边无序部分选择一个数,插入有序部分相应的位置中
*/
public class InsertSort {
public static void sort(int[] nums){
int len = nums.length;
//从1开始是因为可以把索引为0的地方当作有序的部分
for (int i = 1; i < len; i++){
int value = nums[i];
int j = i - 1;
while (j >= 0){
if (value < nums[j]){
nums[j + 1] = nums[j];
}else {
break;
}
j--;
}
nums[j + 1] = value;
}
}
public static void main(String[] args) {
int[] nums = new int[]{2,5,2,3,4,1,8};
sort(nums);
for (int num: nums){
System.out.println(num);
}
}
}
| true
|
84c98bda3b1b0dd6d02d53e19e3e7269fddd4431
|
Java
|
RamziJabali/data-structures-java
|
/src/test/java/RStringTest.java
|
UTF-8
| 1,907
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
import org.junit.Assert;
import org.junit.Test;
public class RStringTest {
@Test
public void testGetRCharArray() {
RString rString = new RString("hello");
RChar[] rChars = new RChar[5];
rChars[0] = new RChar('h');
rChars[1] = new RChar('e');
rChars[2] = new RChar('l');
rChars[3] = new RChar('l');
rChars[4] = new RChar('o');
Assert.assertEquals(rString.getRCharArray(), rChars);
}
@Test
public void testGetReverse() {
RString rString = new RString("olleh");
Assert.assertEquals(rString.getReverse().toString(), "hello");
}
@Test
public void testGetSize() {
RString rString = new RString("olleh");
Assert.assertEquals(rString.getSize(), 5);
}
@Test
public void testisEmpty() {
RString rString = new RString("");
Assert.assertTrue(rString.isEmpty());
}
@Test
public void testEquals() {
RString rString = new RString("hello");
RString rString2 = new RString("hello");
Assert.assertTrue(rString.equals(rString2));
}
@Test
public void testHashCode() {
RString rString = new RString("hello");
Assert.assertEquals(rString.hashCode(), -1220935314);
}
@Test
public void testCompareTo1() {
RString rString = new RString("hello");
RString rString2 = new RString("heflo");
Assert.assertEquals(rString.compareTo(rString2), 1);
}
@Test
public void testCompareTo2() {
RString rString = new RString("hello");
RString rString2 = new RString("hemlo");
Assert.assertEquals(rString.compareTo(rString2), -1);
}
@Test
public void testCompareTo3() {
RString rString = new RString("hello");
RString rString2 = new RString("hello");
Assert.assertEquals(rString.compareTo(rString2), 0);
}
}
| true
|
14a9878be72a830fd55e3ced73bc7b6e623b7fa3
|
Java
|
palotas/seleniumtraining
|
/src/test/java/jsonWireProtocol/JsonWireP.java
|
UTF-8
| 4,227
| 2.453125
| 2
|
[] |
no_license
|
package jsonWireProtocol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.testng.annotations.Test;
import com.google.gson.JsonObject;
public class JsonWireP {
@Test
public void createNewSession() throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClientBuilder.create().build();
//create session
HttpPost httpPost = new HttpPost("http://localhost:4444/wd/hub/session");
httpPost.setHeader("Content-Type", "application/json");
//build capabilities object
JsonObject capabilities = new JsonObject();
capabilities.addProperty("browserName", "firefox");
JsonObject json = new JsonObject();
json.add("desiredCapabilities", capabilities);
//build POST and execute
HttpEntity e = new StringEntity(json.toString());
httpPost.setEntity(e);
HttpResponse response = httpclient.execute(httpPost);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
}
}
@Test
public void navigateToUrl() throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClientBuilder.create().build();
//create session
HttpPost httpPost = new HttpPost("http://localhost:4444/wd/hub/session/893200ae-98cc-4bbc-824b-331468e749a4/url");
httpPost.setHeader("Content-Type", "application/json");
//build capabilities object
JsonObject target = new JsonObject();
target.addProperty("url", "http://gridfusion.net");
//build POST and execute
HttpEntity e = new StringEntity(target.toString());
httpPost.setEntity(e);
HttpResponse response = httpclient.execute(httpPost);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
}
}
@Test
public void quit() throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClientBuilder.create().build();
//create session
HttpDelete httpDelete = new HttpDelete("http://localhost:4444/wd/hub/session/c9ce3053-9fb1-4518-813a-9bb9992df34a/window");
httpDelete.setHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httpDelete);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
}
}
}
| true
|
f3d1b45e79fc0a6adf73dcab966a0e18546f02be
|
Java
|
hongyi0609/MeiTuanEdwin
|
/android/app/src/main/java/com/common/react/HomeReactPackage.java
|
UTF-8
| 1,482
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package com.common.react;
import com.common.react.viewManager.ReactTextViewManager;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Edwin,CHEN on 2019/10/28.
*/
public class HomeReactPackage implements ReactPackage {
/**
* 该方法通过创建原生方法供JS调用
* @param reactContext
* @return
*/
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ToastModule(reactContext));
modules.add(new HomeReactNativeMessageEventModule(reactContext, new HomeNativeMessageEventListener()));
// HomeMessageEventModule用于原生端向服务端发送实时消息
modules.add(new HomeMessageEventModule(reactContext));
return modules;
}
/**
* 该方法通过创建原生的View组件供JS调用,相对复杂
* 注意不要返回null,js会报错
* @param reactContext
* @return
*/
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
List<ViewManager> viewManagerList = new ArrayList<>();
viewManagerList.add(new ReactTextViewManager());
return viewManagerList;
}
}
| true
|
72404c364a55ed1258ed768ce0c22ce3373fb4b8
|
Java
|
HutnikMaksim/forMaxim
|
/src/by/it/kolesnikov/jd02_02/Buyer.java
|
UTF-8
| 2,789
| 3.265625
| 3
|
[] |
no_license
|
package by.it.kolesnikov.jd02_02;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class Buyer extends Thread implements IBuyer, IUseBasket {
private boolean waiting;
Buyer(int number){
this.setName("Buyer №"+number);
Supervisor.addBuyer();
waiting =false;
}
public void setWaiting(boolean waiting) {
this.waiting = waiting;
}
@Override
public void run() {
enterToMarket();
takeBasket();
choseGoods();
putGoodsToBasket();
goToQueue();
goOut();
Supervisor.leaveBuyer();
}
@Override
public void takeBasket(){
System.out.println(this+" took basket");
}
@Override
public void putGoodsToBasket(){
StringBuffer sb =new StringBuffer();
List<String> goods = new ArrayList<>();
List<String> basketGoods = new ArrayList<>();
List<Integer> prices = new ArrayList<>();
List<Integer> price = new ArrayList<>();
for (Map.Entry<String, Integer> entry : Good.goods().entrySet()){
String el = entry.getKey();
Integer pr = entry.getValue();
goods.add(el);
prices.add(pr);
}
int count = Helper.getRandom(1,4);
String delimiter = "";
int sum=0;
for (int i = 0; i < count; i++) {
int rnd = Helper.getRandom(3);
String good = goods.get(rnd);
int pr = prices.get(rnd);
basketGoods.add(good);
price.add(pr);
sum=sum+price.get(i);
sb.append(delimiter);
sb.append(basketGoods.get(i));
delimiter=", ";
}
System.out.println(this+" put next goods to basket: "+sb+": costs $"+sum);
}
@Override
public String toString() {
return getName();
}
@Override
public void enterToMarket() {
System.out.println(this+" entered to Market");
}
@Override
public void choseGoods() {
System.out.println(this+" started to choose goods");
int timeout= Helper.getRandom(500, 2000);
Helper.timeOut(timeout);
System.out.println(this+" finished to choose goods");
}
@Override
public void goToQueue() {
System.out.println(this+" goes to queue");
synchronized (this) {
waiting =true;
QueueBuyers.add(this);
while(waiting)
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(this+" left queue");
}
@Override
public void goOut() {
System.out.println(this+" went out of Market");
}
}
| true
|
169d219b05a380c46671ea0fff3c803f2b2d1faa
|
Java
|
dzonekl/netxstudio
|
/screens/com.netxforge.netxstudio.common/src/com/netxforge/netxstudio/common/model/NetxresourceSummary.java
|
UTF-8
| 4,414
| 1.8125
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 31 jan. 2013 NetXForge.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* Contributors: Christophe Bouhier - initial API and implementation and/or
* initial documentation
*******************************************************************************/
package com.netxforge.netxstudio.common.model;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.ecore.EObject;
import com.google.common.collect.Lists;
import com.netxforge.netxstudio.generics.DateTimeRange;
import com.netxforge.netxstudio.library.NetXResource;
import com.netxforge.netxstudio.metrics.MetricValueRange;
import com.netxforge.netxstudio.metrics.MetricsPackage;
import com.netxforge.netxstudio.operators.Marker;
import com.netxforge.netxstudio.services.RFSService;
/**
* An adapted NetXResource, adds computed information to the resource.
*
* @author Christophe Bouhier
*/
public class NetxresourceSummary extends MonitoringAdapter {
public NetxresourceSummary() {
}
/** Our tolerance markers **/
private List<Marker> toleranceMarkers = Lists.newArrayList();
/** count for our {@link NetXResource#getMetricValueRanges()} **/
private int mvrs;
@Override
protected synchronized void computeForTarget(IProgressMonitor monitor) {
clearComputation();
// Set the context objects.
final RFSService rfsServiceInContext = getRFSService();
if (rfsServiceInContext == null) {
// COMPUTATION STATE => NOT-COMPUTED
return;
}
final DateTimeRange periodInContext = getPeriod();
if (periodInContext == null) {
// COMPUTATION STATE => NOT-COMPUTED
return;
}
// Safely case, checked by our factory.
final NetXResource target = getTarget();
// The count of computed MVR's. (Typically one Tolerance expression will
// compute one MVR).
int computedMVRs = 0;
if (!target.getMetricValueRanges().isEmpty()) {
final SubMonitor childMonitor = SubMonitor.convert(monitor, target
.getMetricValueRanges().size());
childMonitor.setTaskName("Computing summary for "
+ StudioUtils.printModelObject(target));
for (MetricValueRange mvr : target.getMetricValueRanges()) {
mvrs++;
if (monitor != null && monitor.isCanceled()) {
System.out.println("Computation cancelled...");
break;
}
IMonitoringSummary childAdapter = adaptAndCompute(childMonitor,
mvr, this.getContextObjects());
// Guard for potentially non-adapted children.
if (childAdapter != null) {
if (childAdapter.isComputed()) {
computedMVRs++;
// Base our RAG status, on the child's status
this.incrementRag(childAdapter.rag());
}
} else {
System.out.println("SHOULD NOT OCCUR: child not adapted! "
+ StudioUtils.printModelObject(mvr));
}
childMonitor.worked(1);
}
}
if (computedMVRs == target.getMetricValueRanges().size()) {
computationState = ComputationState.COMPUTED;
}
}
public NetXResource getTarget() {
return (NetXResource) super.getTarget();
}
@Override
protected boolean isSameAdapterFor(EObject object) {
// We need notifications for MVR'.
return object.eClass() == MetricsPackage.Literals.METRIC_VALUE_RANGE;
}
@Override
protected boolean isNotFiltered(EObject object) {
// Only for MVR child objects.
return object.eClass() == MetricsPackage.Literals.METRIC_VALUE_RANGE;
}
/**
* Return the markers for this resource, in the last computation from a
* context {@link RFSService}.
*
* @param perio
* @return
*/
public List<Marker> markers() {
return toleranceMarkers;
}
/**
* Get the count for {@link NetXResource#getMetricValueRanges()
*
* @return
*/
public int getMvrs() {
return mvrs;
}
}
| true
|
19c4b63decae3f23ddb88036df133eeb99837a49
|
Java
|
pgupta221286/ApplitoolsHackathon
|
/src/test/java/pageObjects/Applifashion.java
|
UTF-8
| 2,200
| 2.015625
| 2
|
[] |
no_license
|
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Applifashion{
WebDriver webDriver;
String device;
public String main_logo = "IMG____9";
public String search_box = "DIV__customsear__41";
public String menu_bar = "DIV__mainmenu__15";
public String wishlist = "A__wishlist__52";
public String cart_number = "STRONG____50";
public String open_search_box = "A__btnsearchm__59";
public String profile = "A__accesslink__56";
public String cart = "A__cartbt__49";
public String first_shoe="FIGURE____214";
public String big_shoe_image = "DIV__topbanner__188";
public String filters = "filter_col";
public String grid_icon = "I__tiviewgrid__203";
public String list_icon = "I__tiviewlist__205";
public String add_to_wishlist = "I__tiheart__226";
public String similar_shoes = "I__ticontrols__230";
public String add_to_cart = "I__tishopping__234";
public String show_filter_button = "ti-filter";
public String apply_filters_button = "filterBtn";
public String searchResults_xpath="//div[@class='grid_item']";
public String about_us = "A____426";
public String FAQ = "A____428";
public String help = "A____430";
public String my_account = "A____432";
public String blog = "A____434";
public String contacts = "A____436";
public String address = "LI____441";
public String email = "LI____444";
public String email_box = "email_newsletter";
public Applifashion(WebDriver driver, String device) {
this.webDriver=driver;
this.device = device;
}
public void filterBlackShoes() {
if(device.equals("mobile") || device.equals("tablet")) {
webDriver.findElement(By.id(show_filter_button)).click();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webDriver.findElement(By.xpath("//label[contains(text(),'Black')]")).click();
webDriver.findElement(By.id(apply_filters_button)).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clickBlackShoe() {
webDriver.findElement(By.xpath(first_shoe)).click();
}
}
| true
|
29b4e9bdc9c58162a6d1c0a63a0f7c45ce22af5c
|
Java
|
andredupontg/UsuariosRESTfulAPI
|
/src/main/java/com/andredupont/apiRest/controllers/UsuarioCtr.java
|
UTF-8
| 1,388
| 2.5
| 2
|
[] |
no_license
|
package com.andredupont.apiRest.controllers;
import com.andredupont.apiRest.models.Usuario;
import com.andredupont.apiRest.services.UsuarioSrv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Optional;
@RestController
@RequestMapping("/usuario")
public class UsuarioCtr {
@Autowired
UsuarioSrv usuarioSrv;
@GetMapping()
public ArrayList<Usuario> obtenerUsuarios(){
return usuarioSrv.obtenerUsuarios();
}
@PostMapping
public Usuario guardarUsuario(@RequestBody Usuario usuario){
return this.usuarioSrv.guardarUsuario(usuario);
}
@GetMapping(path = "/{id}")
public Optional<Usuario> obtenerUsuarioPorId(@PathVariable("id") Long id){
return this.usuarioSrv.obtenerPorId(id);
}
@GetMapping(path = "/query")
public ArrayList<Usuario> obtenerUsuarioPorPrioridad(@RequestParam("prioridad") int prioridad){
return this.usuarioSrv.obtenerPorPrioridad(prioridad);
}
@DeleteMapping(path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){
boolean ok = this.usuarioSrv.eliminarUsuario(id);
if(ok){
return "Se eliminó el usuario con id " + id;
} else{
return "No pudo eliminar el usuario con id " + id;
}
}
}
| true
|
2f56243bfad513eaad9a20377af043846afda257
|
Java
|
vmihnyuk/cars
|
/src/test/java/framework/PropertyReader.java
|
UTF-8
| 1,187
| 2.796875
| 3
|
[] |
no_license
|
package framework;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PropertyReader {
private static FileInputStream fileInputStream;
private static Properties property;
private static Logger log = Logger.getLogger(PropertyReader.class.getName());
static {
try {
String canonPath = CommonFunctions.getCanonicalPathToResource();
fileInputStream = new FileInputStream(new StringBuilder().append(canonPath).append("config.properties").toString());
property = new Properties();
property.load(fileInputStream);
} catch (Exception ex) {
log.log(Level.SEVERE, "Error with canonical path!", ex);
} finally {
if (fileInputStream != null)
try {
fileInputStream.close();
} catch (IOException e) {
log.log(Level.SEVERE, "Error with reading property!", e);
}
}
}
public static String getTestProperty(String key) {
return property.getProperty(key);
}
}
| true
|
2e19ed27c51973ba575c43bc781a0f84407f03c7
|
Java
|
Folenik/Random-Figures-List-Generator
|
/app/src/main/java/com/dawidredel/myapplication/Models/Figure.java
|
UTF-8
| 3,306
| 3.5
| 4
|
[] |
no_license
|
package com.dawidredel.myapplication.Models;
import java.util.Random;
//klasa zawierająca w sobie same settery i gettery
//jest to pojedynczy element na liście
public class Figure {
private Integer firstrandom, secondrandom; // beda używane w konstruktorze domyslnym (public Figure ponizej)
int randomNumber = new Random().nextInt(3) + 1; // wylosowanie liczby z zakresu 1-3
int randomDimension1; // losowy wymiar1
int randomDimension2; // losowy wymiar2
int result;
int visibility = 1;
int wasChanged = 0;
public Figure(int firstrandom, int secondrandom) {
this.firstrandom = firstrandom;
this.secondrandom = secondrandom;
randomDimension1 = new Random().nextInt((secondrandom - firstrandom) + 1) + firstrandom;
randomDimension2 = new Random().nextInt((secondrandom - firstrandom) + 1) + firstrandom;
//tworzac nowy obiekt Figure nalezy podac paremtr firstrandom oraz secondrandom ktore to
//sa zakresem liczbowym (np od 5 do 10), nastepnie w tym zakresie losuja sie dwie liczby
// randomDimension1 oraz randomDimension2
}
public int getTypeOfFigure() {
return randomNumber;
} // funkcja umozliwiajaca pobranie typu figury (ustalilem ze 1 to prostokat, 2 to trojkat, 3 to kolo)
public void setTypeOfFigure(int randomNumber) {
this.randomNumber= randomNumber;
} // pozwala ustawić randomDimension1 (uzywane jest przy edycji elementu dla nadania mu nowego boku)
public Integer getDimension1() {
return randomDimension1;
} // umozliwia pobranie losowego boku 1
public Integer getDimension2() {
return randomDimension2;
} // umozliwia pobranie losowego bokui 2
public Integer getRectangleArea() {
return randomDimension1 * randomDimension2;
} // umozliwia pobranie pola prostokata
public Integer getTriangleArea() {
return ((randomDimension1 * randomDimension2) / 2);
} // jak wyzej
public Double getCircleArea() {
return (3.141592 * ((getDimension1()*getDimension1())));
} // jak wyzej
public Integer getRectanglePerimeter() {
return 2*randomDimension1 + 2*randomDimension2;
} // umozliwia pobranie pola prostokata
public Integer getTrianglePerimeter() {
return 3*randomDimension1;
} // jak wyzej
public Double getCirclePerimeter() {
return (2*getDimension1()*3.141592);
} // jak wyzej
public void setDimension1(int randomDimension1) {
this.randomDimension1 = randomDimension1;
} // pozwala ustawić randomDimension1 (uzywane jest przy edycji elementu dla nadania mu nowego boku)
public void setDimension2(int randomDimension2) {
this.randomDimension2 = randomDimension2;
} // jak wyzej. ponizsze settery i gettery dzialaja analogicznie
public void setResult(int result) {
this.result = result;
}
public Integer getResult() {
return result;
}
public void setVisibility(int visibility) {
this.visibility = visibility;
}
public Integer getVisibility() {
return visibility;
}
public void setChanged(int wasChanged) {
this.wasChanged = wasChanged;
}
public Integer getChanged() {
return wasChanged;
}
}
| true
|
96ff60e85ea05bc6d3176b555f2f1908c69941c7
|
Java
|
sangeethkumarasp/javaprog
|
/12DDEC18/src/sangeethjava/Prog2.java
|
UTF-8
| 758
| 2.9375
| 3
|
[] |
no_license
|
package sangeethjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Prog2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Stuudent>li=new ArrayList<Stuudent>();
li.add(new Stuudent(10,"sangeeth",14));
li.add(new Stuudent(40,"ramesh",05));
li.add(new Stuudent(30,"raju",13));
li.add(new Stuudent(80,"kaju",141));
li.add(new Stuudent(70,"teju",124));
li.add(new Stuudent(780,"ara",134));
li.add(new Stuudent(1450,"bora",144));
li.add(new Stuudent(1560,"zaer",184));
li.add(new Stuudent(1890,"tURA",194));
Collections.sort(li);
for(Stuudent se:li)
{
System.out.println(se.id+" "+se.name+""+se.age);
}
}
}
| true
|
56b5a6f353c5d50471973e6f3bf57ba9da59b8c4
|
Java
|
dehrgg/spring-todos
|
/src/main/java/com/dehrg/todos/model/TaskList.java
|
UTF-8
| 249
| 2.125
| 2
|
[] |
no_license
|
package com.dehrg.todos.model;
import java.util.Set;
public interface TaskList extends PersistentEntity<Long> {
public String getName();
public void setName(String name);
public Set<Task> getTasks();
public void setTasks(Set<Task> tasks);
}
| true
|
50f8bf9bb7cc55f31bacad629a24413d238bef57
|
Java
|
pwm2017/pwm
|
/eureca/src/it/unirc/pwm/eureca/action/socio/UpdateTessera.java
|
UTF-8
| 930
| 2.140625
| 2
|
[] |
no_license
|
package it.unirc.pwm.eureca.action.socio;
import com.opensymphony.xwork2.ActionSupport;
import it.unirc.pwm.eureca.tessera.dao.TesseraDAOFactory;
import it.unirc.pwm.eureca.tessera.dao.TesseraDAOInterface;
import it.unirc.pwm.eureca.tessera.model.Tessera;
public class UpdateTessera extends ActionSupport
{
private static final long serialVersionUID = 1L;
private Tessera tessera=new Tessera();
private TesseraDAOInterface tdao=TesseraDAOFactory.getDAO();
public Tessera getTessera() {
return tessera;
}
public void setTessera(Tessera tessera) {
this.tessera = tessera;
}
public String execute()
{
return SUCCESS;
}
public String modificaTessera()
{
if(tdao.modificaTessera(tessera))
{
addActionMessage("Tessera modificata correttemente");
return SUCCESS;
}
else
addActionError("Errore nel modifica Tessera");;
return INPUT;
}
}
| true
|
e0f8a8cb8d774d00cc3f4a70401231b656fe3850
|
Java
|
Osamasaqr84/lord
|
/app/src/main/java/com/codesroots/hossam/lordApp/dataLayer/repositories/CategoryRepository.java
|
UTF-8
| 5,572
| 2.359375
| 2
|
[] |
no_license
|
package com.codesroots.hossam.lordApp.dataLayer.repositories;
import android.support.v4.util.Consumer;
import android.util.Log;
import com.codesroots.hossam.lordApp.dataLayer.apiData.ApiInterface;
import com.codesroots.hossam.lordApp.entities.BestOffers;
import com.codesroots.hossam.lordApp.entities.Categories;
import com.codesroots.hossam.lordApp.entities.MoreRate;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CategoryRepository {
private ApiInterface apiService;
private Consumer<Categories> onSuccess;
private Consumer<BestOffers> onSuccessBestOffera;
private Consumer<MoreRate> onSuccessMoreRate;
private Consumer<Throwable> onError;
private Consumer<Throwable> onErrorBestOffers;
private Consumer<Throwable> onErrorMoreRate;
public CategoryRepository(ApiInterface apiService)
{
this.apiService = apiService;
}
public void getAllCategoryData() {
try {
apiService.getCatigriesData().enqueue(new Callback<Categories>() {
@Override
public void onResponse(Call<Categories> call, final Response<Categories> response) {
if (response.body() != null) {
if (response.isSuccessful()) {
if (onSuccess != null) {
onSuccess.accept(response.body());
}
} else {
// TODO: return error
if (onError != null) {
onError.accept(new Exception());
}
}
}
}
@Override
public void onFailure(Call<Categories> call, Throwable t) {
Log.d("GetAllData fail -> ", call.toString());
// TODO: return error
if (onError != null) {
onError.accept(t);
}
}
});
} catch (Exception e) {
Log.d("SplashRepository", e.getMessage());
onError.accept(e);
}
}
public void getBestOffers() {
try {
apiService.getbestoffers().enqueue(new Callback<BestOffers>() {
@Override
public void onResponse(Call<BestOffers> call, final Response<BestOffers> response) {
if (response.body() != null) {
if (response.isSuccessful()) {
if (onSuccessBestOffera != null) {
onSuccessBestOffera.accept(response.body());
}
} else {
// TODO: return error
if (onError != null) {
onError.accept(new Exception());
}
}
}
}
@Override
public void onFailure(Call<BestOffers> call, Throwable t) {
Log.d("GetAllData fail -> ", call.toString());
// TODO: return error
if (onErrorBestOffers != null) {
onErrorBestOffers.accept(t);
}
}
});
} catch (Exception e) {
Log.d("SplashRepository", e.getMessage());
onErrorBestOffers.accept(e);
}
}
public void getMoreRate() {
try {
apiService.getMoreRate().enqueue(new Callback<MoreRate>() {
@Override
public void onResponse(Call<MoreRate> call, final Response<MoreRate> response) {
if (response.body() != null) {
if (response.isSuccessful()) {
if (onSuccessMoreRate != null) {
onSuccessMoreRate.accept(response.body());
}
} else {
// TODO: return error
if (onError != null) {
onError.accept(new Exception());
}
}
}
}
@Override
public void onFailure(Call<MoreRate> call, Throwable t) {
Log.d("GetAllData fail -> ", call.toString());
// TODO: return error
if (onErrorMoreRate != null) {
onErrorMoreRate.accept(t);
}
}
});
} catch (Exception e) {
Log.d("SplashRepository", e.getMessage());
onErrorMoreRate.accept(e);
}
}
public void setOnSuccess(Consumer<Categories> onSuccess) {
this.onSuccess = onSuccess;
}
public void setOnSuccessBest(Consumer<BestOffers> onSuccessBest) {
this.onSuccessBestOffera = onSuccessBest;
}
public void setonSuccessMoreRate(Consumer<MoreRate> onSuccessRate) {
this.onSuccessMoreRate = onSuccessRate;
}
public void setOnError(Consumer<Throwable> onError) {
this.onError = onError;
}
public void onErrorBestOffers(Consumer<Throwable> onError) {
this.onErrorBestOffers = onError;
}
public void onErrorMoreRate(Consumer<Throwable> onError) {
this.onErrorMoreRate = onError;
}
}
| true
|
32f615aaab34afd5a8fa0f32f897b3ed383e6a19
|
Java
|
wang-shun/ecom-maindir
|
/ecom-cms/src/main/java/com/cn/thinkx/ecom/order/service/OrderInfService.java
|
UTF-8
| 1,110
| 1.726563
| 2
|
[] |
no_license
|
package com.cn.thinkx.ecom.order.service;
import java.util.List;
import com.cn.thinkx.ecom.common.service.BaseService;
import com.cn.thinkx.ecom.order.domain.OrderInf;
import com.github.pagehelper.PageInfo;
public interface OrderInfService extends BaseService<OrderInf> {
/**
* 电商交易流水明细
*
* @return
*/
List<OrderInf> listOrderDetail(OrderInf orderInf);
/**
* 电商交易流水明细(含分页)
*
* @param startNum
* @param pageSize
* @param entity
* @return
*/
PageInfo<OrderInf> getOrderDetailPage(int startNum, int pageSize, OrderInf entity);
/**
* 电商交易流水汇总
*
* @param orderInf
* @return
*/
List<OrderInf> listOrderSummarizing(OrderInf orderInf);
/**
* 电商交易流水汇总(含分页)
*
* @param startNum
* @param pageSize
* @param entity
* @return
*/
PageInfo<OrderInf> getOrderSummarizingPage(int startNum, int pageSize, OrderInf entity);
/**
* 根据userID或personalName查询tb_person_inf信息
*
* @param orderInf
* @return
*/
OrderInf getPersonInf(OrderInf orderInf);
}
| true
|
67404082507968b8e50300bd2f72aa43ce9fbb40
|
Java
|
bhupenderkumar/java-compiler
|
/java-compiler-data/src/main/java/files/entities/File.java
|
UTF-8
| 5,173
| 2.171875
| 2
|
[] |
no_license
|
package files.entities;
import files.queries.Queries;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Kacper on 2014-10-09.
*/
@NamedQueries({
@NamedQuery(name = Queries.FILE_BY_ID,
query = "select f from File f where f.id = :id"),
@NamedQuery(name = Queries.USER_FILES,
query = "select f from File f " +
"where f.userId = :id " +
"order by f.creationTime desc"),
@NamedQuery(name = Queries.ALL_FILES,
query = "select f from File f"),
@NamedQuery(name = Queries.FILE_VISIBILITY_BY_FILE_ID,
query = "select fv from FileVisibility fv, File f " +
"where fv.id = f.fileVisibilityId " +
"and f.id = :id"),
@NamedQuery(name = Queries.FILE_STATUS_BY_FILE_ID,
query = "select fs from FileStatus fs, File f " +
"where fs.id = f.fileStatusId " +
"and f.id = :id " +
"order by f.creationTime desc"),
@NamedQuery(name = Queries.FILES_BY_VISIBILITY_ID,
query = "select f from File f " +
"where f.fileVisibilityId = :id " +
"order by f.creationTime desc") ,
@NamedQuery(name = Queries.FILES_BY_STATUS_ID,
query = "select f from File f " +
"where f.fileStatusId = :id"),
@NamedQuery(name = Queries.RECENT_FILES,
query = "select f from File f " +
"order by f.id desc"),
@NamedQuery(name = Queries.COUNT_BY_VISIBILITY,
query = "select count(f) from File f " +
"where f.fileVisibilityId = :id"),
@NamedQuery(name = Queries.COUNT_BY_STATUS,
query = "select count(f) from File f " +
"where f.fileStatusId = :id"),
@NamedQuery(name = Queries.COUNT_ALL,
query = "select count(f) from File f"),
@NamedQuery(name = Queries.USER_FILES_PUBLIC,
query = "select f from File f " +
"where f.userId = :id " +
"and f.fileVisibilityId = :fvId " +
"order by f.creationTime desc")
})
@NamedNativeQueries({
@NamedNativeQuery(name = Queries.ADD_FILE,
query = "insert into files (filename, file_status_id, file_visibility_id, user_id, creation_time, description) " +
"values(?,?,?,?,?,?)"),
@NamedNativeQuery(name = Queries.EDIT_FILE,
query = "update files set filename = ?, file_status_id = ?, file_visibility_id = ?, description = ? " +
"where file_id = ?"),
@NamedNativeQuery(name = Queries.DELETE_FILE,
query = "delete from comments " +
"where file_id = ?;" +
"delete from files " +
"where file_id = ?;")
})
@Entity
@Table(name = "files")
public class File implements Serializable {
private static final long serialVersionUID = -3159813981500842506L;
// file_id serial NOT NULL,
// source_code text NOT NULL,
// file_status_id bigint NOT NULL,
// file_visibility_id bigint NOT NULL
@Id
@Column(name = "file_id", nullable = false, columnDefinition = "bigserial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "filename", nullable = false)
private String filename;
@Column(name = "file_status_id", nullable = false)
private Long fileStatusId;
@Column(name = "file_visibility_id", nullable = false)
private Long fileVisibilityId;
@Column(name = "user_id", nullable = false)
private Long userId;
@Column(name = "creation_time", nullable = false)
private Date creationTime;
@Column(name = "description", nullable = false)
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Long getFileStatusId() {
return fileStatusId;
}
public void setFileStatusId(Long fileStatusId) {
this.fileStatusId = fileStatusId;
}
public Long getFileVisibilityId() {
return fileVisibilityId;
}
public void setFileVisibilityId(Long fileVisibilityId) {
this.fileVisibilityId = fileVisibilityId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long user_id) {
this.userId = user_id;
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return String.format("[file_id=%d, filename=%s, file_visibility_id=%d, file_status_id=%s, user_id=%s", id, filename, fileVisibilityId, fileStatusId, userId);
}
}
| true
|
61a3c26d96b173ca3f6ce929c402e889c971ac3f
|
Java
|
stellar/java-stellar-sdk
|
/src/main/java/org/stellar/sdk/responses/operations/ChangeTrustOperationResponse.java
|
UTF-8
| 1,741
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.stellar.sdk.responses.operations;
import static org.stellar.sdk.Asset.create;
import com.google.common.base.Optional;
import com.google.gson.annotations.SerializedName;
import java.math.BigInteger;
import org.stellar.sdk.Asset;
import org.stellar.sdk.responses.MuxedAccount;
/**
* Represents ChangeTrust operation response.
*
* @see <a href="https://developers.stellar.org/api/resources/operations/" target="_blank">Operation
* documentation</a>
* @see org.stellar.sdk.requests.OperationsRequestBuilder
* @see org.stellar.sdk.Server#operations()
*/
public class ChangeTrustOperationResponse extends OperationResponse {
@SerializedName("trustor")
private String trustor;
@SerializedName("trustor_muxed")
private String trustorMuxed;
@SerializedName("trustor_muxed_id")
private BigInteger trustorMuxedId;
@SerializedName("trustee")
private String trustee;
@SerializedName("asset_type")
private String assetType;
@SerializedName("asset_code")
private String assetCode;
@SerializedName("asset_issuer")
private String assetIssuer;
@SerializedName("limit")
private String limit;
@SerializedName("liquidity_pool_id")
private String liquidityPoolId;
public Optional<MuxedAccount> getTrustorMuxed() {
if (this.trustorMuxed == null || this.trustorMuxed.isEmpty()) {
return Optional.absent();
}
return Optional.of(new MuxedAccount(this.trustorMuxed, this.trustor, this.trustorMuxedId));
}
public String getTrustor() {
return trustor;
}
public String getTrustee() {
return trustee;
}
public String getLimit() {
return limit;
}
public Asset getAsset() {
return create(assetType, assetCode, assetIssuer, liquidityPoolId);
}
}
| true
|
ba757a87165e18146e89b019d3240b2d121cd090
|
Java
|
dharmendrams84/POSBaseCode
|
/src/oracle/retail/stores/pos/ado/utility/TypesafeEnumIfc.java
|
UTF-8
| 1,784
| 1.757813
| 2
|
[] |
no_license
|
/* ===========================================================================
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* ===========================================================================
* $Header: rgbustores/applications/pos/src/oracle/retail/stores/pos/ado/utility/TypesafeEnumIfc.java /rgbustores_13.4x_generic_branch/1 2011/05/05 14:05:41 mszekely Exp $
* ===========================================================================
* NOTES
* <other useful comments, qualifications, etc.>
*
* MODIFIED (MM/DD/YY)
* cgreene 05/26/10 - convert to oracle packaging
* abondala 01/03/10 - update header date
*
* ===========================================================================
* $Log:
* 3 360Commerce 1.2 3/31/2005 4:30:37 PM Robert Pearse
* 2 360Commerce 1.1 3/10/2005 10:26:29 AM Robert Pearse
* 1 360Commerce 1.0 2/11/2005 12:15:20 PM Robert Pearse
*
* Revision 1.2 2004/02/12 16:47:58 mcs
* Forcing head revision
*
* Revision 1.1.1.1 2004/02/11 01:04:11 cschellenger
* updating to pvcs 360store-current
*
*
*
* Rev 1.1 Nov 07 2003 10:53:58 epd
* added serializable interface
*
* Rev 1.0 Nov 04 2003 11:15:08 epd
* Initial revision.
*
* Rev 1.0 Oct 17 2003 12:39:08 epd
* Initial revision.
*
* ===========================================================================
*/
package oracle.retail.stores.pos.ado.utility;
import java.io.Serializable;
/**
* Defines the public contract all typesafe enumerations must implement
*
*/
public interface TypesafeEnumIfc extends Serializable
{
/** fix deserialization */
public abstract Object readResolve() throws java.io.ObjectStreamException;
}
| true
|
e59f3dd8f64ac54df643e091562bb8cfba8330e8
|
Java
|
lee-jung-beom/Java
|
/src/e_oop/SampleClass.java
|
UTF-8
| 1,264
| 3.6875
| 4
|
[] |
no_license
|
package e_oop;
public class SampleClass {
// int field;
//메소드 안에 있는 변수를 "지역변수"라 한다.
//메소드 밖에 있는 변수를 "전역변수"라 한다.
// public static void main(String[] args) {
// int local = 10;
// }
/*
* - 메서드 : 변수를 가지고 할 일
* - 선언 방법 : 리턴타입 메서드명(파라미터){}
* - 파라미터(매개변수) : 실행에 필요한 정보
* - 리턴타입(반환타입) : 실행 후 돌려줘야하는 결과물
*/
// String method1(int parameter){
//
// return parameter + " 를 받아 명령을 수행하고 결과물을 리턴하는 메서드";
// }
//
// void method2(){
// System.out.println("파라미터도 리턴타입도 없는 메서드");
// }
//flowTest1() 호출시 출력되는 문장에 출력 순서대로 번호를 붙여주세요.
// void flowTest1(){
// System.out.println("flowTest1 시작 : 1");
// flowTest3();
// System.out.println("flowTest1 종료 : 6");
// }
// void flowTest2(){
// System.out.println("flowTest2 시작 : 3");
// System.out.println("flowTest2 종료 : 4");
// }
// void flowTest3(){
// System.out.println("flowTest3 시작 : 2");
// flowTest2();
// System.out.println("flowTest3 종료 : 5");
// }
}
| true
|
542b640d336fb8f586535433065c55241bbe3212
|
Java
|
Lorandi/cwi-reset-03-level1
|
/Modulo2/src/aula04/Cliente.java
|
UTF-8
| 217
| 2.203125
| 2
|
[] |
no_license
|
package aula04;
import java.net.HttpURLConnection;
public class Cliente {
private int idade;
private int nome;
public Cliente(int idade) {
this.idade = idade;
this.nome = nome;
}
}
| true
|
6d485a2d9d8aeaeba2afc54bcd4d942f5a81238d
|
Java
|
SidhuAmn/project1
|
/src/game/CardTest.java
|
UTF-8
| 6,060
| 2.671875
| 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 GinRummy;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class CardTest {
public CardTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getPoints method, of class Card.
*/
@Test
public void testGetPointsGood() {
System.out.println("getPoints");
Card instance = new Card();
int expResult = 0;
int result = instance.getPoints();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetPointsBad() {
System.out.println("getPoints");
Card instance = new Card();
int expResult = 0;
int result = instance.getPoints();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetPointsBoundary() {
System.out.println("getPoints");
Card instance = new Card();
int expResult = 0;
int result = instance.getPoints();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
/**
* Test of getOrder method, of class Card.
*/
@Test
public void testGetOrderGood() {
System.out.println("getOrder");
Card instance = new Card();
int expResult = 0;
int result = instance.getOrder();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetOrderBad() {
System.out.println("getOrder");
Card instance = new Card();
int expResult = 0;
int result = instance.getOrder();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetOrderBounary() {
System.out.println("getOrder");
Card instance = new Card();
int expResult = 0;
int result = instance.getOrder();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
/**
* Test of getRank method, of class Card.
*/
@Test
public void testGetRankGood() {
System.out.println("getRank");
Card instance = new Card();
Rank expResult = null;
Rank result = instance.getRank();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetRankBad() {
System.out.println("getRank");
Card instance = new Card();
Rank expResult = null;
Rank result = instance.getRank();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetRankBoundary() {
System.out.println("getRank");
Card instance = new Card();
Rank expResult = null;
Rank result = instance.getRank();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
/**
* Test of getSuit method, of class Card.
*/
@Test
public void testGetSuitGood() {
System.out.println("getSuit");
Card instance = new Card();
Suit expResult = null;
Suit result = instance.getSuit();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetSuitBad() {
System.out.println("getSuit");
Card instance = new Card();
Suit expResult = null;
Suit result = instance.getSuit();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
@Test
public void testGetSuitBoundary() {
System.out.println("getSuit");
Card instance = new Card();
Suit expResult = null;
Suit result = instance.getSuit();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
/**
* Test of toString method, of class Card.
*/
@Test
public void testToString() {
System.out.println("toString");
Card instance = new Card();
String expResult = "";
String result = instance.toString();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
}
| true
|
b8e862b01c6ea768a49ad30d3649e99d0f50570e
|
Java
|
mostafaeweda/advanced-search-techniques
|
/ advancedsearchingtechniquesmostafaeweda/Searching/src/search/methods/BinarySearchTest.java
|
UTF-8
| 2,057
| 2.8125
| 3
|
[] |
no_license
|
package search.methods;
import junit.framework.TestCase;
import list.AbstractList;
import list.SortedList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import search.compartors.IntegerCompartor;
public class BinarySearchTest extends TestCase {
private static AbstractSearch<Integer, IntegerCompartor> search;;
private static AbstractList<Integer> list;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
list = new SortedList<Integer>(10, new IntegerCompartor());
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
search = new BinarySearch<Integer, IntegerCompartor>(list, new IntegerCompartor());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
list = new SortedList<Integer>(10, new IntegerCompartor());
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
search = new BinarySearch<Integer, IntegerCompartor>(list, new IntegerCompartor());
}
@After
public void tearDown() throws Exception {
}
@Test
public void testFind() {
assertEquals(null, search.find(0));
assertEquals(new Integer(1), search.find(1));
assertEquals(new Integer(2), search.find(2));
assertEquals(new Integer(3), search.find(3));
assertEquals(new Integer(4), search.find(4));
assertEquals(new Integer(5), search.find(5));
assertEquals(new Integer(6), search.find(6));
assertEquals(new Integer(7), search.find(7));
assertEquals(new Integer(8), search.find(8));
assertEquals(new Integer(9), search.find(9));
assertEquals(new Integer(10), search.find(10));
assertEquals(null, search.find(11));
}
@Test
public void testFindAll() {
fail("Not yet implemented");
}
}
| true
|
8dbd1d26e62718bde275f1a11eb4f1d2620c7eb0
|
Java
|
xiansenxuan/bilibili-for-app
|
/app/src/main/java/com/xuan/myframework/rx/http/CacheProviders.java
|
UTF-8
| 4,423
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.xuan.myframework.rx.http;
import com.xuan.myframework.view.modle.response.BangumiCommentsModle;
import com.xuan.myframework.view.modle.response.BangumiDetailModle;
import com.xuan.myframework.view.modle.response.BangumiDetailsRecommendedModle;
import com.xuan.myframework.view.modle.response.BangumiIndexModle;
import com.xuan.myframework.view.modle.response.BangumiModle;
import com.xuan.myframework.view.modle.response.BangumiRecommendedModle;
import com.xuan.myframework.view.modle.response.BroadcastTableModle;
import com.xuan.myframework.view.modle.response.ChaseBangumiModle;
import com.xuan.myframework.view.modle.response.ClassificationModle;
import com.xuan.myframework.view.modle.response.CommentModle;
import com.xuan.myframework.view.modle.response.LiveDataModle;
import com.xuan.myframework.view.modle.response.RecommendBannerModle;
import com.xuan.myframework.view.modle.response.RecommendModle;
import com.xuan.myframework.view.modle.response.UserDetailsModle;
import com.xuan.myframework.view.modle.response.VideoDetailsModle;
import com.xuan.myframework.view.modle.response.VideoPlayerModle;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.rx_cache2.EvictProvider;
import io.rx_cache2.LifeCache;
/**
* Created by xuan on 2017/5/10.
*/
public interface CacheProviders {
long duration=3;
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<LiveDataModle> queryLiveData(Observable<LiveDataModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<String> queryLivePlayerData(Observable<String> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<UserDetailsModle> queryUserDetails(Observable<UserDetailsModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<RecommendBannerModle> queryRecommendBannerData(Observable<RecommendBannerModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<RecommendModle> queryRecommendData(Observable<RecommendModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<VideoDetailsModle> queryVideoDetails(Observable<VideoDetailsModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<CommentModle> queryCommentData(Observable<CommentModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<VideoPlayerModle> queryVideoPlayerData(Observable<VideoPlayerModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiRecommendedModle> queryBangumiRecommendedData(Observable<BangumiRecommendedModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiModle> queryBangumiData(Observable<BangumiModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<ChaseBangumiModle> queryChaseBangumiData(Observable<ChaseBangumiModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BroadcastTableModle> queryBroadcastTableData(Observable<BroadcastTableModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiIndexModle> queryBangumiIndexData(Observable<BangumiIndexModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiDetailModle> queryBangumiDetailsData(Observable<BangumiDetailModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiDetailsRecommendedModle> queryBangumiDetailsRecommendData(Observable<BangumiDetailsRecommendedModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<BangumiCommentsModle> queryBangumiDetailsCommentsData(Observable<BangumiCommentsModle> o, EvictProvider provider);
@LifeCache(duration = duration, timeUnit = TimeUnit.MINUTES)
Observable<ClassificationModle> queryClassificationData(Observable<ClassificationModle> o, EvictProvider provider);
}
| true
|
5c043ff768da880e4037da7d2932c889f343a9ba
|
Java
|
easyGuyLyn/lt_b_pai
|
/app/src/main/java/com/dawoo/lotterybox/adapter/lhc/LHCBaseAdapter.java
|
UTF-8
| 8,107
| 2.21875
| 2
|
[] |
no_license
|
package com.dawoo.lotterybox.adapter.lhc;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.dawoo.lotterybox.BoxApplication;
import com.dawoo.lotterybox.R;
import com.dawoo.lotterybox.bean.playtype.PlayDetailBean;
import com.dawoo.lotterybox.util.lottery.LHCUtil;
import com.dawoo.lotterybox.util.lottery.initdata.LHCDataUtils;
import com.dawoo.lotterybox.util.lottery.initdata.Lottery_B_DataUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rain on 18-4-23.
*/
public class LHCBaseAdapter extends RecyclerView.Adapter implements View.OnClickListener {
final int ASKTYPE = 0;
final int BALLTYPETWO = 1;
final int BALLTYPETHREE = 2;
final int WORDTYPETHREE = 3;
final int WORDTYPETWO = 4;
private List<PlayDetailBean> mDatas = new ArrayList<>();
private OnItemClickListener onItemClickListener;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == ASKTYPE) {
return new ASKViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_question_ask, parent, false));
} else if(viewType==BALLTYPETHREE||viewType==BALLTYPETWO){
return new BOLLViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_lhc_bo_item, parent, false));
}else{
return new WordViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_lhc_play_item, parent, false));
}
}
public PlayDetailBean getItem(int position){
return mDatas.get(position);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
holder.itemView.setTag(position);
if (holder instanceof ASKViewHolder)
((ASKViewHolder) holder).bindView(mDatas.get(position));
else if (holder instanceof WordViewHolder)
((WordViewHolder) holder).bindView(mDatas.get(position));
else if (holder instanceof BOLLViewHolder)
((BOLLViewHolder) holder).bindView(mDatas.get(position));
}
@Override
public int getItemCount() {
return mDatas.size();
}
@Override
public int getItemViewType(int position) {
if (mDatas.get(position).isAskview()) {
return ASKTYPE;
} else {
if (Lottery_B_DataUtils.isNum(mDatas.get(position).getNum())) {
int num = Integer.parseInt(mDatas.get(position).getNum());
if (num < 46) {
return BALLTYPETHREE;
}else {
return BALLTYPETWO;
}
} else if (mDatas.get(position).getNum().contains("波")) {
return WORDTYPETHREE;
}else {
return WORDTYPETWO;
}
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int type = getItemViewType(position);
switch (type) {
case ASKTYPE:
return 6;
case BALLTYPETWO:
case WORDTYPETWO:
return 3;
default:
return 2;
}
}
});
}
}
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
//注意这里使用getTag方法获取position
onItemClickListener.onItemClick(v,(int)v.getTag());
}
}
class ASKViewHolder extends RecyclerView.ViewHolder {
TextView view;
public ASKViewHolder(View itemView) {
super(itemView);
view = itemView.findViewById(R.id.question_ask_tv);
if(onItemClickListener!=null){
itemView.setOnClickListener(LHCBaseAdapter.this);
}
}
public void bindView(PlayDetailBean bean) {
view.setText(bean.getNum());
}
}
class BOLLViewHolder extends RecyclerView.ViewHolder {
TextView numView;
TextView changeView;
TextView oddView;
public BOLLViewHolder(View itemView) {
super(itemView);
numView = itemView.findViewById(R.id.lhc_bo_tv);
oddView = itemView.findViewById(R.id.odds_tv);
changeView = itemView.findViewById(R.id.tv_change);
if(onItemClickListener!=null){
itemView.setOnClickListener(LHCBaseAdapter.this);
}
}
public void bindView(PlayDetailBean bean) {
numView.setText(bean.getNum());
oddView.setText(bean.getOdd());
if (LHCDataUtils.hot == 0) {
changeView.setText("");
} else if (LHCDataUtils.hot == 1) {
changeView.setText(bean.getLr());
} else {
changeView.setText(bean.getYl());
}
numView.setBackground(BoxApplication.getContext().getResources().getDrawable(LHCUtil.getBallbg(bean.getNum())));
if (bean.isSelected()) {
oddView.setTextColor(BoxApplication.getContext().getResources().getColor(R.color.text_note_record_yellow));
} else {
oddView.setTextColor(BoxApplication.getContext().getResources().getColor(R.color.color_gray_333333));
}
itemView.setSelected(bean.isSelected());
}
}
class WordViewHolder extends RecyclerView.ViewHolder{
TextView numView;
TextView changeView;
TextView oddView;
public WordViewHolder(View itemView) {
super(itemView);
numView = itemView.findViewById(R.id.lhc_play_tv);
oddView = itemView.findViewById(R.id.odds_tv);
changeView = itemView.findViewById(R.id.tv_change);
if(onItemClickListener!=null){
itemView.setOnClickListener(LHCBaseAdapter.this);
}
}
public void bindView(PlayDetailBean bean) {
numView.setText(bean.getNum());
oddView.setText(bean.getOdd());
if (LHCDataUtils.hot == 0) {
changeView.setText("");
} else if (LHCDataUtils.hot == 1) {
changeView.setText(bean.getLr());
} else {
changeView.setText(bean.getYl());
}
if (bean.isSelected()) {
numView.setTextColor( BoxApplication.getContext().getResources().getColor(R.color.text_note_record_yellow));
oddView.setTextColor( BoxApplication.getContext().getResources().getColor(R.color.text_note_record_yellow));
} else {
numView.setTextColor( BoxApplication.getContext().getResources().getColor(R.color.black));
oddView.setTextColor( BoxApplication.getContext().getResources().getColor(R.color.color_gray_333333));
}
itemView.setSelected(bean.isSelected());
}
}
public interface OnItemClickListener{
void onItemClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
public void setmDatas(List<PlayDetailBean> mDatas){
this.mDatas = mDatas;
}
}
| true
|
cb5b1a304fcc9f3daaca9ce6f1335d525d8cd69e
|
Java
|
aviorbarkan/CPS
|
/src/core/guiUtilities/FloatNumberTextField.java
|
UTF-8
| 782
| 2.859375
| 3
|
[] |
no_license
|
package core.guiUtilities;
import javafx.scene.control.TextField;
public class FloatNumberTextField extends TextField {
private final String FloatNumberRegex = "^(\\d*[.])?\\d+$";
@Override
public void replaceText(int start, int end, String text) {
if (validate(text)) {
super.replaceText(start, end, text);
}
}
@Override
public void replaceSelection(String text) {
if (validate(text)) {
super.replaceSelection(text);
}
}
private boolean validate(String text) {
return text.matches(CpsRegEx.FloatAllowedCharacter);
}
public Float getFloat() {
if(!this.getText().matches(FloatNumberRegex)) {
return Float.NaN;
}
if (this.getText().length() < 9) {
return Float.parseFloat(this.getText());
} else {
return Float.MAX_VALUE;
}
}
}
| true
|
cca796bd8c20f9cc12701050aa966ddd07ce8e2e
|
Java
|
codingliang/tist
|
/src/njxzc/royxu/dao/GroupMemberDao.java
|
UTF-8
| 1,109
| 2.171875
| 2
|
[] |
no_license
|
package njxzc.royxu.dao;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.core.BaseDao;
import njxzc.royxu.domain.GroupMember;
/**
* 项目组成员DAO接口
* @author LiangHong
* @version 2015-10-24
*/
@Repository
public class GroupMemberDao extends BaseDao<GroupMember> {
@Resource
private HibernateTemplate hibernateTemplate;
// 根据del_flag批量修改(等于删除)
public void deleteGroupMembersBySqls(String[] ids) throws SQLException{
List<String> sqls = new ArrayList<String>();
for(String id : ids){
String sql = "update GroupMember set ? where = ?";
sqls.add(sql);
}
updateSqls(sqls);
}
@SuppressWarnings("unchecked")
public List<GroupMember> findGroupMembers(){
String hql = "from GroupMember ";
hql += " order by field(member_type,'老师','学生'),member_sort ";
List<GroupMember> groupMembers = (List<GroupMember>) find(hql);
return groupMembers;
}
}
| true
|
2ffde6d0e020db51215101a6f11c162bcf00467d
|
Java
|
MorningCoffee/GuavaLabs
|
/guava-labs/src/test/java/com/morningcoffee/guava/OptionalTest.java
|
UTF-8
| 5,384
| 3.296875
| 3
|
[] |
no_license
|
package com.morningcoffee.guava;
import com.google.common.base.Optional;
import org.junit.Test;
import static junit.framework.Assert.*;
/**
* Exploring Optional type that fight null-driven development designs
*
* @see <a href="https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained">Guava Guide Article</a>
* Date: 3/23/13
*
* @author osklyarenko
*/
public class OptionalTest {
/**
* Optional#of doesn't allow null passed as a value. Fails fast with NPE
* @throws Exception
*/
@Test(expected = NullPointerException.class)
public void testOptionalOf1() throws Exception {
Optional.of(null);
}
/**
* Optional#isPresent method tests if actual value is there
* @throws Exception
*/
@Test
public void testOptionalOf2() throws Exception {
final Optional<String> optionalString = Optional.of("string reference");
assertTrue(optionalString.isPresent());
assertTrue(optionalString.get().equals("string reference"));
}
/**
* Optional#toString value is NOT equal to value.toString()
* @throws Exception
*/
@Test
public void testOptionalToString() throws Exception {
final Optional<String> optionalString = Optional.of("string");
assertFalse(optionalString.toString().equals("string"));
System.out.println(optionalString.toString());
}
/**
* Optional#hashCode value is NOT equal to value.hashCode()
* @throws Exception
*/
@Test
public void testOptionalHashCode() throws Exception {
final Optional<String> optionalString = Optional.of("string");
final Optional<Integer> optionalInteger = Optional.of(47);
assertFalse(optionalString.hashCode() == optionalString.get().hashCode());
assertFalse(optionalInteger.hashCode() == optionalInteger.get().hashCode());
assertFalse(Optional.absent().hashCode() == 0);
}
/**
* You can't call Optional#get on absent optionals - throws IllegalStateException.
* When you call Optional#get value must always be present
* @throws Exception
*/
@Test(expected = IllegalStateException.class)
public void testOptionalAbsent() throws Exception {
final Optional<?> absent = Optional.absent();
absent.get();
}
/**
* Optional#fromNullable factory method allows you to create optionals from from possibly null references. Still
* you are forced to check for existence of value with Optional#isPresent before calling Optional#get
* @throws Exception
*/
@Test
public void testOptionalFromNullable() throws Exception {
final Optional<?> optionalNull = Optional.fromNullable(null);
assertFalse(optionalNull.isPresent());
final Optional<Object> optionalNotNull = Optional.fromNullable(new Object());
assertTrue(optionalNotNull.isPresent());
optionalNotNull.get();
}
/**
* When specifying argument for Optional#or its value must always be defined otherwise NPE is thrown
* @throws Exception
*/
@Test(expected = NullPointerException.class)
public void testOptionalOr1() throws Exception {
final Optional<Object> optionalNull = Optional.fromNullable(null);
final Object defaultValue = optionalNull.or("default");
assertTrue(defaultValue == "default");
assertTrue(defaultValue.equals("default"));
optionalNull.or((Object)null); // throws NPE
}
/**
* Optional#or can also accept optionals as argument
* @throws Exception
*/
@Test
public void testOptionalOr2() throws Exception {
final Optional<Object> optionalNull = Optional.fromNullable(null);
final Optional<?> reference = Optional.of("reference");
final Optional<?> defaultValue = optionalNull.or(reference);
assertTrue(defaultValue == reference);
assertTrue(defaultValue.isPresent());
assertEquals(defaultValue.get(), "reference");
}
/**
* If null optional is passed to Optional#or method than it's OK, no exception is thrown
* @throws Exception
*/
@Test
public void testOptionalOr3() throws Exception {
final Optional<Object> optionalNull = Optional.fromNullable(null);
final Optional<Object> defaultOptional = Optional.fromNullable(null);
final Optional<Object> resultingDefaultOptional = optionalNull.or(defaultOptional);
assertTrue(defaultOptional == resultingDefaultOptional);
assertFalse(resultingDefaultOptional.isPresent());
}
/**
* Optional#orNull method allows to return null reference when original value is also null
* @throws Exception
*/
@Test
public void testOptionalOrNull1() throws Exception {
final Optional<?> optionalNull = Optional.fromNullable("value");
final Object value = optionalNull.orNull();
assertNotNull(value);
assertTrue(value == "value");
assertEquals(value, "value");
}
/**
* Optional#orNull returns null when original value is absent
* @throws Exception
*/
@Test
public void testOptionalOrNull2() throws Exception {
final Optional<Object> optionalNull = Optional.fromNullable(null);
final Object _ = optionalNull.orNull();
assertNull(_);
}
}
| true
|
4eeb70e8cf6fd4e50559ff93617882f54b274369
|
Java
|
lussei/Articulos
|
/src/main/java/articulos/DataAccess/Articulos.java
|
UTF-8
| 2,266
| 2.234375
| 2
|
[] |
no_license
|
package articulos.DataAccess;
import articulos.Data.Articulo;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import com.google.gson.Gson;
import java.net.InetAddress;
import java.util.ArrayList;
public class Articulos {
private TransportClient client;
public Articulos() throws Exception{
try {
PreBuiltTransportClient tc = new PreBuiltTransportClient(Settings.EMPTY);
client = tc.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
}
catch(Exception e){
e.printStackTrace();
throw e;
}
}
public void add(Articulo articulo){
//BulkRequestBuilder br = client.prepareBulk();
client.prepareIndex("articulos", "articulos", articulo.getId()).setSource(new Gson().toJson(articulo), XContentType.JSON).get();
}
public void update(Articulo articulo){}
public void delete(Articulo articulo){
client.prepareDelete("articulos", "articulos", articulo.getId()).get();
}
public ArrayList<Articulo> get(Articulo articulo){
ArrayList<Articulo> response = new ArrayList<>();
SearchRequestBuilder qb = client.prepareSearch("articulos");
qb.setSize(1000);
if(articulo != null) qb = qb.setQuery(QueryBuilders.matchQuery("id", articulo.getId()));
SearchResponse resp = qb.get();
try {
if(resp != null) {
SearchHits hits = resp.getHits();
for (SearchHit hit : hits) {
response.add(new Gson().fromJson(hit.getSourceAsString(), Articulo.class));
}
}
}catch (Exception e){
e.printStackTrace();
}
return response;
}
}
| true
|
8dfbd534165b02e615a31edf3287c6701b17e44e
|
Java
|
Lonsiege/prn_parser
|
/prn-parser/src/main/java/com/develeap/excercise/Main.java
|
UTF-8
| 1,240
| 3.015625
| 3
|
[] |
no_license
|
package com.develeap.excercise;
import java.io.IOException;
import com.develeap.excercise.controller.LibraryOperations;
import com.develeap.excercise.controller.MyLibrary;
import com.develeap.excercise.util.LibraryParser;
import com.develeap.excercise.util.PrnParser;
public class Main {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
throw new IllegalArgumentException("Use library prn file as parameter");
}
new Main().go(args[0]);
}
private void go(String fname) throws Exception {
LibraryParser parser = new PrnParser();
LibraryOperations myLibrary = new MyLibrary();
try {
myLibrary = parser.parseFile(fname);
System.out.println("There are " + myLibrary.getBooksCount() + " books and " + myLibrary.getAuthorsCount()
+ " authors in this file.");
System.out.println("The most productive authors are:");
System.out.println(myLibrary.printTopAuthor(myLibrary.getTopThreeAuthors(), 1));
System.out.println(myLibrary.printTopAuthor(myLibrary.getTopThreeAuthors(), 2));
System.out.println(myLibrary.printTopAuthor(myLibrary.getTopThreeAuthors(), 3));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
| true
|
a388f0269aafb3e649894bbee7c121c611e935f0
|
Java
|
markgaffo/SampleMonitoringApp
|
/src/SampleMonitoring/RegisterGUI.java
|
UTF-8
| 16,300
| 2.3125
| 2
|
[] |
no_license
|
package SampleMonitoring;
import SampleMonitoringGUI.CsvDBConnection;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class RegisterGUI extends javax.swing.JFrame {
Connection con=null;
ResultSet rs =null;
PreparedStatement prep =null;
public RegisterGUI() {
initComponents();
con=CsvDBConnection.CsvDBConnection();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
usernameTf = new javax.swing.JTextField();
passwordTf = new javax.swing.JPasswordField();
regBtn = new javax.swing.JButton();
backBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.setToolTipText("");
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SampleMonitoringImages/login pic_1.PNG"))); // NOI18N
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Register", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Constantia", 1, 18), new java.awt.Color(8, 118, 188))); // NOI18N
jLabel2.setText("Password:");
jLabel1.setText("Username:");
passwordTf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordTfActionPerformed(evt);
}
});
passwordTf.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
passwordTfKeyPressed(evt);
}
});
regBtn.setBackground(new java.awt.Color(8, 118, 188));
regBtn.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
regBtn.setForeground(new java.awt.Color(255, 255, 255));
regBtn.setText("Register");
regBtn.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102)));
regBtn.setContentAreaFilled(false);
regBtn.setOpaque(true);
regBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
regBtnMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
regBtnMouseExited(evt);
}
});
regBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(usernameTf, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
.addComponent(passwordTf))
.addContainerGap(20, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(regBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(usernameTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(passwordTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addComponent(regBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
backBtn.setBackground(new java.awt.Color(8, 118, 188));
backBtn.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
backBtn.setForeground(new java.awt.Color(255, 255, 255));
backBtn.setText("Back");
backBtn.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102)));
backBtn.setContentAreaFilled(false);
backBtn.setOpaque(true);
backBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
backBtnMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
backBtnMouseExited(evt);
}
});
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(455, 282));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void passwordTfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordTfActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_passwordTfActionPerformed
private void passwordTfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordTfKeyPressed
if(con != null){
try {
if(con.isClosed()){
con=CsvDBConnection.CsvDBConnection();
}
else{
con.close();
con=CsvDBConnection.CsvDBConnection();
}
} catch (SQLException ex) {
Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
con=CsvDBConnection.CsvDBConnection();
}
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
String sql = "INSERT INTO user VALUES (?,?);";
try{
prep=con.prepareStatement(sql);
prep.setString(1, usernameTf.getText());
prep.setString(2, passwordTf.getText());
prep.execute();
rs.close();
prep.close();
con.close();
this.dispose();
LoginGUI logGui = new LoginGUI();
logGui.setVisible(true);
JOptionPane.showMessageDialog(null, "Account created");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Registeration failed " + e);
}
}
}//GEN-LAST:event_passwordTfKeyPressed
private void regBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_regBtnActionPerformed
if(con != null){
try {
if(con.isClosed()){
con=CsvDBConnection.CsvDBConnection();
}
else{
con.close();
con=CsvDBConnection.CsvDBConnection();
}
} catch (SQLException ex) {
Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
con=CsvDBConnection.CsvDBConnection();
}
String sql = "INSERT INTO `user` (`user_name`, `user_password`) VALUES (?,?) ";
try{
prep=con.prepareStatement(sql);
prep.setString(1, usernameTf.getText());
prep.setString(2, passwordTf.getText());
prep.execute();
JOptionPane.showMessageDialog(null, "Account created");
prep.close();
con.close();
this.dispose();
LoginGUI logGui = new LoginGUI();
logGui.setVisible(true);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Registeration failed " + e);
}
}//GEN-LAST:event_regBtnActionPerformed
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
this.dispose();
LoginGUI logGui = new LoginGUI();
logGui.setVisible(true);
}//GEN-LAST:event_backBtnActionPerformed
private void regBtnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_regBtnMouseEntered
regBtn.setBackground(new Color(51,153,255));
}//GEN-LAST:event_regBtnMouseEntered
private void regBtnMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_regBtnMouseExited
regBtn.setBackground(new Color(8,118,188));
}//GEN-LAST:event_regBtnMouseExited
private void backBtnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backBtnMouseEntered
backBtn.setBackground(new Color(51,153,255));
}//GEN-LAST:event_backBtnMouseEntered
private void backBtnMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backBtnMouseExited
backBtn.setBackground(new Color(8,118,188));
}//GEN-LAST:event_backBtnMouseExited
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RegisterGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPasswordField passwordTf;
private javax.swing.JButton regBtn;
private javax.swing.JTextField usernameTf;
// End of variables declaration//GEN-END:variables
}
| true
|
f9e4be2a71c2abb40a4984febf20218f88272bfd
|
Java
|
Qianfugen/ctms
|
/manage/src/main/java/com/zl/pojo/UsualColl.java
|
UTF-8
| 448
| 1.757813
| 2
|
[] |
no_license
|
package com.zl.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* @author junqi
* 常用收款人
*/
public class UsualColl implements Serializable {
/**
* 自己账号
*/
private String mainAcc;
/**
* 收款人账号
*/
private String accIn;
/**
* 收款人用户名
*/
private String accInName;
/**
* 收款金额
*/
private BigDecimal transFund;
}
| true
|
b678a215e2778f3472b55dc61ee263ac7681ca7d
|
Java
|
Valentin-04/Qase
|
/src/test/java/tests/AuthorizationTest.java
|
UTF-8
| 227
| 1.828125
| 2
|
[] |
no_license
|
package tests;
import org.testng.annotations.Test;
public class AuthorizationTest extends BaseTest {
@Test(description = "User authorization")
public void login() {
loginSteps.login(EMAIL, PASSWORD);
}
}
| true
|
41b999b75a9c9169e8f31ae133c8ff85b433257a
|
Java
|
zhanghuijun1988/WikiPageReader
|
/src/main/Reader.java
|
UTF-8
| 4,350
| 3.328125
| 3
|
[] |
no_license
|
package main;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/*
* Author: Huijun Zhang
* This WikiReader project is sending 100 GET requests to wikipedia main page with 100 threads and calculate response time
*/
public class Reader {
private final static int DEFAULT_NUM_REQUESTS = 100;
private final static String URL = "https://en.wikipedia.org/wiki/Main_Page";
public static void main(String[] args) throws Exception {
System.out.println("Welcome to WikiReader, this service will send GET requests simultaneously to " + URL);
int num_requests = DEFAULT_NUM_REQUESTS;
List<Long> respTimeList = new ArrayList<>();
WikiReadTask task = new WikiReadTask();
boolean printLog = false;
// get number of requests from user input
num_requests = getUserInputNumRequests();
printLog = getUserInputPrintLog();
// start sending requests
for (int i = 0; i < num_requests; i++) {
final int j = i;
final boolean print = printLog;
// create one thread for each request, so that threads won't wait for other threads
Thread t = new Thread() {
@Override
public void run() {
task.doGet(j, print);
long time;
try {
time = task.getTimeTaken();
respTimeList.add(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
t.join(); // make sure all threads finish
}
// calculate and print results
calculatePrintResult(respTimeList, num_requests);
}
private static int getUserInputNumRequests() {
int num_requests = DEFAULT_NUM_REQUESTS;
try {
Scanner scanner = new Scanner(System.in);
int input_number;
do {
System.out.println("How many requests do you want to send? Please enter a number from 1 - 100");
while (!scanner.hasNextInt()) {
System.out.println("That's not valid number!");
scanner.next();
}
input_number = scanner.nextInt();
} while (input_number < 1 || input_number > 100);
System.out.println("Thank you! Got number " + input_number);
num_requests = input_number;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return num_requests;
}
private static boolean getUserInputPrintLog() {
boolean print = false;
try {
Scanner scanner = new Scanner(System.in);
String input;
do {
System.out.println("Do you want to print response page content? Please enter Y/N");
input = scanner.nextLine();
input = input.trim().toUpperCase();
} while (!input.equals("Y") && !input.equals("N"));
System.out.println("Thank you! Got input " + input);
if(input.equals("Y")) {
print = true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return print;
}
private static void calculatePrintResult(List<Long> respTimeList, int num_requests) {
if(respTimeList == null || respTimeList.size() == 0 || num_requests == 0) return;
// sort result collection
Collections.sort(respTimeList);
// calculate results: mean and average
long totalTime = 0l;
for(long t : respTimeList) {
totalTime += t;
}
double mean = 0;
if(num_requests % 2 == 0) {
mean = (respTimeList.get(num_requests / 2 - 1) + respTimeList.get(num_requests / 2)) / 2.0;
} else {
mean = respTimeList.get(num_requests / 2);
}
double avg = totalTime / num_requests;
// standard deviation
double stdSum = 0;
for(int i = 0; i < respTimeList.size(); i++) {
double cur = Math.pow(respTimeList.get(i) - avg, 2);
stdSum += cur;
}
stdSum = Math.sqrt(stdSum);
// print results
System.out.println("Start printing results in milliseconds:");
System.out.println("10%: " + respTimeList.get((int)(num_requests / 100.0 * 10)));
System.out.println("50%: " + respTimeList.get((int)(num_requests / 100.0 * 50)));
System.out.println("90%: " + respTimeList.get((int)(num_requests / 100.0 * 90)));
System.out.println("95%: " + respTimeList.get((int)(num_requests / 100.0 * 95)));
System.out.println("99%: " + respTimeList.get((int)(num_requests / 100.0 * 99)));
System.out.println("Average: " + avg);
System.out.println("Mean: " + mean);
System.out.println("Standard Deviation: " + stdSum);
System.out.println("Thank you for using WikiReader, have a nice day!");
}
}
| true
|
ac2540148ad5de720d9cb264a8c99b53bdf5fff1
|
Java
|
jdufner/gudoku
|
/gudoku/src/net/sf/gudoku/client/dto/Sudoku.java
|
ISO-8859-1
| 3,773
| 2.609375
| 3
|
[] |
no_license
|
// $Id: Sudoku.java,v 1.7 2009/11/11 23:11:22 jdufner Exp $
/*
* Gudoku (http://sourceforge.net/projects/gudoku)
* Sudoku-Implementierung auf Basis des Google Webtoolkit
* (http://code.google.com/webtoolkit/). Die Lsungsalgorithmen in Java laufen
* parallel. Die Sudoku-Rtsel werden mittels JDBC in einer Datenbank
* gespeichert.
*
* Copyright (C) 2008 Jrgen Dufner
*
* Dieses Programm ist freie Software. Sie knnen es unter den Bedingungen der
* GNU General Public License, wie von der Free Software Foundation
* verffentlicht, weitergeben und/oder modifizieren, entweder gem Version 3
* der Lizenz oder (nach Ihrer Option) jeder spteren Version.
*
* Die Verffentlichung dieses Programms erfolgt in der Hoffnung, da es Ihnen
* von Nutzen sein wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die
* implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FR EINEN
* BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License.
*
* Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Falls nicht, siehe <http://www.gnu.org/licenses/>.
*
*/
package net.sf.gudoku.client.dto;
import java.io.Serializable;
import java.util.List;
/**
* @author <a href="mailto:juergen@jdufner.de">Jürgen Dufner</a>
* @since 0.1
* @version $Revision: 1.7 $
*/
public class Sudoku extends Observable implements Serializable {
private static final long serialVersionUID = 1L;
private SudokuSize size;
private List<Cell> cells;
private int numberOfFixed;
public SudokuSize getSize() {
return size;
}
public void setSize(SudokuSize size) {
this.size = size;
}
public List<Cell> getCells() {
return cells;
}
public void setCells(List<Cell> cells) {
this.cells = cells;
}
public void setCell(Cell cell) {
// Fge Zelle in Modell ein
int rowInt = Cell.mapClientRow2ServerRow(cell.getRow());
int columnInt = Cell.mapClientColumn2ServerColumn(cell.getColumn());
int index = rowInt * getSize().getUnitSize() + columnInt;
cells.set(index, cell);
// Fhre nderungen an View aus
notifyObservers(cell);
}
public Cell getCell(int row, int column) {
int cellNumber = row * size.getUnitSize() + column;
return (Cell) cells.get(cellNumber);
}
public int getNumberOfFixed() {
return numberOfFixed;
}
public void setNumberOfFixed(int numberOfFixed) {
this.numberOfFixed = numberOfFixed;
}
public int getRowChecksum(int row) {
int checksum = 0;
for (int i = 0; i < size.getUnitSize(); i++) {
if (getCell(row, i).isFixed()) {
checksum += getCell(row, i).getFixed();
}
}
return checksum;
}
public int getColumnChecksum(int column) {
int checksum = 0;
for (int i = 0; i < size.getUnitSize(); i++) {
if (getCell(i, column).isFixed()) {
checksum += getCell(i, column).getFixed();
}
}
return checksum;
}
public String toString() {
return size.toString() + ":" + cells.toString();
}
}
/*
* $Log: Sudoku.java,v $
* Revision 1.7 2009/11/11 23:11:22 jdufner
* Migration to GWT 1.7
* Revision 1.6 2008/06/06 21:07:43 jdufner Default-SerialUID eingebaut
*
* Revision 1.5 2008/05/16 13:55:55 jdufner kleines Namensrefactoring
*
* Revision 1.4 2008/05/16 13:24:39 jdufner Zeige Spiel-ID und Anzahl der gesetzten Felder, kleine Namensrefactorings
*
* Revision 1.3 2008/05/15 21:40:20 jdufner toString-Methode implementiert Revision 1.2 2008/05/09 22:48:46 jdufner
* Javadoc Version-Tag auf CVS keyword Revision gesetzt Revision 1.1.1.1 2008/05/09 20:34:09 jdufner Initial Check-In
*/
| true
|
6fb03d0840695c3c748219f8654477777b29fabd
|
Java
|
parieses/studyJava
|
/src/secondLearning/ArrayListTest.java
|
UTF-8
| 959
| 3.453125
| 3
|
[] |
no_license
|
package secondLearning;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
//jdk1.7开始右侧的尖括号内部可以不写内容
ArrayList<String> arrayList = new ArrayList<>();
System.out.println(arrayList);//[]
arrayList.add("抢完");
System.out.println(arrayList);
System.out.println(arrayList.get(0));
arrayList.remove(0);
System.out.println(arrayList.size());
arrayList.clear();
arrayList.add("打的");
arrayList.add("打的1");
arrayList.add("打2的");
arrayList.add("打3的");
for (String name : arrayList) {
System.out.println(name);
}
//集合存基本类型
ArrayList<Integer> numArr = new ArrayList<>();
ArrayList<Character> charArr = new ArrayList<>();
ArrayList<Byte> b = new ArrayList<>();
}
}
| true
|
b0b7f240f3ebb6b989e4512d223a9376730ca110
|
Java
|
jacsme/APIRepository
|
/WOMAPIRest/src/main/java/com/wom/api/services/LoginService.java
|
UTF-8
| 562
| 1.773438
| 2
|
[] |
no_license
|
package com.wom.api.services;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jettison.json.JSONArray;
public interface LoginService {
public JSONArray getAppVersion() throws Exception;
public JSONArray getLoginUser(String userId, String password, String app) throws Exception;
public JSONArray getStaffInfo(String userId) throws Exception;
public JSONArray submitForgotPassword(HttpServletRequest request, HttpServletResponse response, String emailaddress, String app) throws Exception;
}
| true
|
03ef934adf3558ef2a915fe2a64f6b49e5d06264
|
Java
|
tangtian8/JAVA-000
|
/Week_05/helloword-springbean/src/main/java/top/tangtian/springbean/springbean06/Role6_3.java
|
UTF-8
| 431
| 2.046875
| 2
|
[] |
no_license
|
package top.tangtian.springbean.springbean06;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author tangtian
* @version 1.0
* @className Role6_3
* @description
* @date 2020/11/16 8:53 AM
**/
public class Role6_3 {
private static final Logger LOG = LoggerFactory.getLogger(Role6_3.class);
private User6_1 user6_1;
public void setUser6_1(User6_1 user6_1){
this.user6_1 = user6_1;
}
}
| true
|
c446fe4012c6f27972e2c27f86f7e0219830067e
|
Java
|
SaiquaAslam/FinalSprint2
|
/src/main/java/com/cg/main/exception/PlantNotFoundException.java
|
UTF-8
| 306
| 2
| 2
|
[] |
no_license
|
package com.cg.main.exception;
/**
* @author Saiqua Aslam
*
*/
//customise exception class
public class PlantNotFoundException extends RuntimeException {
public PlantNotFoundException() {
// TODO Auto-generated constructor stub
}
public PlantNotFoundException(String message) {
super(message);
}
}
| true
|
bbf04c39850c2021dca32ee7b405b4ca63027e00
|
Java
|
hxt532084126/Project-first
|
/little-codes4/src/cn/itcast/login/filter/UserFilter.java
|
UTF-8
| 2,666
| 2.5625
| 3
|
[] |
no_license
|
package cn.itcast.login.filter;
import java.io.IOException;
import java.util.ResourceBundle;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.login.bean.User;
import cn.itcast.login.exception.MyException;
public class UserFilter implements Filter {
// 这四个值意思是从admin,User两个properties文件中读取的字符串
// 并将这两对字符串打成字符数组
private String userString;
private String adminString;
private String[] userStrings;
private String[] adminStrings;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
// 获取三个路径
// 获取项目全路径(/day1/1.jsp)
String uri;
// 获取项目虚拟路径(/day1)
String contextPath;
// 获取项目虚拟路径以后的路径(/1.jsp)
String path;
uri = request.getRequestURI();
contextPath = request.getContextPath();
path = uri.substring(contextPath.length());
User user = (User) request.getSession().getAttribute("user");
// 循环遍历字符串数组,然后逐一比对,如若地址值比对成功,那么就继续操作
for (String aString : adminStrings) {
if (path.endsWith(aString)) {
if (user != null) {
String role = user.getRole();
if (!role.equals("admin")) {
throw new MyException("you are not an admin");
}
} else {
throw new MyException("you are not an admin");
}
}
}
// 循环遍历字符串数组,然后逐一比对,如若地址值比对成功,那么就继续操作
for (String uString : userStrings) {
if (path.endsWith(uString)) {
if (user != null) {
String role = user.getRole();
if (!role.equals("user")) {
throw new MyException("you are a not user");
}
} else {
throw new MyException("you are a not user");
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
adminString = ResourceBundle.getBundle("admin").getString("url");
userString = ResourceBundle.getBundle("User").getString("url");
adminStrings = adminString.split(",");
userStrings = userString.split(",");
}
}
| true
|
38ad3d8a018aaf1ed9523482a49a6b29e9b41691
|
Java
|
IbraLM/public_transport
|
/tst/TestPosition.java
|
UTF-8
| 1,528
| 2.515625
| 3
|
[] |
no_license
|
package tec;
class TestPosition{
public void testPassagerDehorsl(){
Position posDehors = Position.dehors();
assert posDehors.estDehors()==true : "Test de estDehors avec passager dehors, attend vrai\n";
assert posDehors.estInterieur()==false : "Test de estInterieur avec passager dehors, attend faux\n";
assert posDehors.estDebout()==false : "Test de estDebout avec passager dehors, attend faux\n";
assert posDehors.estAssis()==false : "Test of estAssis avec passager dehors, attend faux\n";
}
public void testPassagerAssis(){
Position posAssis = Position.dehors();
posAssis = posAssis.assis();
assert posAssis.estAssis() == true : "Test de estAssis avec passager assis, attend vrai\n";
assert posAssis.estInterieur()==true : "Test de estInterieur avec passager assis, attend vrai\n";
assert posAssis.estDebout() == false : "Test de estDebout avec passager assis, attend faux\n";
assert posAssis.estDehors()==false : "Test de estDehors avec passager assis, attend faux\n";
}
public void testPassagerDebout(){
Position posDebout = Position.dehors();
posDebout = posDebout.debout();
assert posDebout.estDebout() == true : "Test de estDebout avec passager debout, attend vrai\n";
assert posDebout.estInterieur()==true : "Test de estInterieur avec passager debout, attend vrai\n";
assert posDebout.estAssis() == false : "Test de estAssis avec passager debout, attend faux\n";
assert posDebout.estDehors()==false : "Test de estDehors avec passager debout, attend faux\n";
}
}
| true
|
71df6d252f9f0d9a975848b758c95ba29056a988
|
Java
|
ishimweChris/stock
|
/src/main/java/com/invetory/stock/controller/CashierController.java
|
UTF-8
| 553
| 1.890625
| 2
|
[] |
no_license
|
package com.invetory.stock.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.invetory.stock.service.CashierService;
@Controller
@RequestMapping("cashier")
public class CashierController {
private CashierService cashierservice;
public String AllCashier(HttpSession session, ModelMap model) {
model.addAttribute("cashier", cashierservice.findAll());
return "cashier";
}
}
| true
|
d770b46f7fd19c728747adf886ee8b0ef9b8467f
|
Java
|
sivanaya/JAVA-airplane
|
/TicketsSales.java
|
UTF-8
| 1,079
| 2.984375
| 3
|
[] |
no_license
|
public class TicketsSales {
protected String FlightNumber;
protected int SoldTo;
protected int numberOfTickets;
public TicketsSales( String FlightNumber, int SoldTo , int numberOfTickets){
this.FlightNumber = FlightNumber;
this.SoldTo = SoldTo;
this.numberOfTickets = numberOfTickets;
} // Constructor
public int getSoldTo() {
return SoldTo;
}
public int getNumberOfTickets(){
return numberOfTickets;
}
public String getFlightNumber() {
return FlightNumber;
}
public int getSoldBy() {
return getSoldBy();
}
public static TicketsSales kindOfSales(String FlightNumber ,int SoldTo, int SoldBy,int numberOfTickets ,String Site){
//Check Which kind of Sale.
if(SoldBy==0){
TicketsSales t= new OnlineSale(FlightNumber ,SoldTo, numberOfTickets , Site);
return t;
}
else {
TicketsSales t= new MarketingSale(FlightNumber ,SoldTo, numberOfTickets , SoldBy);
return t;
}
}
}
| true
|
e48bd94d29b1ed03a0be6f7ed2c368893c681016
|
Java
|
leapframework/framework
|
/base/core/src/main/java/leap/core/i18n/AbstractMessageReader.java
|
UTF-8
| 1,213
| 1.664063
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 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 leap.core.i18n;
import leap.core.annotation.Inject;
import leap.core.el.EL;
import leap.core.el.ExpressionLanguage;
import leap.lang.logging.Log;
import leap.lang.logging.LogFactory;
import java.util.Locale;
public abstract class AbstractMessageReader implements MessageReader {
protected final Log log = LogFactory.get(this.getClass());
protected @Inject ExpressionLanguage el;
protected final Message createMessage(Object source, Locale locale, String string) {
return new Message(source, locale, EL.createCompositeExpression(el, string));
}
}
| true
|
89b2d175aeaba5706e69fc15ca9933c39e26d79f
|
Java
|
franqlin/product_image
|
/src/main/java/com/anhtran/productimage/resource/impl/ImageResourceImpl.java
|
UTF-8
| 1,957
| 2.0625
| 2
|
[] |
no_license
|
/*
* This work is free software; you can redistribute it and/or
* modify it under the terms of the Apache License as published
* by the Apache Software Foundation.
*
* This work is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache License for more details.
*
* Copyright (c) 2015 Anh Tran (tranhoanganh89@gmail.com).
* All rights reserved.
*/
package com.anhtran.productimage.resource.impl;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import com.anhtran.productimage.model.Image;
import com.anhtran.productimage.model.Product;
import com.anhtran.productimage.resource.ImageResource;
import com.anhtran.productimage.service.ImageService;
import com.anhtran.productimage.service.ProductService;
public class ImageResourceImpl implements ImageResource {
@Autowired
private ImageService imageService;
@Autowired
private ProductService productService;
public Image createImage(long productId, String type, String location) {
Image image = new Image();
Product product = productService.getProductFromId(productId);
image.setProduct(product);
image.setType(type);
image.setLocation(location);
return imageService.createImage(image);
}
public Image getImageFromId(long imageId) {
return imageService.getImageFromId(imageId);
}
public Image updateImage(long imageId, long productId, String type, String location) {
Image image = imageService.getImageFromId(imageId);
Product product = productService.getProductFromId(productId);
image.setProduct(product);
image.setType(type);
image.setLocation(location);
return imageService.updateImage(image);
}
public Response deleteImage(long imageId) {
Image image = imageService.getImageFromId(imageId);
imageService.deleteImage(image);
return Response.status(200).entity("").build();
}
}
| true
|
953b1f95043e7d95fbadc8e56f872becc4826562
|
Java
|
amitmnnit91/ChatApplication
|
/src/main/java/com/my/chatapp/WebSocketEventListener.java
|
UTF-8
| 750
| 2.03125
| 2
|
[] |
no_license
|
package com.my.chatapp;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
@Component
public class WebSocketEventListener {
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
System.out.println("Disconnecting user ...");
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
String username = (String) headerAccessor.getSessionAttributes().get("username");
if(username != null) {
CacheManager.deactivateUser(username);
}
}
}
| true
|
cf0dc9e59ff6f3e3dc5247c4bf22b27f60a94e1a
|
Java
|
astghikhay/newsolearn
|
/app/src/main/java/com/astghik/newsolearn/models/Result.java
|
UTF-8
| 1,637
| 2.296875
| 2
|
[] |
no_license
|
package com.astghik.newsolearn.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class Result implements Parcelable, Serializable {
@Expose
@SerializedName("status")
private String status;
@Expose
@SerializedName("total")
private int total;
@Expose
@SerializedName("results")
private List<NewsModel> newsList;
protected Result(Parcel in) {
status = in.readString();
total = in.readInt();
newsList = in.readArrayList(ClassLoader.getSystemClassLoader());
}
public int getTotal() {
return total;
}
public String getStatus() {
return status;
}
public List<NewsModel> getNewsList() {
return newsList;
}
public void setNewsList(List<NewsModel> newsList) {
this.newsList = newsList;
}
public void setStatus(String status) {
this.status = status;
}
public static final Creator<Result> CREATOR = new Creator<Result>() {
@Override
public Result createFromParcel(Parcel in) {
return new Result(in);
}
@Override
public Result[] newArray(int size) {
return new Result[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(status);
parcel.writeInt(total);
parcel.writeTypedList(newsList);
}
}
| true
|
763d103d361d66a2d9ff6ee8968705379a5ccc61
|
Java
|
Dazhi528/ZxingScan
|
/scan/src/main/java/com/dazhi/scan/decoding/DecodeFormatManager.java
|
UTF-8
| 1,266
| 2.15625
| 2
|
[] |
no_license
|
package com.dazhi.scan.decoding;
import com.google.zxing.BarcodeFormat;
import java.util.Vector;
public class DecodeFormatManager {
private DecodeFormatManager() { }
//
private static final Vector<BarcodeFormat> PRODUCT_FORMATS;
public static final Vector<BarcodeFormat> ONE_D_FORMATS;
public static final Vector<BarcodeFormat> QR_CODE_FORMATS;
public static final Vector<BarcodeFormat> DATA_MATRIX_FORMATS;
static {
PRODUCT_FORMATS = new Vector<>(5);
PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
// PRODUCT_FORMATS.add(BarcodeFormat.RSS14);
ONE_D_FORMATS = new Vector<>(PRODUCT_FORMATS.size() + 4);
ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
ONE_D_FORMATS.add(BarcodeFormat.CODE_93);
ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
ONE_D_FORMATS.add(BarcodeFormat.ITF);
QR_CODE_FORMATS = new Vector<>(1);
QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
DATA_MATRIX_FORMATS = new Vector<>(1);
DATA_MATRIX_FORMATS.add(BarcodeFormat.DATA_MATRIX);
}
}
| true
|
b944dd8a33061b8ea2ac3f2e9fbcabcfba3bd635
|
Java
|
Vyacheslav1024/LoveThisWorkQAAutomation
|
/src/test/java/lesson5/TestServer.java
|
UTF-8
| 1,840
| 3.328125
| 3
|
[] |
no_license
|
package test.java.lesson5;
import main.java.lesson5.app.Server;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class TestServer {
public static void beforeMethod() {
}
@Test
public void getUsersShouldReturnProperAmount() {
Server server = new Server();
String usersNames = server.getUsers(); // "Vova, Petya"
int actualUsersAmount = usersNames.split(", ").length;
int expectedUsersAmount = 2;
//actualUsersAmount == expectedUsersAmount; мы проверяем это равенство
assertEquals( // проверь на соответствие actual реальное значение и expected ожидаемое значение
actualUsersAmount,
expectedUsersAmount,
"Expected amount of users to be " + expectedUsersAmount + " but got " + actualUsersAmount
);
}
@Test
public void getUsersShouldReturnAllNamesInUpperCase() {
Server server = new Server();
String[] usersNames = server.getUsers().split(", "); // {"Vova, Petya"}
for (String name : usersNames) {
String actualFirstChar = String.valueOf(name.charAt(0)); //v toLowerCase меняет заглавную букву на прописную
String expectedFirstChar = String.valueOf(name.charAt(0)).toUpperCase(); // v => V
// boolean isEqual = actualFirstChar.equals(expectedFirstChar);
// assertTrue(isEqual); можно просто вставить
assertTrue(
actualFirstChar.equals(expectedFirstChar),
"Expected fist char " + actualFirstChar + " in name " + name + " to be upper case."
);
}
}
}
| true
|
e39a97113110cc4ad139591dc84fecebbf283a02
|
Java
|
condenl/inspt-guarderiac-backend
|
/guarderia-caracol/src/main/java/com/inspt/guarderiacaracol/dto/PhotoDTO.java
|
UTF-8
| 757
| 2.46875
| 2
|
[] |
no_license
|
package com.inspt.guarderiacaracol.dto;
import org.springframework.web.multipart.MultipartFile;
import com.inspt.guarderiacaracol.domain.Photo;
/**
* It never holds both the id and the file data,
* when uploading a new photo the file will be set but not the id,
* when getting the image the id will be set but not the file.
*
*/
public class PhotoDTO {
private Long id;
private MultipartFile file;
public PhotoDTO() { }
public PhotoDTO(Photo photo) {
this.id = photo.getId();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
| true
|
95ce86a5e55fbd9a27967986529455b4799a7ae2
|
Java
|
orf1888/Subiekt
|
/src/main/java/widok/abstrakt/PanelEdytujDodajObiekt.java
|
UTF-8
| 433
| 2.015625
| 2
|
[] |
no_license
|
package widok.abstrakt;
import javax.swing.JDialog;
import javax.swing.JPanel;
import model.ObiektZId;
public abstract class PanelEdytujDodajObiekt extends JPanel
{
private static final long serialVersionUID = 2635368817417751702L;
public abstract void uzupelnijFormatke(Object obiekt, JDialog parent);
public abstract ObiektZId pobierzZFormatki(int id) throws Exception;
public abstract void czysc();
}
| true
|
f1f74abcee8a8f2b11533e6d48b8c4935a697cb7
|
Java
|
tomasfelder/PatronesGOF
|
/EjerciciosPatrones/comportamiento/visitor/ProductoNormal.java
|
UTF-8
| 479
| 3.1875
| 3
|
[] |
no_license
|
package visitor;
public class ProductoNormal implements Visitable {
private double precio;
public ProductoNormal(double precio){
this.setPrecio(precio);
}
@Override
public double aceptar(Visitor v) {
// TODO Auto-generated method stub
return v.visitar(this);
}
/**
* @return the precio
*/
public double getPrecio() {
return precio;
}
/**
* @param precio the precio to set
*/
public void setPrecio(double precio) {
this.precio = precio;
}
}
| true
|
fa3d48988b396138116ce46b8984d3c030b47ca6
|
Java
|
xrewndel/nkt
|
/GAStarter/src/gastarter/ParamsParser.java
|
UTF-8
| 12,293
| 2.5
| 2
|
[] |
no_license
|
package gastarter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
/**
* @author Andrew
GA:
-cfg config (ga3.cfg)
-c crossover (0 - no, 1 - yes)
-m mutation (0 - no, 1 - yes)
-p population size
-g generations
-f work files
GAStarter:
-r repeat
-cb crossover begin(start)
-cs crossover step
-ce crossover end
-mb mutation begin(start)
-ms mutation step
-me mutation end
-frb mutation free rate begin
-frs mutation free rate step
-fre mutation free rate end
-wrb mutation waste rate begin
-wrs mutation waste rate step
-wre mutation waste rate end
-t test (1 or 0). If test - just print task
*/
public class ParamsParser {
// по умолчанию все отключено
public int cpu = Runtime.getRuntime().availableProcessors() - 2;
public static String begin = "java -jar GA.jar -o 0"; // -o 0 = no print to console extra data
public final String cfgDefault = "ga3.cfg";
public String cfg = "ga3.cfg";
public int crossover = 0;
public int mutation = 0;
public int population = 50;
public int generation = 1000;
public int files = 300;
public int repeat = 3;
public int limit = 100;
public int crossBegin = 0;
public int crossStep = 1;
public int crossEnd = 0;
public int mutateBegin = 0;
public int mutateStep = 1;
public int mutateEnd = 0;
public int frb = 0;
public int frs = 0;
public int fre = 0;
public int wrb = 0;
public int wrs = 0;
public int wre = 0;
public boolean test = false;
public ParamsParser (String[] args) {
File cfgFile = new File(args[0]);
Config config = null;
try {
config = new Config(cfgFile.getAbsolutePath());
//config.printPropertyList();
} catch (Exception ex) {
System.out.print("Config file not found: " + ex.getLocalizedMessage() + "\n");
throw new RuntimeException("Specify config file. ");
}
//System.out.println(config.asMap());
//if (args.length % 2 > 0) throw new RuntimeException("Every param must has its value");
/*
for (int param = 0; param < args.length; param++) {
CMD cmd = CMD.fromString(args[param]);
String val = "";
try { val = args[param + 1]; } catch (Exception ex) {}
switch(cmd) {
case h: help(); break;
case cfg: cfg = val; break;
case c: crossover = Integer.valueOf(val); break;
case m: mutation = Integer.valueOf(val); break;
case f: files = Integer.valueOf(val); break;
case p: population = Integer.valueOf(val); break;
case g: generation = Integer.valueOf(val); break;
case l: limit = Integer.valueOf(val); break;
case r: repeat = Integer.valueOf(val); break;
case cb: crossBegin = Integer.valueOf(val); break;
case cs: crossStep = Integer.valueOf(val); break;
case ce: crossEnd = Integer.valueOf(val); break;
case mb: mutateBegin = Integer.valueOf(val); break;
case ms: mutateStep = Integer.valueOf(val); break;
case me: mutateEnd = Integer.valueOf(val); break;
case frb: frb = Integer.valueOf(val); break;
case frs: frs = Integer.valueOf(val); break;
case fre: fre = Integer.valueOf(val); break;
case wrb: wrb = Integer.valueOf(val); break;
case wrs: wrs = Integer.valueOf(val); break;
case wre: wre = Integer.valueOf(val); break;
case wr: wrb = frb; wrs = frs; wre = fre; break; // копируем интервал
case t: test = val.equals("1"); break;
case cpu: cpu = Integer.valueOf(val); break;
default: {
System.out.println("Paramter \"" + args[param] + "\" is unknown");
System.exit(1);
}
}
param++;
}
*/
Map<String, String> paramsMap = config.asMap();
for (String param : paramsMap.keySet()) {
switch(param) {
case "cfg": cfg = paramsMap.get(param);
case "crossover": crossover = Integer.valueOf(paramsMap.get(param)); break;
case "mutation": mutation = Integer.valueOf(paramsMap.get(param)); break;
case "files": files = Integer.valueOf(paramsMap.get(param)); break;
case "population": population = Integer.valueOf(paramsMap.get(param)); break;
case "generation": generation = Integer.valueOf(paramsMap.get(param)); break;
case "limit": limit = Integer.valueOf(paramsMap.get(param)); break;
case "repeat": repeat = Integer.valueOf(paramsMap.get(param)); break;
case "crossBegin": crossBegin = Integer.valueOf(paramsMap.get(param)); break;
case "crossStep": crossStep = Integer.valueOf(paramsMap.get(param)); break;
case "crossEnd": crossEnd = Integer.valueOf(paramsMap.get(param)); break;
case "mutateBegin": mutateBegin = Integer.valueOf(paramsMap.get(param)); break;
case "mutateStep": mutateStep = Integer.valueOf(paramsMap.get(param)); break;
case "mutateEnd": mutateEnd = Integer.valueOf(paramsMap.get(param)); break;
case "frb": frb = Integer.valueOf(paramsMap.get(param)); break;
case "frs": frs = Integer.valueOf(paramsMap.get(param)); break;
case "fre": fre = Integer.valueOf(paramsMap.get(param)); break;
case "wrb": wrb = Integer.valueOf(paramsMap.get(param)); break;
case "wrs": wrs = Integer.valueOf(paramsMap.get(param)); break;
case "wre": wre = Integer.valueOf(paramsMap.get(param)); break;
case "wr": wrb = frb; wrs = frs; wre = fre; break; // копируем интервал
case "test": test = Boolean.valueOf(paramsMap.get(param)); break;
case "cpu": cpu = Integer.valueOf(paramsMap.get(param)); break;
default: {
System.out.println("Paramter \"" + param + "\" is unknown");
System.exit(1);
}
}
}
validate();
}
public boolean crossover() { return crossover == 1 && mutation == 0; }
public boolean mutation() { return crossover == 0 && mutation == 1; }
public boolean crossAndMutate() { return crossover == 1 && mutation == 1; }
public boolean fr() { return frb > 0 && fre > 0; }
public boolean wr() { return wrb > 0 && wre > 0; }
public boolean cross() { return crossBegin > 0 && crossEnd > 0; }
public boolean mutate() { return mutateBegin > 0 && mutateEnd > 0; }
public String fixed() {
StringBuilder sb = new StringBuilder();
sb.append(begin);
if (!cfg.equals(cfgDefault)) sb.append(CMD.cfg.cmd(cfg));
sb.append(CMD.c.cmd(crossover));
sb.append(CMD.m.cmd(mutation));
sb.append(CMD.l.cmd(limit));
if (mutateBegin == mutateEnd) sb.append(CMD.mp.cmd(mutateBegin));
return sb.toString();
}
private void validate() {
if (files < 0) throw new RuntimeException(CMD.f.param() + " < 0");
if (population < 0) throw new RuntimeException(CMD.p.param() + " < 0");
if (generation < 0) throw new RuntimeException(CMD.g.param() + " < 0");
if (repeat < 0) throw new RuntimeException(CMD.r.param() + " < 0");
if (crossBegin < 0) throw new RuntimeException(CMD.cb.param() + " < 0");
if (crossStep < 0) throw new RuntimeException(CMD.cs.param() + " < 0");
if (crossEnd < 0) throw new RuntimeException(CMD.ce.param() + " < 0");
if (crossEnd < crossBegin) throw new RuntimeException(CMD.ce.param() + " < " + CMD.cb.param());
if (crossBegin > 0 && crossEnd > 0) crossover = 1;
if (mutateBegin < 0) throw new RuntimeException(CMD.mb.param() + " < 0");
if (mutateStep < 0) throw new RuntimeException(CMD.ms.param() + " < 0");
if (mutateEnd < 0) throw new RuntimeException(CMD.me.param() + " < 0");
if (mutateEnd < mutateBegin) throw new RuntimeException(CMD.me.param() + " < " + CMD.mb.param());
if (mutateBegin > 0 && mutateEnd > 0) mutation = 1;
if (frb < 0) throw new RuntimeException(CMD.frb.param() + " < 0");
if (frs < 0) throw new RuntimeException(CMD.frs.param() + " < 0");
if (fre < 0) throw new RuntimeException(CMD.fre.param() + " < 0");
if (fre < frb) throw new RuntimeException(CMD.fre.param() + " < " + CMD.frb.param());
if (fre > 0 && fre > 0) mutation = 1;
if (wrb < 0) throw new RuntimeException(CMD.wrb.param() + " < 0");
if (wrs < 0) throw new RuntimeException(CMD.wrs.param() + " < 0");
if (wre < 0) throw new RuntimeException(CMD.wre.param() + " < 0");
if (wre < wrb) throw new RuntimeException(CMD.wre.param() + " < " + CMD.wrb.param());
if (wre > 0 && wre > 0) mutation = 1;
}
public final static void help() {
StringBuilder sb = new StringBuilder();
sb.append(begin).append(CMD.help);
sb.append("\n\tfrb, frs, fre, wrb, wrs, wre are rate but specified in integer like 10, 25");
System.out.println(sb);
}
public enum CMD {
//GA
cfg("-cfg", "\n\t-cfg file.cfg"),
c("-c", "\n\t-c crossover"),
m("-m", "\n\t-m mutation"),
f("-f", "\n\t-f files"),
p("-p", "\n\t-p populatio"),
g("-g", "\n\t-g generations"),
cp("-cp", ""), // crossRate
mp("-mp", ""), // mutateRate
fr("-fr", ""), // freeRate
wr("-wr", ""), // wasteRate
l("-l", "\n\t limit. Track fitness change over n generetion"),
// GA Starter
r("-r", "\n\t-r repeat"),
cb("-cb", "\n\n\t-cb crossover begin(start)"),
cs("-cs", "\n\t-cs crossover step"),
ce("-ce", "\n\t-ce crossover end"),
mb("-mb", "\n\n\t-mb mutation begin(start)"),
ms("-ms", "\n\t-ms mutation step"),
me("-me", "\n\t-me mutation end"),
frb("-frb", "\n\n\t-frb mutation free rate begin"),
frs("-frs", "\n\t-frs mutation free rate step"),
fre("-fre", "\n\t-fre mutation free rate end"),
wrb("-wrb", "\n\n\t-wrb mutation waste rate begin"),
wrs("-wrs", "\n\t-wrs mutation waste rate step"),
wre("-wre", "\n\t-wre mutation waste rate end"),
t("-t", "\n\n\t-t test"),
cpu("-cpu", "\n\t number of cpu"),
h("-h", ""),
undef ("", "");
private final String name;
private final String hlp;
CMD(String n, String h) { name = n; hlp = h; }
private static final Map<String, CMD> params = new HashMap<>();
static { for (CMD parameter : values()) params.put(parameter.name, parameter); }
private static final StringBuilder help = new StringBuilder();
static { for (CMD parameter : values()) help.append(parameter.hlp); }
private static CMD fromString(String name) {
if (params.containsKey(name)) return params.get(name);
else return CMD.undef;
}
//public String hlp() { return hlp; }
public String cmd(String value) { return " " + name + " " + value; }
public String cmd(int value) { return cmd("" + value); }
public String param() { return name; }
}
}
| true
|
e256a0e2f390569aa275b733fd2d3a6a4d7d1c1e
|
Java
|
Kerbaya/locajapa
|
/locajapa/src/main/java/com/kerbaya/locajapa/ValueResolver.java
|
UTF-8
| 2,193
| 2.109375
| 2
|
[] |
no_license
|
/*
* Copyright 2019 Kerbaya Software
*
* This file is part of locajapa.
*
* locajapa is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* locajapa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with locajapa. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kerbaya.locajapa;
import java.util.Iterator;
import java.util.Set;
final class ValueResolver<T, V> implements Resolver<V>
{
private static final long serialVersionUID = 401859217065373792L;
private final EntityHandler<? super T, ?, ? extends V> entityHandler;
private final T localizable;
private final Set<String> candidateLanguageTags;
public ValueResolver(
EntityHandler<? super T, ?, ? extends V> entityHandler,
T localizable,
Set<String> candidateLanguageTags)
{
this.entityHandler = entityHandler;
this.localizable = localizable;
this.candidateLanguageTags = candidateLanguageTags;
}
public static <T, V> V resolve(
EntityHandler<? super T, ?, ? extends V> entityHandler,
T localizable,
Set<String> candidateLanguageTags)
{
Iterator<Localized<V>> iter = LocalizedIterator.create(
entityHandler, localizable);
int matchLanguageLevel = -1;
Localized<V> match = null;
while (iter.hasNext())
{
Localized<V> next = iter.next();
int languageLevel = next.getLanguageLevel();
if ((match == null || languageLevel > matchLanguageLevel)
&& candidateLanguageTags.contains(
next.getLanguageTag()))
{
match = next;
matchLanguageLevel = languageLevel;
}
}
return match == null ? null : match.getValue();
}
@Override
public V get()
{
return resolve(entityHandler, localizable, candidateLanguageTags);
}
}
| true
|
e319a9e7e005718f7a26d37e34fee04174d07fa6
|
Java
|
kiribeam/practices
|
/Practices/src/ThinkingInJava/c18/LargeMappedFiles.java
|
UTF-8
| 521
| 3.109375
| 3
|
[] |
no_license
|
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class LargeMappedFiles{
static int length = 0x8ffffff;
public static void main(String[] args)throws Exception{
MappedByteBuffer out = new RandomAccessFile("test.dat", "rw").getChannel().
map(FileChannel.MapMode.READ_WRITE, 0, length);
for(int i=0; i<length; i++)
out.put((byte) 'x');
System.out.println("Finished writing");
for(int i = length/2; i<length/2 + 6; i++)
System.out.print((char) out.get(i));
}
}
| true
|
d92856c0ddb8a96867aab59b8327066aaee09448
|
Java
|
codingmaster/ProductRecommender3
|
/src/main/java/de/hpi/semrecsys/similarity/ProductSimilarity.java
|
UTF-8
| 1,403
| 2.671875
| 3
|
[] |
no_license
|
package de.hpi.semrecsys.similarity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hpi.semrecsys.model.Product;
import de.hpi.semrecsys.utils.CollectionUtils;
public class ProductSimilarity {
private final Product initialProduct;
private List<AttributeEntityMapping> attributeEntityMapping = new ArrayList<AttributeEntityMapping>();
private Map<Product, Double> similarProducts = new HashMap<Product, Double>();
public ProductSimilarity(Product product) {
this.initialProduct = product;
}
public void addSimilarProduct(Product product, Double value) {
similarProducts.put(product, value);
}
public Map<Product, Double> getSimilarProducts() {
return similarProducts;
}
public Product getInitialProduct() {
return initialProduct;
}
public List<AttributeEntityMapping> getAttributeEntityMappings() {
return attributeEntityMapping;
}
public void addAttributeEntityMapping(AttributeEntityMapping AttributeEntityMapping) {
attributeEntityMapping.add(AttributeEntityMapping);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Base: " + initialProduct + "\n");
Map<Product, Double> sortedMap = CollectionUtils.sortByValueAsc(getSimilarProducts());
builder.append(CollectionUtils.mapToString(sortedMap) + "\n");
return builder.toString();
}
}
| true
|
2b8883a2034e92c65338e2ce6096f79dec283618
|
Java
|
ngochuy200596/Library
|
/src/main/java/com/html5/library/model/Category.java
|
UTF-8
| 378
| 1.976563
| 2
|
[] |
no_license
|
package com.html5.library.model;
import lombok.Data;
import javax.persistence.*;
/**
* Created by NGOCHUY-PC on 12/9/2016.
*/
@Entity
@Table(name="category")
@Data
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long categoryID;
private String categoryName;
private Long parentID;
private String categoryImage;
}
| true
|