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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e62623e57e88bc97a1e69495dc99564d47bcf3f8
|
Java
|
Lobos008/Wumpus-BF
|
/Wumpus_Best_First/src/wumpus_best_first/Agent.java
|
UTF-8
| 1,087
| 3.21875
| 3
|
[] |
no_license
|
package wumpus_best_first;
import java.util.ArrayList;
public class Agent {
private int x_cuurent, y_current;
private ArrayList solution;
private int attack;
public Agent(int x_cuurent, int y_current) {
this.x_cuurent = x_cuurent;
this.y_current = y_current;
this.solution = new ArrayList<Movement>();
this.attack = 1;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getX_cuurent() {
return x_cuurent;
}
public void setX_cuurent(int x_cuurent) {
this.x_cuurent = x_cuurent;
}
public int getY_current() {
return y_current;
}
public void setY_current(int y_current) {
this.y_current = y_current;
}
public ArrayList getSolution() {
return solution;
}
public void setSolution(ArrayList solution) {
this.solution = solution;
}
public void addMovement(int x, int y) {
this.solution.add(new Movement(x, y));
}
}
| true
|
2d26c1f34353e4638e7defc9d5c252d61a683086
|
Java
|
MosaicOrange/Portfolio
|
/Java/ObjectDraw/src/Lab05/Tshirt.java
|
UTF-8
| 2,383
| 3.40625
| 3
|
[] |
no_license
|
package Lab05;
import objectdraw.*;
import java.awt.*;
public class Tshirt
{
private static final double SIZE = 120;
private static final double SLEEVE_WIDTH = SIZE;
private static final double SLEEVE_HEIGHT = 0.2 * SIZE;
private static final double BODY_WIDTH = 0.6 * SIZE;
private static final double BODY_HEIGHT = (0.65)*SIZE;
private static final double BODY_INSET = 0.2*SIZE;
private static final double NECK_WIDTH = 0.3*SIZE;
private static final double NECK_HEIGHT = 0.06*SIZE;
private static final double NECK_INSET = 0.35*SIZE;
private Color newColor;
private FramedRect sleeveTrim, bodyTrim;
private FramedOval neckTrim;
private FilledRect body, sleeves;
private FilledOval neck;
public Tshirt( double x, double y, DrawingCanvas canvas )
{
sleeveTrim = new FramedRect( x, y + NECK_HEIGHT/2, SLEEVE_WIDTH, SLEEVE_HEIGHT, canvas);
bodyTrim = new FramedRect( x + BODY_INSET, y + NECK_HEIGHT/2, BODY_WIDTH, BODY_HEIGHT, canvas);
sleeves = new FilledRect( x+1, y+NECK_HEIGHT/2+1, SLEEVE_WIDTH-1, SLEEVE_HEIGHT-1, canvas);
body = new FilledRect( x+BODY_INSET+1, y+NECK_HEIGHT/2+1, BODY_WIDTH-1, BODY_HEIGHT-1, canvas);
neck = new FilledOval( x + NECK_INSET, y, NECK_WIDTH, NECK_HEIGHT, canvas);
neckTrim = new FramedOval( x + NECK_INSET, y, NECK_WIDTH, NECK_HEIGHT, canvas);
body.setColor(Color.white);
neck.setColor(Color.white);
sleeves.setColor(Color.white);
}
public void move( double xOffset, double yOffset )
{
body.move(xOffset,yOffset);
neck.move(xOffset,yOffset);
sleeves.move(xOffset,yOffset);
bodyTrim.move(xOffset,yOffset);
sleeveTrim.move(xOffset,yOffset);
neckTrim.move(xOffset,yOffset);
}
public void moveTo( double x, double y)
{
move( x - sleeves.getX(), y - neck.getY());
}
public boolean contains( Location pt)
{
return body.contains(pt) || sleeves.contains(pt) || neck.contains(pt);
}
public void setColor (Color newColor)
{
body.setColor(newColor);
neck.setColor(newColor);
sleeves.setColor(newColor);
bodyTrim.setColor(Color.black);
sleeveTrim.setColor(Color.black);
neckTrim.setColor(Color.black);
}
public Color getColor ()
{
return body.getColor();
}
}
| true
|
098c9a3cb490efe01ecf534970da8917323a3190
|
Java
|
stanimirtrufenev/Java-Course
|
/Homework1/homework(1)/src/Z7.java
|
UTF-8
| 574
| 3.46875
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Z7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in, "UTF-8");
System.out.println("Please enter number: ");
int num = input.nextInt();
input.close();
int c = num % 5;
boolean divide5 = c == 0;
System.out.print("Chisloto se deli na 5 bez ostatuk: ");
System.out.println(divide5);
int d = num % 7;
boolean divideto7 = d == 0;
System.out.print("Chisloto se deli na 7 bez ostatuk: ");
System.out.println(divideto7);
}
}
| true
|
4e93be2d24b393313d0e35594978b69d0cd38a83
|
Java
|
Melisha-N/Task-SpringBoot-Eg-Grocery
|
/src/main/java/com/wolken/wolkenapp/entity/GroceryEntity.java
|
UTF-8
| 847
| 2.203125
| 2
|
[] |
no_license
|
package com.wolken.wolkenapp.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@Entity
@Table(name="grocery_table")
public class GroceryEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "grocery_id")
private int groceryId;
@Column(name = "grocery_category")
private String groceryCategory;
@Column(name = "grocery_name")
private String groceryName;
@Column(name = "grocery_type")
private String groceryType;
@Column(name = "grocery_quantity")
private String groceryQuantity;
@Column(name = "grocery_ratings")
private float groceryRatings;
}
| true
|
ee1f453bf6a0394251b73ebdc0de3bff9c5aa805
|
Java
|
kshan219/core-java
|
/src/com/yali/problems/ClassSeleniumDemo.java
|
UTF-8
| 1,343
| 3.4375
| 3
|
[] |
no_license
|
package com.yali.problems;
class Assertion {
WebDriver d;
Assertion(WebDriver d) {
this.d = d;
}
void until(ExpectedCondition condition) {
System.out.println(condition.apply(d));
}
}
class WebDriver {
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
interface ExpectedCondition {
public Boolean apply(WebDriver d);
}
class WebDriverWait {
WebDriver webDriver;
int timeout;
public WebDriverWait(WebDriver webDriver, int timeout) {
super();
this.webDriver = webDriver;
this.timeout = timeout;
}
}
class Excetp implements ExpectedCondition
{
public Boolean apply(WebDriver d) { return
d.getTitle().equals("我眼中软件工程人员该有的常识");
}
}
public class ClassSeleniumDemo {
public static void main(String[] args) {
WebDriver driver = new WebDriver();
ClassSeleniumDemo cs = new ClassSeleniumDemo();
assertTrue("The page title should be chagned as expected",
new WebDriverWait(driver, 3))
.until(new ExpectedCondition() {
@Override
public Boolean apply(WebDriver d) {
return d.getTitle().equals("我眼中软件工程人员该有的常识");
}
});
}
public static Assertion assertTrue(String message, WebDriverWait driverWait) {
return new Assertion(null);
}
}
| true
|
8ea5f7b30c06ccf91567ca5fe8b7fb0298647dd9
|
Java
|
vvakame/DroppShare
|
/Android/src/net/vvakame/droppshare/helper/SelectorHelper.java
|
UTF-8
| 2,730
| 2.5
| 2
|
[] |
no_license
|
package net.vvakame.droppshare.helper;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.res.AssetManager;
/**
* DroppSelectorActivityのヘルパ
*
* @author vvakame
*/
public class SelectorHelper {
public static final String DEFAULT = "generatedWatching.txt";
public static final String MANUAL = "manuallyWatching.txt";
/**
* 監視対象設定ファイルのインストール
*
* @param context
*/
public static void installWatchingFile(Context context) {
AssetManager am = context.getAssets();
try {
InputStream is = am.open(DEFAULT);
File def = new File(AppDataUtil.EX_STRAGE, DEFAULT);
def.getParentFile().mkdirs();
def.createNewFile();
FileOutputStream fout = new FileOutputStream(def);
byte[] byteArray = new byte[1024];
int len = 0;
while (-1 != (len = is.read(byteArray))) {
fout.write(byteArray, 0, len);
}
File man = new File(AppDataUtil.EX_STRAGE, MANUAL);
man.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 設定ファイルの読み込み
*
* @return 読み込み先ファイルパスのリスト
*/
public static List<String> readWatchingFile() {
ArrayList<String> fileList = new ArrayList<String>();
FileInputStream fin = null;
File def = new File(AppDataUtil.EX_STRAGE, DEFAULT);
try {
fin = new FileInputStream(def);
fileList.addAll(parseFile(fin));
} catch (FileNotFoundException e) {
} finally {
try {
if (fin != null) {
fin.close();
fin = null;
}
} catch (IOException e) {
}
}
File man = new File(AppDataUtil.EX_STRAGE, MANUAL);
try {
fin = new FileInputStream(man);
fileList.addAll(parseFile(fin));
} catch (FileNotFoundException e) {
} finally {
try {
if (fin != null) {
fin.close();
fin = null;
}
} catch (IOException e) {
}
}
return fileList;
}
/**
* 渡されたファイルの内容を読んで返す
*
* @return 読み込み先ファイルパスのリスト
*/
private static List<String> parseFile(FileInputStream fin) {
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
List<String> list = new ArrayList<String>();
String line;
try {
while ((line = br.readLine()) != null) {
if (!"".equals(line) && line.charAt(0) != '#') {
list.add(line);
}
}
} catch (IOException e) {
}
return list;
}
}
| true
|
094df6e11a08dea0e97f7296577619f189a541ff
|
Java
|
ahmadmahoud/RX-libraries
|
/app/src/main/java/com/example/lib/language/MyShared.java
|
UTF-8
| 546
| 2.234375
| 2
|
[] |
no_license
|
package com.example.lib.language;
import android.content.Context;
import android.content.SharedPreferences;
public class MyShared {
SharedPreferences sharedPreferences;
public MyShared() {
sharedPreferences = AppClass.context.getSharedPreferences("userData", Context.MODE_PRIVATE);
}
public void setLanguage (String language) {
sharedPreferences.edit().putString("language",language).apply();
}
public String getLanguage() {
return sharedPreferences.getString("language","default");
}
}
| true
|
d2384b0aa8bd5a0eb35027d0149610ddcf0ae9f0
|
Java
|
HKMOpen/SDKhb
|
/android-SDK-HB/library/src/main/java/com/hypebeast/sdk/api/model/symfony/Range.java
|
UTF-8
| 1,230
| 2.5
| 2
|
[] |
no_license
|
package com.hypebeast.sdk.api.model.symfony;
import com.google.gson.annotations.SerializedName;
/**
* Created by hesk on 2/3/15.
*/
public class Range {
@SerializedName("from")
private int from = 0;
@SerializedName("to")
private int to = 0;
@SerializedName("count")
private int count = 0;
@SerializedName("min")
private int min = 0;
@SerializedName("max")
private int max = 0;
@SerializedName("total_count")
private int total_count = 0;
@SerializedName("total")
private int total = 0;
@SerializedName("mean")
private float mean = 0f;
public Range() {
}
public int getfrom() {
return from;
}
public int getto() {
return to;
}
private String tag;
public String getCallDisplay() {
if (from == 0) {
tag = money(to) + " and under";
} else if (to == 0) {
tag = money(from) + " and above";
} else {
tag = money(from) + " - " + money(to);
}
return tag;
}
public TermWrap getTerm() {
return new TermWrap(getCallDisplay(), count);
}
private String money(int n) {
return "$" + (int) n / 100 + ".00";
}
}
| true
|
b85a76a968b519ce5040c05bc73e31a0a24ade0e
|
Java
|
lisaamann/01_Basics
|
/src/at/la/cc/basics/Basics1.java
|
UTF-8
| 159
| 1.539063
| 2
|
[] |
no_license
|
package at.la.cc.basics;
public class Basics1 {
public static void main(String[] args) {
System.out.println("Hello Conding Campus!");
}
}
| true
|
94dc66f9239197caa33165847ce56c8272158302
|
Java
|
beerzyp/LPOO-Chess-Android
|
/T1/src/Game/OgreMap.java
|
UTF-8
| 1,553
| 3
| 3
|
[] |
no_license
|
package Game;
import java.util.ArrayList;
import java.util.Arrays;
import Others.Pair;
public class OgreMap implements GameMap, Cloneable {
public OgreMap(char[][] map) {
if(map != null){
int l = map.length;
matrix = new char[l][];
for (int i = 0 ; i < l ; i++) {
matrix[i] = Arrays.copyOf(map[i], map[i].length);
}}
for (int i = 0 ; i < matrix.length ; i++) {
for (int j = 0 ; j < matrix[i].length ; j++) {
if(matrix[i][j] == 'I'){
this.doors.add(new Pair(i,j));
}
}
}
}
ArrayList<Pair> doors = new ArrayList<Pair>();
private char[][] matrix={
{'X','X','X','X','X','X','X','X','X'},
{'I',' ',' ',' ',' ',' ',' ','k','X'},
{'X',' ',' ',' ',' ',' ',' ',' ','X'},
{'X',' ',' ',' ',' ',' ',' ',' ','X'},
{'X',' ',' ',' ',' ',' ',' ',' ','X'},
{'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X'},
{'X', ' ', ' ', ' ', ' ', ' ',' ',' ', 'X'},
{'X', ' ', ' ', ' ', ' ', ' ',' ',' ','X'},
{'X', 'X', 'X', 'X', 'X', 'X','X','X','X'},
};
@Override public OgreMap clone() {
OgreMap n = new OgreMap(matrix);
return n;
}
ArrayList<Pair> getDoors(){return this.doors;}
public char[][] getMap() {
return this.matrix;
}
// public GameMap nextMap() {
// return null;
// }
public boolean moveTo(int x, int y) {
if(this.matrix[x][y] == ' ')
return true;
else if(this.matrix[x][y] == 'k')
return true;
else if(this.matrix[x][y] == 'S')
return true;
return false;
}
}
| true
|
9e4c75856d54cf9245463f3ae5a71a2a355fbad9
|
Java
|
chernikovalexey/MondayShooter
|
/src/com/twopeople/game/entity/building/Decal.java
|
UTF-8
| 474
| 2.625
| 3
|
[] |
no_license
|
package com.twopeople.game.entity.building;
import com.twopeople.game.entity.Entity;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;
/**
* Created by Alexey
* At 4:53 PM on 3/5/14
*/
public class Decal extends Entity {
public Decal(float x, float y) {
super(x, y, 0, 128, Wall.HEIGHT, 64, true);
}
@Override
public Shape getBB() {
return new Rectangle(x + width / 2, y + height + depth / 2, 1, 1);
}
}
| true
|
e9c4a1c9a132ac671d9ef83b754878708df04004
|
Java
|
ArneTroch99/FireDEVS
|
/src/util/tracking/EncodedTrackerDataStore.java
|
UTF-8
| 4,876
| 2.40625
| 2
|
[] |
no_license
|
package util.tracking;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import util.SortedEnumerableList;
public class EncodedTrackerDataStore extends MutableTrackerDataStoreImpl
{
private HashMap<String, Integer>[] seeds;
private HashMap<String, HashMap<String, Integer>>[] legend;
private int seed;
public EncodedTrackerDataStore(SortedEnumerableList<String> inputPortNames,
SortedEnumerableList<String> outputPortNames,
SortedEnumerableList<String> stateNames,
SortedEnumerableList<String> timeNames)
{
super(inputPortNames, outputPortNames, stateNames, timeNames);
initialize();
}
public EncodedTrackerDataStore(TrackerDataStore dataStore)
{
super(dataStore);
initialize();
}
@SuppressWarnings("unchecked")
private void initialize()
{
this.seed = 0;
this.legend = (HashMap<String, HashMap<String, Integer>>[]) new HashMap[] {
new HashMap<String, HashMap<String, Integer>>(),
new HashMap<String, HashMap<String, Integer>>(),
new HashMap<String, HashMap<String, Integer>>(),
new HashMap<String, HashMap<String, Integer>>()
};
this.seeds = (HashMap<String, Integer>[]) new HashMap[] {
new HashMap<String, Integer>(),
new HashMap<String, Integer>(),
new HashMap<String, Integer>(),
new HashMap<String, Integer>()
};
}
@Override
public Object getData(TrackedVariableMetadata meta, int index)
{
return this.getData(meta.name, meta.type, index);
}
@Override
public Object getData(String name, TrackerDataStore.DataType dType, int index)
{
Object o = super.getData(name, dType, index);
return o == null ? "" : this.encode(name, dType, o.toString(), this.nextSeed(name, dType));
}
@Override
public void forEachData(String name, TrackerDataStore.DataType dType, Consumer<Object> f)
{
super.forEachData(name, dType, (Object o) -> {
String valString = o.toString();
f.accept(this.encode(name, dType, valString, this.nextSeed(name, dType)));
});
}
public void forEachLegend(String name, TrackerDataStore.DataType dType, BiConsumer<String, Integer> f)
{
Set<String> valSet = new HashSet<String>();
super.forEachData(name, dType, (Object o) -> {
String valString = "";
if (o != null)
{
valString = o.toString();
}
if (!valSet.contains(valString))
{
valSet.add(valString);
f.accept(valString, this.encode(name, dType, valString, this.nextSeed(name, dType)));
}
});
}
private boolean legendContainsKey(String name, TrackerDataStore.DataType dType, String key)
{
if (!this.legend[dType.i].containsKey(name))
{
return false;
}
return this.legend[dType.i].get(name).containsKey(key);
}
private Integer getLegend(String name, TrackerDataStore.DataType dType, String value)
{
if (!this.legend[dType.i].containsKey(name))
{
return null;
}
return this.legend[dType.i].get(name).get(value);
}
private Integer putLegend(String name, TrackerDataStore.DataType dType, String key, Integer value)
{
if (!this.legend[dType.i].containsKey(name))
{
this.legend[dType.i].put(name, new HashMap<String, Integer>());
}
return this.legend[dType.i].get(name).put(key, value);
}
private int nextSeed(String name, TrackerDataStore.DataType dType)
{
if (this.seeds[dType.i].containsKey(name))
{
int seed = this.seeds[dType.i].get(name) + 1;
this.seeds[dType.i].put(name, seed);
return seed;
}
this.seed += 100;
this.seeds[dType.i].put(name, this.seed);
return this.seed;
}
private Integer encode(String name, TrackerDataStore.DataType dType, String valString, int seed)
{
Integer value;
if (this.legendContainsKey(name, dType, valString))
{
value = this.getLegend(name, dType, valString);
}
else
{
value = new Integer(seed);
this.putLegend(name, dType, valString, value);
}
return value;
}
}
| true
|
33ffae1d21990fc267adfa578b5f70c64b554d41
|
Java
|
qoo7972365/timmy
|
/OSWE/oswe/openCRX/rtjar/rt.jar.src/com/sun/java/browser/dom/DOMAccessor.java
|
UTF-8
| 466
| 1.726563
| 2
|
[] |
no_license
|
package com.sun.java.browser.dom;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public interface DOMAccessor {
Document getDocument(Object paramObject) throws DOMException;
DOMImplementation getDOMImplementation();
}
/* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/java/browser/dom/DOMAccessor.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
| true
|
ab2efee33eeb5bb9a89311a5761c6670db988c62
|
Java
|
AhmadHoghooghi/HelloWorldSeries
|
/contacts/src/main/java/ir/asta/training/events/entities/EventEntity.java
|
UTF-8
| 1,207
| 2.4375
| 2
|
[] |
no_license
|
package ir.asta.training.events.entities;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name="WISE_EVENT")
public class EventEntity {
private Long id;
private String title;
private String description;
private Date startDateTime;
private Date endDateTime;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Date startDateTime) {
this.startDateTime = startDateTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
}
| true
|
294de63f941112bdc89d90d8bb58fa8863598b69
|
Java
|
zhaolongs/AndroidBaseLib
|
/androidbaselibrary/src/main/java/com/studyyoun/androidbaselibrary/activity/CommonBasePicSelectActivity.java
|
UTF-8
| 9,534
| 2.078125
| 2
|
[] |
no_license
|
package com.studyyoun.androidbaselibrary.activity;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import com.studyyoun.androidbaselibrary.crop.CropActivity;
import java.util.ArrayList;
import java.util.List;
import me.nereo.multi_image_selector.MultiImageSelector;
public abstract class CommonBasePicSelectActivity extends CommonBaseActivity {
private ArrayList<String> mSelectPath;
private String[] permissions = new String[3];
private static final int REQUEST_IMAGE = 2;
private void initPicSelectFunction(){
permissions[0] = Manifest.permission.READ_EXTERNAL_STORAGE;
permissions[1] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
permissions[2] = Manifest.permission.CAMERA;
}
protected void selectPicImageFunction(){
pickPreImage(true,1);
}
private boolean mIsCropBoolean = false;
protected void selectPicAndCropImageFunction(){
mIsCropBoolean=true;
pickPreImage(true,1);
}
protected void selectPicImageFunction(boolean showCamera){
pickPreImage(showCamera,1);
}
protected void selectPicImageFunction(int maxNum ){
pickPreImage(true,maxNum);
}
protected void selectPicImageFunction(boolean showCamera,int maxNum ){
pickPreImage(showCamera,maxNum);
}
/**
* 发起选择图片
* @param showCamera 是否显示相机功能
* @param maxNum 多选 1为单选,大于1为多选
*/
private void pickPreImage(boolean showCamera,int maxNum) {
initPicSelectFunction();
if (!checkPermissions(permissions)) {
ActivityCompat.requestPermissions(CommonBasePicSelectActivity.this, permissions, 0);
} else {
pickImage(showCamera,maxNum);
}
}
/**
* 调起选择图片功能
*/
private void pickImage(boolean showCamera,int maxNum) {
//多选 最多选择的图片数
if (maxNum<=0) {
maxNum=1;
}
MultiImageSelector selector = MultiImageSelector.create();
selector.showCamera(showCamera);
selector.count(maxNum);
if (maxNum==1) {
//单选
selector.single();
}else {
//多选
selector.multi();
}
selector.origin(mSelectPath);
selector.start(CommonBasePicSelectActivity.this, REQUEST_IMAGE);
}
@Override //只要开发者调用了requestPermissions方法,就算用户勾选了"不再提示"框,也会回调本方法
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (checkPermissions(permissions)) {
pickImage(true,1);
} else {
showReasonAndRequestAgainIfCouldbe();
}
}
/**
* 检查所需权限是否都授予
*
* @param permissions 权限数组
* @return 判断结果
*/
private boolean checkPermissions(String[] permissions) {
for (String perm : permissions) {
if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* 弹出对话框向用户解释为何需要该权限,并尝试再次请求权限
* <p>
* 注:shouldShowRequestPermissionRationale(Activity activity,String permission)方法
* 如果用户已经授予该权限,此方法将返回false。
* 如果应用之前请求过此权限但用户拒绝了请求,此方法将返回 true。
* 如果用户在过去拒绝了权限请求,并在权限请求系统对话框中选择了 Don't ask again 选项,此方法将返回 false。
*/
private void showReasonAndRequestAgainIfCouldbe() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
new AlertDialog.Builder(this)
.setTitle("需要权限")
.setMessage("该功能需要您授予拍照权限")
.setPositiveButton("同意", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(CommonBasePicSelectActivity.this, new String[]{Manifest.permission.CAMERA}, 0);
}
})
.setNegativeButton("拒绝", null)
.create().show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框,跳转应用设置界面
new AlertDialog.Builder(this)
.setTitle("需要权限")
.setMessage("该功能需要您授予拍照权限,请手动开启权限")
.setPositiveButton("同意", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri packageURI = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
startActivity(intent);
}
})
.setNegativeButton("拒绝", null)
.create().show();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("需要权限")
.setMessage("该功能需要读取您的内存卡上的图片")
.setPositiveButton("同意", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(CommonBasePicSelectActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
})
.setNegativeButton("拒绝", null)
.create().show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框,跳转应用设置界面
new AlertDialog.Builder(this)
.setTitle("需要权限")
.setMessage("该功能需要读取您的内存卡上的图片,请手动开启权限")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri packageURI = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
startActivity(intent);
}
})
.create().show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
if (mSelectPath != null&&mSelectPath.size()>0) {
if (mIsCropBoolean) {
//剪切
CropActivity.show(CommonBasePicSelectActivity.this,mSelectPath.get(0));
}else {
if (mPicSelectCallBack != null) {
mPicSelectCallBack.callBack(mSelectPath);
}
}
}else {
if (mPicSelectCallBack != null) {
mPicSelectCallBack.callBack(null);
}
}
}
}else if (requestCode==0x04){
if (resultCode == RESULT_OK) {
if (mPicSelectCallBack != null) {
String lCrop_path = data.getStringExtra("crop_path");
if (TextUtils.isEmpty(lCrop_path)) {
mPicSelectCallBack.callBack(null);
}else {
ArrayList<String> lStrings = new ArrayList<>();
lStrings.add(lCrop_path);
mPicSelectCallBack.callBack(lStrings);
}
}
}
}
}
protected PicSelectCallBack mPicSelectCallBack;
public interface PicSelectCallBack{
void callBack(List<String> selectPathList);
}
}
| true
|
00eed6437cae2929ddd426e1cbb4504c8f24ab37
|
Java
|
Kageschwump/23_final
|
/src/main/java/Squaretype/BrewerySquare.java
|
UTF-8
| 3,438
| 2.765625
| 3
|
[] |
no_license
|
package Squaretype;
import Controller.GUIHandler;
import Model.GameSquare;
import Model.Player;
import gui_fields.GUI_Brewery;
import gui_fields.GUI_Field;
import gui_fields.GUI_Ownable;
import gui_fields.GUI_Shipping;
import java.awt.*;
public class BrewerySquare extends GameSquare {
private String name;
private String description = "Snup en sodavand!";
private int rent;
private int price;
private Player owner;
private Color bgColor = Color.pink;
private Color fgColor = Color.black;
private GUI_Brewery fieldType;
public BrewerySquare(String name, int rent, int price){
fieldType = new GUI_Brewery( "default", name ,"",description, Integer.toString(rent),bgColor,fgColor);
this.name = name;
this.rent = rent;
this.price = price;
}
@Override
public void function(Player player, GUIHandler guiHandler) {
fieldType.setCar(player.getGuiPlayer(),true);
String selection;
if (propertySquareNotOwned() && player.getAccount().getBalance() > price) {
selection = guiHandler.getGui().getUserSelection("vil du købe "+ name +"?", "ja", "nej");
switch (selection){
case ("ja"):
owner = player;
player.getAccount().addBrewery(name);
player.getAccount().updateScore(-price);
player.getGuiPlayer().setBalance(player.getAccount().getBalance());
fieldType.setOwnableLabel(player.getName());
fieldType.setBorder(player.getGuiPlayer().getPrimaryColor());
break;
case ("nej"):
break;
}
} else if (player != owner) {
player.getAccount().updateScore(-1 * priceForLanding(player.getLastRoll()));
player.getGuiPlayer().setBalance(player.getAccount().getBalance());
owner.getAccount().updateScore(priceForLanding(player.getLastRoll()));
owner.getGuiPlayer().setBalance(owner.getAccount().getBalance());
}
}
public boolean propertySquareNotOwned() {
if (owner == null) {
return true;
} else
return false;
}
public int priceForLanding(int diceEyes) {
int priceToPay = 0;
int numOfBrewery = 0;
if (owner != null) {
for (int i = 0; i < owner.getAccount().getBreweryProp().length; i++) {
if (owner.getAccount().getBreweryProp()[i] != null) {
numOfBrewery++;
}
}
switch (numOfBrewery) {
case 1:
priceToPay = diceEyes * 100;
break;
case 2:
priceToPay = diceEyes * 200;
break;
}
} else{
priceToPay = 0;
}
return priceToPay;
}
@Override
public String getName() {
return null;
}
@Override
public GUI_Field getGuiField() {
return fieldType;
}
@Override
public String getDesc() {
return description;
}
@Override
public Color getColor() {
return bgColor;
}
public void removeOwner()
{
owner.getAccount().updateScore(price/2);
owner = null;
}
public void setOwner(Player player)
{
owner = player;
}
}
| true
|
4e64f774b75e0088edaacffd8e79a41d7b5484a7
|
Java
|
ShaxSharipov91/shahboz-test-challenge
|
/src/main/java/com/challenge/pages/DashboardPage.java
|
UTF-8
| 1,826
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
package com.challenge.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.List;
public class DashboardPage extends BasePage {
//region Page Factory Elements
@FindBy(how = How.XPATH, using = "//a[contains(.,'Filter Task')]")
private WebElement filterTasksButton;
final String contactDropDownLocator = "//div[@class='col-xs-12 col-sm-10']";
@FindBy(how = How.XPATH, using = contactDropDownLocator)
private WebElement contactDropDown;
@FindAll(@FindBy(how = How.XPATH, using = "//*[@id=\"ui-select-choices-0\"]/li/div/small"))
private List<WebElement> contacts;
@FindBy(how = How.XPATH, using = contactDropDownLocator + "/div/div/a/span[2]")
private WebElement contactDropDownValue;
//endregion
public DashboardPage(WebDriver webDriver) {
super(webDriver);
PageFactory.initElements(webDriver, this);
}
private void clickFilterTaskButton() {
webDriverWait.until(ExpectedConditions.visibilityOf(filterTasksButton));
this.filterTasksButton.click();
webDriverWait.until(ExpectedConditions.visibilityOf(contactDropDown));
}
public void selectContactToFilter(String contactEmail) {
clickFilterTaskButton();
contactDropDown.click();
for (WebElement element : contacts) {
if (element.getText().equals(contactEmail)) {
element.click();
break;
}
}
}
public String getFilterValue() {
return this.contactDropDownValue.getText();
}
}
| true
|
959102fe0a71d110b089cd07e2f93d18fa9cd662
|
Java
|
aliyun/aliyun-openapi-java-sdk
|
/aliyun-java-sdk-swas/src/main/java/com/aliyuncs/swas/transform/v20170810/DescribeEcsImageResponseUnmarshaller.java
|
UTF-8
| 3,356
| 1.648438
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.aliyuncs.swas.transform.v20170810;
import com.aliyuncs.swas.model.v20170810.DescribeEcsImageResponse;
import com.aliyuncs.swas.model.v20170810.DescribeEcsImageResponse.Data;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeEcsImageResponseUnmarshaller {
public static DescribeEcsImageResponse unmarshall(DescribeEcsImageResponse describeEcsImageResponse, UnmarshallerContext _ctx) {
describeEcsImageResponse.setRequestId(_ctx.stringValue("DescribeEcsImageResponse.RequestId"));
describeEcsImageResponse.setCode(_ctx.stringValue("DescribeEcsImageResponse.Code"));
describeEcsImageResponse.setIsSuccess(_ctx.booleanValue("DescribeEcsImageResponse.IsSuccess"));
Data data = new Data();
data.setProgress(_ctx.stringValue("DescribeEcsImageResponse.Data.Progress"));
data.setImageId(_ctx.stringValue("DescribeEcsImageResponse.Data.ImageId"));
data.setImageName(_ctx.stringValue("DescribeEcsImageResponse.Data.ImageName"));
data.setImageFamily(_ctx.stringValue("DescribeEcsImageResponse.Data.ImageFamily"));
data.setImageVersion(_ctx.stringValue("DescribeEcsImageResponse.Data.ImageVersion"));
data.setDescription(_ctx.stringValue("DescribeEcsImageResponse.Data.Description"));
data.setSize(_ctx.longValue("DescribeEcsImageResponse.Data.Size"));
data.setImageOwnerAlias(_ctx.stringValue("DescribeEcsImageResponse.Data.ImageOwnerAlias"));
data.setIsSupportIoOptimized(_ctx.booleanValue("DescribeEcsImageResponse.Data.IsSupportIoOptimized"));
data.setIsSupportCloudinit(_ctx.booleanValue("DescribeEcsImageResponse.Data.IsSupportCloudinit"));
data.setOSName(_ctx.stringValue("DescribeEcsImageResponse.Data.OSName"));
data.setOSNameEn(_ctx.stringValue("DescribeEcsImageResponse.Data.OSNameEn"));
data.setArchitecture(_ctx.stringValue("DescribeEcsImageResponse.Data.Architecture"));
data.setStatus(_ctx.stringValue("DescribeEcsImageResponse.Data.Status"));
data.setProductCode(_ctx.stringValue("DescribeEcsImageResponse.Data.ProductCode"));
data.setIsSubscribed(_ctx.booleanValue("DescribeEcsImageResponse.Data.IsSubscribed"));
data.setCreationTime(_ctx.stringValue("DescribeEcsImageResponse.Data.CreationTime"));
data.setIsSelfShared(_ctx.stringValue("DescribeEcsImageResponse.Data.IsSelfShared"));
data.setOSType(_ctx.stringValue("DescribeEcsImageResponse.Data.OSType"));
data.setPlatform(_ctx.stringValue("DescribeEcsImageResponse.Data.Platform"));
data.setUsage(_ctx.stringValue("DescribeEcsImageResponse.Data.Usage"));
data.setIsCopied(_ctx.booleanValue("DescribeEcsImageResponse.Data.IsCopied"));
data.setResourceGroupId(_ctx.stringValue("DescribeEcsImageResponse.Data.ResourceGroupId"));
describeEcsImageResponse.setData(data);
return describeEcsImageResponse;
}
}
| true
|
a6c0d0f24231dcf0d898652be511c5ee82d7f357
|
Java
|
UnibucProjects/ReadHub
|
/readhub/src/main/java/com/fmiunibuc/readhub/web/ShelfController.java
|
UTF-8
| 3,689
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package com.fmiunibuc.readhub.web;
import com.fmiunibuc.readhub.model.Library;
import com.fmiunibuc.readhub.model.Shelf;
import com.fmiunibuc.readhub.model.User;
import com.fmiunibuc.readhub.model.repositories.*;
import com.fmiunibuc.readhub.service.LoggerService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;
@RestController
@RequestMapping("/api")
public class ShelfController {
private final LoggerService loggerService = new LoggerService();
private ShelfRepository shelfRepository;
private BookCopyRepository bookCopyRepository;
private BookRepository bookRepository;
private UserRepository userRepository;
private LibraryRepository libraryRepository;
public ShelfController(ShelfRepository shelfRepository, BookCopyRepository bookCopyRepository, UserRepository userRepository, LibraryRepository libraryRepository) {
this.shelfRepository = shelfRepository;
this.bookCopyRepository = bookCopyRepository;
this.userRepository = userRepository;
this.libraryRepository = libraryRepository;
}
@GetMapping("/shelves")
Collection<Shelf> shelves(){
loggerService.info("Request to get all shelves");
return shelfRepository.findAll();
}
@GetMapping("/shelf/{id}")
ResponseEntity<?> getShelf(@PathVariable Long id) {
loggerService.info("Request to get shelf " + id);
Optional<Shelf> shelf = shelfRepository.findById(id);
return shelf.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@GetMapping("/myShelves/{userId}/{bookId}")
Collection<Shelf> myShelves(@PathVariable Long userId, @PathVariable Long bookId) {
loggerService.info("Request to get all shelves of user " + userId);
Optional<User> user = userRepository.findById(userId);
Library library = null;
if(user.isPresent()) {
library = user.get().getLibrary();
}
if(library != null) {
return library.getShelfList();
}
return null;
}
@PostMapping("/shelf/{id}")
ResponseEntity<Shelf> createShelf(@Valid @RequestBody Shelf shelf, @PathVariable Long id) throws URISyntaxException {
loggerService.info("Request to create shelf");
Optional<User> user = userRepository.findById(id);
Library library = null;
if(user.isPresent()) {
library = user.get().getLibrary();
}
if (library != null)
{
shelf.setLibrary(library);
library.getShelfList().add(shelf);
}
Shelf result = shelfRepository.save(shelf);
return ResponseEntity.created(new URI("/api/shelf/" + result.getId()))
.body(result);
}
@PutMapping("/shelf/{id}")
ResponseEntity<Shelf> updateShelf(@Valid @RequestBody Shelf shelf) {
loggerService.info("Request to update shelf " + shelf.getId());
Shelf result = shelfRepository.save(shelf);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/shelf/{id}")
public ResponseEntity<?> deleteShelf(@PathVariable Long id) {
loggerService.info("Request to delete shelf " + id);
Optional<Shelf> tbd = shelfRepository.findById(id);
tbd.get().getLibrary().getShelfList().remove(tbd.get());
shelfRepository.deleteById(id);
return ResponseEntity.ok().build();
}
}
| true
|
044623bf449a33c046d8869ce333b26580a9fe7d
|
Java
|
marcinsafian/JDP-1912-02
|
/src/main/java/com/kodilla/ecommercee/domain/Product/ProductDto.java
|
UTF-8
| 358
| 1.765625
| 2
|
[] |
no_license
|
package com.kodilla.ecommercee.domain.Product;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class ProductDto {
private Long id;
private String description;
private BigDecimal price;
private String groupName;
}
| true
|
2ba4378dada3f34a974994df20680a9715d7dc9a
|
Java
|
nononohave/huanhuanGit
|
/app/src/main/java/com/cos/huanhuan/model/AddressVO.java
|
UTF-8
| 2,128
| 2.15625
| 2
|
[] |
no_license
|
package com.cos.huanhuan.model;
import java.io.Serializable;
/**
* Created by Administrator on 2017/8/23.
*/
public class AddressVO implements Serializable{
private int id;//地址id
private int userId;//用户id
private String province;//省份
private String city;//地级市
private String county;//市、县级市
private String address;//详细地址
private String zipCode;//邮编
private String name;//真实姓名
private String phone;//手机号
private Boolean isDefault;//是否默认
private Boolean isManage;//是否点击了管理
public Boolean getManage() {
return isManage;
}
public void setManage(Boolean manage) {
isManage = manage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getDefault() {
return isDefault;
}
public void setDefault(Boolean aDefault) {
isDefault = aDefault;
}
}
| true
|
b2d5193e7d865b1d2a97691aa6347dd580199174
|
Java
|
flyfaster/toysrc
|
/mytoybox/test/wordPattern.java
|
UTF-8
| 1,407
| 3.4375
| 3
|
[] |
no_license
|
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<Character, String> patternmap = new HashMap<Character, String>();
HashMap<String, Character> rmap = new HashMap<String, Character>();
int pos = 0; int spacepos=0;
for(int i=0; i<pattern.length(); i++) {
if(pos>=str.length())
return false;
spacepos = str.indexOf(' ', pos);
if (spacepos<0)
spacepos = str.length();
String word = str.substring(pos, spacepos);
pos = spacepos+1;
Character ch = pattern.charAt(i);
if(patternmap.containsKey(ch)){
if(patternmap.get(ch).compareTo(word)!=0){
//System.out.format("'%s' not match '%s'\n", word, patternmap.get(ch));
return false;
}
} else {
if (rmap.containsKey(word))
return false;
rmap.put(word, ch);
patternmap.put(ch, word);
}
}
if(pos<str.length())
return false;
return true;
}
public static void main(String[] argv) {
Solution mysol = new Solution();
if(mysol.wordPattern("abba", "dog cat cat dog"))
System.out.println("true");
else
System.out.println("false");
}
}
//C:\onega\leetcode>"C:\Program Files\Java\jdk1.8.0_60\bin\javac.exe" Solution.java
//C:\onega\leetcode>java -cp . Solution
| true
|
916e549749ffc5b4e1daa5fb87b1344191f959fd
|
Java
|
grenny87/TestProject
|
/src/com/main/TestCryptoAes.java
|
UTF-8
| 3,269
| 2.734375
| 3
|
[] |
no_license
|
package com.main;
import java.security.Key;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class TestCryptoAes {
private static final String ALGORITHM = "AES";
private static final String keyValue = "4D92199549E0F2EF009B4160F3582E5528A11A45017F3EF8";
public static void main(String args[]) throws Exception {
String encriptValue = encrypt("Hom nay tao di da bong");
decrypt(encriptValue);
}
/**
* @param args
* @throws Exception
*/
public static String encrypt(String valueToEnc) throws Exception {
IvParameterSpec iv = buildIvParameterSpec();
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
System.out.println(Cipher.getMaxAllowedKeyLength("4D92199549E0F2EF009B4160F3582E5528A11A45017F3EF8"));
c.init(Cipher.ENCRYPT_MODE, key, iv );
byte[] hexByte = Hex.decodeHex("4D92199549E0F2EF009B4160F3582E5528A11A45017F3EF8".toCharArray());
byte[] hexByte2 = extractHexStringToByte("4D92199549E0F2EF009B4160F3582E5528A11A45017F3EF8");
System.out.println("valueToEnc.getBytes().length "+valueToEnc.getBytes().length);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
System.out.println("encValue hex string " + Hex.encodeHexString(encValue));
String cipherText = Base64.encodeBase64String(encValue);
System.out.println("encValue length " + encValue.length );
System.out.println("encryptedValue " + cipherText);
return cipherText;
}
private static IvParameterSpec buildIvParameterSpec() {
String ivStr = "35B2FF0795FB84BBD666DB8430CA214E";
byte[] ivBytes = extractHexStringToByte(ivStr);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
return iv;
}
private static byte[] extractHexStringToByte(String ivStr) {
byte[] ivBytes = new byte[ivStr.length()/2];
for(int i = 0; i < ivStr.length(); i+=2) {
ivBytes[i/2] = (byte) Integer.parseInt(ivStr.substring(i, i + 2) , 16);
}
return ivBytes;
}
public static String decrypt(String encryptedValue) throws Exception {
IvParameterSpec iv = buildIvParameterSpec();
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, key, iv);
byte[] enctVal = c.doFinal(Base64.decodeBase64(encryptedValue));
System.out.println("enctVal length " + enctVal.length);
byte[] decordedValue = new Base64().decode(enctVal);
System.out.println("decordedValue " + new String(enctVal, "UTF-8"));
return decordedValue.toString();
}
private static Key generateKey() throws Exception {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// byte[] b = md.digest(keyValue);
Key key = new SecretKeySpec(Hex.decodeHex(keyValue.toCharArray()), ALGORITHM);
// Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
}
| true
|
4d77a1f04d5196a84d321d7a3d0830d410c93405
|
Java
|
flpkpm/GanHuoIO
|
/app/src/main/java/ren/solid/ganhuoio/utils/DialogUtils.java
|
UTF-8
| 3,923
| 2
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ren.solid.ganhuoio.utils;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import com.afollestad.materialdialogs.MaterialDialog;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.SaveListener;
import ren.solid.ganhuoio.R;
import ren.solid.ganhuoio.bean.bomb.CollectTable;
import ren.solid.ganhuoio.common.event.CollectChangeEvent;
import ren.solid.ganhuoio.module.mine.LoginActivity;
import ren.solid.library.rx.RxBus;
import ren.solid.library.utils.SnackBarUtils;
/**
* Created by _SOLID
* Date:2016/5/19
* Time:10:02
*/
public class DialogUtils {
public static void showActionDialog(final Context context, final View itemView, final CollectTable bean) {
new MaterialDialog.Builder(context)
.items(R.array.action)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
CharSequence[] action = context.getResources().getTextArray(R.array.action);
if (text.equals(action[0])) {
SinaWeiBoShareUtil share = new SinaWeiBoShareUtil(context);
share.setTextObj(bean.getDesc() + "\n" + context.getString(R.string.app_download_url));
share.setWebpageObj("来自干货IO的分享", bean.getUrl(), bean.getDesc());
share.sendMultiMessage();
} else if (text.equals(action[1])) {
doCollect(bean, context, itemView);
}
}
})
.show();
}
private static void doCollect(CollectTable bean, final Context context, final View view) {
if (AuthorityUtils.isLogin()) {
bean.setUsername(AuthorityUtils.getUserName());
bean.save(context, new SaveListener() {
@Override
public void onSuccess() {
SnackBarUtils.makeShort(view, "收藏成功").success();
RxBus.getInstance().post(new CollectChangeEvent());
}
@Override
public void onFailure(int i, String s) {
if (i == 401) {
SnackBarUtils.makeShort(view, "你已经收藏过了").info();
} else {
SnackBarUtils.makeShort(view, "收藏失败").danger();
}
}
});
} else {
SnackBarUtils.makeLong(view, context.getResources().getString(R.string.mine_no_login))
.warning(context.getString(R.string.mine_click_login)
, new View.OnClickListener() {
@Override
public void onClick(View v) {
context.startActivity(new Intent(context, LoginActivity.class));
}
});
}
}
public static void showUnDoCollectDialog(final View itemView
, final CollectTable bean, final DeleteListener listener) {
new MaterialDialog.Builder(itemView.getContext())
.items(R.array.deleteCollect)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
unDoCollect(bean, itemView, listener);
}
})
.show();
}
private static void unDoCollect(CollectTable bean, final View view
, final DeleteListener listener) {
bean.delete(view.getContext(), listener);
}
}
| true
|
d6ded0ea8c0f42b90ce1cbf765a300ee4009317f
|
Java
|
rafaelgarrote/taller-Storm-Twitter
|
/src/main/java/TwitterTopologia.java
|
UTF-8
| 2,431
| 2.34375
| 2
|
[] |
no_license
|
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.topology.TopologyBuilder;
import bolt.FileWriterBolt;
import spout.TwitterSpout;
import twitter4j.FilterQuery;
public class TwitterTopologia {
private static String consumerKey = "FILL IN HERE";
private static String consumerSecret = "FILL IN HERE";
private static String accessToken = "FILL IN HERE";
private static String accessTokenSecret = "FILL IN HERE";
public static void main(String[] args) throws Exception {
/**************** SETUP ****************/
String remoteClusterTopologyName = null;
if (args!=null) {
if (args.length==1) {
remoteClusterTopologyName = args[0];
}
// If credentials are provided as commandline arguments
else if (args.length==4) {
consumerKey =args[0];
consumerSecret =args[1];
accessToken =args[2];
accessTokenSecret =args[3];
}
}
/**************** ****************/
TopologyBuilder builder = new TopologyBuilder();
FilterQuery tweetFilterQuery = new FilterQuery();
// TODO: Define your own twitter query
// tweetFilterQuery.track(new String[]{"Music"});
// See https://github.com/kantega/storm-twitter-workshop/wiki/Basic-Twitter-stream-reading-using-Twitter4j
TwitterSpout spout = new TwitterSpout(consumerKey, consumerSecret, accessToken, accessTokenSecret, tweetFilterQuery);
//TODO: Set the twitter spout as spout on this topology. Hint: Use the builder object.
FileWriterBolt fileWriterBolt = new FileWriterBolt("MyTweets.txt");
//TODO: Route messages from the spout to the file writer bolt. Hint: Again, use the builder object.
Config conf = new Config();
conf.setDebug(false);
if (remoteClusterTopologyName!=null) {
conf.setNumWorkers(3);
StormSubmitter.submitTopology(remoteClusterTopologyName, conf, builder.createTopology());
}
else {
conf.setMaxTaskParallelism(3);
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("twitter-fun", conf, builder.createTopology());
Thread.sleep(460000);
cluster.shutdown();
}
}
}
| true
|
ff6bca8feb1e63ccba18334129877fe780372bd6
|
Java
|
daedafusion/aniketos
|
/aniketos-core/src/main/java/com/daedafusion/aniketos/services/admin/PolicyAdminService.java
|
UTF-8
| 6,040
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.daedafusion.aniketos.services.admin;
import com.daedafusion.aniketos.exceptions.ServiceErrorException;
import com.daedafusion.security.admin.PolicyAdmin;
import com.daedafusion.sf.ServiceFramework;
import com.daedafusion.sf.ServiceFrameworkException;
import com.daedafusion.sf.ServiceFrameworkFactory;
import com.daedafusion.security.authentication.Subject;
import com.daedafusion.security.authentication.Token;
import com.daedafusion.security.authentication.TokenExchange;
import com.daedafusion.security.common.LockoutPolicy;
import com.daedafusion.security.common.PasswordPolicy;
import com.daedafusion.security.exceptions.InvalidTokenException;
import com.daedafusion.security.exceptions.UnauthorizedException;
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
* Created by mphilpot on 7/29/14.
*/
@Path("admin/policy")
public class PolicyAdminService
{
private static final Logger log = Logger.getLogger(PolicyAdminService.class);
@GET
@Path("lockout/{domain}")
@Produces(MediaType.APPLICATION_JSON)
public LockoutPolicy getLockoutPolicy(@HeaderParam("authorization") String tokenString,
@PathParam("domain") String domain)
{
try
{
ServiceFramework framework = ServiceFrameworkFactory.getInstance().getFramework();
TokenExchange tokenExchange = framework.getService(TokenExchange.class);
PolicyAdmin admin = framework.getService(PolicyAdmin.class);
Token token = tokenExchange.getToken(tokenString);
Subject subject = tokenExchange.exchange(token);
return admin.getLockoutPolicy(subject, domain);
}
catch (ServiceFrameworkException e)
{
log.error("", e);
throw new ServiceErrorException();
}
catch (UnauthorizedException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.UnauthorizedException();
}
catch (InvalidTokenException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.BadRequestException("Invalid Token");
}
}
@GET
@Path("password/{domain}")
@Produces(MediaType.APPLICATION_JSON)
public PasswordPolicy getPasswordPolicy(@HeaderParam("authorization") String tokenString,
@PathParam("domain") String domain)
{
try
{
ServiceFramework framework = ServiceFrameworkFactory.getInstance().getFramework();
TokenExchange tokenExchange = framework.getService(TokenExchange.class);
PolicyAdmin admin = framework.getService(PolicyAdmin.class);
Token token = tokenExchange.getToken(tokenString);
Subject subject = tokenExchange.exchange(token);
return admin.getPasswordPolicy(subject, domain);
}
catch (ServiceFrameworkException e)
{
log.error("", e);
throw new ServiceErrorException();
}
catch (UnauthorizedException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.UnauthorizedException();
}
catch (InvalidTokenException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.BadRequestException("Invalid Token");
}
}
@POST
@Path("lockout/{domain}")
@Consumes(MediaType.APPLICATION_JSON)
public void setLockoutPolicy(@HeaderParam("authorization") String tokenString,
@PathParam("domain") String domain,
LockoutPolicy policy)
{
try
{
ServiceFramework framework = ServiceFrameworkFactory.getInstance().getFramework();
TokenExchange tokenExchange = framework.getService(TokenExchange.class);
PolicyAdmin admin = framework.getService(PolicyAdmin.class);
Token token = tokenExchange.getToken(tokenString);
Subject subject = tokenExchange.exchange(token);
admin.setLockoutPolicy(subject, domain, policy);
}
catch (ServiceFrameworkException e)
{
log.error("", e);
throw new ServiceErrorException();
}
catch (UnauthorizedException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.UnauthorizedException();
}
catch (InvalidTokenException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.BadRequestException("Invalid Token");
}
}
@POST
@Path("password/{domain}")
@Consumes(MediaType.APPLICATION_JSON)
public void setPasswordPolicy(@HeaderParam("authorization") String tokenString,
@PathParam("domain") String domain,
PasswordPolicy policy)
{
try
{
ServiceFramework framework = ServiceFrameworkFactory.getInstance().getFramework();
TokenExchange tokenExchange = framework.getService(TokenExchange.class);
PolicyAdmin admin = framework.getService(PolicyAdmin.class);
Token token = tokenExchange.getToken(tokenString);
Subject subject = tokenExchange.exchange(token);
admin.setPasswordPolicy(subject, domain, policy);
}
catch (ServiceFrameworkException e)
{
log.error("", e);
throw new ServiceErrorException();
}
catch (UnauthorizedException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.UnauthorizedException();
}
catch (InvalidTokenException e)
{
log.error("", e);
throw new com.daedafusion.aniketos.exceptions.BadRequestException("Invalid Token");
}
}
}
| true
|
05dfa866b128b03ed26003e7e815cd7059b4bcc1
|
Java
|
glarimy/glarimy-java-soap-services
|
/glarimy-bank-server-3.0.0/src/main/java/com/glarimy/bank/Bank.java
|
UTF-8
| 4,086
| 2.09375
| 2
|
[] |
no_license
|
package com.glarimy.bank;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebService(name = "Bank", targetNamespace = "http://www.glarimy.com/bank")
@XmlSeeAlso({
ObjectFactory.class
})
public interface Bank {
/**
*
* @param customer
* @return
* returns int
*/
@WebMethod(action = "http://www.glarimy.com/bank/openAccountFor")
@WebResult(name = "no", targetNamespace = "http://www.glarimy.com/bank")
@RequestWrapper(localName = "openAccountFor", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.OpenAccountFor")
@ResponseWrapper(localName = "openAccountForResponse", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.OpenAccountForResponse")
public int openAccountFor(
@WebParam(name = "customer", targetNamespace = "http://www.glarimy.com/bank")
Customer customer);
/**
*
* @param no
* @param amount
* @return
* returns double
*/
@WebMethod(action = "http://www.glarimy.com/bank/deposit")
@WebResult(name = "balance", targetNamespace = "http://www.glarimy.com/bank")
@RequestWrapper(localName = "deposit", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.Deposit")
@ResponseWrapper(localName = "depositResponse", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.DepositResponse")
public double deposit(
@WebParam(name = "no", targetNamespace = "http://www.glarimy.com/bank")
int no,
@WebParam(name = "amount", targetNamespace = "http://www.glarimy.com/bank")
double amount);
/**
*
* @param no
* @param amount
* @return
* returns double
*/
@WebMethod(action = "http://www.glarimy.com/bank/withdraw")
@WebResult(name = "balance", targetNamespace = "http://www.glarimy.com/bank")
@RequestWrapper(localName = "withdraw", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.Withdraw")
@ResponseWrapper(localName = "withdrawResponse", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.WithdrawResponse")
public double withdraw(
@WebParam(name = "no", targetNamespace = "http://www.glarimy.com/bank")
int no,
@WebParam(name = "amount", targetNamespace = "http://www.glarimy.com/bank")
double amount);
/**
*
* @param no
* @return
* returns com.glarimy.bank.Account
*/
@WebMethod(action = "http://www.glarimy.com/bank/find")
@WebResult(name = "account", targetNamespace = "http://www.glarimy.com/bank")
@RequestWrapper(localName = "find", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.Find")
@ResponseWrapper(localName = "findResponse", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.FindResponse")
public Account find(
@WebParam(name = "no", targetNamespace = "http://www.glarimy.com/bank")
int no);
/**
*
* @param no
* @return
* returns java.util.List<com.glarimy.bank.Transaction>
*/
@WebMethod(action = "http://www.glarimy.com/bank/history")
@WebResult(name = "transaction", targetNamespace = "http://www.glarimy.com/bank")
@RequestWrapper(localName = "history", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.History")
@ResponseWrapper(localName = "historyResponse", targetNamespace = "http://www.glarimy.com/bank", className = "com.glarimy.bank.HistoryResponse")
public List<Transaction> history(
@WebParam(name = "no", targetNamespace = "http://www.glarimy.com/bank")
int no);
}
| true
|
a2b2cae54e9d2d7ae16dd01d3744e643224b9bbb
|
Java
|
tereshko/cloud_storage
|
/cloud_client/src/main/java/controllers/Controller_signin.java
|
UTF-8
| 3,434
| 2.328125
| 2
|
[] |
no_license
|
package controllers;
import Network.Client;
import Network.ClientCommands;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.log4j.Logger;
import security.GFG;
import java.io.IOException;
public class Controller_signin {
Logger LOGGER = Logger.getLogger(Controller_signin.class);
private Client client = Client.getInstance();
ClientCommands clientCommands = new ClientCommands();
public void buttonExitAction(ActionEvent actionEvent) {
Platform.exit();
}
@FXML
Button registration;
public void buttonRegistration(ActionEvent actionEvent) {
Stage stage = (Stage) registration.getScene().getWindow();
stage.close();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/registration_modal.fxml"));
Parent registration_scene = null;
try {
registration_scene = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
stage = new Stage();
stage.setTitle("Cloud Client");
stage.setScene(new Scene(registration_scene));
stage.show();
}
@FXML
PasswordField passwordField_password;
@FXML
TextField textField_username;
@FXML
Label label_error;
public void buttonLogIn(ActionEvent actionEvent) {
String pass = getCryptPass(passwordField_password.getText());
String userName = textField_username.getText();
//TODO сделать проверку на то, что данные не пустые
LOGGER.info("buttonLogIn." + " username: " + userName + " password: " + pass);
String sendToServer = "authorization\n" + userName + "\n" + pass;
System.out.println("Sended to server: " + sendToServer);
clientCommands.sendCommand(client.getCurrentChannel(), sendToServer);
client.getHandler().getCallback(callback -> {
System.out.println("CLIENT: " + callback);
if (callback.equals("notOk")) {
Platform.runLater(() -> {
label_error.setText("User not found");
}
);
} else {
changeScheme();
}
});
}
private void changeScheme() {
Platform.runLater(() -> {
Stage stage = (Stage) registration.getScene().getWindow();
stage.close();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/main_modal.fxml"));
Parent registration_scene = null;
try {
registration_scene = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
stage = new Stage();
stage.setTitle("Cloud Client");
stage.setScene(new Scene(registration_scene));
stage.show();
}
);
}
private String getCryptPass(String pass) {
return GFG.toHexString(GFG.getSHA(pass));
}
}
| true
|
c43f9862d83ca8f3d31abc49f001b61a88d0237a
|
Java
|
Jatish-Khanna/leetcode_hackerrank_java_solutions
|
/Find_the_longest_path_in_a_matrix_with_given_constraints.java
|
UTF-8
| 2,036
| 3.359375
| 3
|
[] |
no_license
|
class Solution {
static int ROWS;
static int COLS;
private static int findLongestPathOverAll(int[][] matrix) {
int maxPathLength = 0;
if (matrix == null)
return maxPathLength;
int[][] visited = new int[ROWS][COLS];
for (int rowIndex = 0; rowIndex < ROWS; rowIndex++) {
for (int colIndex = 0; colIndex < COLS; colIndex++) {
if (visited[rowIndex][colIndex] == 0) {
maxPathLength = Math.max(maxPathLength, depthFirstSearch(matrix, visited, rowIndex, colIndex));
}
}
}
return maxPathLength;
}
private static int depthFirstSearch(int[][] matrix, int[][] visited, int rowIndex, int colIndex) {
// Out of bounds
if (rowIndex < 0 || rowIndex >= ROWS || colIndex < 0 || colIndex >= COLS)
return 0;
// Already visited the position
if (visited[rowIndex][colIndex] != 0)
return visited[rowIndex][colIndex];
// Iterate over other four directions
if (rowIndex < ROWS - 1 && matrix[rowIndex][colIndex] == matrix[rowIndex + 1][colIndex] + 1)
return visited[rowIndex][colIndex] = depthFirstSearch(matrix, visited, rowIndex + 1, colIndex) + 1;
if (rowIndex > 0 && matrix[rowIndex][colIndex] == matrix[rowIndex - 1][colIndex] + 1)
return visited[rowIndex][colIndex] = depthFirstSearch(matrix, visited, rowIndex - 1, colIndex) + 1;
if (colIndex < COLS - 1 && matrix[rowIndex][colIndex] == matrix[rowIndex][colIndex + 1] + 1)
return visited[rowIndex][colIndex] = depthFirstSearch(matrix, visited, rowIndex, colIndex + 1) + 1;
if (colIndex > 0 && matrix[rowIndex][colIndex] == matrix[rowIndex][colIndex - 1] + 1)
return visited[rowIndex][colIndex] = depthFirstSearch(matrix, visited, rowIndex, colIndex - 1) + 1;
return visited[rowIndex][colIndex] = 1;
}
// driver program
public static void main(String[] args) {
int matrix[][] = { { 1, 2, 7 },
{ 5, 15, 8 },
{ 13, 14, 9 },
{ 12, 11, 10 } };
ROWS = matrix.length;
COLS = matrix[0].length;
System.out.println("Length of the longest path is " + findLongestPathOverAll(matrix));
}
}
| true
|
0b6898d9d3de46b770bac0a45e35c86feec6df2b
|
Java
|
haodeSun/GSP
|
/src/main/java/com/thinkgem/jeesite/modules/sys/web/SysAlarmFilterController.java
|
UTF-8
| 4,153
| 1.804688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.thinkgem.jeesite.modules.gsp.service.exception.BusinessException;
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.SysAlarmFilter;
import com.thinkgem.jeesite.modules.sys.service.SysAlarmFilterService;
/**
* 预警过滤配置Controller
* @author yohu
* @version 2016-12-26
*/
@Controller
@RequestMapping(value = "${adminPath}/sys/sysAlarmFilter")
public class SysAlarmFilterController extends BaseController {
@SuppressWarnings("WeakerAccess")
SysAlarmFilterService sysAlarmFilterService;
@Autowired
public SysAlarmFilterController(SysAlarmFilterService sysAlarmFilterService) {
Assert.notNull(sysAlarmFilterService);
this.sysAlarmFilterService = sysAlarmFilterService;
}
@ModelAttribute
public SysAlarmFilter get(@RequestParam(required=false) String id) {
SysAlarmFilter entity = null;
if (StringUtils.isNotBlank(id)){
entity = sysAlarmFilterService.get(id);
}
if (entity == null){
entity = new SysAlarmFilter();
}
return entity;
}
@RequiresPermissions("sys:sysAlarmFilter:view")
@RequestMapping(value = {"list", ""})
public String list(
@RequestParam(required = false) String conditionOrder,
SysAlarmFilter sysAlarmFilter,
HttpServletRequest request,
HttpServletResponse response,
Model model) {
Page<SysAlarmFilter> page = sysAlarmFilterService.findPage(new Page<>(request, response), sysAlarmFilter);
model.addAttribute("page", page);
//保存上次查询条件
model.addAttribute("conditionOrder", conditionOrder);
return "modules/sys/sysAlarmFilterList";
}
@RequiresPermissions("sys:sysAlarmFilter:view")
@RequestMapping(value = "form")
public String form(SysAlarmFilter sysAlarmFilter, Model model, String view) {
model.addAttribute("sysAlarmFilter", sysAlarmFilter);
if(view != null && !view.isEmpty()){
return view;
}
return "modules/sys/sysAlarmFilterForm";
}
@RequiresPermissions("sys:sysAlarmFilter:edit")
@RequestMapping(value = "save")
public String save(
SysAlarmFilter sysAlarmFilter,
Model model,
RedirectAttributes redirectAttributes) {
if (!beanValidator(model, sysAlarmFilter)){
return form(sysAlarmFilter, model, null);
}
try{
sysAlarmFilterService.save(sysAlarmFilter);
} catch (Exception e) {
String message = e.getMessage();
if (message != null && !message.isEmpty()) {
String[] mess = message.split(",");
if (mess.length >= 2) {
message = mess[0];
}
addMessage(redirectAttributes, message);
}
return form(sysAlarmFilter, model, null);
}
addMessage(redirectAttributes, "保存预警过滤配置成功");
return "redirect:"+Global.getAdminPath()+"/sys/sysAlarmFilter/?repage";
}
@RequiresPermissions("sys:sysAlarmFilter:edit")
@RequestMapping(value = "delete")
public String delete(
SysAlarmFilter sysAlarmFilter,
RedirectAttributes redirectAttributes) {
try {
sysAlarmFilterService.delete(sysAlarmFilter);
} catch (BusinessException e) {
e.printStackTrace();
}
addMessage(redirectAttributes, "删除预警过滤配置成功");
return "redirect:"+Global.getAdminPath()+"/sys/sysAlarmFilter/?repage";
}
}
| true
|
b018c86760f38a46118878e4a23ec9cabccce9ff
|
Java
|
thend-wk/friendship
|
/src/main/java/com/thend/friendship/utils/JsonSerializer.java
|
UTF-8
| 2,097
| 2.40625
| 2
|
[] |
no_license
|
package com.thend.friendship.utils;
import java.io.StringWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.type.TypeReference;
public class JsonSerializer {
private static final Log logger = LogFactory.getLog(JsonSerializer.class);
public static ObjectMapper json = new ObjectMapper();
private static final JsonFactory jsonFactory = new JsonFactory();
static {
json.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false)
.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)
.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
}
public static String toJson(Object pojo) {
return toJson(pojo, false);
}
public static String toJson(Object pojo, boolean prettyPrint) {
try {
StringWriter sw = new StringWriter();
JsonGenerator jg = jsonFactory.createJsonGenerator(sw);
if (prettyPrint) {
jg.useDefaultPrettyPrinter();
}
json.writeValue(jg, pojo);
return sw.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T> T fromJson(String jsonAsString, Class<T> pojoClass) {
try {
return json.readValue(jsonAsString, pojoClass);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
public static <T> T fromJson(String jsonAsString,TypeReference<T> typeRef){
try {
return json.readValue(jsonAsString, typeRef);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
| true
|
43ff1d59fb5160aacba2c72995308a03c75b69c1
|
Java
|
aliyun/aliyun-odps-java-sdk
|
/odps-sdk-impl/odps-mapred-local/src/test/java/com/aliyun/odps/mapred/local/AllowNoInputPositive.java
|
UTF-8
| 2,354
| 1.648438
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyun.odps.mapred.local;
import java.io.IOException;
import org.junit.Test;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.local.common.WareHouse;
import com.aliyun.odps.mapred.JobClient;
import com.aliyun.odps.mapred.MapperBase;
import com.aliyun.odps.mapred.RunningJob;
import com.aliyun.odps.mapred.conf.JobConf;
import com.aliyun.odps.mapred.conf.SessionState;
import com.aliyun.odps.mapred.local.utils.TestUtils;
public class AllowNoInputPositive {
public static class Mapper1 extends MapperBase {
@Override
public void setup(TaskContext context) throws IOException {
System.err.println("Mapper1 running");
context.getCounter("MyCounters", "EnterSetup").increment(1);
}
}
public static void main(String[] args) throws OdpsException {
JobConf job1 = new JobConf();
job1.setMapperClass(Mapper1.class);
job1.setNumReduceTasks(0);
// job.setAllowNoInput(true); // new mr do not need this
RunningJob rj = JobClient.runJob(job1);
long counter = rj.getCounters().findCounter("MyCounters", "EnterSetup").getValue();
int expect = job1.getInt("odps.stage.mapper.num", 1);
if (counter != expect) {
throw new RuntimeException("Incorrect counter, expect: " + expect + ", get: " + counter);
}
}
@Test
public void test() throws Exception {
WareHouse wareHouse = WareHouse.getInstance();
String project = TestUtils.odps_test_mrtask;
TestUtils.setEnvironment(project);
new AllowNoInputPositive().main(new String[0]);
}
}
| true
|
0dc7e7dc2ea451489b02ddfcfb12d00475dfa2e6
|
Java
|
npatel338/Fancy_Hotel
|
/fancyhotel/src/main/java/com/db/cs4400/fancyhotel/dao/ReservationDao.java
|
UTF-8
| 6,693
| 2.28125
| 2
|
[] |
no_license
|
package com.db.cs4400.fancyhotel.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.db.cs4400.fancyhotel.model.Customer;
import com.db.cs4400.fancyhotel.model.Reservation;
import com.db.cs4400.fancyhotel.model.Room;
import com.db.cs4400.fancyhotel.util.Util;
@Component
public class ReservationDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Value("${room.location.query}")
private String roomLocationQuery;
@Value("${room.search.reservation.query}")
private String roomSearchReservationQuery;
@Value("${room.save.reservation.query}")
private String roomSaveReservationQuery;
@Value("${room.save.reservation.room.query}")
private String roomSaveReservationExtraBedQuery;
@Value("${room.get.max.reservation.number}")
private String roomGetMaxReservationNumberQuery;
@Value("${room.search.reservationbyid.query}")
private String roomSearchReservationByIdQuery;
public List<String> getLocations() {
List<String> locations = new ArrayList<String>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
String.format(roomLocationQuery));
if (CollectionUtils.isNotEmpty(rows)) {
for (Map<String, Object> row : rows) {
locations.add((String)row.get("Loc"));
}
}
return locations;
}
public List<Room> searchRooms(final String location, final Date startDate, final Date endDate) {
if (StringUtils.isEmpty(location) || startDate == null || endDate == null) {
return null;
}
java.sql.Date sqlStartDate = new java.sql.Date(startDate.getTime());
java.sql.Date sqlEndDate = new java.sql.Date(endDate.getTime());
List<Room> rooms = new ArrayList<>();
String sqlQuery = String.format(roomSearchReservationQuery,
sqlStartDate, sqlStartDate, sqlEndDate, sqlEndDate, location, location);
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sqlQuery);
if (CollectionUtils.isNotEmpty(rows)) {
for (Map<String, Object> row : rows) {
if (MapUtils.isNotEmpty(row)) {
Room room = new Room();
room.setRoomNumber((Integer) row.get("Room_num"));
room.setCategory((String) row.get("Category"));
room.setCostDay((BigDecimal) row.get("Cost_day"));
room.setCostExtraBed((BigDecimal) row.get("Cost_extra_bed"));
room.setNumOfPeopleAllowed((Integer) row.get("Num_People"));
room.setLocation((String) row.get("Loc"));
rooms.add(room);
}
}
}
return rooms;
}
public List<Room> searchRoomsByRooms(final String location,
final Date startDate, final Date endDate, final List<Integer> roomNums) {
if (StringUtils.isEmpty(location) || startDate == null || endDate == null) {
return null;
}
java.sql.Date sqlStartDate = new java.sql.Date(startDate.getTime());
java.sql.Date sqlEndDate = new java.sql.Date(endDate.getTime());
List<Room> rooms = new ArrayList<>();
String sqlQuery = String.format(roomSearchReservationQuery,
sqlStartDate, sqlStartDate, sqlEndDate, sqlEndDate, location, location);
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sqlQuery);
if (CollectionUtils.isNotEmpty(rows)) {
for (Map<String, Object> row : rows) {
if (MapUtils.isNotEmpty(row)) {
Room room = new Room();
room.setRoomNumber((Integer) row.get("Room_num"));
room.setCategory((String) row.get("Category"));
room.setCostDay((BigDecimal) row.get("Cost_day"));
room.setCostExtraBed((BigDecimal) row.get("Cost_extra_bed"));
room.setNumOfPeopleAllowed((Integer) row.get("Num_People"));
room.setLocation((String) row.get("Loc"));
rooms.add(room);
}
}
}
return rooms;
}
public Integer saveReservation(final List<Reservation> reservations, final Integer cardNumber) {
if (CollectionUtils.isEmpty(reservations) || cardNumber == null) {
return null;
}
int reservationNumber = getMaxReservationNumber() + 1;
for (Reservation reservation : reservations) {
java.sql.Date sqlStartDate = new java.sql.Date(reservation.getStartDate().getTime());
java.sql.Date sqlEndDate = new java.sql.Date(reservation.getEndDate().getTime());
float totalCostPerRoom = 0;
long noOfDaysStay = Util.getDifferenceDays(reservation.getStartDate(), reservation.getEndDate());
totalCostPerRoom += noOfDaysStay * reservation.getCostOfRoom();
if (reservation.isExtraBed()) {
totalCostPerRoom += noOfDaysStay * reservation.getCostOfExtraBed();
}
this.jdbcTemplate.execute(String.format(
roomSaveReservationQuery, reservationNumber, reservation.getRoomNumber(), reservation.getLocation(),
sqlStartDate, sqlEndDate, totalCostPerRoom, 1, cardNumber, reservation.getUserName()));
int extraBed = reservation.isExtraBed() ? 1 : 0;
this.jdbcTemplate.execute(String.format(
roomSaveReservationExtraBedQuery, reservationNumber, reservation.getRoomNumber(), reservation.getLocation(),
extraBed));
}
return new Integer(reservationNumber);
}
public List<Reservation> searchReservation(final Integer reservationId) {
if (reservationId == null) {
return null;
}
List<Reservation> reservations = new ArrayList<Reservation>();
List<Map<String, Object>> rows = this.jdbcTemplate.queryForList(String
.format(roomSearchReservationByIdQuery, reservationId));
if (CollectionUtils.isNotEmpty(rows)) {
for (Map<String, Object> row : rows) {
java.sql.Date sqlStartDate = (java.sql.Date) row.get("St_dt");
java.sql.Date sqlEndDate = (java.sql.Date) row.get("End_dt");
Reservation reservation = new Reservation();
reservation.setLocation((String) row.get("Loc"));
reservation.setStartDate(new Date(sqlStartDate.getTime()));
reservation.setEndDate(new Date(sqlEndDate.getTime()));
reservations.add(reservation);
}
}
return reservations;
}
public int getMaxReservationNumber() {
int max = 0;
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
String.format(roomGetMaxReservationNumberQuery));
if (CollectionUtils.isNotEmpty(rows)) {
Map<String, Object> row = rows.iterator().next();
if (MapUtils.isNotEmpty(row) && row.get("Res_num") != null) {
max = (Integer) row.get("Res_num");
}
}
return max;
}
private long generateReservationNumber() {
Date now = new Date();
return now.getTime();
}
}
| true
|
c61490e916bddb7fef1edcd482a3f61eeaa276e7
|
Java
|
CaeserNieh/Gene_Algorithm
|
/src/CarStart.java
|
UTF-8
| 3,785
| 2.640625
| 3
|
[] |
no_license
|
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
public class CarStart extends Thread {
private Car car;
private Engine engine;
private double[] bestDNA;
private double[] bestLocation;
private int sysFlag;// 0 for Fuzzy 1 for GA
public static Point carT, carL, carR, min_InterPointT, min_InterPointL, min_InterPointR;
public static Point CarLocate, CarT_Locate, CarL_Locate, CarR_Locate;
public Distence dis;
private boolean isTerminated = false;
public CarStart(Car car, Engine engine) {
// TODO Auto-generated constructor stub
this.car = car;
this.engine = engine;
CountInterPoint_TRL();
}
public void terminator() {
isTerminated = true;
interrupt();
}
public Point CountMinInterPoint(Point o, Point p, Point Sensor) {
double min_dist = 1000;
double dist;
Point min_InterPoint = new Point(0, 0);
for (int i = 0; i < 7; i++) {
Point InterPoint;
InterPoint = Distence.Intersec(o, p, MainClass.BoundPoint.get(i), MainClass.BoundPoint.get(i + 1));
dist = CountDist(Sensor, InterPoint);
if (dist < min_dist) {
min_dist = dist;
min_InterPoint = InterPoint;
}
}
return min_InterPoint;
}
public double CountDist(Point p, Point q) {
double distX = p.getX() - q.getX();
double distY = p.getY() - q.getY();
return Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
}
public void CountInterPoint_TRL() {
CarLocate = new Point(car.getX(), car.getY());
carT = new Point(car.getX() + car.getRadius() * Math.cos(Math.toRadians(car.getPhi())),
car.getY() + car.getRadius() * Math.sin(Math.toRadians(car.getPhi())));
carR = new Point(car.getX() + car.getRadius() * Math.cos(Math.toRadians(car.getPhi() + 45)),
car.getY() + car.getRadius() * Math.sin(Math.toRadians(car.getPhi() + 45)));
carL = new Point(car.getX() + car.getRadius() * Math.cos(Math.toRadians(car.getPhi() - 45)),
car.getY() + car.getRadius() * Math.sin(Math.toRadians(car.getPhi() - 45)));
CarT_Locate = new Point(car.getX() + 300 * Math.cos(Math.toRadians(car.getPhi())),
car.getY() + 300 * Math.sin(Math.toRadians(car.getPhi())));
min_InterPointT = CountMinInterPoint(CarLocate, CarT_Locate, carT);
CarR_Locate = new Point(car.getX() + 300 * Math.cos(Math.toRadians(car.getPhi() + 45)),
car.getY() + 300 * Math.sin(Math.toRadians(car.getPhi() + 45)));
min_InterPointR = CountMinInterPoint(CarLocate, CarR_Locate, carR);
CarL_Locate = new Point(car.getX() + 300 * Math.cos(Math.toRadians(car.getPhi() - 45)),
car.getY() + 300 * Math.sin(Math.toRadians(car.getPhi() - 45)));
min_InterPointL = CountMinInterPoint(CarLocate, CarL_Locate, carL);
}
public void run() {
while (!isTerminated) {
double distT, distL, distR;
double theta = car.getTheta();
engine.newlocation(theta);
CountInterPoint_TRL();
distR = CountDist(carR, min_InterPointR);
distL = CountDist(carL, min_InterPointL);
distT = CountDist(carT, min_InterPointT);
FuzzySystem fSystem = new FuzzySystem();
fSystem.Right_Left(distR, distL);
fSystem.Front(distT);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("TrainingData.txt", true));
bw.write(distT + " " + distR + " " + distL + " " + theta);
bw.newLine();
bw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(distT + " " + distR + " " + distL + " " + theta);
car.setTheta(fSystem.Defuzzification());
MainClass.frame.revalidate();
MainClass.frame.repaint();
if (car.getY() - car.getRadius() <= 215) {
terminator();
}
try {
sleep(50);
} catch (InterruptedException e) {
}
}
}
}
| true
|
cb32957c31769a33e19b0b9d806a2b48519ae769
|
Java
|
youkiixu/YJAPP
|
/platforms/android/WeexFrameworkWrapper/nexus/nexus/src/main/java/com/eros/framework/model/PlatformConfigBean.java
|
UTF-8
| 9,134
| 1.828125
| 2
|
[
"MIT"
] |
permissive
|
package com.eros.framework.model;
import android.content.Context;
import android.text.TextUtils;
import com.eros.framework.constant.Constant;
import com.eros.framework.manager.ManagerFactory;
import com.eros.framework.manager.StorageManager;
import java.io.Serializable;
import java.util.List;
/**
* Created by Carry on 2017/8/23.
*/
public class PlatformConfigBean implements Serializable {
private String AppName;
private String appBoard;
private boolean androidIsListenHomeBack;
private Page Page;
private Url url;
private Wechat wechat;
private Umeng umeng;
private Amap amap;
private TabBar tabBar;
private boolean customBundleUpdate;
public boolean isCustomBundleUpdate() {
return customBundleUpdate;
}
public void setCustomBundleUpdate(boolean customBundleUpdate) {
this.customBundleUpdate = customBundleUpdate;
}
public boolean isAndroidIsListenHomeBack() {
return androidIsListenHomeBack;
}
public void setAndroidIsListenHomeBack(boolean androidIsListenHomeBack) {
this.androidIsListenHomeBack = androidIsListenHomeBack;
}
public Wechat getWechat() {
return wechat;
}
public void setWechat(Wechat wechat) {
this.wechat = wechat;
}
public Umeng getUmeng() {
return umeng;
}
public void setUmeng(Umeng umeng) {
this.umeng = umeng;
}
public Amap getAmap() {
return amap;
}
public void setAmap(Amap amap) {
this.amap = amap;
}
public String getAppName() {
return AppName;
}
public void setAppName(String appName) {
AppName = appName;
}
public PlatformConfigBean.Page getPage() {
return Page;
}
public void setPage(PlatformConfigBean.Page page) {
Page = page;
}
public Url getUrl() {
return url;
}
public void setUrl(Url url) {
this.url = url;
}
public String getAppBoard() {
return appBoard;
}
public void setAppBoard(String appBoard) {
this.appBoard = appBoard;
}
public TabBar getTabBar() {
return tabBar;
}
public void setTabBar(TabBar tabBar) {
this.tabBar = tabBar;
}
public class Page {
private String homePage;
private String mediatorPage;
private String navBarColor;
private String navItemColor;
public String getNavItemColor() {
return navItemColor;
}
public void setNavItemColor(String navItemColor) {
this.navItemColor = navItemColor;
}
public String getHomePage(Context context) {
StorageManager storageManager = ManagerFactory.getManagerService(StorageManager.class);
String page = storageManager.getData(context, Constant.SP.SP_HOMEPAGE_URL);
if (TextUtils.isEmpty(page)) {
page = homePage;
}
return page;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getMediatorPage() {
return mediatorPage;
}
public void setMediatorPage(String mediatorPage) {
this.mediatorPage = mediatorPage;
}
public String getNavBarColor() {
return navBarColor;
}
public void setNavBarColor(String navBarColor) {
this.navBarColor = navBarColor;
}
}
public class Url {
private String request;
private String jsServer;
private String image;
private String bundleUpdate;
private String socketServer;
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public String getJsServer() {
return TextUtils.isEmpty(jsServer) ? "http://app.weex-eros.com:8889" : jsServer;
}
public void setJsServer(String jsServer) {
this.jsServer = jsServer;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBundleUpdate() {
return bundleUpdate;
}
public void setBundleUpdate(String bundleUpdate) {
this.bundleUpdate = bundleUpdate;
}
public String getSocketServer() {
return socketServer;
}
public void setSocketServer(String socketServer) {
this.socketServer = socketServer;
}
}
public class Wechat {
private boolean enabled;
private String appId;
private String appSecret;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public boolean isWechatAvailable() {
return enabled && !TextUtils.isEmpty(appId) && !TextUtils.isEmpty(appSecret);
}
}
public class Umeng {
private boolean enabled;
private String androidAppKey;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAndroidAppKey() {
return androidAppKey;
}
public void setAndroidAppKey(String androidAppKey) {
this.androidAppKey = androidAppKey;
}
public boolean isUmengAvailable() {
return enabled && !TextUtils.isEmpty(androidAppKey);
}
}
public class Amap {
private boolean enabled;
private String androidAppKey;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAndroidAppKey() {
return androidAppKey;
}
public void setAndroidAppKey(String androidAppKey) {
this.androidAppKey = androidAppKey;
}
public boolean isAmapAvailable() {
return enabled && !TextUtils.isEmpty(androidAppKey);
}
}
public static class TabBar {
private String color;
private String selectedColor;
private String backgroundColor;
private String borderColor;
private List<TabItem> list;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSelectedColor() {
return selectedColor;
}
public void setSelectedColor(String selectedColor) {
this.selectedColor = selectedColor;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public String getBorderColor() {
return borderColor;
}
public void setBorderColor(String borderColor) {
this.borderColor = borderColor;
}
public List<TabItem> getList() {
return list;
}
public void setList(List<TabItem> list) {
this.list = list;
}
}
public static class TabItem {
private String pagePath;
private String text;
private String icon;
private String selectedIcon;
private boolean navShow;
private String navTitle;
public String getPagePath() {
return pagePath;
}
public void setPagePath(String pagePath) {
this.pagePath = pagePath;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getSelectedIcon() {
return selectedIcon;
}
public void setSelectedIcon(String selectedIcon) {
this.selectedIcon = selectedIcon;
}
public boolean isNavShow() {
return navShow;
}
public void setNavShow(boolean navShow) {
this.navShow = navShow;
}
public String getNavTitle() {
return navTitle;
}
public void setNavTitle(String navTitle) {
this.navTitle = navTitle;
}
}
}
| true
|
8013cb23b4d272b3feb3d07638aeba84e1c38a48
|
Java
|
ruchinbaliyan/CacheInJava
|
/src/remaining/subtopics/FailSafeAndFailFAst.java
|
UTF-8
| 1,426
| 3.140625
| 3
|
[] |
no_license
|
package remaining.subtopics;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class FailSafeAndFailFAst {
public static void main(String[] args) {
// checkFailFastBehavior();
checkFailSafeBehavior();
}
private static void checkFailFastBehavior() {
Map<String, Integer> map = new HashMap<>();
map.put("First", 10);
map.put("Second", 20);
map.put("Third", 30);
map.put("Fourth", 40);
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
map.put("Fifth", 50);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey());
}
}
private static void checkFailSafeBehavior() {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("First", 10);
map.put("Second", 20);
map.put("Third", 30);
map.put("Fourth", 40);
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
map.put("Fifth", 50);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey());
}
}
}
| true
|
04d065958f3dd3138ea39341e9e7ceb15f254eda
|
Java
|
DonDan-prog/task4
|
/Num1.java
|
UTF-8
| 828
| 3.59375
| 4
|
[] |
no_license
|
public class Num1
{
public static void main(String[] args)
{
System.out.println(bessi(10, 7, "hello my name is Bessie and this is my essay"));
}
public static String bessi(int n, int k, String str)
{
String ret = "";
String[] arr = str.split(" ");
int added = 0; // amount of added spaces
String temp_str = "";
for(int i = 0; i < n;)
{
String s = arr[i];
if(temp_str.length() + s.length() - added <= k)
{
temp_str += s + ' ';
added++;
i++;
}
else
{
added = 0;
ret += temp_str + '\n';
temp_str = "";
}
}
ret += temp_str + '\n';
return ret;
}
}
| true
|
1e8ceeb9604e71e67eb3ab7f28d75b7fc69653e5
|
Java
|
Bugguga/Bombmeth
|
/src/logic/GameController.java
|
UTF-8
| 457
| 2.71875
| 3
|
[] |
no_license
|
package logic;
import entity.Player;
public class GameController {
private static Player player1,player2;
private static boolean isWin=false;
private static GameMap gameMap;
public static void initializeMap() {
player1 = new Player("Good",3,1);
player2 = new Player("Nut",3,1);
gameMap = new GameMap();
}
public static boolean isWin() {
return isWin;
}
public static void setWin(boolean isWin) {
GameController.isWin = isWin;
}
}
| true
|
a216264b2eb7455710535861ea33b2ee3e80f21a
|
Java
|
wendellavila/BancoJavaFX
|
/src/TestaBanco.java
|
UTF-8
| 1,236
| 2.5625
| 3
|
[] |
no_license
|
//=========================================================================================//
// Projeto Banco com Interface gráfica JavaFX //
// //
// Autor: Wendell João Castro de Ávila //
// RA: 2017.1.08.013 //
// Data: 28/07/2018 //
// //
//=========================================================================================//
import windows.MainWindow;
import javafx.application.Application;
import javafx.stage.Stage;
public class TestaBanco extends Application {
public static void main(String[] args) {
launch(args);
}
//=================================== javafx ==========================================//
@Override
public void start(Stage stage) throws Exception {
MainWindow mainWindow = new MainWindow(stage);
mainWindow.display();
}
}
| true
|
2524e488dc81c3397e4bec632e59c3699b510ea7
|
Java
|
emirPuskaITAkademija/JavaGUIGroupThree
|
/src/seven/CustomTablePanel.java
|
UTF-8
| 715
| 2.609375
| 3
|
[] |
no_license
|
package seven;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class CustomTablePanel extends JPanel{
private final JTable table;
public CustomTablePanel(PlayerDao playerDao) {
Vector columnNames = playerDao.getColumnNames();
Vector rowData = playerDao.getRowData();
OurTableModel tableModel = new OurTableModel(columnNames, rowData);
table = new JTable(tableModel);
table.setPreferredScrollableViewportSize(new Dimension(500, 80));
table.setFillsViewportHeight(true);
add(new JScrollPane(table));
}
}
| true
|
b359046101263fff2c417a4e921ee94b23eed278
|
Java
|
AiRrRock/FileSystem
|
/fs/src/main/java/is/this_way/better/filesystem/model/high_level_items/SystemInfo.java
|
UTF-8
| 1,936
| 3.046875
| 3
|
[] |
no_license
|
package is.this_way.better.filesystem.model.high_level_items;
import java.util.Observable;
public class SystemInfo extends Observable {
private int sectors;
private int sectorSize;
private long fileStructurePos;
private int offset;
private SystemInfo(SystemInfoBuilder builder){
this.sectors=builder.sectors;
this.sectorSize=builder.sectorSize;
this.fileStructurePos =builder.fileStructurePos;
this.offset=builder.offset;
}
public long getSize(){
return sectors*sectorSize+offset;
}
public int getSectors() {
return sectors;
}
public int getSectorSize() {
return sectorSize;
}
public long getFileStructurePos() {
return fileStructurePos;
}
public int getOffset() {
return offset;
}
public void addSectors(int numberToAdd){
sectors+=numberToAdd;
setChanged();
notifyObservers();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(sectors+"\n");
sb.append(sectorSize+"\n");
sb.append(offset+"\n");
return sb.toString();
}
public static class SystemInfoBuilder {
private int sectors;
private int sectorSize;
private long fileStructurePos;
private int offset;
public SystemInfoBuilder(int sectors, int sectorSize){
this.sectors=sectors;
this.sectorSize= sectorSize;
}
public SystemInfoBuilder setOffset(int offset) {
this.offset = offset;
return this;
}
public SystemInfoBuilder setFileStructurePos(long fileStructurePos) {
this.fileStructurePos = fileStructurePos;
return this;
}
public SystemInfo build(){return new SystemInfo(this);}
}
}
| true
|
509a8ce4d5f2dd77ca6c7feca57fced278f00531
|
Java
|
gongxuanzhang/gaea-all
|
/gaea-core/src/main/java/com/gxz/gaea/core/config/GaeaEnvironment.java
|
UTF-8
| 1,030
| 2
| 2
|
[] |
no_license
|
package com.gxz.gaea.core.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author gxz gongxuanzhang@foxmail.com
*
* 由{@link GaeaHomeInjection}进行默认注入
**/
@ConfigurationProperties(prefix = "gaea")
@Getter
@Setter
public class GaeaEnvironment {
/**
* 当收集器收集到null或者捕获异常的时候是否终止此次之行
**/
private boolean collectorStop;
/**
* 可指定工作目录 如果不指定
* 默认当前目录在 ${home}/bin/执行
**/
private String home;
/**
* 默认 为${home}/config
**/
private String configPath;
/**
* 默认为 ${home}/log
**/
private String logPath;
/**
* 默认为 ${home}/data
**/
private String dataPath;
private String nodeName;
// back dir
private String backPath;
// dataWarehouse下
private String dataWarehouseCsvPath;
private String dataWarehouseJsonPath;
}
| true
|
e6eb4279ba6793c9acebf74c3054d9f372d7926a
|
Java
|
Egor322129/HistoryQuestsAndroid
|
/app/src/main/java/com/example/android/historyquests/QuestMetaData.java
|
UTF-8
| 619
| 2.296875
| 2
|
[] |
no_license
|
package com.example.android.historyquests;
import java.io.Serializable;
import java.util.ArrayList;
public class QuestMetaData implements Serializable {
public String questId;
public int lastRoundNum;
public boolean lastRoundRight;
public int level;
public ArrayList<String> players;
public QuestMetaData(String questId, int lastRoundNum, boolean lastRoundRight, int level, ArrayList<String> players) {
this.questId = questId;
this.lastRoundNum = lastRoundNum;
this.lastRoundRight = lastRoundRight;
this.level = level;
this.players = players;
}
}
| true
|
e35b54c2d2c0858c7c59ee9e2381c1b99e366c36
|
Java
|
Asher-fei/CarCare
|
/app/src/main/java/com/lida/carcare/adapter/AdapterBill.java
|
UTF-8
| 1,629
| 2.28125
| 2
|
[] |
no_license
|
package com.lida.carcare.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lida.carcare.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by WeiQingFeng on 2017/4/7.
*/
public class AdapterBill extends BaseAdapter {
private int count;
private Context context;
public AdapterBill(Context context, int count) {
this.count = count;
this.context = context;
}
@Override
public int getCount() {
return count;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.item_billdetail, null);
viewHolder=new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
@BindView(R.id.tvName)
TextView tvName;
@BindView(R.id.tvParams)
TextView tvParams;
@BindView(R.id.root)
LinearLayout root;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
| true
|
fe95f6f27889c2d7834ea1298c7e6882cbc53e9f
|
Java
|
SHUCharles/gdemo1
|
/src/main/java/com/glodon/gdemo1/GDemo1Application.java
|
UTF-8
| 1,701
| 2.109375
| 2
|
[] |
no_license
|
package com.glodon.gdemo1;
import com.glodon.gdemo1.service.Materials;
import com.glodon.gdemo1.utils.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GDemo1Application implements CommandLineRunner {
@Autowired
private Materials materials;
private static String destUrl = "";
public static String sourceUrl;
public static String targetUrl;
public static String JsonUrl;
public static void main(String[] args) throws ParseException {
CommandLineParser parser = new GnuParser();
org.apache.commons.cli.CommandLine cmd = parser.parse(CommandLine.OPTIONS, args);
if (cmd.hasOption("t")){
targetUrl = cmd.getOptionValue("t");
}
if (cmd.hasOption("d")){
setDestUrl(cmd.getOptionValue("d"));
}
if (cmd.hasOption("s")){
sourceUrl = cmd.getOptionValue("s");
}
if (cmd.hasOption("j")){
JsonUrl = cmd.getOptionValue("j");
}
SpringApplication.run(GDemo1Application.class, args);
}
public static void setDestUrl(String destUrl) {
GDemo1Application.destUrl = destUrl;
}
public static String getDestUrl() {
return destUrl;
}
@Override
public void run(String... args) throws Exception {
materials.copyAndRename();
}
}
| true
|
36772dacd136267a29eae09ef4dcbc3b8eb80f9a
|
Java
|
tatsuromiyazaki/ex-beginner
|
/src/main/java/com/example/controller/Exam04Controller.java
|
UTF-8
| 833
| 2.3125
| 2
|
[] |
no_license
|
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.domain.User;
import com.example.form.UserForm;
@Controller
@RequestMapping("/ex04")
public class Exam04Controller {
@RequestMapping("")
public String index() {
return "exam04";
}
@ModelAttribute
public UserForm setUpForm() {
return new UserForm();
}
@RequestMapping("/ex04-result")
public String result(UserForm form, Model model) {
User user = new User();
user.setName(form.getName());
user.setAge(Integer.parseInt(form.getAge()));
user.setComment(form.getComment());
model.addAttribute("user", user);
return "exam04-result";
}
}
| true
|
f002ce889edf2f34898f8d025ae1dd9e0fa22c13
|
Java
|
phannhathuy2804/Restaurant-information-tracking-app
|
/app/src/main/java/com/example/cmpt276project/ui/restaurantlist/PlaceInfo.java
|
UTF-8
| 2,665
| 2.109375
| 2
|
[] |
no_license
|
package com.example.cmpt276project.ui.restaurantlist;
import com.example.cmpt276project.model.Inspection;
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
public class PlaceInfo {
private String name;
private String address;
private String trackingNumber;
private String hazardLevelColor;
private String lastInspectionDate;
private LatLng latLng;
private List<Inspection> inspection;
public PlaceInfo(String name, String address, String trackingNumber, String hazardLevelColor, String lastInspectionDate, double lat, double lon, List<Inspection> inspection) {
this.name = name;
this.address = address;
this.trackingNumber = trackingNumber;
this.hazardLevelColor = hazardLevelColor;
this.lastInspectionDate = lastInspectionDate;
this.latLng = new LatLng(lat, lon);
this.inspection = inspection;
}
public PlaceInfo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTrackingNumber() {
return trackingNumber;
}
public void setTrackingNumber(String trackingNumber) {
this.trackingNumber = trackingNumber;
}
public String getHazardLevelColor() {
return hazardLevelColor;
}
public void setHazardLevelColor(String hazardLevelColor) {
this.hazardLevelColor = hazardLevelColor;
}
public String getLastInspectionDate() {
return lastInspectionDate;
}
public void setLastInspectionDate(String lastInspectionDate) {
this.lastInspectionDate = lastInspectionDate;
}
public LatLng getLatLng() {
return latLng;
}
public void setLatLng(double lat, double lon) {
this.latLng = new LatLng(lat, lon);
}
public List<Inspection> getInspection() {
return inspection;
}
public void setInspection(List<Inspection> inspection) {
this.inspection = inspection;
}
@Override
public String toString() {
return "PlaceInfo{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", trackingNumber='" + trackingNumber + '\'' +
", hazardLevelColor='" + hazardLevelColor + '\'' +
", lastInspectionDate='" + lastInspectionDate + '\'' +
", latLng=" + latLng +
", inspection=" + inspection +
'}';
}
}
| true
|
872e47e850c016164330beb18cb2f06c7fc0a965
|
Java
|
CNGL-repo/RMLProcessor
|
/src/test/java/be/ugent/mmlab/rml/MapperTest.java
|
UTF-8
| 4,949
| 1.953125
| 2
|
[
"MIT"
] |
permissive
|
package be.ugent.mmlab.rml;
import be.ugent.mmlab.rml.core.RMLEngine;
import be.ugent.mmlab.rml.core.RMLMappingFactory;
import be.ugent.mmlab.rml.model.RMLMapping;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.Test;
import junit.framework.TestCase;
import static junit.framework.TestCase.assertTrue;
import junit.framework.TestSuite;
import net.antidot.semantic.rdf.model.impl.sesame.SesameDataSet;
import net.antidot.semantic.rdf.rdb2rdf.r2rml.exception.InvalidR2RMLStructureException;
import net.antidot.semantic.rdf.rdb2rdf.r2rml.exception.InvalidR2RMLSyntaxException;
import net.antidot.semantic.rdf.rdb2rdf.r2rml.exception.R2RMLDataError;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
/**
* Unit test for simple App.
*/
public class MapperTest
extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public MapperTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(MapperTest.class);
}
/**
* Tests
*/
public void testExample1() {
URL fileToRMLFile = getClass().getResource("/example1/example.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example1/example.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
public void testExample2() {
URL fileToRMLFile = getClass().getResource("/example2/example.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example2/example.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
public void testExample3() {
URL fileToRMLFile = getClass().getResource("/example3/example3.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example3/example3.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
public void testExample4() {
URL fileToRMLFile = getClass().getResource("/example4/example4_Venue.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example4/example4_Venue.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
/*public void testExample5() {
URL fileToRMLFile = getClass().getResource("/example5/museum-model.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example5/museum.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
}*/
public void testExample6() {
URL fileToRMLFile = getClass().getResource("/example6/example.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example6/example.output.ttl");
assertTrue(desiredOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
public void testExample7() {
URL fileToRMLFile = getClass().getResource("/example7/example7.rml.ttl");
URL fileToOutputFile = getClass().getResource("/example7/example7.output.ttl");
assertTrue(desiredContextOutput(fileToOutputFile).isEqualTo(assertMap(fileToRMLFile)));
}
private SesameDataSet desiredOutput (URL outputURL){
SesameDataSet desiredOutput = new SesameDataSet();
desiredOutput.addFile(outputURL.getFile(), RDFFormat.TURTLE);
return desiredOutput;
}
private SesameDataSet desiredContextOutput (URL outputURL){
SesameDataSet desiredOutput = new SesameDataSet();
desiredOutput.addFile(outputURL.getFile(), RDFFormat.NQUADS);
return desiredOutput;
}
private SesameDataSet assertMap(URL mappingURL) {
try {
RMLMapping mapping = RMLMappingFactory.extractRMLMapping(mappingURL.getFile());
RMLEngine engine = new RMLEngine();
SesameDataSet output = engine.runRMLMapping(mapping, "http://example.com");
output.dumpRDF(System.out, RDFFormat.TURTLE);
return output;
} catch (SQLException | InvalidR2RMLStructureException | InvalidR2RMLSyntaxException |
R2RMLDataError | RepositoryException | RDFParseException ex) {
Logger.getLogger(MapperTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MapperTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MapperTest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
| true
|
9299b7e46bf8d11917410111dcca88e06b253a3f
|
Java
|
uttejadiraju/Spring-Framework-Concepts
|
/JPA hello World/jpa-kickstart-example/src/main/java/elementCollection/Boot.java
|
UTF-8
| 1,983
| 3.015625
| 3
|
[] |
no_license
|
package elementCollection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;
public class Boot {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit");
try {
persistEntity(emf);
runNativeQueries(emf);
loadEntity(emf);
} finally {
emf.close();
}
}
private static void persistEntity(EntityManagerFactory emf) {
System.out.println("-- Persisting entities --");
EntityManager em = emf.createEntityManager();
Customer c1 = new Customer();
c1.setName("Lindsey Craft");
c1.setPhoneNumbers(Arrays.asList("111-111-1111", "222-222-222"));
System.out.println(c1);
Customer c2 = new Customer();
c2.setName("Morgan Philips");
c2.setPhoneNumbers(Arrays.asList("333-333-3333"));
System.out.println(c2);
em.getTransaction().begin();
em.persist(c1);
em.persist(c2);
em.getTransaction().commit();
em.close();
}
private static void runNativeQueries(EntityManagerFactory emf) {
System.out.println("-- Native queries --");
EntityManager em = emf.createEntityManager();
nativeQuery(em, "Select * from Customer");
nativeQuery(em, "Select * from Customer_PhoneNumbers");
}
private static void loadEntity(EntityManagerFactory emf) {
System.out.println("-- Loading Customer --");
EntityManager em = emf.createEntityManager();
List<Customer> entityAList = em.createQuery("Select t from Customer t").getResultList();
entityAList.forEach(System.out::println);
em.close();
}
private static void nativeQuery(EntityManager em, String s) {
System.out.printf("'%s'%n", s);
Query query = em.createNativeQuery(s);
List list = query.getResultList();
for (Object o : list) {
if (o instanceof Object[]) {
System.out.println(Arrays.toString((Object[]) o));
} else {
System.out.println(o);
}
}
}
}
| true
|
3ffdd06fcd4be9aab31d312394fe3643ee05fdef
|
Java
|
SebUndefined/margot-java
|
/src/main/java/de/onetwotree/margaux/service/UserService.java
|
UTF-8
| 705
| 1.976563
| 2
|
[] |
no_license
|
package de.onetwotree.margaux.service;
import de.onetwotree.margaux.dto.UserDTO;
import de.onetwotree.margaux.entity.UserCustom;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.List;
/**
* Created by SebUndefined on 21/07/17.
*/
public interface UserService {
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
Page<UserCustom> findAll(Pageable pageable);
UserCustom save(UserDTO userDTO);
UserCustom findByUsername(String username);
UserCustom getUser(Long id);
List<UserCustom> getAllUsers();
}
| true
|
245763f07a0e2c4b08d73a7e46cb7711e1366650
|
Java
|
kb-1000/android-torchlight-temp
|
/app/src/main/java/com/fake/android/torchlight/camera/CameraMarshmallow.java
|
UTF-8
| 1,999
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.fake.android.torchlight.camera;
import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.widget.Toast;
import com.fake.android.torchlight.R;
class CameraMarshmallow extends Camera {
private String mCameraID;
private CameraManager mCameraManager;
private Context mContext;
private boolean invalid = false;
private String invalidityErrorString;
@TargetApi(Build.VERSION_CODES.M)
public void init(Context context) {
mContext = context;
mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
try {
assert mCameraManager != null;
String[] list = mCameraManager.getCameraIdList();
mCameraID = list[0];
} catch (CameraAccessException e) {
CameraControl.noFlash();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
invalid = true;
invalidityErrorString = e.getMessage();
CameraControl.noFlash();
} catch (IndexOutOfBoundsException e) {
Toast.makeText(mContext, R.string.no_camera, Toast.LENGTH_LONG).show();
invalid = true;
invalidityErrorString = mContext.getString(R.string.no_camera);
CameraControl.noFlash();
}
}
public void release() {
}
@TargetApi(Build.VERSION_CODES.M)
protected void toggle(boolean enable) {
if (invalid) {
Toast.makeText(mContext, invalidityErrorString, Toast.LENGTH_LONG).show();
CameraControl.noFlash();
return;
}
try {
mCameraManager.setTorchMode(mCameraID, enable);
} catch (CameraAccessException e) {
CameraControl.noFlash();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
| true
|
5e1a098a516fc4aa3e261e69dd5b3df5503ca9ce
|
Java
|
J4g0n/prj_010_Cours
|
/src/package_4_POOexos/Exercice0530_0540_0550.java
|
UTF-8
| 1,969
| 2.96875
| 3
|
[] |
no_license
|
package package_4_POOexos;
/**
* Created by ipi on 30/01/2015.
*/
public class Exercice0530_0540_0550 {
private String numeroCompte;
private String dateCreation;
private String typeCompte;
private double tauxRemuneration = -1;
public Exercice0530_0540_0550(String numeroCompte, String dateCreation, String typeCompte) {
this.numeroCompte = numeroCompte;
this.dateCreation = dateCreation;
this.typeCompte = typeCompte;
}
public Exercice0530_0540_0550(String numeroCompte, String dateCreation, String typeCompte, double tauxRemuneration) {
this.numeroCompte = numeroCompte;
this.dateCreation = dateCreation;
this.typeCompte = typeCompte;
this.tauxRemuneration = tauxRemuneration;
}
public String getNumeroCompte() {
return numeroCompte;
}
public void setNumeroCompte(String numeroCompte) {
this.numeroCompte = numeroCompte;
}
public String getDateCreation() {
return dateCreation;
}
public void setDateCreation(String dateCreation) {
this.dateCreation = dateCreation;
}
public String getTypeCompte() {
return typeCompte;
}
public void setTypeCompte(String typeCompte) {
this.typeCompte = typeCompte;
}
public double getTauxRemuneration() {
return tauxRemuneration;
}
public void setTauxRemuneration(double tauxRemuneration) {
this.tauxRemuneration = tauxRemuneration;
}
public void affiche() {
System.out.println("Numero compte: " + numeroCompte);
System.out.println("Date de création: " + dateCreation);
System.out.println("Type du compte: " + typeCompte);
if (tauxRemuneration > 0) {
System.out.println("Taux de rémunération: " + tauxRemuneration);
}
}
public void finalize() {
System.out.println("Je suis le desctructeur de la classe compte bancaire");
}
}
| true
|
760c6d7fb7dca4ddc12395c4edf7448a261ab93a
|
Java
|
juanczapata/reimagined-ceviche
|
/src/main/java/com/jcczdev/hotel/uam/data/model/location/Province.java
|
UTF-8
| 587
| 2.328125
| 2
|
[] |
no_license
|
package com.jcczdev.hotel.uam.data.model.location;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter @Setter @NoArgsConstructor
public class Province {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;
public Province(Long id, String name, Country country) {
this.id = id;
this.name = name;
this.country = country;
}
}
| true
|
1bc2dda45a546bbb05303acf931aae0973f3d335
|
Java
|
ygma/DeckOfCards
|
/RestfulApi/src/test/java/com/example/deckofcards/restfulapi/controller/DeckTest.java
|
UTF-8
| 1,820
| 2.25
| 2
|
[] |
no_license
|
package com.example.deckofcards.restfulapi.controller;
import com.example.deckofcards.dao.deck.Deck;
import com.example.deckofcards.dao.game.Game;
import com.example.deckofcards.restfulapi.controller.response.Link;
import com.example.deckofcards.restfulapi.controller.response.LinkRels;
import lombok.SneakyThrows;
import lombok.var;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.example.deckofcards.restfulapi.utils.LinkUtils.getLink;
import static org.junit.jupiter.api.Assertions.*;
public class DeckTest extends ApiBaseTest{
@Test
@SneakyThrows
public void should_create_a_deck() {
Link link = getLink(getRootLinks(), LinkRels.CREATE_DECK);
callApiToCreateResource(link);
List<Deck> actual = deckRepository.getAll();
assertEquals(1, actual.size());
}
@Test
@SneakyThrows
public void should_add_a_deck_to_a_game_deck_if_deck_is_available() {
Link linkToCreateDeck = getLink(getRootLinks(), LinkRels.CREATE_DECK);
callApiToCreateResource(linkToCreateDeck);
Link linkToCreateGame = getLink(getRootLinks(), LinkRels.CREATE_GAME);
var gameResponse = callApiToCreateResource(linkToCreateGame);
Link linkToAddDeckToGame = getLink(gameResponse.getLinks(), LinkRels.ADD_DECK_TO_GAME);
assertNotNull(linkToAddDeckToGame);
String gameId = gameResponse.getData().getId();
Game game = gameRepository.get(gameId);
assertEquals(0, game.getUnDealtCards().size());
callApi(linkToAddDeckToGame);
game = gameRepository.get(gameId);
assertEquals(52, game.getUnDealtCards().size());
gameResponse = callApiToCreateResource(linkToCreateGame);
assertNull(getLink(gameResponse.getLinks(), LinkRels.ADD_DECK_TO_GAME));
}
}
| true
|
b59ae23c52fac7b0da28268aef300cb633dbf5f9
|
Java
|
bdlions/InventoryServer
|
/src/main/java/org/bdlions/inventory/entity/manager/EntityManagerAdjustStockOrder.java
|
UTF-8
| 15,975
| 2.15625
| 2
|
[] |
no_license
|
package org.bdlions.inventory.entity.manager;
import java.util.ArrayList;
import java.util.List;
import org.bdlions.inventory.db.HibernateUtil;
import org.bdlions.inventory.entity.EntityAdjustStockOrder;
import org.bdlions.inventory.entity.EntityAdjustStockOrderProduct;
import org.bdlions.inventory.entity.EntityCustomer;
import org.bdlions.inventory.entity.EntityPOShowRoomProduct;
import org.bdlions.inventory.entity.EntityPOShowRoomReturnProduct;
import org.bdlions.inventory.entity.EntityPurchaseOrder;
import org.bdlions.inventory.entity.EntityPurchaseOrderPayment;
import org.bdlions.inventory.entity.EntitySaleOrder;
import org.bdlions.inventory.entity.EntitySaleOrderPayment;
import org.bdlions.inventory.entity.EntitySaleOrderProduct;
import org.bdlions.inventory.entity.EntitySaleOrderReturnProduct;
import org.bdlions.inventory.entity.EntityShowRoomStock;
import org.bdlions.inventory.entity.EntitySupplier;
import org.bdlions.inventory.util.Constants;
import org.bdlions.inventory.util.StringUtils;
import org.bdlions.inventory.util.TimeUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Nazmul Hasan
*/
public class EntityManagerAdjustStockOrder {
private final Logger logger = LoggerFactory.getLogger(EntityManagerAdjustStockOrder.class);
private int appId;
public EntityManagerAdjustStockOrder(int appId)
{
this.appId = appId;
}
public EntityAdjustStockOrder createAdjustStockOrder(EntityAdjustStockOrder entityAdjustStockOrder, Session session)
{
entityAdjustStockOrder.setCreatedOn(TimeUtils.getCurrentTime());
entityAdjustStockOrder.setModifiedOn(TimeUtils.getCurrentTime());
session.save(entityAdjustStockOrder);
return entityAdjustStockOrder;
}
public EntityAdjustStockOrder createAdjustStockOrder(EntityAdjustStockOrder entityAdjustStockOrder)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
return createAdjustStockOrder(entityAdjustStockOrder, session);
}
finally
{
session.close();
}
}
public EntityAdjustStockOrder createAdjustStockOrder(EntityAdjustStockOrder entityAdjustStockOrder, List<EntityAdjustStockOrderProduct> entityAdjustStockOrderProductList, List<EntityShowRoomStock> entityShowRoomStockList)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
Transaction tx = session.getTransaction();
tx.begin();
long currentUnixTime = TimeUtils.getCurrentTime();
try
{
entityAdjustStockOrder = createAdjustStockOrder(entityAdjustStockOrder, session);
if(entityAdjustStockOrder != null && !StringUtils.isNullOrEmpty(entityAdjustStockOrder.getOrderNo()))
{
if(entityAdjustStockOrderProductList != null && !entityAdjustStockOrderProductList.isEmpty())
{
List<EntityAdjustStockOrderProduct> entityAdjustStockOrderProducts = new ArrayList<>();
//for each item, set order no into list
for(int counter = 0; counter < entityAdjustStockOrderProductList.size(); counter++)
{
EntityAdjustStockOrderProduct entityAdjustStockOrderProduct = entityAdjustStockOrderProductList.get(counter);
entityAdjustStockOrderProduct.setOrderNo(entityAdjustStockOrder.getOrderNo());
entityAdjustStockOrderProducts.add(entityAdjustStockOrderProduct);
}
EntityManagerAdjustStockOrderProduct entityManagerAdjustStockOrderProduct = new EntityManagerAdjustStockOrderProduct(this.appId);
List<EntityAdjustStockOrderProduct> resultEntityAdjustStockOrderProducts = entityManagerAdjustStockOrderProduct.addAdjustStockOrderProducts(entityAdjustStockOrderProducts, session);
if(resultEntityAdjustStockOrderProducts == null || resultEntityAdjustStockOrderProducts.isEmpty())
{
tx.rollback();
return null;
}
}
if(entityShowRoomStockList != null && !entityShowRoomStockList.isEmpty())
{
List<EntityShowRoomStock> entityShowRoomStocks = new ArrayList<>();
//for each item, set order no into list
for(int counter = 0; counter < entityShowRoomStockList.size(); counter++)
{
EntityShowRoomStock entityShowRoomStock = entityShowRoomStockList.get(counter);
//entityShowRoomStock.setPurchaseOrderNo(entityPurchaseOrder.getOrderNo());
entityShowRoomStock.setOrderNo(entityAdjustStockOrder.getOrderNo());
entityShowRoomStock.setCreatedOn(currentUnixTime);
entityShowRoomStock.setModifiedOn(currentUnixTime);
entityShowRoomStocks.add(entityShowRoomStock);
}
EntityManagerShowRoomStock entityManagerShowRoomStock = new EntityManagerShowRoomStock(this.appId);
List<EntityShowRoomStock> resultEntityShowRoomStocks = entityManagerShowRoomStock.addShowRoomStocks(entityShowRoomStocks, session);
if(resultEntityShowRoomStocks == null || resultEntityShowRoomStocks.isEmpty())
{
tx.rollback();
return null;
}
}
tx.commit();
return entityAdjustStockOrder;
}
else
{
tx.rollback();
return null;
}
}
finally
{
session.close();
}
}
public boolean updateAdjustStockOrder(EntityAdjustStockOrder entityAdjustStockOrder, Session session)
{
entityAdjustStockOrder.setModifiedOn(TimeUtils.getCurrentTime());
session.update(entityAdjustStockOrder);
return true;
}
public boolean updateAdjustStockOrder(EntityAdjustStockOrder entityAdjustStockOrder)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
return updateAdjustStockOrder(entityAdjustStockOrder, session);
}
finally
{
session.close();
}
}
public boolean updateAdjustStockOrder(EntityAdjustStockOrder currentEntityAdjustStockOrder, EntityAdjustStockOrder entityAdjustStockOrder, List<EntityAdjustStockOrderProduct> entityAdjustStockOrderProductList, List<EntityShowRoomStock> entityShowRoomStockList)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
Transaction tx = session.getTransaction();
tx.begin();
long currentUnixTime = TimeUtils.getCurrentTime();
try
{
if(entityAdjustStockOrder != null && entityAdjustStockOrder.getId() > 0 && updateAdjustStockOrder(entityAdjustStockOrder, session))
{
EntityManagerAdjustStockOrderProduct entityManagerAdjustStockOrderProduct = new EntityManagerAdjustStockOrderProduct(this.appId);
EntityManagerShowRoomStock entityManagerShowRoomStock = new EntityManagerShowRoomStock(this.appId);
//deleting existing products
if(!StringUtils.isNullOrEmpty(currentEntityAdjustStockOrder.getOrderNo()))
{
entityManagerAdjustStockOrderProduct.deleteAdjustStockOrderProductsByOrderNo(currentEntityAdjustStockOrder.getOrderNo(), session);
List<Integer> transactionCategoryIds = new ArrayList<>();
transactionCategoryIds.add(Constants.SS_TRANSACTION_CATEGORY_ID_STOCK_ADJUSTMENT);
entityManagerShowRoomStock.deleteShowRoomProductsBySaleOrderNoAndTransactionCategoryIds(currentEntityAdjustStockOrder.getOrderNo(), transactionCategoryIds, session);
}
if(entityAdjustStockOrderProductList != null && !entityAdjustStockOrderProductList.isEmpty())
{
List<EntityAdjustStockOrderProduct> entityAdjustStockOrderProducts = new ArrayList<>();
//for each item, set order no into list
for(int counter = 0; counter < entityAdjustStockOrderProductList.size(); counter++)
{
EntityAdjustStockOrderProduct entityAdjustStockOrderProduct = entityAdjustStockOrderProductList.get(counter);
entityAdjustStockOrderProduct.setOrderNo(entityAdjustStockOrder.getOrderNo());
entityAdjustStockOrderProducts.add(entityAdjustStockOrderProduct);
}
List<EntityAdjustStockOrderProduct> resultEntityAdjustStockOrderProducts = entityManagerAdjustStockOrderProduct.addAdjustStockOrderProducts(entityAdjustStockOrderProducts, session);
if(resultEntityAdjustStockOrderProducts == null || resultEntityAdjustStockOrderProducts.isEmpty())
{
tx.rollback();
return false;
}
}
if(entityShowRoomStockList != null && !entityShowRoomStockList.isEmpty())
{
List<EntityShowRoomStock> entityShowRoomStocks = new ArrayList<>();
//for each item, set order no into list
for(int counter = 0; counter < entityShowRoomStockList.size(); counter++)
{
EntityShowRoomStock entityShowRoomStock = entityShowRoomStockList.get(counter);
//entityShowRoomStock.setSaleOrderNo(entitySaleOrder.getOrderNo());
entityShowRoomStock.setOrderNo(entityAdjustStockOrder.getOrderNo());
entityShowRoomStock.setCreatedOn(currentUnixTime);
entityShowRoomStock.setModifiedOn(currentUnixTime);
entityShowRoomStocks.add(entityShowRoomStock);
}
List<EntityShowRoomStock> resultEntityShowRoomStocks = entityManagerShowRoomStock.addShowRoomStocks(entityShowRoomStocks, session);
if(resultEntityShowRoomStocks == null || resultEntityShowRoomStocks.isEmpty())
{
tx.rollback();
return false;
}
}
tx.commit();
return true;
}
else
{
tx.rollback();
return false;
}
}
finally
{
session.close();
}
}
public EntityAdjustStockOrder getLastAdjustStockOrder()
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
Query<EntityAdjustStockOrder> query = session.getNamedQuery("getLastAdjustStockeOrder");
query.setMaxResults(1);
List<EntityAdjustStockOrder> adjustStockOrderList = query.getResultList();
if(adjustStockOrderList == null || adjustStockOrderList.isEmpty())
{
return null;
}
else
{
return adjustStockOrderList.get(0);
}
}
finally
{
session.close();
}
}
public EntityAdjustStockOrder getAdjustStockOrderByOrderNo(String orderNo)
{
if(StringUtils.isNullOrEmpty(orderNo))
{
return null;
}
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
Query<EntityAdjustStockOrder> query = session.getNamedQuery("getAdjustStockeOrderByOrderNo");
query.setParameter("orderNo", orderNo);
List<EntityAdjustStockOrder> adjustStockOrderList = query.getResultList();
if(adjustStockOrderList == null || adjustStockOrderList.isEmpty())
{
return null;
}
else
{
return adjustStockOrderList.get(0);
}
}
finally
{
session.close();
}
}
public EntityAdjustStockOrder getAdjustStockOrderById(int id)
{
if(id <= 0)
{
return null;
}
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
Query<EntityAdjustStockOrder> query = session.getNamedQuery("getAdjustStockOrderById");
query.setParameter("id", id);
List<EntityAdjustStockOrder> adjustStockOrderList = query.getResultList();
if(adjustStockOrderList == null || adjustStockOrderList.isEmpty())
{
return null;
}
else
{
return adjustStockOrderList.get(0);
}
}
finally
{
session.close();
}
}
public List<EntityAdjustStockOrder> getAdjustStockOrders(int offset, int limit)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
Query<EntityAdjustStockOrder> query = session.getNamedQuery("getAllAdjustStockeOrders");
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
finally
{
session.close();
}
}
public List<EntityAdjustStockOrder> searchAdjustStockOrdersDQ(String orderNo, long startTime, long endTime, int offset, int limit)
{
Session session = HibernateUtil.getInstance().getSession(this.appId);
try
{
String where = "";
if(!StringUtils.isNullOrEmpty(orderNo))
{
if(StringUtils.isNullOrEmpty(where))
{
where += " where order_no like '%" + orderNo + "%' ";
}
else
{
where += " AND order_no like '%" + orderNo + "%' ";
}
if(startTime > 0)
{
if( StringUtils.isNullOrEmpty(where) )
{
where += " where created_on >= " + startTime ;
}
else
{
where += " AND created_on >= " + startTime ;
}
}
if(endTime > 0)
{
if( StringUtils.isNullOrEmpty(where) )
{
where += " where created_on <= " + endTime ;
}
else
{
where += " AND created_on <= " + endTime ;
}
}
}
Query query = session.createSQLQuery("select {aso.*} from adjust_stock_orders aso " + where + " order by modified_on desc limit :limit offset :offset")
.addEntity("aso",EntityAdjustStockOrder.class)
.setInteger("limit", limit)
.setInteger("offset", offset);
return query.list();
}
finally
{
session.close();
}
}
}
| true
|
e36ce4fec74ecf20b5cc66814ffca13851490fdc
|
Java
|
redusjt/projeto
|
/Sistema_predial/src/service/UsuarioService.java
|
UTF-8
| 1,388
| 2.46875
| 2
|
[] |
no_license
|
package service;
import dao.UsuarioDAO;
import transferObject.UsuarioTO;
public class UsuarioService {
private UsuarioDAO usuarioDAO = new UsuarioDAO();
UsuarioTO usuarioTO;
public boolean cadastrarUsuario(int tipo, String nome, String dataNasc, String endereco, String bairro, long telefone, String senha,
String empresa, String horEntrada, String horSaida, long cpf, boolean permissaoAC) {
UsuarioTO usuarioTO = new UsuarioTO(tipo, nome, dataNasc, endereco, bairro, telefone, senha, empresa, horEntrada, horSaida, cpf, permissaoAC);
if (usuarioDAO.cadastrarUsuario(usuarioTO))
return true;
else
return false;
}
public UsuarioTO consultarUsuario(long cpf) {
usuarioTO = usuarioDAO.consultarUsuario(cpf);
return usuarioTO;
}
public boolean alterarUsuario(int tipo, String nome, String dataNasc, String endereco, String bairro, long telefone, String senha,
String empresa, String horEntrada, String horSaida, long cpf, boolean permissaoAC){
UsuarioTO usuarioTO = new UsuarioTO(tipo, nome, dataNasc, endereco, bairro, telefone, senha, empresa, horEntrada, horSaida, cpf, permissaoAC);
if (usuarioDAO.alterarUsuario(cpf, usuarioTO))
return true;
else
return false;
}
public boolean excluirUsuario(long cpf) {
if (usuarioDAO.excluirUsuario(cpf))
return true;
else
return false;
}
}
| true
|
19cc24b470684e8dac2a4cf60f68eb76437ad6fb
|
Java
|
Momonoazoro/shop
|
/src/main/java/com/lyreco/shop/model/SbLine.java
|
UTF-8
| 729
| 2.59375
| 3
|
[] |
no_license
|
package com.lyreco.shop.model;
import lombok.Builder;
import lombok.Data;
@Data
public class SbLine extends Product {
private int quantity;
private double sellPrice;
@Builder
public SbLine(Long id, String title, String description, double purchasePrice, String category, String brand,
int stock, int quantity, double sellPrice) {
super(id, title, description, purchasePrice, category, brand, stock);
}
@Builder
public SbLine(Product product, int quantity, double sellPrice){
super(product.getId(), product.getTitle(), product.getDescription(), product.getPurchasePrice(),
product.getCategory(), product.getBrand(), product.getStock());
this.quantity = quantity;
this.sellPrice = sellPrice;
}
}
| true
|
78c4af3af8af4e6882b9102334a75f9f547fa0ef
|
Java
|
yersan/pull-request-processor
|
/src/main/java/org/jboss/pull/processor/data/Attributes.java
|
UTF-8
| 1,171
| 1.6875
| 2
|
[] |
no_license
|
package org.jboss.pull.processor.data;
import java.util.List;
import java.util.Map;
public final class Attributes {
public static final Attribute<Boolean> WRITE_PERMISSION = new Attribute<>("write");
public static final Attribute<PullRequestData> PULL_REQUEST= new Attribute<>("pullRequest");
public static final Attribute<List<PullRequestData>> PULL_REQUEST_RELATED= new Attribute<>("pullRequestsRelated");
public static final Attribute<List<IssueData>> ISSUES_RELATED= new Attribute<>("issuesRelated");
public static final Attribute<Map<String, List<LabelData>>> LABELS = new Attribute<>("labels");
public static final Attribute<String> BRANCH = new Attribute<>("branch");
public static final Attribute<List<IssueData>> ISSUES_OTHER_STREAMS = new Attribute<>("issuesOtherStreams");
public static final Attribute<Map<String, Integer>> STATUS = new Attribute<>("status");
public static final Attribute<LinkData> REPOSITORY = new Attribute<>("repository");
public static final Attribute<List<String>> STREAMS = new Attribute<>("streams");
public static final Attribute<List<String>> MESSAGES = new Attribute<>("messages");
}
| true
|
7c0467aa4880a66434080109a26e03a87b3ff7a2
|
Java
|
AdrianoMarra/framework-observable-party-account
|
/project/creditcard/views/GenBillView.java
|
UTF-8
| 2,342
| 2.828125
| 3
|
[] |
no_license
|
package creditcard.views;
/*
A basic implementation of the JDialog class.
*/
import java.awt.*;
import java.util.Date;
import javax.swing.*;
import creditcard.ccard;
import creditcard.models.CreditCardAccount;
import creditcard.models.Person;
public class GenBillView extends javax.swing.JDialog {
private String reportString = "";
// {{DECLARE_CONTROLS
private JScrollPane JScrollPane1 = new JScrollPane();
private JTextArea JTextField1 = new JTextArea();
private JButton JButton_OK = new JButton();
public GenBillView(Frame parent) {
super(parent);
// This code is automatically generated by Visual Cafe when you add
// components to the visual environment. It instantiates and initializes
// the components. To modify the code, only use code syntax that matches
// what Visual Cafe can generate, or Visual Cafe may be unable to back
// parses your Java file into its visual envirenment.
// {{ INIT_CONTROLS
getContentPane().setLayout(null);
setSize(405, 367);
setVisible(false);
getContentPane().add(JScrollPane1);
JScrollPane1.setBounds(24, 24, 758, 240);
JScrollPane1.getViewport().add(JTextField1);
JTextField1.setBounds(0, 0, 755, 237);
JButton_OK.setText("OK");
JButton_OK.setActionCommand("OK");
getContentPane().add(JButton_OK);
JButton_OK.setBounds(296, 276, 196, 24);
for (Person customer : ccard.customersList) {
reportString += "Name = " + customer.getName() + "\n";
reportString += "Address = " + customer.getStreet() + "," + customer.getCity() + "," + customer.getState()
+ "," + customer.getZip() + "\n";
for (CreditCardAccount account : customer.getCreditCardAccountList())
reportString += account.report(new Date()) + "\n";
reportString += "-----------------------------------\n";
}
JTextField1.setText(reportString);
// }}
// {{REGISTER_LISTENERS
SymAction lSymAction = new SymAction();
JButton_OK.addActionListener(lSymAction);
// }}
}
public GenBillView() {
this((Frame) null);
}
// }}
void JButtonOK_actionPerformed(java.awt.event.ActionEvent event) {
dispose();
}
class SymAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object object = event.getSource();
if (object == JButton_OK)
JButtonOK_actionPerformed(event);
}
}
}
| true
|
099c1ee696b0e13e878153553fc4574ca42635c0
|
Java
|
johnnyfivedev/UtilPack
|
/app/src/main/java/com/johnnyfivedev/utilpack/FileManager.java
|
UTF-8
| 17,052
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.johnnyfivedev.utilpack;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.text.format.Formatter;
import android.util.Pair;
import android.webkit.MimeTypeMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.core.os.EnvironmentCompat;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import javax.annotation.Nonnull;
public class FileManager {
private static final String DEFAULT_FILE_NAME_PREFIX = "doctors_handbook";
private static final String TEMP_JPG_FILE_NAME = "temp.jpg";
private final Context context;
public FileManager(Context context) {
this.context = context;
}
// fixme creates only jpg copies
public File createFileCopy(String pathToUploadAvatarFile) {
try {
final File file = new File(context.getCacheDir(), TEMP_JPG_FILE_NAME);
file.createNewFile();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(pathToUploadAvatarFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80 /*ignored for PNG*/, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArray);
fileOutputStream.flush();
fileOutputStream.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean isExternalStorageAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* @return path if has enough required free space,
* else - null
*/
public String getAvailableFolderPath(@NonNull List<Pair<String, Long>> storagesHolder, long requiredFreeSpaceBytes) {
List<File> externalDirs = new ArrayList<>();
File[] files = ContextCompat.getExternalFilesDirs(context, null);
for (File file : files) {
if (file != null && EnvironmentCompat.getStorageState(file).equals(Environment.MEDIA_MOUNTED)) {
long fileFreeSpace = file.getFreeSpace();
storagesHolder.add(Pair.create(file.getAbsolutePath(), fileFreeSpace));
if (fileFreeSpace > requiredFreeSpaceBytes) {
externalDirs.add(file);
}
}
}
if (!externalDirs.isEmpty()) {
File mostFreeExtDir = Collections.max(externalDirs, (o1, o2) -> Long.compare(o1.getFreeSpace(), o2.getFreeSpace()));
return mostFreeExtDir.getAbsolutePath() + "/databases/";
}
File internalDir = context.getFilesDir();
if (internalDir != null) {
long internalDirFreeSpace = internalDir.getFreeSpace();
storagesHolder.add(Pair.create(internalDir.getAbsolutePath(), internalDirFreeSpace));
if (internalDirFreeSpace > requiredFreeSpaceBytes) {
return internalDir.getAbsolutePath() + "/databases/";
}
}
return null;
}
// https://stackoverflow.com/a/31691791/6325722
public String getMimeType(Uri uri) {
String mimeType = null;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver contentResolver = context.getContentResolver();
mimeType = contentResolver.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}
return mimeType;
}
public String getMimeType(@NonNull File file) {
String type = null;
final String url = file.toString();
final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
}
if (type == null) {
type = "*/*";
}
return type;
}
public String getBaseMimeType(@NonNull File file) {
return extractBaseFromMimeType(getMimeType(file));
}
public String extractBaseFromMimeType(String mimeType) {
String baseMimeType = mimeType.split("/")[0];
return baseMimeType + "/*";
}
public String getFileExtension(Uri uri) {
String extension;
//Check uri format to avoid null
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
//If scheme is a content
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
//If scheme is a File
//This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
public String createFileNameWithTimestamp(String prefix, String extension) {
return prefix + System.currentTimeMillis() + "." + extension;
}
public String generateDefaultFileName(String extension) {
return DEFAULT_FILE_NAME_PREFIX + UUID.randomUUID().toString() + "." + extension;
}
public File createFromUri(@NonNull Uri uri) {
return new File(uri.getPath());
}
/**
* @return file length in bytes
*/
public long getFileSizeBytes(@Nullable File file) {
if (file == null) {
return 0;
}
return file.length();
}
public String getFileSizeFormatted(@Nullable File file) {
if (file == null) {
return Formatter.formatFileSize(context, 0);
}
return Formatter.formatFileSize(context, file.length());
}
public String getFileSizeFormatted(long sizeBytes) {
return Formatter.formatFileSize(context, sizeBytes);
}
public File createFileInExternalStorage(String extension) {
return new File(Environment.getExternalStorageDirectory(), generateDefaultFileName(extension));
}
public File createFileInExternalStorage(String namePrefix, String extension) {
return new File(Environment.getExternalStorageDirectory(), createFileNameWithTimestamp(namePrefix, extension));
}
@Nullable
public File createFileInExternalCache(String name, String extension) {
// Этот способ создает в папке cache видимый файл, но приписывает ему сгенерированный постфикс
/* File file = null;
try {
file = File.createTempFile(name + "_", "." + extension, context.getExternalCacheDir());
} catch (IOException e) {
e.printStackTrace();
}
return file;*/
// Этот способ создает в папке cache/*сгенерированное имя* невидимый файл
/*File file = new File(Files.createTempDir(), name + "." + extension);
try {
if (file.createNewFile()) {
return file;
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return file;*/
// Этот способ создает в папке cache видимый файл
File file = new File(context.getExternalCacheDir(), name + "." + extension);
try {
if (file.createNewFile()) {
return file;
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public File createTempFileInCacheDir(@Nonnull Uri fileUri) {
InputStream in = null;
OutputStream out = null;
File result = null;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isVirtualFile(fileUri)) {
in = getInputStreamForVirtualFile(fileUri, "*/*");
} else {
ContentResolver contentResolver = context.getContentResolver();
in = contentResolver.openInputStream(fileUri);
}
File saveDirectory = new File(context.getExternalCacheDir(), "temp");
if (!saveDirectory.exists()) {
saveDirectory.mkdirs();
}
String fileName = fixFileName(getFileName(fileUri));
result = new File(saveDirectory, fileName);
out = new FileOutputStream(result);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public String fixFileName(@Nullable String fileName) {
if (fileName == null) {
return fileName;
}
//remove invalid characters
//private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
//original regexp
//[\/\n\r\t\f\`\?\*\\\<\>\|\":]
String result = fileName.replaceAll("[\\/\\n\\r\\t\\f\\`\\?\\*\\\\\\<\\>\\|\\\":]", "_");
// cut file name to 127 chars or FileInputStream throws FileNotFoundException
int javaCharSize = 2;
int validFileNameLength = 255 / javaCharSize - 1;
if (fileName.length() >= validFileNameLength) {
result = result.substring(0, 255 / javaCharSize - 1);
}
return result;
}
public boolean deleteFile(Uri uri) {
if (uri != null && uri.getPath() != null) {
return new File(uri.getPath()).delete();
}
return false;
}
public boolean deleteFile(File file) {
if (file != null) {
return file.delete();
}
return false;
}
public boolean deleteFile(String filePath) {
if (filePath != null) {
return new File(filePath).delete();
}
return false;
}
// https://stackoverflow.com/a/25005243/6325722
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
public String getFileName(@Nullable File file) {
if (file == null) {
return "";
}
int index = file.getName().lastIndexOf('/');
return file.getName().substring(index + 1);
}
/* public void writeToEndOfFile(String filePath, String content) {
try {
FileWriter fileWriter = new FileWriter(filePath, true);
fileWriter.write("\n" + DateTime.now(TimeZone.getDefault()).format("YYYY-MM-DD hh:mm:ss", Locale.getDefault()) + "\t" + content + "\n");
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}*/
public void clearFile(String filePath) {
try {
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write("");
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isImage(String extension) {
return FileExtensions.Image.containsIgnoreCase(extension);
}
public boolean isFileExists(String fullFilePath) {
File file = new File(fullFilePath);
return file.isFile();
}
public boolean isDirectoryExists(String fullFilePath) {
File file = new File(fullFilePath);
return file.isDirectory();
}
public boolean createDirIfNotExists(String fillDirPath) {
File directory = new File(fillDirPath);
return directory.mkdir();
}
//region ===================== Internal ======================
//https://stackoverflow.com/a/53707346/6325722
@RequiresApi(api = Build.VERSION_CODES.N)
private boolean isVirtualFile(Uri uri) {
if (!DocumentsContract.isDocumentUri(context, uri)) {
return false;
}
Cursor cursor = context.getContentResolver().query(
uri,
new String[]{DocumentsContract.Document.COLUMN_FLAGS},
null, null, null);
int flags = 0;
if (cursor.moveToFirst()) {
flags = cursor.getInt(0);
}
cursor.close();
return (flags & DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT) != 0;
}
private InputStream getInputStreamForVirtualFile(Uri uri, String mimeTypeFilter) throws IOException {
ContentResolver contentResolver = context.getContentResolver();
String[] openableMimeTypes = contentResolver.getStreamTypes(uri, mimeTypeFilter);
if (openableMimeTypes == null || openableMimeTypes.length < 1) {
throw new FileNotFoundException();
}
return contentResolver
.openTypedAssetFileDescriptor(uri, openableMimeTypes[0], null)
.createInputStream();
}
//endregion
public static abstract class FileExtensions {
public enum Image {
JPG("jpg"),
PNG("png"),
BMP("bmp"),
GIF("gif");
String value;
Image(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
public static List<String> asList() {
List<String> list = new ArrayList<>();
for (Image value : values()) {
list.add(value.toString());
}
return list;
}
public static boolean containsIgnoreCase(String extension) {
for (Image value : values()) {
if (value.toString().equalsIgnoreCase(extension)) {
return true;
}
}
return false;
}
}
public static final String TXT = "txt";
}
public static class CreateFileAsyncTask extends AsyncTask<Uri, Void, File> {
private final FileManager fileManager;
private final Callback callback;
public CreateFileAsyncTask(FileManager fileManager, Callback callback) {
this.fileManager = fileManager;
this.callback = callback;
}
@Override
protected File doInBackground(Uri... uris) {
return fileManager.createTempFileInCacheDir(uris[0]);
}
@Override
protected void onPostExecute(File result) {
if (callback != null) {
callback.onResult(result);
}
}
public interface Callback {
void onResult(File file);
}
}
}
| true
|
3cfbc4b943b5994df2fcd080022249799c746e55
|
Java
|
RoboticsTeam4904/standard
|
/commands/motor/MotorBrake.java
|
UTF-8
| 825
| 2.671875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
package org.usfirst.frc4904.standard.commands.motor;
import org.usfirst.frc4904.standard.subsystems.motor.BrakeableMotor;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class MotorBrake extends CommandBase {
protected final BrakeableMotor[] motors;
public MotorBrake(String name, BrakeableMotor... motors) {
super();
setName(name);
this.motors = motors;
for (BrakeableMotor motor : motors) {
motor.setBrakeMode();
if (motor instanceof SubsystemBase) {
addRequirements((SubsystemBase) motor);
}
}
}
public MotorBrake(BrakeableMotor... motors) {
this("MotorBreak", motors);
}
public void execute() {
for (BrakeableMotor motor : motors) {
motor.neutralOutput();
}
}
public boolean isFinished() {
return false;
}
}
| true
|
54a2e5027b4427fd088bfd37b5bbfcdc4ab4ba5d
|
Java
|
ldionmarcil/optimistoolkit
|
/OptimisY3/ServiceManagerWeb/src/main/java/eu/optimis/sm/gui/client/model/ServiceProviderVM.java
|
UTF-8
| 1,524
| 2
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2012 University of Stuttgart
* 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 eu.optimis.sm.gui.client.model;
import java.io.Serializable;
import com.extjs.gxt.ui.client.data.BaseModel;
public class ServiceProviderVM extends BaseModel implements Serializable {
private static final long serialVersionUID = -5793462378870650903L;
public ServiceProviderVM() {
}
public ServiceProviderVM(String vm_id, String vm_type, String vm_status, String vm_deployment_duration_in_ms) {
set("vm_id", vm_id);
set("vm_type", vm_type);
set("vm_status", vm_status);
set("vm_deployment_duration_in_ms", vm_deployment_duration_in_ms);
}
public String getName() {
return (String) get("vm_id");
}
public String toString() {
return new String("<br> vm id = "+get("vm_id")+
"<br> type = "+get("vm_type")+
"<br> status = "+get("vm_status")+
"<br> deployment duration in ms = "+get("vm_deployment_duration_in_ms")
+ "<br>"
);
}
}
| true
|
bf8b2763aee7aecbf2499ca673cf82e545c5212d
|
Java
|
RyanTech/HeartEvaluation
|
/HeartEvaluation/src/cn/skyduck/questionnaire/ICreateQuestionnaireModelFactory.java
|
UTF-8
| 284
| 2.046875
| 2
|
[] |
no_license
|
package cn.skyduck.questionnaire;
import cn.skyduck.questionnaire.model.FullQuestionnaireModel;
/**
* 创建一张问卷(整张 量表)
*
* @author skyduck
*
*/
public interface ICreateQuestionnaireModelFactory {
public FullQuestionnaireModel createQuestionnaireModel();
}
| true
|
84068de2e7ac89f2ea0e2b30bd98c75c5eb9d582
|
Java
|
L3-MIAGE-UJF/L3-Miage_Projet-communication
|
/src/onodes/RMI/Client/ModelRMIClientRemote.java
|
UTF-8
| 729
| 2.359375
| 2
|
[] |
no_license
|
package onodes.RMI.Client;
import java.rmi.Remote;
import java.rmi.RemoteException;
/*
* Besoin de conserver la même architecture de package dans Le serveur comme le client
* afin que les classes puissent être trouvé lors du Naming.lookup()
*/
/**
*
* DO NOT EDIT THIS FILE IT BELONG TO THE FRAMEWORK
* @author groupe1
*
*/
public interface ModelRMIClientRemote extends Remote {
/**
* @return
* @throws RemoteException
*/
public String getInfoClient() throws RemoteException;
/**
* @param methodName
* @param cArgs
* @param oArgs
* @return
* @throws RemoteException
*/
public Object invokeMethodOnControllerAppClient(String methodName,
Class[] cArgs, Object[] oArgs) throws RemoteException;
}
| true
|
49e8fc2c3617723da393d2b072c1434503b70778
|
Java
|
deepexpert-gaohz/sa-d
|
/jnnsBank/risk-api/src/main/java/com/ideatech/ams/risk/model/service/RiskConfigerFieldService.java
|
UTF-8
| 348
| 1.859375
| 2
|
[] |
no_license
|
package com.ideatech.ams.risk.model.service;
import com.ideatech.ams.risk.model.dto.RiskConfigerFieldDto;
import java.util.List;
public interface RiskConfigerFieldService {
List<RiskConfigerFieldDto> findAll();
RiskConfigerFieldDto findByField(String field, String code);
void save(RiskConfigerFieldDto riskConfigerFieldDto);
}
| true
|
9b2250bee392011be63638868b0944edefbd6acb
|
Java
|
patel-kp-github/Practise
|
/src/main/java/com/example/Common/MyAnnotationClass.java
|
UTF-8
| 774
| 2.9375
| 3
|
[] |
no_license
|
package com.example.Common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
public class MyAnnotationClass {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
MyAnnotationClass myanno=new MyAnnotationClass();
Method method = myanno.getClass().getMethod("myMethod");
MyAnnotation m = method.getAnnotation(MyAnnotation.class);
System.out.println(m.value1());
}
@MyAnnotation(value1=10)
public void myMethod(){
System.out.println("inside method myMethod");
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
int value1();
}
| true
|
421b07ae07b62dd9ca58b04ed7833c1bb0ab3142
|
Java
|
anand1104/htmlparserGradle
|
/src/main/java/com/ahoy/parser/dao/MerchantCategoryDao.java
|
UTF-8
| 450
| 1.859375
| 2
|
[] |
no_license
|
package com.ahoy.parser.dao;
import com.ahoy.parser.domain.MerchantCategoryDo;
import com.ahoy.parser.domain.MerchantDo;
import java.util.List;
public interface MerchantCategoryDao {
public MerchantCategoryDo selectByCategoryNameAndMerchant(String catName, MerchantDo merchantDo);
public boolean saveOrUpdate(MerchantCategoryDo merchantCategoryDo);
public List<MerchantCategoryDo> selectByMerchant(MerchantDo merchantDo);
}
| true
|
3f5d71d1f7d19c0c63adfd32bdc653551ac70e45
|
Java
|
njmube/ch.bfh.bti7081.s2017.green
|
/teamgreen-pms-app/src/main/java/ch/bfh/bti7081/s2017/green/domain/builder/AppointmentJournalEntryBuilder.java
|
UTF-8
| 2,820
| 2.671875
| 3
|
[] |
no_license
|
package ch.bfh.bti7081.s2017.green.domain.builder;
import ch.bfh.bti7081.s2017.green.domain.*;
import java.time.LocalDateTime;
/**
* Created by Tobias Joder on 22.05.2017.
*/
public final class AppointmentJournalEntryBuilder implements RundumSorglosBuilder<AppointmentJournalEntryBuilder> {
private Appointment appointment;
private int journalEntryType;
private String text;
private boolean isImportant;
private Person createdBy; // In BaseEntity verschieben
private LocalDateTime createdOn; // In BaseEntity verschieben
private Person modifiedBy; // In BaseEntity verschieben
private LocalDateTime modifiedOn; // In BaseEntity verschieben
private AppointmentJournalEntryBuilder() {
}
public static AppointmentJournalEntryBuilder anAppointmentJournalEntry() {
return new AppointmentJournalEntryBuilder();
}
public AppointmentJournalEntryBuilder withAppointment(Appointment appointment) {
this.appointment = appointment;
return this;
}
public AppointmentJournalEntryBuilder withJournalEntryType(int journalEntryType) {
this.journalEntryType = journalEntryType;
return this;
}
public AppointmentJournalEntryBuilder withText(String text) {
this.text = text;
return this;
}
public AppointmentJournalEntryBuilder withCreatedBy(Person createdBy) {
this.createdBy = createdBy;
return this;
}
public AppointmentJournalEntryBuilder withCreatedOn(LocalDateTime createdOn) {
this.createdOn = createdOn;
return this;
}
public AppointmentJournalEntryBuilder withModifiedBy(Person modifiedBy) {
this.modifiedBy = modifiedBy;
return this;
}
public AppointmentJournalEntryBuilder withModifiedOn(LocalDateTime modifiedOn) {
this.modifiedOn = modifiedOn;
return this;
}
public AppointmentJournalEntryBuilder withIsImportant(boolean isImportant) {
this.isImportant = isImportant;
return this;
}
public AppointmentJournalEntry build() {
AppointmentJournalEntry appointmentJournalEntry = new AppointmentJournalEntry();
appointmentJournalEntry.setAppointment(appointment);
appointmentJournalEntry.setJournalEntryType(journalEntryType);
appointmentJournalEntry.setText(text);
appointmentJournalEntry.setImportant(isImportant);
return appointmentJournalEntry;
}
@Override
public AppointmentJournalEntryBuilder rundumSorglos() {
HealthVisitor hv = HealthVisitorBuilder.aHealthVisitor().rundumSorglos().build();
journalEntryType = 0;
text = "Es geht im gut! Trinkt viel";
createdBy = hv;
createdOn = LocalDateTime.now();
isImportant = true;
return this;
}
}
| true
|
ca82b008c11e453e71ba2c9f82365727f3da3686
|
Java
|
Vincent34/LiveWallPaper
|
/app/src/main/java/test/vc/particles/ParticlesActivity.java
|
UTF-8
| 3,489
| 2.25
| 2
|
[] |
no_license
|
package test.vc.particles;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
/**
* Created by HaoZhe Chen on 2015/4/4.
* The main activity of game AirHockey.
*/
public class ParticlesActivity extends ActionBarActivity {
private GLSurfaceView glSurfaceView;
private boolean rendererSet = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
glSurfaceView = new GLSurfaceView(this);
//Check openGl ES vision.
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportEs2 = configurationInfo.reqGlEsVersion >= 0x20000
|| (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
&& (Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")));
final ParticlesRenderer particlesRenderer = new ParticlesRenderer(this);
if (supportEs2) {
//Request an OpenGL ES 2.0 compatibel context.
glSurfaceView.setEGLContextClientVersion(2);
//Assign render.
glSurfaceView.setRenderer(particlesRenderer);
rendererSet = true;
} else {
Toast.makeText(this, "The Device doesn't support OpenGL ES 2.0", Toast.LENGTH_SHORT).show();
return;
}
glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
float previousX, previousY;
@Override
public boolean onTouch(View view, MotionEvent event) {
if (event != null) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
previousX = event.getX();
previousY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
final float deltaX = event.getX() - previousX;
final float deltaY = event.getY() - previousY;
previousX = event.getX();
previousY = event.getY();
glSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
particlesRenderer.handleTouchDrag(deltaX, deltaY);
}
});
}
return true;
} else {
return false;
}
}
});
setContentView(glSurfaceView);
}
@Override
protected void onPause() {
super.onPause();
if (rendererSet) {
glSurfaceView.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (rendererSet) {
glSurfaceView.onResume();
}
}
}
| true
|
90baf62822d7c3ff2f7dd9616b0382c949c85bb5
|
Java
|
lshain-android-source/tools-idea
|
/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiFileRangePointerImpl.java
|
UTF-8
| 1,684
| 1.976563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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.intellij.psi.impl.smartPointers;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SmartPsiFileRange;
import org.jetbrains.annotations.NotNull;
/**
* User: cdr
*/
class SmartPsiFileRangePointerImpl extends SmartPsiElementPointerImpl<PsiFile> implements SmartPsiFileRange {
SmartPsiFileRangePointerImpl(@NotNull PsiFile containingFile, @NotNull ProperTextRange range) {
super(containingFile, createElementInfo(containingFile, range), PsiFile.class);
}
@NotNull
private static SmartPointerElementInfo createElementInfo(@NotNull PsiFile containingFile, @NotNull ProperTextRange range) {
if (range.equals(containingFile.getTextRange())) return new FileElementInfo(containingFile);
return new SelfElementInfo(containingFile.getProject(), range, PsiElement.class, containingFile, containingFile.getLanguage());
}
@Override
public PsiFile getElement() {
if (getRange() == null) return null; // range is invalid
return getContainingFile();
}
}
| true
|
0bbba21fedafb08d3000933f1a590da5b6a175e5
|
Java
|
atheys/Portfolio
|
/RankStat1/src/logistics/units/DUnit.java
|
UTF-8
| 1,767
| 2.953125
| 3
|
[] |
no_license
|
package logistics.units;
import java.util.ArrayList;
import data.core.structure.GameDay;
import logistics.base.FrontMan;
/**
* Distribution Unit Class.
*
* @author Andreas Theys.
* @version 1.0
*/
public class DUnit {
/**
* Class attributes;
*/
private GameDay gd;
private FrontMan fm;
private ArrayList<AUnit> assets;
/**
* General constructor.
*
* @param gd
* relevant date.
* @param fm
* responsible FrontMan-Object.
*/
public DUnit(GameDay gd, FrontMan fm) {
this.gd = gd;
this.fm = fm;
this.assets = new ArrayList<AUnit>();
}
/**
* General constructor.
*
* @param gd
* relevant date.
* @param fm
* responsible FrontMan-Object.
* @param assets
* responsibility assets.
*/
public DUnit(GameDay gd, FrontMan fm, ArrayList<AUnit> assets) {
this.gd = gd;
this.fm = fm;
this.assets = assets;
}
/**
* GameDay getter.
*
* @return relevant GameDay-Object.
*/
public GameDay getGd() {
return gd;
}
/**
* FrontMan getter.
*
* @return relevant FrontMan-Object.
*/
public FrontMan getFm() {
return fm;
}
/**
* Assets Getter.
*
* @return list of relevant AUnit-Objects.
*/
public ArrayList<AUnit> getAssets() {
return assets;
}
/**
* Assets Setter.
*
* @param assets
* new list of relevant AUnit-Objects.
*/
public void setAssets(ArrayList<AUnit> assets) {
this.assets = assets;
}
/**
* Adds an AUnit asset to the list of assets.
*
* @param a
* AUnit-Object to add.
*/
public void addAsset(AUnit a) {
for (AUnit ass : this.assets) {
if (ass.equals(a)) {
this.assets.remove(ass);
this.assets.add(a);
return;
}
}
this.assets.add(a);
}
}
| true
|
4533a734250fc9e7c49edcda6b3473344818367c
|
Java
|
webservices1930/Eko
|
/EkoSpringServer/src/main/java/co/edu/javeriana/eko/model/MarketPlace.java
|
UTF-8
| 389
| 2.265625
| 2
|
[] |
no_license
|
package co.edu.javeriana.eko.model;
import java.util.List;
public class MarketPlace {
private List<Producto> productos;
public MarketPlace() {}
public MarketPlace(List<Producto> productos) {
this.productos = productos;
}
public List<Producto> getProductos() {
return productos;
}
public void setProductos(List<Producto> productos) {
this.productos = productos;
}
}
| true
|
70b2b4d1ebe017f465cbce59e11630aaa4f28e3a
|
Java
|
RyanFu/cmsserver
|
/test/com/smit/test/sub/SubscribeTest.java
|
UTF-8
| 977
| 2.046875
| 2
|
[] |
no_license
|
package com.smit.test.sub;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import com.smit.web.pubsubhubbub.HubConstraint;
public class SubscribeTest {
/**
* @param args
* @throws IOException
* @throws Exception
*/
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://localhost:8080/pring/subscribe.do");
postMethod.addParameter(HubConstraint.HUB_MODE_PARAM,"subscribe");
postMethod.addParameter(HubConstraint.HUB_TOPIC_PARAM,"http://xinple.org/?feed=rss2&p=385");
postMethod.addParameter(HubConstraint.HUB_VERIFY,"async");
postMethod.addParameter(HubConstraint.HUB_CALLBACK_PARAM,"http://localhost:8080/pring/subcallback.do");
client.executeMethod(postMethod);
System.out.println(postMethod.getStatusCode());
}
}
| true
|
e85d8fb652fa332b6ea15f794bfdb836ac8fe415
|
Java
|
rongalakathyayani/Java_application
|
/UpdateBook.java
|
UTF-8
| 8,739
| 2.625
| 3
|
[] |
no_license
|
package com.book.practice;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ActionEvent;
import javax.swing.LayoutStyle.ComponentPlacement;
public class UpdateBook extends JFrame {
static BooksForm frame;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new BooksForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public void UpdateBook() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 404);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblUpdateBook = new JLabel("Update Book");
lblUpdateBook.setForeground(Color.GRAY);
lblUpdateBook.setFont(new Font("Tahoma", Font.PLAIN, 18));
JLabel lblSerialNo = new JLabel("Serial No:");
JLabel lblBookName = new JLabel("BookName:");
JLabel lblTypeOfBook = new JLabel("TypeOfBook:");
JLabel lblDateOfCollection = new JLabel("DateOfCollection :");
JLabel lblPrice = new JLabel("Price :");
JLabel lblCategory= new JLabel("Category:");
JLabel lblPriority= new JLabel("Priority:");
textField = new JTextField();
textField.setColumns(10);
/*enableEvents(AWTEvent.FOCUS_EVENT_MASK);
textField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
System.out.println("----------------------");
System.out.println(textField.getText());
}
@Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
System.out.println("----------------------");
System.out.println(textField.getText());
}
});*/
System.out.println(textField.getText());
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setColumns(10);
JButton btnUpdateBook = new JButton("UpdateBooks ");
btnUpdateBook.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SerialNo=textField.getText();
String BookName=textField_1.getText();
String TypeOfBook=textField_2.getText();
String DateOfCollection=textField_3.getText();
String Price=textField_4.getText();
String Category=textField_5.getText();
String iPriority=textField_6.getText();
int Priority = Integer.parseInt(iPriority);
int i=UpdateBookDao.save(SerialNo, BookName, TypeOfBook, DateOfCollection, Price, Category, Priority);
if(i>0){
JOptionPane.showMessageDialog(UpdateBook.this,"Books updated successfully!");
BookSuccess.main(new String[]{});
frame.dispose();
}else{
JOptionPane.showMessageDialog(UpdateBook.this,"Sorry, unable to save!");
}
}
});
JButton btnBack = new JButton("Back");
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(150)
.addComponent(lblUpdateBook))
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
.addComponent(lblSerialNo,GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
.addComponent(lblBookName, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
.addComponent(lblTypeOfBook, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
.addComponent(lblDateOfCollection, GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
.addComponent(lblPrice, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addComponent(lblCategory, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addComponent(lblPriority, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE))
.addGap(47)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_3, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_4, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_5, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_6, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE))))
.addContainerGap(125, Short.MAX_VALUE))
.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
.addGap(161)
.addComponent(btnUpdateBook, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE)
.addContainerGap(162, Short.MAX_VALUE))
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap(359, Short.MAX_VALUE)
.addComponent(btnBack)
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblUpdateBook)
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblSerialNo)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblBookName)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblTypeOfBook)
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDateOfCollection)
.addComponent(textField_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblPrice)
.addComponent(textField_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblCategory)
.addComponent(textField_5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblPriority)
.addComponent(textField_6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(30)
.addComponent(lblUpdateBook, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBack)
.addContainerGap(53, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}
| true
|
1819b7d61d71adb8df231a6ef2c0035d7ce95c57
|
Java
|
bellmit/self
|
/yimao/yimao-user/src/main/java/com/yimao/cloud/user/service/RedAccountService.java
|
UTF-8
| 1,173
| 1.789063
| 2
|
[] |
no_license
|
package com.yimao.cloud.user.service;
import com.yimao.cloud.pojo.dto.user.*;
import com.yimao.cloud.pojo.vo.PageVO;
import com.yimao.cloud.user.po.Distributor;
import com.yimao.cloud.user.po.DistributorOrder;
import com.yimao.cloud.user.po.UserDistributorApply;
import java.util.List;
import java.util.Map;
public interface RedAccountService {
/**
* @description 根据新id获取红包账户
* @author Liu Yi
* @date 2019/9/9 13:41
* @param
* @return com.yimao.cloud.pojo.dto.user.RedAccountDTO
*/
RedAccountDTO getRedAccountById(Integer id);
/**
* @description 根据老id获取红包账户
* @author Liu Yi
* @date 2019/9/9 13:41
* @param
* @return com.yimao.cloud.pojo.dto.user.RedAccountDTO
*/
RedAccountDTO getRedAccountByOldId(String oldId);
/**
* @description 根据账户id获取红包账户
* @author Liu Yi
* @date 2019/9/9 13:41
* @param accountId 账户id
* @parama accountType 账户类型
* @return com.yimao.cloud.pojo.dto.user.RedAccountDTO
*/
RedAccountDTO getRedAccountByAccountId(Integer accountId,Integer accountType);
}
| true
|
42ac4c8b3ea57ea6569237633347992304af2e47
|
Java
|
OceanicExchanges/SearchFilter
|
/Preprocessing/src/main/java/main/DocumentCreator.java
|
UTF-8
| 7,942
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package main;
import access.IndexWriteSingleton;
import access.Location;
import access.LocationSingleton;
import de.uni_stuttgart.searchfilter.common.configuration.C;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
abstract class DocumentCreator implements Runnable {
static final Logger logger = Logger.getLogger(
DocumentCreator.class.getName());
final IndexWriter writer;
final Document document;
final StoredField visualizationData;
final StoredField textData;
// Index fields
private final LongPoint idField;
private final IntPoint lengthField;
private final StringField dateField;
private final Field textField;
private final DoublePoint longitudeField;
private final DoublePoint latitudeField;
private final StringField languageField;
private final LongPoint clusterField;
File file;
AtomicInteger counter;
Map<String, Location> locations;
DocumentCreator(File file, AtomicInteger counter) throws IOException {
this.file = file;
this.counter = counter;
this.locations = LocationSingleton.getInstance();
// Setup the fields
idField = new LongPoint(C.FieldNames.ID, 0);
visualizationData = new StoredField(C.FieldNames.VISUALIZATION, "");
textData = new StoredField(C.FieldNames.TEXT_DATA, "");
lengthField = new IntPoint(C.FieldNames.LENGTH, 0);
dateField = new StringField(C.FieldNames.DATE, "", Field.Store.NO);
textField = new TextField(C.FieldNames.TEXT, "", Field.Store.NO);
longitudeField = new DoublePoint(C.FieldNames.LONGITUDE, 0.0);
latitudeField = new DoublePoint(C.FieldNames.LATITUDE, 0.0);
languageField = new StringField(C.FieldNames.LANGUAGE, "", Field.Store.NO);
clusterField = new LongPoint(C.FieldNames.CLUSTER, 0);
document = new Document();
document.add(idField);
document.add(visualizationData);
document.add(textData);
document.add(lengthField);
document.add(dateField);
document.add(textField);
document.add(longitudeField);
document.add(latitudeField);
document.add(languageField);
document.add(clusterField);
writer = IndexWriteSingleton.getInstance();
}
/**
* Add an identification
*
* @param identification String representation of the ID
* @param visualization JSON that contains the visualization data
* @param text JSON that contains the text data
*/
final void addIdentification(String identification, JSONObject visualization,
JSONObject text) {
long id = Long.parseLong(identification);
idField.setLongValue(id);
visualization.put(C.JSONFieldNames.ID, id);
text.put(C.JSONFieldNames.ID, id);
}
/**
* Add length of the text
*
* @param text Full text of the entire document
* @param visualization JSON that contains the visualization data
*/
final void addTextLength(String text, JSONObject visualization) {
int length = text.split("\\s").length;
lengthField.setIntValue(length);
visualization.put(C.JSONFieldNames.TEXT_LENGTH, length);
}
/**
* Add date of the publication
*
* @param date ISO 8601 String representation of the date
* @param visualization JSON that contains the visualization data
* @param text JSON that contains the text data
*/
final void addDate(String date, JSONObject visualization, JSONObject text) {
String[] elements = date.split("-");
switch (elements.length) {
case 1:
date = elements[0] + "-01-01";
break;
case 2:
date = elements[0] + "-" + elements[1] + "-01";
break;
default:
break;
}
dateField.setStringValue(date);
visualization.put(C.JSONFieldNames.DATE, date);
text.put(C.JSONFieldNames.DATE, date);
}
/**
* Add full text
*
* @param text full text
* @param textDocument JSON that contains the text data
*/
final void addText(String text, JSONObject textDocument) {
textField.setStringValue(text);
textDocument.put(C.JSONFieldNames.TEXT, text);
}
/**
* Add publisher
*
* @param publisher publisher string
* @param textDocument JSON that contains the text data
*/
final void addPublisher(String publisher, JSONObject textDocument) {
textDocument.put(C.JSONFieldNames.PUBLISHER, publisher);
}
/**
* Add title
*
* @param title title string
* @param textDocument JSON that contains the text data
*/
final void addTitle(String title, JSONObject textDocument) {
textDocument.put(C.JSONFieldNames.TITLE, title);
}
/**
* Add link
*
* @param link URL of article at library
* @param textDocument JSON that contains the text data
*/
final void addLink(String link, JSONObject textDocument) {
textDocument.put(C.JSONFieldNames.LINK, link);
}
/**
* Add coordinates
*
* @param latitude
* @param longitude
* @param visualization JSON that contains the visualization data
*/
final void addCoordinates(double latitude, double longitude,
JSONObject visualization, JSONObject text) {
text.put(C.JSONFieldNames.LATITUDE, latitude);
text.put(C.JSONFieldNames.LONGITUDE, longitude);
visualization.put(C.JSONFieldNames.LATITUDE, latitude);
visualization.put(C.JSONFieldNames.LONGITUDE, longitude);
latitudeField.setDoubleValue(latitude);
longitudeField.setDoubleValue(longitude);
}
/**
* Add languages
*
* @param language ISO language code
* @param visualization JSON that contains the visualization data
*/
final void addLanguage(String language, JSONObject visualization, JSONObject text) {
text.put(C.JSONFieldNames.LANGUAGE, language);
visualization.put(C.JSONFieldNames.LANGUAGE, language);
languageField.setStringValue(language);
}
/**
* Add cluster ID
*
* @param clusterString
* @param visualization JSON that contains the visualization data
*/
final void addCluster(String clusterString, JSONObject visualization, JSONObject text) {
long cluster = Long.parseLong(clusterString);
text.put(C.JSONFieldNames.CLUSTER, cluster);
visualization.put(C.JSONFieldNames.CLUSTER, cluster);
clusterField.setLongValue(cluster);
}
/**
* Add the place of publication
*
* @param placeOfPublication
* @param text
*/
final void addPlaceOfPublication(String placeOfPublication, JSONObject text) {
text.put(C.JSONFieldNames.PLACE_OF_PUBLICATION, placeOfPublication);
}
final void addCorpus(String corpus, JSONObject visualization, JSONObject text) {
text.put(C.JSONFieldNames.CORPUS, corpus);
visualization.put(C.JSONFieldNames.CORPUS, corpus);
}
/**
* Return the latitude of the given place of publication
*
* @param placeOfPublication
*
* @return latitude
*/
final double getLatitude(String placeOfPublication) {
if (locations.containsKey(placeOfPublication)) {
return locations.get(placeOfPublication).latitude;
}
return -1.0;
}
/**
* Return the longitude of the given place of publication
*
* @param placeOfPublication
*
* @return longitude
*/
final double getLongitude(String placeOfPublication) {
if (locations.containsKey(placeOfPublication)) {
return locations.get(placeOfPublication).longitude;
}
return -1.0;
}
/**
* Set all fields to default values.
*/
final void resetFields() {
idField.setLongValue(0);
visualizationData.setStringValue("");
textData.setStringValue("");
lengthField.setIntValue(0);
dateField.setStringValue("");
textField.setStringValue("");
longitudeField.setDoubleValue(0.0);
latitudeField.setDoubleValue(0.0);
languageField.setStringValue("");
}
}
| true
|
fe41fa9416c84e95eae91328ab9d828c728c2b33
|
Java
|
abhisheksherekar/CRM
|
/CRM-for-online-gadget-repairing-1/src/main/java/com/crm/main/Repo/ServiceProviderReop.java
|
UTF-8
| 435
| 1.8125
| 2
|
[] |
no_license
|
package com.crm.main.Repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.crm.main.Model.ServiceProvider;
@Repository
public interface ServiceProviderReop extends JpaRepository<ServiceProvider, Integer> {
public ServiceProvider findBySpEmailAndSpPasssword(String mailid, String pwd);
public ServiceProvider findBySpEmail(String mailid);
}
| true
|
ff121151ba1489e4ed8ebde8c811ff12f984198d
|
Java
|
tyolab/CommonAndroid
|
/src/main/java/au/com/tyo/android/images/utils/BitmapUtils.java
|
UTF-8
| 12,617
| 2.046875
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2017 TYONLINE TECHNOLOGY PTY. LTD. (TYO Lab)
*/
package au.com.tyo.android.images.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class BitmapUtils {
private static final String LOG_TAG = "BitmapUtils";
public static byte[] bitmapToBytesInPNG(Bitmap bitmap) {
return bitmapToBytes(bitmap, Bitmap.CompressFormat.PNG);
}
/**
*
* @param bitmap
* @param format
* @return
*/
public static byte[] bitmapToBytes(Bitmap bitmap, Bitmap.CompressFormat format) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(format, 100, stream);
byte[] bytes = stream.toByteArray();
return bytes;
}
/**
*
* @param bitmap
* @param photo
* @throws IOException
*/
public static void toJPG(Bitmap bitmap, File photo) throws IOException {
saveTo(bitmap, photo, Bitmap.CompressFormat.JPEG);
}
/**
*
* @param bitmap
* @param photo
* @throws IOException
*/
public static void toPNG(Bitmap bitmap, File photo) throws IOException {
saveTo(bitmap, photo, Bitmap.CompressFormat.PNG);
}
/**
*
* @param bitmap
* @param format
* @return
* @throws IOException
*/
public static String toBase64EncodedString(Bitmap bitmap, Bitmap.CompressFormat format) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
saveTo(bitmap, stream, format);
String encodedString = android.util.Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
stream.close();
return encodedString;
}
/**
*
* @param bitmap
* @param photo
* @param format
* @throws IOException
*/
public static void saveTo(Bitmap bitmap, File photo, Bitmap.CompressFormat format) throws IOException {
OutputStream stream = new FileOutputStream(photo);
saveTo(bitmap, stream, format);
stream.close();
}
public static void saveTo(Bitmap bitmap, OutputStream stream, Bitmap.CompressFormat format) {
saveTo(bitmap, stream, format, 100);
}
/**
* If the format is lossless, such as png, the quality will be ignored
*
* @param bitmap
* @param stream
* @param format
* @param quality
*/
public static void saveTo(Bitmap bitmap, OutputStream stream, Bitmap.CompressFormat format, int quality) {
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bitmap, 0, 0, null);
newBitmap.compress(format, quality, stream);
}
/**
*
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof PictureDrawable) {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(((PictureDrawable) drawable).getPicture());
}
else if (drawable instanceof BitmapDrawable && (bitmap = ((BitmapDrawable) drawable).getBitmap()) != null) {
//
}
if (bitmap == null) {
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
return bitmap;
}
/**
*
* @param urlStr
* @return
*/
public static Bitmap getBitmapFromURL(String urlStr) {
Bitmap bitmap = null;
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = inputStreamToBitmap(input);
} catch (IOException e) {
Log.e(LOG_TAG, "cannot get the image from link :" + urlStr);
}
return bitmap;
}
public static Bitmap getBitmapFromAssets(Context context, String path) throws IOException {
InputStream inputStream = context.getAssets().open(path);
return inputStreamToBitmap(inputStream);
}
public static Bitmap getBitmapFromFile(String path) throws IOException {
return getBitmapFromFile(new File(path));
}
public static Bitmap getBitmapFromFile(File path) throws IOException {
InputStream inputStream = new FileInputStream(((path)));
return inputStreamToBitmap(inputStream);
}
/**
*
* @param bitmap
* @return
*/
public static byte[] bitmapToBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = bitmapToByteArrayOutputStream(bitmap);
byte[] bytes = stream.toByteArray();
try {
stream.close();
}
catch (Exception ex) {
}
return bytes;
}
/**
*
* @param bytes
* @return
*/
public static Bitmap bytesToBitmap(byte[] bytes) {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
/**
*
* @param stream
* @return
*/
public static Bitmap inputStreamToBitmap(InputStream stream) {
return BitmapFactory.decodeStream(stream);
}
/**
* http://stackoverflow.com/questions/8381514/android-converting-color-image-to-grayscale
*
* @param original
* @return
*/
public static Bitmap toGrayscale(Bitmap original) {
/*
similarly
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get one pixel color
pixel = src.getPixel(x, y);
// retrieve color of all channels
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
// take conversion up to one single value
R = G = B = (int)(0.299 * R + 0.587 * G + 0.114 * B);
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
*/
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
return colorFilterIt(original, cm);
}
public static Bitmap colorFilterIt(Bitmap original, ColorMatrix cm) {
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
return colorFilterIt(original, f);
}
public static Bitmap colorFilterIt(Bitmap original, ColorFilter colorFilter) {
int width, height;
height = original.getHeight();
width = original.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height, original.getConfig());
Canvas c = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColorFilter(colorFilter);
c.drawBitmap(original, 0, 0, paint);
return bitmap;
}
public static Bitmap toSepia(Bitmap original) {
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrix colorScale = new ColorMatrix();
colorScale.setScale(1, 1, 0.8f, 1);
cm.postConcat(colorScale);
return colorFilterIt(original, cm);
}
public static Bitmap toBinary(Bitmap original) {
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
float m = 255f;
float t = -255*128f;
ColorMatrix threshold = new ColorMatrix(new float[] {
m, 0, 0, 1, t,
0, m, 0, 1, t,
0, 0, m, 1, t,
0, 0, 0, 1, 0
});
cm.postConcat(threshold);
return colorFilterIt(original, cm);
}
public static Bitmap toInvert(Bitmap original) {
ColorMatrix cm = new ColorMatrix(new float[] {
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0
});
return colorFilterIt(original, cm);
}
public static Bitmap toAlphaBlue(Bitmap original) {
ColorMatrix cm = new ColorMatrix(new float[] {
0, 0, 0, 0, 0,
0.3f, 0, 0, 0, 50,
0, 0, 0, 0, 255,
0.2f, 0.4f, 0.4f, 0, -30
});
return colorFilterIt(original, cm);
}
public static Bitmap toAlphaPink(Bitmap original) {
ColorMatrix cm = new ColorMatrix(new float[] {
0, 0, 0, 0, 255,
0, 0, 0, 0, 0,
0.2f, 0, 0, 0, 50,
0.2f, 0.2f, 0.2f, 0, -20
});
return colorFilterIt(original, cm);
}
public static Bitmap redIt(Bitmap original) {
return colorFilterIt(original, new LightingColorFilter(Color.RED, 0));
}
public static Bitmap blueIt(Bitmap original) {
return colorFilterIt(original, new LightingColorFilter(Color.BLUE, 0));
}
public static Bitmap greenIt(Bitmap original) {
return colorFilterIt(original, new LightingColorFilter(Color.GREEN, 0));
}
public static Bitmap yellowIt(Bitmap original) {
return colorFilterIt(original, new LightingColorFilter(Color.YELLOW, 0));
}
/**
* Convert View to BITMAP
*
* solutions were found here:
* http://stackoverflow.com/questions/2801116/converting-a-view-to-bitmap-without-displaying-it-in-android
*
*/
public static Bitmap getViewBitmapFromCache(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Log.e(LOG_TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
/**
* Alternatively,
* http://stackoverflow.com/questions/5536066/convert-view-to-bitmap-on-android
*
* @param view
* @return
*/
public static Bitmap getViewBitmap(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
public static ByteArrayOutputStream bitmapToByteArrayOutputStream(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream;
}
public static Bitmap scaleBitmap(Bitmap bitmap, float scale) {
int width = Math.round(bitmap.getWidth() * scale);
int height = Math.round(bitmap.getHeight() * scale);
Bitmap target = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.scale(scale, scale);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
return target;
}
}
| true
|
0922c453c7fa179e5ab82c9d3d46fea50e5b1dc8
|
Java
|
BBPL/ardrone
|
/android/src/main/java/com/parrot/ardronetool/video/UsbVideoDownloader.java
|
UTF-8
| 1,808
| 2.578125
| 3
|
[] |
no_license
|
package com.parrot.ardronetool.video;
import java.util.List;
public class UsbVideoDownloader {
private static final String TAG = UsbVideoDownloader.class.getSimpleName();
private UsbVideoDownloadProgressListener listener;
public enum Status {
OK,
FAIL,
PROGRESS,
TIMEOUT,
CANCEL
}
public interface UsbVideoDownloadProgressListener {
void onProgress(Status status, VideoItem videoItem, float f);
}
public static class VideoItem {
public int size;
public String userboxName;
public String videoName;
public boolean equals(Object obj) {
if (!(obj instanceof VideoItem)) {
return false;
}
VideoItem videoItem = (VideoItem) obj;
return this.userboxName.equals(videoItem.userboxName) && this.videoName.equals(videoItem.videoName);
}
}
private final native int deleteItemNative(String str, String str2);
public native int cancelAllDownloads();
public boolean deleteItem(VideoItem videoItem) {
if (videoItem != null) {
return deleteItemNative(videoItem.userboxName, videoItem.videoName) >= 0;
} else {
throw new IllegalArgumentException();
}
}
public native void downloadItem(VideoItem videoItem, String str);
public native List<VideoItem> getMediaItems();
protected void onVideoProgressChanged(VideoItem videoItem, int i, float f) {
if (this.listener != null) {
this.listener.onProgress(Status.values()[i], videoItem, f);
}
}
public void setVideoDownloadProgressListener(UsbVideoDownloadProgressListener usbVideoDownloadProgressListener) {
this.listener = usbVideoDownloadProgressListener;
}
}
| true
|
74818e56a1280fd4f3c5b8da62407c7bacbc11fe
|
Java
|
JDRodriguez8/grupo-pf-5C
|
/hogwarts.java
|
UTF-8
| 3,063
| 2.78125
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
import java.net.*;
public class hogwarts{
static int puertoservidor = 1500;
public static void main(String[] args){
try{
String host = "127.0.0.1";
Socket servidor = new Socket(host, Servidor.puertoservidores);
InputStreamReader isr = new InputStreamReader(servidor.getInputStream());
BufferedReader in = new BufferedReader(isr);
// esta es la instruccion para la salidas del servidor hacia el otro servidor
PrintWriter out = new PrintWriter(servidor.getOutputStream(), true);
ArrayList<String> contactos = new ArrayList<String>();
contactos.add("julia@hogwarts");
contactos.add("hatshepshut8@hogwarts");
contactos.add("papitochulo@hogwarts");
contactos.add("olga.la@hogwarts");
contactos.add("pancha@hogwarts");
String recibo1 = in.readLine();
System.out.println("Servidor: " + recibo1);
String[] ingresomail = recibo1.split(" ");
String comandosend = ingresomail[0];
String comandomail = ingresomail[1];
String contacto = ingresomail[2];
if (Arrays.asList(comandosend).contains("SEND")){
String recibo2 = in.readLine();
System.out.println("Servidor: " + recibo2);
String[] ingresodestino = recibo2.split(" ");
String comandom = ingresodestino[0];
String comandofrom = ingresodestino[1];
String destinatario = ingresodestino[2];
String recibo3 = in.readLine();
System.out.println("Servidor: " + recibo3);
String[] ingresosub = recibo3.split(" ");
String comandomm = ingresosub[0];
String comandosub = ingresosub[1];
String txt = ingresosub[2];
String recibo4 = in.readLine();
System.out.println("Servidor: " + recibo4);
String[] ingresobody = recibo4.split(" ");
String comandommm = ingresobody[0];
String comandobody = ingresobody[1];
String texto = ingresobody[2];
String recibo5 = in.readLine();
System.out.println("Servidor: " + recibo5);
String[] ingresoend = recibo5.split(" ");
String comandoend = ingresoend[0];
String comandos = ingresoend[1];
String m = ingresoend[2];
if ((Arrays.asList(destinatario).contains(null)) || (Arrays.asList(txt).contains(null)) || (Arrays.asList(texto).contains(null))){
if (contactos.contains(contacto)){
out.println("OK SEND MAIL");
}else{
out.println("SEND ERROR 201 " + contacto);
}
}else{
out.println("SEND ERROR 202");
out.println("SEND ERROR 203");
out.println("SEND ERROR 204");
}
}else if(Arrays.asList(comandosend).contains("CHECK")){
if (contactos.contains(contacto)){
out.println("OK NEWCONT " + contacto);
}else{
out.println("CHECK ERROR 205");
}
}
}catch (Exception e){
System.out.println("INVALID COMMAND ERROR");
}
}
}
| true
|
5ba6c9e6e6d700ccc2fc39c8d9d3c716c6c39095
|
Java
|
onelogin/onelogin-java-sdk
|
/src/main/java/com/onelogin/client/api/ApiAuthClaimsApi.java
|
UTF-8
| 31,252
| 1.6875
| 2
|
[] |
no_license
|
/*
* OneLogin API
* OpenAPI Specification for OneLogin
*
* The version of the OpenAPI document: 3.1.1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.onelogin.client.api;
import com.onelogin.client.ApiCallback;
import com.onelogin.client.ApiClient;
import com.onelogin.client.ApiException;
import com.onelogin.client.ApiResponse;
import com.onelogin.client.Configuration;
import com.onelogin.client.Pair;
import com.onelogin.client.ProgressRequestBody;
import com.onelogin.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import com.onelogin.client.model.AltErr;
import com.onelogin.client.model.AuthClaim;
import com.onelogin.client.model.AuthId;
import com.onelogin.client.model.TokenClaim;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class ApiAuthClaimsApi {
private ApiClient localVarApiClient;
private int localHostIndex;
private String localCustomBaseUrl;
public ApiAuthClaimsApi() {
this(Configuration.getDefaultApiClient());
}
public ApiAuthClaimsApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public int getHostIndex() {
return localHostIndex;
}
public void setHostIndex(int hostIndex) {
this.localHostIndex = hostIndex;
}
public String getCustomBaseUrl() {
return localCustomBaseUrl;
}
public void setCustomBaseUrl(String customBaseUrl) {
this.localCustomBaseUrl = customBaseUrl;
}
/**
* Build call for createAuthClaim
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public okhttp3.Call createAuthClaimCall(String apiAuthId, String contentType, AuthClaim authClaim, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = authClaim;
// create path and map variables
String localVarPath = "/api/2/api_authorizations/{api_auth_id}/claims"
.replace("{" + "api_auth_id" + "}", localVarApiClient.escapeString(apiAuthId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentType != null) {
localVarHeaderParams.put("Content-Type", localVarApiClient.parameterToString(contentType));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call createAuthClaimValidateBeforeCall(String apiAuthId, String contentType, AuthClaim authClaim, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'apiAuthId' is set
if (apiAuthId == null) {
throw new ApiException("Missing the required parameter 'apiAuthId' when calling createAuthClaim(Async)");
}
return createAuthClaimCall(apiAuthId, contentType, authClaim, _callback);
}
/**
* Create Api Auth Server Claim
* Create Authorization Claim
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @return Integer
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public Integer createAuthClaim(String apiAuthId, String contentType, AuthClaim authClaim) throws ApiException {
ApiResponse<Integer> localVarResp = createAuthClaimWithHttpInfo(apiAuthId, contentType, authClaim);
return localVarResp.getData();
}
/**
* Create Api Auth Server Claim
* Create Authorization Claim
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @return ApiResponse<Integer>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public ApiResponse<Integer> createAuthClaimWithHttpInfo(String apiAuthId, String contentType, AuthClaim authClaim) throws ApiException {
okhttp3.Call localVarCall = createAuthClaimValidateBeforeCall(apiAuthId, contentType, authClaim, null);
Type localVarReturnType = new TypeToken<Integer>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Create Api Auth Server Claim (asynchronously)
* Create Authorization Claim
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public okhttp3.Call createAuthClaimAsync(String apiAuthId, String contentType, AuthClaim authClaim, final ApiCallback<Integer> _callback) throws ApiException {
okhttp3.Call localVarCall = createAuthClaimValidateBeforeCall(apiAuthId, contentType, authClaim, _callback);
Type localVarReturnType = new TypeToken<Integer>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for deleteAuthClaim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> Success. The claim is deleted. No content is returned. </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteAuthClaimCall(String apiAuthId, Integer claimId, String contentType, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/api/2/api_authorizations/{api_auth_id}/claims/{claim_id}"
.replace("{" + "api_auth_id" + "}", localVarApiClient.escapeString(apiAuthId.toString()))
.replace("{" + "claim_id" + "}", localVarApiClient.escapeString(claimId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentType != null) {
localVarHeaderParams.put("Content-Type", localVarApiClient.parameterToString(contentType));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call deleteAuthClaimValidateBeforeCall(String apiAuthId, Integer claimId, String contentType, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'apiAuthId' is set
if (apiAuthId == null) {
throw new ApiException("Missing the required parameter 'apiAuthId' when calling deleteAuthClaim(Async)");
}
// verify the required parameter 'claimId' is set
if (claimId == null) {
throw new ApiException("Missing the required parameter 'claimId' when calling deleteAuthClaim(Async)");
}
return deleteAuthClaimCall(apiAuthId, claimId, contentType, _callback);
}
/**
* Delete Api Auth Server Claim
* Delete Authorization Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> Success. The claim is deleted. No content is returned. </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public void deleteAuthClaim(String apiAuthId, Integer claimId, String contentType) throws ApiException {
deleteAuthClaimWithHttpInfo(apiAuthId, claimId, contentType);
}
/**
* Delete Api Auth Server Claim
* Delete Authorization Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> Success. The claim is deleted. No content is returned. </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public ApiResponse<Void> deleteAuthClaimWithHttpInfo(String apiAuthId, Integer claimId, String contentType) throws ApiException {
okhttp3.Call localVarCall = deleteAuthClaimValidateBeforeCall(apiAuthId, claimId, contentType, null);
return localVarApiClient.execute(localVarCall);
}
/**
* Delete Api Auth Server Claim (asynchronously)
* Delete Authorization Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> Success. The claim is deleted. No content is returned. </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteAuthClaimAsync(String apiAuthId, Integer claimId, String contentType, final ApiCallback<Void> _callback) throws ApiException {
okhttp3.Call localVarCall = deleteAuthClaimValidateBeforeCall(apiAuthId, claimId, contentType, _callback);
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
/**
* Build call for getAuthclaims
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getAuthclaimsCall(String apiAuthId, String contentType, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/api/2/api_authorizations/{api_auth_id}/claims"
.replace("{" + "api_auth_id" + "}", localVarApiClient.escapeString(apiAuthId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentType != null) {
localVarHeaderParams.put("Content-Type", localVarApiClient.parameterToString(contentType));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getAuthclaimsValidateBeforeCall(String apiAuthId, String contentType, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'apiAuthId' is set
if (apiAuthId == null) {
throw new ApiException("Missing the required parameter 'apiAuthId' when calling getAuthclaims(Async)");
}
return getAuthclaimsCall(apiAuthId, contentType, _callback);
}
/**
* Get Api Auth Server claims
* Get Authorization claims
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @return List<TokenClaim>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public List<TokenClaim> getAuthclaims(String apiAuthId, String contentType) throws ApiException {
ApiResponse<List<TokenClaim>> localVarResp = getAuthclaimsWithHttpInfo(apiAuthId, contentType);
return localVarResp.getData();
}
/**
* Get Api Auth Server claims
* Get Authorization claims
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @return ApiResponse<List<TokenClaim>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<TokenClaim>> getAuthclaimsWithHttpInfo(String apiAuthId, String contentType) throws ApiException {
okhttp3.Call localVarCall = getAuthclaimsValidateBeforeCall(apiAuthId, contentType, null);
Type localVarReturnType = new TypeToken<List<TokenClaim>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Get Api Auth Server claims (asynchronously)
* Get Authorization claims
* @param apiAuthId (required)
* @param contentType (optional, default to application/json)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getAuthclaimsAsync(String apiAuthId, String contentType, final ApiCallback<List<TokenClaim>> _callback) throws ApiException {
okhttp3.Call localVarCall = getAuthclaimsValidateBeforeCall(apiAuthId, contentType, _callback);
Type localVarReturnType = new TypeToken<List<TokenClaim>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for updateClaim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public okhttp3.Call updateClaimCall(String apiAuthId, Integer claimId, String contentType, AuthClaim authClaim, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = authClaim;
// create path and map variables
String localVarPath = "/api/2/api_authorizations/{api_auth_id}/claims/{claim_id}"
.replace("{" + "api_auth_id" + "}", localVarApiClient.escapeString(apiAuthId.toString()))
.replace("{" + "claim_id" + "}", localVarApiClient.escapeString(claimId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentType != null) {
localVarHeaderParams.put("Content-Type", localVarApiClient.parameterToString(contentType));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call updateClaimValidateBeforeCall(String apiAuthId, Integer claimId, String contentType, AuthClaim authClaim, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'apiAuthId' is set
if (apiAuthId == null) {
throw new ApiException("Missing the required parameter 'apiAuthId' when calling updateClaim(Async)");
}
// verify the required parameter 'claimId' is set
if (claimId == null) {
throw new ApiException("Missing the required parameter 'claimId' when calling updateClaim(Async)");
}
return updateClaimCall(apiAuthId, claimId, contentType, authClaim, _callback);
}
/**
* Update Api Auth Server Claim
* Update Authorization Server Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @return AuthId
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public AuthId updateClaim(String apiAuthId, Integer claimId, String contentType, AuthClaim authClaim) throws ApiException {
ApiResponse<AuthId> localVarResp = updateClaimWithHttpInfo(apiAuthId, claimId, contentType, authClaim);
return localVarResp.getData();
}
/**
* Update Api Auth Server Claim
* Update Authorization Server Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @return ApiResponse<AuthId>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public ApiResponse<AuthId> updateClaimWithHttpInfo(String apiAuthId, Integer claimId, String contentType, AuthClaim authClaim) throws ApiException {
okhttp3.Call localVarCall = updateClaimValidateBeforeCall(apiAuthId, claimId, contentType, authClaim, null);
Type localVarReturnType = new TypeToken<AuthId>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Update Api Auth Server Claim (asynchronously)
* Update Authorization Server Claim
* @param apiAuthId (required)
* @param claimId (required)
* @param contentType (optional, default to application/json)
* @param authClaim (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
<tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr>
<tr><td> 404 </td><td> Not Found </td><td> - </td></tr>
<tr><td> 422 </td><td> Unprocessable Entity </td><td> - </td></tr>
</table>
*/
public okhttp3.Call updateClaimAsync(String apiAuthId, Integer claimId, String contentType, AuthClaim authClaim, final ApiCallback<AuthId> _callback) throws ApiException {
okhttp3.Call localVarCall = updateClaimValidateBeforeCall(apiAuthId, claimId, contentType, authClaim, _callback);
Type localVarReturnType = new TypeToken<AuthId>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}
| true
|
e7d6731a1273c90bfcdab8e89e1fea5d825f1919
|
Java
|
newSue/Mobilemdm
|
/src/main/java/com/winchannel/crm/wechat/util/WechatMessageConstant.java
|
UTF-8
| 2,594
| 2.0625
| 2
|
[] |
no_license
|
package com.winchannel.crm.wechat.util;
public class WechatMessageConstant {
/**
* 接收消息的参数
*
* {@code TOUSERNAME} 接收的用户openid {@code FROMUSERNAME} 发送方的openid
* {@code CREATETIME} 微信平台的创建时间 用来排重 {@code MSGTYPE} 发送消息的类型
* {@link com.winchannel.crm.wechat.util.MessageType} {@code MSGID} 消息的id
* {@code CONTENT} 文本消息内容 {@code PICURL} 图片消息中的图片url {@code MEDIAID} 媒体ID
* {@code FORMAT} 语音消息的格式(amr,speex等) {@code THUMBMEDIAID} 缩略图id
* {@code LOCATION_X} 地理位置维度 {@code LOCATION_Y} 地理位置经度 {@code SCALE} 地图缩放大小
* {@code LABEL}地理位置信息 {@code DESCRIPTION} 链接消息描述 {@code URL} 链接消息的url
* {@code TITLE} 链接消息标题
*/
public static final String TOUSERNAME = "ToUserName";
public static final String FROMUSERNAME = "FromUserName";
public static final String CREATETIME = "CreateTime";
public static final String MSGTYPE = "MsgType";
public static final String CONTENT = "Content";
public static final String MSGID = "MsgId";
public static final String PICURL = "PicUrl";
public static final String MEDIAID = "MediaId";
public static final String FORMAT = "Format";
public static final String THUMBMEDIAID = "ThumbMediaId";
public static final String LOCATION_X = "Location_X";
public static final String LOCATION_Y = "Location_Y";
public static final String SCALE = "Scale";
public static final String LABEL = "Label";
public static final String DESCRIPTION = "Description";
public static final String URL = "Url";
public static final String TITLE = "Title";
/**
* {@code EVENT }事件类型 { @link com.winchannel.crm.wechat.util.EventType}
* {@code EVENTKEY } 事件的key 值 {@code TICKET }二维码的ticket {@code LATITUDE } 维度
* {@code LONGITUDE } 经度 {@code PRECISION} 地理位置精度
*/
public static final String EVENT = "Event";
public static final String EVENTKEY = "EventKey";
public static final String TICKET = "Ticket";
public static final String LATITUDE = "Latitude";
public static final String LONGITUDE = "Longitude";
public static final String PRECISION = "Precision";
/**
* 微信平台所需要的链接
*/
/**
* 上传多媒体文件的链接
*/
public static final String UPLOAD_MEDIA_URL="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
}
| true
|
a6e9f69ae5d0cd5be2a8c875b357c2b7ff3b6ab4
|
Java
|
jkratz55/java-sockets-example
|
/src/main/java/io/jkratz/katas/socket/udp/UDPClient.java
|
UTF-8
| 1,187
| 3.09375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package io.jkratz.katas.socket.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient {
private final DatagramSocket socket;
private final InetAddress address;
private final int port;
public UDPClient(InetAddress address, int port) throws SocketException {
this.address = address;
this.port = port;
this.socket = new DatagramSocket();
}
public String sendMessage(String message) throws IOException {
// Convert message to byte array and send to server
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(packet);
// Setup packet for receiving response
byte[] responseBuffer = new byte[256];
DatagramPacket responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length);
socket.receive(responsePacket);
return new String(responsePacket.getData(), 0, responsePacket.getLength());
}
public void close() {
socket.close();
}
}
| true
|
3a441fcce0c62c2b97a95f93ef797805449749d5
|
Java
|
WeCanRun/Sorting-Algorithm
|
/BubbleSort2.java
|
UTF-8
| 1,579
| 3.96875
| 4
|
[] |
no_license
|
package com.wuyi.notecode.sort;
public class BubbleSort2<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int n = nums.length;
boolean isSorted = false;
int low = 0, high = n - 1;
while (low < high && !isSorted) {
isSorted = true;
// 逆向冒泡,大的往下沉
for (int j = low; j < high; j++) {
if (less(nums[j + 1], nums[j])) {
swap(nums, j, j + 1);
isSorted = false;
}
}
high--;
// 正向冒泡,小的往上浮
for (int j = high; j > low; j--) {
if (less(nums[j], nums[j - 1])) {
swap(nums, j, j - 1);
isSorted = false;
}
}
low++;
}
}
public static void main(String[] args) {
BubbleSort2<Integer> sortInt = new BubbleSort2<>();
Integer a[] = {4, 9, 1, 2, 5, 8, 7, 6};
sortInt.sort(a);
System.out.println("最终结果:");
sortInt.display(a);
BubbleSort2<Double> sortDouble = new BubbleSort2<>();
Double b[] = {2.2, 58.3, 6.0, 56.1, 5.1, 93.63};
sortDouble.sort(b);
System.out.println("最终结果:");
sortDouble.display(b);
BubbleSort2<String> sortStr = new BubbleSort2<>();
String s[] = {"d", "f", "D", "r", "U"};
sortStr.sort(s);
System.out.println("最终结果:");
sortStr.display(s);
}
}
| true
|
b25ae3cdf07f237524c07f8ec7c10a69b3196e33
|
Java
|
rpalvair/java-12
|
/src/main/java/com/palvair/java12/SwitchImprovements.java
|
UTF-8
| 359
| 3.34375
| 3
|
[] |
no_license
|
package com.palvair.java12;
import java.time.DayOfWeek;
public class SwitchImprovements {
public String getMessage(final DayOfWeek dayOfWeek) {
return switch (dayOfWeek) {
case MONDAY,TUESDAY,WEDNESDAY, THURSDAY -> "Stay focus";
case FRIDAY -> "It's friday!";
default -> "Life is good!";
};
}
}
| true
|
6ea818ccba6c46113f3b434a4a29c3e1cde7015d
|
Java
|
xeonye/algorithmroad
|
/src/main/java/interview/KNumber.java
|
UTF-8
| 1,200
| 3.65625
| 4
|
[] |
no_license
|
package interview;
/**
* Module Desc:
* 给出一组数据,找出第k个大的数
* 利用快排的思想,时间复杂度是o(n)
* https://blog.csdn.net/orangefly0214/article/details/86527462
* User: empcl
* DateTime: 2019/8/5 13:02
*/
public class KNumber {
private static int findKNumber(int[] a,int k,int start,int end) {
int pivot = getPivotIndex(a,start,end);
if (pivot == k - 1) {
return a[pivot];
} else if (pivot > (k - 1)) {
return findKNumber(a,k,start,pivot - 1);
} else
return findKNumber(a,k,pivot + 1,end);
}
private static int getPivotIndex(int[] a,int start,int end) {
int tmp = a[start];
while (start < end) {
while (start < end && a[end] <= tmp)
end--;
a[start] = a[end];
while (start < end && a[start] >= tmp)
start++;
a[end] = a[start];
}
a[start] = tmp; // 当前位置start是pivot应该在的位置。
return start;
}
public static void main(String[] args) {
int[] a = {5,2,3,4,4,1,2};
System.out.println(findKNumber(a,4,0,4));
}
}
| true
|
4170130dbc13984ae522620baf7293da55906810
|
Java
|
shannu95/NotownMusicalRecords
|
/database_project/Connection_DB.java
|
UTF-8
| 793
| 2.546875
| 3
|
[] |
no_license
|
package database_project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Connection_DB {
private static Connection con;
public static Connection DBCon() throws SQLException {
if(con==null){
try {
String DB="jdbc:oracle:thin:@localhost:1521:orcl";
String user="hr";
String pass="hr";
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = (Connection) DriverManager.getConnection(DB,user,pass);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Connection has not been established");
}
}
return con;
}
}
| true
|
58e2e1c59026a4ed5414c1d5a4e649a944a4af68
|
Java
|
TheShinyBunny/DPScript
|
/src/com/shinysponge/dpscript/pawser/VariableType.java
|
UTF-8
| 1,708
| 2.5
| 2
|
[] |
no_license
|
package com.shinysponge.dpscript.pawser;
import com.shinysponge.dpscript.oop.ClassInstance;
import com.shinysponge.dpscript.oop.LazyValue;
import com.shinysponge.dpscript.pawser.parsers.SelectorParser;
import com.shinysponge.dpscript.pawser.score.LazyScoreValue;
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
public enum VariableType {
SELECTOR(Selector.class, LazyValue.toLazyConsumer(SelectorParser::parseSelectorCommand)),
INTEGER(Integer.class, (i,n)-> Collections.singletonList(SelectorParser.parseScoreOperators(Parser.getScoreAccess(n)))),
ENUM(Enum.class),
STRING(String.class),
SCORE(LazyScoreValue.class),
OBJECT(ClassInstance.class);
private Class<?> valueType;
private BiFunction<LazyValue<?>, String, List<String>> accessParser;
<T> VariableType(Class<T> valueType, Function<LazyValue<T>, List<String>> accessParser) {
this.valueType = valueType;
this.accessParser = (l,n)->accessParser.apply((LazyValue<T>) l);
}
<T> VariableType(Class<T> valueType, BiFunction<LazyValue<T>, String, List<String>> accessParser) {
this.valueType = valueType;
this.accessParser = (l,n)->accessParser.apply((LazyValue<T>)l,n);
}
VariableType(Class<?> valueType) {
this.valueType = valueType;
}
public BiFunction<LazyValue<?>, String, List<String>> getAccessParser() {
return accessParser;
}
public static VariableType get(Object value) {
for (VariableType t : values()) {
if (t.valueType.isInstance(value)) {
return t;
}
}
return null;
}
}
| true
|
6b6d31a9c37d2abb6dd34f96967f604ea138fb9a
|
Java
|
anandrajak/Urika_GAAS_Automation
|
/src/main/java/com/yarcdata/tests/automation/libraries/common/SuiteConstants.java
|
UTF-8
| 4,028
| 2.03125
| 2
|
[] |
no_license
|
/**
* Copyright 2013 YarcData LLC All Rights Reserved.
*/
package com.yarcdata.tests.automation.libraries.common;
/**
* <p>
* SuiteConstants - To perform functionalities before and after each test class execution
* </p>
* @author Venkatachalam
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class SuiteConstants {
protected FunctionsLibrary FunctionsLibrary = new FunctionsLibrary ();
String sPOMXML = System.getProperty ("user.dir") + "/pom.xml";
// String sDataFile = FunctionsLibrary.functionReadXMLData(sPOMXML, "project.datalibrary");
protected static String seleniumPropertyFile;
protected static String seleniumInputFile;
protected static String dataInputFile;
protected static String ruleInputFile;
protected static String rawrdfInputfile;
protected static String CopyRawRdf;
protected static String sBrowserType;
protected static String sUrikaMachine;
protected static String sUsername;
protected static String sPassword;
public static String managedatasheetname;
public static String adddatatableurl;
public static String urlNegativescenarios;
public static String adddatatablelocalfile;
public static String localFilenegativescenarios;
public static String adddeletedatatablelocalfile;
public static String adddatatableRawRDF;
public static String rawRDFnegativescenarios;
public static String cancelAdddatatablelocalfile;
public static String twouseradddatatable;
public static String hugefiledata;
public static String cancelAdddatatableRawRdf;
public static String twouseraddtablerawrdf;
public static String manageRulesSheetName;
public static String deleteall;
public static String addRuleFileTable;
public static String ruleFileNegativeCases;
public static String deleteRuleFile;
public static String nonDeleteRule;
public static String ruleNameSearch;
public static void loadproperties() throws FileNotFoundException, IOException{
Properties props = new Properties();
seleniumPropertyFile = System.getProperty("selenium.properties");
seleniumInputFile = System.getProperty("selenium.input.file.location");
dataInputFile = System.getProperty("dataset.file.location");
ruleInputFile = System.getProperty("ruleset.file.location");
rawrdfInputfile = System.getProperty("rawrdfinputfile.location");
props.load(new FileInputStream(seleniumPropertyFile));
sBrowserType = props.getProperty("urika.browser");
sUrikaMachine = props.getProperty("urika.url");
sUsername = props.getProperty("urika.username");
sPassword = props.getProperty("urika.password");
//Manage data Sheet input
managedatasheetname = props.getProperty("excel.Managedata");
//Add Url Table Names
adddatatableurl = props.getProperty("excel.AdddatatableURL");
urlNegativescenarios = props.getProperty("excel.URLNegativescenarios");
//Add Local File Table Names
adddatatablelocalfile = props.getProperty("excel.Adddatatable_localfile");
localFilenegativescenarios = props.getProperty("excel.LocalFile_Negativescenarios");
twouseradddatatable = props.getProperty("excel.TwouserAdddatatable");
//Add RawRdf Table Names
adddatatableRawRDF = props.getProperty("excel.Adddatatable_RawRDF");
rawRDFnegativescenarios = props.getProperty("excel.RawRDF_Negativescenarios");
twouseraddtablerawrdf=props.getProperty("excel.TwouserAdddatatableRawRDF");
//Manage Rules Sheet Input
manageRulesSheetName = props.getProperty("excel.ManageRules");
//Add Rules Table Names
deleteall = props.getProperty("excel.deleteall");
addRuleFileTable = props.getProperty("excel.AddRuleFileTable");
ruleFileNegativeCases = props.getProperty("excel.RuleFile_NegativeCases");
deleteRuleFile = props.getProperty("excel.deleteRule");
nonDeleteRule = props.getProperty("excel.nonDeleteRule");
ruleNameSearch = props.getProperty("excel.ruleNameSearch");
}
}
| true
|
b5a9a46ade2965ddf243384a490f60873f9478d2
|
Java
|
MathieuPichon/INSA-miniproject-Tower-Defense
|
/TowerDefense.java
|
UTF-8
| 1,505
| 3.4375
| 3
|
[] |
no_license
|
public class TowerDefense {
Square goal = new Square(9,9);
Square [][] mainGrid = new Square[10][10];
public TowerDefense() {
//initialise the grid with all the squares
//we need it to attribute the neighborgs later
for(int i = 0; i<10; i++){
for(int j = 0; j<10; j++){
mainGrid[i][j] = new Square(i,j);
}
}
//attributing neighbors
for(int i = 0; i<10; i++){
for(int j = 0; j<10; j++){
if(i-1>=0) {
mainGrid[i][j].neighbors[0] = mainGrid[i-1][j];
}
if(i+1<=9) {
mainGrid[i][j].neighbors[2] = mainGrid[i+1][j];
}
if(j-1>=0) {
mainGrid[i][j].neighbors[3] = mainGrid[i][j-1];
}
if(j+1<=9) {
mainGrid[i][j].neighbors[1] = mainGrid[i][j+1];
}
}
}
}
public static void main(String[] args) {
TowerDefense towerDefense = new TowerDefense();
Square goal = towerDefense.getMainGrid(9,9);
Square start = towerDefense.getMainGrid(0,0);
Enemy Thomas = new Enemy();
System.out.println(Thomas.findPath( start, goal));
}
public Square getMainGrid (int i, int j) {
return mainGrid[i][j];
}
}
| true
|
0fd76c2c740220fc8437a1c1661810d916c71203
|
Java
|
kingz10102/finalproject
|
/src/main/java/com/example/finalproject/controller/SneakerController.java
|
UTF-8
| 843
| 2.171875
| 2
|
[] |
no_license
|
package com.example.finalproject.controller;
import com.example.finalproject.models.Sneakers;
import com.example.finalproject.service.SneakerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/sneakers")
public class SneakerController {
@Autowired
SneakerService sneakerService;
@GetMapping
public Iterable<Sneakers> findAll() {
return sneakerService.listSneakers();
}
@GetMapping("/{title}")
public Sneakers getSneakers(@PathVariable String title) {
return sneakerService.getSneakers(title);
}
//to receive a specific post
@PostMapping
public Sneakers createSneakers(@RequestBody Sneakers newSneakers) {
return sneakerService.createSneakers(newSneakers);
}
}
| true
|
cb5c7e8d749c094f5880544ff3d450001e498d89
|
Java
|
Creators-of-Create/Create
|
/src/main/java/com/simibubi/create/foundation/gui/CustomLightingSettings.java
|
UTF-8
| 1,909
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package com.simibubi.create.foundation.gui;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
public class CustomLightingSettings implements ILightingSettings {
private Vector3f light1;
private Vector3f light2;
private Matrix4f lightMatrix;
protected CustomLightingSettings(float yRot, float xRot) {
init(yRot, xRot, 0, 0, false);
}
protected CustomLightingSettings(float yRot1, float xRot1, float yRot2, float xRot2) {
init(yRot1, xRot1, yRot2, xRot2, true);
}
protected void init(float yRot1, float xRot1, float yRot2, float xRot2, boolean doubleLight) {
light1 = Vector3f.ZP.copy();
light1.transform(Vector3f.YP.rotationDegrees(yRot1));
light1.transform(Vector3f.XN.rotationDegrees(xRot1));
if (doubleLight) {
light2 = Vector3f.ZP.copy();
light2.transform(Vector3f.YP.rotationDegrees(yRot2));
light2.transform(Vector3f.XN.rotationDegrees(xRot2));
} else {
light2 = Vector3f.ZERO;
}
lightMatrix = new Matrix4f();
lightMatrix.setIdentity();
}
@Override
public void applyLighting() {
RenderSystem.setupLevelDiffuseLighting(light1, light2, lightMatrix);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private float yRot1, xRot1;
private float yRot2, xRot2;
private boolean doubleLight;
public Builder firstLightRotation(float yRot, float xRot) {
yRot1 = yRot;
xRot1 = xRot;
return this;
}
public Builder secondLightRotation(float yRot, float xRot) {
yRot2 = yRot;
xRot2 = xRot;
doubleLight = true;
return this;
}
public Builder doubleLight() {
doubleLight = true;
return this;
}
public CustomLightingSettings build() {
if (doubleLight) {
return new CustomLightingSettings(yRot1, xRot1, yRot2, xRot2);
} else {
return new CustomLightingSettings(yRot1, xRot1);
}
}
}
}
| true
|
8ab373ace289c726c886df21d9a0884809bb3993
|
Java
|
P79N6A/icse_20_user_study
|
/methods/Method_9253.java
|
UTF-8
| 2,043
| 1.953125
| 2
|
[] |
no_license
|
private void updateHint(){
if (!isAlwaysShare && !isNeverShare && !addToGroup) {
if (chatType == ChatObject.CHAT_TYPE_CHANNEL) {
actionBar.setSubtitle(LocaleController.formatPluralString("Members",selectedContacts.size()));
}
else {
if (selectedContacts.size() == 0) {
actionBar.setSubtitle(LocaleController.formatString("MembersCountZero",R.string.MembersCountZero,LocaleController.formatPluralString("Members",maxCount)));
}
else {
actionBar.setSubtitle(LocaleController.formatString("MembersCount",R.string.MembersCount,selectedContacts.size(),maxCount));
}
}
}
if (chatType != ChatObject.CHAT_TYPE_CHANNEL) {
if (doneButtonVisible && allSpans.isEmpty()) {
if (currentDoneButtonAnimation != null) {
currentDoneButtonAnimation.cancel();
}
currentDoneButtonAnimation=new AnimatorSet();
currentDoneButtonAnimation.playTogether(ObjectAnimator.ofFloat(floatingButton,"scaleX",0.0f),ObjectAnimator.ofFloat(floatingButton,"scaleY",0.0f),ObjectAnimator.ofFloat(floatingButton,"alpha",0.0f));
currentDoneButtonAnimation.addListener(new AnimatorListenerAdapter(){
@Override public void onAnimationEnd( Animator animation){
floatingButton.setVisibility(View.INVISIBLE);
}
}
);
currentDoneButtonAnimation.setDuration(180);
currentDoneButtonAnimation.start();
doneButtonVisible=false;
}
else if (!doneButtonVisible && !allSpans.isEmpty()) {
if (currentDoneButtonAnimation != null) {
currentDoneButtonAnimation.cancel();
}
currentDoneButtonAnimation=new AnimatorSet();
floatingButton.setVisibility(View.VISIBLE);
currentDoneButtonAnimation.playTogether(ObjectAnimator.ofFloat(floatingButton,"scaleX",1.0f),ObjectAnimator.ofFloat(floatingButton,"scaleY",1.0f),ObjectAnimator.ofFloat(floatingButton,"alpha",1.0f));
currentDoneButtonAnimation.setDuration(180);
currentDoneButtonAnimation.start();
doneButtonVisible=true;
}
}
}
| true
|
9296feb28bd97e111622927dcab7577abed712b4
|
Java
|
spoto/WTSC-2020
|
/experiments/white_listed_fragment/io/takamaka/code/whitelisting/internal/database/java/util/function/IntUnaryOperator.java
|
UTF-8
| 373
| 2.40625
| 2
|
[] |
no_license
|
package io.takamaka.code.whitelisting.internal.database.java.util.function;
public interface IntUnaryOperator {
int applyAsInt(int operand);
java.util.function.IntUnaryOperator compose(java.util.function.IntUnaryOperator before);
java.util.function.IntUnaryOperator andThen(java.util.function.IntUnaryOperator before);
java.util.function.IntUnaryOperator identity();
}
| true
|
b19eb14f2df64eac82773d96840b6101cdec717a
|
Java
|
bellmit/cdx
|
/labor-cultural-palace/src/main/java/com/inspur/vista/labor/cp/entity/QuartzJobAdd.java
|
UTF-8
| 2,613
| 2.09375
| 2
|
[] |
no_license
|
package com.inspur.vista.labor.cp.entity;
import java.util.List;
import java.util.Map;
/**
* @Title: QuartzJob
* @Description: //TODO
* @Author: gengpeng
* @CreateDate: 2020/1/6 11:35
* @Version: 1.0
*/
public class QuartzJobAdd {
/**
* 任务名称
*/
private String jobName;
/**
* 任务分组
*/
private String jobGroup;
/**
* 任务描述
*/
private String description;
/**
* 执行类包名类名
*/
private String jobClassName;
/**
* 执行时间的cron表达式
*/
private String cronExpression;
/**
* 任务名称 用于修改
*/
private String oldJobName;
/**
* 任务分组 用于修改
*/
private String oldJobGroup;
private List<Map<String, Object>> jobDataParam;
public QuartzJobAdd() {
super();
}
public QuartzJobAdd(String jobName, String jobGroup, String description, String jobClassName, String cronExpression) {
super();
this.jobName = jobName;
this.jobGroup = jobGroup;
this.description = description;
this.jobClassName = jobClassName;
this.cronExpression = cronExpression;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobGroup() {
return jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getJobClassName() {
return jobClassName;
}
public void setJobClassName(String jobClassName) {
this.jobClassName = jobClassName;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getOldJobName() {
return oldJobName;
}
public void setOldJobName(String oldJobName) {
this.oldJobName = oldJobName;
}
public String getOldJobGroup() {
return oldJobGroup;
}
public void setOldJobGroup(String oldJobGroup) {
this.oldJobGroup = oldJobGroup;
}
public List<Map<String, Object>> getJobDataParam() {
return jobDataParam;
}
public void setJobDataParam(List<Map<String, Object>> jobDataParam) {
this.jobDataParam = jobDataParam;
}
}
| true
|
a86a65ab5c5f730788da7dc61e6134445e2731e6
|
Java
|
RyanJaJa/Game
|
/src/main/java/com/exce/model/parameter/BetItem.java
|
UTF-8
| 223
| 2.03125
| 2
|
[] |
no_license
|
package com.exce.model.parameter;
import java.io.Serializable;
public enum BetItem implements Serializable {
ZERO, CHAMPION, SECOND, THIRD, FOURTH, FIFTH, SIXTH, SEVENTH, EIGHT, NINTH, TENTH, CHAMPION_SECOND
}
| true
|
8dfa9446b1b0fedf5ab795b269467097a8dbc434
|
Java
|
AnupriyaG/Freight-Management-System-Spring-Boot
|
/src/main/java/edu/njit/fms/utils/ReportUtils.java
|
UTF-8
| 10,013
| 2.515625
| 3
|
[] |
no_license
|
package edu.njit.fms.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import edu.njit.fms.db.entity.CdpProjects;
import edu.njit.fms.db.entity.CustomProject;
import edu.njit.fms.db.repository.FmsStipRepository;
/**
* This class is responsible for generating data required when building a CrystalReport
* @author Karthik Sankaran
* @version February 2020
*/
public class ReportUtils {
private final static Logger logger = Logger.getLogger(ReportUtils.class);
/**
* Generates an image using ArcGIS
* @param cdpProject The CDP project, used to determine extent and highlighting
* @param fmsStipRepository A reference to the FMS STIP table
* @return A string containing the URL of the generated image
* @throws ClientProtocolException
* @throws IOException
* @throws JSONException
*/
public static String generateReportGISImage(CdpProjects cdpProject, FmsStipRepository fmsStipRepository)
throws ClientProtocolException, IOException, JSONException {
CustomProject cp = new CustomProject(cdpProject.getDbnum(), cdpProject.getSri(), cdpProject.getMpStart(), cdpProject.getMpEnd(), 0);
List<CustomProject> cdpl = new ArrayList<>();
cdpl.add(cp);
return generateReportGISImage(cdpl, fmsStipRepository);
}
/**
* Generates an image using ArcGIS
* @param routesList A list of routes/StartMP/endMP data
* @param fmsStipRepository A reference to the FMS STIP table
* @return A string containing the URL of the generated image
* @throws ClientProtocolException
* @throws IOException
* @throws JSONException
*/
public static String generateReportGISImage(List<CustomProject> routesList, FmsStipRepository fmsStipRepository)
throws ClientProtocolException, IOException, JSONException {
double finalMinX = -300, finalMinY = -300, finalMaxX = 300, finalMaxY = 300; //init with max/min values
for (CustomProject c : routesList) {
List<Object[]> bbdata = fmsStipRepository.getLatLngFromSRIandMP(c.getSri().substring(0,9) + "%", c.getMpStart() + "", c.getMpEnd() + "");
for (Object[] bb : bbdata) {
String BLAT = ((BigDecimal) bb[0]).toString();
String BLONG = ((BigDecimal) bb[1]).toString();
double X,Y;
//Logger.getLogger("ReportImage").info(BLAT+ " , " +BLONG);
if (BLAT==null||BLONG==null) {
Logger.getLogger("ReportImage").info("No Data found");
X=0;Y=0;
} else {
//Logger.getLogger("ReportImage").info("DBNUM found");
X = Double.parseDouble(BLONG);
Y = Double.parseDouble(BLAT);
}
if (X > finalMinX) finalMinX = X;
if (Y > finalMinY) finalMinY = Y;
if (X < finalMaxX) finalMaxX = X;
if (Y < finalMaxY) finalMaxY = Y;
}
}
/* if (bbdata.size()>1) {
finalMinX+=0.01;
finalMaxX-=0.01;
finalMinY+=0.01;
finalMaxY-=0.01;
} else {
finalMinX=((BigDecimal) bbdata.get(0)[1]).doubleValue();//Double.parseDouble((String) bbdata.get(0)[1]);
finalMaxX=((BigDecimal) bbdata.get(0)[1]).doubleValue();//Double.parseDouble((String) bbdata.get(0)[1]);
finalMinY=((BigDecimal) bbdata.get(0)[0]).doubleValue();//Double.parseDouble((String) bbdata.get(0)[0]);
finalMaxY=((BigDecimal) bbdata.get(0)[0]).doubleValue();//Double.parseDouble((String) bbdata.get(0)[0]);
finalMinX+=0.01;
finalMaxX-=0.01;
finalMinY+=0.01;
finalMaxY-=0.01;
} */
if (finalMinX == finalMaxX && finalMinY == finalMaxY) {
finalMinX+=0.01;
finalMaxX-=0.01;
finalMinY+=0.01;
finalMaxY-=0.01;
}
System.out.println("MinX:" + finalMinX + ",maxX:" + finalMaxX + ",minY:" + finalMinY + ",maxY:" + finalMaxY);
System.out.println("X Diff: " + (finalMaxX - finalMinX));
System.out.println("Y Diff: " + (finalMaxY - finalMinY));
if (finalMinY - finalMaxY < 0.002) finalMinY += 0.001;
String serviceData = generateArcGISImageRequestPOSTData(routesList, finalMaxX, finalMaxY, finalMinX, finalMinY);
String url = "http://transprod05.njit.edu:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task/execute";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
String USER_AGENT = "Mozilla/5.0";
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("Format", "PNG32"));
urlParameters.add(new BasicNameValuePair("returnZ", "false"));
urlParameters.add(new BasicNameValuePair("returnM", "false"));
urlParameters.add(new BasicNameValuePair("f", "JSON"));
urlParameters.add(new BasicNameValuePair("Web_Map_as_JSON", serviceData));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
JSONObject resultData = new JSONObject(result.toString());
String imgURL = "";
if (resultData.has("results")) {
JSONObject resultsObj = resultData.getJSONArray("results").getJSONObject(0);
imgURL = resultsObj.getJSONObject("value").getString("url");
}
return imgURL;
}
/**
* Creates the POST data that must be sent to ArcGIS to generate the image
* @param routesList List of customProjects to highlight
* @param maxX Extent
* @param maxY Extent
* @param minX Extent
* @param minY Extent
* @return The POST data to be sent to ArcGIS
*/
private static String generateArcGISImageRequestPOSTData(List<CustomProject> routesList, double maxX,
double maxY, double minX, double minY) {
//lets build the definition expression
List<String> defExpParts = new ArrayList<>();
for (CustomProject c : routesList) defExpParts.add("(SRI LIKE '"+c.getSri().substring(0,9)+"%' AND MP_START >= "+c.getMpStart()+" AND MP_END <= "+c.getMpEnd()+")");
String defExpr = defExpParts.stream().collect(Collectors.joining(" OR "));
logger.info("Generating ARCGIS Request");
String request = "{" +
"\"mapOptions\":{" +
"\"extent\":{" +
"\"xmin\":"+maxX+"," +
"\"ymin\":"+maxY+"," +
"\"xmax\":"+minX+"," +
"\"ymax\":"+minY+"," +
"\"spatialReference\":{" +
"\"wkid\":4326" +
"}" +
"}" +
"}," +
"\"operationalLayers\":[" +
"{" +
"\"url\":\"http://transprod05.njit.edu:6080/arcgis/rest/services/FMS/FMS_NJ_Roadway_New/MapServer/0\"," +
"\"layerDefinition\":{" +
"\"definitionExpression\":\""+defExpr+"\"," +
"\"drawingInfo\":{\"renderer\":{\"type\":\"simple\",\"symbol\":{\"type\":\"esriSLS\",\"color\":[230,0,0,255],\"width\":2,\"style\":\"esriSLSSolid\"}}}" +
"}" +
"}," +
"{" +
"\"url\":\"http://transprod05.njit.edu:6080/arcgis/rest/services/FMS/FMS_NJ_Roadway_New/MapServer/1\"," +
"\"layerDefinition\":{" +
"\"definitionExpression\":\""+defExpr+"\"," +
"\"drawingInfo\":{\"renderer\":{\"type\":\"simple\",\"symbol\":{\"type\":\"esriSLS\",\"color\":[230,0,0,255],\"width\":2,\"style\":\"esriSLSSolid\"}}}" +
"}" +
"}," +
"{" +
"\"url\":\"http://transprod05.njit.edu:6080/arcgis/rest/services/FMS/FMS_NJ_Roadway_New/MapServer/2\"," +
"\"layerDefinition\":{" +
"\"definitionExpression\":\""+defExpr+"\"," +
"\"drawingInfo\":{\"renderer\":{\"type\":\"simple\",\"symbol\":{\"type\":\"esriSLS\",\"color\":[230,0,0,255],\"width\":2,\"style\":\"esriSLSSolid\"}}}" +
"}" +
"}" +
"]," +
"\"baseMap\":{" +
"\"title\":\"Topographic Basemap\"," +
"\"baseMapLayers\":[" +
"{" +
"\"url\":\"https://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer\"" +
"}" +
"]" +
"}," +
"\"exportOptions\":{" +
"\"outputSize\":[" +
"800," +
"700" +
"]" +
"}" +
"}";
logger.info("JSON Request: " + request);
return request;
}
}
| true
|
e2a1f05e48ce7cf97fce1ac6df8a08f846c7d774
|
Java
|
cjw05/bsTD
|
/src/util/SimpleKeyboardInput.java
|
UTF-8
| 650
| 2.890625
| 3
|
[] |
no_license
|
package util;
import java.awt.event.*;
public class SimpleKeyboardInput implements KeyListener{
private boolean[] keys;
public SimpleKeyboardInput(){
keys=new boolean[256];
}
public synchronized boolean keyDown(int keyCode){
return keys[keyCode];
}
public synchronized void keyPressed(KeyEvent e){
int keyCode=e.getKeyCode();
if(keyCode>=0 && keyCode<keys.length){
keys[keyCode]=true;
}
}
public void keyTyped(KeyEvent e){
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int keyCode=e.getKeyCode();
if(keyCode>=0 && keyCode<keys.length){
keys[keyCode]=false;
}
}
}
| true
|
85c2c8431178a3b7ae51d4241ba610d6e86d178d
|
Java
|
aman5898/Java-Codes-Crux
|
/Code/Crux4Sum2017/src/aug20/HEncoder.java
|
UTF-8
| 2,338
| 3.140625
| 3
|
[] |
no_license
|
package aug20;
import java.util.ArrayList;
public class HEncoder {
private HashMap<Character, String> encoder = new HashMap<>();
private HashMap<String, Character> decoder = new HashMap<>();
private class Node implements Comparable<Node> {
Character data;
int freq;
Node left;
Node right;
@Override
public int compareTo(Node o) {
return this.freq - o.freq;
}
}
public HEncoder(String feeder) throws Exception{
// 1. freq map
HashMap<Character, Integer> fmap = new HashMap<>();
for(int i = 0; i < feeder.length(); i++){
Character ch = feeder.charAt(i);
if(fmap.containsKey(ch)){
fmap.put(ch, fmap.get(ch) + 1);
} else {
fmap.put(ch, 1);
}
}
// 2. prepare heap
Heap<Node> heap = new Heap<>();
ArrayList<Character> keys = new ArrayList<>(fmap.keyset());
for(Character key: keys){
Node node = new Node();
node.data = key;
node.freq = fmap.get(key);
heap.addHP(node);
}
// 3. till the size is 1, remove two, merge and add back
while(heap.size() > 1){
Node one = heap.removeHP();
Node two = heap.removeHP();
Node merged = new Node();
merged.freq = one.freq + two.freq;
merged.left = one;
merged.right = two;
heap.addHP(merged);
}
// 4. get the final node
Node fn = heap.removeHP();
// 5. traverse, to fill enc and dec
traverse(fn, "");
}
private void traverse(Node node, String psf) throws Exception {
if(node == null){
return;
}
if(node.left == null && node.right == null){
encoder.put(node.data, psf);
decoder.put(psf, node.data);
}
traverse(node.left, psf + 0);
traverse(node.right, psf + 1);
}
// abcdabcd => 101001000101001000
public String compress(String str) throws Exception {
String rv = "";
for(int i = 0; i < str.length(); i++){
Character ch = str.charAt(i);
rv += encoder.get(ch);
}
return rv;
}
// 101001000101001000 => abcdabcd
public String decompress(String str) throws Exception {
String rv = "";
String code = "";
for(int i = 0; i < str.length(); i++){
Character ch = str.charAt(i);
code += ch;
if(decoder.containsKey(code)){
rv += decoder.get(code);
code = "";
}
}
return rv;
}
}
| true
|
b2c159bd7972dd63b321780a2b48391e4df730fb
|
Java
|
AnantaKadyan/GitTest
|
/lecture3/homeexercises/program6/src/PascalTriangle.java
|
UTF-8
| 1,275
| 4.15625
| 4
|
[] |
no_license
|
/* Author: Ananta
Version : 1.0.0
Purpose: to get an input of number of rows from the user and print out the pascal's triangle*/
import java.util.Scanner; // to get input from the user
class PascalTriangle
{
public static void main(String args[])
{
char choice = 'y'; // value of variable choice is set to yes to repeat the experiment
do{
int row, num1, num3, number=1, num2;
Scanner scan = new Scanner(System.in); // object input and scan are formed to take inputs
Scanner input = new Scanner(System.in);
System.out.print("Enter Number of Rows : ");
row = scan.nextInt();
for(num1=0;num1<row;num1++) // for loop is used to form the pascal's triangle
{
for(num3=row; num3>num1; num3--)
{
System.out.print(" ");
}
number = 1;
for(num2=0;num2<=num1;num2++)
{
System.out.print(number+ " "); // to print out the number in form of the triangle
number = number * (num1 - num2) / (num2 + 1);
}
System.out.println(); // next line blanck is printed
}
System.out.println(" Do you want to continue ? ");
choice = input.next().charAt(0); // to take in a character input
} while(choice == 'y') ; // while loop condition is y to get the program repeated
}
}
| true
|