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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f3498012976b9be4cf61dcf33431e85b59d0424e
|
Java
|
RyanTech/12306-Android-Decompile
|
/12306/src/com/google/common/collect/PeekingIterator.java
|
UTF-8
| 293
| 2.40625
| 2
|
[] |
no_license
|
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
@GwtCompatible
public abstract interface PeekingIterator<E> extends Iterator<E>
{
public abstract E next();
public abstract E peek();
public abstract void remove();
}
| true
|
e34cef254fcac7fe0684ba303ae5b0f03a430e9d
|
Java
|
rosiiinka/GameOfCodes
|
/src/enums/Grades.java
|
UTF-8
| 740
| 3.046875
| 3
|
[] |
no_license
|
package enums;
public enum Grades {
EXCELLENT(6, 91, 100, 1.0),
VERY_GOOD(5, 76, 90, 0.8),
GOOD(4, 61, 75, 0.6),
PASSABLE(3, 51, 60, 0.3),
FAILURE(2, 0, 50, 0);
private int grade;
private int minRate;
private int maxRate;
private double factor;
Grades(int grade, int minRate, int maxRate, double factor) {
this.grade = grade;
this.minRate = minRate;
this.maxRate = maxRate;
this.factor = factor;
}
public int getGrade() {
return this.grade;
}
public int getMinRate() {
return this.minRate;
}
public int getMaxRate() {
return this.maxRate;
}
public double getFactor() {
return this.factor;
}
}
| true
|
20b2ab5d4c4dbdbc6b4f401aa1cea90aac150307
|
Java
|
deepak1214/CompetitiveCode
|
/Misc/Fibonacci_Search/solution.java
|
UTF-8
| 3,993
| 4.0625
| 4
|
[
"MIT"
] |
permissive
|
/*
Algorithm:
Let the searched element be x.
The idea is to first find the smallest Fibonacci number that is greater than or equal to the length of given array. Let the found Fibonacci number be fib (m’th Fibonacci number). We use (m-2)’th Fibonacci number as the index (If it is a valid index). Let (m-2)’th Fibonacci Number be i, we compare arr[i] with x, if x is same, we return i. Else if x is greater, we recur for subarray after i, else we recur for subarray before i.
Below is the complete algorithm
Let arr[0..n-1] be the input array and element to be searched be x.
Find the smallest Fibonacci Number greater than or equal to n. Let this number be fibM [m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be fibMm1 [(m-1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].
While the array has elements to be inspected:
Compare x with the last element of the range covered by fibMm2
If x matches, return index
Else If x is less than the element, move the three Fibonacci variables two Fibonacci down, indicating elimination of approximately rear two-third of the remaining array.
Else x is greater than the element, move the three Fibonacci variables one Fibonacci down. Reset offset to index. Together these indicate elimination of approximately front one-third of the remaining array.
Since there might be a single element remaining for comparison, check if fibMm1 is 1. If Yes, compare x with that remaining element. If match, return index.
*/
// Java program for Fibonacci Search
import java.util.*;
class Fibonacci
{
// Utility function to find minimum
// of two elements
public static int min(int x, int y)
{ return (x <= y)? x : y; }
/* Returns index of x if present, else returns -1 */
public static int fibMonaccianSearch(int arr[],
int x, int n)
{
/* Initialize fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci No.
int fibMMm1 = 1; // (m-1)'th Fibonacci No.
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest
Fibonacci Number greater than or equal to n */
while (fibM < n)
{
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from front
int offset = -1;
/* while there are elements to be inspected.
Note that we compare arr[fibMm2] with x.
When fibM becomes 1, fibMm2 becomes 0 */
while (fibM > 1)
{
// Check if fibMm2 is a valid location
int i = min(offset+fibMMm2, n-1);
/* If x is greater than the value at
index fibMm2, cut the subarray array
from offset to i */
if (arr[i] < x)
{
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is less than the value at index
fibMm2, cut the subarray after i+1 */
else if (arr[i] > x)
{
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* element found. return index */
else return i;
}
/* comparing the last element with x */
if(fibMMm1 == 1 && arr[offset+1] == x)
return offset+1;
/*element not found. return -1 */
return -1;
}
// driver code
public static void main(String[] args)
{
int arr[] = {10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100};
int n = 11;
int x = 85;
System.out.print ("Found at index: "+
fibMonaccianSearch(arr, x, n));
}
}
| true
|
cccf6d5e3743796fed917843081b0e7655f85e0c
|
Java
|
Justin002/Android
|
/ep2p-app/ep2p_app/src/com/beyondsoft/ep2p/utils/BlurBitmapDisplayer.java
|
UTF-8
| 4,922
| 2.171875
| 2
|
[] |
no_license
|
package com.beyondsoft.ep2p.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
import com.nostra13.universalimageloader.core.assist.LoadedFrom;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
public class BlurBitmapDisplayer implements BitmapDisplayer {
protected final int radius;
protected Context context;
public BlurBitmapDisplayer(Context context,int radius) {
this(radius,context,0);
}
public BlurBitmapDisplayer(int radius,Context context,int marginPixels) {
this.radius = radius;
this.context=context;
}
@Override
public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {
if (!(imageAware instanceof ImageViewAware)) {
throw new IllegalArgumentException("ImageAware should wrap ImageView. ImageViewAware is expected.");
}
//bitmap=Blur.fastblur(context, bitmap,radius, false);
// Bitmap overlay = Bitmap.createBitmap(100,50,Bitmap.Config.RGB_565);
// Paint paint = new Paint();
// paint.setFlags(Paint.FILTER_BITMAP_FLAG);
// Canvas canvas = new Canvas(overlay);
// canvas.drawBitmap(bitmap, 0, 0, paint);
// imageAware.setImageBitmap(FastBlur.doBlur(overlay,60, true));
// Bitmap blurred = blurRenderScript(bitmap,radius);//second parametre is radius
// imageAware.setImageBitmap(blurred); //radius decide blur amount
blur(bitmap, imageAware);
// float width_bkg = bkg.getWidth();
// float height_bkg = bkg.getHeight();
// float measuredWidth_view = view.getMeasuredWidth();
// float measuredHeight_view = view.getMeasuredHeight();
// float x = measuredWidth_view / width_bkg;
// float y = measuredHeight_view / height_bkg;
//
// Bitmap overlay = Bitmap.createBitmap(100,50,Bitmap.Config.RGB_565);
// Canvas canvas = new Canvas(overlay);
// canvas.translate(-view.getLeft(), -view.getTop());
// //canvas.scale(1 / y, 1 / x);
// Paint paint = new Paint();
// //paint.setARGB(50, 0, 0, 0);
// paint.setFlags(Paint.FILTER_BITMAP_FLAG);
// canvas.drawBitmap(bkg, 0, 0, paint);
}
private Bitmap blurRenderScript(Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(context);
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
private void blur(Bitmap bkg, ImageAware view) {
// long startMs = System.currentTimeMillis();
float scaleFactor = 1;
// float radius = 20;
//if (downScale.isChecked()) {
scaleFactor = 8;
// radius = 2;
//}
Bitmap overlay = Bitmap.createBitmap((int) (bkg.getWidth()/scaleFactor),
(int) (bkg.getHeight()/scaleFactor), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(overlay);
// canvas.translate(-bkg.getLeft()/scaleFactor, -view.getTop()/scaleFactor);
canvas.scale(1 / scaleFactor, 1 / scaleFactor);
//Paint paint = new Paint();
//paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(bkg, 0, 0, null);
overlay = FastBlur.doBlur(overlay, (int)radius, true);
view.setImageBitmap(overlay);
}
}
| true
|
b8dc7acb1ee195e5b7dc2e6e571513638ff2f886
|
Java
|
grdo3126/Draudimas
|
/IFunkcijos.java
|
UTF-8
| 309
| 2.125
| 2
|
[] |
no_license
|
package Draudimas;
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
public interface IFunkcijos {
DerivativeStructure pirmaFunkcija(DerivativeStructure x, double vardiklis, double rodiklis);
DerivativeStructure antraFunkcija(DerivativeStructure x, double daugiklis);
}
| true
|
d78c3ed879573c2cd506322c6182e87b5b918b04
|
Java
|
zhangdaxianya/Maven
|
/src/test/java/Demo.java
|
UTF-8
| 567
| 2.96875
| 3
|
[] |
no_license
|
import org.junit.Test;
import java.util.Random;
public class Demo {
@Test
public void demo(){
Random random = new Random();
String[] str = {"A", "B", "C", "D", "E", "F", "G", "a", "b", "c", "d", "e", "f", "g"};
String code = "";
for (int i = 0; i < 5; i++) {
Integer index = random.nextInt(str.length);
code += str[index];
}
System.out.println(code);
System.out.println(System.currentTimeMillis());
System.out.println(System.currentTimeMillis()+code);
}
}
| true
|
615bed67dd6b4fc546a05a82992f77c37a8d7319
|
Java
|
strebellev/ecosystemV5.1
|
/Zodrak Rage V11/src/entity/Buisson.java
|
UTF-8
| 2,565
| 2.453125
| 2
|
[] |
no_license
|
package entity;
import java.util.ArrayList;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import processing.core.PVector;
public class Buisson {
PApplet parent;
ArrayList<PVector> buisson;
public PVector position;
int r;
public int randomBuisson;
int animBuisson = 8;
public boolean dropPlantBranch;
PImage[] animB = new PImage[animBuisson];
PImage img;
@SuppressWarnings("deprecation")
public Buisson(PApplet p,PVector l){
position = l.get();
parent = p;
r = 32;
buisson = new ArrayList<PVector>();
//img = tempImg;
randomBuisson = (int) p.random(8);
animB[0] = p.loadImage("res/newvegetal/buisson/buisson0.png");
animB[1] = p.loadImage("res/newvegetal/buisson/buisson1.png");
animB[2] = p.loadImage("res/newvegetal/buisson/buisson2.png");
animB[3] = p.loadImage("res/newvegetal/buisson/buisson3.png");
animB[4] = p.loadImage("res/newvegetal/buisson/buisson4.png");
animB[5] = p.loadImage("res/newvegetal/buisson/buisson5.png");
animB[6] = p.loadImage("res/newvegetal/buisson/buisson6.png");
animB[7] = p.loadImage("res/newvegetal/buisson/buisson7.png");
}
@SuppressWarnings("deprecation")
public void add(PVector l){
buisson.add(l.get());
}
public void display(PApplet p){
p.ellipseMode(PConstants.CENTER);
p.fill(0);
//p.ellipse(position.x, position.y, r, r);
p.image(img, position.x-16, position.y-16);
}
public void display2(PApplet p){
if(randomBuisson == 0){
p.image(animB[0], position.x-23, position.y-62);
}
if(randomBuisson == 1){
p.image(animB[1], position.x-14, position.y-70);
dropPlantBranch = true;
}
if(randomBuisson == 2){
p.image(animB[2], position.x-17, position.y-64);
dropPlantBranch = true;
}
if(randomBuisson == 3){
p.image(animB[3], position.x-12, position.y-83);
dropPlantBranch = true;
}
if(randomBuisson == 4){
p.image(animB[4], position.x-47, position.y-38);
dropPlantBranch = true;
}
if(randomBuisson == 5){
p.image(animB[5], position.x-42, position.y-29);
}
if(randomBuisson == 6){
p.image(animB[6], position.x-29, position.y-82);
dropPlantBranch = true;
}
if(randomBuisson == 7){
p.image(animB[4], position.x-30, position.y-83);
dropPlantBranch = true;
}
}
public ArrayList<PVector> getBuisson(){
return buisson;
}
public PVector position(){
return position;
}
public float getR(){
return r;
}
}
| true
|
5ce0271ecc5e47a95f83bf6465b0058f9fbe8a1b
|
Java
|
freemed/openclinicga
|
/src/be/openclinic/system/Application.java
|
UTF-8
| 3,152
| 2.703125
| 3
|
[] |
no_license
|
package be.openclinic.system;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import be.mxs.common.util.db.MedwanQuery;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
public class Application {
public static byte[] encrypt(String sValue) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
return md.digest(sValue.getBytes());
}
catch (Exception e) {
Debug.println("Application encryption error: "+e.getMessage());
}
return null;
}
public static boolean checkPassword(byte[] aPassword) {
try {
if (MessageDigest.isEqual(aPassword,encrypt("ditisgeenpaswoord"))) {
return true;
}
}
catch (Exception e) {
Debug.println("Application checkPassword error: "+e.getMessage());
}
return false;
}
public static boolean isDisabled(String sScreenId){
if (sScreenId.endsWith(".edit")){
sScreenId = sScreenId.substring(0,sScreenId.length()-5);
}
else if (sScreenId.endsWith(".select")){
sScreenId = sScreenId.substring(0,sScreenId.length()-7);
}
else if (sScreenId.endsWith(".delete")){
sScreenId = sScreenId.substring(0,sScreenId.length()-7);
}
else if (sScreenId.endsWith(".add")){
sScreenId = sScreenId.substring(0,sScreenId.length()-5);
}
return MedwanQuery.getInstance().getDisabledApplications().get(sScreenId)!=null;
}
public static boolean storeScreenId(String sScreenId){
if (ScreenHelper.checkString(sScreenId).length()>0){
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
String sSQL = "INSERT INTO Applications (ScreenId, UpdateTime) VALUES (?,?)";
PreparedStatement ps = oc_conn.prepareStatement(sSQL);
ps.setString(1,sScreenId.toLowerCase());
ps.setTimestamp(2,new Timestamp(new java.util.Date().getTime()));
ps.executeUpdate();
ps.close();
oc_conn.close();
return true;
}
catch (Exception e){
e.printStackTrace();
}
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public static boolean deleteScreens(){
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
String sSQL = "DELETE FROM Applications";
PreparedStatement ps = oc_conn.prepareStatement(sSQL);
ps.executeUpdate();
ps.close();
oc_conn.close();
return true;
}
catch (Exception e){
e.printStackTrace();
}
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
| true
|
3e0958a811121c79ecb1f0742458a10cb166ee30
|
Java
|
LiFBoy/mmfenqi
|
/fenqi_android/.svn/pristine/bd/bd1d193a14fc36bfc3062e6a36ded708730f4de1.svn-base
|
UTF-8
| 356
| 1.640625
| 2
|
[] |
no_license
|
package com.mmfenqi.Bean;
import java.io.Serializable;
public class PayOrderInfo implements Serializable{
private static final long serialVersionUID = -5161864593795177321L;
public String username = "" ;
public String clientid = "" ;
public String orderid = "" ;
public String addtime = "" ;
public int fee = 0 ;
public String status = "" ;
}
| true
|
dd43b13b533b1eb8bc1ed7908caed65a934ec21e
|
Java
|
liucan0/LeetCode
|
/LeetCode/src/main/java/leetCode/array/simple/Leet_169_MajorElement.java
|
UTF-8
| 1,241
| 4.28125
| 4
|
[] |
no_license
|
package leetCode.array.simple;
/**
* leetcode 169 数组中的多数元素
* 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
*
* 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
*/
public class Leet_169_MajorElement {
/**
* 四种方法:1.使用hashMap, 2.排序数组在返回数组中间值
* 3.分治法,4.波伊-摩尔投票算法。
* 此处采用投票算法。
* 1.维护一个候选众数num和他的出现次数count,初始时nums可以为任何数,count为0。
* 2.遍历数组nums中的所有元素,对于每个元素x,在判断x之前,如果count的值为0,先将x的赋予num,
* 随后判断:a.如果x与num相等,count的值加一,如果不等,则值减一。
* 3.遍历完成后,num即为整个数组的众数
* @param nums
* @return
*/
public int majorElement(int[] nums) {
int num = 0, count = 0;
for (int temp : nums) {
if (count == 0) {
num = temp;
}
count = temp == num ? count + 1 : count - 1;
}
return num;
}
}
| true
|
3e97805fe2ba542140ada43e483eea828ebaddfa
|
Java
|
gabrielgouv/java-spi-greetings-example
|
/greetings-service/src/main/java/com/github/gabrielgouv/greetings/api/GreetingsService.java
|
UTF-8
| 125
| 1.78125
| 2
|
[] |
no_license
|
package com.github.gabrielgouv.greetings.api;
public interface GreetingsService {
String greetMessage(String name);
}
| true
|
8efb2935c034abe93ed5382bfd9e1559a4e174d4
|
Java
|
satish-v/ctupoc
|
/ctuuploadms/src/main/java/com/capgemini/ctu/dao/CtuDao.java
|
UTF-8
| 541
| 1.507813
| 2
|
[] |
no_license
|
package com.capgemini.ctu.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
@Repository
@Transactional
public interface CtuDao extends JpaRepository {
}
| true
|
68c54a539ec811d6ef95490f8faa5770a0115966
|
Java
|
GarinZ/venus
|
/venus-service/src/main/java/art/meiye/venus/service/vo/auth/EmailLoginResponse.java
|
UTF-8
| 283
| 1.640625
| 2
|
[] |
no_license
|
package art.meiye.venus.service.vo.auth;
import lombok.Data;
/**
* @author Garin
* @date 2020-08-11
*/
@Data
public class EmailLoginResponse {
/**
* 用户id
*/
private Integer userId;
/**
* 用户id对应的token
*/
private String token;
}
| true
|
a27f542bff0c42e84f5218bd987476c50fe38426
|
Java
|
luolidong/java_design_pattern
|
/src/main/java/com/imooc/design/pattern/behavioral/strategy/LijianPromotionStrategy.java
|
UTF-8
| 242
| 2.40625
| 2
|
[] |
no_license
|
package com.imooc.design.pattern.behavioral.strategy;
/**
* Created by dell on 2019/4/10.
*/
public class LijianPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println("立减");
}
}
| true
|
75ee2b55054a3057b555eced7b0ff816656ed6b8
|
Java
|
faraonelife/Spring-Project
|
/project/src/main/java/uz/farhod/rest/service/ProductService.java
|
UTF-8
| 901
| 2.34375
| 2
|
[] |
no_license
|
package uz.farhod.rest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uz.farhod.rest.entity.Product;
import uz.farhod.rest.payload.ApiResponse;
import uz.farhod.rest.repository.ProductRepository;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
@Autowired
ProductRepository productRepository;
public List<Product> getProductsList(){
return productRepository.findAll();
}
public ApiResponse getProductDetailsById(Integer id){
Optional<Product> optionalProduct = productRepository.findById(id);
if (!optionalProduct.isPresent())
return new ApiResponse("Product with this id Not Found!", false);
Product product = optionalProduct.get();
return new ApiResponse("Product details: ", true, product);
}
}
| true
|
90e988f920a95aacc18f83fd25c310e7fc757c96
|
Java
|
jjjikolpp/acorn.spsou
|
/spring_mvc7_para_post/src/main/java/pack/model/SangpumModel.java
|
UTF-8
| 314
| 2.28125
| 2
|
[] |
no_license
|
package pack.model;
import org.springframework.stereotype.Component;
import pack.controller.SangpumBean;
@Component
public class SangpumModel {
public String compute(SangpumBean bean){
String ss = "품명 : " + bean.getSang() + " " +
", 금액 : " + (bean.getSu() * bean.getDan());
return ss;
}
}
| true
|
580b04219c1ac90df195228fe53e7bb08b828288
|
Java
|
YangIPhone/blog-java
|
/blog-java/src/main/java/com/yang/service/impl/ResourceServiceImpl.java
|
UTF-8
| 1,154
| 1.742188
| 2
|
[] |
no_license
|
package com.yang.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yang.mapper.ResourceMapper;
import com.yang.pojo.Resource;
import com.yang.service.ResourceService;
@Service
public class ResourceServiceImpl implements ResourceService {
@Autowired
ResourceMapper resourceMapper;
@Override
public List<Resource> resListByAll() {
// TODO Auto-generated method stub
return resourceMapper.resListByAll();
}
@Override
public List<Resource> resListByUserid(String userid) {
// TODO Auto-generated method stub
return resourceMapper.resListByUserid(userid);
}
@Override
public List<Resource> resListByDescribe(String describe) {
// TODO Auto-generated method stub
return resourceMapper.resListByDescribe("%"+describe+"%");
}
@Override
public int addResource(Resource resource) {
// TODO Auto-generated method stub
return resourceMapper.addResource(resource);
}
@Override
public Resource getResourceByResid(String resid) {
// TODO Auto-generated method stub
return resourceMapper.getResourceByResid(resid);
}
}
| true
|
c34d61cba6300548b14b2e1be70a6549f6224bb8
|
Java
|
WadeXHong/CHOCOLABS
|
/app/src/main/java/com/wadexhong/chocolabs/helper/JsonHelper.java
|
UTF-8
| 896
| 2.203125
| 2
|
[] |
no_license
|
package com.wadexhong.chocolabs.helper;
import android.util.Log;
import com.google.gson.Gson;
import com.wadexhong.chocolabs.objects.Data;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by wade8 on 2018/6/27.
*/
public class JsonHelper {
public final String url = "http://www.mocky.io/v2/5a97c59c30000047005c1ed2";
public Data fetchJson() {
Request request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
try {
Response response = client.newCall(request).execute();
Gson gson = new Gson();
return gson.fromJson(response.body().string(), Data.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| true
|
5246f7d1f84b1f533767d0ecc05b80b6d54cda16
|
Java
|
kosbr/ix-client
|
/src/main/java/com/github/kosbr/ix/dto/Task.java
|
UTF-8
| 1,337
| 2.265625
| 2
|
[] |
no_license
|
package com.github.kosbr.ix.dto;
import com.google.common.base.MoreObjects;
import java.io.Serializable;
/**
* Created by kosbr on 08.04.2016.
*/
public class Task implements Serializable {
private static final long serialVersionUID = -7401961224124280149L;
private Integer id;
private String serviceName;
private String methodName;
private Object[] arguments;
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(final String serviceName) {
this.serviceName = serviceName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(final String methodName) {
this.methodName = methodName;
}
public Object[] getArguments() {
return arguments;
}
public void setArguments(final Object[] arguments) {
this.arguments = arguments;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("serviceName", serviceName)
.add("methodName", methodName)
.add("arguments", arguments)
.toString();
}
}
| true
|
bb802d2fbc18b6c68c0b4b9a753cd5038166272b
|
Java
|
Aukomn/Super-Geek-Reader
|
/app/src/main/java/org/chaos/fx/cnbeta/hotarticles/ScrollingActivity.java
|
UTF-8
| 2,081
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.chaos.fx.cnbeta.hotarticles;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.View;
import android.widget.TextView;
import org.chaos.fx.cnbeta.R;
public class ScrollingActivity extends BaseActivity {
private int position;
private TextView tvd_content;
private TextView tvd_author;
private TextView tvd_date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ArticleData article = getIntent().getParcelableExtra("articleData");
position = getIntent().getIntExtra("position", 0);
final CollapsingToolbarLayout collapsingToolbar=(CollapsingToolbarLayout)findViewById(R.id.toolbar_layout);
collapsingToolbar.setTitle(article.title);
tvd_author = (TextView) findViewById(R.id.detail_author);
tvd_date = (TextView) findViewById(R.id.detail_date);
tvd_content = (TextView) findViewById(R.id.detail_content);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tvd_content.setText(Html.fromHtml(article.content, Html.FROM_HTML_MODE_LEGACY));
} else {
tvd_content.setText(Html.fromHtml(article.content));
}
tvd_date.setText(article.datetime);
tvd_author.setText(article.reference);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "感谢使用", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
| true
|
6ad76bc9aae5a4f20a79d77b76852f4871488053
|
Java
|
gaihub1/GitClone
|
/Karan_Workspace/src/MulTable.java
|
UTF-8
| 544
| 3.484375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class MulTable {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number for multiplication table :: ");
int a = scan.nextInt();
System.out.println("Enter the multiplication table length :: ");
int x= scan.nextInt();
scan.close();
int res = 0;
for(int i = 1; i <= x; i++)
{
res = a * i;
System.out.println(a + " * " + i + " = " + res);
}
}
}
| true
|
f8e0112174ba5975236d0304755d1ff395310b20
|
Java
|
seshank4/ChatBotNLPService
|
/src/com/aetna/dataeng/chatbot/service/ChatService.java
|
UTF-8
| 1,211
| 2.625
| 3
|
[] |
no_license
|
package com.aetna.dataeng.chatbot.service;
import java.util.HashMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
@Path("/chatservice")
public class ChatService {
/**
* @author ganesh
* @param ChatModel
* function for chat
* @return
* @throws JSONException
*/
@POST
@Path("/interact")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ChatModel chat(ChatModel model) throws JSONException{
HashMap<String, String> map = new HashMap<String, String>();
map.put("hi", "Hello");
map.put("how are you", "I'am fine! How are you?");
String msg = model.getMessage();
if(msg.trim().toLowerCase().contains("how are you")){
msg = "how are you";
}
String response = map.get(msg.trim().toLowerCase());
if(response == null){
response = "Sorry, I don't know how to respond to that yet";
}
ChatModel resModel = new ChatModel();
resModel.setMessage(response);
return resModel;
}
@Path("/test")
@GET
@Produces("text/plain")
public String test() {
return "Hi";
}
}
| true
|
68ac25ff618b84d2141bf943f5ca742580cf446e
|
Java
|
rposcro/jwavez
|
/jwavez-core/src/main/java/com/rposcro/jwavez/core/commands/types/BasicCommandType.java
|
UTF-8
| 377
| 2.109375
| 2
|
[
"MIT"
] |
permissive
|
package com.rposcro.jwavez.core.commands.types;
import com.rposcro.jwavez.core.classes.CommandClass;
@CommandTypeEnum(commandClass = CommandClass.CMD_CLASS_BASIC)
public enum BasicCommandType implements CommandType {
BASIC_SET(0x01),
BASIC_GET(0x02),
BASIC_REPORT(0x03),
;
BasicCommandType(int code) {
CommandTypesRegistry.registerConstant(this, code);
}
}
| true
|
da793e3423c56a78c77d483df17ce4a3adfca779
|
Java
|
TheyCallMeRobinson/Duel
|
/src/main/java/player/Human.java
|
UTF-8
| 1,165
| 3.34375
| 3
|
[] |
no_license
|
package player;
import com.nocompanyyet.asset.Card;
import com.nocompanyyet.asset.State;
import service.ExceptionHandlingService;
import service.IOService;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Human extends Player {
public Human() {
this.name = IOService.requestPlayerName();
}
// asking human player for his card on current move
public Card requestCard(State state) {
Scanner scn = new Scanner(System.in);
Card card = new Card(-1);
System.out.printf("%s's turn:\n", this.name);
// if he's entered some wrong input or non-existing card in his deck, we throw an exception and immediately
// warn him about the mistake and offer him another try
try {
Integer temp = scn.nextInt();
card.setValue(temp);
if(!this.getOwnDeck().contains(card))
throw new NoSuchElementException();
}
catch (NoSuchElementException e1) {
card = ExceptionHandlingService.handleWrongCardInputException(this, card);
}
this.getOwnDeck().remove(card);
return card;
}
}
| true
|
3ed17b067f900c8d5ca9bd67aa8744418292c7db
|
Java
|
emmanoe/javadelar
|
/simpleui/src_basic/Run.java
|
UTF-8
| 1,855
| 3
| 3
|
[] |
no_license
|
package src_basic;
import java.util.Collection;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import fr.ubordeaux.simpleUI.Application;
import fr.ubordeaux.simpleUI.ApplicationRunnable;
import fr.ubordeaux.simpleUI.Arena;
import fr.ubordeaux.simpleUI.TimerRunnable;
import fr.ubordeaux.simpleUI.TimerTask;
public class Run implements ApplicationRunnable<Item> {
private int width;
private int height;
public Run(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void run(final Arena<Item> arg0, Collection<? extends Item> arg1) {
MouseListener mouseHandler = new MouseListener();
/*
* We build the graphical interface by adding the graphical component
* corresponding to the Arena - by calling createComponent - to a JFrame.
*/
final JFrame frame = new JFrame("Test Arena");
/*
* This is our KeyHandler that will be called by the Arena in case of key events
*/
KeyListener keyListener = new KeyListener(frame);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(arg0.createComponent(this.width, this.height, mouseHandler, keyListener));
frame.pack();
frame.setVisible(true);
/*
* We initially draw the component
*/
arg0.refresh();
/*
* We ask the Application to call the following run function every seconds. This
* method just refresh the component.
*/
Application.timer(100, new TimerRunnable() {
public void run(TimerTask timerTask) {
arg0.refresh();
((Planet)arg1.toArray()[0]).incrSpaceShips();
((Planet)arg1.toArray()[1]).incrSpaceShips();
((Planet)arg1.toArray()[2]).incrSpaceShips();
((Planet)arg1.toArray()[3]).incrSpaceShips();
for (Item item : arg1) {
item.move();
}
}
});
}
}
| true
|
569213f2eca5ac77e1ad7ace9168579f99465819
|
Java
|
chnbin/CodeSnippet
|
/Leetcode/169. Majority Element.java
|
UTF-8
| 435
| 2.953125
| 3
|
[] |
no_license
|
class Solution {
public int majorityElement(int[] nums) {
int candicate = 0;
int counter = 0;
for(int num: nums) {
if (counter == 0) {
candicate = num;
counter = 1;
continue;
}
if (num == candicate) {
counter += 1;
} else {
counter -= 1;
}
}
return candicate;
}
}
| true
|
3fc96129adb2e53a7bd353823c87fd1967756bc9
|
Java
|
bloodlee/AndroidFlickrIpResolver
|
/app/src/main/java/app/yli/org/flickriptranslator/MainActivity.java
|
UTF-8
| 2,908
| 2.078125
| 2
|
[] |
no_license
|
package app.yli.org.flickriptranslator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.common.base.Strings;
public class MainActivity extends Activity {
private TextView outputTextView;
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputTextView = (TextView)findViewById(R.id.outpout_textview);
outputTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
TextView infoTextView = (TextView)findViewById(R.id.info_textview);
infoTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Context context = getApplicationContext();
int id = item.getItemId();
if (id == R.id.refresh) {
ProgressDialog pd = ProgressDialog.show(MainActivity.this, "", "正在查找可用的服务器...");
new TranslatingTask(getApplicationContext(), outputTextView, pd).execute("", "", "");
} else if (id == R.id.copy) {
CharSequence output = outputTextView.getText();
CharSequence toastText = context.getText(R.string.copy_fail_info);
if (!Strings.isNullOrEmpty(output.toString())) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", output);
clipboard.setPrimaryClip(clip);
toastText = context.getText(R.string.copy_info);
}
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
} else if (id == R.id.about) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.innoli.com/wordpress/?page_id=792"));
startActivity(browserIntent);
}
return super.onOptionsItemSelected(item);
}
}
| true
|
88204a8794af39ec91f759e19de24848464767f1
|
Java
|
VivekMakwana24/MyClasses
|
/app/src/main/java/com/example/myclasses/model/CountryCodePojo.java
|
UTF-8
| 1,605
| 2.5625
| 3
|
[] |
no_license
|
package com.example.myclasses.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CountryCodePojo{
@SerializedName("response_code")
private int responseCode;
@SerializedName("type")
private String type;
@SerializedName("message")
private String message;
@SerializedName("status")
private boolean status;
@SerializedName("data")
private List<CountryCodePojoItem> countryCodePojo;
public void setResponseCode(int responseCode){
this.responseCode = responseCode;
}
public int getResponseCode(){
return responseCode;
}
public void setType(String type){
this.type = type;
}
public String getType(){
return type;
}
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public void setStatus(boolean status){
this.status = status;
}
public boolean isStatus(){
return status;
}
public void setCountryCodePojo(List<CountryCodePojoItem> countryCodePojo){
this.countryCodePojo = countryCodePojo;
}
public List<CountryCodePojoItem> getCountryCodePojo(){
return countryCodePojo;
}
@Override
public String toString(){
return
"CountryCodePojo{" +
"response_code = '" + responseCode + '\'' +
",type = '" + type + '\'' +
",message = '" + message + '\'' +
",status = '" + status + '\'' +
",countryCodePojo = '" + countryCodePojo + '\'' +
"}";
}
}
| true
|
3c3c0478493ce1c68057e03885bcd5d0f61592bb
|
Java
|
hackdie/SchoolPocket
|
/src/classes/Item_enviar_mjes_combo.java
|
UTF-8
| 424
| 2.40625
| 2
|
[] |
no_license
|
package classes;
public class Item_enviar_mjes_combo {
public int id;
public String materia;
public Item_enviar_mjes_combo(int _id, String _materia ){
this.id = _id;
this.materia = _materia;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMateria() {
return materia;
}
public void setMateria(String materia) {
this.materia = materia;
}
}
| true
|
3dd6132ce991c468efb804eeb7081c05b388f6f0
|
Java
|
MySelfBlank/xuecheng
|
/xc-service-manage-course/src/main/java/com/xuecheng/manage_course/dao/CategoryMapper.java
|
UTF-8
| 334
| 1.671875
| 2
|
[] |
no_license
|
package com.xuecheng.manage_course.dao;
import com.xuecheng.framework.domain.course.ext.CategoryNode;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 分类dao接口
* @author 鲜磊 on 2019/4/30
**/
@Mapper
public interface CategoryMapper {
//分类查询
public CategoryNode selectList();
}
| true
|
2ba1c8f9df8c2f927da93ddbb9a738f7dde17a4f
|
Java
|
javaengineer/javaTest
|
/src/com/xc/java/pattern/factory/abstr/AbstractFactory.java
|
UTF-8
| 260
| 2.5625
| 3
|
[] |
no_license
|
package com.xc.java.pattern.factory.abstr;
/**
* 抽象工厂
*
* 把所有的厂家放这里统一管理,便于扩展
*/
public abstract class AbstractFactory {
public abstract String getMengniuMilk();
public abstract String getYiliMilk();
}
| true
|
f6474f438b313011f66a1937c73de750fdafb763
|
Java
|
volponi121/4esoft2020
|
/src/main/java/aula20201109/AppProducerConsumer.java
|
UTF-8
| 2,846
| 3.1875
| 3
|
[] |
no_license
|
package aula20201109;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class AppProducerConsumer extends JDialog {
private JPanel panel = new JPanel();
private List<Job> pendingJobs = new ArrayList<>();
private List<Worker> workers = new ArrayList<>();
protected void createNewJob(int size) {
Job newJob = new Job(size);
JobProgressPanel jobProgressPanel = new JobProgressPanel(newJob);
this.panel.add(jobProgressPanel);
this.panel.revalidate();
this.revalidate();
}
public static void main(String[] args) {
AppProducerConsumer app = new AppProducerConsumer();
app.setVisible(true);
}
private static class JobProgressPanel extends JPanel {
private Job job;
private int wordDone = 0;
private JProgressBar progressBar;
public JobProgressPanel(Job job) {
this.progressBar = new JProgressBar(job.getSize());
this.job = job;
BoxLayout boxLayout = new BoxLayout(this, BoxLayout.LINE_AXIS);
this.setLayout(boxLayout);
this.add(progressBar);
}
}
private class ControlPanel extends JPanel {
private JTextField jobSize = new JTextField(20);
private JButton btnAddJob = new JButton("Add Job");
private JLabel workerCount = new JLabel("0");
private JButton btnAddWorker = new JButton("Add Worker");
public ControlPanel() {
btnAddJob.addActionListener(e -> {
int jobSizeAsInt = Integer.parseInt(jobSize.getText());
System.out.println(jobSizeAsInt);
createNewJob(jobSizeAsInt);
});
btnAddWorker.addActionListener(e -> {
System.out.println("New worker created!");
Worker newWorker = new Worker();
workers.add(newWorker);
newWorker.start();
});
BoxLayout boxLayout = new BoxLayout(this, BoxLayout.LINE_AXIS);
this.setLayout(boxLayout);
this.add(jobSize);
this.add(btnAddJob);
this.add(workerCount);
this.add(btnAddWorker);
}
}
public AppProducerConsumer() {
super();
panel.setBackground(Color.LIGHT_GRAY);
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.add(new ControlPanel());
this.add(panel);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setSize(600, 400);
}
}
| true
|
7e354ff90bc6e1e1c30682c67e3ace700e2c0430
|
Java
|
MosinRA/WeatherOnBoard
|
/app/src/main/java/com/mosin/weatheronboard/interfaces/IOpenWeatherMap.java
|
UTF-8
| 457
| 2.078125
| 2
|
[] |
no_license
|
package com.mosin.weatheronboard.interfaces;
import com.mosin.weatheronboard.model.WeatherRequest;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface IOpenWeatherMap {
//api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
@GET ("data/2.5/weather")
Call<WeatherRequest> loadWeather(@Query("q") String cityName, @Query("units") String Metric, @Query("appid") String appId);
}
| true
|
cd5a9355c254a2ee60a0dbe9fdd9fe565ced9812
|
Java
|
mezz/FTBLib
|
/src/main/java/ftb/lib/notification/ClickAction.java
|
UTF-8
| 1,772
| 2.171875
| 2
|
[] |
no_license
|
package ftb.lib.notification;
import com.google.gson.JsonElement;
import ftb.lib.api.client.FTBLibClient;
import ftb.lib.api.gui.GuiScreenRegistry;
import latmod.lib.LMUtils;
import latmod.lib.util.FinalIDObject;
import net.minecraft.client.gui.*;
import net.minecraftforge.fml.relauncher.*;
import java.io.File;
import java.net.URI;
public abstract class ClickAction extends FinalIDObject
{
public ClickAction(String s)
{
super(s);
}
@SideOnly(Side.CLIENT)
public abstract void onClicked(JsonElement data);
// Static //
public static final ClickAction CMD = new ClickAction("cmd")
{
@SideOnly(Side.CLIENT)
public void onClicked(JsonElement data)
{ FTBLibClient.execClientCommand("/" + data.getAsString()); }
};
public static final ClickAction SHOW_CMD = new ClickAction("show_cmd")
{
@SideOnly(Side.CLIENT)
public void onClicked(JsonElement data)
{ FTBLibClient.mc.displayGuiScreen(new GuiChat(data.getAsString())); }
};
public static final ClickAction URL = new ClickAction("url")
{
@SideOnly(Side.CLIENT)
public void onClicked(JsonElement data)
{
try { LMUtils.openURI(new URI(data.getAsString())); }
catch(Exception ex) { ex.printStackTrace(); }
}
};
public static final ClickAction FILE = new ClickAction("file")
{
@SideOnly(Side.CLIENT)
public void onClicked(JsonElement data)
{
try { LMUtils.openURI(new File(data.getAsString()).toURI()); }
catch(Exception ex) { ex.printStackTrace(); }
}
};
public static final ClickAction GUI = new ClickAction("gui")
{
@SideOnly(Side.CLIENT)
public void onClicked(JsonElement data)
{
GuiScreen gui = GuiScreenRegistry.openGui(FTBLibClient.mc.thePlayer, data.getAsString());
if(gui != null) FTBLibClient.mc.displayGuiScreen(gui);
}
};
}
| true
|
772f0b6d394a27e989903a1b7bf6fea40a8e6f21
|
Java
|
xsfs/DesignPattern
|
/src/Bridge/BridgeAdapter/Abstraction.java
|
UTF-8
| 247
| 2.5
| 2
|
[] |
no_license
|
package Bridge.BridgeAdapter;
public abstract class Abstraction {
protected Implementor implementor=null;
protected Abstraction(Implementor implementor){
this.implementor=implementor;
}
public abstract void operation();
}
| true
|
2f434906bb7e2ee527a502e6b005026970b79fda
|
Java
|
wuyufei2019/JSLYG
|
/src/main/java/com/cczu/model/controller/PageSekbMsdsController.java
|
UTF-8
| 4,395
| 1.835938
| 2
|
[] |
no_license
|
package com.cczu.model.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cczu.sys.comm.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cczu.model.entity.TMESK_MsdsEntity;
import com.cczu.model.service.ISekbMsdsService;
import com.cczu.sys.comm.controller.BaseController;
import com.cczu.sys.comm.mapper.JsonMapper;
import com.cczu.sys.system.service.RoleService;
/**
* Msds信息controller
*
* @author jason
* @date 2017年7月1日
*/
@Controller
@RequestMapping("sekb/msds")
public class PageSekbMsdsController extends BaseController {
@Autowired
private RoleService roleService;
@Autowired
private ISekbMsdsService sekbMsdsService;
/**
* 列表显示页面
*
* @param model
*/
@RequestMapping(value = "index")
public String index(Model model) {
return "sekb/msds/index";
}
/**
* list页面
*
* @param request
*/
@RequiresPermissions("sekb:msds:view")
@RequestMapping(value = "list")
@ResponseBody
public Map<String, Object> getData(HttpServletRequest request) {
Map<String, Object> map = getPageMap(request);
map.put("zwname", request.getParameter("sekb_msds_zw_name"));
map.put("zwname2", request.getParameter("sekb_msds_zw_name2"));
return sekbMsdsService.dataGrid(map);
}
/**
* 查看页面跳转
*
* @param id,model
*/
@RequiresPermissions("sekb:msds:view")
@RequestMapping(value = "view/{id}", method = RequestMethod.GET)
public String view(@PathVariable("id") Integer id, Model model) {
//查询选择的产品信息
long id1 = id;
TMESK_MsdsEntity tm = sekbMsdsService.findById(id1);
model.addAttribute("res", tm);
//返回页面
model.addAttribute("action", "view");
return "sekb/msds/view";
}
/**
* 导出Excel
*
* @param request
*/
@RequiresPermissions("sekb:msds:excel")
@RequestMapping(value = "excel")
@ResponseBody
public void getExcel(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("zwname", request.getParameter("sekb_msds_zw_name"));
map.put("zwname2", request.getParameter("sekb_msds_zw_name2"));
map.put("colval", request.getParameter("colval"));
map.put("coltext", request.getParameter("coltext"));
sekbMsdsService.exportExcel(response, map);
}
/**
* 显示所有列
*
* @param id,model
*/
@RequiresPermissions("sekb:msds:excel")
@RequestMapping(value = "colindex", method = RequestMethod.GET)
public String colindex(Model model) {
model.addAttribute("url", "sekb/msds/excel");
return "common/formexcel";
}
@RequestMapping(value = "json")
@ResponseBody
public String getDataJson(HttpServletRequest request) {
List<TMESK_MsdsEntity> list = sekbMsdsService.findByWzName(request.getParameter("name"));
if (list != null && list.size() > 0)
return JsonMapper.getInstance().toJson(list.get(0));
else {
Map<String, Object> map = new HashMap<>();
map.put("m1", "");
map.put("m10", "");
map.put("m20", "");
return JsonMapper.getInstance().toJson(map);
}
}
@RequestMapping(value = "info/{casNo}")
@ResponseBody
public String getInfoByCasNo(@PathVariable("casNo") String casNo, HttpServletRequest request) {
Assert.isTrue(StringUtils.isNotEmpty(casNo));
TMESK_MsdsEntity msds = sekbMsdsService.getByCasNo(casNo);
return JSON.toJSONString(msds);
}
}
| true
|
010759a66f699fb1939c5d094dce358dc9d2ded5
|
Java
|
anilgmaipady/spring-cloud-example
|
/netflix-eureka-naming-server/src/main/java/com/springcloudexample/microservices/netflixeurekanamingserver/NetflixEurekaNamingServerApplication.java
|
UTF-8
| 840
| 1.671875
| 2
|
[] |
no_license
|
package com.springcloudexample.microservices.netflixeurekanamingserver;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
@EnableEurekaServer
@EnableAdminServer
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
public class NetflixEurekaNamingServerApplication {
public static void main(String[] args) {
SpringApplication.run(NetflixEurekaNamingServerApplication.class, args);
}
}
| true
|
322ad0b47f3d52e9c7186da236569270fbf5e40f
|
Java
|
Guevarak1/AsyncJavaExamples
|
/src/main/java/com/kevguev/tutorial/asyncexamples/tutorials/RunnableWithExecutor.java
|
UTF-8
| 717
| 3.09375
| 3
|
[] |
no_license
|
package com.kevguev.tutorial.asyncexamples.tutorials;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class RunnableWithExecutor {
private static void spinThreadWithExecutorService() {
System.out.println("pre hello world at: " + System.currentTimeMillis());
Thread thread = new Thread(() -> System.out.println("Hello world at: " + System.currentTimeMillis()));
thread.start();
System.out.println("post hello world at: " + System.currentTimeMillis());
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("hello world from executor at: " + System.currentTimeMillis()));
}
}
| true
|
1d2ddc1276ee8f8d2b4e09445243430a5011a3ec
|
Java
|
gnunn1/avroprotobuf
|
/camel-demo-restprotobuf/src/main/java/demo/camel/MyRouteBuilder.java
|
UTF-8
| 1,243
| 1.929688
| 2
|
[] |
no_license
|
package demo.camel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.protobuf.ProtobufDataFormat;
import org.apache.camel.model.rest.RestBindingMode;
/**
* A Camel Java DSL Router
*/
public class MyRouteBuilder extends RouteBuilder {
public void configure() {
String registryconfig="&additionalProperties.apicurio.registry.url={{registryurl}}";
registryconfig +="&additionalProperties.apicurio.registry.global-id={{globalid}}";
//ProtobufDataFormat format = new ProtobufDataFormat("demo.camel.TransactionProtos$Transaction");
restConfiguration().component("netty-http").host("localhost").port("8081").bindingMode(RestBindingMode.auto);
rest("/").post("transfer").consumes("application/json").to("direct:transfer");
from("direct:transfer")
.setHeader("sender",jsonpath("$.sender.userid"))
.marshal().protobuf("demo.camel.TransactionProtos$Transaction")
.bean(demo.camel.TransactionProtos.Transaction.class, "parseFrom(${body})")
.toD("kafka:webtrans?key=${header.sender}"+registryconfig)
.setBody(simple("Transaction from ${header.sender} sent."))
;
}
}
| true
|
fbe59c7dcc7b4f5d25eb4ceae9d7be1a4dd0157b
|
Java
|
andrevriibeiro/eventryapp-android
|
/app/src/main/java/br/com/eventryapp/adapter/PresentesAdapter.java
|
UTF-8
| 3,801
| 2.25
| 2
|
[] |
no_license
|
package br.com.eventryapp.adapter;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import br.com.eventryapp.R;
import br.com.eventryapp.manager.EventoManager;
import br.com.eventryapp.model.Evento;
import br.com.eventryapp.model.EventoPresente;
import br.com.eventryapp.model.Presente;
import br.com.eventryapp.service.listener.EventoServiceListener;
import okhttp3.ResponseBody;
import retrofit2.Response;
public class PresentesAdapter extends RecyclerView.Adapter<PresentesAdapter.ViewHolder> {
private Evento evento;
public PresentesAdapter(Evento evento) {
this.evento = evento;
}
@NonNull
@Override
public PresentesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.presente_item,
parent, false);
return new PresentesAdapter.ViewHolder(itemView);
}
@Override
public void onBindViewHolder(PresentesAdapter.ViewHolder holder, final int position) {
final Presente presente = evento.getPresentes().get(position);
holder.mTextViewNomePresente.setText(presente.getNomepresente());
holder.mTextViewDescricaoPresente.setText(presente.getDescricao());
holder.mImageViewRemovePresente.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventoPresente eventoPresente = new EventoPresente();
eventoPresente.setEvento(evento);
eventoPresente.setPresente(presente);
final ProgressDialog progressDialog = new ProgressDialog(v.getContext());
progressDialog.setMessage(v.getContext().getString(R.string.removendo_presente));
progressDialog.show();
EventoManager eventoManager = new EventoManager(v.getContext());
eventoManager.deletarEventoPresente(eventoPresente, new EventoServiceListener() {
@Override
public void onSuccess(Evento evento) {}
@Override
public void onSuccess(Response response) {
evento.getPresentes().remove(presente);
notifyItemRemoved(position);
notifyItemRangeChanged(position,evento.getPresentes().size());
progressDialog.dismiss();
}
@Override
public void onSucess(ResponseBody responseBody) {
}
@Override
public void onSuccess(List<Evento> eventos) {}
@Override
public void onFail(Throwable t) {
}
});
}
});
}
@Override
public int getItemCount() {
return evento.getPresentes().size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewNomePresente;
public TextView mTextViewDescricaoPresente;
public ImageView mImageViewRemovePresente;
public ViewHolder(View itemView) {
super(itemView);
mImageViewRemovePresente = (ImageView) itemView.findViewById(R.id.image_view_remove);
mTextViewNomePresente = (TextView) itemView.findViewById(R.id.text_view_nome_presente);
mTextViewDescricaoPresente = (TextView) itemView.findViewById(R.id.text_view_descricao_presente);
}
}
}
| true
|
3f504b7a0c75822a45f13eb26eb4cd00ce917a17
|
Java
|
Tmdsb941/springbootesthree
|
/src/main/java/com/cs/springbootesthree/service/KaoshiService.java
|
UTF-8
| 321
| 1.882813
| 2
|
[] |
no_license
|
package com.cs.springbootesthree.service;
import com.cs.springbootesthree.pojo.Kaoshi;
import org.springframework.stereotype.Service;
import java.util.List;
public interface KaoshiService {
Kaoshi login(String ksname,String kspwd);
int del(int ksid);
Kaoshi ist(Kaoshi kaoshi);
List<Kaoshi> ALL();
}
| true
|
37e9b2634c553ab5af36ad0910836f38dc39f0b7
|
Java
|
rhawan/microservices-tcc-alfa
|
/sales-microservices-resourceserver-cliente/src/main/java/br/alfa/sales/util/CargaCliente.java
|
UTF-8
| 2,940
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package br.alfa.sales.util;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.alfa.sales.model.Cliente;
import br.alfa.sales.model.TipoPessoa;
import br.alfa.sales.model.UF;
import br.alfa.sales.repository.ClienteRepository;
@Component
public class CargaCliente {
private static final String NOME_ARQUIVO = "carga_clientes.txt";
@Autowired
private ClienteRepository clienteRepository;
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy") ;
public void realizarCargaArquivo() {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(NOME_ARQUIVO).getFile());
LineIterator it = null;
try {
it = FileUtils.lineIterator(file, "UTF-8");
while(it.hasNext()) {
String linha = it.nextLine();
String[] dados = linha.split("\\|");
inserirCliente(dados[0], dados[1], dados[2], dados[3], dados[4],
dados[5], dados[6], dados[7], dados[8], dados[9]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
it.close();
}
}
protected void inserirCliente(String nome, String cpfCnpj, String tipoPessoa,
String telefone, String endereco, String cidade,
String uf, String email, String valorLimiteCredito, String dataUltimaCompra) {
try {
Cliente cliente = getClienteExistente(cpfCnpj);
if (cliente == null) {
TipoPessoa tipoPessoaEnum = TipoPessoa.valueOf(tipoPessoa);
UF ufEnum = UF.valueOf(uf);
BigDecimal valorLimiteCred = new BigDecimal(valorLimiteCredito.replace(",", "."));
LocalDate dataUltCompra = LocalDate.parse(dataUltimaCompra, FORMATTER);
clienteRepository.save(criarCliente(nome, cpfCnpj, tipoPessoaEnum,
telefone, endereco, cidade, ufEnum, email, valorLimiteCred, dataUltCompra));
System.out.printf("Inserindo cliente -> CPF/CNPJ: %s Nome: %s ", cpfCnpj, nome);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
private Cliente getClienteExistente(String cpfCnpj) {
return clienteRepository.findByCpfCnpj(cpfCnpj);
}
private Cliente criarCliente(String nome, String cpfCnpj, TipoPessoa tipoPessoa,
String telefone, String endereco, String cidade, UF uf,
String email, BigDecimal valorLimiteCredito, LocalDate dataUltimaCompra) {
Cliente cliente = new Cliente();
cliente.setNome(nome);
cliente.setCpfCnpj(cpfCnpj);
cliente.setTipoPessoa(tipoPessoa);
cliente.setTelefone(telefone);
cliente.setEndereco(endereco);
cliente.setCidade(cidade);
cliente.setUF(uf);
cliente.setEmail(email);
cliente.setValorLimiteCredito(valorLimiteCredito);
cliente.setDataUltimaCompra(dataUltimaCompra);
return cliente;
}
}
| true
|
3528675361fa6996de586db3f3e1142ace7a2e3f
|
Java
|
ParthPancholi/janrain4j
|
/src/main/java/com/googlecode/janrain4j/springframework/EngagePartnerServiceFactoryBean.java
|
UTF-8
| 2,262
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/* Copyright 2011 Sergey Tsymbler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.janrain4j.springframework;
import com.googlecode.janrain4j.api.engage.EngagePartnerService;
import com.googlecode.janrain4j.api.engage.EngagePartnerServiceFactory;
import com.googlecode.janrain4j.conf.Config;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
* {@link org.springframework.beans.factory.FactoryBean} that sets up an {@link com.googlecode.janrain4j.api.engage.EngagePartnerService} and exposes it for
* bean references.
*
* <p>Usage example:
* <pre>
* <bean class="com.googlecode.janrain4j.springframework.EngagePartnerServiceFactoryBean" />
* </pre>
*
* @author Sergey Tsymbler
* @since 1.2
*/
public class EngagePartnerServiceFactoryBean implements FactoryBean<EngagePartnerService>, InitializingBean {
private EngagePartnerService engagePartnerService = null;
private Config config = null;
public EngagePartnerService getObject() throws Exception {
return engagePartnerService;
}
public Class<? extends EngagePartnerService> getObjectType() {
return EngagePartnerService.class;
}
public boolean isSingleton() {
return true;
}
public void afterPropertiesSet() throws Exception {
if (config == null) {
engagePartnerService = EngagePartnerServiceFactory.getEngagePartnerService();
}
else {
engagePartnerService = EngagePartnerServiceFactory.getEngagePartnerService(config);
}
}
public void setConfig(Config config) {
this.config = config;
}
}
| true
|
c749e6c76a234396e393cdc4dfca13a2aad72cf3
|
Java
|
christopherdavid/hybrid_app
|
/Android/SlideAndroidPlugins/src/com/neatorobotics/android/slide/framework/pluginhelper/ErrorTypes.java
|
UTF-8
| 5,587
| 2.25
| 2
|
[] |
no_license
|
package com.neatorobotics.android.slide.framework.pluginhelper;
public class ErrorTypes {
public static final int ERROR_TYPE_UNKNOWN = -501;
public static final int ERROR_NETWORK_ERROR = -502;
public static final int JSON_PARSING_ERROR = -503;
public static final int INVALID_SCHEDULE_ID = -504;
public static final int INVALID_EVENT_ID = -505;
public static final int ERROR_DB_ERROR = -506;
public static final int JSON_CREATION_ERROR = -507;
public static final int INVALID_PARAMETER = -508;
public static final int ERROR_TYPE_USER_UNAUTHORIZED = -509;
public static final int ROBOT_NOT_CONNECTED = -511;
public static final int ROBOT_ALREADY_CONNECTED = -512;
public static final int DIFFERENT_ROBOT_ALREADY_CONNECTED = -515;
public static final int ERROR_TYPE_WIFI_NOT_CONNECTED = -516;
public static final int ERROR_TYPE_NETWORK_INFO_NOT_SET = -519;
/**
* Authentication of the user failed. - This will occur when the email
* and/or the password is incorrect while Logging-in. - This will occur if
* the authentication token has expired. In this case the user will need to
* login again with the correct credentials.
*/
public static final int ERROR_AUTHENTICATION_FAILED = -101;
/**
* Email id entered does not match the usual format of the email id.
*
*/
public static final int ERROR_INVALID_EMAIL_ID = -105;
/**
* Email id is already registered with the server. - This will occur while
* creating a user account with already registered user email id. The user
* needs to provide a email id which is not already registered.
*/
public static final int ERROR_EMAIL_ALREADY_REGISTERED = -106;
/**
* Create User failed due to some unknown server error. - User should retry.
*/
public static final int ERROR_CREATE_USER_FAILED_TRY_AGAIN = -108;
/**
* Old password does not match to the current password of the user. - To
* change the password, user needs to provide the current password. If
* entered password does not match the current password,
* ERROR_OLD_PASSWORD_MISMATCH error is returned
*/
public static final int ERROR_OLD_PASSWORD_MISMATCH = -110;
/**
* Robot name value entered is empty - This will occur when Robot name value
* is entered empty. User should enter a non-empty for the robot name.
*/
public static final int ERROR_INVALID_ROBOT_ACCOUNT_DETAIL = -111;
/**
* Email id not found on the server. - This will occur when the user sends a
* forgot password request and email id given isn't registered on the
* server.
*/
public static final int ERROR_EMAIL_NOT_REGISTERED = -112;
/**
* Robot id not found on the server. - This will occur while associating a
* robot with the user.
*/
public static final int ERROR_ROBOT_NOT_REGISTERED = -114;
/**
* Alternate email id entered does not match the usual format of the email
* id.
*/
public static final int ERROR_INVALID_ALTERNATE_EMAIL_ID = -115;
/**
* Resend validation-email limit reached. - This will occur when the
* validation email sending limit is reached. Currently the limit is 5.
*/
public static final int ERROR_RESEND_VALIDATION_EMAIL_LIMIT_REACHED = -116;
/**
* Email Id already validated. - This will occur if the user requests to
* send a validation email, but the email is already validated on the
* server.
*/
public static final int ERROR_EMAIL_ALREADY_VALIDATED = -117;
/**
* Schedule version does not match. Please retrieve the latest schedule and
* then edit. - This will occur if the user does not have the latest
* schedule and the user tries to edit it (Some other user edited the
* schedule persay). The application should request for the latest schedule
* so that the user can then edit the same.
*/
public static final int ERROR_SCHEDULE_VERSION_MISMATCH = -129;
/**
* Schedule type is not supported. - This will occur if the application
* sends an invalid schedule type to the plugin layer. Currently supported
* schedule type is Basic schedule.
*/
public static final int ERROR_INVALID_SCHEDULE_TYPE = -133;
/**
* Invalid linking code. - This will occur if the user enters an invalid
* linking code.
*/
public static final int ERROR_INVALID_LINKING_CODE = -154;
/**
* Linking code expired. - This happens if the user hasn't entered the
* linking code before the timeout.
*/
public static final int ERROR_LINKING_CODE_EXPIRED = -155;
/**
* No schedule exists for given robot. - This will occur if there is no
* schedule for the robot. The user/application should create a new
* schedule.
*/
public static final int ERROR_NO_SCHEDULE_FOR_GIVEN_ROBOT = -159;
/**
* Linking code already in use. - This results if the linking code is
* already used for association.
*/
public static final int ERROR_LINKING_CODE_IN_USE = -180;
/**
* Association is already present for robot and user
*/
public static final int ERROR_ROBOT_USER_ASSOCIATION_ALREADY_EXISTS = -182;
/**
* Robot already has some other user associated with it.
*/
public static final int ERROR_ROBOT_HAS_ASSOCIATED_USER = -192;
}
| true
|
a95ae38bbeeeb65d3a88a7336b889a8232787599
|
Java
|
OSrcD/java-for-linux
|
/java-for-gitee/Test/src/KeyboardEventListener.java
|
UTF-8
| 927
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import java.util.*;
public interface KeyboardEventListener extends EventListener {
public void GlobalKeyPressed(KeyboardEvent event);
public void GlobalKeyReleased(KeyboardEvent event);
}
class KeyboardEvent extends EventObject {
private static final long serialVersionUID = 2341653211621224652L;
boolean ts, ap, ek;
int vk;
public KeyboardEvent(Object source, boolean ts, int vk, boolean ap, boolean ek) {
super(source);
this.ts = ts;
this.vk = vk;
this.ap = ap;
this.ek = ek;
}
public boolean getTransitionState() {
return ts;
}
public long getVirtualKeyCode() {
return vk;
}
public boolean isAltPressed() {
return ap;
}
public boolean isExtendedKey() {
return ek;
}
public boolean equals(KeyboardEvent event) {
if (event.getVirtualKeyCode() == vk) {
if (event.isExtendedKey() == ek) {
if (event.isAltPressed() == ap) {
return true;
}
}
}
return false;
}
}
| true
|
2d44ff821e2d18376b02609c7531d6a27a306729
|
Java
|
xSke/CoreServer
|
/src/mikera/vectorz/impl/JoinedMultiVector.java
|
UTF-8
| 17,652
| 2.171875
| 2
|
[] |
no_license
|
/*
* Decompiled with CFR 0_129.
*/
package mikera.vectorz.impl;
import java.nio.DoubleBuffer;
import mikera.arrayz.INDArray;
import mikera.vectorz.AVector;
import mikera.vectorz.Op;
import mikera.vectorz.impl.ADenseArrayVector;
import mikera.vectorz.impl.AJoinedVector;
import mikera.vectorz.impl.JoinedVector;
import mikera.vectorz.impl.Vector0;
import mikera.vectorz.util.ErrorMessages;
import mikera.vectorz.util.IntArrays;
import mikera.vectorz.util.VectorzException;
public final class JoinedMultiVector
extends AJoinedVector {
private static final long serialVersionUID = 6226205676178066609L;
private final int n;
private final AVector[] vecs;
private final int[] splits;
private JoinedMultiVector(int length, AVector[] vecs, int[] splits) {
super(length);
this.n = vecs.length;
this.vecs = vecs;
this.splits = splits;
}
private JoinedMultiVector(AVector[] vs) {
this(JoinedMultiVector.sumOfLengths(vs), vs, new int[vs.length + 1]);
int j = 0;
for (int i = 0; i < this.n; ++i) {
this.splits[i + 1] = j += vs[i].length();
}
}
private static final int sumOfLengths(AVector[] vs) {
int result = 0;
for (AVector v : vs) {
result += v.length();
}
return result;
}
@Override
public boolean isFullyMutable() {
for (AVector v : this.vecs) {
if (v.isFullyMutable()) continue;
return false;
}
return true;
}
@Override
public void copyTo(AVector dest, int offset) {
for (AVector v : this.vecs) {
v.copyTo(dest, offset);
offset += v.length();
}
}
@Override
public void toDoubleBuffer(DoubleBuffer dest) {
for (AVector v : this.vecs) {
v.toDoubleBuffer(dest);
}
}
@Override
public void addToArray(int offset, double[] array, int arrayOffset, int length) {
int i2;
int start = offset;
int end = start + length;
if (start < 0 || end > this.length || length < 0) {
throw new IndexOutOfBoundsException(ErrorMessages.invalidRange(this, offset, length));
}
int i1 = IntArrays.indexLookup(this.splits, start);
if (i1 == (i2 = IntArrays.indexLookup(this.splits, end - 1))) {
this.vecs[i1].addToArray(offset -= this.splits[i1], array, arrayOffset, length);
return;
}
this.vecs[i1].addToArray(offset - this.splits[i1], array, arrayOffset, this.splits[i1 + 1] - offset);
this.vecs[i2].addToArray(0, array, arrayOffset + this.splits[i2] - offset, end - this.splits[i2]);
for (int i = i1 + 1; i < i2; ++i) {
int io = this.splits[i] - offset;
this.vecs[i].addToArray(array, arrayOffset + io);
}
}
@Override
public void addToArray(double[] dest, int offset, int stride) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].addToArray(dest, offset + stride * this.splits[i], stride);
}
}
@Override
public void addMultipleToArray(double factor, int offset, double[] array, int arrayOffset, int length) {
int i2;
int start = offset;
int end = start + length;
if (start < 0 || end > this.length || length < 0) {
throw new IndexOutOfBoundsException(ErrorMessages.invalidRange(this, offset, length));
}
int i1 = IntArrays.indexLookup(this.splits, start);
if (i1 == (i2 = IntArrays.indexLookup(this.splits, end - 1))) {
this.vecs[i1].addMultipleToArray(factor, offset -= this.splits[i1], array, arrayOffset, length);
return;
}
this.vecs[i1].addMultipleToArray(factor, offset - this.splits[i1], array, arrayOffset, this.splits[i1 + 1] - offset);
this.vecs[i2].addMultipleToArray(factor, 0, array, arrayOffset + this.splits[i2] - offset, end - this.splits[i2]);
for (int i = i1 + 1; i < i2; ++i) {
int io = this.splits[i] - offset;
this.vecs[i].addMultipleToArray(factor, 0, array, arrayOffset + io, this.vecs[i].length());
}
}
@Override
public void addAt(int i, double v) {
int j = IntArrays.indexLookup(this.splits, i);
int joff = i - this.splits[j];
this.vecs[j].addAt(joff, v);
}
@Override
public void getElements(double[] data, int offset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].getElements(data, offset + this.splits[i]);
}
}
@Override
public void multiplyTo(double[] data, int offset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].multiplyTo(data, offset + this.splits[i]);
}
}
@Override
public void divideTo(double[] data, int offset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].divideTo(data, offset + this.splits[i]);
}
}
@Override
public void copyTo(int start, AVector dest, int destOffset, int length) {
this.subVector(start, length).copyTo(dest, destOffset);
}
@Override
public AVector subVector(int start, int length) {
int i2;
int end = start + length;
if (length == 0) {
return Vector0.INSTANCE;
}
if (start < 0 || end > this.length || length < 0) {
throw new IndexOutOfBoundsException(ErrorMessages.invalidRange(this, start, length));
}
if (length == this.length) {
return this;
}
int i1 = IntArrays.indexLookup(this.splits, start);
if (i1 == (i2 = IntArrays.indexLookup(this.splits, end - 1))) {
return this.vecs[i1].subVector(start - this.splits[i1], length);
}
int nn = i2 - i1 + 1;
AVector[] nvecs = new AVector[nn];
nvecs[0] = this.vecs[i1].subVector(start - this.splits[i1], this.splits[i1 + 1] - start);
nvecs[nn - 1] = this.vecs[i2].subVector(0, end - this.splits[i2]);
for (int i = 1; i < i2 - i1; ++i) {
nvecs[i] = this.vecs[i1 + i];
}
return new JoinedMultiVector(nvecs);
}
@Override
public AVector tryEfficientJoin(AVector v) {
if (v instanceof JoinedMultiVector) {
return this.join((JoinedMultiVector)v);
}
if (v instanceof JoinedVector) {
return this.join((JoinedVector)v);
}
AVector ej = this.vecs[this.n - 1].tryEfficientJoin(v);
if (ej != null) {
AVector[] nvecs = (AVector[])this.vecs.clone();
nvecs[this.n - 1] = ej;
return new JoinedMultiVector(nvecs);
}
AVector[] nvecs = new AVector[this.n + 1];
System.arraycopy(this.vecs, 0, nvecs, 0, this.n);
nvecs[this.n] = v;
return new JoinedMultiVector(nvecs);
}
public AVector join(JoinedMultiVector v) {
AVector[] nvecs = new AVector[this.n + v.n];
System.arraycopy(this.vecs, 0, nvecs, 0, this.n);
System.arraycopy(v.vecs, 0, nvecs, this.n, v.n);
return new JoinedMultiVector(nvecs);
}
public AVector join(JoinedVector v) {
AVector ej = this.vecs[this.n - 1].tryEfficientJoin(v.left);
if (ej != null) {
AVector[] nvecs = new AVector[this.n + 1];
System.arraycopy(this.vecs, 0, nvecs, 0, this.n);
nvecs[this.n - 1] = ej;
nvecs[this.n] = v.right;
return new JoinedMultiVector(nvecs);
}
AVector[] nvecs = new AVector[this.n + 2];
System.arraycopy(this.vecs, 0, nvecs, 0, this.n);
nvecs[this.n] = v.left;
nvecs[this.n + 1] = v.right;
return new JoinedMultiVector(nvecs);
}
@Override
public void add(AVector a) {
assert (this.length() == a.length());
if (a instanceof JoinedMultiVector) {
this.add((JoinedMultiVector)a);
} else {
this.add(a, 0);
}
}
public void add(JoinedMultiVector a) {
if (IntArrays.equals(this.splits, a.splits)) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].add(a.vecs[i]);
}
} else {
this.add(a, 0);
}
}
@Override
public void scaleAdd(double factor, double constant) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].scaleAdd(factor, constant);
}
}
@Override
public void add(double constant) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].add(constant);
}
}
@Override
public void reciprocal() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].reciprocal();
}
}
@Override
public void clamp(double min, double max) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].clamp(min, max);
}
}
@Override
public double dotProduct(AVector v) {
if (v instanceof ADenseArrayVector) {
ADenseArrayVector av = (ADenseArrayVector)v;
return this.dotProduct(av.getArray(), av.getArrayOffset());
}
return super.dotProduct(v);
}
@Override
public double dotProduct(double[] data, int offset) {
double result = 0.0;
for (int i = 0; i < this.n; ++i) {
result += this.vecs[i].dotProduct(data, offset + this.splits[i]);
}
return result;
}
@Override
public void add(AVector a, int aOffset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].add(a, aOffset + this.splits[i]);
}
}
@Override
public void add(double[] data, int offset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].add(data, offset + this.splits[i]);
}
}
@Override
public void add(int offset, AVector a) {
this.add(offset, a, 0, a.length());
}
@Override
public void addMultiple(AVector a, double factor) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].addMultiple(a, this.splits[i], factor);
}
}
@Override
public void addMultiple(AVector a, int aOffset, double factor) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].addMultiple(a, aOffset + this.splits[i], factor);
}
}
@Override
public void addProduct(AVector a, AVector b, double factor) {
for (int i = 0; i < this.n; ++i) {
int off = this.splits[i];
this.vecs[i].addProduct(a, off, b, off, factor);
}
}
@Override
public void addProduct(AVector a, int aOffset, AVector b, int bOffset, double factor) {
for (int i = 0; i < this.n; ++i) {
int off = this.splits[i];
this.vecs[i].addProduct(a, aOffset + off, b, bOffset + off, factor);
}
}
@Override
public void signum() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].signum();
}
}
@Override
public void abs() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].abs();
}
}
@Override
public void exp() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].exp();
}
}
@Override
public void log() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].log();
}
}
@Override
public void negate() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].negate();
}
}
@Override
public void applyOp(Op op) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].applyOp(op);
}
}
@Override
public double elementSum() {
double result = 0.0;
for (int i = 0; i < this.n; ++i) {
result += this.vecs[i].elementSum();
}
return result;
}
@Override
public double elementProduct() {
double result = 1.0;
for (int i = 0; i < this.n; ++i) {
if ((result *= this.vecs[i].elementProduct()) != 0.0) continue;
return 0.0;
}
return result;
}
@Override
public double elementMax() {
double result = this.vecs[0].elementMax();
for (int i = 0; i < this.n; ++i) {
double m = this.vecs[i].elementMax();
if (m <= result) continue;
result = m;
}
return result;
}
@Override
public double elementMin() {
double result = this.vecs[0].elementMin();
for (int i = 0; i < this.n; ++i) {
double m = this.vecs[i].elementMin();
if (m >= result) continue;
result = m;
}
return result;
}
@Override
public double magnitudeSquared() {
double result = 0.0;
for (int i = 0; i < this.n; ++i) {
result += this.vecs[i].magnitudeSquared();
}
return result;
}
@Override
public long nonZeroCount() {
long result = 0L;
for (int i = 0; i < this.n; ++i) {
result += this.vecs[i].nonZeroCount();
}
return result;
}
@Override
public double get(int i) {
this.checkIndex(i);
int j = IntArrays.indexLookup(this.splits, i);
return this.vecs[j].unsafeGet(i - this.splits[j]);
}
@Override
public void set(AVector src) {
this.checkSameLength(src);
this.set(src, 0);
}
@Override
public double unsafeGet(int i) {
int j = IntArrays.indexLookup(this.splits, i);
return this.vecs[j].unsafeGet(i - this.splits[j]);
}
@Override
public void set(AVector src, int srcOffset) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].set(src, srcOffset + this.splits[i]);
}
}
@Override
public void set(int i, double value) {
this.checkIndex(i);
this.unsafeSet(i, value);
}
@Override
public void unsafeSet(int i, double value) {
int j = IntArrays.indexLookup(this.splits, i);
this.vecs[j].unsafeSet(i - this.splits[j], value);
}
@Override
public void fill(double value) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].fill(value);
}
}
@Override
public void square() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].square();
}
}
@Override
public void sqrt() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].sqrt();
}
}
@Override
public void tanh() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].tanh();
}
}
@Override
public void logistic() {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].logistic();
}
}
@Override
public void multiply(double value) {
for (int i = 0; i < this.n; ++i) {
this.vecs[i].multiply(value);
}
}
@Override
public double[] toDoubleArray() {
double[] data = new double[this.length];
for (int i = 0; i < this.n; ++i) {
this.vecs[i].copyTo(data, this.splits[i]);
}
return data;
}
@Override
public boolean equals(AVector v) {
if (v instanceof JoinedMultiVector) {
return this.equals((JoinedMultiVector)v);
}
if (v instanceof ADenseArrayVector) {
ADenseArrayVector av = (ADenseArrayVector)v;
return this.equalsArray(av.getArray(), av.getArrayOffset());
}
return super.equals(v);
}
public boolean equals(JoinedMultiVector v) {
if (IntArrays.equals(this.splits, v.splits)) {
for (int i = 0; i < this.n; ++i) {
if (this.vecs[i].equals(v.vecs[i])) continue;
return false;
}
}
return super.equals(v);
}
@Override
public boolean equalsArray(double[] data, int offset) {
for (int i = 0; i < this.n; ++i) {
if (this.vecs[i].equalsArray(data, offset + this.splits[i])) continue;
return false;
}
return true;
}
@Override
public JoinedMultiVector exactClone() {
AVector[] nvecs = new AVector[this.n];
for (int i = 0; i < this.n; ++i) {
nvecs[i] = this.vecs[i].exactClone();
}
return new JoinedMultiVector(nvecs);
}
public static /* varargs */ AVector wrap(AVector ... vecs) {
return new JoinedMultiVector(vecs);
}
public static /* varargs */ AVector create(AVector ... vecs) {
return new JoinedMultiVector((AVector[])vecs.clone());
}
@Override
public void validate() {
super.validate();
if (this.splits[this.n] != this.length) {
throw new VectorzException("Unexpected final slit position - not equal to JoinedMultVector length");
}
}
@Override
public int componentCount() {
return this.n;
}
@Override
public AVector getComponent(int k) {
return this.vecs[k];
}
@Override
public AJoinedVector withComponents(INDArray[] segments) {
AVector[] nvecs = new AVector[this.n];
for (int i = 0; i < this.n; ++i) {
AVector v;
INDArray a = segments[i];
if (!this.isSameShape(a)) {
throw new IllegalArgumentException(ErrorMessages.incompatibleShapes(this, a));
}
nvecs[i] = v = segments[i].asVector();
}
return new JoinedMultiVector(this.length, nvecs, this.splits);
}
}
| true
|
2ff977e5c1a88abd24fd44ba651d11338b9c5f0f
|
Java
|
morristech/orcller_android
|
/android/Orcller/app/src/main/java/com/orcller/app/orcller/model/Album.java
|
UTF-8
| 2,703
| 1.984375
| 2
|
[] |
no_license
|
package com.orcller.app.orcller.model;
import android.text.TextUtils;
import com.orcller.app.orcller.R;
import com.orcller.app.orcllermodules.model.User;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;
import pisces.psfoundation.ext.Application;
import pisces.psfoundation.utils.DateUtil;
/**
* Created by pisces on 11/15/15.
*/
public class Album extends AlbumInfo {
public enum Permission {
None(0),
Public(1),
Followers(2),
Private(3);
private int value;
private Permission(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public enum ReportType {
Inappropriate(1);
private int value;
private ReportType(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public boolean page_replace_enabled;
public int default_page_index;
public int permission;
public String desc;
public String encrypted_id;
public String name;
public Comments comments = new Comments();
public Contributors contributors = new Contributors();
public Favorites favorites = new Favorites();
public Likes likes = new Likes();
public Pages pages = new Pages();
public Album() {
super();
init(null);
}
public Album(User user) {
super();
init(user);
}
public Page getCover() {
return pages.data.size() > 0 ? pages.data.get(0) : null;
}
public String getViewName() {
return TextUtils.isEmpty(name) ?
Application.applicationContext().getResources().getString(R.string.w_untitled) :
name;
}
private void init(User user) {
Locale locale = Application.applicationContext().getResources().getConfiguration().locale;
Pattern pattern = Pattern.compile("(.*)ko(.*)");
String formatString = "MMM d, yyyy aaa";
if (pattern.matcher(locale.getLanguage()).matches())
formatString = "yyyy년 M월 d일 aaa";
name = new SimpleDateFormat(formatString).format(new Date());
id = DateUtil.toUnixtimestamp(new Date());
if (user != null) {
this.user = user;
permission = user.user_options.album_permission;
user_uid = user.user_uid;
user_id = user.user_id;
user_link = user.user_link;
user_name = user.user_name;
user_picture = user.user_picture;
}
}
}
| true
|
29053681ed10b360a6347a9f5c7ec2fb2f06702a
|
Java
|
BashkoAnastasya/Java
|
/MaxMin/anastasiya/Number.java
|
UTF-8
| 300
| 2.5625
| 3
|
[] |
no_license
|
package com.intexsoft.bashko.anastasiya;
public class Number {
private int number;
private int length;
public Number(int number, int length) {
this.number=number;
this.length=length;
}
public int getLength() {
return length;
}
public int getnumber() {
return number;
}
}
| true
|
d9df69aa4f34d667d7cbdfc3b799f4592d20def5
|
Java
|
raziullahkhan/Java
|
/UdemyJava+Andr/src/Java_and1/WorkingWithFiles.java
|
UTF-8
| 506
| 3.3125
| 3
|
[] |
no_license
|
package Java_and1;
import java.io.IOException;
import java.io.PrintWriter;
public class WorkingWithFiles {
public static void main(String[] args) throws IOException{
//create the file and open the file
//if the file exist it will replace the file
PrintWriter outputFile=new PrintWriter("Output.txt");
outputFile.println("This is line 1");
outputFile.println("This is line 2");
outputFile.println("THis is line 3");
outputFile.close();
}
}
| true
|
d773c741920ab23f1064fc182b01fda9fc24270c
|
Java
|
sandervalstar/java-spring-basics
|
/labs/03-spring-application-context/exercise-7/src/main/java/domain/Sugar.java
|
UTF-8
| 132
| 2.328125
| 2
|
[] |
no_license
|
package domain;
public class Sugar extends Ingredient {
public Sugar(long id, String name) {
super(id, name);
}
}
| true
|
2dde6ce995a5c18a7f9b9f918e262295f0a22509
|
Java
|
anyjava/springboot-study
|
/spring-boot-test/src/test/java/dev/anyjava/springboot/test/domain/EmployeeRepositoryTest.java
|
UTF-8
| 928
| 2.15625
| 2
|
[] |
no_license
|
package dev.anyjava.springboot.test.domain;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class EmployeeRepositoryTest {
private static final Long ANY_EMPLOYEE_ID = 1L;
@Autowired
private EmployeeRepository employeeRepository;
@DatabaseSetup("/dbunit/employee.xml")
@Test
public void testFindById() {
Employee employee = employeeRepository.findById(ANY_EMPLOYEE_ID).orElse(null);
assertThat(employee).isNotNull();
}
}
| true
|
26c1afd97c9f590a958681ff55bb6ef19b7e5db1
|
Java
|
bhagyaperera123/POS-System
|
/test/BPos/Model/CustomerTest.java
|
UTF-8
| 1,447
| 2.609375
| 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 BPos.Model;
//
//import BPos.DB.Customer;
//import org.junit.AfterClass;
//import org.junit.BeforeClass;
//import org.junit.Test;
//import static org.junit.Assert.*;
//
///**
// *
// * @author Bhagya
// */
//public class CustomerTest {
//
// public CustomerTest() {
// }
//
// @BeforeClass
// public static void setUpClass() {
// }
//
// @AfterClass
// public static void tearDownClass() {
// }
//
// /**
// * Test of saveCustomer method, of class Customer.
// */
// @Test
// public void testSaveCustomer() {
// System.out.println("saveCustomer");
// Customer c = new Customer();
// c.setName("Amal");
// c.setMobile("0719877862");
// BPos.Model.Customer instance = new BPos.Model.Customer();
// instance.saveCustomer(c);
// }
//
// @Test
// public void testGetcustomer() {
// System.out.println("getcustomer");
// String mob = "0719877863";
// BPos.Model.Customer instance = new BPos.Model.Customer();
// Customer expResult = null;
// Customer result = instance.getcustomer(mob);
// assertEquals(mob, result.getMobile());
// }
//
//}
| true
|
e7c99ee0abdd0181ca0909e986619d3ffe9fb948
|
Java
|
entrudo/Autotest
|
/src/com/company/Lessons_home_Work/Lesson15_Less_Work/Task2/Enum/RunOn.java
|
UTF-8
| 222
| 2.296875
| 2
|
[] |
no_license
|
package com.company.Lessons_home_Work.Lesson15_Less_Work.Task2.Enum;
public enum RunOn {
LOCAL,
BUILDSERVER,
REMONE;
public static RunOn getString (String str){
return RunOn.valueOf(str);
}
}
| true
|
71576835d6d8df106709f1395d505d9ac056e194
|
Java
|
Ball-ll/MavenSpringSSM
|
/src/main/java/com/service/TestService.java
|
UTF-8
| 171
| 1.71875
| 2
|
[] |
no_license
|
package com.service;
import java.util.List;
import com.entitys.TestEntity;
public interface TestService{
public List<TestEntity> find(TestEntity testinfo);
}
| true
|
f58abbcddffbeff61e57dbbdf706abb5f382ad93
|
Java
|
wushiba/source-code
|
/com.yd.parent/com.yd.service/src/main/java/com/yd/service/crawer/TmallBijiaProcess.java
|
UTF-8
| 4,955
| 1.992188
| 2
|
[] |
no_license
|
package com.yd.service.crawer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.yd.api.crawer.BijiaProcess;
import com.yd.api.crawer.result.CrawerSiteBrandResult;
import com.yd.service.crawer.bean.CrawerTmallItem;
import com.yd.service.crawer.dao.CrawerTmallItemDao;
import com.yd.service.crawer.util.MockViewHelper;
//@Service
public class TmallBijiaProcess implements BijiaProcess{
@Resource
private CrawerTmallItemDao crawerTmallItemDao;
@Override
public boolean isSite(String site) {
return "天猫".equals(site);
}
public static String getUrl(String url, Map<String, String> params){
StringBuilder str = new StringBuilder();
str.append(url);
boolean first = true;
for (String key : params.keySet()) {
if (first) {
first = false;
str.append("?");
} else {
str.append("&");
}
str.append(key).append("=").append(params.get(key));
}
return str.toString();
}
public static Map<String,String> getParam(String url){
Map<String,String> param=new HashMap<String,String>();
String p=url.substring(url.indexOf("?"));
for(String str:p.split("&")) {
try {
String name=str.split("=")[0];
String value=str.split("=")[1];
param.put(name, value);
}catch(Exception e) {
}
}
return param;
}
public static String getPath(String url){
String p=url.substring(0,url.indexOf("?"));
return p;
}
@Override
public void getExecuteSku(CrawerSiteBrandResult brand) {
System.out.println("==============brand:"+JSONObject.toJSONString(brand));
for(int pageNo=1;pageNo<=10;pageNo++) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String path=getPath(brand.getSearchUrl());
Map<String,String> param=getParam(brand.getSearchUrl());
param.put("pageNo", pageNo+"");
String newUrl=getUrl(path, param);
int count=viewPerPage(newUrl, brand.getIndexUrl(), brand);
if(count<8) {
break;
}
}
}
public int viewPerPage(String url,String referer,CrawerSiteBrandResult brand) {
System.out.println("url==="+url);
String body=MockViewHelper.views(url, referer,getCookies()).getBody();
int index1=body.indexOf("(");
int index2=body.lastIndexOf(")");
body=body.substring(index1+2, index2).replaceAll("\\"", "");
body=body.replaceAll("\\"", "").replaceAll("\\\"", "\"");
System.out.println(body);
Document doc=Jsoup.parse(body);
if(doc.getElementsByAttributeValueContaining("class", "J_TItems").size()==0) {
return 0;
}
Element container=doc.getElementsByAttributeValueContaining("class", "J_TItems").get(0);
Elements itemList=container.getElementsByAttributeValueContaining("class", "item ");
System.out.println("itemList size:"+itemList.size());
int count=0;
for(int i=0;i<itemList.size();i++) {
String itemId=itemList.get(i).attr("data-id");
if(StringUtils.isNotEmpty(itemId)) {
count++;
itemId=itemId.replaceAll("\\\"", "");
System.out.println("itemId:"+itemId.substring(1,itemId.length()-1));
CrawerTmallItem param=new CrawerTmallItem();
param.setBrand(brand.getBrand());
param.setSiteName(brand.getSiteName());
param.setItemId(itemId.substring(1,itemId.length()-1));
param.setCreateTime(new Date());
try {
crawerTmallItemDao.insert(param);
}catch(Exception e) {
}
}
}
return count;
}
public static Map<String,String> getCookies(){
Map<String,String> cookie=new HashMap<String,String>();
String str="hng=CN%7Czh-CN%7CCNY%7C156; lid=%E5%85%A8%E5%8A%9B%E4%BB%A5%E8%B5%B4%E6%88%91%E4%BB%AC%E5%BF%83%E4%B8%AD%E7%9A%84%E6%A2%A6; enc=bIAyR%2FBDEqid2D2ubLsJLk8hXxaqqDyAuo%2FDu2faPxLFNHtGnpxzmBZEEGfpWkAAIsLYtmZgph0xb%2FhQY5kQZg%3D%3D; cna=lE40FmWCiVACATy6H9jH1mMh; _m_h5_tk=e0b812c93921688de848e50447a85625_1574932078803; _m_h5_tk_enc=7a68f07c7552f8d9235010abdc9d9187; cq=ccp%3D1; pnm_cku822=; t=6e6d142f9e1f83c2adbaf9fdd61b03ad; tracknick=%5Cu5168%5Cu529B%5Cu4EE5%5Cu8D74%5Cu6211%5Cu4EEC%5Cu5FC3%5Cu4E2D%5Cu7684%5Cu68A6; _tb_token_=f6fa6e335d733; cookie2=1fa9b48f9f05a8d909454a571757ddf0; x5sec=7b2273686f7073797374656d3b32223a22316234616464623530616431666565316138343133643066613838613835383743506a506b753846455053712b356e53694d756553686f4b4e544d314d7a55774f5463374d513d3d227d; l=dBrXwpZgqnw2yhcNKOCanurza77OSIRYYuPzaNbMi_5Q86Ts_mQOk3FpmF96VjW5TaTB4s6vWjp9-etkZV6vA-eKo_Zp7n_qcFsB4; isg=BJGRzeUIqES3TMQZg2yE5XG6oJ3rVg7uU2N-a3Mmjth3GrFsu01YQWl8vK5ZEp2o";
String[] arr=str.split(";");
for(String items:arr) {
try {
String name=items.split("=")[0];
String value=items.split("=")[1];
cookie.put(name.trim(), value.trim());
}catch(Exception e) {
}
}
return cookie;
}
}
| true
|
1f353ed51dbeee3dc2398ddc286850b41933a398
|
Java
|
81219122/goods
|
/src/com/zhangrun/service/impl/UserService.java
|
UTF-8
| 5,368
| 2.59375
| 3
|
[] |
no_license
|
package com.zhangrun.service.impl;
import cn.itcast.commons.CommonUtils;
import com.zhangrun.dao.impl.UserDao;
import com.zhangrun.entity.User;
import com.zhangrun.exception.UserException;
import com.zhangrun.service.IUserService;
import com.zhangrun.utils.MailUtils;
import java.sql.SQLException;
/**
* @author zhangrun
* @version 1.0
* @date 2020/2/14 12:32
*/
public class UserService implements IUserService {
private UserDao userDao=new UserDao();
/*
* @Param [loginname]
* @return boolean
* 校验用户名是否存在
*/
@Override
public boolean validateLoginname(String loginname) {
try {
return userDao.findByName(loginname);
} catch (SQLException e) {
throw new RuntimeException (e);
}
}
/*
* @Param
*校验email是否存在
* @return boolean
*/
@Override
public boolean validateEmail(String email) {
try {
return userDao.findByEmail(email);
} catch (SQLException e) {
throw new RuntimeException (e);
}
}
//用户注册
@Override
public void regist(User user) {
user.setUid(CommonUtils.uuid());
user.setStatus(false);
user.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());
userDao.add(user); //新增
String content="<a href='http://localhost:8080/goods/userServlet?method=activation&activationCode="+user.getActivationCode()+"'>网上商城</a>";
MailUtils.sendMail(user.getEmail(),content,"激活邮件");
/*Properties properties=new Properties(); //根据类加载器读取配置文件到properties中
try {
properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
*//*
*登录邮件服务器,得到session
*//*
String host=properties.getProperty("host"); //服务器主机名
String name=properties.getProperty("username"); //登录名
String pass=properties.getProperty("password"); //登录密码
Session session= cn.itcast.mail.MailUtils.createSession(host,name,pass);
*//*
*创建mail 对象
*//*
String from=properties.getProperty("from");
String to=user.getEmail();
String subject=properties.getProperty("subject");
//MessageFormat.format()方法会把第一个参数中的{0}使用第二个参数来替换
String content= MessageFormat.format(properties.getProperty("content"),user.getActivationCode()); //把配置文件中{0}替换成user.getActivationCode()
Mail mail=new Mail(from,to,subject,content);
//发邮件
try {
MailUtils.send(session,mail);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}*/
}
@Override
public void activation(String activationCode) throws UserException {
/*
* 1. 通过激活码查询用户
* 2. 如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码)
* 3. 查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活)
* 4. 修改用户状态为true
*/
User user = userDao.findByCode(activationCode);
if(user == null) throw new UserException("无效的激活码!");
if(user.isStatus()) throw new UserException("您已经激活过了,不要二次激活!");
userDao.updataStatus(user.getUid(), true);//修改状态
}
/*
* @Param [user]
* @return com.zhangrun.entity.User
* 用户登录功能
*/
@Override
public User login(User user) {
return userDao.login(user.getLoginname(),user.getLoginpass());
}
/*
* @Param [uid, newPass, oldPass]
* @return void
* 修改密码功能
*/
@Override
public void updatePass(String uid, String newPass, String oldPass) throws UserException {
try {
boolean bool= false;
bool = userDao.findByuidAndPass(uid, oldPass);
if (!bool){
throw new UserException("旧密码错误");
}
userDao.updatePass(uid,newPass);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/*@Override
public void activation(String activationCode)throws UserException {
*//*
* 1. 通过激活码查询用户
* 2. 如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码)
* 3. 查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活)
* 4. 修改用户状态为true
*//*
User byCode = userDao.findByCode(activationCode);
if(byCode == null){
throw new UserException("无效的激活码!");
}
if(byCode.isStatus()){
throw new UserException("您已经激活过了,不要二次激活!");
}
userDao.updataStatus(byCode.getUid(), true);//修改状态
}*/
}
| true
|
dc127d6979b0e77127ec6ac4fac4d0a49ad88cb0
|
Java
|
hedaoming/JavaDeep
|
/src/conrrent/noLock/TestAtomicStampedReference.java
|
UTF-8
| 2,187
| 3.34375
| 3
|
[] |
no_license
|
package conrrent.noLock;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
* Created by ipc on 2017/6/13.
*/
public class TestAtomicStampedReference {
static AtomicStampedReference<Integer> asr = new AtomicStampedReference<Integer>(19,0);
public static void main(String args[]){
//模拟充值
for(int i = 0;i<3;i++){
final int stamped = asr.getStamp();
new Thread(){
@Override
public void run() {
while(true){
while(true){
Integer m = asr.getReference();
if(m<20){
if(asr.compareAndSet(m,m+20,stamped,stamped-1)){
System.out.println("余额小于20元,充值成功,余额:"+asr.getReference()+"元");
break;
}
}else{
System.out.println("余额大于20元,无需充值");
break;
}
}
}
}
}.start();
}
//模拟消费
new Thread(){
@Override
public void run() {
for(int i = 0;i<100;i++){
while(true){
int stamped = asr.getStamp();
Integer m = asr.getReference();
if(m>10){
if(asr.compareAndSet(m,m-10,stamped,stamped-1)){
System.out.println("消费十元,现在余额:"+asr.getReference()+"元");
break;
}
}else{
System.out.println("余额不足");
break;
}
}
try{
Thread.sleep(100);
}catch(Exception e){
}
}
}
}.start();
}
}
| true
|
f4cd9bd09b7dbe5ba8665ecfee7d90a8af7cac2c
|
Java
|
boloBeach/Xieee
|
/Xieee/src/main/java/net/xieee/spider/util/Constants.java
|
UTF-8
| 1,130
| 1.773438
| 2
|
[] |
no_license
|
package net.xieee.spider.util;
/**
* this class is constants with the splider
*
* @author royzhang
*
*/
public class Constants {
/**
* url filter,the reason some url can not get this code.
*/
public final static String filter = "about,about us";
/**
* the LinkQueue max size
*/
public final static int max_url = 1000;
/**
* get html code timeout
*/
public final static int timeout = 60000;
/**
* save img path
*/
public final static String savePath = "/usr/local/nginx/html/xieee/images/";
/**
* 图片显示地址
*/
public final static String imgHTTPPath = "http://172.17.111.191:8080/images/";
/**
* spring xml name
*/
public final static String springXMLName = "applicationContext.xml";
/**
* get img by name
*/
public final static String admin = "admin";
/**
* 显示首页的信息的默认的pagesize个数
*/
public final static Integer index_pageSize = 5;
/**
* 显示首页的信息的默认显示方式,按照时间的先后顺序来进系
*/
public final static Integer index_types = 1;
}
| true
|
6e3a99f9fa12592baa840b7d8d3e5fa4602152b3
|
Java
|
sk354-hdm/JavaKurs1
|
/java_kurs_1/src/Figuren/FolgeDerMausFigur.java
|
UTF-8
| 783
| 3.03125
| 3
|
[] |
no_license
|
package Figuren;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
public class FolgeDerMausFigur extends Ellipse2D.Double implements MouseMotionListener{
public FolgeDerMausFigur(JPanel panel) {
this.height = 40;
this.width = 40;
this.x = 0;
this.y = 0;
panel.addMouseMotionListener(this);
}
public void zeichne(Graphics2D g) {
g.setBackground(Color.YELLOW);
g.fill(this);
}
public void bewege() {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
this.x = e.getX() -20;
this.y = e.getY() -20;
}
}
| true
|
9fe48aff1cc30346f7829a1039b3e31c31f07a5a
|
Java
|
hkj141421/StudyDemo
|
/NioDemo/src/main/java/FrameWork/com/nio/Codec/JsonDecode.java
|
UTF-8
| 1,056
| 2.296875
| 2
|
[] |
no_license
|
package FrameWork.com.nio.Codec;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
/**
* Created by forget on 2019/12/6.
*/
public class JsonDecode extends MessageToMessageDecoder<String>{
private Class aClass;
public JsonDecode(){
}
public JsonDecode(Class aClass){
this.aClass=aClass;
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, String o, List list) throws Exception {
JSONObject jsonObject=JSONObject.parseObject(o);
Set<String> set=jsonObject.keySet();
String value=null;
Object o1=aClass.newInstance();
Field[] fs=o1.getClass().getDeclaredFields();
for (Field f: fs) {
f.setAccessible(true);
f.set(o1,jsonObject.getString(f.getName()));
}
list.add(o1);
}
}
| true
|
ac50b2238d34d1aa24597c961bf3560f5580ae5f
|
Java
|
bingo1118/kaiping
|
/app/src/main/java/com/smart/cloud/fire/activity/Inspection/InspHistory/InspHIstoryItemActivity.java
|
UTF-8
| 8,142
| 1.6875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.smart.cloud.fire.activity.Inspection.InspHistory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.smart.cloud.fire.activity.NFCDev.NFCImageShowActivity;
import com.smart.cloud.fire.global.ConstantValues;
import com.smart.cloud.fire.global.Question;
import com.smart.cloud.fire.utils.T;
import com.smart.cloud.fire.utils.VolleyHelper;
import com.smart.cloud.fire.view.TakePhoto.Photo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import fire.cloud.smart.com.smartcloudfire.R;
public class InspHIstoryItemActivity extends Activity {
@Bind(R.id.question_recyclerview)
RecyclerView question_recyclerview;
@Bind(R.id.name)
TextView name_tv;
@Bind(R.id.address)
TextView address_tv;
@Bind(R.id.time)
TextView time_tv;
@Bind(R.id.state)
TextView state_tv;
@Bind(R.id.worker_tv)
TextView worker_tv;
@Bind(R.id.memo_tv)
TextView memo_tv;
@Bind(R.id.location_photo_iv)
ImageView location_photo_iv;
@Bind(R.id.sign_photo_iv)
ImageView sign_photo_iv;
private Context mContext;
private String uid;
private String prid;
List<Question> listQ;
InspHistoryItemQuestionAdapter questionAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insp_history_item);
ButterKnife.bind(this);
mContext = this;
uid=getIntent().getStringExtra("uid");
prid=getIntent().getStringExtra("prid");
getNormalDevInfo();
}
private void getNormalDevInfo() {
if(uid==null){
return;
}
VolleyHelper helper=VolleyHelper.getInstance(mContext);
RequestQueue mQueue = helper.getRequestQueue();
String url="";
url= ConstantValues.SERVER_IP_NEW+"getQuestionResultList?uid="+uid+"&prid="+prid;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String questionJson=response.getString("questionTypes");
name_tv.setText("名称:"+response.getString("deviceName"));
address_tv.setText("位置:"+response.getString("address"));
time_tv.setText("时间:"+response.getJSONObject("record").getString("checktime"));
state_tv.setText("总评:"+response.getString("deviceStateName"));
memo_tv.setText("备注:"+response.getString("memo"));
worker_tv.setText("巡检人:"+response.getJSONObject("record").getString("workerName"));
String location_img_path=ConstantValues.NFC_IMAGES+"cheakImg//"+response.getJSONObject("record").getString("imgs");
String sign_img_path=ConstantValues.NFC_IMAGES+"cheakImg//"+response.getJSONObject("record").getString("signature");
Glide.with(mContext)
.load(location_img_path)
.placeholder(R.drawable.photo_ok)
.into(location_photo_iv);
location_photo_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, NFCImageShowActivity.class);
intent.putExtra("path",location_img_path);
mContext.startActivity(intent);
}
});
Glide.with(mContext)
.load(sign_img_path)
.placeholder(R.drawable.photo_ok)
.into(sign_photo_iv);
sign_photo_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, NFCImageShowActivity.class);
intent.putExtra("path",sign_img_path);
mContext.startActivity(intent);
}
});
dealwithQuestionJson(questionJson);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
T.showShort(mContext,"网络错误");
}
});
mQueue.add(jsonObjectRequest);
}
private void dealwithQuestionJson(String questionJson) {
try {
JSONArray jsonArray=new JSONArray(questionJson);
if(jsonArray.length()!=0){
listQ=new ArrayList<>();
for(int i=0;i<jsonArray.length();i++){
JSONObject temp=jsonArray.getJSONObject(i);
String qtname=temp.getString("qtname");
JSONArray tempA=temp.getJSONArray("questions");
for(int j=0;j<tempA.length();j++){
Question question=new Question();
if(j==0){
question.setFirstItem(true);
}else{
question.setFirstItem(false);
}
question.setAnswer(tempA.getJSONObject(j).getInt("result"));
question.setQjudge(tempA.getJSONObject(j).getString("qjudge"));
question.setQuestionType(qtname);
question.setQdetail(tempA.getJSONObject(j).getString("qdetail"));
question.setQid(tempA.getJSONObject(j).getInt("qid"));
String photosString=tempA.getJSONObject(j).getString("images");
String[] photosList=photosString.split("#");
List<Photo> photos=new ArrayList<>();
for(String s:photosList){
if(s.length()>0){
photos.add(new Photo(s,ConstantValues.NFC_IMAGES+"cheakImg//"+s));
}
}
question.setRemark(tempA.getJSONObject(j).getString("remark"));
question.setPhotos(photos);
listQ.add(question);
}
}
}
questionAdapter=new InspHistoryItemQuestionAdapter(mContext,listQ,false);
question_recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
question_recyclerview.setAdapter(questionAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| true
|
2450caedc22f87a04798d3d57d3283b21a1d513d
|
Java
|
mohammedragabmohammedborik/Thaa
|
/app/src/main/java/com/dtag/thaa/Onclicklistenerd.java
|
UTF-8
| 110
| 1.71875
| 2
|
[] |
no_license
|
package com.dtag.thaa;
public interface Onclicklistenerd {
void onItemClickedListener(int position);
}
| true
|
b2e968860719ccfbf701627bb4199e983a436c71
|
Java
|
mekarbal/project_got_talent_javaConsole_mysql
|
/src/enums/ConDb.java
|
UTF-8
| 444
| 2.28125
| 2
|
[] |
no_license
|
package enums;
public enum ConDb {
AUTH("mail.smtp.auth", "true"),
SSL("mail.smtp.starttls.enable", "true"),
HOST("mail.smtp.host", "smtp.gmail.com"),
PORT("mail.smtp.port", "587");
private String props = "";
private String value = "";
ConDb(String props,String value) {
this.props=props;
this.value=value;
}
public String getProps() {
return props;
}
public String getValue() {
return value;
}
}
| true
|
9c598feefe836d7eb71b13fc037ca46f97202d78
|
Java
|
mike-neck/java-til
|
/reactor-tutorial/src/test/java/com/example/lesson/FromBlockingTest.java
|
UTF-8
| 4,351
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 Shinya Mochida
*
* Licensed under the Apache License,Version2.0(the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,software
* Distributed under the License is distributed on an"AS IS"BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lesson;
import com.example.ParameterSupplier;
import com.example.annotations.Lesson;
import com.example.lesson.api.BlockingWriter;
import com.example.lesson.api.FromBlocking;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import java.io.*;
import java.time.Duration;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.assertAll;
@ExtendWith({ParameterSupplier.class})
@Lesson(11)
class FromBlockingTest {
private final ClassLoader loader = getClass().getClassLoader();
private InputStream inputStream(final String name) {
return loader.getResourceAsStream(name);
}
private Reader reader(final String name) {
return new InputStreamReader(inputStream(name));
}
private BufferedReader bufferedReader(@SuppressWarnings("SameParameterValue") final String name) {
return new BufferedReader(reader(name));
}
@Test
void fromBlockingWithDeferSubscribeOnScheduler(final FromBlocking fromBlocking) throws IOException {
try (final BufferedReader reader = bufferedReader("from-blocking-test.txt")) {
final Flux<String> flux = fromBlocking.fromBlockingToFluxWithScheduler(reader);
StepVerifier.create(flux)
.expectNext("foo")
.expectNext("bar")
.expectNext("baz")
.verifyComplete();
}
}
@Test
void toBlockingConsumerWithPublishOnScheduler(final FromBlocking fromBlocking) {
final BlockingWriterImpl writer = new BlockingWriterImpl(3);
final Flux<String> tester = Flux.create(writer::setSink).log();
final Flux<String> flux = Flux.just("foo", "bar", "baz").log()
.doOnTerminate(writer::close);
final Mono<Void> mono = fromBlocking.fluxToBlockingConsumer(flux, writer);
assertAll(
() -> StepVerifier.create(mono).verifyComplete(),
() -> StepVerifier.create(tester)
.expectNext("foo")
.expectNext("bar")
.expectNext("baz")
.verifyComplete()
);
}
}
class BlockingWriterImpl implements BlockingWriter {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Queue<String> queue = new ConcurrentLinkedQueue<>();
private FluxSink<String> sink;
private final CountDownLatch latch;
BlockingWriterImpl(final int expectedCount) {
latch = new CountDownLatch(expectedCount);
}
public void setSink(final FluxSink<String> sink) {
this.sink = sink;
sink.onRequest(this::publish);
sink.onDispose(executor::shutdown);
sink.onCancel(executor::shutdown);
}
private void publish(final long request) {
final long size = request <= queue.size() ? request : queue.size();
for (long i = 0; i < size; i++) {
final String poll = queue.poll();
sink.next(poll);
latch.countDown();
}
}
@Override
public void write(final String value) {
queue.offer(value);
}
@Override
public void close() {
CompletableFuture.runAsync(() -> {
try {
latch.await();
Objects.requireNonNull(sink).complete();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, executor);
}
}
| true
|
f6a8915770b813f3a0f27476ad3e5c80ed16273e
|
Java
|
smcclain56/java-graph
|
/Graph.java
|
UTF-8
| 5,490
| 3.46875
| 3
|
[] |
no_license
|
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Map;
/**
* A class that implements a Graph with a Hashmap of integers as the keys, and
* array lists of integers as the values.
*
* @author Gennie Cheatham, Sarah McClain
*
*/
public class Graph<V> implements GraphIfc<V> {
protected Map<V, List<V>> directedGraph;
/**
* Constructor for directed graph.
*/
public Graph(){
directedGraph = new HashMap<V, List<V>>();
}
/**
* Returns the number of vertices in the graph
* @return The number of vertices in the graph
*/
@Override
public int numVertices() {
return directedGraph.size();
}
/**
* Returns the number of edges in the graph
* @return The number of edges in the graph
*/
@Override
public int numEdges() {
int totalEdges = 0;
for(V v : directedGraph.keySet()){
int listSize = directedGraph.get(v).size();
totalEdges += listSize;
}
return totalEdges;
}
/**
* Removes all vertices from the graph
*/
@Override
public void clear() {
directedGraph.clear();
}
/**
* Adds a vertex to the graph. This method has no effect if the vertex already exists in the graph.
* @param v The vertex to be added
*
*/
@Override
public void addVertex(V v) {
if(containsVertex(v) == false ) {
List<V> list = new ArrayList<V>();
directedGraph.put(v, list);
}
}
/**
* Adds an edge between vertices u and v in the graph.
* @param u A vertex in the graph
* @param v A vertex in the graph
* @throws IllegalArgumentException if either vertex does not occur in the graph.
*/
@Override
public void addEdge(V u, V v) {
//throws error if either vertex is not in map
if(containsVertex(u)==false ||
containsVertex(v) == false) {
throw new IllegalArgumentException();
}
if(edgeExists(u, v) ==false) {
//adds vertex to list of edges
List<V> listU = directedGraph.get(u);
listU.add(v);
}
}
/**
* Returns the set of all vertices in the graph.
* @return A set containing all vertices in the graph
*/
@Override
public Set<V> getVertices() {
return directedGraph.keySet();
}
/**
* Returns the neighbors of v in the graph. A neighbor is a vertex that is connected to
* v by an edge. If the graph is directed, this returns the vertices u for which an
* edge (v, u) exists.
*
* @param v An existing node in the graph
* @return All neighbors of v in the graph.
* @throws IllegalArgumentException if the vertex does not occur in the graph
*/
@Override
public List<V> getNeighbors(V v) {
if(containsVertex(v) == false){
throw new IllegalArgumentException();
}
List<V> listV = directedGraph.get(v);
return listV;
}
/**
* Determines whether the given vertex is already contained in the graph. The comparison
* is based on the <code>equals()</code> method in the class V.
*
* @param v The vertex to be tested.
* @return True if v exists in the graph, false otherwise.
*/
@Override
public boolean containsVertex(V v) {
if(directedGraph.containsKey(v)) {
return true;
}
return false;
}
/**
* Determines whether an edge exists between two vertices. In a directed graph,
* this returns true only if the edge starts at v and ends at u.
* @param v A node in the graph
* @param u A node in the graph
* @return True if an edge exists between the two vertices
* @throws IllegalArgumentException if either vertex does not occur in the graph
*/
@Override
public boolean edgeExists(V v, V u) {
if(containsVertex(v)==false || containsVertex(u)==false ) {
throw new IllegalArgumentException();
}
List<V> listV = directedGraph.get(v);
for(int i=0; i<listV.size(); i++) {
if(listV.get(i).equals(u)) {
return true;
}
}
return false;
}
/**
* Returns the degree of the vertex. In a directed graph, this returns the outdegree of the
* vertex.
* @param v A vertex in the graph
* @return The degree of the vertex
* @throws IllegalArgumentException if the vertex does not occur in the graph
*/
@Override
public int degree(V v) {
int listSize = directedGraph.get(v).size();
return listSize;
}
/**
* Returns a string representation of the graph. The string representation shows all
* vertices and edges in the graph.
* @return A string representation of the graph
*/
@Override
public String toString() {
String toString = "";
for(V v : directedGraph.keySet()){
List<V> list = directedGraph.get(v);
toString += "\n" + v + ": ";
for(int i=0; i<degree(v); i++) {
toString += list.get(i) + ", ";
}
}
return toString;
}
}
| true
|
14141161e573e8c22f80aff8e9c19aeb01abb6cb
|
Java
|
alexandrejonathas/teste-pratico-publica
|
/src/main/java/br/com/publica/testepratico/infrastructure/repository/JogoRepositoryImpl.java
|
UTF-8
| 1,973
| 2.328125
| 2
|
[] |
no_license
|
package br.com.publica.testepratico.infrastructure.repository;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import br.com.publica.testepratico.domain.filter.JogoFilter;
import br.com.publica.testepratico.domain.model.Jogo;
import br.com.publica.testepratico.domain.model.Time;
import br.com.publica.testepratico.domain.repository.JogoRepositoryQueries;
@Repository
public class JogoRepositoryImpl implements JogoRepositoryQueries {
@PersistenceContext
private EntityManager manager;
@Override
public List<Jogo> filtrar(JogoFilter filter) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Jogo> criteria = builder.createQuery(Jogo.class);
Root<Jogo> root = criteria.from(Jogo.class);
root.fetch("timeCasa", JoinType.INNER);
root.fetch("timeVisitante", JoinType.INNER);
Join<Jogo, Time> timeCasa = root.join("timeCasa");
Join<Jogo, Time> timeVisitante = root.join("timeVisitante");
List<Predicate> predicates = new ArrayList<>();
if(!StringUtils.isEmpty(filter.getNome())) {
String filtro = "%"+filter.getNome()+"%";
predicates.add(builder.or(builder.like(timeCasa.get("nome"), filtro) ,builder.like(timeVisitante.get("nome"), filtro)));
}
criteria.distinct(true);
criteria.where(predicates.toArray(new Predicate[predicates.size()]));
criteria.orderBy(builder.desc(root.get("data")));
TypedQuery<Jogo> query = manager.createQuery(criteria);
return query.getResultList();
}
}
| true
|
780b58f70d24a542e7704bcdb398fe6d6ffdbecf
|
Java
|
riccardomengoli/StabilimentoBalneare
|
/StabilimentoBalneare/src/ombrelloniani/view/fxmlControllers/GestionePrenotazione.java
|
UTF-8
| 2,862
| 2.59375
| 3
|
[] |
no_license
|
package ombrelloniani.view.fxmlControllers;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import ombrelloniani.view.VistaNavigator;
public class GestionePrenotazione extends FXMLController {
@FXML private Button backButton;
@FXML private Button nuovaPren;
@FXML private Button modificaPren;
@FXML private Button terminaPren;
@FXML private Button cancellaPren;
@FXML private Line hr1;
public GestionePrenotazione() {
};
/**
* Lega la lunghezza della linea di separazione alla lunghezza del suo
* container, necessario in quanto gli oggetti Shape non sono resizable. Vengono
* aggiunti 0.5 px alla coordinata y per ottenere un effetto di pixel pieno,
* evitando aliasing (Javadoc Shape). Initialize viene invocato al termine del
* caricamento del contenuto del file fxml.
*/
@FXML
private void initialize() {
Pane parent = (Pane) hr1.getParent();
hr1.startXProperty().bind(new SimpleDoubleProperty(50));
hr1.endXProperty().bind(parent.widthProperty().subtract(50));
// Evito aliasing
hr1.setStartY(0.5);
hr1.setEndY(0.5);
}
/**
* Evento al click del bottone di nuova prenotazione. Cambio scena.
*/
@FXML
private void handleNuovaPren(ActionEvent event) {
VistaNavigator.loadView(VistaNavigator.CREAPRENOTAZIONE);
}
/**
* Evento al click del bottone di modifica prenotazione. Cambio scena.
*/
@FXML
private void handleModificaPren(ActionEvent event) {
// VistaNavigator.loadView(VistaNavigator.MODIFICAPRENOTAZIONE);
}
/**
* Evento al click del bottone di termina prenotazione. Cambio scena.
*/
@FXML
private void handleTerminaPren(ActionEvent event) {
VistaNavigator.loadView(VistaNavigator.TERMINAPRENOTAZIONE);
}
/**
* Evento al click del bottone di cancella prenotazione. Cambio scena.
*/
@FXML
private void handleCancellaPren(ActionEvent event) {
// VistaNavigator.loadView(VistaNavigator.CANCELLAPRENOTAZIONE);
}
/**
* Evento all'entrata del mouse sopra i bottoni del menu. Imposta il colore.
*/
@FXML
private void handleHoverInButton(MouseEvent event) {
((Button) event.getSource()).setStyle("-fx-background-color: #4449d9;");
}
/**
* Evento all'uscita del mouse dai bottoni del menu. Resetta il colore
* principale.
*/
@FXML
private void handleHoverOutButton(MouseEvent event) {
((Button) event.getSource()).setStyle("");
}
/**
* Evento al click di indietro. Ritorno alla view precedente.
*/
@FXML
private void handleBack(ActionEvent event) {
if (getCallingScene() != null) {
VistaNavigator.loadView(getCallingScene());
}
}
}
| true
|
b054ed3bb70c08666627d8b08483d72007217525
|
Java
|
anthonywittemann/workspace
|
/CSC142Albright/src/AWCh2Pr10.java
|
UTF-8
| 572
| 3.734375
| 4
|
[] |
no_license
|
// Anthony Wittemann
// Chapter 2 Program 10 Test Average
// Due 2/4/14
public class AWCh2Pr10 {
/**
* @param args
*/
public static void main(String[] args) {
// 75, 83, 87 as the three test scores
short testScore0 = 75;
short testScore1 = 83;
short testScore2 = 87;
float averageTestScore = (float) ((float) (testScore0 + testScore1 + testScore2) / 3.0);
System.out.println("Test Score 1: " + testScore0 + " Test Score 2: " + testScore1 +
" Test Score 3: " + testScore2);
System.out.printf("Test Score Average: " + "%1$.2f", averageTestScore);
}
}
| true
|
fb58fbbcf60d6405e9cf16e625f4d618089ce193
|
Java
|
MayconDouglass/sistema-vendas
|
/src/DAO/DAOUsuario.java
|
UTF-8
| 10,345
| 2.59375
| 3
|
[] |
no_license
|
package DAO;
import model.ModelUsuario;
import Connect.ConexaoMySql;
import java.util.ArrayList;
/**
*
* @author Maycon Douglas
*/
public class DAOUsuario extends ConexaoMySql {
/**
* grava Usuario
*
* @param pModelUsuario return int
*/
public int salvarUsuarioDAO(ModelUsuario pModelUsuario) {
try {
this.conectar();
return this.insertSQL(
"INSERT INTO setusuario ("
+ "iduser,"
+ "nome,"
+ "area,"
+ "perfil,"
+ "email,"
+ "login,"
+ "senha,"
+ "aniversario,"
+ "status"
+ ") VALUES ("
+ "'" + pModelUsuario.getIduser() + "',"
+ "'" + pModelUsuario.getNome() + "',"
+ "'" + pModelUsuario.getArea() + "',"
+ "'" + pModelUsuario.getPerfil() + "',"
+ "'" + pModelUsuario.getEmail() + "',"
+ "'" + pModelUsuario.getLogin() + "',"
+ "'" + pModelUsuario.getSenha() + "',"
+ "'" + pModelUsuario.getAniversario() + "',"
+ "'" + pModelUsuario.getStatus() + "'"
+ ");"
);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
this.fecharConexao();
}
}
/**
* recupera Usuario
*
* @param pIduser return ModelUsuario
*/
public ModelUsuario getUsuarioDAO(int pIduser) {
ModelUsuario modelUsuario = new ModelUsuario();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "iduser,"
+ "nome,"
+ "area,"
+ "perfil,"
+ "email,"
+ "login,"
+ "senha,"
+ "aniversario,"
+ "status"
+ " FROM"
+ " setusuario"
+ " WHERE"
+ " iduser = '" + pIduser + "'"
+ ";"
);
while (this.getResultSet().next()) {
modelUsuario.setIduser(this.getResultSet().getInt(1));
modelUsuario.setNome(this.getResultSet().getString(2));
modelUsuario.setArea(this.getResultSet().getInt(3));
modelUsuario.setPerfil(this.getResultSet().getInt(4));
modelUsuario.setEmail(this.getResultSet().getString(5));
modelUsuario.setLogin(this.getResultSet().getString(6));
modelUsuario.setSenha(this.getResultSet().getString(7));
modelUsuario.setAniversario(this.getResultSet().getString(8));
modelUsuario.setStatus(this.getResultSet().getInt(9));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.fecharConexao();
}
return modelUsuario;
}
/**
* recupera Usuario pelo login
*
* @param pLogin return ModelUsuario
*/
public ModelUsuario getUsuarioLoginDAO(String pLogin) {
ModelUsuario modelUsuario = new ModelUsuario();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "iduser,"
+ "nome,"
+ "area,"
+ "perfil,"
+ "email,"
+ "login,"
+ "senha,"
+ "aniversario,"
+ "status"
+ " FROM"
+ " setusuario"
+ " WHERE"
+ " login = '" + pLogin + "'"
+ ";"
);
while (this.getResultSet().next()) {
modelUsuario.setIduser(this.getResultSet().getInt(1));
modelUsuario.setNome(this.getResultSet().getString(2));
modelUsuario.setArea(this.getResultSet().getInt(3));
modelUsuario.setPerfil(this.getResultSet().getInt(4));
modelUsuario.setEmail(this.getResultSet().getString(5));
modelUsuario.setLogin(this.getResultSet().getString(6));
modelUsuario.setSenha(this.getResultSet().getString(7));
modelUsuario.setAniversario(this.getResultSet().getString(8));
modelUsuario.setStatus(this.getResultSet().getInt(9));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.fecharConexao();
}
return modelUsuario;
}
/**
* Verifica se ja existe login igual na BD
*
* @param pLogin
* @return
*/
public ModelUsuario getUsuarioVerificaLoginDAO(String pLogin) {
ModelUsuario modelUsuario = new ModelUsuario();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "count(login)"
+ " FROM"
+ " setusuario"
+ " WHERE"
+ " login = '" + pLogin + "'"
+ ";"
);
while (this.getResultSet().next()) {
modelUsuario.setValidacao(this.getResultSet().getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.fecharConexao();
}
return modelUsuario;
}
/**
* Validar login e senha usuário
*
* @param pModelUsuario
* @return
*/
public boolean getValidarUsuarioDAO(ModelUsuario pModelUsuario) {
ModelUsuario modelUsuario = new ModelUsuario();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "iduser,"
+ "nome,"
+ "area,"
+ "perfil,"
+ "email,"
+ "login,"
+ "senha,"
+ "aniversario,"
+ "status"
+ " FROM"
+ " setusuario"
+ " WHERE login = '" + pModelUsuario.getLogin() + "'"
+ " AND senha = '" + pModelUsuario.getSenha() + "'"
+ " AND status = '1'"
+ ";"
);
return getResultSet().next();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.fecharConexao();
}
}
/**
* recupera uma lista de Usuario return ArrayList
*/
public ArrayList<ModelUsuario> getListaUsuarioDAO() {
ArrayList<ModelUsuario> listamodelUsuario = new ArrayList();
ModelUsuario modelUsuario = new ModelUsuario();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "iduser,"
+ "nome,"
+ "area,"
+ "perfil,"
+ "email,"
+ "login,"
+ "senha,"
+ "aniversario,"
+ "status"
+ " FROM"
+ " setusuario"
+ ";"
);
while (this.getResultSet().next()) {
modelUsuario = new ModelUsuario();
modelUsuario.setIduser(this.getResultSet().getInt(1));
modelUsuario.setNome(this.getResultSet().getString(2));
modelUsuario.setArea(this.getResultSet().getInt(3));
modelUsuario.setPerfil(this.getResultSet().getInt(4));
modelUsuario.setEmail(this.getResultSet().getString(5));
modelUsuario.setLogin(this.getResultSet().getString(6));
modelUsuario.setSenha(this.getResultSet().getString(7));
modelUsuario.setAniversario(this.getResultSet().getString(8));
modelUsuario.setStatus(this.getResultSet().getInt(9));
listamodelUsuario.add(modelUsuario);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.fecharConexao();
}
return listamodelUsuario;
}
/**
* atualiza Usuario
*
* @param pModelUsuario return boolean
*/
public boolean atualizarUsuarioDAO(ModelUsuario pModelUsuario) {
try {
this.conectar();
return this.executarUpdateDeleteSQL(
"UPDATE setusuario SET "
+ "iduser = '" + pModelUsuario.getIduser() + "',"
+ "nome = '" + pModelUsuario.getNome() + "',"
+ "area = '" + pModelUsuario.getArea() + "',"
+ "perfil = '" + pModelUsuario.getPerfil() + "',"
+ "email = '" + pModelUsuario.getEmail() + "',"
+ "login = '" + pModelUsuario.getLogin() + "',"
+ "senha = '" + pModelUsuario.getSenha() + "',"
+ "aniversario = '" + pModelUsuario.getAniversario() + "',"
+ "status = '" + pModelUsuario.getStatus() + "'"
+ " WHERE "
+ "iduser = '" + pModelUsuario.getIduser() + "'"
+ ";"
);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.fecharConexao();
}
}
/**
* exclui Usuario
*
* @param pIduser return boolean
*/
public boolean excluirUsuarioDAO(int pIduser) {
try {
this.conectar();
return this.executarUpdateDeleteSQL(
"DELETE FROM setusuario "
+ " WHERE "
+ "iduser = '" + pIduser + "'"
+ ";"
);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.fecharConexao();
}
}
}
| true
|
39ea0182aef8da5832aba64d36be716fd2c0f601
|
Java
|
tmc1245/ghidra
|
/Ghidra/Debug/Debugger-sctl/src/main/java/ghidra/dbg/sctl/protocol/v2012ext/SelSctl2012ExtPacket.java
|
UTF-8
| 1,332
| 1.695313
| 2
|
[
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/* ###
* IP: GHIDRA
*
* 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 ghidra.dbg.sctl.protocol.v2012ext;
import java.util.Map;
import ghidra.dbg.sctl.protocol.AbstractSelSctlPacket;
import ghidra.dbg.sctl.protocol.SctlPacket;
import ghidra.dbg.sctl.protocol.consts.Mkind;
import ghidra.dbg.sctl.protocol.v2012base.SelSctl2012Packet;
public class SelSctl2012ExtPacket extends AbstractSelSctlPacket {
public SelSctl2012ExtPacket() {
super();
}
public SelSctl2012ExtPacket(int tag, SctlPacket sel) {
super(tag, sel);
}
public static final Map<Mkind, Class<? extends SctlPacket>> METHOD_MAP =
typeMap(Mkind.class, SctlPacket.class) //
.putAll(SelSctl2012Packet.METHOD_MAP) //
.put(Mkind.Texec, SctlExecuteRequest.class) //
.put(Mkind.Rexec, SctlExecuteReply.class) //
.build();
}
| true
|
ec21b835838df4d17e15b56ea94b40143ffcea4e
|
Java
|
projectforcol/ImportData2BioIDE
|
/src/main/java/org/big/repository/CitationRepository.java
|
UTF-8
| 4,406
| 2.078125
| 2
|
[] |
no_license
|
package org.big.repository;
import java.util.Date;
import java.util.List;
import org.big.entity.Citation;
import org.big.repository.base.BaseRepository;
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.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*<p><b>Citation的DAO类接口</b></p>
*<p> Citation的DAO类接口,与User有关的持久化操作方法</p>
* @author BINZI
*<p>Created date: 2018/06/11 10:35</p>
*<p>Copyright: The Research Group of Biodiversity Informatics (BiodInfo Group) - 中国科学院动物研究所生物多样性信息学研究组</p>
* @version: 0.1
* @since JDK 1.80_144
*/
@Repository
public interface CitationRepository extends BaseRepository<Citation, String> {
/**
*<b>带分页排序的条件查询</b>
*<p> 带分页排序的条件查询</p>
* @author BINZI
* @param findText 条件关键词,这里是模糊匹配
* @param pageable 分页排序方案实体
* @return org.springframework.data.domain.Page<org.big.entity.Citation>
*/
@Query(value = "Select c from Citation c where ("
+ "c.sciname like %?1% or "
+ "c.authorship like %?1% or "
+ "c.nametype like %?1% or "
+ "c.inputer like %?1% or "
+ "c.inputtime like %?1% or "
+ "c.synchdate like %?1%) and "
+ "c.status = 1")
Page<Citation> searchInfo(String searchText, Pageable pageable);
/**
*<b>根据id查询一个实体</b>
*<p> 带分页排序的条件查询</p>
* @param id
* @return
*/
@Query(value = "Select c from Citation c Where c.id = ?1")
Citation findOneById(String id);
/**
*<b>通过Id删除一个实体</b>
*<p> 通过Id删除一个实体</p>
* @author BINZI
* @param citationId
*/
@Modifying
@Transactional
@Query("Delete Citation c where c.id =?1")
void deleteOneById(String citationId);
/**
*<b>通过TaxonId查询Taxon下的所有Citation实体</b>
*<p> 通过TaxonId查询Taxon下的所有Citation实体</p>
* @author BINZI
* @param taxonId
*/
@Query(value = "Select c from Citation c Where c.taxon.id = ?1 and c.status = 1")
Page<Citation> searchCitationsByTaxonId(Pageable pageable, String taxonId);
/**
* <b>根据taxonId修改Taxon下的Citations</b>
* <p> 根据taxonId修改Taxon下的Citations</p>
* @param request
* @return
*/
@Query(value = "Select c from Citation c Where c.taxon.id = ?1")
List<Citation> findCitationListByTaxonId(String taxonId);
//zxy
@Modifying
@Transactional
@Query("Delete Citation c where c.inputtime =?1 and c.sourcesid = ?2")
void deleteByInputtimeAndSourcesid(Date inputtime,String sourcesid);
@Transactional
@Modifying
@Query(value = "delete from citation where taxon_id in (select id from taxon where taxaset_id = (select id from taxaset where tsname = ?1 and dataset_id = (select id from dataset where dsname = ?2 and team_id = (select id from team where name = ?3))))", nativeQuery = true)
void deleteCitation(String tsname, String dsname, String teamName);
@Transactional
@Modifying
@Query(value = "delete from citation where taxon_id in (select id from taxon where taxaset_id = ?1)", nativeQuery = true)
void deleteCitationByTaxaSetId(String tsId);
@Query(value = "select a.id,a.taxon_id,a.sciname,a.authorship,a.nameType,a.citationstr,b.rank_id from citation a left join taxon b on a.taxon_id = b.id where b.taxaset_id = ?1 and a.nametype!=?2 and b.rank_id in (?3)",nativeQuery = true)
List<Object[]> findByNametypeAndTaxaSetAndRankIn(String taxasetId,int nametypeNotEq,List<String> rankNameIn);
@Query(value = "select c.id,c.sciname,c.authorship,c.nametype,c.taxon_id from citation c left join taxon t on c.taxon_id = t.id left join taxaset b on t.taxaset_id = b.id where b.dataset_id =?1 and c.sciname =?2",nativeQuery = true)
List<Object[]> findByDatasetAndSciName(String datasetId, String sciname);
@Query(value = "Select c from Citation c Where c.taxon.id = ?1 and c.sciname = ?2")
Citation findByTaxonIdAndSciname(String taxonId, String acceptName);
//Containing like '%xxx%'
List<Citation> findByAuthorshipContaining(String authorship);
List<Citation> findByScinameEndingWith(String sciname);
}
| true
|
1a5f02a7bad2229661cd41758972390895d16ee9
|
Java
|
tkdtanu/oauth2-social-login
|
/spring-boot2-oauth2/src/main/java/com/tkd/oauth2/security/jwt/TokenProvider.java
|
UTF-8
| 2,754
| 2.328125
| 2
|
[] |
no_license
|
package com.tkd.oauth2.security.jwt;
import com.tkd.oauth2.properties.AppProperties;
import com.tkd.oauth2.security.model.AppUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
@Component
@Slf4j
public class TokenProvider {
private final AppProperties appProperties;
@Autowired
public TokenProvider(AppProperties appProperties) {
this.appProperties = appProperties;
}
public String createToken(Authentication authentication) {
AppUser appUser = (AppUser) authentication.getPrincipal();
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime expirryDate = localDateTime.plusSeconds(appProperties.getAuth().getTokenExpirationTime()/1000);
return Jwts.builder()
.setSubject(Long.toString(appUser.getId()))
.setIssuedAt(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()))
.setExpiration(Date.from(expirryDate.atZone(ZoneId.systemDefault()).toInstant()))
.signWith(SignatureAlgorithm.HS512, appProperties.getAuth().getTokenSecret())
.compact();
}
public boolean isValid(String authToken) {
log.debug("validating JWT Toke : {}", authToken);
try {
Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
log.error("Invalid JWT Signature");
} catch (MalformedJwtException ex) {
log.error("Invalid JWT Token");
} catch (ExpiredJwtException ex) {
log.error("Expired JWT Token");
} catch (UnsupportedJwtException ex) {
log.error("Unsupported JWT Token");
} catch (IllegalArgumentException ex) {
log.error("JWT claims string is empty");
}
return false;
}
public Long getUserIdFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(appProperties.getAuth().getTokenSecret())
.parseClaimsJws(token)
.getBody();
return Long.parseLong(claims.getSubject());
}
}
| true
|
830ab185e5ae04182f60af26722b690784a1f0fe
|
Java
|
x3platform/x-general-framework
|
/src/membership/src/main/java/com/x3platform/membership/authentication/SSOAuthenticationManagement.java
|
UTF-8
| 1,384
| 2.359375
| 2
|
[] |
no_license
|
package com.x3platform.membership.authentication;
import com.x3platform.membership.Account;
import com.x3platform.util.StringUtil;
/**
* 单点登录验证请求管理
* 登录帐号统一使用系统管理员配置登录密码
*/
public final class SSOAuthenticationManagement extends GenericAuthenticationManagement {
/**
* 获取认证的用户信息
*/
@Override
public Account getAuthUser() {
String accountIdentity = getIdentityValue();
// Http 方式的验证, accountIdentity 不允许为空.
if (StringUtil.isNullOrEmpty(accountIdentity)) {
return null;
}
// 获取帐号信息
Account account = getSessionAccount(accountIdentity);
if (account == null) {
return null;
}
// 写入临时存储
if (!cacheStorage.containsKey(accountIdentity)) {
synchronized (cacheSyncRoot) {
if (!cacheStorage.containsKey(accountIdentity)) {
addSession(accountIdentity, account);
}
}
}
// if(MembershipConfigurationView.getInstance().getCacheRedis().equalsIgnoreCase("on")){
// if (redisTemplate.hashGet(hashKey, accountIdentity) != null) {
// synchronized (this.getCacheSyncRoot()) {
// if (redisTemplate.hashGet(hashKey, accountIdentity) != null) {
// this.addSession(accountIdentity, account);
// }
// }
// }}
return account;
}
}
| true
|
c42199445217b2ae8ba3517432cf54ca4444d2f7
|
Java
|
eljec/mjo_mision_cba
|
/NuevaApp/app/src/main/java/aplication/mjo/misioncba/com/mjomisioncbaapp/model/ReadingJsonProvider.java
|
UTF-8
| 1,285
| 2.53125
| 3
|
[] |
no_license
|
package aplication.mjo.misioncba.com.mjomisioncbaapp.model;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jucastillo on 1/1/18.
*/
public class ReadingJsonProvider
{
private final AssetManager assetManager;
public ReadingJsonProvider(@NonNull AssetManager assetManager) {
this.assetManager = assetManager;
}
public ReadingJsonModel obtain(@NonNull String assetFileName) {
return parseItinerary(createInputStream(assetFileName));
}
private InputStream createInputStream(@NonNull String assetFileName) {
try {
return assetManager.open(assetFileName);
} catch (IOException e) {
throw new IllegalStateException("There is not asset with the name: " + assetFileName, e);
}
}
private ReadingJsonModel parseItinerary(@NonNull InputStream inputStream) {
try {
return new ObjectMapper().readValue(inputStream, ReadingJsonModel.class);
} catch (IOException e) {
throw new IllegalStateException("Cannot create an instance of ReadingJsonModel from asset resource.", e);
}
}
}
| true
|
9df439fc25a6664b7db3cadeecf66edd86da3d39
|
Java
|
yuruyigit/lotteryServer
|
/后台调试版/src/main/java/lottery/domains/content/biz/UserMessageService.java
|
UTF-8
| 516
| 1.851563
| 2
|
[] |
no_license
|
package lottery.domains.content.biz;
import javautils.jdbc.PageList;
import lottery.domains.content.vo.user.UserMessageVO;
public abstract interface UserMessageService
{
public abstract PageList search(String paramString1, String paramString2, String paramString3, String paramString4, int paramInt1, int paramInt2, int paramInt3);
public abstract UserMessageVO getById(int paramInt);
public abstract boolean delete(int paramInt);
public abstract boolean save(int paramInt, String paramString);
}
| true
|
d0a8fc8040bd203dbb7fff3c441cd23b174e9204
|
Java
|
sumathikotthuri/java-programming
|
/java-programming/src/practice/java/fundamentals/inheritance/TeamEventRegistration.java
|
UTF-8
| 1,735
| 3.359375
| 3
|
[] |
no_license
|
package practice.java.fundamentals.inheritance;
public class TeamEventRegistration extends EventRegistration{
private int noOfParticipants;
private int teamNo;
TeamEventRegistration(String name, String nameOfEvent
,int noOfParticipants,int teamNo){
super(name,nameOfEvent);
this.noOfParticipants = noOfParticipants;
this.teamNo = teamNo;
}
public int getNoOfParticipants() {
return noOfParticipants;
}
public void setNoOfParticipants(int noOfParticipants) {
this.noOfParticipants = noOfParticipants;
}
public int getTeamNo() {
return teamNo;
}
public void setTeamNo(int teamNo) {
this.teamNo = teamNo;
}
void registerEvent(){
switch(getNameOfEvent()){
case "ShakeALeg":
setRegistrationFee(50);
break;
case "Sing&Win":
setRegistrationFee(60);
break;
case "Actathon":
setRegistrationFee(80);
break;
case "PlayAway":
setRegistrationFee(100);
break;
default:
setRegistrationFee(0);
}
if(getRegistrationFee()!=0){
setRegistrationFee(getRegistrationFee()*getNoOfParticipants());
System.out.println("Thank You "+ getName() +" for your participation."
+"Your registration fee is : "+getRegistrationFee());
System.out.println("You are participant no: "+getTeamNo());
}else{
System.out.println("Please choose a valid event");
}
}
}
| true
|
f99bebcb2d2a715d3a016f6a41ccb5a0c6b2e9a2
|
Java
|
ffipertani/creditsuisse
|
/src/main/java/com/ff/creditsuisse/LiveOrderClient.java
|
UTF-8
| 1,240
| 2.515625
| 3
|
[] |
no_license
|
package com.ff.creditsuisse;
import com.ff.creditsuisse.exception.OrderNotFoundException;
import com.ff.creditsuisse.exception.OrderNotValidException;
import com.ff.creditsuisse.model.Order;
import com.ff.creditsuisse.model.OrderSummary;
import com.ff.creditsuisse.store.InMemoryOrderDataStore;
import com.ff.creditsuisse.store.OrderDataStore;
import com.ff.creditsuisse.validator.OrderValidator;
import java.util.*;
public class LiveOrderClient {
private final LiveOrderService liveOrderService;
public LiveOrderClient() {
OrderDataStore buyDataStore = new InMemoryOrderDataStore(new TreeMap(Comparator.reverseOrder()), new HashMap<>());
OrderDataStore sellDataStore = new InMemoryOrderDataStore(new TreeMap(), new HashMap<>());
this.liveOrderService = new LiveOrderService(sellDataStore, buyDataStore, new OrderValidator());
}
public void addOrder(Order order) throws OrderNotValidException {
liveOrderService.addOrder(order);
}
public void cancelOrder(Order order) throws OrderNotFoundException, OrderNotValidException {
liveOrderService.cancelOrder(order);
}
public List<OrderSummary> liveOrders() {
return liveOrderService.getLiveOrders();
}
}
| true
|
fc2761168aacad4b080dc64895fe654e0d7760e9
|
Java
|
agnibrainhack/Accenture_Hack
|
/app/src/main/java/com/example/hp/ikurenewedition/BMICALC.java
|
UTF-8
| 1,487
| 2.265625
| 2
|
[] |
no_license
|
package com.example.hp.ikurenewedition;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.hp.ikurenewedition.R;
/**
* Created by hp on 01-02-2018.
*/
public class BMICALC extends AppCompatActivity {
private String weight;
private String height;
TextView txt;
Double ht, wt;
private double bmi;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi);
Intent i = getIntent();
height = i.getStringExtra("height");
weight = i.getStringExtra("weight");
txt = findViewById(R.id.bmitext);
ht = Double.parseDouble(height);
wt = Double.parseDouble(weight);
ht = ht / 100;
bmi = wt / Math.pow(ht , 2);
float display = (float) (Math.floor(bmi * 100) / 100);
txt.setText(String.valueOf(display));
if(display<=18.5)
txt.setBackgroundResource(R.drawable.circ_red);
else if(display>18.5 && display<=25)
txt.setBackgroundResource(R.drawable.circ_res);
else if(display>25 && display<=30)
txt.setBackgroundResource(R.drawable.circ_lightyellow);
else if(display>30 && display<=40)
txt.setBackgroundResource(R.drawable.color_darkyellow);
else
txt.setBackgroundResource(R.drawable.circ_red);
}
}
| true
|
2005bd7d0a186886f8125159f00d8abffd4336b3
|
Java
|
mertcan14/hrmsProject2
|
/hrmsproject/src/main/java/kodlamaio/hrmsproject/businees/abstracts/JobSeekerKnowledgeService.java
|
UTF-8
| 427
| 1.859375
| 2
|
[] |
no_license
|
package kodlamaio.hrmsproject.businees.abstracts;
import java.util.List;
import kodlamaio.hrmsproject.core.utilities.results.DataResult;
import kodlamaio.hrmsproject.core.utilities.results.Result;
import kodlamaio.hrmsproject.entities.concretes.JobSeekerKnowledge;
public interface JobSeekerKnowledgeService {
Result add(JobSeekerKnowledge jobSeekerKnowledge);
DataResult<List<JobSeekerKnowledge>> getByUserId(int id);
}
| true
|
585d2d6a49406a013281cddfca3722f374fcf2bf
|
Java
|
dekzz/design-patterns
|
/WebBrowserCache/src/org/dt/Strategy/NKPageRemove.java
|
UTF-8
| 1,174
| 2.734375
| 3
|
[] |
no_license
|
package org.dt.Strategy;
import java.util.HashMap;
import java.util.Map;
import org.dt.datomala_zadaca_4.FileHandler;
import org.dt.datomala_zadaca_4.Log;
import java.util.Date;
import org.dt.MVC.Model.CacheModel;
public class NKPageRemove implements RemovalStrategy{
@Override
public void execute(HashMap<String, CacheModel> map_) {
String mostUsedKey = "";
CacheModel mostUsed = new CacheModel();
for (Map.Entry pair : map_.entrySet()) {
CacheModel temp = (CacheModel)pair.getValue();
if(temp.getTimesUsed() >= mostUsed.getTimesUsed()) {
mostUsedKey = (String)pair.getKey();
mostUsed = temp;
}
}
FileHandler.deleteFile(mostUsed.getStoragePath());
map_.remove(mostUsedKey);
Log.getInstance().writeLog("DEL | File '" + mostUsed.getStoragePath() + "' (" + mostUsedKey + ")"
+ " removed from cache/storage after " + (new Date().getTime() - mostUsed.getTimeStored().getTime()) /1000
+ " sec of activity with " + mostUsed.getTimesUsed() + " times being used!");
}
}
| true
|
633ee0bccac9b8fdae69845bd187c78d38306509
|
Java
|
alpome/bandcamp-file-fixer
|
/bcff.java
|
UTF-8
| 5,770
| 2.984375
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Arrays;
import java.util.List;
import static java.lang.System.exit;
/***
* @author Alexander Merluzzi
* @date February 27 2020
* @title Bandcamp File Fixer - BCFF
* This is a small utility with the purpose of renaming songs downloaded from
* Bandcamp to remove the artist and album name prepended to every track.
*
* Something about the way Java (or CMD?) handles Unicode prevents inputting an initial
* folder with Unicode.
*/
class bcff{
final static String REGEX = ".* - .* - .*";
final static String PATH = "";
final static double ver = 0.8;
//static ArrayList<String> list = new ArrayList<String>();
static FilenameFilter fnf = new FilenameFilter() {
public boolean accept(File dir, String filename) {
if (filename.endsWith(".zip"))
System.out.println("Zip archive - skipped");
return !filename.endsWith(".zip");
}
};
/**
*
* @param args
*/
public static void main(String[] args){
//Scanner in = new Scanner(System.in, "UTF-8");
File folder = null;
boolean recurse = false, rmv_art = false, rmv_alb = false;
//@TODO Finish code to use CLI arguments rather than Scanner
if (args.length <= 0) {
System.out.println("Bandcamp File Fixer - BCFF v " + ver);
exit(1);
} else {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-r":
recurse = true;
break;
case "-ar":
//set remove artist flag to either TRUE or FALSE
rmv_art = true;
System.out.println("Removing only artist name");
break;
case "-al":
//set remove album flag to either TRUE or FALSE
rmv_alb = true;
System.out.println("Removing only album name");
break;
case "-v":
System.out.println("BCFF version " + ver);
System.exit(0);
case "-h":
System.out.println("Options:");
System.out.println("-h Print this text and exit");
System.out.println("-v Print version number and exit");
System.out.println("-r Recurse through sub-folders nestled under provided directory. Default is false.");
System.out.println("-ar Remove artist name only. Default is false. (Not yet implemented.)");
System.out.println("-al Remove album name only. Default is false. (Not yet implemented.)");
System.out.println("-m Rename music files only. Default is false. (Not yet implemented.)");
System.exit(0);
default:
//Check if input is a valid file directory and begin process
//otherwise quit program
String dir = args[i];
folder = new File(dir);
if (!folder.exists() && !folder.isDirectory()){
System.out.println("Path provided - " + dir + " - either does not exist or is not a directory.");
System.exit(1);
}
}
}
}
/*
Loop to get valid directory as input
do{
System.out.print("Provide path to directory: ");
String dir = in.nextLine();
folder = new File(dir);
System.out.println(folder);
System.out.println(folder.exists());
System.out.println(folder.isDirectory());
System.out.println(folder.isFile());
if (!folder.exists() && !folder.isDirectory()){
System.out.println("Path provided - " + dir + " - either does not exist or is not a directory.");
folder = null;
}
} while (folder == null);
in.close();*/
File[] ff = folder.listFiles(fnf);
if (ff == null){
System.out.println("There are no files to rename in this folder.");
System.exit(1);
}
if (recurse) {
/*
Checks if directory contains any files or subdirectories, ignoring .zip archives
Calls file tree stepping function if files/subdirectories are found
*/
try {
if (ff.length > 0) {
checkTree(ff);
} else {
if (ff == null)
System.out.println("No file list found");
else if (ff.length <= 0)
System.out.println("File list length is less than or equal to 0: " + ff.length);
}
} catch (NullPointerException npe) {
System.out.println("Provided directory is empty");
}
} else {
if (ff != null) {
System.out.println("Renaming only top-level files");
for (File f : ff)
rename(f);
}
}
}
/**
* A function to check the provided file list and either call itself on any subdirectories
* or appropriately rename any music files it may find
* @param files
*/
static void checkTree(File[] files){
Pattern n = Pattern.compile(REGEX);
Matcher m;
for (File f: files){
m = n.matcher(f.getName());
if (f.isDirectory()){
checkTree(f.listFiles(fnf));
} else {
//if (m.matches())
rename(f);
}
}
}
/**
* A function to check that a provided file is (a) a supported music file and
* (b) conforms to normal Bandcamp naming conventions.
* It then renames the file according to how the user has specified.
* @param file
*/
static void rename(File file){
String name = file.getName(), fixed_name = null;
String path = file.getPath(), fixed_path = path.replace(name, "");
String parent_f = file.getParentFile().getName();
if (name.contains(parent_f)){
//System.out.println("Renaming " + name);
fixed_name = name.replace(parent_f, "").substring(3);
file.renameTo(new File(fixed_path + fixed_name));
//System.out.println("Renamed to " + fixed_name);
}
}
/**
* Checks whether a provided file is a supported music file
* @param file
* @return
*/
//@TODO finish
static Boolean supportedExt(File file){
return true;
}
}
| true
|
1c87dc451153ddead7978da19cb7d693a17aef50
|
Java
|
googleapis/google-cloud-java
|
/java-contentwarehouse/proto-google-cloud-contentwarehouse-v1/src/main/java/com/google/cloud/contentwarehouse/v1/DocumentSchemaServiceProto.java
|
UTF-8
| 12,199
| 1.796875
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2023 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/contentwarehouse/v1/document_schema_service.proto
package com.google.cloud.contentwarehouse.v1;
public final class DocumentSchemaServiceProto {
private DocumentSchemaServiceProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_CreateDocumentSchemaRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_CreateDocumentSchemaRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_GetDocumentSchemaRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_GetDocumentSchemaRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_UpdateDocumentSchemaRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_UpdateDocumentSchemaRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_DeleteDocumentSchemaRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_DeleteDocumentSchemaRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n>google/cloud/contentwarehouse/v1/docum"
+ "ent_schema_service.proto\022 google.cloud.c"
+ "ontentwarehouse.v1\032\034google/api/annotatio"
+ "ns.proto\032\027google/api/client.proto\032\037googl"
+ "e/api/field_behavior.proto\032\031google/api/r"
+ "esource.proto\0326google/cloud/contentwareh"
+ "ouse/v1/document_schema.proto\032\033google/pr"
+ "otobuf/empty.proto\"\261\001\n\033CreateDocumentSch"
+ "emaRequest\022A\n\006parent\030\001 \001(\tB1\342A\001\002\372A*\n(con"
+ "tentwarehouse.googleapis.com/Location\022O\n"
+ "\017document_schema\030\002 \001(\01320.google.cloud.co"
+ "ntentwarehouse.v1.DocumentSchemaB\004\342A\001\002\"a"
+ "\n\030GetDocumentSchemaRequest\022E\n\004name\030\001 \001(\t"
+ "B7\342A\001\002\372A0\n.contentwarehouse.googleapis.c"
+ "om/DocumentSchema\"\265\001\n\033UpdateDocumentSche"
+ "maRequest\022E\n\004name\030\001 \001(\tB7\342A\001\002\372A0\n.conten"
+ "twarehouse.googleapis.com/DocumentSchema"
+ "\022O\n\017document_schema\030\002 \001(\01320.google.cloud"
+ ".contentwarehouse.v1.DocumentSchemaB\004\342A\001"
+ "\002\"d\n\033DeleteDocumentSchemaRequest\022E\n\004name"
+ "\030\001 \001(\tB7\342A\001\002\372A0\n.contentwarehouse.google"
+ "apis.com/DocumentSchema\"\206\001\n\032ListDocument"
+ "SchemasRequest\022A\n\006parent\030\001 \001(\tB1\342A\001\002\372A*\n"
+ "(contentwarehouse.googleapis.com/Locatio"
+ "n\022\021\n\tpage_size\030\002 \001(\005\022\022\n\npage_token\030\003 \001(\t"
+ "\"\202\001\n\033ListDocumentSchemasResponse\022J\n\020docu"
+ "ment_schemas\030\001 \003(\01320.google.cloud.conten"
+ "twarehouse.v1.DocumentSchema\022\027\n\017next_pag"
+ "e_token\030\002 \001(\t2\225\t\n\025DocumentSchemaService\022"
+ "\356\001\n\024CreateDocumentSchema\022=.google.cloud."
+ "contentwarehouse.v1.CreateDocumentSchema"
+ "Request\0320.google.cloud.contentwarehouse."
+ "v1.DocumentSchema\"e\332A\026parent,document_sc"
+ "hema\202\323\344\223\002F\"3/v1/{parent=projects/*/locat"
+ "ions/*}/documentSchemas:\017document_schema"
+ "\022\336\001\n\024UpdateDocumentSchema\022=.google.cloud"
+ ".contentwarehouse.v1.UpdateDocumentSchem"
+ "aRequest\0320.google.cloud.contentwarehouse"
+ ".v1.DocumentSchema\"U\332A\024name,document_sch"
+ "ema\202\323\344\223\002823/v1/{name=projects/*/location"
+ "s/*/documentSchemas/*}:\001*\022\305\001\n\021GetDocumen"
+ "tSchema\022:.google.cloud.contentwarehouse."
+ "v1.GetDocumentSchemaRequest\0320.google.clo"
+ "ud.contentwarehouse.v1.DocumentSchema\"B\332"
+ "A\004name\202\323\344\223\0025\0223/v1/{name=projects/*/locat"
+ "ions/*/documentSchemas/*}\022\261\001\n\024DeleteDocu"
+ "mentSchema\022=.google.cloud.contentwarehou"
+ "se.v1.DeleteDocumentSchemaRequest\032\026.goog"
+ "le.protobuf.Empty\"B\332A\004name\202\323\344\223\0025*3/v1/{n"
+ "ame=projects/*/locations/*/documentSchem"
+ "as/*}\022\330\001\n\023ListDocumentSchemas\022<.google.c"
+ "loud.contentwarehouse.v1.ListDocumentSch"
+ "emasRequest\032=.google.cloud.contentwareho"
+ "use.v1.ListDocumentSchemasResponse\"D\332A\006p"
+ "arent\202\323\344\223\0025\0223/v1/{parent=projects/*/loca"
+ "tions/*}/documentSchemas\032S\312A\037contentware"
+ "house.googleapis.com\322A.https://www.googl"
+ "eapis.com/auth/cloud-platformB\202\002\n$com.go"
+ "ogle.cloud.contentwarehouse.v1B\032Document"
+ "SchemaServiceProtoP\001ZPcloud.google.com/g"
+ "o/contentwarehouse/apiv1/contentwarehous"
+ "epb;contentwarehousepb\252\002 Google.Cloud.Co"
+ "ntentWarehouse.V1\312\002 Google\\Cloud\\Content"
+ "Warehouse\\V1\352\002#Google::Cloud::ContentWar"
+ "ehouse::V1b\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.contentwarehouse.v1.DocumentSchemaProto.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
});
internal_static_google_cloud_contentwarehouse_v1_CreateDocumentSchemaRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_contentwarehouse_v1_CreateDocumentSchemaRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_CreateDocumentSchemaRequest_descriptor,
new java.lang.String[] {
"Parent", "DocumentSchema",
});
internal_static_google_cloud_contentwarehouse_v1_GetDocumentSchemaRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_contentwarehouse_v1_GetDocumentSchemaRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_GetDocumentSchemaRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_contentwarehouse_v1_UpdateDocumentSchemaRequest_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_contentwarehouse_v1_UpdateDocumentSchemaRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_UpdateDocumentSchemaRequest_descriptor,
new java.lang.String[] {
"Name", "DocumentSchema",
});
internal_static_google_cloud_contentwarehouse_v1_DeleteDocumentSchemaRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_contentwarehouse_v1_DeleteDocumentSchemaRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_DeleteDocumentSchemaRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasRequest_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasRequest_descriptor,
new java.lang.String[] {
"Parent", "PageSize", "PageToken",
});
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasResponse_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_contentwarehouse_v1_ListDocumentSchemasResponse_descriptor,
new java.lang.String[] {
"DocumentSchemas", "NextPageToken",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.contentwarehouse.v1.DocumentSchemaProto.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| true
|
00b49301374fbcbe102a01a429d3338829eadfe1
|
Java
|
liu67224657/besl-platform
|
/framework/src/main/java/com/enjoyf/platform/service/event/system/SystemEventType.java
|
UTF-8
| 11,770
| 1.625
| 2
|
[] |
no_license
|
/**
* CoryRight 2011 fivewh.com
*/
package com.enjoyf.platform.service.event.system;
import com.google.common.base.Strings;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: <a mailto="yinpengyi@fivewh.com">Yin Pengyi</a>
* Create time: 11-8-17 下午1:23
* Description:
*/
public class SystemEventType implements Serializable {
private static Map<String, SystemEventType> map = new HashMap<String, SystemEventType>();
//new accoun register.
public static final SystemEventType ACCOUNT_REGISTER = new SystemEventType("account.register");
public static final SystemEventType INVITE_REGISTER = new SystemEventType("invite.register");
//timeline insert events.
public static final SystemEventType TIMELINE_INSERT = new SystemEventType("timeline.insert");
public static final SystemEventType TIMELINE_REMOVE = new SystemEventType("timeline.remove");
public static final SystemEventType TIMELINE_INIT = new SystemEventType("timeline.init");
public static final SystemEventType TIMELINE_FOCUS_REMOVE = new SystemEventType("timeline.focus.remove");
public static final SystemEventType TIMELINE_FAVORITE_CONTENT_INSERT = new SystemEventType("timeline.favorite.content.insert");
public static final SystemEventType TIMELINE_FAVORITE_CONTENT_REMOVE = new SystemEventType("timeline.favorite.content.remove");
//notice insert events
public static final SystemEventType NOTICE_INSERT = new SystemEventType("notice.insert");
public static final SystemEventType NOTICE_RESET = new SystemEventType("notice.reset");
//social broadcast event
public static final SystemEventType SOCIAL_CONTENT_POST_BROADCAST = new SystemEventType("social.content.post.broadcast");
public static final SystemEventType SOCIAL_CONTENT_REMOVE_BROADCAST = new SystemEventType("social.content.remove.broadcast");
public static final SystemEventType SOCIAL_REPLY_POST_BROADCAST = new SystemEventType("social.reply.post.broadcast");
public static final SystemEventType SOCIAL_REPLY_REMOVE_BROADCAST = new SystemEventType("social.reply.remove.broadcast");
public static final SystemEventType SOCIAL_CATEGORY_REMOVE = new SystemEventType("social.category.remove");
public static final SystemEventType SOCIAL_CONTENT_FAVORITE_BROADCAST = new SystemEventType("social.content.favorite.broadcast");
public static final SystemEventType SOCIAL_CONTENT_FAVORITE_REMOVE_BROADCAST = new SystemEventType("social.content.favorite.remove.broadcast");
//content sum increase event
public static final SystemEventType CONTENT_SUM_INCREASE = new SystemEventType("content.sum.increase");
public static final SystemEventType CONTENT_SUM_SET = new SystemEventType("content.sum.set");
public static final SystemEventType CONTENT_FAVORITE = new SystemEventType("content.favorite");
public static final SystemEventType CONTENT_FAVORITE_REMOVE = new SystemEventType("content.favorite.remove");
public static final SystemEventType CONTENT_REPLIED = new SystemEventType("content.replied");
public static final SystemEventType CONTENT_POST = new SystemEventType("content.post");
public static final SystemEventType CONTENT_RELATION_CREATE = new SystemEventType("content.relation.create");
public static final SystemEventType CONTENT_RELATION_REMOVE = new SystemEventType("content.relation.remove");
public static final SystemEventType SOCIAL_CONTENT_RELATION_CREATE = new SystemEventType("social.content.relation.create");
public static final SystemEventType SOCIAL_TIMELINE_RELATION_CREATE = new SystemEventType("social.timeline.relation.create");
public static final SystemEventType SOCIAL_TIMELINE_RELATION_REMOVE = new SystemEventType("social.timeline.relation.remove");
public static final SystemEventType CONTENT_INTERACTION_SUM_INCREASE = new SystemEventType("contentinteraction.sum.increase");
public static final SystemEventType SOCIAL_CONTENT_HOT_INSERT = new SystemEventType("social.content.hot.insert");
public static final SystemEventType HOT_ACTIVITY = new SystemEventType("content.activity.hot.ranks");
//profile sum increase event
public static final SystemEventType PROFILE_SUM_SET = new SystemEventType("profile.sum.set");
public static final SystemEventType PROFILE_ONLINE_ON = new SystemEventType("profile.online.on");
public static final SystemEventType PROFILE_ONLINE_OFF = new SystemEventType("profile.online.off");
public static final SystemEventType PROFILE_LAST_INTERACTION_INCREASE = new SystemEventType("profile.last.interaction.increase");
public static final SystemEventType CHECK_PROFILE_MOBILE_DEVICE = new SystemEventType("check.profile.mobile.device");
//habit tag
public static final SystemEventType HABIT_TAG_SAVE = new SystemEventType("habit.tag.save");
//short url
public static final SystemEventType SHORTURL_SUM_INCREASE = new SystemEventType("shorturl.sum.increase");
public static final SystemEventType SYNC_POST_CONTENT = new SystemEventType("sync.post.content");
public static final SystemEventType RESOURCE_IOS_INSERT = new SystemEventType("resource.ios.insert");
public static final SystemEventType GAME_SUM_INCREASE = new SystemEventType("game.sum.increase");
public static final SystemEventType BILLING_ENCOURAGE_EVENT = new SystemEventType("billing.encourage");
//viewline
public static final SystemEventType VIEWLINE_ITEM_SUM_INCREASE_EVENT = new SystemEventType("viewline.item.sumincrease");
public static final SystemEventType VIEWLINE_ITEM_INSERT_EVENT = new SystemEventType("viewline.item.insert");
public static final SystemEventType VIEWLINE_ITEM_REMOVE_EVENT = new SystemEventType("viewline.item.remove");
public static final SystemEventType VIEWLINE_POST_SYSTEM_MESSAGE_EVENT = new SystemEventType("viewline.post.system.message");
//advertise events
public static final SystemEventType ADV_PUBLISH_CLICK = new SystemEventType("adv.publish.click");
public static final SystemEventType ADV_PAGE_VIEW = new SystemEventType("adv.page.view");
public static final SystemEventType ADV_USER_REGISTER = new SystemEventType("adv.user.register");
public static final SystemEventType SOCIAL_RECOMMEND_EVENT = new SystemEventType("social.recommend.event");
public static final SystemEventType SOCIAL_RECOMMEND_MODIFY_EVENT = new SystemEventType("social.recommend.modify");
public static final SystemEventType JOYMEAPP_PUSHMESSAGEDEVICE_REGISTER = new SystemEventType("joymeapp.pushmessagedevice.register");
public static final SystemEventType SHARE_EXCHANGE_GIFT = new SystemEventType("share.exchange.gift");
public static final SystemEventType ACTIVITY_CALEVENTTIME_GIFT = new SystemEventType("activity.event.type");
public static final SystemEventType MESSAGE_SOCIAL_MESSAGE_CREATE = new SystemEventType("message.social.message.create");
public static final SystemEventType LOCATION_INSERT = new SystemEventType("location.insert");
public static final SystemEventType SOCIAL_INCREASE_SUM = new SystemEventType("social.increase.sum");
public static final SystemEventType USER_POINT_INCREASE = new SystemEventType("point.user.point.increase");
public static final SystemEventType SOCIAL_DEFAULT_FOCUS = new SystemEventType("social.default.focus");
public static final SystemEventType PROFILE_SOLRJ_EVENT = new SystemEventType("profile.solrj.event");
public static final SystemEventType USERCENTER_SUM_INCREASE = new SystemEventType("usercenter.sum.increase");
public static final SystemEventType TASK_AWARD_EVENT = new SystemEventType("task.award.event");
public static final SystemEventType GAMEDB_MODIFYTIME_EVENT = new SystemEventType("gamedb.modifytime.event");
public static final SystemEventType GAMEDB_PC_AGREE_EVENT = new SystemEventType("gamedb.pc.agree.event");
public static final SystemEventType GAMEDB_SUM_INCREASE_EVENT = new SystemEventType("gamedb.sum.increase");
public static final SystemEventType PROFILE_SUM_INCREASE = new SystemEventType("profile.sum.increase");
public static final SystemEventType USERRELATION_BUILD = new SystemEventType("userrelation.build");
public static final SystemEventType USERRELATION_REMOVE = new SystemEventType("userrelation.remove");
public static final SystemEventType USERTIMELINE_INSERT = new SystemEventType("usertimeline.insert");
public static final SystemEventType USERTIMELINE_INSERT_BOARD = new SystemEventType("usertimeline.insert.board");
//push
public static final SystemEventType APP_PUSH_EVENT = new SystemEventType("app.push.event");
public static final SystemEventType ACTIVITY_USER = new SystemEventType("activity.user");
//GameClient
public static final SystemEventType GAMECLIENT_MIYOU_POST_EVENT = new SystemEventType("gc.miyou.post");
public static final SystemEventType MIYOU_ADD_LONGSUM = new SystemEventType("miyou.add.longsum");
//pc
public static final SystemEventType PCSTAT_GAME_STAT_PCSTAT_EVENT = new SystemEventType("pcstat.game.stat.pcstat.event");
//new accoun register.
public static final SystemEventType ADVERTISE_DEVICE_ACTIVITY = new SystemEventType("advertise.device.activity");
public static final SystemEventType ADVERTISE_DEVICE_CLICK = new SystemEventType("advertise.device.click");
/////////UGC wiki//////////////////
public static final SystemEventType WIKI_PROFILE_SUM_INCREASE = new SystemEventType("wiki.profile.sum.increase");
public static final SystemEventType WIKI_NOTICE = new SystemEventType("wiki.notice.send");
public static final SystemEventType WIKI_SOCIAL_STATUS_BROAD = new SystemEventType("wiki.social.broad");
public static final SystemEventType JOYMEAPP_CLIENT_LINE_ITEM = new SystemEventType("client.line.item");
public static final SystemEventType GAME_INCR_COLLECTION_LIST_CACHE = new SystemEventType("incr.game.collection.list.cache");
public static final SystemEventType VOTE_KEY = new SystemEventType("vote.key");
public static final SystemEventType WANBA_PROFILESUM_INCREASE = new SystemEventType("wanba.profilesum.increase");
public static final SystemEventType WANBA_QUESTION_NOTICE = new SystemEventType("wanba.question.notice");
public static final SystemEventType WANBA_REPLY_NOTICE = new SystemEventType("wanba.reply.notice");
public static final SystemEventType WIKI_NOTICE_EVENT=new SystemEventType("wiki.notice.event");
public static final SystemEventType WIKIAPP_ADDSEARCH_EVENT=new SystemEventType("wikiapp.addsearch.event");
public static final SystemEventType WIKIAPP_DELSEARCH_EVENT=new SystemEventType("wikiapp.delsearch.event");
//point evnt
public static final SystemEventType POINT_RECOMMEND_EVENT = new SystemEventType("point.recommend");
//
private String code;
public SystemEventType(String c) {
this.code = c.toLowerCase();
map.put(code, this);
}
public String getCode() {
return code;
}
@Override
public int hashCode() {
return code.hashCode();
}
@Override
public String toString() {
return "SystemEventType: code=" + code;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj instanceof SystemEventType)) {
return false;
}
return code.equalsIgnoreCase(((SystemEventType) obj).getCode());
}
public static SystemEventType getByCode(String c) {
if (Strings.isNullOrEmpty(c)) {
return null;
}
return map.get(c.toLowerCase());
}
public static Collection<SystemEventType> getAll() {
return map.values();
}
}
| true
|
8a9464f4342a627d0e34396e54df469bdb8dac83
|
Java
|
toroman/raf-block
|
/src/edu/raf/gef/gui/swing/menus/MenuManagerSAXImporter.java
|
UTF-8
| 4,359
| 2.140625
| 2
|
[] |
no_license
|
/*
RAF GEF - Graphical Editor Framework
Copyright (C) <2007> Srecko Toroman, Ivan Bocic
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/>.
*/
package edu.raf.gef.gui.swing.menus;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import edu.raf.gef.app.IResources;
import edu.raf.gef.gui.actions.GlobalAction;
/**
* Parses Menu XML file and fills the menu manager with the standard menus
* configuration.
* <p>
* This class doesn't <i>sucks</i>! It is a SAX2.0 handler for our menu xml
* format.
*
* @since May 28. 2008.
* @version 1.0
* @author Srecko Toroman (Срећко Тороман) <a
* href="mailto:sreckotoroman@gmail.com">sreckotoroman@gmail.com</a>
*/
public class MenuManagerSAXImporter extends DefaultHandler {
private MenuManager manager;
private Stack<String> xpath;
private IResources resources;
public static void fillMenu(MenuManager menu, InputStream is, IResources resources)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
try {
SAXParser parser = saxFactory.newSAXParser();
parser.parse(is, new MenuManagerSAXImporter(menu, resources));
} finally {
try {
is.close();
} catch (Throwable ex) {
}
}
}
public MenuManagerSAXImporter(MenuManager manager, IResources resources) {
this.manager = manager;
this.resources = resources;
}
@Override
public void startElement(String uri, String localName, String name, Attributes attr)
throws SAXException {
// root element
if ("menubar".equalsIgnoreCase(name)) {
xpath = new Stack<String>();
xpath.add(MenuManager.ROOT);
} else if ("container".equals(name)) {
String parentPart = xpath.peek();
String id = attr.getValue("id");
if (id == null) {
// TODO: add XML Scheme instead and don't check manually?
throw new SAXException("ID musn't be null! Element: " + name);
}
MenuPartContainer container = manager.createContainer(parentPart, id);
String text = attr.getValue("text");
container.getMenu().setText(text != null ? text : id);
String mnemonic = attr.getValue("mnemonic");
if (mnemonic != null)
container.getMenu().setMnemonic(mnemonic.charAt(0));
String icon = attr.getValue("icon");
container.getMenu().setIcon(icon != null ? resources.getIcon(icon) : null);
xpath.push(id);
} else if ("part".equals(name)) {
String parentContainer = xpath.peek();
String id = attr.getValue("id");
if (id == null) {
// TODO: add XML Scheme instead and don't check manually?
throw new SAXException("ID musn't be null! Element: " + name);
}
manager.createPart(parentContainer, id);
xpath.push(id);
} else if ("action".equals(name)) {
String id = attr.getValue("id");
try {
// StandardOverridableAction action = new
// StandardOverridableAction(manager
// .getParent(), id);
GlobalAction action = new GlobalAction(manager.getParent(), id);
String parentPart = xpath.peek();
manager.addAction(parentPart, action);
} catch (Exception e) {
log.log(Level.SEVERE, "Couldn't create action id=" + id, e);
return;
}
}
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
if ("menubar".equals(name)) {
xpath.clear();
xpath = null;
} else if ("container".equals(name)) {
xpath.pop();
} else if ("part".equals(name)) {
xpath.pop();
}
}
private static final Logger log = Logger.getLogger(MenuManagerSAXImporter.class.getName());
}
| true
|
2a3be8438bb8f76d401bd17a51ac0eaff3bb4cb6
|
Java
|
akotynski/empiria.player
|
/src/main/java/eu/ydp/empiria/player/client/module/dictionary/external/controller/ExplanationController.java
|
UTF-8
| 2,948
| 2.328125
| 2
|
[] |
no_license
|
package eu.ydp.empiria.player.client.module.dictionary.external.controller;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.user.client.ui.IsWidget;
import eu.ydp.empiria.player.client.gin.factory.DictionaryModuleFactory;
import eu.ydp.empiria.player.client.module.dictionary.external.model.Entry;
import eu.ydp.empiria.player.client.module.dictionary.external.view.ExplanationView;
import javax.inject.Inject;
public class ExplanationController {
private final ExplanationView explanationView;
private Entry entry;
private final ExplanationDescriptionSoundController explanationDescriptionSoundController;
private final EntryDescriptionSoundController entryDescriptionSoundController;
@Inject
public ExplanationController(ExplanationView explanationView,
DictionaryModuleFactory dictionaryModuleFactory) {
this.explanationView = explanationView;
this.explanationDescriptionSoundController = dictionaryModuleFactory.getExplanationDescriptionSoundController(explanationView);
this.entryDescriptionSoundController = dictionaryModuleFactory.geEntryDescriptionSoundController(explanationView);
}
public void init() {
addExplanationPlayButtonHandler();
addEntryExamplePanelHandler();
addEntryPlayButtonHandler();
}
public void processEntry(Entry entry) {
explanationView.processEntry(entry);
this.entry = entry;
}
public void show() {
explanationView.show();
}
public void hide() {
explanationDescriptionSoundController.stop();
entryDescriptionSoundController.stop();
explanationView.hide();
}
public IsWidget getView() {
return explanationView;
}
private void addEntryExamplePanelHandler() {
this.explanationView.addEntryExamplePanelHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
entryDescriptionSoundController.playOrStopEntrySound(entry.getEntrySound());
}
});
}
private void addExplanationPlayButtonHandler() {
this.explanationView.addPlayButtonHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
explanationDescriptionSoundController.playOrStopExplanationSound(entry.getEntryExampleSound());
}
});
}
private void addEntryPlayButtonHandler() {
this.explanationView.addEntryPlayButtonHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
entryDescriptionSoundController.playOrStopEntrySound(entry.getEntrySound());
}
});
}
}
| true
|
8edb5713ed748dacf6d570a2d97c1dd299d3282d
|
Java
|
wuxiaolee/spring-batch-demo
|
/springbatch-mybatis/src/test/java/com/wl/service/JobSplitDemoConfigurationTest.java
|
UTF-8
| 1,499
| 1.8125
| 2
|
[] |
no_license
|
package com.wl.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JobSplitDemoConfigurationTest {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job jobSplitDemoJob;
@Test
public void launchJobSplit() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
JobParameters jobParameters = new JobParametersBuilder().addDate("time", new Date()).toJobParameters();
jobLauncher.run(jobSplitDemoJob, jobParameters);
}
}
| true
|
d90ca014f80f2a11c43c56b989a4607db2711197
|
Java
|
enjoygeek/FaceDetection
|
/facedetection-integration/src/main/java/com/cloud/remote/FacePlusPlusProcessResult.java
|
UTF-8
| 3,049
| 2.46875
| 2
|
[] |
no_license
|
package com.cloud.remote;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import com.cloud.dto.Coordinate2D;
import com.cloud.dto.FaceDetection;
import com.cloud.dto.Image;
import com.cloud.dto.ProcessResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FacePlusPlusProcessResult extends ProcessResult {
public FacePlusPlusProcessResult(String endpoint) {
super(endpoint);
}
/*
* private Image parseImageData(Map<String, Object> processResult) throws
* Exception { String url = String.valueOf(processResult.get("url"));//El
* webservice retorna la url completa con la extension String extensionImage
* ="."+FilenameUtils.getExtension(url); url =
* FilenameUtils.removeExtension(url); Integer imgWidth =
* Integer.valueOf(String.valueOf(processResult .get("img_width"))); Integer
* imgheight = Integer.valueOf(String.valueOf(processResult
* .get("img_height"))); Boolean download = false; return new
* Image(url,imgWidth, imgheight, download ); }
*/
public FaceDetection parseFace(Map<String, Object> attributes) {
FaceDetection faceDetection = new FaceDetection();
if (!attributes.containsKey("position"))
return faceDetection;
Map<String, Object> position = (Map<String, Object>) attributes.get("position");
if (!position.containsKey("eye_left"))
return faceDetection;
Map<String, Double> eye_left = (Map<String, Double>) position.get("eye_left");
if (!position.containsKey("eye_right"))
return faceDetection;
Map<String, Double> eye_right = (Map<String, Double>) position.get("eye_right");
Integer[] eyeLeft = new Integer[] { new Double(eye_left.get("x") / 100 * this.image.getWidth()).intValue(),
new Double(eye_left.get("y") / 100 * this.image.getHeight()).intValue(), };
Integer[] eyeRight = new Integer[] { new Double(eye_right.get("x") / 100 * this.image.getWidth()).intValue(),
new Double(eye_right.get("y") / 100 * this.image.getHeight()).intValue(), };
Coordinate2D ojoIzquierdo = new Coordinate2D(eyeLeft[0], eyeLeft[1]);
Coordinate2D ojoDerecho = new Coordinate2D(eyeRight[0], eyeRight[1]);
faceDetection.setLeftEye(ojoIzquierdo);
faceDetection.setRightEye(ojoDerecho);
return faceDetection;
}
@Override
public void process(Map<String, Object> processResult) throws Exception {
this.setServiceOutput(processResult.toString());
// this.setImage(parseImageData(processResult));
// Get detected faces
if (!processResult.containsKey("face")) return ;
List<Object> faces = (List<Object>) processResult.get("face");
// For each face, recover eye positions
for (Object face : faces) {
Map<String, Object> attributes = (Map<String, Object>) face;
this.image.addDetections(parseFace(attributes));
}
}
@Override
public String toString() {
ObjectMapper om = new ObjectMapper();
try {
return om.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
}
}
| true
|
d1c41a972de7471e278cc01f17ae9976fdcf4ac3
|
Java
|
marcusgalvin/JavaGiraffe
|
/Giraffe/src/Methods.java
|
UTF-8
| 283
| 3.203125
| 3
|
[] |
no_license
|
public class Methods {
public static void main (String [] args)
{
System.out.println("top");
sayHi("joe", 27);
System.out.println("bottom");
}
public static void sayHi(String name, int age)
{
System.out.println("Hi " + name + " you are " + age);
}
}
| true
|
1d601e4eac98e943d9de606764011af7d60b57e8
|
Java
|
hsine55/Algorithms
|
/src/minCut/GraphMinCut.java
|
UTF-8
| 3,420
| 3.09375
| 3
|
[] |
no_license
|
package minCut;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class GraphMinCut {
private static final String FILE_PATH = "testFiles/minCut/minCut.txt";
private static Map<Integer, List<Integer>> adjLists = new HashMap<>();
private static final Random rand = new Random();
private static Graph graph = new Graph();
private static void readGraphIntoAdjList() {
try {
FileReader fileReader = new FileReader(FILE_PATH);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while((line = bufferedReader.readLine()) != null) {
String[] splittedString = line.split("\\s+");
Integer currentVertex = Integer.valueOf(splittedString[0]);
List<Integer> adjacentVertices = new ArrayList<Integer>();
for(int i=1; i<splittedString.length; i++) {
adjacentVertices.add(Integer.valueOf(splittedString[i]));
}
adjLists.put(currentVertex, adjacentVertices);
}
bufferedReader.close();
}
catch(Exception e){
System.out.println("Error while reading file line by line: " + e.getMessage());
}
}
private static void createGraph() {
for(Integer vertexName : adjLists.keySet()) {
Vertex currentVertex = graph.getVertex(vertexName);
for(Integer edgeTo: adjLists.get(vertexName)) {
Vertex v2 = graph.getVertex(edgeTo);
Edge e;
if( (e = v2.getEdgeTo(currentVertex)) == null ) {
e = new Edge();
e.getEndPoints().add(v2);
e.getEndPoints().add(currentVertex);
graph.addEdge(e);
v2.addIncidentEdge(e);
currentVertex.addIncidentEdge(e);
}
}
}
}
private static void contract(Edge e) {
graph.removeEdge(e);
Vertex v1 = e.getEndPoints().get(0);
Vertex v2 = e.getEndPoints().get(1);
v1 = cleanVertex(e,v1);
v2 = cleanVertex(e,v2);
Vertex mergedVertex = new Vertex(v1.getLabel());
redirectEdges(v1, mergedVertex);
redirectEdges(v2, mergedVertex);
graph.addVertex(mergedVertex);
}
private static Edge chooseRandomEdge() {
Edge randomEdge = graph.getListOfEdges().get(rand.nextInt(graph.getListOfEdges().size()));
return randomEdge;
}
private static void redirectEdges(Vertex fromV, Vertex toV) {
for(Iterator<Edge> it=fromV.getIncidentEdges().iterator(); it.hasNext(); ) {
Edge e = it.next();
it.remove();
if (e.getOppositePoint(fromV) == toV) {
graph.removeEdge(e);
toV.removeIncidentEdge(e);
} else {
e.replaceEndPoint(fromV, toV);
toV.addIncidentEdge(e);
}
}
}
public static int calculateMinCut() {
while(graph.getListOfVertices().size() > 2) {
Edge e = chooseRandomEdge();
contract(e);
}
return graph.getListOfEdges().size();
}
private static Vertex cleanVertex(Edge e, Vertex v) {
graph.removeVertex(v.getLabel());
v.removeIncidentEdge(e);
return v;
}
public static void main(String[] args) {
int n=1;
long minCut = Long.MAX_VALUE;
readGraphIntoAdjList();
while(n<500) {
createGraph();
int currentCut = calculateMinCut();
if (currentCut < minCut) {
minCut = currentCut;
}
n +=1;
}
System.out.println(minCut);
}
}
| true
|
eebc804596275527a01b69adc407392ba4e204b3
|
Java
|
nikas90/book-shop
|
/src/main/java/org/angisource/bookshop/entity/Book.java
|
UTF-8
| 712
| 2.34375
| 2
|
[] |
no_license
|
package org.angisource.bookshop.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
@lombok.Getter
@lombok.Setter
@lombok.EqualsAndHashCode(of = "isbn")
@lombok.ToString(exclude="id")
@Entity
public class Book implements Serializable {
public Book() {}
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private long id;
@NotNull
@Size(min = 1)
@Column(unique = true)
private String isbn;
@NotNull
@Size(min = 1)
private String title;
@NotNull
@Size(min = 1)
private String author;
@NotNull
@Size(min = 1)
private String description;
}
| true
|
7dbeae8d4b892bbdd09e48acb6090f0f7e44b5a0
|
Java
|
xeraph/kraken
|
/detector/kraken-sonar/src/main/java/org/krakenapps/sonar/passive/ids/HttpAttackDetector.java
|
UTF-8
| 4,125
| 1.976563
| 2
|
[] |
no_license
|
package org.krakenapps.sonar.passive.ids;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.krakenapps.malwaredomains.MalwareDomain;
import org.krakenapps.malwaredomains.MalwareDomainService;
import org.krakenapps.pcap.Protocol;
import org.krakenapps.pcap.decoder.http.DefaultHttpProcessor;
import org.krakenapps.pcap.decoder.http.HttpRequest;
import org.krakenapps.pcap.decoder.http.HttpResponse;
import org.krakenapps.sonar.Metabase;
import org.krakenapps.sonar.PassiveScanner;
import org.krakenapps.sonar.passive.ids.checker.InjectionChecker;
import org.krakenapps.sonar.passive.ids.rule.Rule;
import org.krakenapps.sonar.passive.safebrowsing.GoogleSafeBrowsing;
import java.io.File;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(name = "sonar-http-attack-detector")
@Provides
public class HttpAttackDetector extends DefaultHttpProcessor {
private final Logger logger = LoggerFactory.getLogger(HttpAttackDetector.class.getName());
@Requires
private PassiveScanner scanner;
@Requires
private MalwareDomainService malwareDomainService;
private InjectionChecker injectionChecker;
private GoogleSafeBrowsing gsb;
final String DATA_PATH = System.getProperty("kraken.data.dir") + "/kraken-sonar/ids-rules/http/";
@Validate
public void start() {
// Create Data Location
prepareDataPath();
// Load RFI Injection script
injectionChecker = new InjectionChecker();
injectionChecker.setHomeDir(DATA_PATH);
injectionChecker.load();
// Load GoogleSafeBrowsing
gsb = new GoogleSafeBrowsing(DATA_PATH);
gsb.update();
scanner.addTcpSniffer(Protocol.HTTP, this);
logger.info("kraken sonar: http attack detector started.");
}
private void prepareDataPath() {
File dir = new File(DATA_PATH);
if (!dir.isDirectory()) {
dir.mkdirs();
}
}
@Invalidate
public void stop() {
if (scanner != null)
scanner.removeTcpSniffer(Protocol.HTTP, this);
}
@Override
public void onRequest(HttpRequest req) {
String rawUrl = req.getURL().toString();
String url = normalizeUrl(rawUrl);
logger.trace("kraken sonar: check url {}", url);
List<Rule> injections = injectionChecker.check(url);
if (!injections.isEmpty()) {
trace("Injection", rawUrl, injections);
// alert(rawUrl, "Injection",
// metabase.updateIpEndPoint(req.getLocalAddress()));
}
MalwareDomain malwareDomain = malwareDomainService.match(req.getURL());
if (malwareDomain != null) {
logger.info("kraken sonar: malware domain detected [{}]", malwareDomain);
}
int result = gsb.SafeCheck(url);
if (result == 1) {
// alert(rawUrl, "GSB-Malware",
// metabase.updateIpEndPoint(req.getLocalAddress()));
}
if (result == 2) {
// alert(rawUrl, "GSB-BlackList",
// metabase.updateIpEndPoint(req.getLocalAddress()));
}
}
@Override
public void onResponse(HttpRequest req, HttpResponse resp) {
}
private static String normalizeUrl(String originalURL) {
String url = "";
String[] tempSplit = originalURL.split("/");
String tempToken = tempSplit[0];
for (int i = 1; i < tempSplit.length; ++i) {
if (tempSplit[i].equals(".")) {
// this token "./" found! -> remove this token
} else if (tempSplit[i].equals("..")) {
// next token "../" found! -> remove this token and next token
tempToken = "[DEL]";
} else {
if (tempToken.equals("[DEL]") == false) {
url += tempToken + "/";
}
tempToken = tempSplit[i];
}
}
if (tempToken.isEmpty() == false) {
url += tempToken + "/";
}
return url;
}
private void trace(String title, String url, List<Rule> result) {
if (result.isEmpty() == false) {
System.out.println(title + " found! - '" + url + "'");
for (Rule r : result)
System.out.println(" >> " + r);
}
}
}
| true
|
55e8f5e9a50e21184d08ca5da545dd3fe5d3b5b0
|
Java
|
yyjianchi/taotao
|
/taotao-manager-web/src/main/java/com/taotao/controller/ContentController.java
|
UTF-8
| 1,473
| 1.921875
| 2
|
[] |
no_license
|
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.content.service.ContentService;
import com.taotao.easyuidatagridresult.EasyUIDataGridResult;
import com.taotao.pojo.TbContent;
import com.taotao.taotaoresult.TaotaoResult;
@Controller
public class ContentController {
@Autowired
private ContentService contentService;
@RequestMapping("/content/query/list")
@ResponseBody
public EasyUIDataGridResult getContent(@RequestParam(value="categoryId", defaultValue="0")Long catagoryId,int page,int rows){
return contentService.getContentList(catagoryId, page, rows);
}
@RequestMapping("/content/save")
@ResponseBody
public TaotaoResult addContent(TbContent content) {
TaotaoResult result = contentService.addContent(content);
return result;
}
@RequestMapping("/rest/content/edit")
@ResponseBody
public TaotaoResult updateContent(TbContent content){
TaotaoResult result=contentService.updateContent(content);
return result;
}
@RequestMapping("/content/delete")
@ResponseBody
public TaotaoResult deleteContent(String ids){
TaotaoResult result=contentService.deleteContent(ids);
return result;
}
}
| true
|
8f861b4b82cdbcddb1131377dec6bcf567c325f9
|
Java
|
amritsingh4100/oneness
|
/app/src/main/java/com/amrit/oneness/Activity/LoginAndRegisterScreen.java
|
UTF-8
| 1,780
| 2.078125
| 2
|
[] |
no_license
|
package com.amrit.oneness.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.amrit.oneness.Adapters.LoginAndRegisterFragmentAdapter;
import com.amrit.oneness.Adapters.ZoomOutPageTransformer;
import com.amrit.oneness.Customs.Utils;
import com.amrit.oneness.Interfaces.FragmentInterface;
import com.amrit.oneness.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginAndRegisterScreen extends AppCompatActivity implements FragmentInterface {
String TAG= getClass().getSimpleName();
FirebaseAuth mAuth;
ViewPager2 viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_and_register_layout);
intializeViews();
}
private void intializeViews()
{
mAuth = FirebaseAuth.getInstance();
viewPager= findViewById(R.id.login_and_register_viewpager_id);
LoginAndRegisterFragmentAdapter loginAndRegisterFragmentAdapter =new LoginAndRegisterFragmentAdapter(this,this);
viewPager.setPageTransformer(new ZoomOutPageTransformer());
viewPager.setUserInputEnabled(false);
viewPager.setAdapter(loginAndRegisterFragmentAdapter);
}
@Override
public void switchTo(int number) {
viewPager.setCurrentItem(number);
}
}
| true
|
383ecc3de743cedc7f3320fc0d78ac57c079b0be
|
Java
|
Adaptivity/Growthcraft-1.7
|
/src/java/growthcraft/core/integration/WailaIntegrationBase.java
|
UTF-8
| 330
| 1.882813
| 2
|
[] |
no_license
|
package growthcraft.core.integration;
import cpw.mods.fml.common.event.FMLInterModComms;
// Because sometimes you don't want to do stupid stuff over and over again
public class WailaIntegrationBase
{
public WailaIntegrationBase()
{
FMLInterModComms.sendMessage("Waila", "register", getClass().getName() + ".register");
}
}
| true
|
51773333961a478254e7713637ed88497ecc8f24
|
Java
|
Stomick/avfofun
|
/app/src/main/java/evfor/fun/skvader/ui/adapters/FilterableListAdapter.java
|
UTF-8
| 966
| 2.265625
| 2
|
[] |
no_license
|
package evfor.fun.skvader.ui.adapters;
import android.annotation.SuppressLint;
import evfor.fun.skvader.ui.utils.ListFilter;
import evfor.fun.skvader.ui.utils.iListFilter;
import evfor.fun.skvader.utils.Predicatable;
import java.util.List;
public abstract class FilterableListAdapter<T extends Predicatable, H extends BaseAdapter.ViewHolder>
extends ListAdapter<T, H> {
private iListFilter<T> filter;
FilterableListAdapter(List<T> list) {
super(list);
}
@Override
public void setList(List<T> list) {
super.setList(list);
filter = new ListFilter<>(list);
}
@SuppressLint("CheckResult")
public void filter(String text) {
filter.filter(text)
.subscribe(this::onChangeList);
}
private void onChangeList(iListFilter.ChangeList<T> changeList) {
addAll(changeList.getToAdd().listIterator());
removeAll(changeList.getToRemove().listIterator());
}
}
| true
|
87a44624755aac712000b75ee2cd4390378d7a06
|
Java
|
pikolinianita/SWTest-sec
|
/src/main/java/pl/sobczak/swapp/httpconsume/SwapiUrls.java
|
UTF-8
| 699
| 2.25
| 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 pl.sobczak.swapp.httpconsume;
/**
*
* @author piko
*/
public enum SwapiUrls {
PEOPLE("https://swapi.dev/api/people/"),
PLANET("https://swapi.dev/api/planets/"),
FILMS("https://swapi.dev/api/films/");
private final String urlAddress;
private SwapiUrls(String str) {
urlAddress = str;
}
public String getSearchUri() {
return urlAddress + "?search=";
}
public String getUri() {
return urlAddress;
}
}
| true
|
b3a4ac6ab64be8231775df95f8350eba0ea8e1ca
|
Java
|
tabria/BGXTrader
|
/src/main/java/trader/exit/service/ClosePositionService.java
|
UTF-8
| 1,877
| 2.9375
| 3
|
[] |
no_license
|
package trader.exit.service;
import trader.broker.BrokerGateway;
import trader.strategy.TradingStrategyConfiguration;
import trader.entity.trade.BrokerTradeDetails;
import java.math.BigDecimal;
import java.util.HashMap;
public class ClosePositionService {
private static final String MARKET_ORDER = "marketOrder";
private static final String INSTRUMENT = "instrument";
private static final String UNITS_SIZE = "unitsSize";
public ClosePositionService() {
}
public boolean closePosition(BrokerTradeDetails tradeDetails, BrokerGateway brokerGateway, TradingStrategyConfiguration configuration, BigDecimal partsToClose){
BigDecimal currentUnits = tradeDetails.getCurrentUnits();
if (partsToClose == null || partsToClose.compareTo(BigDecimal.ONE)< 0)
throw new IllegalArgumentException();
brokerGateway.placeOrder(createCloseSettings(currentUnits, configuration, partsToClose), MARKET_ORDER);
return true;
}
@Override
public String toString() {
return "position closed @";
}
private HashMap<String, String> createCloseSettings(BigDecimal currentUnits, TradingStrategyConfiguration configuration, BigDecimal partsToClose) {
HashMap<String, String> settings = new HashMap<>();
settings.put(INSTRUMENT, configuration.getInstrument());
settings.put(UNITS_SIZE, reverseUnitsSizeSign(currentUnits, partsToClose).toString());
return settings;
}
//multiply with -1 to reverse units size. This will open trade with opposite direction to the current trade
private BigDecimal reverseUnitsSizeSign(BigDecimal currentUnits, BigDecimal partsToClose) {
return currentUnits
.divide(partsToClose, 0, BigDecimal.ROUND_HALF_UP)
.multiply(BigDecimal.valueOf(-1)).setScale(0, BigDecimal.ROUND_HALF_UP);
}
}
| true
|
674dc7b58043fd0511a23c1cf13892141f0ea719
|
Java
|
DomenikaD/Factura
|
/src/ec/edu/ups/vista/VentanaEliminarCliente.java
|
UTF-8
| 5,144
| 2.109375
| 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 ec.edu.ups.vista;
import ec.edu.ups.controladores.ControladorCliente;
import javax.swing.JOptionPane;
/**
*
* @author Domenika Delgado
*/
public class VentanaEliminarCliente extends javax.swing.JInternalFrame {
private ControladorCliente controladorCliente;
/**
* Creates new form VentananEliminarCliente
*/
public VentanaEliminarCliente(ControladorCliente controladorCliente) {
initComponents();
this.controladorCliente = controladorCliente;
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
btnEliminar = new javax.swing.JButton();
txtCodigo = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btnCancelar = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
btnEliminar.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
btnEliminar.setText("Eliminar");
btnEliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEliminarActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(60, 30, 33, 0);
getContentPane().add(btnEliminar, gridBagConstraints);
txtCodigo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.ipadx = 84;
gridBagConstraints.ipady = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(33, 90, 0, 0);
getContentPane().add(txtCodigo, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(204, 51, 0));
jLabel1.setText("Ingrese Codigo del Cliente");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(20, 60, 0, 0);
getContentPane().add(jLabel1, gridBagConstraints);
btnCancelar.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
btnCancelar.setText("Cancelar");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(60, 61, 33, 27);
getContentPane().add(btnCancelar, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
//Eliminar un cliente por el codigo
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
// TODO add your handling code here:
int codigo=Integer.parseInt(txtCodigo.getText());
controladorCliente.delete(codigo);
//Mensaje de que el Cliente se elimino
JOptionPane.showMessageDialog(this, "Cliente Eliminado");
//Limpiar el texto
txtCodigo.setText("");
}//GEN-LAST:event_btnEliminarActionPerformed
//Boton para cancelar y cerrar ventana
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnEliminar;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField txtCodigo;
// End of variables declaration//GEN-END:variables
}
| true
|
6389244d2f36616f14aae2211c14cb00c70142cb
|
Java
|
oyakimets/ibabai_r
|
/IbabaiRetail/src/com/android/ibabairetail/proto/Promoact.java
|
UTF-8
| 429
| 2
| 2
|
[] |
no_license
|
package com.android.ibabairetail.proto;
import org.json.JSONObject;
public class Promoact {
JSONObject pa=null;
public Promoact(JSONObject pa) {
this.pa=pa;
}
public int getPromoId() {
return(pa.optInt("promoact_id"));
}
public int getClientId() {
return(pa.optInt("client_id"));
}
public int getDiscount() {
return(pa.optInt("discount"));
}
public int getCatInd() {
return(pa.optInt("category"));
}
}
| true
|
b6c8cb990924fadfd1c836452c0473f5793586d5
|
Java
|
edadasko/SoftwareDesign_labs
|
/lab5_Battleship/app/src/main/java/com/example/battleship/model/Grid.java
|
UTF-8
| 780
| 3.078125
| 3
|
[] |
no_license
|
package com.example.battleship.model;
import java.io.Serializable;
public class Grid implements Serializable {
public static final int Height = Position.MaxX + 1;
public static final int Width = Position.MaxY + 1;
private CellStatus[][] cells;
public Grid() {
cells = new CellStatus[Height][Width];
for (int i = 0; i < Height; i++)
for (int j = 0; j < Width; j++)
cells[i][j] = CellStatus.Empty;
}
public CellStatus[][] getCells() {
return cells;
}
public CellStatus getCell(Position position) {
return cells[position.getX()][position.getY()];
}
public void setCell(CellStatus status, Position position) {
cells[position.getX()][position.getY()] = status;
}
}
| true
|