blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e337ccd3a3498016aef4a403752a2c936b42724 | 33,663,953,720,062 | e013ec787e57af5c8c798f5714d9f930b76dfd32 | /Solutions/Codeforces Solutions/276-B_LittleGirlandGame.java | 2f9b9eda525ec5298ac0e81853a2efbf3bef71e7 | [] | no_license | omaryasser/Competitive-Programming | https://github.com/omaryasser/Competitive-Programming | da66cb75bf6ed5495454d2f57333b02fe30a5b68 | ba71b23ae3d0c4ef8bbdeff0cd12c3daca19d809 | refs/heads/master | 2021-04-29T00:39:29.663000 | 2019-02-19T04:20:56 | 2019-02-19T04:20:56 | 121,832,844 | 17 | 8 | null | null | null | null | null | null | null | null | null | null | null | null | null | https://codeforces.com/contest/276/submission/18008314 | UTF-8 | Java | 54 | java | 276-B_LittleGirlandGame.java | Java | [] | null | [] | https://codeforces.com/contest/276/submission/18008314 | 54 | 0.851852 | 0.648148 | 1 | 54 | 0 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 2 |
b2869ba1abb77d05dc90551e3ff5705f1357aecd | 463,856,522,737 | 311e29ae3a299521f7992196543fc27202bcc761 | /HomeWork2/pointDistance/src/main/java/com/cuiods/arithmetic/points/arithmetic/PointDistance.java | 1534cb9f0aebd3c573b97c67f5d1baeab0ce6c69 | [
"Apache-2.0"
] | permissive | cuiods/Arithmetic | https://github.com/cuiods/Arithmetic | 10649fdc4e0f6ec103c7ac390564a7d772bcff57 | 1d922a0f5cc2acb9da6a23f229af0fac212d96c3 | refs/heads/master | 2020-03-29T11:09:23.188000 | 2019-02-20T09:26:00 | 2019-02-20T09:26:00 | 149,838,392 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cuiods.arithmetic.points.arithmetic;
import javafx.util.Pair;
import java.util.*;
public class PointDistance {
private List<Point> points = new ArrayList<>();
private Comparator<Point> xCompare = Comparator.comparingInt(o -> o.x);
private Comparator<Point> yCompare = Comparator.comparingInt(o -> o.y);
public DistanceResult minDistancePoint(DistanceMethod method) {
DistanceResult result = new DistanceResult(new ArrayList<>(),0);
if (points.size() <= 1) {
List<Pair<Point,Point>> resultPoint = new ArrayList<>();
return new DistanceResult(resultPoint, 0);
}
switch (method) {
case ENUM: return enumDistance();
case DIVIDE: return divideDistance();
default: return result;
}
}
public double minDistancePointQuick(DistanceMethod method) {
if (points.size() <= 1) {
return 0;
}
switch (method) {
case ENUM: return enumDistanceQuick();
case DIVIDE: return divideDistanceQuick();
default: return 0;
}
}
private DistanceResult enumDistance() {
long start = System.nanoTime();
double minDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> result = new ArrayList<>();
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
double distance = distance(points.get(i), points.get(j));
if (distance < minDistance) {
result.clear();
result.add(new Pair<>(points.get(i), points.get(j)));
minDistance = distance;
} else if (distance == minDistance) {
result.add(new Pair<>(points.get(i), points.get(j)));
}
}
}
long end = System.nanoTime();
DistanceResult distanceResult = new DistanceResult(result, minDistance);
distanceResult.setTime(end-start);
return distanceResult;
}
private double enumDistanceQuick() {
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
double distance = distance(points.get(i), points.get(j));
if (distance < minDistance) {
minDistance = distance;
}
}
}
return minDistance;
}
private DistanceResult divideDistance() {
long start = System.nanoTime();
points.sort(xCompare);
DistanceResult result = divideDistance(0, points.size()-1);
long end = System.nanoTime();
result.setTime(end-start);
return result;
}
private double divideDistanceQuick() {
points.sort(xCompare);
return divideDistanceQuick(0, points.size()-1);
}
private double divideDistanceQuick(int start, int end) {
double minDistance = Double.MAX_VALUE;
if (end - start == 0) return minDistance;
if (end - start == 1) return distance(points.get(start),points.get(end));
int half = (end+start)>>1;
double resultLeft = divideDistanceQuick(start, half);
double resultRight = divideDistanceQuick(half, end);
double minHalf = Math.min(resultLeft, resultRight);
minDistance = minHalf;
List<Point> middlePoints = new ArrayList<>();
for (int i = start; i < end; i++) {
if (Math.abs(points.get(i).x - points.get(half).x) < minHalf)
middlePoints.add(points.get(i));
}
double minMiddleDistance = Double.MAX_VALUE;
if (middlePoints.size() > 1 ) {
middlePoints.sort(yCompare);
for (int i = 0; i < middlePoints.size(); i++) {
for (int j = i+1; j < middlePoints.size() && j < i+8; j++) {
if (middlePoints.get(j).y-middlePoints.get(i).y>minHalf) break;
double distance = distance(middlePoints.get(i), middlePoints.get(j));
if (distance < minMiddleDistance) {
minMiddleDistance = distance;
}
}
}
}
if (minDistance > minMiddleDistance) minDistance = minMiddleDistance;
return minDistance;
}
private DistanceResult divideDistance(int start, int end) {
double minDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> result = new ArrayList<>();
if (end - start == 0) {
return new DistanceResult(result, minDistance);
}
if (end - start == 1) {
result.add(new Pair<>(points.get(start),points.get(end)));
return new DistanceResult(result, distance(points.get(start),points.get(end)));
}
//划分左右
int half = (end+start)>>1;
DistanceResult resultLeft = divideDistance(start, half);
DistanceResult resultRight = divideDistance(half, end);
//划分中间分区
double minHalf = Math.min(resultLeft.getMinDistance(), resultRight.getMinDistance());
List<Point> middlePoints = new ArrayList<>();
for (int i = start; i < end; i++) {
if (Math.abs(points.get(i).x - points.get(half).x) < minHalf)
middlePoints.add(points.get(i));
}
//计算中间分区的距离最小值
double minMiddleDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> middleResult = new ArrayList<>();
if (middlePoints.size() > 1 ) {
middlePoints.sort(yCompare);
for (int i = 0; i < middlePoints.size(); i++) {
for (int j = i+1; j < middlePoints.size() && j < i+8; j++) {
if (middlePoints.get(j).y-middlePoints.get(i).y>minHalf) break;
double distance = distance(middlePoints.get(i), middlePoints.get(j));
if (distance < minMiddleDistance) {
middleResult.clear();
middleResult.add(new Pair<>(middlePoints.get(i), middlePoints.get(j)));
minMiddleDistance = distance;
} else if (distance == minMiddleDistance) {
middleResult.add(new Pair<>(middlePoints.get(i), middlePoints.get(j)));
}
}
}
}
DistanceResult resultMiddle = new DistanceResult(middleResult, minMiddleDistance);
//合并结果
if (resultLeft.getMinDistance() < resultRight.getMinDistance()) {
minDistance = resultLeft.getMinDistance();
result = resultLeft.getPoints();
} else if (resultLeft.getMinDistance() == resultRight.getMinDistance()) {
minDistance = resultLeft.getMinDistance();
result = resultLeft.getPoints();
result.removeAll(resultRight.getPoints());
result.addAll(resultRight.getPoints());
} else {
minDistance = resultRight.getMinDistance();
result = resultRight.getPoints();
}
if (minDistance == resultMiddle.getMinDistance()) {
result.removeAll(resultMiddle.getPoints());
result.addAll(resultMiddle.getPoints());
} else if (minDistance > resultMiddle.getMinDistance()) {
minDistance = resultMiddle.getMinDistance();
result = resultMiddle.getPoints();
}
return new DistanceResult(result, minDistance);
}
public void setPoints(List<Point> points) {
this.points = points;
}
public List<Point> getPoints() {
return points;
}
public void addPoint(Point point) {
points.add(point);
}
public void clear() {
points.clear();
}
private double distance(Point a, Point b) {
return Math.sqrt(Math.pow((a.x-b.x),2) + Math.pow((a.y-b.y),2));
}
}
| UTF-8 | Java | 7,978 | java | PointDistance.java | Java | [] | null | [] | package com.cuiods.arithmetic.points.arithmetic;
import javafx.util.Pair;
import java.util.*;
public class PointDistance {
private List<Point> points = new ArrayList<>();
private Comparator<Point> xCompare = Comparator.comparingInt(o -> o.x);
private Comparator<Point> yCompare = Comparator.comparingInt(o -> o.y);
public DistanceResult minDistancePoint(DistanceMethod method) {
DistanceResult result = new DistanceResult(new ArrayList<>(),0);
if (points.size() <= 1) {
List<Pair<Point,Point>> resultPoint = new ArrayList<>();
return new DistanceResult(resultPoint, 0);
}
switch (method) {
case ENUM: return enumDistance();
case DIVIDE: return divideDistance();
default: return result;
}
}
public double minDistancePointQuick(DistanceMethod method) {
if (points.size() <= 1) {
return 0;
}
switch (method) {
case ENUM: return enumDistanceQuick();
case DIVIDE: return divideDistanceQuick();
default: return 0;
}
}
private DistanceResult enumDistance() {
long start = System.nanoTime();
double minDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> result = new ArrayList<>();
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
double distance = distance(points.get(i), points.get(j));
if (distance < minDistance) {
result.clear();
result.add(new Pair<>(points.get(i), points.get(j)));
minDistance = distance;
} else if (distance == minDistance) {
result.add(new Pair<>(points.get(i), points.get(j)));
}
}
}
long end = System.nanoTime();
DistanceResult distanceResult = new DistanceResult(result, minDistance);
distanceResult.setTime(end-start);
return distanceResult;
}
private double enumDistanceQuick() {
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
double distance = distance(points.get(i), points.get(j));
if (distance < minDistance) {
minDistance = distance;
}
}
}
return minDistance;
}
private DistanceResult divideDistance() {
long start = System.nanoTime();
points.sort(xCompare);
DistanceResult result = divideDistance(0, points.size()-1);
long end = System.nanoTime();
result.setTime(end-start);
return result;
}
private double divideDistanceQuick() {
points.sort(xCompare);
return divideDistanceQuick(0, points.size()-1);
}
private double divideDistanceQuick(int start, int end) {
double minDistance = Double.MAX_VALUE;
if (end - start == 0) return minDistance;
if (end - start == 1) return distance(points.get(start),points.get(end));
int half = (end+start)>>1;
double resultLeft = divideDistanceQuick(start, half);
double resultRight = divideDistanceQuick(half, end);
double minHalf = Math.min(resultLeft, resultRight);
minDistance = minHalf;
List<Point> middlePoints = new ArrayList<>();
for (int i = start; i < end; i++) {
if (Math.abs(points.get(i).x - points.get(half).x) < minHalf)
middlePoints.add(points.get(i));
}
double minMiddleDistance = Double.MAX_VALUE;
if (middlePoints.size() > 1 ) {
middlePoints.sort(yCompare);
for (int i = 0; i < middlePoints.size(); i++) {
for (int j = i+1; j < middlePoints.size() && j < i+8; j++) {
if (middlePoints.get(j).y-middlePoints.get(i).y>minHalf) break;
double distance = distance(middlePoints.get(i), middlePoints.get(j));
if (distance < minMiddleDistance) {
minMiddleDistance = distance;
}
}
}
}
if (minDistance > minMiddleDistance) minDistance = minMiddleDistance;
return minDistance;
}
private DistanceResult divideDistance(int start, int end) {
double minDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> result = new ArrayList<>();
if (end - start == 0) {
return new DistanceResult(result, minDistance);
}
if (end - start == 1) {
result.add(new Pair<>(points.get(start),points.get(end)));
return new DistanceResult(result, distance(points.get(start),points.get(end)));
}
//划分左右
int half = (end+start)>>1;
DistanceResult resultLeft = divideDistance(start, half);
DistanceResult resultRight = divideDistance(half, end);
//划分中间分区
double minHalf = Math.min(resultLeft.getMinDistance(), resultRight.getMinDistance());
List<Point> middlePoints = new ArrayList<>();
for (int i = start; i < end; i++) {
if (Math.abs(points.get(i).x - points.get(half).x) < minHalf)
middlePoints.add(points.get(i));
}
//计算中间分区的距离最小值
double minMiddleDistance = Double.MAX_VALUE;
List<Pair<Point,Point>> middleResult = new ArrayList<>();
if (middlePoints.size() > 1 ) {
middlePoints.sort(yCompare);
for (int i = 0; i < middlePoints.size(); i++) {
for (int j = i+1; j < middlePoints.size() && j < i+8; j++) {
if (middlePoints.get(j).y-middlePoints.get(i).y>minHalf) break;
double distance = distance(middlePoints.get(i), middlePoints.get(j));
if (distance < minMiddleDistance) {
middleResult.clear();
middleResult.add(new Pair<>(middlePoints.get(i), middlePoints.get(j)));
minMiddleDistance = distance;
} else if (distance == minMiddleDistance) {
middleResult.add(new Pair<>(middlePoints.get(i), middlePoints.get(j)));
}
}
}
}
DistanceResult resultMiddle = new DistanceResult(middleResult, minMiddleDistance);
//合并结果
if (resultLeft.getMinDistance() < resultRight.getMinDistance()) {
minDistance = resultLeft.getMinDistance();
result = resultLeft.getPoints();
} else if (resultLeft.getMinDistance() == resultRight.getMinDistance()) {
minDistance = resultLeft.getMinDistance();
result = resultLeft.getPoints();
result.removeAll(resultRight.getPoints());
result.addAll(resultRight.getPoints());
} else {
minDistance = resultRight.getMinDistance();
result = resultRight.getPoints();
}
if (minDistance == resultMiddle.getMinDistance()) {
result.removeAll(resultMiddle.getPoints());
result.addAll(resultMiddle.getPoints());
} else if (minDistance > resultMiddle.getMinDistance()) {
minDistance = resultMiddle.getMinDistance();
result = resultMiddle.getPoints();
}
return new DistanceResult(result, minDistance);
}
public void setPoints(List<Point> points) {
this.points = points;
}
public List<Point> getPoints() {
return points;
}
public void addPoint(Point point) {
points.add(point);
}
public void clear() {
points.clear();
}
private double distance(Point a, Point b) {
return Math.sqrt(Math.pow((a.x-b.x),2) + Math.pow((a.y-b.y),2));
}
}
| 7,978 | 0.560434 | 0.556649 | 210 | 36.742859 | 26.292324 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719048 | false | false | 2 |
f88208a2fae285838231528ad3591037a3c1784a | 17,119,739,651,643 | 7defd9257cba97ca3f230fc3b273836f07181689 | /exam2/src/main/java/Mapp/exam2/App.java | 5d936d52919c118793d263070faa2884b724efab | [] | no_license | jiabang/exam | https://github.com/jiabang/exam | 08c4ae56a16cfb642450790e9b4f6193bae1dbe7 | c3be7a13c427f8566d9f5ab9a4205421b2a51d74 | refs/heads/master | 2021-01-19T22:52:49.278000 | 2017-03-06T03:47:14 | 2017-03-06T03:47:14 | 83,781,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Mapp.exam2;
import java.util.Scanner;
/**
* 编程实现工资个人所得税计算程序
*
*/
public class App
{
public static void main( String[] args ){
double pay =0;
double pay_money =0;
System.out.println( "请输入工资:");
Scanner sc=new Scanner(System.in);
double money =sc.nextDouble();
//1500
if(money<=1500){
pay=money*0.03;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//1500-4500
else if(money>1500 || money <=4500) {
pay_money=money-1500;
pay=pay_money*0.1;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//4500-9000
else if (money >4500 || money <=9000){
pay_money=money-4500;
pay=pay_money*0.2;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//9000-35000
else if (money>9000 || money <=35000){
pay_money=money-9000;
pay=pay_money*0.25;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//35000-55000
else if (money>35000 || money <=55000){
pay_money=money-35000;
pay=pay_money*0.3;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//55000-80000
else if (money>55000 || money <=80000){
pay_money=money-55000;
pay=pay_money*0.35;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//>80000
else if (money>80000){
pay_money=money-80000;
pay=pay_money*0.45;
System.out.println( "所需要缴纳的税费为:"+pay);
}
}
}
| UTF-8 | Java | 1,593 | java | App.java | Java | [] | null | [] | package Mapp.exam2;
import java.util.Scanner;
/**
* 编程实现工资个人所得税计算程序
*
*/
public class App
{
public static void main( String[] args ){
double pay =0;
double pay_money =0;
System.out.println( "请输入工资:");
Scanner sc=new Scanner(System.in);
double money =sc.nextDouble();
//1500
if(money<=1500){
pay=money*0.03;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//1500-4500
else if(money>1500 || money <=4500) {
pay_money=money-1500;
pay=pay_money*0.1;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//4500-9000
else if (money >4500 || money <=9000){
pay_money=money-4500;
pay=pay_money*0.2;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//9000-35000
else if (money>9000 || money <=35000){
pay_money=money-9000;
pay=pay_money*0.25;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//35000-55000
else if (money>35000 || money <=55000){
pay_money=money-35000;
pay=pay_money*0.3;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//55000-80000
else if (money>55000 || money <=80000){
pay_money=money-55000;
pay=pay_money*0.35;
System.out.println( "所需要缴纳的税费为:"+pay);
}
//>80000
else if (money>80000){
pay_money=money-80000;
pay=pay_money*0.45;
System.out.println( "所需要缴纳的税费为:"+pay);
}
}
}
| 1,593 | 0.555088 | 0.445614 | 64 | 21.265625 | 14.680176 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.671875 | false | false | 2 |
ba1c3032f14bc04b5e797df547e1749caa268bee | 30,030,411,336,671 | d38900c06a75e6c71b51f4290809763218626411 | /.svn/pristine/ba/ba1c3032f14bc04b5e797df547e1749caa268bee.svn-base | dc3f218d68b37ddec9f9c8807fb8e7647857dba2 | [] | no_license | XClouded/avp | https://github.com/XClouded/avp | ef5d0df5fd06d67793f93539e6421c5c8cef06c5 | 4a41681376cd3e1ec7f814dcd1f178d89e94f3d6 | refs/heads/master | 2017-02-26T23:03:31.245000 | 2014-07-22T19:03:40 | 2014-07-22T19:03:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lvsint.abp.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import uk.co.abp.AbpException;
import uk.co.abp.AbpManager;
import uk.co.abp.EventManager;
import uk.co.abp.NotAuthorizedException;
import uk.co.abp.Workspace;
import uk.co.abp.WorkspaceSession;
import com.lvsint.abp.common.Constants;
import com.lvsint.abp.common.bean.EventPath;
import com.lvsint.abp.common.bean.EventPathInfo;
import com.lvsint.abp.common.bean.Phrase;
import com.lvsint.abp.common.pxp.PXPData;
import com.lvsint.abp.richclient.eventcreator.customattributes.CustomAttributeUtil;
import com.lvsint.util.HTTPTools;
import com.lvsint.util.NumberUtils;
public class EventPathSave extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8102891809853086011L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body onload='document.save.description.focus()'>");
out.println("Load an event path");
out.println("<form name='save' method='post' action='com.lvsint.abp.servlet.EventPathSave.pxp'>");
out.println("<input type='text' name='eventPathId'>eventPathId<br>");
out.println("<input type='text' name='description'>description<br>");
out.println("<input type='text' name='isEvent'>isEvent<br>");
out.println("<input type='text' name='tagId'>tagId<br>");
out.println("<input type='text' name='isCurrent'>isCurrent<br>");
out.println("<input type='text' name='parentId'>parentId<br>");
out.println("<input type='text' name='feedCode'>feedCode<br>");
out.println("<input type='text' name='contents'>contents<br>");
out.println("<input type='submit' name='Submit' value='Submit'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
boolean encode = session.getAttribute(Login.ATTRIBUTE_NO_ENCODING) == null;
PXPData pxpResponse = new PXPData();
response.setContentType("text/plain; charset=utf8");
try {
String key = AbpManager.getWorkspaceStorageName();
AbpManager abpManager = (AbpManager) session.getAttribute(key);
Workspace workspace = abpManager.makeWorkspace(request);
EventManager eventManager = abpManager.getEventManager(workspace);
EventPath eventPath;
long id = NumberUtils.parseLong(request.getParameter("eventPathId"), Constants.NULL_ID);
long parentPathId = NumberUtils.parseLong(request.getParameter("parentId"), Constants.NULL_ID);
String description = HTTPTools.parse(request.getParameter("description"), "");
boolean isEvent = HTTPTools.parse(request.getParameter("isEvent"), false);
Phrase phrase = null;
if (description != null && description.length() != 0) {
phrase = eventManager.loadPhrase(workspace, description);
}
if (phrase == null) {
phrase = eventManager.makePhrase(workspace, description);
eventManager.savePhrase(workspace, phrase);
}
if (id == Constants.NULL_ID) {
/*
* Check if we have an eventpath with the same parent and description, if we do, load it, if we don't we
* have to create a new eventpath.
*/
eventPath =
eventManager.loadEventPathByParentAndDescriptionAndEventYN(workspace, parentPathId,
description, isEvent);
if (eventPath == null) {
eventPath = eventManager.makeEventPath(workspace, parentPathId, description);
}
} else {
eventPath = eventManager.loadEventPath(workspace, id);
}
eventPath.setDescription(description);
eventPath.setEvent(HTTPTools.parse(request.getParameter("isEvent"), eventPath.isEvent()));
eventPath.setTagId(NumberUtils.parseLong(request.getParameter("tagId"), eventPath.getTagId()));
eventPath.setCurrent(HTTPTools.parse(request.getParameter("isCurrent"), eventPath.isCurrent()));
eventPath.setPhraseId(phrase.getId());
eventPath.setFeedCode(HTTPTools.parse(request.getParameter("feedCode"), eventPath.getFeedCode()));
eventPath.setComments(HTTPTools.parse(request.getParameter("comments"), eventPath.getComments()));
eventPath.setPublished(HTTPTools.parse(request.getParameter("isPublished"), eventPath.isPublished()));
eventPath.setPublicised(HTTPTools.parse(request.getParameter("isPublicised"), eventPath.isPublicised()));
eventPath
.setPrintOrder(NumberUtils.parseInt(request.getParameter("printOrder"), eventPath.getPrintOrder()));
eventPath.setPublishSort(NumberUtils.parseInt(request.getParameter("publishSort"), Constants.NULL_INT));
eventPath
.setBestOfSets(NumberUtils.parseInt(request.getParameter("bestOfSets"), eventPath.getBestOfSets()));
eventPath.setBestOfGames(NumberUtils.parseInt(request.getParameter("bestOfGames"),
eventPath.getBestOfGames()));
eventPath.setGrade(NumberUtils.parseInt(request.getParameter("grade"), Constants.NULL_INT));
eventPath.setSuppressP2P(HTTPTools.parse(request.getParameter("suppressP2P"), eventPath.isCurrent()));
eventPath.clearCustomAttributes();
eventPath.setCustomAttributes(CustomAttributeUtil.formatAsMap(request.getParameter("customAttributes")));
WorkspaceSession workspaceSession = workspace.startSession();
try {
eventManager.saveEventPath(workspace, eventPath);
String dirtGoing = HTTPTools.parse(request.getParameter("eventPathInfo.dirtGoing"), "");
String turfGoing = HTTPTools.parse(request.getParameter("eventPathInfo.turfGoing"), "");
String weather = HTTPTools.parse(request.getParameter("eventPathInfo.weather"), "");
if (!dirtGoing.equals("") || !turfGoing.equals("") || !weather.equals("")) {
EventPathInfo eventPathInfo = new EventPathInfo(eventPath.getId(), turfGoing, dirtGoing, weather);
eventManager.saveEventPathInfo(workspace, eventPathInfo);
}
workspace.commitSession(workspaceSession);
pxpResponse.setLong("eventPath.id", eventPath.getId());
} finally {
workspace.endSession(workspaceSession);
}
} catch (NotAuthorizedException ex) {
pxpResponse.setError(1, ex);
} catch (AbpException ex) {
pxpResponse.setError(1, ex);
} catch (NullPointerException ex) {
pxpResponse.setError(1, ex);
}
pxpResponse.print(response.getWriter(), encode);
}
}
| UTF-8 | Java | 7,606 | ba1c3032f14bc04b5e797df547e1749caa268bee.svn-base | Java | [] | null | [] | package com.lvsint.abp.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import uk.co.abp.AbpException;
import uk.co.abp.AbpManager;
import uk.co.abp.EventManager;
import uk.co.abp.NotAuthorizedException;
import uk.co.abp.Workspace;
import uk.co.abp.WorkspaceSession;
import com.lvsint.abp.common.Constants;
import com.lvsint.abp.common.bean.EventPath;
import com.lvsint.abp.common.bean.EventPathInfo;
import com.lvsint.abp.common.bean.Phrase;
import com.lvsint.abp.common.pxp.PXPData;
import com.lvsint.abp.richclient.eventcreator.customattributes.CustomAttributeUtil;
import com.lvsint.util.HTTPTools;
import com.lvsint.util.NumberUtils;
public class EventPathSave extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8102891809853086011L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body onload='document.save.description.focus()'>");
out.println("Load an event path");
out.println("<form name='save' method='post' action='com.lvsint.abp.servlet.EventPathSave.pxp'>");
out.println("<input type='text' name='eventPathId'>eventPathId<br>");
out.println("<input type='text' name='description'>description<br>");
out.println("<input type='text' name='isEvent'>isEvent<br>");
out.println("<input type='text' name='tagId'>tagId<br>");
out.println("<input type='text' name='isCurrent'>isCurrent<br>");
out.println("<input type='text' name='parentId'>parentId<br>");
out.println("<input type='text' name='feedCode'>feedCode<br>");
out.println("<input type='text' name='contents'>contents<br>");
out.println("<input type='submit' name='Submit' value='Submit'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
boolean encode = session.getAttribute(Login.ATTRIBUTE_NO_ENCODING) == null;
PXPData pxpResponse = new PXPData();
response.setContentType("text/plain; charset=utf8");
try {
String key = AbpManager.getWorkspaceStorageName();
AbpManager abpManager = (AbpManager) session.getAttribute(key);
Workspace workspace = abpManager.makeWorkspace(request);
EventManager eventManager = abpManager.getEventManager(workspace);
EventPath eventPath;
long id = NumberUtils.parseLong(request.getParameter("eventPathId"), Constants.NULL_ID);
long parentPathId = NumberUtils.parseLong(request.getParameter("parentId"), Constants.NULL_ID);
String description = HTTPTools.parse(request.getParameter("description"), "");
boolean isEvent = HTTPTools.parse(request.getParameter("isEvent"), false);
Phrase phrase = null;
if (description != null && description.length() != 0) {
phrase = eventManager.loadPhrase(workspace, description);
}
if (phrase == null) {
phrase = eventManager.makePhrase(workspace, description);
eventManager.savePhrase(workspace, phrase);
}
if (id == Constants.NULL_ID) {
/*
* Check if we have an eventpath with the same parent and description, if we do, load it, if we don't we
* have to create a new eventpath.
*/
eventPath =
eventManager.loadEventPathByParentAndDescriptionAndEventYN(workspace, parentPathId,
description, isEvent);
if (eventPath == null) {
eventPath = eventManager.makeEventPath(workspace, parentPathId, description);
}
} else {
eventPath = eventManager.loadEventPath(workspace, id);
}
eventPath.setDescription(description);
eventPath.setEvent(HTTPTools.parse(request.getParameter("isEvent"), eventPath.isEvent()));
eventPath.setTagId(NumberUtils.parseLong(request.getParameter("tagId"), eventPath.getTagId()));
eventPath.setCurrent(HTTPTools.parse(request.getParameter("isCurrent"), eventPath.isCurrent()));
eventPath.setPhraseId(phrase.getId());
eventPath.setFeedCode(HTTPTools.parse(request.getParameter("feedCode"), eventPath.getFeedCode()));
eventPath.setComments(HTTPTools.parse(request.getParameter("comments"), eventPath.getComments()));
eventPath.setPublished(HTTPTools.parse(request.getParameter("isPublished"), eventPath.isPublished()));
eventPath.setPublicised(HTTPTools.parse(request.getParameter("isPublicised"), eventPath.isPublicised()));
eventPath
.setPrintOrder(NumberUtils.parseInt(request.getParameter("printOrder"), eventPath.getPrintOrder()));
eventPath.setPublishSort(NumberUtils.parseInt(request.getParameter("publishSort"), Constants.NULL_INT));
eventPath
.setBestOfSets(NumberUtils.parseInt(request.getParameter("bestOfSets"), eventPath.getBestOfSets()));
eventPath.setBestOfGames(NumberUtils.parseInt(request.getParameter("bestOfGames"),
eventPath.getBestOfGames()));
eventPath.setGrade(NumberUtils.parseInt(request.getParameter("grade"), Constants.NULL_INT));
eventPath.setSuppressP2P(HTTPTools.parse(request.getParameter("suppressP2P"), eventPath.isCurrent()));
eventPath.clearCustomAttributes();
eventPath.setCustomAttributes(CustomAttributeUtil.formatAsMap(request.getParameter("customAttributes")));
WorkspaceSession workspaceSession = workspace.startSession();
try {
eventManager.saveEventPath(workspace, eventPath);
String dirtGoing = HTTPTools.parse(request.getParameter("eventPathInfo.dirtGoing"), "");
String turfGoing = HTTPTools.parse(request.getParameter("eventPathInfo.turfGoing"), "");
String weather = HTTPTools.parse(request.getParameter("eventPathInfo.weather"), "");
if (!dirtGoing.equals("") || !turfGoing.equals("") || !weather.equals("")) {
EventPathInfo eventPathInfo = new EventPathInfo(eventPath.getId(), turfGoing, dirtGoing, weather);
eventManager.saveEventPathInfo(workspace, eventPathInfo);
}
workspace.commitSession(workspaceSession);
pxpResponse.setLong("eventPath.id", eventPath.getId());
} finally {
workspace.endSession(workspaceSession);
}
} catch (NotAuthorizedException ex) {
pxpResponse.setError(1, ex);
} catch (AbpException ex) {
pxpResponse.setError(1, ex);
} catch (NullPointerException ex) {
pxpResponse.setError(1, ex);
}
pxpResponse.print(response.getWriter(), encode);
}
}
| 7,606 | 0.656981 | 0.653563 | 153 | 48.712418 | 36.70509 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false | 2 | |
1b8f6f691232d35b97ad24a786240b7faea13aaa | 27,178,553,101,878 | adbc3a828b0053dc2691b2126203aee6f6d5b7e2 | /src/main/java/io/github/dmnisson/labvision/entities/AdminInfo.java | b3e435d33632e3def2f91bafdd88a8e398b6999f | [] | no_license | dmnisson/labvision | https://github.com/dmnisson/labvision | f25c8376496c438ea2bc1adbaaae256bda4e3a4f | 0ca3e05c443c0e560241a77483f2e342a5cf7f32 | refs/heads/master | 2020-04-01T08:15:09.296000 | 2020-03-14T14:18:55 | 2020-03-14T14:18:55 | 153,023,100 | 0 | 0 | null | false | 2020-02-08T00:38:49 | 2018-10-14T22:02:35 | 2020-02-08T00:38:17 | 2020-02-08T00:38:11 | 1,961 | 0 | 0 | 3 | Java | false | false | package io.github.dmnisson.labvision.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.Email;
import javax.validation.constraints.Pattern;
/**
* Information for users with admin privileges
* @author David Nisson
*
*/
@Entity
@ValidAdminInfo
public class AdminInfo {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "id", updatable = false, nullable = false )
private Integer id;
@OneToOne( mappedBy = "adminInfo", targetEntity = LabVisionUser.class )
private LabVisionUser user;
@Column
private String firstName;
@Column
private String lastName;
@Column
@Email(message = "Email address must be valid.")
private String email;
@Column
@Pattern(regexp="^\\+[1-9]\\d{1,14}$", message="Phone number must be in E.164 format.")
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LabVisionUser getUser() {
return user;
}
public void setUser(LabVisionUser user) {
this.user = user;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
| UTF-8 | Java | 1,714 | java | AdminInfo.java | Java | [
{
"context": "package io.github.dmnisson.labvision.entities;\n\nimport javax.persistence.Col",
"end": 26,
"score": 0.9921947121620178,
"start": 18,
"tag": "USERNAME",
"value": "dmnisson"
},
{
"context": "rmation for users with admin privileges\n * @author David Nisson\n *\n */\n@Enti... | null | [] | package io.github.dmnisson.labvision.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.Email;
import javax.validation.constraints.Pattern;
/**
* Information for users with admin privileges
* @author <NAME>
*
*/
@Entity
@ValidAdminInfo
public class AdminInfo {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "id", updatable = false, nullable = false )
private Integer id;
@OneToOne( mappedBy = "adminInfo", targetEntity = LabVisionUser.class )
private LabVisionUser user;
@Column
private String firstName;
@Column
private String lastName;
@Column
@Email(message = "Email address must be valid.")
private String email;
@Column
@Pattern(regexp="^\\+[1-9]\\d{1,14}$", message="Phone number must be in E.164 format.")
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LabVisionUser getUser() {
return user;
}
public void setUser(LabVisionUser user) {
this.user = user;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
| 1,708 | 0.723454 | 0.718786 | 91 | 17.835165 | 18.672577 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.10989 | false | false | 2 |
cb4295653a8195ae9fb4677cee355dc0565dd7f2 | 6,777,458,448,483 | 6a52be8f4afc645c1a2297c6582da5f2e948e64c | /demo/src/main/java/com/xmu/crms/view/TopicController.java | 43ac4d0e352fb67a8ed6854c37e947d1c9dec5a3 | [] | no_license | Group2-1/ClassManagement | https://github.com/Group2-1/ClassManagement | bcb90074eb37067d87049ab70974eb1a3ad3226a | 9fefc0dae83b2290769c16dc286ae9a4f64e8a5b | refs/heads/master | 2021-09-01T18:22:47.952000 | 2017-12-28T07:24:28 | 2017-12-28T07:24:28 | 112,998,563 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xmu.crms.view;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Response;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xmu.crms.entity.Topic;
import com.xmu.crms.view.vo.GroupVO;
import com.xmu.crms.view.vo.TopicVO;
/**
*
* @author lingyun
*
*/
@RestController
@RequestMapping("/topic")
public class TopicController {
@GetMapping("/{topicId}")
public TopicVO selectTopic(@PathVariable("topicId") int topicId) {
TopicVO topic = new TopicVO();
topic.setId(257L);
topic.setSerial("A");
topic.setName("领域模型与模块");
topic.setDescription("Domain model与模块划分");
topic.setGroupLeft(2);
topic.setGroupLimit(5);
topic.setGroupMemberLimit(6);
return topic;
/*return new Topic(257, "A", "领域模型与模块", "Domain model与模块划分", 2, 5, 6);
*/
}
@PutMapping("/{topicId}")
public Topic updateTopic(@PathVariable("topicId") int topicId, @RequestBody Topic topic, HttpServletResponse response) {
response.setStatus(204);
return null;
}
@DeleteMapping("/{topicId}")
public Response deleteTopic(@PathVariable("topicId") int topicId, HttpServletResponse response) {
response.setStatus(204);
return null;
}
@GetMapping("/{topicId}/group")
public List<GroupVO> selectGroupsForTopic(@PathVariable("topicId") int topicId) {
List<GroupVO> groups = new ArrayList<>();
/*Group group1 = new Group();
group1.setId(23);
group1.setName("1A1");
groups.add(group1);
Group group2 = new Group();
group2.setId(26);
group2.setName("2A2");
groups.add(group2);*/
return groups;
}
}
| UTF-8 | Java | 2,176 | java | TopicController.java | Java | [
{
"context": "t com.xmu.crms.view.vo.TopicVO;\n/**\n * \n * @author lingyun\n *\n */\n@RestController\n@RequestMapping(\"/topic\")\n",
"end": 737,
"score": 0.9988501667976379,
"start": 730,
"tag": "USERNAME",
"value": "lingyun"
}
] | null | [] | package com.xmu.crms.view;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Response;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xmu.crms.entity.Topic;
import com.xmu.crms.view.vo.GroupVO;
import com.xmu.crms.view.vo.TopicVO;
/**
*
* @author lingyun
*
*/
@RestController
@RequestMapping("/topic")
public class TopicController {
@GetMapping("/{topicId}")
public TopicVO selectTopic(@PathVariable("topicId") int topicId) {
TopicVO topic = new TopicVO();
topic.setId(257L);
topic.setSerial("A");
topic.setName("领域模型与模块");
topic.setDescription("Domain model与模块划分");
topic.setGroupLeft(2);
topic.setGroupLimit(5);
topic.setGroupMemberLimit(6);
return topic;
/*return new Topic(257, "A", "领域模型与模块", "Domain model与模块划分", 2, 5, 6);
*/
}
@PutMapping("/{topicId}")
public Topic updateTopic(@PathVariable("topicId") int topicId, @RequestBody Topic topic, HttpServletResponse response) {
response.setStatus(204);
return null;
}
@DeleteMapping("/{topicId}")
public Response deleteTopic(@PathVariable("topicId") int topicId, HttpServletResponse response) {
response.setStatus(204);
return null;
}
@GetMapping("/{topicId}/group")
public List<GroupVO> selectGroupsForTopic(@PathVariable("topicId") int topicId) {
List<GroupVO> groups = new ArrayList<>();
/*Group group1 = new Group();
group1.setId(23);
group1.setName("1A1");
groups.add(group1);
Group group2 = new Group();
group2.setId(26);
group2.setName("2A2");
groups.add(group2);*/
return groups;
}
}
| 2,176 | 0.702538 | 0.68656 | 77 | 26.636364 | 25.155056 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.883117 | false | false | 2 |
7b8b2484ec2fc79aea81cd483bfda0bfbdab9095 | 18,562,848,712,409 | 2d884cd4f35d2a8b4c25644eb742c372982b1fcd | /src/test/java/HelloPrefix.java | bd3573b15c063d53fef060c23744a06206a684ee | [] | no_license | karolwarak/restAssuredExercise | https://github.com/karolwarak/restAssuredExercise | ef622698f7c7f418e8aaf738aca254d3fe8354cf | d2b2c3040be64e7131558a60c8bce0672c875be1 | refs/heads/master | 2020-04-07T03:30:15.536000 | 2018-12-16T18:49:45 | 2018-12-16T18:49:45 | 158,018,777 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.junit.Test;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class HelloPrefix {
// bardzo przydatny test sprawdzajacy czy schema z jaka odpowiada serwer jest prawidlowa
// https://jsonschema.net/
@Test
public void serverInfoPassesSchemaValidation(){
get("https://safe-plateau-87483.herokuapp.com/hello")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("schema.json"));
}
}
| UTF-8 | Java | 569 | java | HelloPrefix.java | Java | [] | null | [] | import org.junit.Test;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class HelloPrefix {
// bardzo przydatny test sprawdzajacy czy schema z jaka odpowiada serwer jest prawidlowa
// https://jsonschema.net/
@Test
public void serverInfoPassesSchemaValidation(){
get("https://safe-plateau-87483.herokuapp.com/hello")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("schema.json"));
}
}
| 569 | 0.6942 | 0.685413 | 18 | 30.611111 | 29.769745 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 2 |
69478e79af4a07af9316b2e83816bcde385cad5e | 4,578,435,200,735 | 1dc369c2d6e9837bd76bd1bbc9004e731cb4ccb6 | /app/src/main/java/edu/byu/testare/cs246multi_threadedprogramming/MainActivity.java | 4b75a47da10a2880b9a1d64c6e58b21b925f04bc | [] | no_license | Testare/Cs246Multi-threadedProgramming | https://github.com/Testare/Cs246Multi-threadedProgramming | 4b6b9fafd76587b15aac1e7e488cf6b93b38823e | 332e62de46fe7908d39a25ff7bb3d57a4aa40ccd | refs/heads/master | 2016-08-12T11:25:20.808000 | 2016-02-16T07:25:29 | 2016-02-16T07:25:29 | 51,772,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.byu.testare.cs246multi_threadedprogramming;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* The class for the main activitiy of the app
*/
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private int progressCheck;
private Handler mHandler = new Handler();
private synchronized void setBarProgress(int prog) {
progressCheck = Math.min(100,prog);
}
private synchronized int getBarProgress() {
return progressCheck;
}
private static final String FILE_NAME = "file.file";
private ArrayAdapter<String> listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1);
listView.setAdapter(listAdapter);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
/*Create button event listener*/
findViewById(R.id.createButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
File file = new File(context.getFilesDir(), FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
for (int i = 1; i <= 10; ++i) {
fileOut.println(i);
setBarProgress(i * 10);
System.out.println("-" + i);
mHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(getBarProgress());
}
});
Thread.sleep(250);
}
fileOut.close();
} catch (IOException | InterruptedException ioe) {
ioe.printStackTrace(System.err);
}
}
});
thread.start();
}
});
/*Load button*/
findViewById(R.id.loadButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
File f = new File(context.getFilesDir(), FILE_NAME);
Scanner fileIn = new Scanner(f);
setBarProgress(0);
System.out.println("!..!" + f.exists());
final List<String> loadedList = new ArrayList<>();
while (fileIn.hasNextLine()) {
String s = fileIn.nextLine();
System.out.println("+" + s);
loadedList.add(s);
setBarProgress(getBarProgress()+10);
mHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(getBarProgress());
}
});
Thread.sleep(250);
}
fileIn.close();
mHandler.post(new Runnable() {
@Override
public void run() {
listAdapter.clear();
listAdapter.addAll(loadedList);
loadedList.clear();
listAdapter.notifyDataSetChanged();
}
});
} catch (IOException | InterruptedException ioe) {
ioe.printStackTrace(System.err);
}
}
});
thread.start();
}
});
/*Clear button*/
findViewById(R.id.clearButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.post(new Runnable() {
@Override
public void run() {
listAdapter.clear();
listAdapter.notifyDataSetChanged();
}
});
}
});
}
}
| UTF-8 | Java | 5,785 | java | MainActivity.java | Java | [] | null | [] | package edu.byu.testare.cs246multi_threadedprogramming;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* The class for the main activitiy of the app
*/
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private int progressCheck;
private Handler mHandler = new Handler();
private synchronized void setBarProgress(int prog) {
progressCheck = Math.min(100,prog);
}
private synchronized int getBarProgress() {
return progressCheck;
}
private static final String FILE_NAME = "file.file";
private ArrayAdapter<String> listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1);
listView.setAdapter(listAdapter);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
/*Create button event listener*/
findViewById(R.id.createButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
File file = new File(context.getFilesDir(), FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
for (int i = 1; i <= 10; ++i) {
fileOut.println(i);
setBarProgress(i * 10);
System.out.println("-" + i);
mHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(getBarProgress());
}
});
Thread.sleep(250);
}
fileOut.close();
} catch (IOException | InterruptedException ioe) {
ioe.printStackTrace(System.err);
}
}
});
thread.start();
}
});
/*Load button*/
findViewById(R.id.loadButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
File f = new File(context.getFilesDir(), FILE_NAME);
Scanner fileIn = new Scanner(f);
setBarProgress(0);
System.out.println("!..!" + f.exists());
final List<String> loadedList = new ArrayList<>();
while (fileIn.hasNextLine()) {
String s = fileIn.nextLine();
System.out.println("+" + s);
loadedList.add(s);
setBarProgress(getBarProgress()+10);
mHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(getBarProgress());
}
});
Thread.sleep(250);
}
fileIn.close();
mHandler.post(new Runnable() {
@Override
public void run() {
listAdapter.clear();
listAdapter.addAll(loadedList);
loadedList.clear();
listAdapter.notifyDataSetChanged();
}
});
} catch (IOException | InterruptedException ioe) {
ioe.printStackTrace(System.err);
}
}
});
thread.start();
}
});
/*Clear button*/
findViewById(R.id.clearButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.post(new Runnable() {
@Override
public void run() {
listAdapter.clear();
listAdapter.notifyDataSetChanged();
}
});
}
});
}
}
| 5,785 | 0.45134 | 0.447537 | 157 | 35.847134 | 24.514175 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509554 | false | false | 2 |
ce7fc9f3d2cef7ab165c5b64be0a2adb9713815d | 5,454,608,531,201 | dc6760018ea8f6d730f8d7f0feb13b30602af2da | /app one/src/me/lican/app/ui/Main.java | b9e260a97a9f95a2e9ce08a497beab0e40122b69 | [] | no_license | onthedesk/lican | https://github.com/onthedesk/lican | 6e4e9f079555e9353359703c4efa1877f2767f0d | 747d292989fb6db18a058212011be034a3aa04a4 | refs/heads/master | 2016-05-24T17:37:56.233000 | 2013-11-12T09:43:59 | 2013-11-12T09:43:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.lican.app.ui;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import me.lican.app.AppContext;
import me.lican.app.R;
import me.lican.app.common.BitmapManager;
import me.lican.app.common.FileUtils;
import me.lican.app.common.ImageUtils;
import me.lican.app.common.StringUtils;
import me.lican.app.common.UIHelper;
import me.lican.app.ui.base.BaseSlidingFragmentActivity;
import me.lican.app.ui.slidingmenu.SlidingMenu;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
/**
* 应用程序首页
*
* @author alfred
*
*/
public class Main extends BaseSlidingFragmentActivity {
private SlidingMenu sm;
private AppContext appContext;// 全局Context
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// TODO 广播处理
initSlidingMenu();
// above_slidingmenu 右侧主页面的样式
// setContentView(R.layout.above_slidingmenu);
setContentView(R.layout.main);
appContext = (AppContext) getApplication();
// 网络连接判断
if (!appContext.isNetworkConnected()) {
// UIHelper.ToastMessage(this, R.string.network_not_connected);
}
// 初始化登录
appContext.initLoginInfo();
imageTest();
cameraTest();
}
private void initSlidingMenu() {
// behind_slidingmenu 侧边栏的样式
setBehindContentView(R.layout.behind_slidingmenu);
// customize the SlidingMenu
// TODO 阅读SlidingMenu,设置个性化的边栏
// TODO 取消SlidingMenu的log输出
sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
// sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// image test memebers
private BitmapManager bmpManager;
private ImageView img;
private String url = "http://images.sohu.com/bill/s2013/waptest/v3/banner/1024/ms-banner.jpg";
private String err = "err";
public void imageTest() {
// 获取网络图片,并展示,使用bitmapManager
img = (ImageView) findViewById(R.id.test_img);
UIHelper.showLoadImage(img, url, err);
}
// camera test members
private final static int CROP = 200;
private Button editer;
private final static String FILE_SAVEPATH = Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Lican/Portrait/";
private String album = "图库";
private String camera = "相机";
private Uri origUri;
private Uri cropUri;
private File protraitFile;
private Bitmap protraitBitmap;
private String protraitPath;
public void cameraTest() {
editer = (Button) findViewById(R.id.user_info_editer);
editer.setOnClickListener(editerClickListener);
}
private View.OnClickListener editerClickListener = new View.OnClickListener() {
public void onClick(View v) {
CharSequence[] items = { album, camera };
imageChooseItem(items);
}
};
// 裁剪头像的绝对路径
private Uri getUploadTempFile(Uri uri) {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File savedir = new File(FILE_SAVEPATH);
if (!savedir.exists()) {
savedir.mkdirs();
}
} else {
// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像,请检查SD卡是否挂载");
return null;
}
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);
// 如果是标准Uri
if (StringUtils.isEmpty(thePath)) {
thePath = ImageUtils.getAbsoluteImagePath(this, uri);
}
String ext = FileUtils.getFileFormat(thePath);
ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
// 照片命名
String cropFileName = "osc_crop_" + timeStamp + "." + ext;
// 裁剪头像的绝对路径
protraitPath = FILE_SAVEPATH + cropFileName;
protraitFile = new File(protraitPath);
cropUri = Uri.fromFile(protraitFile);
return this.cropUri;
}
// 拍照保存的绝对路径
private Uri getCameraTempFile() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File savedir = new File(FILE_SAVEPATH);
if (!savedir.exists()) {
savedir.mkdirs();
}
} else {
// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像,请检查SD卡是否挂载");
return null;
}
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
// 照片命名
String cropFileName = "lican_camera_" + timeStamp + ".jpg";
// 裁剪头像的绝对路径
protraitPath = FILE_SAVEPATH + cropFileName;
protraitFile = new File(protraitPath);
cropUri = Uri.fromFile(protraitFile);
this.origUri = this.cropUri;
return this.cropUri;
}
/**
* 操作选择
*
* @param items
*/
public void imageChooseItem(CharSequence[] items) {
AlertDialog imageDialog = new AlertDialog.Builder(this)
.setTitle("上传头像")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// 相册选图
if (item == 0) {
startImagePick();
}
// 手机拍照
else if (item == 1) {
startActionCamera();
}
}
}).create();
imageDialog.show();
}
/**
* 选择图片裁剪
*
* @param output
*/
private void startImagePick() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"),
ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
}
/**
* 相机拍照
*
* @param output
*/
private void startActionCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
startActivityForResult(intent,
ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
}
/**
* 拍照后裁剪
*
* @param data
* 原始图片
* @param output
* 裁剪后图片
*/
private void startActionCrop(Uri data) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data, "image/*");
intent.putExtra("output", this.getUploadTempFile(data));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", CROP);// 输出图片大小
intent.putExtra("outputY", CROP);
intent.putExtra("scale", true);// 去黑边
intent.putExtra("scaleUpIfNeeded", true);// 去黑边
startActivityForResult(intent,
ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
}
private void uploadNewPhoto() {
// 将图片展现在页面上
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
img.setImageBitmap(protraitBitmap);
} else {
Log.i("camera_test", "can not get bitmap");
}
}
};
new Thread() {
public void run() {
Message msg = new Message();
if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
protraitBitmap = ImageUtils
.loadImgThumbnail(protraitPath, 200, 200);
msg.what = 1;
} else {
msg.what = -1;
}
handler.sendMessage(msg);
}
}.start();
}
@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
startActionCrop(origUri);// 拍照后裁剪
break;
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
startActionCrop(data.getData());// 选图后裁剪
break;
case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
uploadNewPhoto();// 上传新照片
break;
}
}
}
| UTF-8 | Java | 8,613 | java | Main.java | Java | [
{
"context": "dget.ImageView;\r\n\r\n/**\r\n * 应用程序首页\r\n * \r\n * @author alfred\r\n * \r\n */\r\npublic class Main extends BaseSlidingF",
"end": 951,
"score": 0.9991560578346252,
"start": 945,
"tag": "USERNAME",
"value": "alfred"
}
] | null | [] | package me.lican.app.ui;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import me.lican.app.AppContext;
import me.lican.app.R;
import me.lican.app.common.BitmapManager;
import me.lican.app.common.FileUtils;
import me.lican.app.common.ImageUtils;
import me.lican.app.common.StringUtils;
import me.lican.app.common.UIHelper;
import me.lican.app.ui.base.BaseSlidingFragmentActivity;
import me.lican.app.ui.slidingmenu.SlidingMenu;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
/**
* 应用程序首页
*
* @author alfred
*
*/
public class Main extends BaseSlidingFragmentActivity {
private SlidingMenu sm;
private AppContext appContext;// 全局Context
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// TODO 广播处理
initSlidingMenu();
// above_slidingmenu 右侧主页面的样式
// setContentView(R.layout.above_slidingmenu);
setContentView(R.layout.main);
appContext = (AppContext) getApplication();
// 网络连接判断
if (!appContext.isNetworkConnected()) {
// UIHelper.ToastMessage(this, R.string.network_not_connected);
}
// 初始化登录
appContext.initLoginInfo();
imageTest();
cameraTest();
}
private void initSlidingMenu() {
// behind_slidingmenu 侧边栏的样式
setBehindContentView(R.layout.behind_slidingmenu);
// customize the SlidingMenu
// TODO 阅读SlidingMenu,设置个性化的边栏
// TODO 取消SlidingMenu的log输出
sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
// sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// image test memebers
private BitmapManager bmpManager;
private ImageView img;
private String url = "http://images.sohu.com/bill/s2013/waptest/v3/banner/1024/ms-banner.jpg";
private String err = "err";
public void imageTest() {
// 获取网络图片,并展示,使用bitmapManager
img = (ImageView) findViewById(R.id.test_img);
UIHelper.showLoadImage(img, url, err);
}
// camera test members
private final static int CROP = 200;
private Button editer;
private final static String FILE_SAVEPATH = Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Lican/Portrait/";
private String album = "图库";
private String camera = "相机";
private Uri origUri;
private Uri cropUri;
private File protraitFile;
private Bitmap protraitBitmap;
private String protraitPath;
public void cameraTest() {
editer = (Button) findViewById(R.id.user_info_editer);
editer.setOnClickListener(editerClickListener);
}
private View.OnClickListener editerClickListener = new View.OnClickListener() {
public void onClick(View v) {
CharSequence[] items = { album, camera };
imageChooseItem(items);
}
};
// 裁剪头像的绝对路径
private Uri getUploadTempFile(Uri uri) {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File savedir = new File(FILE_SAVEPATH);
if (!savedir.exists()) {
savedir.mkdirs();
}
} else {
// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像,请检查SD卡是否挂载");
return null;
}
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);
// 如果是标准Uri
if (StringUtils.isEmpty(thePath)) {
thePath = ImageUtils.getAbsoluteImagePath(this, uri);
}
String ext = FileUtils.getFileFormat(thePath);
ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
// 照片命名
String cropFileName = "osc_crop_" + timeStamp + "." + ext;
// 裁剪头像的绝对路径
protraitPath = FILE_SAVEPATH + cropFileName;
protraitFile = new File(protraitPath);
cropUri = Uri.fromFile(protraitFile);
return this.cropUri;
}
// 拍照保存的绝对路径
private Uri getCameraTempFile() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File savedir = new File(FILE_SAVEPATH);
if (!savedir.exists()) {
savedir.mkdirs();
}
} else {
// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像,请检查SD卡是否挂载");
return null;
}
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
// 照片命名
String cropFileName = "lican_camera_" + timeStamp + ".jpg";
// 裁剪头像的绝对路径
protraitPath = FILE_SAVEPATH + cropFileName;
protraitFile = new File(protraitPath);
cropUri = Uri.fromFile(protraitFile);
this.origUri = this.cropUri;
return this.cropUri;
}
/**
* 操作选择
*
* @param items
*/
public void imageChooseItem(CharSequence[] items) {
AlertDialog imageDialog = new AlertDialog.Builder(this)
.setTitle("上传头像")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// 相册选图
if (item == 0) {
startImagePick();
}
// 手机拍照
else if (item == 1) {
startActionCamera();
}
}
}).create();
imageDialog.show();
}
/**
* 选择图片裁剪
*
* @param output
*/
private void startImagePick() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"),
ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
}
/**
* 相机拍照
*
* @param output
*/
private void startActionCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
startActivityForResult(intent,
ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
}
/**
* 拍照后裁剪
*
* @param data
* 原始图片
* @param output
* 裁剪后图片
*/
private void startActionCrop(Uri data) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data, "image/*");
intent.putExtra("output", this.getUploadTempFile(data));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", CROP);// 输出图片大小
intent.putExtra("outputY", CROP);
intent.putExtra("scale", true);// 去黑边
intent.putExtra("scaleUpIfNeeded", true);// 去黑边
startActivityForResult(intent,
ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
}
private void uploadNewPhoto() {
// 将图片展现在页面上
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
img.setImageBitmap(protraitBitmap);
} else {
Log.i("camera_test", "can not get bitmap");
}
}
};
new Thread() {
public void run() {
Message msg = new Message();
if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
protraitBitmap = ImageUtils
.loadImgThumbnail(protraitPath, 200, 200);
msg.what = 1;
} else {
msg.what = -1;
}
handler.sendMessage(msg);
}
}.start();
}
@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
startActionCrop(origUri);// 拍照后裁剪
break;
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
startActionCrop(data.getData());// 选图后裁剪
break;
case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
uploadNewPhoto();// 上传新照片
break;
}
}
}
| 8,613 | 0.680103 | 0.676662 | 302 | 24.943708 | 20.024656 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.258278 | false | false | 2 |
42363ce0402f2e4e11a7f431f69573eb4366c3f7 | 20,401,094,714,219 | dc886041f1a3a7a162216df625def0ac4a7e2c47 | /Basic/src/f_exception/Ex01_TryCatch.java | 8c404b31b0f665dd57dcde1527097addf1359f83 | [] | no_license | rkskdhs/Multicampus | https://github.com/rkskdhs/Multicampus | 4c15e99604f36cac8e108ee23f44e751775f79af | 60badb8e7d9272636ec11afd2ff25873c7b006c6 | refs/heads/master | 2020-03-24T17:09:33.408000 | 2018-08-30T08:10:47 | 2018-08-30T08:10:47 | 142,850,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package f_exception;
public class Ex01_TryCatch {
public static void main(String[] args) {
//오류 1. 에러:심각한 오류 2. 예외:심각하지 않은 오류->프로그램 비정상적인 종료
//예외처리-> 프로그램을 정사 종료까지 끌고가기 위함
String [] str = {"소고기", "양고기", "닭고기"};
try {
for(int i = 0; i<4; i++) {
System.out.print(str[i]);
}
System.out.println("예외구문 발생여지 구문");
return;
}catch(Exception ex) {
System.out.println("예외발생:" +ex.getMessage());
ex.printStackTrace();
}finally {
System.out.println("무조건 수행");
}
System.out.println("프로그램 종료");
}
} | UTF-8 | Java | 747 | java | Ex01_TryCatch.java | Java | [] | null | [] | package f_exception;
public class Ex01_TryCatch {
public static void main(String[] args) {
//오류 1. 에러:심각한 오류 2. 예외:심각하지 않은 오류->프로그램 비정상적인 종료
//예외처리-> 프로그램을 정사 종료까지 끌고가기 위함
String [] str = {"소고기", "양고기", "닭고기"};
try {
for(int i = 0; i<4; i++) {
System.out.print(str[i]);
}
System.out.println("예외구문 발생여지 구문");
return;
}catch(Exception ex) {
System.out.println("예외발생:" +ex.getMessage());
ex.printStackTrace();
}finally {
System.out.println("무조건 수행");
}
System.out.println("프로그램 종료");
}
} | 747 | 0.554593 | 0.544194 | 30 | 17.299999 | 16.957102 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.233333 | false | false | 2 |
a26cfe931e8081862e963fb96f245874c0fec4be | 17,652,315,589,092 | f28670a75818d86de2d1c92f03eb274fa0d5a5fb | /mars-rover/java/src/main/java/rover/Planet.java | d5d304a380797f807ea71b19fbb50e1c731e260c | [] | no_license | Ekito/coding-dojo | https://github.com/Ekito/coding-dojo | 3db331105375de982c1b500e77596de125e6c145 | 91f9434428f658065f9327e5517c2c3c2c8b7862 | refs/heads/master | 2020-12-11T03:40:00.801000 | 2016-04-07T15:05:09 | 2016-04-07T15:05:09 | 55,419,755 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rover;
import java.util.LinkedList;
import java.util.List;
/**
* Created by olivier on 10/03/16.
*/
public class Planet {
public final int size;
private List<Obstacle> obstacles = new LinkedList<>();
public Planet(int size) {
this.size = size;
}
public Planet() {
this(26);
}
public void add(Obstacle obstacle) {
this.obstacles.add(obstacle);
}
public boolean hasObstacle(int x, int y) {
return this.obstacles.contains(new Obstacle(x, y));
}
boolean exists(int x, int y) {
return x/ size != 0 || y/ size != 0;
}
}
| UTF-8 | Java | 621 | java | Planet.java | Java | [
{
"context": "kedList;\nimport java.util.List;\n\n/**\n * Created by olivier on 10/03/16.\n */\npublic class Planet {\n\n pu",
"end": 91,
"score": 0.7151470184326172,
"start": 87,
"tag": "USERNAME",
"value": "oliv"
},
{
"context": "st;\nimport java.util.List;\n\n/**\n * Created by... | null | [] | package rover;
import java.util.LinkedList;
import java.util.List;
/**
* Created by olivier on 10/03/16.
*/
public class Planet {
public final int size;
private List<Obstacle> obstacles = new LinkedList<>();
public Planet(int size) {
this.size = size;
}
public Planet() {
this(26);
}
public void add(Obstacle obstacle) {
this.obstacles.add(obstacle);
}
public boolean hasObstacle(int x, int y) {
return this.obstacles.contains(new Obstacle(x, y));
}
boolean exists(int x, int y) {
return x/ size != 0 || y/ size != 0;
}
}
| 621 | 0.590982 | 0.574879 | 34 | 17.264706 | 17.957972 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441176 | false | false | 2 |
61f0aa03bf941f4eb958526348ffa477b51e9e64 | 28,286,654,670,154 | 51b2825ebe53fc9179919698a45ba4ebf6a30539 | /12.JDBC&CRUD/BT/ManagerUser/src/main/java/controller/SearchUserServlet.java | fa7788e7ee06369e8fc2be4938e4ec1c48403126 | [] | no_license | NguyenHai-CodeGym/Module3 | https://github.com/NguyenHai-CodeGym/Module3 | 956605e4bd418eb31e2f702413f6601c804c4b48 | bfd0d05016f1dd1411822e94219455671ff63b4e | refs/heads/master | 2023-03-09T07:53:00.013000 | 2021-02-22T08:20:16 | 2021-02-22T08:20:16 | 330,913,586 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import model.User;
import service.UserServiceIpml;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "SearchUserServlet", urlPatterns = "/searchUser")
public class SearchUserServlet extends HttpServlet {
UserServiceIpml userServiceIpml = new UserServiceIpml();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CountryName = request.getParameter("search");
List<User> userList = new ArrayList<>();
try {
userList = userServiceIpml.findByCountry(CountryName);
request.setAttribute("users",userList);
RequestDispatcher dispatcher = request.getRequestDispatcher("search-user.jsp");
dispatcher.forward(request,response);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("search-user.jsp");
dispatcher.forward(request,response);
}
}
| UTF-8 | Java | 1,495 | java | SearchUserServlet.java | Java | [] | null | [] | package controller;
import model.User;
import service.UserServiceIpml;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "SearchUserServlet", urlPatterns = "/searchUser")
public class SearchUserServlet extends HttpServlet {
UserServiceIpml userServiceIpml = new UserServiceIpml();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CountryName = request.getParameter("search");
List<User> userList = new ArrayList<>();
try {
userList = userServiceIpml.findByCountry(CountryName);
request.setAttribute("users",userList);
RequestDispatcher dispatcher = request.getRequestDispatcher("search-user.jsp");
dispatcher.forward(request,response);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("search-user.jsp");
dispatcher.forward(request,response);
}
}
| 1,495 | 0.752508 | 0.752508 | 37 | 39.405407 | 30.608654 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.837838 | false | false | 2 |
4c1730807c52dc7fd543dc5b01623d6bc3373980 | 3,307,124,862,300 | b312e1002247c5e00586b9f206a97b53955fdd81 | /Workspace/apiProject/src/kh/java/api/Calc.java | 03a707c115ae5e1bbb93fff45213cb389e69051a | [] | no_license | Rkato1/WebProject | https://github.com/Rkato1/WebProject | 0301e3ec2728f5234028d5e982ab54fdd3cda99e | 6a38d9ce342747facbb0fdc6ac31212516631bad | refs/heads/master | 2023-04-27T09:21:06.193000 | 2021-05-12T01:42:30 | 2021-05-12T01:42:30 | 286,740,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kh.java.api;
import java.util.Scanner;
public class Calc {
public void main() {
Scanner sc = new Scanner(System.in);
System.out.print("첫번째 정수 입력 : ");
String num1 = sc.next();
System.out.print("두번째 정수 입력 : ");
String num2 = sc.next();
System.out.print("연산자 입력(+,-,*,/) : ");
String oper = sc.next();
Integer i = Integer.valueOf(num1);
Integer i1 = Integer.valueOf(num2);
Double d = Double.valueOf(num1);
switch(oper) {
case "+":
System.out.println(num1+oper+num2+"="+(i.intValue()+i1.intValue()));
break;
case "-":
System.out.println(num1+oper+num2+"="+(i.intValue()-i1.intValue()));
break;
case "*":
System.out.println(num1+oper+num2+"="+i.intValue()*i1.intValue());
break;
case "/":
System.out.println(num1+oper+num2+"="+d.doubleValue()/i1.intValue());
break;
default:
System.out.println("잘못된 연산자 입력");
break;
}
}
}
| UTF-8 | Java | 949 | java | Calc.java | Java | [] | null | [] | package kh.java.api;
import java.util.Scanner;
public class Calc {
public void main() {
Scanner sc = new Scanner(System.in);
System.out.print("첫번째 정수 입력 : ");
String num1 = sc.next();
System.out.print("두번째 정수 입력 : ");
String num2 = sc.next();
System.out.print("연산자 입력(+,-,*,/) : ");
String oper = sc.next();
Integer i = Integer.valueOf(num1);
Integer i1 = Integer.valueOf(num2);
Double d = Double.valueOf(num1);
switch(oper) {
case "+":
System.out.println(num1+oper+num2+"="+(i.intValue()+i1.intValue()));
break;
case "-":
System.out.println(num1+oper+num2+"="+(i.intValue()-i1.intValue()));
break;
case "*":
System.out.println(num1+oper+num2+"="+i.intValue()*i1.intValue());
break;
case "/":
System.out.println(num1+oper+num2+"="+d.doubleValue()/i1.intValue());
break;
default:
System.out.println("잘못된 연산자 입력");
break;
}
}
}
| 949 | 0.61676 | 0.596648 | 36 | 23.861111 | 20.639973 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.527778 | false | false | 2 |
5239a24b2b25f7532618f940b4cf1b8619531a28 | 28,467,043,284,949 | 701280fe421d57fb7207ad5534afcc86a265cd40 | /src/main/java/de/bit/cairo/jna/sample/CairoSample.java | 01c3e5818de9f7de4b6ecca84534d3e4c14a23e0 | [
"MIT"
] | permissive | bridgingIT/cairo-jna-sample | https://github.com/bridgingIT/cairo-jna-sample | 8a92a946e3d3581e673bac4814a634a18e6913c7 | baf0a7f76e854373c3bb0bec227f33db454a8106 | refs/heads/master | 2020-04-16T02:00:10.883000 | 2016-10-06T15:24:11 | 2016-10-06T15:24:11 | 67,986,949 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.bit.cairo.jna.sample;
import cairo.CairoLibrary;
import cairo.CairoMatrix;
import cairo.CairoSurface;
import cairo.Cairo;
public class CairoSample {
public static void main(String[] args) {
int width = 273;
int height = 115;
CairoLibrary cairoLib = CairoLibrary.INSTANCE;
try (CairoSurface surface = cairoLib.cairo_image_surface_create(CairoLibrary.cairo_format_t.CAIRO_FORMAT_ARGB32,
width, height)) {
try (Cairo cr = cairoLib.cairo_create(surface)) {
cairoLib.cairo_set_source_rgb(cr, 1, 1, 1);
cairoLib.cairo_rectangle(cr, 0, 0, width, height);
cairoLib.cairo_fill(cr);
int[] rows = { 3, 3, 2, 2, 3, 3 };
int[] horizontalOffset = { 10, 47, 84, 164, 201, 238 };
int[] verticalOffset = { 10, 45, 80 };
int rectSize = 25;
cairoLib.cairo_set_source_rgb(cr, 0.5859375, 0.7421875, 0.859375);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < rows[i]; j++) {
cairoLib.cairo_rectangle(cr, horizontalOffset[i], verticalOffset[j], rectSize, rectSize);
cairoLib.cairo_fill(cr);
}
}
cairoLib.cairo_set_source_rgb(cr, 0.8823529412, 0.0, 0.1960784314);
try (CairoMatrix transformMatrix = new CairoMatrix()) {
cairoLib.cairo_matrix_init_identity(transformMatrix);
cairoLib.cairo_matrix_translate(transformMatrix, 136.5, 19.5);
cairoLib.cairo_matrix_rotate(transformMatrix, -17.4 * Math.PI / 180);
cairoLib.cairo_transform(cr, transformMatrix);
}
cairoLib.cairo_rectangle(cr, -12.5, -12.5, rectSize, rectSize);
cairoLib.cairo_fill(cr);
cairoLib.cairo_surface_write_to_png(surface, "target/bit.png");
}
}
}
} | UTF-8 | Java | 1,645 | java | CairoSample.java | Java | [] | null | [] | package de.bit.cairo.jna.sample;
import cairo.CairoLibrary;
import cairo.CairoMatrix;
import cairo.CairoSurface;
import cairo.Cairo;
public class CairoSample {
public static void main(String[] args) {
int width = 273;
int height = 115;
CairoLibrary cairoLib = CairoLibrary.INSTANCE;
try (CairoSurface surface = cairoLib.cairo_image_surface_create(CairoLibrary.cairo_format_t.CAIRO_FORMAT_ARGB32,
width, height)) {
try (Cairo cr = cairoLib.cairo_create(surface)) {
cairoLib.cairo_set_source_rgb(cr, 1, 1, 1);
cairoLib.cairo_rectangle(cr, 0, 0, width, height);
cairoLib.cairo_fill(cr);
int[] rows = { 3, 3, 2, 2, 3, 3 };
int[] horizontalOffset = { 10, 47, 84, 164, 201, 238 };
int[] verticalOffset = { 10, 45, 80 };
int rectSize = 25;
cairoLib.cairo_set_source_rgb(cr, 0.5859375, 0.7421875, 0.859375);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < rows[i]; j++) {
cairoLib.cairo_rectangle(cr, horizontalOffset[i], verticalOffset[j], rectSize, rectSize);
cairoLib.cairo_fill(cr);
}
}
cairoLib.cairo_set_source_rgb(cr, 0.8823529412, 0.0, 0.1960784314);
try (CairoMatrix transformMatrix = new CairoMatrix()) {
cairoLib.cairo_matrix_init_identity(transformMatrix);
cairoLib.cairo_matrix_translate(transformMatrix, 136.5, 19.5);
cairoLib.cairo_matrix_rotate(transformMatrix, -17.4 * Math.PI / 180);
cairoLib.cairo_transform(cr, transformMatrix);
}
cairoLib.cairo_rectangle(cr, -12.5, -12.5, rectSize, rectSize);
cairoLib.cairo_fill(cr);
cairoLib.cairo_surface_write_to_png(surface, "target/bit.png");
}
}
}
} | 1,645 | 0.666869 | 0.599392 | 53 | 30.056604 | 28.115271 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.735849 | false | false | 2 |
591943dc18fd396f0a30ab4a5fb150c6e218cd31 | 18,399,639,941,612 | 051568531bd0beb2524190397b4b9052f52c56be | /src/test/java/org/atlasapi/equiv/EquivalenceRecordSerializerTest.java | cd59f4676911c8825f2ab7444f2dd6c8612ca895 | [] | no_license | jamiepg1/atlas-cassandra | https://github.com/jamiepg1/atlas-cassandra | 186d26d495e636ae59bcb8a785e3eb9709cf1afb | 3b5d4fea3141d482df0717cb87b606b1a7bcdba8 | refs/heads/master | 2017-12-02T20:35:59.663000 | 2014-11-11T05:15:49 | 2014-11-11T05:15:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.atlasapi.equiv;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import org.atlasapi.equiv.EquivalenceRecord;
import org.atlasapi.equiv.EquivalenceRecordSerializer;
import org.atlasapi.equiv.EquivalenceRef;
import org.atlasapi.media.common.Id;
import org.atlasapi.media.common.Serializer;
import org.atlasapi.media.content.Content;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Publisher;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class EquivalenceRecordSerializerTest {
private Serializer<EquivalenceRecord, byte[]> serializer
= new EquivalenceRecordSerializer();
@Test
public void testDeSerializesEquivalenceRecord() {
EquivalenceRecord record = record(1234L, Publisher.METABROADCAST)
.copyWithGeneratedAdjacent(ImmutableList.of(ref(1235, Publisher.BBC)))
.copyWithExplicitAdjacent(ImmutableList.of(ref(1236, Publisher.PA)))
.copyWithEquivalents(ImmutableList.of(ref(1237, Publisher.C4)));
EquivalenceRecord deserialized = serializer.deserialize(serializer.serialize(record));
assertThat(deserialized.getId(), is(deserialized.getId()));
assertThat(deserialized.getPublisher(), is(deserialized.getPublisher()));
assertThat(deserialized.getCreated(), is(deserialized.getCreated()));
assertThat(deserialized.getUpdated(), is(deserialized.getUpdated()));
assertThat(deserialized.getGeneratedAdjacents(), is(deserialized.getGeneratedAdjacents()));
assertThat(deserialized.getExplicitAdjacents(), is(deserialized.getExplicitAdjacents()));
assertThat(deserialized.getEquivalents(), is(deserialized.getEquivalents()));
}
private EquivalenceRecord record(long id, Publisher source) {
Content content = new Episode();
content.setId(id);
content.setPublisher(source);
EquivalenceRecord record = EquivalenceRecord.valueOf(content);
return record;
}
private EquivalenceRef ref(int id, Publisher source) {
return new EquivalenceRef(Id.valueOf(id), source);
}
}
| UTF-8 | Java | 2,196 | java | EquivalenceRecordSerializerTest.java | Java | [] | null | [] | package org.atlasapi.equiv;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import org.atlasapi.equiv.EquivalenceRecord;
import org.atlasapi.equiv.EquivalenceRecordSerializer;
import org.atlasapi.equiv.EquivalenceRef;
import org.atlasapi.media.common.Id;
import org.atlasapi.media.common.Serializer;
import org.atlasapi.media.content.Content;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Publisher;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class EquivalenceRecordSerializerTest {
private Serializer<EquivalenceRecord, byte[]> serializer
= new EquivalenceRecordSerializer();
@Test
public void testDeSerializesEquivalenceRecord() {
EquivalenceRecord record = record(1234L, Publisher.METABROADCAST)
.copyWithGeneratedAdjacent(ImmutableList.of(ref(1235, Publisher.BBC)))
.copyWithExplicitAdjacent(ImmutableList.of(ref(1236, Publisher.PA)))
.copyWithEquivalents(ImmutableList.of(ref(1237, Publisher.C4)));
EquivalenceRecord deserialized = serializer.deserialize(serializer.serialize(record));
assertThat(deserialized.getId(), is(deserialized.getId()));
assertThat(deserialized.getPublisher(), is(deserialized.getPublisher()));
assertThat(deserialized.getCreated(), is(deserialized.getCreated()));
assertThat(deserialized.getUpdated(), is(deserialized.getUpdated()));
assertThat(deserialized.getGeneratedAdjacents(), is(deserialized.getGeneratedAdjacents()));
assertThat(deserialized.getExplicitAdjacents(), is(deserialized.getExplicitAdjacents()));
assertThat(deserialized.getEquivalents(), is(deserialized.getEquivalents()));
}
private EquivalenceRecord record(long id, Publisher source) {
Content content = new Episode();
content.setId(id);
content.setPublisher(source);
EquivalenceRecord record = EquivalenceRecord.valueOf(content);
return record;
}
private EquivalenceRef ref(int id, Publisher source) {
return new EquivalenceRef(Id.valueOf(id), source);
}
}
| 2,196 | 0.731785 | 0.724044 | 55 | 38.927273 | 30.564302 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 2 |
57d50643bff1962241584b04937961cc847f5241 | 27,333,171,925,092 | 1c05388e35fda29797576d62c379b66124ec7896 | /src/com/intermediate/classesandobjects/BasketballPlayer.java | ba1fadc7395a727440ff4cd1b3b0dd63191ec8b1 | [] | no_license | kon3ktor/complete-java-course | https://github.com/kon3ktor/complete-java-course | 44bb797529f11355984055a0696f91428cec8e16 | 3d5a61f357ce344d87d7b3e2569ce7f864a514fa | refs/heads/master | 2023-07-23T15:15:40.623000 | 2023-07-06T13:49:33 | 2023-07-06T13:49:33 | 236,841,794 | 93 | 81 | null | false | 2022-09-20T12:42:46 | 2020-01-28T21:07:48 | 2022-09-18T06:40:03 | 2022-08-08T17:53:03 | 83 | 58 | 56 | 1 | Java | false | false | package com.intermediate.classesandobjects;
import java.util.Random;
public class BasketballPlayer {
private String name;
private String nickname;
private int yearOfBorn;
private String team;
private double freeThrowPercentage;
private double pointsPerGame;
private int gamesPlayed;
public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
this.name = name;
this.nickname = nickname;
this.yearOfBorn = yearOfBorn;
this.team = team;
this.freeThrowPercentage = freeThrowPercentage;
this.pointsPerGame = pointsPerGame;
this.gamesPlayed = gamesPlayed;
}
public void freeThrow(){
Random randomNumberGenerator = new Random();
if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
System.out.println(name + " failed to score free throw.");
} else {
System.out.println(name + " scored free throw.");
}
}
}
| UTF-8 | Java | 1,072 | java | BasketballPlayer.java | Java | [
{
"context": "\n this.name = name;\n this.nickname = nickname;\n this.yearOfBorn = yearOfBorn;\n th",
"end": 530,
"score": 0.989610493183136,
"start": 522,
"tag": "USERNAME",
"value": "nickname"
}
] | null | [] | package com.intermediate.classesandobjects;
import java.util.Random;
public class BasketballPlayer {
private String name;
private String nickname;
private int yearOfBorn;
private String team;
private double freeThrowPercentage;
private double pointsPerGame;
private int gamesPlayed;
public BasketballPlayer(String name, String nickname, int yearOfBorn, String team, double freeThrowPercentage, double pointsPerGame, int gamesPlayed) {
this.name = name;
this.nickname = nickname;
this.yearOfBorn = yearOfBorn;
this.team = team;
this.freeThrowPercentage = freeThrowPercentage;
this.pointsPerGame = pointsPerGame;
this.gamesPlayed = gamesPlayed;
}
public void freeThrow(){
Random randomNumberGenerator = new Random();
if((randomNumberGenerator.nextDouble() * 100) > freeThrowPercentage) {
System.out.println(name + " failed to score free throw.");
} else {
System.out.println(name + " scored free throw.");
}
}
}
| 1,072 | 0.675373 | 0.672575 | 34 | 30.529411 | 29.933491 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735294 | false | false | 2 |
24e0471ac01f78c90f9aaa6d8f1b4559eaf6a70a | 21,388,937,145,472 | fc389a2ac1aeb7b636a725bbb899917597cc72aa | /src/headfirst/designpatterns/observer/simple/MsgSubscriber2.java | 067bf508c130245e66604d56e2d05f9260ad41ab | [] | no_license | harilok512/week1-assignment | https://github.com/harilok512/week1-assignment | f5f80f6cdf5bc768ec30066e24638d781ec0d93d | 9792895f1712493b219c121508b3344e8cf07c67 | refs/heads/main | 2023-08-02T05:38:03.310000 | 2021-10-01T15:35:42 | 2021-10-01T15:35:42 | 406,037,662 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package headfirst.designpatterns.observer.simple;
public class MsgSubscriber2 implements Observer {
@Override
public void update(Message m) {
System.out.println("MessageSubscriberTwo :: " + m.getMessageContent());
}
}
| UTF-8 | Java | 236 | java | MsgSubscriber2.java | Java | [] | null | [] | package headfirst.designpatterns.observer.simple;
public class MsgSubscriber2 implements Observer {
@Override
public void update(Message m) {
System.out.println("MessageSubscriberTwo :: " + m.getMessageContent());
}
}
| 236 | 0.733051 | 0.728814 | 8 | 28.5 | 27.147743 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 2 |
521d81ddd67545960744aa1314570f6a18d33891 | 30,614,526,891,032 | a2fc79a6f2562f57bbb1ee2354eefae76fe091f6 | /src/main/java/kz/epam/action/DomAction.java | 665ebac47d78b00a184fe5208582d48a7854b32c | [] | no_license | kazrulit/xmlParser | https://github.com/kazrulit/xmlParser | bc069a32e492f06d12eaea9cce019554049d1c28 | 84adf2616ca19fbbb377fb295715096b140258e0 | refs/heads/master | 2021-01-10T08:49:24.465000 | 2015-11-20T07:44:10 | 2015-11-20T07:44:10 | 46,324,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kz.epam.action;
import kz.epam.configs.Configs;
import kz.epam.entity.Category;
import kz.epam.service.DOMFactoryService;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class DomAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
DOMFactoryService domFactoryService = new DOMFactoryService();
domFactoryService.runParser();
List<Category> shopList = domFactoryService.getShopList();
request.setAttribute(Configs.SHOP_LIST, shopList);
return mapping.findForward(Configs.SUCCESS);
}
}
| UTF-8 | Java | 929 | java | DomAction.java | Java | [] | null | [] | package kz.epam.action;
import kz.epam.configs.Configs;
import kz.epam.entity.Category;
import kz.epam.service.DOMFactoryService;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class DomAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
DOMFactoryService domFactoryService = new DOMFactoryService();
domFactoryService.runParser();
List<Category> shopList = domFactoryService.getShopList();
request.setAttribute(Configs.SHOP_LIST, shopList);
return mapping.findForward(Configs.SUCCESS);
}
}
| 929 | 0.787944 | 0.787944 | 25 | 36.16 | 31.212408 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 2 |
2dc54888c7e4f7b1fa45bd02e14e5a564a7a8d8c | 10,522,669,933,998 | 32eada593838f463588281ca55639b7a9096c17b | /src/walgreens/ecom/gqm/factory/BOfactory.java | 6a6e6d9d46f87ce71fbc4c24cf3702d292de51cd | [] | no_license | progsri/GQM_2.0 | https://github.com/progsri/GQM_2.0 | 0d85fe86edbf94960a05b8372297766ab09fc5e6 | f07a6750bf3f5b7415a008363dde7a2ed6f11d8c | refs/heads/master | 2016-09-05T18:39:57.391000 | 2015-08-31T20:47:45 | 2015-08-31T20:47:45 | 41,696,384 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package walgreens.ecom.gqm.factory;
import walgreens.ecom.gqm.bo.InternetBO;
import walgreens.ecom.gqm.bo.ProductBO;
public class BOfactory {
private InternetBO internetBO;
private ProductBO productBO;
public BOfactory() {
if ( internetBO == null ) {
setInternetBO(new InternetBO());
}
if( productBO == null) {
setProductBO(new ProductBO());
}
}
public InternetBO getInternetBO() {
return internetBO;
}
private void setInternetBO(InternetBO internetBO) {
this.internetBO = internetBO;
}
public ProductBO getProductBO() {
return productBO;
}
private void setProductBO(ProductBO productBO) {
this.productBO = productBO;
}
}
| UTF-8 | Java | 682 | java | BOfactory.java | Java | [] | null | [] | package walgreens.ecom.gqm.factory;
import walgreens.ecom.gqm.bo.InternetBO;
import walgreens.ecom.gqm.bo.ProductBO;
public class BOfactory {
private InternetBO internetBO;
private ProductBO productBO;
public BOfactory() {
if ( internetBO == null ) {
setInternetBO(new InternetBO());
}
if( productBO == null) {
setProductBO(new ProductBO());
}
}
public InternetBO getInternetBO() {
return internetBO;
}
private void setInternetBO(InternetBO internetBO) {
this.internetBO = internetBO;
}
public ProductBO getProductBO() {
return productBO;
}
private void setProductBO(ProductBO productBO) {
this.productBO = productBO;
}
}
| 682 | 0.708211 | 0.708211 | 41 | 15.634147 | 16.490583 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.390244 | false | false | 2 |
06258e55ab3528f2dd2eb43d77d66db9fed5b319 | 1,108,101,578,997 | 7b342af6147f1691ee7dae282e4c41e2877caf97 | /test/cais220project/CAIS220ProjectTest.java | 4f3d3af5a7a3572dc1cd824869f8cdcd9770a97b | [] | no_license | lhayesgolding/EarthquakeData | https://github.com/lhayesgolding/EarthquakeData | f4b62c06618c4f039a489e267d8cb8db4e98767b | 9016a1aac0344d002d004c6cdbe7c69b1d877899 | refs/heads/master | 2020-07-17T03:46:28.922000 | 2019-09-02T21:53:18 | 2019-09-02T21:53:18 | 205,935,018 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Westfield State University: CAIS 220: Program Design II
* @author Liz Hayes-Golding (ehayesgolding0123@westfield.ma.edu)
* Created Dec 12, 2017 2:01:11 PM
*
*/
package cais220project;
import javafx.stage.Stage;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author lizhayes-golding
*/
public class CAIS220ProjectTest {
public CAIS220ProjectTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of start method, of class CAIS220Project.
*/
@Test
public void testStart() {
System.out.println("start");
Stage primaryStage = null;
CAIS220Project instance = new CAIS220Project();
instance.start(primaryStage);
// Do I need this JUnit test? What do I need to test for?
}
}
| UTF-8 | Java | 1,098 | java | CAIS220ProjectTest.java | Java | [
{
"context": "University: CAIS 220: Program Design II\n * @author Liz Hayes-Golding (ehayesgolding0123@westfield.ma.edu)\n * Created D",
"end": 90,
"score": 0.9998019933700562,
"start": 73,
"tag": "NAME",
"value": "Liz Hayes-Golding"
},
{
"context": ": Program Design II\n * @author L... | null | [] | /*
* Westfield State University: CAIS 220: Program Design II
* @author <NAME> (<EMAIL>)
* Created Dec 12, 2017 2:01:11 PM
*
*/
package cais220project;
import javafx.stage.Stage;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author lizhayes-golding
*/
public class CAIS220ProjectTest {
public CAIS220ProjectTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of start method, of class CAIS220Project.
*/
@Test
public void testStart() {
System.out.println("start");
Stage primaryStage = null;
CAIS220Project instance = new CAIS220Project();
instance.start(primaryStage);
// Do I need this JUnit test? What do I need to test for?
}
}
| 1,060 | 0.634791 | 0.602004 | 55 | 18.963636 | 17.914913 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.254545 | false | false | 2 |
9e747f7fcb6ebddc6f3d09a647eb0423c7882c9f | 31,052,613,571,600 | 3530ad51ea6ea56b7b692ad9103f07373157ce5b | /app/src/main/java/com/example/jeancarlos/snapfootball/Database/FirebaseHelper.java | e3c26d27e9eb005fb059bbf46fde5af71e951fb2 | [] | no_license | jeanslikecodes/snapfootball | https://github.com/jeanslikecodes/snapfootball | 07fcca10cef00dc0bcfa7e08d344319966c4de82 | bb9b17d5ea566efdbdb54c37a31c4a852797e202 | refs/heads/master | 2023-08-16T23:50:50.773000 | 2017-06-06T23:21:00 | 2017-06-06T23:21:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jeancarlos.snapfootball.Database;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.example.jeancarlos.snapfootball.Adapter.AnuncioAdapter;
import com.example.jeancarlos.snapfootball.Model.Anuncio;
import com.example.jeancarlos.snapfootball.Model.Usuario;
import com.example.jeancarlos.snapfootball.My_Interface.RecyclerViewOnClickListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
/**
* Created by Jean Carlos on 05/06/2017.
*/
public class FirebaseHelper {
Context context;
RecyclerView listView;
DatabaseReference rootRef;
ArrayList<Anuncio> receitaList= new ArrayList<>();
AnuncioAdapter adapter;
RecyclerViewOnClickListener recyclerViewOnClickListener;
public FirebaseHelper(Context context, RecyclerViewOnClickListener recyclerViewOnClickListener, RecyclerView listView)
{
this.recyclerViewOnClickListener = recyclerViewOnClickListener;
this.context= context;
this.listView= listView;
rootRef= FirebaseDatabase.getInstance().getReference();
}
public FirebaseHelper(Context context)
{
this.context= context;
rootRef= FirebaseDatabase.getInstance().getReference("users");
}
/*public void saveData(String nome, String ingredientes, String modoPreparo, Integer tempoPreparo,
Float nivelDificuldade, Integer quantidadePorcoes, String caminhoFoto) {
String id = rootRef.push().getKey();
Anuncio receita= new Anuncio(id, nome, ingredientes, modoPreparo, tempoPreparo,
nivelDificuldade, quantidadePorcoes, caminhoFoto);
rootRef.child("receita").push().setValue(receita);
}
public void saveData(String nome, Float nivelDificuldade) {
/* String id = rootRef.push().getKey();
Receita receita= new Receita(id, nome, nivelDificuldade);
rootRef.child(id).setValue(receita);
} */
public void saveData(Usuario usuario) {
if (usuario.getId_usuario()!=null){
rootRef.child(usuario.getId_usuario()).setValue(usuario);
}
else{
String id = rootRef.push().getKey();
usuario.setId_usuario(id);
rootRef.child(id).setValue(usuario);
}
}
/*public void refreshData()
{
rootRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError firebaseError) {
}
});
}
/*public void getUpdates(DataSnapshot dataSnapshot){
receitaList.clear();
for(DataSnapshot ds :dataSnapshot.getChildren()){
Receita receita= new Receita();
receita.setId(ds.getValue(Receita.class).getId());
receita.setNome(ds.getValue(Receita.class).getNome());
receita.setNivelDificuldade(ds.getValue(Receita.class).getNivelDificuldade());
receitaList.add(receita);
}
if(receitaList.size()>0){
adapter = new ReceitaAdapter(context, receitaList);
adapter.setRecyclerViewOnClickListener(recyclerViewOnClickListener);
listView.setAdapter(adapter);
}else {
Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
}
}
public static void deleteData(String id) {
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("receita").child(id);
//removendo receita
dR.removeValue();
} */
}
| UTF-8 | Java | 4,300 | java | FirebaseHelper.java | Java | [
{
"context": "e;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Jean Carlos on 05/06/2017.\n */\n\npublic class FirebaseHelper {",
"end": 728,
"score": 0.9998554587364197,
"start": 717,
"tag": "NAME",
"value": "Jean Carlos"
}
] | null | [] | package com.example.jeancarlos.snapfootball.Database;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.example.jeancarlos.snapfootball.Adapter.AnuncioAdapter;
import com.example.jeancarlos.snapfootball.Model.Anuncio;
import com.example.jeancarlos.snapfootball.Model.Usuario;
import com.example.jeancarlos.snapfootball.My_Interface.RecyclerViewOnClickListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
/**
* Created by <NAME> on 05/06/2017.
*/
public class FirebaseHelper {
Context context;
RecyclerView listView;
DatabaseReference rootRef;
ArrayList<Anuncio> receitaList= new ArrayList<>();
AnuncioAdapter adapter;
RecyclerViewOnClickListener recyclerViewOnClickListener;
public FirebaseHelper(Context context, RecyclerViewOnClickListener recyclerViewOnClickListener, RecyclerView listView)
{
this.recyclerViewOnClickListener = recyclerViewOnClickListener;
this.context= context;
this.listView= listView;
rootRef= FirebaseDatabase.getInstance().getReference();
}
public FirebaseHelper(Context context)
{
this.context= context;
rootRef= FirebaseDatabase.getInstance().getReference("users");
}
/*public void saveData(String nome, String ingredientes, String modoPreparo, Integer tempoPreparo,
Float nivelDificuldade, Integer quantidadePorcoes, String caminhoFoto) {
String id = rootRef.push().getKey();
Anuncio receita= new Anuncio(id, nome, ingredientes, modoPreparo, tempoPreparo,
nivelDificuldade, quantidadePorcoes, caminhoFoto);
rootRef.child("receita").push().setValue(receita);
}
public void saveData(String nome, Float nivelDificuldade) {
/* String id = rootRef.push().getKey();
Receita receita= new Receita(id, nome, nivelDificuldade);
rootRef.child(id).setValue(receita);
} */
public void saveData(Usuario usuario) {
if (usuario.getId_usuario()!=null){
rootRef.child(usuario.getId_usuario()).setValue(usuario);
}
else{
String id = rootRef.push().getKey();
usuario.setId_usuario(id);
rootRef.child(id).setValue(usuario);
}
}
/*public void refreshData()
{
rootRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError firebaseError) {
}
});
}
/*public void getUpdates(DataSnapshot dataSnapshot){
receitaList.clear();
for(DataSnapshot ds :dataSnapshot.getChildren()){
Receita receita= new Receita();
receita.setId(ds.getValue(Receita.class).getId());
receita.setNome(ds.getValue(Receita.class).getNome());
receita.setNivelDificuldade(ds.getValue(Receita.class).getNivelDificuldade());
receitaList.add(receita);
}
if(receitaList.size()>0){
adapter = new ReceitaAdapter(context, receitaList);
adapter.setRecyclerViewOnClickListener(recyclerViewOnClickListener);
listView.setAdapter(adapter);
}else {
Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
}
}
public static void deleteData(String id) {
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("receita").child(id);
//removendo receita
dR.removeValue();
} */
}
| 4,295 | 0.666744 | 0.664419 | 133 | 31.330828 | 29.246868 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.556391 | false | false | 2 |
aa270685ff26e849b8f54a33274362b20e13ec04 | 17,059,610,107,619 | c98c136e0716c044f91db9207ed8256c209bea67 | /app/src/main/java/cn/yznu/gdmapoperate/ui/activity/ElectricFenceActivity.java | c8ece01baefc1962685fc1d4c35d5411d497ccb6 | [] | no_license | brycegao/GDMapOperate | https://github.com/brycegao/GDMapOperate | d501e5cb54380581270b6e1f9dd9c39e493cfa72 | eebf0ceb435a0986221017c7f0ebf0abbfc2e4f9 | refs/heads/master | 2020-06-16T07:32:58.419000 | 2019-07-06T07:59:27 | 2019-07-06T07:59:27 | 195,513,534 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.yznu.gdmapoperate.ui.activity;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.Button;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import cn.yznu.gdmapoperate.ui.widget.MarkSizeView;
import cn.yznu.gdmapoperate.R;
public class ElectricFenceActivity extends AppCompatActivity {
private AMap aMap;
private MarkSizeView markSizeView;
private AppCompatTextView txtTips;
private Button btnPaint;
private Projection projection;
private Polygon polygon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_electric_fence);
MapView mapView = (MapView) findViewById(R.id.map_view);
markSizeView = (MarkSizeView) findViewById(R.id.mark_size);
txtTips = (AppCompatTextView) findViewById(R.id.capture_tips);
btnPaint = (Button) findViewById(R.id.btn_paint);
mapView.onCreate(savedInstanceState);
aMap = mapView.getMap();
projection = aMap.getProjection();
initView();
}
/**
* 初始化视图
*/
private void initView() {
markSizeView.setVisibility(View.GONE);
txtTips.setVisibility(View.GONE);
btnPaint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
markSizeView.setVisibility(View.VISIBLE);
txtTips.setVisibility(View.VISIBLE);
}
});
//负责将屏幕位置和地理坐标(经纬度)进行转换。屏幕位置是相对地图的左上角的位置
markSizeView.setmOnClickListener(new MarkSizeView.onClickListener() {//绘制矩形围栏
@Override
public void onConfirm(Rect markedArea) {
Point pointTopLeft = new Point(markedArea.left, markedArea.top);
LatLng topLef = projection.fromScreenLocation(pointTopLeft);
Point pointTopRight = new Point(markedArea.right, markedArea.top);
LatLng topRight = projection.fromScreenLocation(pointTopRight);
Point pointBottomLeft = new Point(markedArea.left, markedArea.bottom);
LatLng bottomLeft = projection.fromScreenLocation(pointBottomLeft);
Point pointBottomRight = new Point(markedArea.right, markedArea.bottom);
LatLng bottomRight = projection.fromScreenLocation(pointBottomRight);
markSizeView.reset();
markSizeView.setEnabled(true);
paintElec(topLef, topRight, bottomRight, bottomLeft);
}
@Override
public void onConfirm(MarkSizeView.GraphicPath path) {
}
@Override
public void onCancel() {
txtTips.setVisibility(View.VISIBLE);
}
@Override
public void onTouch() {
txtTips.setVisibility(View.GONE);
}
});
}
/**
* 绘制围栏
*/
private void paintElec(LatLng leftTop, LatLng rightTop, LatLng bottomRight, LatLng bottomLeft) {
markSizeView.setVisibility(View.GONE);
if (polygon != null) {
polygon.remove();
}
PolygonOptions polygonOptions = new PolygonOptions();
// 添加 多边形的每个顶点(顺序添加)
polygonOptions.add(
leftTop, rightTop, bottomRight, bottomLeft);
polygonOptions.strokeWidth(1) // 多边形的边框
.strokeColor(Color.RED) // 边框颜色
.fillColor(Color.parseColor("#3FFF0000")); // 多边形的填充色
// 添加一个多边形
polygon = aMap.addPolygon(polygonOptions);
}
}
| UTF-8 | Java | 4,163 | java | ElectricFenceActivity.java | Java | [] | null | [] | package cn.yznu.gdmapoperate.ui.activity;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.Button;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import cn.yznu.gdmapoperate.ui.widget.MarkSizeView;
import cn.yznu.gdmapoperate.R;
public class ElectricFenceActivity extends AppCompatActivity {
private AMap aMap;
private MarkSizeView markSizeView;
private AppCompatTextView txtTips;
private Button btnPaint;
private Projection projection;
private Polygon polygon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_electric_fence);
MapView mapView = (MapView) findViewById(R.id.map_view);
markSizeView = (MarkSizeView) findViewById(R.id.mark_size);
txtTips = (AppCompatTextView) findViewById(R.id.capture_tips);
btnPaint = (Button) findViewById(R.id.btn_paint);
mapView.onCreate(savedInstanceState);
aMap = mapView.getMap();
projection = aMap.getProjection();
initView();
}
/**
* 初始化视图
*/
private void initView() {
markSizeView.setVisibility(View.GONE);
txtTips.setVisibility(View.GONE);
btnPaint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
markSizeView.setVisibility(View.VISIBLE);
txtTips.setVisibility(View.VISIBLE);
}
});
//负责将屏幕位置和地理坐标(经纬度)进行转换。屏幕位置是相对地图的左上角的位置
markSizeView.setmOnClickListener(new MarkSizeView.onClickListener() {//绘制矩形围栏
@Override
public void onConfirm(Rect markedArea) {
Point pointTopLeft = new Point(markedArea.left, markedArea.top);
LatLng topLef = projection.fromScreenLocation(pointTopLeft);
Point pointTopRight = new Point(markedArea.right, markedArea.top);
LatLng topRight = projection.fromScreenLocation(pointTopRight);
Point pointBottomLeft = new Point(markedArea.left, markedArea.bottom);
LatLng bottomLeft = projection.fromScreenLocation(pointBottomLeft);
Point pointBottomRight = new Point(markedArea.right, markedArea.bottom);
LatLng bottomRight = projection.fromScreenLocation(pointBottomRight);
markSizeView.reset();
markSizeView.setEnabled(true);
paintElec(topLef, topRight, bottomRight, bottomLeft);
}
@Override
public void onConfirm(MarkSizeView.GraphicPath path) {
}
@Override
public void onCancel() {
txtTips.setVisibility(View.VISIBLE);
}
@Override
public void onTouch() {
txtTips.setVisibility(View.GONE);
}
});
}
/**
* 绘制围栏
*/
private void paintElec(LatLng leftTop, LatLng rightTop, LatLng bottomRight, LatLng bottomLeft) {
markSizeView.setVisibility(View.GONE);
if (polygon != null) {
polygon.remove();
}
PolygonOptions polygonOptions = new PolygonOptions();
// 添加 多边形的每个顶点(顺序添加)
polygonOptions.add(
leftTop, rightTop, bottomRight, bottomLeft);
polygonOptions.strokeWidth(1) // 多边形的边框
.strokeColor(Color.RED) // 边框颜色
.fillColor(Color.parseColor("#3FFF0000")); // 多边形的填充色
// 添加一个多边形
polygon = aMap.addPolygon(polygonOptions);
}
}
| 4,163 | 0.647222 | 0.64521 | 113 | 34.194691 | 25.366642 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.628319 | false | false | 2 |
5b0d2f4f8140afd190ef6c7b6194dbb6f56ed416 | 23,630,910,068,926 | 9a779f611b65edf2a1b06cc31034c73ccc8e0a25 | /app/src/main/java/com/cosmos/android/svcecalculator/ShowResult.java | b39135c68dfc8b2220de5fcc6fce48eb7bc4eb97 | [] | no_license | sriramph98/svcecalc | https://github.com/sriramph98/svcecalc | 987adc9704d60e21b3f04200d685369b26a2f841 | f59fccb4bee81e88f25b74243c19d4369b796631 | refs/heads/master | 2021-09-26T22:16:24.349000 | 2018-11-03T14:44:16 | 2018-11-03T14:48:22 | 111,187,500 | 0 | 0 | null | false | 2018-11-03T14:44:17 | 2017-11-18T08:01:45 | 2018-11-03T14:43:51 | 2018-11-03T14:44:16 | 1,981 | 0 | 0 | 0 | Java | false | null | package com.cosmos.android.svcecalculator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.cosmos.android.svcecalculator.model.Phase;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import static android.content.Intent.ACTION_SEND;
public class ShowResult extends AppCompatActivity {
TextView txt = null;
Button minBtn = null;
Context context = this;
LinearLayout minimumGradeContainer = null;
LinearLayout minimumGradeContainer2 = null;
LinearLayout phaseContainer = null;
ScrollView resultScrollView = null;
ImageButton screenshotBtn = null;
ImageButton backBtn = null;
LinearLayout showResultHeader = null;
private void initialize() {
txt = findViewById(R.id.resultTextView);
minimumGradeContainer = findViewById(R.id.minimumGradeContainer);
minimumGradeContainer2 = findViewById(R.id.minimumGradeContainer2);
phaseContainer = findViewById(R.id.phaseContainer);
resultScrollView = findViewById(R.id.resultScrollView);
screenshotBtn = findViewById(R.id.screenshotBtn);
backBtn = findViewById(R.id.backBtn);
showResultHeader = findViewById(R.id.showResultHeader);
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
void addMinimumGradeView(Set<Map.Entry<String, Double>> entrySet, ViewGroup root) {
for (Map.Entry<String, Double> value : entrySet) {
double minGradeVal = ((value.getValue() - DataHelper.INSTANCE.getInternatlMark()) * 2.0d);
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.minimum_grade_item, root, false);
TextView valueTxt = (viewGroup.findViewById(R.id.minimumPoints));
TextView gradeTxt = (viewGroup.findViewById(R.id.minimumLabel));
gradeTxt.setText(value.getKey());
valueTxt.setText(String.format("%1$,.0f", minGradeVal));
if (minGradeVal > 100d) {
valueTxt.setText(":(");
valueTxt.setTextColor(ContextCompat.getColor(this, R.color.error_light));
} else if (minGradeVal < 45) {
valueTxt.setText("45");
}
root.addView(viewGroup);
}
}
private Bitmap getBitmapFromView(View view) {
ScrollView scrollView = (ScrollView) view;
int width = scrollView.getChildAt(0).getWidth();
int height = scrollView.getChildAt(0).getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
Uri getImageUri(Bitmap b) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", "");
return Uri.parse(path);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/SoinSansNeue-Light.otf")
.setFontAttrId(R.attr.fontPath)
.build()
);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_result);
initialize();
String internals_s = String.format("%1$,.2f", DataHelper.INSTANCE.getInternatlMark());
txt.setText(internals_s);
int i = 0;
for (Phase phase : DataHelper.INSTANCE.getPhases()) {
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.phase_item, phaseContainer, false);
TextView catMarkTxt = viewGroup.findViewById(R.id.catMark);
TextView assMarkTxt = viewGroup.findViewById(R.id.assMark);
TextView phaseTitle = (TextView) LayoutInflater.from(this).inflate(R.layout.phase_text_view, phaseContainer, false);
phaseTitle.setText("Phase " + ++i);
catMarkTxt.setText(String.valueOf(phase.getCatMark()));
assMarkTxt.setText(String.valueOf(phase.getAssMark()));
phaseContainer.addView(phaseTitle);
phaseContainer.addView(viewGroup);
}
Map<String, Double> values = new LinkedHashMap<>();
values.put("S", 90.0d);
values.put("A", 80.0d);
values.put("B", 70.0d);
addMinimumGradeView(values.entrySet(), minimumGradeContainer);
values.clear();
values.put("C", 60.0d);
values.put("D", 57.0d);
values.put("E", 50.0d);
addMinimumGradeView(values.entrySet(), minimumGradeContainer2);
backBtn.setOnClickListener(v -> finish());
screenshotBtn.setOnClickListener(v -> {
Intent shareIntent = new Intent(ACTION_SEND);
showResultHeader.setVisibility(View.GONE);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(getBitmapFromView(resultScrollView)));
showResultHeader.setVisibility(View.VISIBLE);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_text)));
});
}
}
| UTF-8 | Java | 6,282 | java | ShowResult.java | Java | [] | null | [] | package com.cosmos.android.svcecalculator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.cosmos.android.svcecalculator.model.Phase;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import static android.content.Intent.ACTION_SEND;
public class ShowResult extends AppCompatActivity {
TextView txt = null;
Button minBtn = null;
Context context = this;
LinearLayout minimumGradeContainer = null;
LinearLayout minimumGradeContainer2 = null;
LinearLayout phaseContainer = null;
ScrollView resultScrollView = null;
ImageButton screenshotBtn = null;
ImageButton backBtn = null;
LinearLayout showResultHeader = null;
private void initialize() {
txt = findViewById(R.id.resultTextView);
minimumGradeContainer = findViewById(R.id.minimumGradeContainer);
minimumGradeContainer2 = findViewById(R.id.minimumGradeContainer2);
phaseContainer = findViewById(R.id.phaseContainer);
resultScrollView = findViewById(R.id.resultScrollView);
screenshotBtn = findViewById(R.id.screenshotBtn);
backBtn = findViewById(R.id.backBtn);
showResultHeader = findViewById(R.id.showResultHeader);
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
void addMinimumGradeView(Set<Map.Entry<String, Double>> entrySet, ViewGroup root) {
for (Map.Entry<String, Double> value : entrySet) {
double minGradeVal = ((value.getValue() - DataHelper.INSTANCE.getInternatlMark()) * 2.0d);
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.minimum_grade_item, root, false);
TextView valueTxt = (viewGroup.findViewById(R.id.minimumPoints));
TextView gradeTxt = (viewGroup.findViewById(R.id.minimumLabel));
gradeTxt.setText(value.getKey());
valueTxt.setText(String.format("%1$,.0f", minGradeVal));
if (minGradeVal > 100d) {
valueTxt.setText(":(");
valueTxt.setTextColor(ContextCompat.getColor(this, R.color.error_light));
} else if (minGradeVal < 45) {
valueTxt.setText("45");
}
root.addView(viewGroup);
}
}
private Bitmap getBitmapFromView(View view) {
ScrollView scrollView = (ScrollView) view;
int width = scrollView.getChildAt(0).getWidth();
int height = scrollView.getChildAt(0).getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
Uri getImageUri(Bitmap b) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", "");
return Uri.parse(path);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/SoinSansNeue-Light.otf")
.setFontAttrId(R.attr.fontPath)
.build()
);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_result);
initialize();
String internals_s = String.format("%1$,.2f", DataHelper.INSTANCE.getInternatlMark());
txt.setText(internals_s);
int i = 0;
for (Phase phase : DataHelper.INSTANCE.getPhases()) {
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.phase_item, phaseContainer, false);
TextView catMarkTxt = viewGroup.findViewById(R.id.catMark);
TextView assMarkTxt = viewGroup.findViewById(R.id.assMark);
TextView phaseTitle = (TextView) LayoutInflater.from(this).inflate(R.layout.phase_text_view, phaseContainer, false);
phaseTitle.setText("Phase " + ++i);
catMarkTxt.setText(String.valueOf(phase.getCatMark()));
assMarkTxt.setText(String.valueOf(phase.getAssMark()));
phaseContainer.addView(phaseTitle);
phaseContainer.addView(viewGroup);
}
Map<String, Double> values = new LinkedHashMap<>();
values.put("S", 90.0d);
values.put("A", 80.0d);
values.put("B", 70.0d);
addMinimumGradeView(values.entrySet(), minimumGradeContainer);
values.clear();
values.put("C", 60.0d);
values.put("D", 57.0d);
values.put("E", 50.0d);
addMinimumGradeView(values.entrySet(), minimumGradeContainer2);
backBtn.setOnClickListener(v -> finish());
screenshotBtn.setOnClickListener(v -> {
Intent shareIntent = new Intent(ACTION_SEND);
showResultHeader.setVisibility(View.GONE);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(getBitmapFromView(resultScrollView)));
showResultHeader.setVisibility(View.VISIBLE);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_text)));
});
}
}
| 6,282 | 0.679879 | 0.672397 | 161 | 38.018635 | 28.308521 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 2 |
5f20457b9b007abdaa392af5acf18b59973004ba | 24,730,421,696,891 | bbe67ef46c5237b474894000ca1c090d9aaa10e2 | /minv2/src_report/com/repair/report/dao/IDictProteamDao.java | f859d189105f695617b5de960d3c702d6905578a | [] | no_license | eliaidi/minv2 | https://github.com/eliaidi/minv2 | 7920e97d1cb038093942b3b55d25c272333446e7 | bd9680053138f92e6bb3db82ee8be741484b6d2d | refs/heads/master | 2021-01-13T07:40:09.957000 | 2016-02-25T09:26:56 | 2016-02-25T09:26:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.repair.report.dao;
import com.repair.entity.DictProteam;
import com.repair.util.daoSupport.BaseDao;
/**
*
* @see 班组dao层
* @author 周云韬
* @date 2015-12-24
* @version 1.0
*/
public interface IDictProteamDao extends BaseDao<DictProteam>{
}
| UTF-8 | Java | 285 | java | IDictProteamDao.java | Java | [
{
"context": ".BaseDao;\r\n\r\n/**\r\n * \r\n * @see 班组dao层\r\n * @author 周云韬\r\n * @date 2015-12-24\r\n * @version 1.0\r\n */\r\npubli",
"end": 159,
"score": 0.9996604919433594,
"start": 156,
"tag": "NAME",
"value": "周云韬"
}
] | null | [] | package com.repair.report.dao;
import com.repair.entity.DictProteam;
import com.repair.util.daoSupport.BaseDao;
/**
*
* @see 班组dao层
* @author 周云韬
* @date 2015-12-24
* @version 1.0
*/
public interface IDictProteamDao extends BaseDao<DictProteam>{
}
| 285 | 0.684982 | 0.648352 | 15 | 16.200001 | 18.159296 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 2 |
bff8cdeae46a9e9db405b8d8d87f786c91a7045f | 28,698,971,480,102 | 468df9ac53fc8001814342c839f71897e743a49a | /app/src/main/java/com/example/phamthaivuong/demosqlite/UpdateActivity.java | df271f79c6fbae64674e981d4241149a4b82cf46 | [] | no_license | phamthaivuong/sqlite | https://github.com/phamthaivuong/sqlite | 6f234f3b2939cab614e7d54f433ead031aed8a23 | d37367644a03d0f6d2716fc6a0b7a3cd3d48c2f3 | refs/heads/master | 2020-04-13T10:04:55.529000 | 2018-12-26T10:56:04 | 2018-12-26T10:56:04 | 163,129,380 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.phamthaivuong.demosqlite;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.phamthaivuong.demosqlite.DatabaseHepler.Database;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class UpdateActivity extends AppCompatActivity {
private String DATABASE_NAME = "database";
final int RESQUEST_TAKE_PHOTO = 123;
final int RESQUERT_CHOOSE_PHOTO = 321;
int id = -1;
ImageView imgHinh;
Button btnChup,btnChon,btnLuu,btnQuayLai;
EditText edtTen,edtSdt,edtEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
init();
initUI();
addEvents();
}
private void addEvents() {
btnChon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
choosePhoto();
}
});
btnChup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TakePickre();
}
});
btnLuu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update();
Toast.makeText(UpdateActivity.this, "Cập nhật thành công ", Toast.LENGTH_SHORT).show();
}
});
btnQuayLai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cancel();
}
});
}
private void Cancel() {
finish();
}
private void update() {
String ten = edtTen.getText().toString();
String sdt = edtSdt.getText().toString();
String email = edtEmail.getText().toString();
byte[] anh = getByteArrayFromImageView(imgHinh);
ContentValues contentValues = new ContentValues();
contentValues.put("Ten",ten);
contentValues.put("SDT",sdt);
contentValues.put("Email",email);
contentValues.put("Anh",anh);
SQLiteDatabase database = Database.initDatabase(this,DATABASE_NAME);
database.update("NhanVien",contentValues,"Id = ?",new String[]{id+""});
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
private byte[] getByteArrayFromImageView(ImageView imgv) {
BitmapDrawable drawable = (BitmapDrawable)imgHinh.getDrawable();
Bitmap bmp = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
private void init() {
imgHinh = (ImageView)findViewById(R.id.imageViewHinh);
btnChup = (Button)findViewById(R.id.buttonChup);
btnChon = (Button)findViewById(R.id.buttonChonhinh);
btnLuu = (Button)findViewById(R.id.buttonLuu);
btnQuayLai = (Button)findViewById(R.id.buttonQuaylai);
edtTen = (EditText)findViewById(R.id.editTextTen);
edtSdt = (EditText)findViewById(R.id.editTextSdt);
edtEmail = (EditText)findViewById(R.id.editTextEmail);
}
private void initUI() {
Intent intent = getIntent();
id = intent.getIntExtra("ID",-1);
SQLiteDatabase database = Database.initDatabase(this,DATABASE_NAME);
Cursor cursor = database.rawQuery("SELECT * FROM NhanVien WHERE Id = ?",new String[]{id + ""});
cursor.moveToFirst();
String ten = cursor.getString(1);
String sdt = cursor.getString(2);
String email = cursor.getString(3);
byte[] anh = cursor.getBlob(4);
Bitmap bitmap = BitmapFactory.decodeByteArray(anh,0,anh.length);
imgHinh.setImageBitmap(bitmap);
edtSdt.setText(sdt);
edtTen.setText(ten);
edtEmail.setText(email);
}
private void TakePickre(){ // chup hinh
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,RESQUEST_TAKE_PHOTO);
}
private void choosePhoto(){ //Chon hinh
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,RESQUERT_CHOOSE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == RESQUERT_CHOOSE_PHOTO){ //Chon hinh
try
{
Uri imgUri = data.getData();
InputStream is = getContentResolver().openInputStream(imgUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imgHinh.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if (requestCode == RESQUEST_TAKE_PHOTO){
Bitmap bitmap = (Bitmap)data.getExtras().get("Data");
imgHinh.setImageBitmap(bitmap);
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
| UTF-8 | Java | 5,916 | java | UpdateActivity.java | Java | [] | null | [] | package com.example.phamthaivuong.demosqlite;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.phamthaivuong.demosqlite.DatabaseHepler.Database;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class UpdateActivity extends AppCompatActivity {
private String DATABASE_NAME = "database";
final int RESQUEST_TAKE_PHOTO = 123;
final int RESQUERT_CHOOSE_PHOTO = 321;
int id = -1;
ImageView imgHinh;
Button btnChup,btnChon,btnLuu,btnQuayLai;
EditText edtTen,edtSdt,edtEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
init();
initUI();
addEvents();
}
private void addEvents() {
btnChon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
choosePhoto();
}
});
btnChup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TakePickre();
}
});
btnLuu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update();
Toast.makeText(UpdateActivity.this, "Cập nhật thành công ", Toast.LENGTH_SHORT).show();
}
});
btnQuayLai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cancel();
}
});
}
private void Cancel() {
finish();
}
private void update() {
String ten = edtTen.getText().toString();
String sdt = edtSdt.getText().toString();
String email = edtEmail.getText().toString();
byte[] anh = getByteArrayFromImageView(imgHinh);
ContentValues contentValues = new ContentValues();
contentValues.put("Ten",ten);
contentValues.put("SDT",sdt);
contentValues.put("Email",email);
contentValues.put("Anh",anh);
SQLiteDatabase database = Database.initDatabase(this,DATABASE_NAME);
database.update("NhanVien",contentValues,"Id = ?",new String[]{id+""});
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
private byte[] getByteArrayFromImageView(ImageView imgv) {
BitmapDrawable drawable = (BitmapDrawable)imgHinh.getDrawable();
Bitmap bmp = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
private void init() {
imgHinh = (ImageView)findViewById(R.id.imageViewHinh);
btnChup = (Button)findViewById(R.id.buttonChup);
btnChon = (Button)findViewById(R.id.buttonChonhinh);
btnLuu = (Button)findViewById(R.id.buttonLuu);
btnQuayLai = (Button)findViewById(R.id.buttonQuaylai);
edtTen = (EditText)findViewById(R.id.editTextTen);
edtSdt = (EditText)findViewById(R.id.editTextSdt);
edtEmail = (EditText)findViewById(R.id.editTextEmail);
}
private void initUI() {
Intent intent = getIntent();
id = intent.getIntExtra("ID",-1);
SQLiteDatabase database = Database.initDatabase(this,DATABASE_NAME);
Cursor cursor = database.rawQuery("SELECT * FROM NhanVien WHERE Id = ?",new String[]{id + ""});
cursor.moveToFirst();
String ten = cursor.getString(1);
String sdt = cursor.getString(2);
String email = cursor.getString(3);
byte[] anh = cursor.getBlob(4);
Bitmap bitmap = BitmapFactory.decodeByteArray(anh,0,anh.length);
imgHinh.setImageBitmap(bitmap);
edtSdt.setText(sdt);
edtTen.setText(ten);
edtEmail.setText(email);
}
private void TakePickre(){ // chup hinh
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,RESQUEST_TAKE_PHOTO);
}
private void choosePhoto(){ //Chon hinh
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,RESQUERT_CHOOSE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == RESQUERT_CHOOSE_PHOTO){ //Chon hinh
try
{
Uri imgUri = data.getData();
InputStream is = getContentResolver().openInputStream(imgUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imgHinh.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if (requestCode == RESQUEST_TAKE_PHOTO){
Bitmap bitmap = (Bitmap)data.getExtras().get("Data");
imgHinh.setImageBitmap(bitmap);
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
| 5,916 | 0.632826 | 0.629949 | 172 | 33.360466 | 23.501812 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.732558 | false | false | 2 |
1879ca6290e3fda3751c9ba95653031a4f412840 | 13,142,599,943,807 | 23f0ac3d948052eae66bb03b019004ff5d3b2610 | /Practise2/dialog/src/main/java/ru/mirea/makarov/dialog/MyProgressDialogFragment.java | ca4a1b517a197455dc15b2a5989767678d296e91 | [] | no_license | Sergey030520/Sergey030520-MobileDevelopment | https://github.com/Sergey030520/Sergey030520-MobileDevelopment | f8803889d9c530f66c6cd9f56243d472ebbcd652 | c6e36f851fcbcf37ec6872d95e4c201cef8a97be | refs/heads/main | 2023-05-03T23:47:08.643000 | 2021-05-27T17:13:06 | 2021-05-27T17:13:06 | 371,449,971 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.mirea.makarov.dialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
public class MyProgressDialogFragment {
public MyProgressDialogFragment(Context context){
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
progressDialog.setTitle("Mirea");
progressDialog.setMessage("Подождите чуть чуть!");
progressDialog.show();
}
}
| UTF-8 | Java | 582 | java | MyProgressDialogFragment.java | Java | [] | null | [] | package ru.mirea.makarov.dialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
public class MyProgressDialogFragment {
public MyProgressDialogFragment(Context context){
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
progressDialog.setTitle("Mirea");
progressDialog.setMessage("Подождите чуть чуть!");
progressDialog.show();
}
}
| 582 | 0.757522 | 0.757522 | 19 | 28.736841 | 19.490461 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 2 |
b9a64b7158d3b4ccbc4033b1a352c233c7fec057 | 19,404,662,266,549 | a7a82f2aad23b31ffe90f09c22090abbe421f43e | /d3-radarchart-play2/app/app/models/MetricSet.java | cba6c17f1f33d854733e2272105fc049598908c6 | [
"Unlicense"
] | permissive | nikkijuk/d3-radarchart-play2 | https://github.com/nikkijuk/d3-radarchart-play2 | 84a120db5648763a3bf1f0f7b88d45511f58cb89 | 85f0af9169ff15bdd3fbaa71f5f3a520658f5b9b | refs/heads/master | 2020-08-06T20:10:15.701000 | 2013-09-16T08:40:28 | 2013-09-16T08:40:28 | 12,808,075 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.models;
import java.util.ArrayList;
import java.util.List;
public class MetricSet {
public String name;
public List<Metric> metrics = new ArrayList<Metric> ();
}
| UTF-8 | Java | 183 | java | MetricSet.java | Java | [] | null | [] | package app.models;
import java.util.ArrayList;
import java.util.List;
public class MetricSet {
public String name;
public List<Metric> metrics = new ArrayList<Metric> ();
}
| 183 | 0.73224 | 0.73224 | 12 | 14.25 | 16.462711 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 2 |
5a35288a56bf172c24a0e82ba6a7c6b92d3aac96 | 19,404,662,264,722 | 9ca1f078e99c512627e95a3912469f55809fb963 | /src/main/java/hr/tvz/car/parts/shop/service/util/Emailer.java | 44df7f2d41ee1c56432c823ac34a0f9d32028eb7 | [] | no_license | CorrectHorseBatteryStapple/pioswebapp | https://github.com/CorrectHorseBatteryStapple/pioswebapp | f051d7739d5649f587abfa9e8780aa9e1c4208c7 | 4265645d9d87f7f8ea9e9e4e99c3af57a84e8c36 | refs/heads/master | 2021-01-10T18:00:44.102000 | 2016-05-02T22:34:35 | 2016-05-02T22:34:35 | 53,781,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.tvz.car.parts.shop.service.util;
public interface Emailer {
void sendEmail(String emailTo, String header, String content);
}
| UTF-8 | Java | 142 | java | Emailer.java | Java | [] | null | [] | package hr.tvz.car.parts.shop.service.util;
public interface Emailer {
void sendEmail(String emailTo, String header, String content);
}
| 142 | 0.760563 | 0.760563 | 6 | 22.666666 | 25.163908 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 2 |
baf45d33017d385f3ebc663e30e752c5a0567fb1 | 7,645,041,806,200 | 82bfd28259d439612f10822857667eef37b84d8c | /bpm-core/wf/wf-api/src/main/java/org/openbpm/bpm/api/model/def/BpmDefProperties.java | 043f503193ed35d68262ca02fad2aa4db9ef82d0 | [] | no_license | GetString0522/openea-bpm | https://github.com/GetString0522/openea-bpm | 45c5c11744e521a57841b3e412d2b547fbe482ba | 3f45e8f225aa7248d624b845ac9f42873d40267d | refs/heads/master | 2020-06-19T08:33:01.338000 | 2019-06-19T17:44:11 | 2019-06-19T17:44:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.openbpm.bpm.api.model.def;
import lombok.Data;
import org.openbpm.bpm.api.model.def.IBpmDefinition.STATUS;
import java.io.Serializable;
import org.hibernate.validator.constraints.NotBlank;
@Data
public class BpmDefProperties implements Serializable {
protected boolean allowExecutorEmpty = true;
protected String description = "";
protected boolean logSubmitData = true;
@NotBlank
protected String status = STATUS.DRAFT;
@NotBlank
protected String subjectRule = "{发起人:startorName}在{发起时间:startDate}发起{流程标题:title}";
protected Integer supportMobile = Integer.valueOf(0);
public String getDescription() {
if (this.description == null) {
return "";
}
return this.description;
}
}
| UTF-8 | Java | 795 | java | BpmDefProperties.java | Java | [] | null | [] | package org.openbpm.bpm.api.model.def;
import lombok.Data;
import org.openbpm.bpm.api.model.def.IBpmDefinition.STATUS;
import java.io.Serializable;
import org.hibernate.validator.constraints.NotBlank;
@Data
public class BpmDefProperties implements Serializable {
protected boolean allowExecutorEmpty = true;
protected String description = "";
protected boolean logSubmitData = true;
@NotBlank
protected String status = STATUS.DRAFT;
@NotBlank
protected String subjectRule = "{发起人:startorName}在{发起时间:startDate}发起{流程标题:title}";
protected Integer supportMobile = Integer.valueOf(0);
public String getDescription() {
if (this.description == null) {
return "";
}
return this.description;
}
}
| 795 | 0.714472 | 0.713168 | 26 | 28.5 | 22.84269 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
13b97301de14c11b37728e2ad1b70457420e9a6f | 3,539,053,113,586 | cd261749b2b1bc59d6df9cd2abfe6a3ff47decae | /src/java/org/satic/web/model/FacadeGrado.java | d4fe549bec57e97f6dbd4ae0c894f3cb1c7cfa34 | [] | no_license | GarciaLabastidaMiguelAngel/serviceWebAndRestWithSpringAndSpringJDBC | https://github.com/GarciaLabastidaMiguelAngel/serviceWebAndRestWithSpringAndSpringJDBC | d4ef77cb7db602248603b78ca152448a04e51409 | 321461ad4efe504e8844b7f32800780485a41846 | refs/heads/master | 2016-09-06T04:50:50.753000 | 2015-03-18T21:56:08 | 2015-03-18T21:56:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.satic.web.model;
import java.util.List;
import org.satic.persistence.pojo.DAO.GradoDAO;
import org.satic.persistence.pojo.Grado;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author miguel
*/
@Service
public class FacadeGrado{
@Autowired
private GradoDAO gradoDAO;
public List<Grado> obtenerTodosGrados() {
return gradoDAO.getGrados();
}
public Grado obtenerGrado(Integer i){
return gradoDAO.getGradoById(i);
}
}
| UTF-8 | Java | 741 | java | FacadeGrado.java | Java | [
{
"context": "ngframework.stereotype.Service;\n\n/**\n *\n * @author miguel\n */\n@Service\npublic class FacadeGrado{\n\t\n\t@Aut",
"end": 459,
"score": 0.7223610281944275,
"start": 456,
"tag": "NAME",
"value": "mig"
},
{
"context": "amework.stereotype.Service;\n\n/**\n *\n * @author... | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.satic.web.model;
import java.util.List;
import org.satic.persistence.pojo.DAO.GradoDAO;
import org.satic.persistence.pojo.Grado;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author miguel
*/
@Service
public class FacadeGrado{
@Autowired
private GradoDAO gradoDAO;
public List<Grado> obtenerTodosGrados() {
return gradoDAO.getGrados();
}
public Grado obtenerGrado(Integer i){
return gradoDAO.getGradoById(i);
}
}
| 741 | 0.721997 | 0.721997 | 34 | 20.794117 | 21.685966 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 2 |
7ac14f747aa703c30413f29bc5526847c1b63555 | 6,279,242,231,058 | a422e6cdd2680957ad1d8d94c7e5ba76d9d6f9cd | /app/src/main/java/com/daloski/mystore/repos/MainRepo.java | 551e9c94b86725e148151138e41f3c291d2043cd | [] | no_license | oruamdalo/MyStore | https://github.com/oruamdalo/MyStore | e3bcae79f2e89199f9fc131b08fc67410c657f25 | efd7eb7a7fdf81ef8f834343792c9924c935125a | refs/heads/master | 2022-12-09T18:46:55.710000 | 2020-09-12T10:08:20 | 2020-09-12T10:08:20 | 294,916,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.daloski.mystore.repos;
import androidx.lifecycle.MutableLiveData;
import com.daloski.mystore.api.Api;
import com.daloski.mystore.models.Item;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainRepo {
public MutableLiveData<List<Item>> getItems(String name){
MutableLiveData<List<Item>> data = new MutableLiveData<>();
Api.getInstance().searchByName(name, new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
data.postValue(null);
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.body() != null){
String html = response.body().string();
String json = Api.parse(html);
if(json != null) {
json = json.replaceAll("AF_initDataCallback", "").replaceAll(";</script", "").substring(1);
try {
List<Item> items = Api.fetchJson(json);
data.postValue(items);
} catch (JSONException e) {
//e.printStackTrace();
data.postValue(null);
}
}else{
data.postValue(null);
}
}
}
});
return data;
}
}
| UTF-8 | Java | 1,664 | java | MainRepo.java | Java | [] | null | [] | package com.daloski.mystore.repos;
import androidx.lifecycle.MutableLiveData;
import com.daloski.mystore.api.Api;
import com.daloski.mystore.models.Item;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainRepo {
public MutableLiveData<List<Item>> getItems(String name){
MutableLiveData<List<Item>> data = new MutableLiveData<>();
Api.getInstance().searchByName(name, new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
data.postValue(null);
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.body() != null){
String html = response.body().string();
String json = Api.parse(html);
if(json != null) {
json = json.replaceAll("AF_initDataCallback", "").replaceAll(";</script", "").substring(1);
try {
List<Item> items = Api.fetchJson(json);
data.postValue(items);
} catch (JSONException e) {
//e.printStackTrace();
data.postValue(null);
}
}else{
data.postValue(null);
}
}
}
});
return data;
}
}
| 1,664 | 0.527043 | 0.524639 | 54 | 29.814816 | 26.327759 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537037 | false | false | 2 |
074ba5789eee2daa0a0f54168356fc5798946dae | 30,648,886,644,122 | 5d2ad9fe93a5e68d0aaab1803fdbdbe6a681133f | /src/main/java/com/grupolainmaculada/sictem/dao/jdbc/JdbcDocumentoDAO.java | b099b10e8b744eac02a64a5ba25aab4ba585b409 | [] | no_license | geraldvaras/sictem | https://github.com/geraldvaras/sictem | f2eb6646df8737d6e43d305b499813e25b25bb4d | b0483a5abe0d81d993d4cf090bd095e8411bc10c | refs/heads/master | 2018-01-07T13:32:58.706000 | 2012-08-08T23:58:37 | 2012-08-08T23:58:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.grupolainmaculada.sictem.dao.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.grupolainmaculada.sictem.dao.DocumentoDAO;
import com.grupolainmaculada.sictem.dominio.Documento;
import com.grupolainmaculada.sictem.dominio.Empresa;
import com.grupolainmaculada.sictem.dominio.Sucursales;
import com.grupolainmaculada.sictem.dominio.UserSystema;
@Repository
public class JdbcDocumentoDAO implements DocumentoDAO{
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private static final class DocumentoMapper implements RowMapper<Documento>{
public Documento mapRow(ResultSet rs, int rowNum) throws SQLException {
Documento documento = new Documento();
Empresa empresa = new Empresa();
documento.setEmpresa(empresa);
empresa.setCodEmp(rs.getInt("codEmp"));
Sucursales sucursales = new Sucursales();
documento.setSucursales(sucursales);
sucursales.setCodSuc(rs.getInt("codSuc"));
documento.setDescripcion(rs.getString("descripcion"));
documento.setTipoDoc(rs.getInt("tipoDoc"));
documento.setEstaReg(rs.getInt("estareg"));
documento.setFechaReg(rs.getTimestamp("fechareg"));
UserSystema userSystema = new UserSystema();
userSystema.setCodUsu(rs.getInt("creador"));
documento.setUsersystema(userSystema);
return documento;
}
}
private static final String SQL_Listar_Documentos = "SELECT * FROM documentos";
public List<Documento> listarDocumentos() {
// TODO Auto-generated method stub
return this.jdbcTemplate.query(SQL_Listar_Documentos, new DocumentoMapper());
}
private static final String SQL_Actualizar_Documento = "UPDATE documentos SET descripcion = ? , estareg = ? WHERE codEmp = ? AND codSuc = ? AND tipoDoc = ?";
public void actualizarDocumento(Documento documento) {
// TODO Auto-generated method stub
this.jdbcTemplate.update(SQL_Actualizar_Documento,new Object[]{documento.getDescripcion(),documento.getEstaReg(),documento.getEmpresa().getCodEmp(),documento.getSucursales().getCodSuc(),documento.getTipoDoc()});
}
private static final String SQL_Obtener_Documento = "SELECT * From documentos WHERE tipoDoc = ?";
public Documento obtenerDocumentoPorId(Long codigoDocumento) {
// TODO Auto-generated method stub
return this.jdbcTemplate.queryForObject(SQL_Obtener_Documento, new Object[]{codigoDocumento}, new DocumentoMapper());
}
private static final String SQL_Registrar_Documento = "INSERT INTO documentos (codEmp,codsuc, tipoDoc,descripcion,estaReg,creador) VALUES (1,1,?,?,?,1)";
public void registrarDocumento(Documento documento) {
// TODO Auto-generated method stub
this.jdbcTemplate.update(SQL_Registrar_Documento,new Object[]{documento.getTipoDoc(), documento.getDescripcion(),documento.getEstaReg()});
}
}
| UTF-8 | Java | 3,178 | java | JdbcDocumentoDAO.java | Java | [] | null | [] | package com.grupolainmaculada.sictem.dao.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.grupolainmaculada.sictem.dao.DocumentoDAO;
import com.grupolainmaculada.sictem.dominio.Documento;
import com.grupolainmaculada.sictem.dominio.Empresa;
import com.grupolainmaculada.sictem.dominio.Sucursales;
import com.grupolainmaculada.sictem.dominio.UserSystema;
@Repository
public class JdbcDocumentoDAO implements DocumentoDAO{
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private static final class DocumentoMapper implements RowMapper<Documento>{
public Documento mapRow(ResultSet rs, int rowNum) throws SQLException {
Documento documento = new Documento();
Empresa empresa = new Empresa();
documento.setEmpresa(empresa);
empresa.setCodEmp(rs.getInt("codEmp"));
Sucursales sucursales = new Sucursales();
documento.setSucursales(sucursales);
sucursales.setCodSuc(rs.getInt("codSuc"));
documento.setDescripcion(rs.getString("descripcion"));
documento.setTipoDoc(rs.getInt("tipoDoc"));
documento.setEstaReg(rs.getInt("estareg"));
documento.setFechaReg(rs.getTimestamp("fechareg"));
UserSystema userSystema = new UserSystema();
userSystema.setCodUsu(rs.getInt("creador"));
documento.setUsersystema(userSystema);
return documento;
}
}
private static final String SQL_Listar_Documentos = "SELECT * FROM documentos";
public List<Documento> listarDocumentos() {
// TODO Auto-generated method stub
return this.jdbcTemplate.query(SQL_Listar_Documentos, new DocumentoMapper());
}
private static final String SQL_Actualizar_Documento = "UPDATE documentos SET descripcion = ? , estareg = ? WHERE codEmp = ? AND codSuc = ? AND tipoDoc = ?";
public void actualizarDocumento(Documento documento) {
// TODO Auto-generated method stub
this.jdbcTemplate.update(SQL_Actualizar_Documento,new Object[]{documento.getDescripcion(),documento.getEstaReg(),documento.getEmpresa().getCodEmp(),documento.getSucursales().getCodSuc(),documento.getTipoDoc()});
}
private static final String SQL_Obtener_Documento = "SELECT * From documentos WHERE tipoDoc = ?";
public Documento obtenerDocumentoPorId(Long codigoDocumento) {
// TODO Auto-generated method stub
return this.jdbcTemplate.queryForObject(SQL_Obtener_Documento, new Object[]{codigoDocumento}, new DocumentoMapper());
}
private static final String SQL_Registrar_Documento = "INSERT INTO documentos (codEmp,codsuc, tipoDoc,descripcion,estaReg,creador) VALUES (1,1,?,?,?,1)";
public void registrarDocumento(Documento documento) {
// TODO Auto-generated method stub
this.jdbcTemplate.update(SQL_Registrar_Documento,new Object[]{documento.getTipoDoc(), documento.getDescripcion(),documento.getEstaReg()});
}
}
| 3,178 | 0.761485 | 0.760541 | 76 | 39.815788 | 40.567265 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.171053 | false | false | 2 |
0608c249c2288fe3f653d47f558b59a7d14ab9d6 | 20,581,483,333,903 | eed497cd61c3273bc57191c2371ec7b390e4721d | /src/main/java/virtualpetshelter/VirtualPetShelterApp.java | 44eb076811dcc36f1be45461f0c006953c47f1b4 | [] | no_license | SusanWendt/virtual-pet-shelter | https://github.com/SusanWendt/virtual-pet-shelter | 2e8a4a6d3b7090fc75e3d2c7aa68af55861a790e | 1118c6db49edd7f251abd40f65835201ec1bee46 | refs/heads/master | 2021-09-06T10:27:52.367000 | 2018-02-05T14:54:11 | 2018-02-05T14:54:11 | 119,997,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package virtualpetshelter;
import java.util.Scanner;
public class VirtualPetShelterApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
VirtualPetShelter myShelter = new VirtualPetShelter();
// welcome message
System.out.println("Welcome to BitBuddies Bed and Breakfast, a SoozaPoalooza Vitrual Pet Emporium(TM) corp.");
// default VirtualPets options
System.out.println("Please select a theme for your pet inventory: ");
System.out.println("1) Bikini Bottom");
System.out.println("2) Dogs");
System.out.println("3) Disney");
String themeChosen = input.nextLine();
if (themeChosen.equals("1")) {
myShelter.addPet(new VirtualPet("Bob", "sea sponge", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Patrick", "just a star", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("MrCrabs", "stressed", 25, 25, 25, 25));
}
if (themeChosen.equals("2")) {
myShelter.addPet(new VirtualPet("Lassie", "Smart Collie", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Fido", "Loyal Dog", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Cujo", "Nightmare", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Snoopy", "Cartoon", 25, 25, 25, 25));
}
if (themeChosen.equals("3")) {
myShelter.addPet(new VirtualPet("Mickey", "the Mouse", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Minnie", "also Mouse", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Donald", "the Duck", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Pluto", "the Dog", 25, 25, 25, 25));
}
// game loop
String option = "";
while (!option.equals("quit")) {
// pets displayed
System.out.println("Your Virtual Pet inventory:");
System.out.print("\tname\t");
System.out.print("| description \t\t");
System.out.print("| hunger \t");
System.out.print("| thirst \t");
System.out.print("| bathroom \t");
System.out.print("| energy \t");
System.out.print("| status \t");
System.out.println();
System.out.println(
"----------------|-----------------------|---------------|---------------|---------------|---------------|---------------");
myShelter.showPets();
System.out.println();
// game menu
System.out.println("What would you like to do?");
System.out.println("1) Feed all the pets.");
System.out.println("2) Water all the pets.");
System.out.println("3) Let out all the pets to go to the bathroom .");
System.out.println("4) Playtime for all of the pets.");
System.out.println("5) Play with just one pet.");
System.out.println("6) Choose a pet to be adopted by a loving family.");
System.out.println("7) Invite a new pet to BitBuddies Bed and Breakfast.");
System.out.println("Or type 'quit' to exit game.");
option = input.nextLine();
if (option.equals("1")) {
myShelter.feedAllPets();
System.out.println("You have chosen to feed all the pets.");
}
if (option.equals("2")) {
myShelter.waterAllPets();
System.out.println(
"You have chosen to water all the pets. But now need to go to the bathroom has increased.");
}
if (option.equals("3")) {
myShelter.letOutAllPets();
System.out.println("You have chosen to let all the pets go to the bathroom.");
}
if (option.equals("4")) {
myShelter.playWithAllPets();
System.out.println("You have chosen to play with all the pets.");
}
if (option.equals("5")) {
System.out.println("Which pet would you like to play with? Type name:");
String petChosen = input.nextLine();
myShelter.playWithPetByName(petChosen);
System.out.println("You have chosen to play with " + petChosen);
}
if (option.equals("6")) {
System.out.println("Which pet would you like to be adopted? Type name:");
String petChosen = input.nextLine();
myShelter.adoptPet(petChosen);
System.out.println("You have chosen to send " + petChosen + " to a forever home. (Leaving BitBuddies)");
}
if (option.equals("7")) {
System.out.println("Please enter the name of the pet you would like to add:");
String petName = input.nextLine();
System.out.println("Please enter a brief description of the pet you would like to admit:");
String petDescription = input.nextLine();
myShelter.addPet(new VirtualPet(petName, petDescription));
System.out.println("You have added " + petName + " the " + petDescription + " to BitBuddies.");
}
if (option.equalsIgnoreCase("Quit")) {
System.out.println("Goodbye!");
input.close();
System.exit(0);
}
myShelter.tickAllPets();
}
}
}
| UTF-8 | Java | 4,578 | java | VirtualPetShelterApp.java | Java | [
{
"context": "quals(\"1\")) {\n\t\t\tmyShelter.addPet(new VirtualPet(\"Bob\", \"sea sponge\", 25, 25, 25, 25));\n\t\t\tmyShelter.ad",
"end": 698,
"score": 0.9952220320701599,
"start": 695,
"tag": "NAME",
"value": "Bob"
},
{
"context": "25, 25, 25));\n\t\t\tmyShelter.addPet(new Virtua... | null | [] | package virtualpetshelter;
import java.util.Scanner;
public class VirtualPetShelterApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
VirtualPetShelter myShelter = new VirtualPetShelter();
// welcome message
System.out.println("Welcome to BitBuddies Bed and Breakfast, a SoozaPoalooza Vitrual Pet Emporium(TM) corp.");
// default VirtualPets options
System.out.println("Please select a theme for your pet inventory: ");
System.out.println("1) Bikini Bottom");
System.out.println("2) Dogs");
System.out.println("3) Disney");
String themeChosen = input.nextLine();
if (themeChosen.equals("1")) {
myShelter.addPet(new VirtualPet("Bob", "sea sponge", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Patrick", "just a star", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("MrCrabs", "stressed", 25, 25, 25, 25));
}
if (themeChosen.equals("2")) {
myShelter.addPet(new VirtualPet("Lassie", "Smart Collie", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Fido", "Loyal Dog", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Cujo", "Nightmare", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Snoopy", "Cartoon", 25, 25, 25, 25));
}
if (themeChosen.equals("3")) {
myShelter.addPet(new VirtualPet("Mickey", "the Mouse", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Minnie", "also Mouse", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Donald", "the Duck", 25, 25, 25, 25));
myShelter.addPet(new VirtualPet("Pluto", "the Dog", 25, 25, 25, 25));
}
// game loop
String option = "";
while (!option.equals("quit")) {
// pets displayed
System.out.println("Your Virtual Pet inventory:");
System.out.print("\tname\t");
System.out.print("| description \t\t");
System.out.print("| hunger \t");
System.out.print("| thirst \t");
System.out.print("| bathroom \t");
System.out.print("| energy \t");
System.out.print("| status \t");
System.out.println();
System.out.println(
"----------------|-----------------------|---------------|---------------|---------------|---------------|---------------");
myShelter.showPets();
System.out.println();
// game menu
System.out.println("What would you like to do?");
System.out.println("1) Feed all the pets.");
System.out.println("2) Water all the pets.");
System.out.println("3) Let out all the pets to go to the bathroom .");
System.out.println("4) Playtime for all of the pets.");
System.out.println("5) Play with just one pet.");
System.out.println("6) Choose a pet to be adopted by a loving family.");
System.out.println("7) Invite a new pet to BitBuddies Bed and Breakfast.");
System.out.println("Or type 'quit' to exit game.");
option = input.nextLine();
if (option.equals("1")) {
myShelter.feedAllPets();
System.out.println("You have chosen to feed all the pets.");
}
if (option.equals("2")) {
myShelter.waterAllPets();
System.out.println(
"You have chosen to water all the pets. But now need to go to the bathroom has increased.");
}
if (option.equals("3")) {
myShelter.letOutAllPets();
System.out.println("You have chosen to let all the pets go to the bathroom.");
}
if (option.equals("4")) {
myShelter.playWithAllPets();
System.out.println("You have chosen to play with all the pets.");
}
if (option.equals("5")) {
System.out.println("Which pet would you like to play with? Type name:");
String petChosen = input.nextLine();
myShelter.playWithPetByName(petChosen);
System.out.println("You have chosen to play with " + petChosen);
}
if (option.equals("6")) {
System.out.println("Which pet would you like to be adopted? Type name:");
String petChosen = input.nextLine();
myShelter.adoptPet(petChosen);
System.out.println("You have chosen to send " + petChosen + " to a forever home. (Leaving BitBuddies)");
}
if (option.equals("7")) {
System.out.println("Please enter the name of the pet you would like to add:");
String petName = input.nextLine();
System.out.println("Please enter a brief description of the pet you would like to admit:");
String petDescription = input.nextLine();
myShelter.addPet(new VirtualPet(petName, petDescription));
System.out.println("You have added " + petName + " the " + petDescription + " to BitBuddies.");
}
if (option.equalsIgnoreCase("Quit")) {
System.out.println("Goodbye!");
input.close();
System.exit(0);
}
myShelter.tickAllPets();
}
}
}
| 4,578 | 0.64526 | 0.62145 | 114 | 39.157894 | 29.08746 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.929825 | false | false | 2 |
d3e91fb07ff8d90f86b728f4a0ee388945cc17ec | 20,581,483,337,668 | 49dcbbaceb67089c36a67c284069a437a4285ef5 | /src/ffos/rusija2018/view/FormaUtakmice.java | c7e79a453f19cbe5092e42184e8c08e5e0c94dfd | [] | no_license | SanjaSusilovic/Rusija2018 | https://github.com/SanjaSusilovic/Rusija2018 | 10ace5d3bc3f452596a35727e547232dc969a2f9 | 766e940c67bf2de6476ceb9e237ceaf1345506b1 | refs/heads/master | 2020-05-13T19:48:42.028000 | 2019-04-16T09:11:54 | 2019-04-16T09:11:54 | 181,655,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ffos.rusija2018.view;
import ffos.rusija2018.controller.ObradaMjesto;
import ffos.rusija2018.controller.ObradaEkipa;
import ffos.rusija2018.controller.ObradaUtakmica;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.DefaultComboBoxModel;
import ffos.rusija2018.model.Utakmica;
import ffos.rusija2018.model.Ekipa;
import ffos.rusija2018.model.Mjesto;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import java.util.HashSet;
/**
*
* @author Sanja
*/
public class FormaUtakmice extends javax.swing.JFrame {
private ObradaUtakmica ou;
private ObradaEkipa oe;
private ObradaMjesto om;
/**
* Creates new form FormaUtakmice
*/
public FormaUtakmice() {
initComponents();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
ou= new ObradaUtakmica();
oe = new ObradaEkipa();
om = new ObradaMjesto();
DefaultComboBoxModel m = new DefaultComboBoxModel();
for(Ekipa p : oe.getEkipe()){
m.addElement(p);
}
domacin.setModel(m);
ucitaj();
DefaultComboBoxModel a = new DefaultComboBoxModel();
for(Ekipa p : oe.getEkipe()){
a.addElement(p);
}
gost.setModel(a);
ucitaj();
DefaultComboBoxModel n = new DefaultComboBoxModel();
for(Mjesto p : om.getMjesta()){
n.addElement(p);
}
mjesto.setModel(n);
ucitaj();
}
private void ucitaj() {
DefaultListModel m = new DefaultListModel();
for (Utakmica p : ou.getUtakmice()) {
m.addElement(p);
}
lista.setModel(m);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lista = new javax.swing.JList<>();
jLabel1 = new javax.swing.JLabel();
domacin = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
gost = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
rezultat = new javax.swing.JTextField();
mjesto = new javax.swing.JComboBox<>();
dodaj = new javax.swing.JButton();
promjeni = new javax.swing.JButton();
obrisi = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Rusija 2018 Utakmice");
lista.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
listaValueChanged(evt);
}
});
jScrollPane1.setViewportView(lista);
jLabel1.setText("Domaćin");
domacin.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel2.setText("Mjesto");
jLabel3.setText("Gost");
gost.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel4.setText("Rezultat");
mjesto.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
dodaj.setText("Dodaj");
dodaj.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dodajActionPerformed(evt);
}
});
promjeni.setText("Promijeni");
promjeni.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
promjeniActionPerformed(evt);
}
});
obrisi.setText("Obriši");
obrisi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
obrisiActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(domacin, 0, 164, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(gost, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addComponent(rezultat)
.addComponent(mjesto, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(dodaj)
.addGap(18, 18, 18)
.addComponent(promjeni))))
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(obrisi)))
.addContainerGap(48, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mjesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(domacin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(gost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rezultat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dodaj)
.addComponent(promjeni))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(obrisi)))
.addContainerGap(22, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void dodajActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dodajActionPerformed
// TODO add your handling code here:
Utakmica i = new Utakmica();
i.setRezultat(rezultat.getText());
i.setDomacin((Ekipa)domacin.getSelectedItem());
i.setGost((Ekipa)gost.getSelectedItem());
i.setMjesto((Mjesto)mjesto.getSelectedItem());
ou.dodaj(i);
ucitaj();
}//GEN-LAST:event_dodajActionPerformed
private void promjeniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_promjeniActionPerformed
// TODO add your handling code here:
try {
Utakmica i = (Utakmica) lista.getSelectedValue();
i.setRezultat(rezultat.getText());
i.setDomacin((Ekipa)domacin.getSelectedItem());
i.setGost((Ekipa)gost.getSelectedItem());
i.setMjesto((Mjesto)mjesto.getSelectedItem());
ou.promjeni(i);
ucitaj();
} catch (Exception e) {
JOptionPane.showConfirmDialog(rootPane, "Prvo odaberite stavku");
}
}//GEN-LAST:event_promjeniActionPerformed
private void obrisiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_obrisiActionPerformed
// TODO add your handling code here:
try {
Utakmica i = (Utakmica)lista.getSelectedValue();
ou.obrisi(i);
ucitaj();
} catch (Exception e) {
JOptionPane.showConfirmDialog(rootPane, "Prvo odaberite stavku");
}
}//GEN-LAST:event_obrisiActionPerformed
private void listaValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaValueChanged
// TODO add your handling code here:
try {
Utakmica i = (Utakmica)lista.getSelectedValue();
rezultat.setText(i.getRezultat());
DefaultComboBoxModel m = (DefaultComboBoxModel)domacin.getModel();
DefaultComboBoxModel a = (DefaultComboBoxModel)gost.getModel();
DefaultComboBoxModel n = (DefaultComboBoxModel)mjesto.getModel();
} catch (Exception e) {
}
}//GEN-LAST:event_listaValueChanged
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton dodaj;
private javax.swing.JComboBox<String> domacin;
private javax.swing.JComboBox<String> gost;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<Utakmica> lista;
private javax.swing.JComboBox<String> mjesto;
private javax.swing.JButton obrisi;
private javax.swing.JButton promjeni;
private javax.swing.JTextField rezultat;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 12,006 | java | FormaUtakmice.java | Java | [
{
"context": "ane;\nimport java.util.HashSet;\n\n\n/**\n *\n * @author Sanja\n */\npublic class FormaUtakmice extends javax.swin",
"end": 689,
"score": 0.9991415143013,
"start": 684,
"tag": "NAME",
"value": "Sanja"
},
{
"context": "setViewportView(lista);\n\n jLabel1.setText(\... | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ffos.rusija2018.view;
import ffos.rusija2018.controller.ObradaMjesto;
import ffos.rusija2018.controller.ObradaEkipa;
import ffos.rusija2018.controller.ObradaUtakmica;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.DefaultComboBoxModel;
import ffos.rusija2018.model.Utakmica;
import ffos.rusija2018.model.Ekipa;
import ffos.rusija2018.model.Mjesto;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import java.util.HashSet;
/**
*
* @author Sanja
*/
public class FormaUtakmice extends javax.swing.JFrame {
private ObradaUtakmica ou;
private ObradaEkipa oe;
private ObradaMjesto om;
/**
* Creates new form FormaUtakmice
*/
public FormaUtakmice() {
initComponents();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
ou= new ObradaUtakmica();
oe = new ObradaEkipa();
om = new ObradaMjesto();
DefaultComboBoxModel m = new DefaultComboBoxModel();
for(Ekipa p : oe.getEkipe()){
m.addElement(p);
}
domacin.setModel(m);
ucitaj();
DefaultComboBoxModel a = new DefaultComboBoxModel();
for(Ekipa p : oe.getEkipe()){
a.addElement(p);
}
gost.setModel(a);
ucitaj();
DefaultComboBoxModel n = new DefaultComboBoxModel();
for(Mjesto p : om.getMjesta()){
n.addElement(p);
}
mjesto.setModel(n);
ucitaj();
}
private void ucitaj() {
DefaultListModel m = new DefaultListModel();
for (Utakmica p : ou.getUtakmice()) {
m.addElement(p);
}
lista.setModel(m);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lista = new javax.swing.JList<>();
jLabel1 = new javax.swing.JLabel();
domacin = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
gost = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
rezultat = new javax.swing.JTextField();
mjesto = new javax.swing.JComboBox<>();
dodaj = new javax.swing.JButton();
promjeni = new javax.swing.JButton();
obrisi = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Rusija 2018 Utakmice");
lista.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
listaValueChanged(evt);
}
});
jScrollPane1.setViewportView(lista);
jLabel1.setText("Domaćin");
domacin.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel2.setText("Mjesto");
jLabel3.setText("Gost");
gost.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel4.setText("Rezultat");
mjesto.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
dodaj.setText("Dodaj");
dodaj.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dodajActionPerformed(evt);
}
});
promjeni.setText("Promijeni");
promjeni.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
promjeniActionPerformed(evt);
}
});
obrisi.setText("Obriši");
obrisi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
obrisiActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(domacin, 0, 164, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(gost, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addComponent(rezultat)
.addComponent(mjesto, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(dodaj)
.addGap(18, 18, 18)
.addComponent(promjeni))))
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(obrisi)))
.addContainerGap(48, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mjesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(domacin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(gost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rezultat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dodaj)
.addComponent(promjeni))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(obrisi)))
.addContainerGap(22, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void dodajActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dodajActionPerformed
// TODO add your handling code here:
Utakmica i = new Utakmica();
i.setRezultat(rezultat.getText());
i.setDomacin((Ekipa)domacin.getSelectedItem());
i.setGost((Ekipa)gost.getSelectedItem());
i.setMjesto((Mjesto)mjesto.getSelectedItem());
ou.dodaj(i);
ucitaj();
}//GEN-LAST:event_dodajActionPerformed
private void promjeniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_promjeniActionPerformed
// TODO add your handling code here:
try {
Utakmica i = (Utakmica) lista.getSelectedValue();
i.setRezultat(rezultat.getText());
i.setDomacin((Ekipa)domacin.getSelectedItem());
i.setGost((Ekipa)gost.getSelectedItem());
i.setMjesto((Mjesto)mjesto.getSelectedItem());
ou.promjeni(i);
ucitaj();
} catch (Exception e) {
JOptionPane.showConfirmDialog(rootPane, "Prvo odaberite stavku");
}
}//GEN-LAST:event_promjeniActionPerformed
private void obrisiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_obrisiActionPerformed
// TODO add your handling code here:
try {
Utakmica i = (Utakmica)lista.getSelectedValue();
ou.obrisi(i);
ucitaj();
} catch (Exception e) {
JOptionPane.showConfirmDialog(rootPane, "Prvo odaberite stavku");
}
}//GEN-LAST:event_obrisiActionPerformed
private void listaValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaValueChanged
// TODO add your handling code here:
try {
Utakmica i = (Utakmica)lista.getSelectedValue();
rezultat.setText(i.getRezultat());
DefaultComboBoxModel m = (DefaultComboBoxModel)domacin.getModel();
DefaultComboBoxModel a = (DefaultComboBoxModel)gost.getModel();
DefaultComboBoxModel n = (DefaultComboBoxModel)mjesto.getModel();
} catch (Exception e) {
}
}//GEN-LAST:event_listaValueChanged
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton dodaj;
private javax.swing.JComboBox<String> domacin;
private javax.swing.JComboBox<String> gost;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<Utakmica> lista;
private javax.swing.JComboBox<String> mjesto;
private javax.swing.JButton obrisi;
private javax.swing.JButton promjeni;
private javax.swing.JTextField rezultat;
// End of variables declaration//GEN-END:variables
}
| 12,006 | 0.617794 | 0.607631 | 289 | 40.536331 | 33.378185 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581315 | false | false | 2 |
db4196ca9635d713ba79ecbc8ae5be8af2abb1a8 | 30,047,591,233,099 | db0002ecab8139936c9b52f5b94d16bb59b8e385 | /src/main/java/com/kedacom/apitest/window/SocketWindowTest.java | 895426d71e46b4e582ca236810a3d204607677c1 | [] | no_license | leeegeng/flink | https://github.com/leeegeng/flink | 22f70a2f071236ddb5f6a15032765b226358cdb3 | 390027c2ab88c1eafbe9ea47597ebb935527c2dd | refs/heads/main | 2023-07-08T02:09:54.395000 | 2021-08-16T05:52:21 | 2021-08-16T05:52:21 | 396,589,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kedacom.apitest.window;
import com.kedacom.pojo.CarNumCount;
import com.kedacom.pojo.DeviceInfo;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.aggregation.AggregationFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class SocketWindowTest {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
// 1 设置socket信息
ParameterTool parameterTool = ParameterTool.fromArgs(args);
// String host = parameterTool.get("host");
// int port = parameterTool.getInt("port");
String host = "172.16.64.85";
int port = 8888;
// 2 从socket读取数据
DataStream<String> inputDataStream = env.socketTextStream(host, port);
DataStream<DeviceInfo> mapStream = inputDataStream.map(new MapFunction<String, DeviceInfo>() {
@Override
public DeviceInfo map(String s) throws Exception {
String[] fields = s.split(",");
return new DeviceInfo(fields[0], new Integer(fields[1]), new Integer(fields[2]), new Long(fields[3]));
}
});
SingleOutputStreamOperator<Tuple2<String, Long>> resultStream = mapStream
.assignTimestampsAndWatermarks(
new BoundedOutOfOrdernessTimestampExtractor<DeviceInfo>(Time.seconds(2)) {
@Override
public long extractTimestamp(DeviceInfo deviceInfo) {
return deviceInfo.getTime() * 1000;
}
})
.keyBy(DeviceInfo::getName)
.window(TumblingEventTimeWindows.of(Time.seconds(10)))
.aggregate(new AggregateFunction<DeviceInfo, Tuple2<String, Long>, Tuple2<String, Long>>() {
@Override
public Tuple2<String, Long> createAccumulator() {
return new Tuple2<>("", 0L);
}
@Override
public Tuple2<String, Long> add(DeviceInfo deviceInfo, Tuple2<String, Long> value) {
value.f0 = deviceInfo.getName();
value.f1 += deviceInfo.getCarNum();
return value;
}
@Override
public Tuple2<String, Long> getResult(Tuple2<String, Long> stringLongTuple2) {
return stringLongTuple2;
}
@Override
public Tuple2<String, Long> merge(Tuple2<String, Long> stringLongTuple2, Tuple2<String, Long> acc1) {
stringLongTuple2.f1 += acc1.f1;
return stringLongTuple2;
}
});
mapStream.print("data");
resultStream.print("sum");
//
// // 2 全窗口测试
// SingleOutputStreamOperator<DeviceInfo> apply = deviceStream.keyBy(devic -> devic.getName())
// .timeWindow(Time.seconds(5))
// .apply(new WindowFunction<DeviceInfo, DeviceInfo, String, TimeWindow>() {
// @Override
// public void apply(String s, TimeWindow timeWindow, Iterable<DeviceInfo> iterable, Collector<DeviceInfo> collector) throws Exception {
// AtomicInteger total = new AtomicInteger();
// AtomicReference<DeviceInfo> deviceInfo = new AtomicReference<>();
// iterable.forEach(dev -> {
// total.addAndGet(dev.getCarNum());
// deviceInfo.set(dev);
// });
// if (deviceInfo != null) {
// deviceInfo.get().setCarNum(total.get());
// }
//
// collector.collect(deviceInfo.get());
// }
// });
// apply.print("apply");
//
env.execute("device job");
}
}
| UTF-8 | Java | 5,368 | java | SocketWindowTest.java | Java | [
{
"context": "ameterTool.getInt(\"port\");\n String host = \"172.16.64.85\";\n int port = 8888;\n\n\n // 2 从socket",
"end": 1956,
"score": 0.9997028708457947,
"start": 1944,
"tag": "IP_ADDRESS",
"value": "172.16.64.85"
}
] | null | [] | package com.kedacom.apitest.window;
import com.kedacom.pojo.CarNumCount;
import com.kedacom.pojo.DeviceInfo;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.aggregation.AggregationFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class SocketWindowTest {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
// 1 设置socket信息
ParameterTool parameterTool = ParameterTool.fromArgs(args);
// String host = parameterTool.get("host");
// int port = parameterTool.getInt("port");
String host = "172.16.64.85";
int port = 8888;
// 2 从socket读取数据
DataStream<String> inputDataStream = env.socketTextStream(host, port);
DataStream<DeviceInfo> mapStream = inputDataStream.map(new MapFunction<String, DeviceInfo>() {
@Override
public DeviceInfo map(String s) throws Exception {
String[] fields = s.split(",");
return new DeviceInfo(fields[0], new Integer(fields[1]), new Integer(fields[2]), new Long(fields[3]));
}
});
SingleOutputStreamOperator<Tuple2<String, Long>> resultStream = mapStream
.assignTimestampsAndWatermarks(
new BoundedOutOfOrdernessTimestampExtractor<DeviceInfo>(Time.seconds(2)) {
@Override
public long extractTimestamp(DeviceInfo deviceInfo) {
return deviceInfo.getTime() * 1000;
}
})
.keyBy(DeviceInfo::getName)
.window(TumblingEventTimeWindows.of(Time.seconds(10)))
.aggregate(new AggregateFunction<DeviceInfo, Tuple2<String, Long>, Tuple2<String, Long>>() {
@Override
public Tuple2<String, Long> createAccumulator() {
return new Tuple2<>("", 0L);
}
@Override
public Tuple2<String, Long> add(DeviceInfo deviceInfo, Tuple2<String, Long> value) {
value.f0 = deviceInfo.getName();
value.f1 += deviceInfo.getCarNum();
return value;
}
@Override
public Tuple2<String, Long> getResult(Tuple2<String, Long> stringLongTuple2) {
return stringLongTuple2;
}
@Override
public Tuple2<String, Long> merge(Tuple2<String, Long> stringLongTuple2, Tuple2<String, Long> acc1) {
stringLongTuple2.f1 += acc1.f1;
return stringLongTuple2;
}
});
mapStream.print("data");
resultStream.print("sum");
//
// // 2 全窗口测试
// SingleOutputStreamOperator<DeviceInfo> apply = deviceStream.keyBy(devic -> devic.getName())
// .timeWindow(Time.seconds(5))
// .apply(new WindowFunction<DeviceInfo, DeviceInfo, String, TimeWindow>() {
// @Override
// public void apply(String s, TimeWindow timeWindow, Iterable<DeviceInfo> iterable, Collector<DeviceInfo> collector) throws Exception {
// AtomicInteger total = new AtomicInteger();
// AtomicReference<DeviceInfo> deviceInfo = new AtomicReference<>();
// iterable.forEach(dev -> {
// total.addAndGet(dev.getCarNum());
// deviceInfo.set(dev);
// });
// if (deviceInfo != null) {
// deviceInfo.get().setCarNum(total.get());
// }
//
// collector.collect(deviceInfo.get());
// }
// });
// apply.print("apply");
//
env.execute("device job");
}
}
| 5,368 | 0.612172 | 0.60206 | 115 | 45.434784 | 31.752611 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.756522 | false | false | 2 |
2d1ff4760ff3bc8b39ac2975a3c06b071dcb97f8 | 28,140,625,750,851 | fcf4bc88297548d68ccf60f12fad116b3a9e150f | /Part2.java | f9b2f6ac8fbed8c4acb2e54197b91ad70e387b66 | [] | no_license | MichaelRoytman/DatabaseTrends | https://github.com/MichaelRoytman/DatabaseTrends | d21e7a947da78fffa968485367c61df9c786daf1 | 1db79ee966543ef17f33f88d678b26fccf8eaa55 | refs/heads/master | 2020-12-07T21:03:11.590000 | 2016-08-29T00:10:57 | 2016-08-29T00:13:38 | 66,797,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//Michael Roytman
//COSI127B: Database Management Systems
//Professor Cherniack
//Programming Assignment 2
//5.2 Task #2 - Visualizing Trade Relationships by Region
//NOTE: all code except for the query on line 25 and the modification to the initialization of the weight on line 42
//was the existing starter code, so I did not comment extensively on code that was not written by me.
import java.sql.*;
import edu.brandeis.cs127b.pa2.graphviz.*;
public class Part2 {
static final String JDBC_DRIVER = "com.postgresql.jdbc.Driver";
static final String DB_TYPE = "postgresql";
static final String DB_DRIVER = "jdbc";
static final String DB_NAME = System.getenv("PGDATABASE");
static final String DB_HOST = System.getenv("PGHOST");
static final String DB_URL = String.format("%s:%s://%s/%s",DB_DRIVER, DB_TYPE, DB_HOST, DB_NAME);
static final String DB_USER = System.getenv("PGUSER");
static final String DB_PASSWORD = System.getenv("PGPASSWORD");
//query to generate the flow of currency between regions; all other code, except the weight modification on line 39
//was the existing starter code
static final String QUERY = "SELECT R1.r_name, R2.r_name, SUM(l_extendedprice * (1+l_tax) * (1-l_discount)) FROM region AS R1"
+ " INNER JOIN nation ON R1.r_regionkey = n_regionkey INNER JOIN customer ON n_nationkey = c_nationkey INNER JOIN orders ON c_custkey = o_custkey"
+ " INNER JOIN lineitem ON o_orderkey = l_orderkey INNER JOIN supplier ON l_suppkey = s_suppkey INNER JOIN nation AS N2 ON"
+ " s_nationkey = N2.n_nationkey INNER JOIN region AS R2 ON N2.n_regionkey = R2.r_regionkey GROUP BY R1.r_name, R2.r_name;";
public static void main(String[] args) throws SQLException{
DirectedGraph g = new DirectedGraph();
try {
Connection conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(QUERY);
String fromLabel;
String toLabel;
String weight;
while ( rs.next() ) {
fromLabel = rs.getString(1).trim();
toLabel = rs.getString(2).trim();
//gets the weight as an int from the ResultSet, divides the integer by 1,000,000 (as edges are represented in millions), concatenate
//to String "$", and concatenates the letter "M" to represent millions
weight = ("$"+(rs.getInt(3)/1000000)).trim() + "M";
Node from = new Node(fromLabel);
Node to = new Node(toLabel);
DirectedEdge e = new DirectedEdge(from, to);
e.addLabel(weight);
g.add(e);
}
System.out.println(g);
} catch (SQLException s) {
throw s;
}
}
} | UTF-8 | Java | 2,588 | java | Part2.java | Java | [
{
"context": "\n//Michael Roytman\n//COSI127B: Database Management Systems\n//Profess",
"end": 18,
"score": 0.9997822046279907,
"start": 3,
"tag": "NAME",
"value": "Michael Roytman"
},
{
"context": "Roytman\n//COSI127B: Database Management Systems\n//Professor Cherniack\n//Programmin... | null | [] |
//<NAME>
//COSI127B: Database Management Systems
//Professor Cherniack
//Programming Assignment 2
//5.2 Task #2 - Visualizing Trade Relationships by Region
//NOTE: all code except for the query on line 25 and the modification to the initialization of the weight on line 42
//was the existing starter code, so I did not comment extensively on code that was not written by me.
import java.sql.*;
import edu.brandeis.cs127b.pa2.graphviz.*;
public class Part2 {
static final String JDBC_DRIVER = "com.postgresql.jdbc.Driver";
static final String DB_TYPE = "postgresql";
static final String DB_DRIVER = "jdbc";
static final String DB_NAME = System.getenv("PGDATABASE");
static final String DB_HOST = System.getenv("PGHOST");
static final String DB_URL = String.format("%s:%s://%s/%s",DB_DRIVER, DB_TYPE, DB_HOST, DB_NAME);
static final String DB_USER = System.getenv("PGUSER");
static final String DB_PASSWORD = System.getenv("PGPASSWORD");
//query to generate the flow of currency between regions; all other code, except the weight modification on line 39
//was the existing starter code
static final String QUERY = "SELECT R1.r_name, R2.r_name, SUM(l_extendedprice * (1+l_tax) * (1-l_discount)) FROM region AS R1"
+ " INNER JOIN nation ON R1.r_regionkey = n_regionkey INNER JOIN customer ON n_nationkey = c_nationkey INNER JOIN orders ON c_custkey = o_custkey"
+ " INNER JOIN lineitem ON o_orderkey = l_orderkey INNER JOIN supplier ON l_suppkey = s_suppkey INNER JOIN nation AS N2 ON"
+ " s_nationkey = N2.n_nationkey INNER JOIN region AS R2 ON N2.n_regionkey = R2.r_regionkey GROUP BY R1.r_name, R2.r_name;";
public static void main(String[] args) throws SQLException{
DirectedGraph g = new DirectedGraph();
try {
Connection conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(QUERY);
String fromLabel;
String toLabel;
String weight;
while ( rs.next() ) {
fromLabel = rs.getString(1).trim();
toLabel = rs.getString(2).trim();
//gets the weight as an int from the ResultSet, divides the integer by 1,000,000 (as edges are represented in millions), concatenate
//to String "$", and concatenates the letter "M" to represent millions
weight = ("$"+(rs.getInt(3)/1000000)).trim() + "M";
Node from = new Node(fromLabel);
Node to = new Node(toLabel);
DirectedEdge e = new DirectedEdge(from, to);
e.addLabel(weight);
g.add(e);
}
System.out.println(g);
} catch (SQLException s) {
throw s;
}
}
} | 2,579 | 0.710201 | 0.691654 | 57 | 44.403507 | 39.162216 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.526316 | false | false | 2 |
0c545c20dfb2c0e717d5c8b14392c44113db6f55 | 1,202,590,871,686 | e448e46a7c03f8bcde41925c06f1e613cd64e849 | /src/com/pighouse/server/springmvc/controller/SecurityCodeController.java | f19b06ddc214f3b26eb74a497094b51876575bda | [] | no_license | wangwengcn/pighouse | https://github.com/wangwengcn/pighouse | 9c122034eb93674fd83997e82f6010da694f94ae | 234dd61313ea8348529c00a9dde668d7350c0c39 | refs/heads/master | 2021-01-23T03:22:04.135000 | 2013-04-20T03:47:02 | 2013-04-20T03:47:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pighouse.server.springmvc.controller;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.pighouse.server.constants.ModelConstant;
import com.pighouse.server.constants.UserConstant;
import com.pighouse.server.domain.vo.AjaxResult;
import com.pighouse.server.utils.SecurityCode;
@Controller
@RequestMapping(value="/securityCode")
@SessionAttributes(UserConstant.SECURITY_CODE)
public class SecurityCodeController {
@RequestMapping(value="/get")
public void getCode(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception
{
response.setContentType("image/jpeg");
OutputStream os = response.getOutputStream();
String code = SecurityCode.getCertPic(os, 60, 30, 21);
modelMap.addAttribute(UserConstant.SECURITY_CODE, code);
os.flush();
os.close();
}
@RequestMapping(value="/validate")
public @ResponseBody AjaxResult validateCode(ModelMap model, SessionStatus status, String securityCode) throws Exception
{
AjaxResult result = new AjaxResult(ModelConstant.RESULT_FALSE_STRING);
String code = (String) model.get(UserConstant.SECURITY_CODE);
if(null == code || null == securityCode)
{
return result;
}
if(code.equalsIgnoreCase(securityCode.trim()))
{
result = new AjaxResult(ModelConstant.RESULT_SUCCESS_STRING);
}
return result;
}
}
| UTF-8 | Java | 1,810 | java | SecurityCodeController.java | Java | [] | null | [] | package com.pighouse.server.springmvc.controller;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.pighouse.server.constants.ModelConstant;
import com.pighouse.server.constants.UserConstant;
import com.pighouse.server.domain.vo.AjaxResult;
import com.pighouse.server.utils.SecurityCode;
@Controller
@RequestMapping(value="/securityCode")
@SessionAttributes(UserConstant.SECURITY_CODE)
public class SecurityCodeController {
@RequestMapping(value="/get")
public void getCode(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception
{
response.setContentType("image/jpeg");
OutputStream os = response.getOutputStream();
String code = SecurityCode.getCertPic(os, 60, 30, 21);
modelMap.addAttribute(UserConstant.SECURITY_CODE, code);
os.flush();
os.close();
}
@RequestMapping(value="/validate")
public @ResponseBody AjaxResult validateCode(ModelMap model, SessionStatus status, String securityCode) throws Exception
{
AjaxResult result = new AjaxResult(ModelConstant.RESULT_FALSE_STRING);
String code = (String) model.get(UserConstant.SECURITY_CODE);
if(null == code || null == securityCode)
{
return result;
}
if(code.equalsIgnoreCase(securityCode.trim()))
{
result = new AjaxResult(ModelConstant.RESULT_SUCCESS_STRING);
}
return result;
}
}
| 1,810 | 0.772376 | 0.769061 | 52 | 32.807693 | 29.000689 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 2 |
603abef0b475d197ebf6239590f081d50f2c60fc | 292,057,831,118 | e516f24608aa05d4f2fe824f64727fa0976264c6 | /app/src/main/java/com/alkiseyyup/demirorentech/soldierotomation/data/model/soldier/SoldierDao.java | be3a6ad187b0dbdeb0789be0dad39367427df9be | [] | no_license | EyyupAlkis/SoldierAutomation | https://github.com/EyyupAlkis/SoldierAutomation | ecb971161c3cf138e77d2802b76c8a5bc249c54f | 78a6909235ce660ce00cacc1d220809e9f6a5e69 | refs/heads/master | 2020-11-28T06:40:58.254000 | 2019-12-24T12:10:12 | 2019-12-24T12:10:12 | 229,731,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alkiseyyup.demirorentech.soldierotomation.data.model.soldier;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface SoldierDao {
@Insert
void insert(SoldierEntity entity);
@Query("SELECT * FROM soldier_table order by id desc")
LiveData<List<SoldierEntity>> getAllSoldiers();
}
| UTF-8 | Java | 422 | java | SoldierDao.java | Java | [] | null | [] | package com.alkiseyyup.demirorentech.soldierotomation.data.model.soldier;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface SoldierDao {
@Insert
void insert(SoldierEntity entity);
@Query("SELECT * FROM soldier_table order by id desc")
LiveData<List<SoldierEntity>> getAllSoldiers();
}
| 422 | 0.767772 | 0.767772 | 19 | 21.210526 | 21.90789 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 2 |
40d8464256f4c93b4ee81ccabceb002cc32d1f34 | 8,856,222,624,064 | 63f1d48d9685adee030f3a91caac7269f04ed0bb | /zefun/src/main/java/com/zefun/web/dto/MemberComboDto.java | b9377948f047ff1b074c63b0a31896b8498893e4 | [
"Apache-2.0"
] | permissive | gaoguofan/jobwisdom | https://github.com/gaoguofan/jobwisdom | d8811ef8cfe7b75a9bbae27d9cdda188968121b2 | 66d9eefb472742d90d6a36ddd01ae9170043dc0a | refs/heads/master | 2016-09-15T08:13:01.260000 | 2016-09-14T10:47:46 | 2016-09-14T10:47:46 | 55,659,988 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zefun.web.dto;
import java.math.BigDecimal;
import java.util.List;
import com.zefun.web.entity.MemberComboProject;
/**
* 会员疗程信息传输对象
* @author 张进军
* @date Oct 24, 2015 10:50:14 AM
*/
public class MemberComboDto {
/** 记录标识 */
private Integer recordId;
/** 疗程标识 */
private Integer comboId;
/** 疗程名称 */
private String comboName;
/** 疗程价格 */
private BigDecimal comboPrice;
/** 疗程图片 */
private String comboImage;
/** 项目总价 */
private BigDecimal projectAmount;
/** 项目数量 */
private Integer projectCount;
/** 剩余数量 */
private Integer remainingCount;
/** 消费门店*/
private String storeName;
/** 部门*/
private String deptName;
/** 销售人员*/
private String lastOperatorName;
/** 过期时间*/
private String overdueTime;
/** 创建时间*/
private String createTime;
/** 是否过期 */
private Integer isTime;
/**项目列表*/
private List<MemberComboProject> projectList;
/** 是否次数限制(0:否,1:是)*/
private Integer isCountLimit;
public Integer getIsCountLimit() {
return isCountLimit;
}
public void setIsCountLimit(Integer isCountLimit) {
this.isCountLimit = isCountLimit;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Integer getIsTime() {
return isTime;
}
public void setIsTime(Integer isTime) {
this.isTime = isTime;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getOverdueTime() {
return overdueTime;
}
public void setOverdueTime(String overdueTime) {
this.overdueTime = overdueTime;
}
public String getLastOperatorName() {
return lastOperatorName;
}
public void setLastOperatorName(String lastOperatorName) {
this.lastOperatorName = lastOperatorName;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public Integer getRecordId() {
return recordId;
}
public void setRecordId(Integer recordId) {
this.recordId = recordId;
}
public Integer getComboId() {
return comboId;
}
public void setComboId(Integer comboId) {
this.comboId = comboId;
}
public String getComboName() {
return comboName;
}
public void setComboName(String comboName) {
this.comboName = comboName;
}
public BigDecimal getComboPrice() {
return comboPrice;
}
public void setComboPrice(BigDecimal comboPrice) {
this.comboPrice = comboPrice;
}
public String getComboImage() {
return comboImage;
}
public void setComboImage(String comboImage) {
this.comboImage = comboImage;
}
public BigDecimal getProjectAmount() {
return projectAmount;
}
public void setProjectAmount(BigDecimal projectAmount) {
this.projectAmount = projectAmount;
}
public Integer getProjectCount() {
return projectCount;
}
public void setProjectCount(Integer projectCount) {
this.projectCount = projectCount;
}
public Integer getRemainingCount() {
return remainingCount;
}
public void setRemainingCount(Integer remainingCount) {
this.remainingCount = remainingCount;
}
public List<MemberComboProject> getProjectList() {
return projectList;
}
public void setProjectList(List<MemberComboProject> projectList) {
this.projectList = projectList;
}
}
| UTF-8 | Java | 3,967 | java | MemberComboDto.java | Java | [
{
"context": ".MemberComboProject;\n\n/**\n * 会员疗程信息传输对象\n* @author 张进军\n* @date Oct 24, 2015 10:50:14 AM \n*/\npublic class",
"end": 161,
"score": 0.9988929629325867,
"start": 158,
"tag": "NAME",
"value": "张进军"
}
] | null | [] | package com.zefun.web.dto;
import java.math.BigDecimal;
import java.util.List;
import com.zefun.web.entity.MemberComboProject;
/**
* 会员疗程信息传输对象
* @author 张进军
* @date Oct 24, 2015 10:50:14 AM
*/
public class MemberComboDto {
/** 记录标识 */
private Integer recordId;
/** 疗程标识 */
private Integer comboId;
/** 疗程名称 */
private String comboName;
/** 疗程价格 */
private BigDecimal comboPrice;
/** 疗程图片 */
private String comboImage;
/** 项目总价 */
private BigDecimal projectAmount;
/** 项目数量 */
private Integer projectCount;
/** 剩余数量 */
private Integer remainingCount;
/** 消费门店*/
private String storeName;
/** 部门*/
private String deptName;
/** 销售人员*/
private String lastOperatorName;
/** 过期时间*/
private String overdueTime;
/** 创建时间*/
private String createTime;
/** 是否过期 */
private Integer isTime;
/**项目列表*/
private List<MemberComboProject> projectList;
/** 是否次数限制(0:否,1:是)*/
private Integer isCountLimit;
public Integer getIsCountLimit() {
return isCountLimit;
}
public void setIsCountLimit(Integer isCountLimit) {
this.isCountLimit = isCountLimit;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Integer getIsTime() {
return isTime;
}
public void setIsTime(Integer isTime) {
this.isTime = isTime;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getOverdueTime() {
return overdueTime;
}
public void setOverdueTime(String overdueTime) {
this.overdueTime = overdueTime;
}
public String getLastOperatorName() {
return lastOperatorName;
}
public void setLastOperatorName(String lastOperatorName) {
this.lastOperatorName = lastOperatorName;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public Integer getRecordId() {
return recordId;
}
public void setRecordId(Integer recordId) {
this.recordId = recordId;
}
public Integer getComboId() {
return comboId;
}
public void setComboId(Integer comboId) {
this.comboId = comboId;
}
public String getComboName() {
return comboName;
}
public void setComboName(String comboName) {
this.comboName = comboName;
}
public BigDecimal getComboPrice() {
return comboPrice;
}
public void setComboPrice(BigDecimal comboPrice) {
this.comboPrice = comboPrice;
}
public String getComboImage() {
return comboImage;
}
public void setComboImage(String comboImage) {
this.comboImage = comboImage;
}
public BigDecimal getProjectAmount() {
return projectAmount;
}
public void setProjectAmount(BigDecimal projectAmount) {
this.projectAmount = projectAmount;
}
public Integer getProjectCount() {
return projectCount;
}
public void setProjectCount(Integer projectCount) {
this.projectCount = projectCount;
}
public Integer getRemainingCount() {
return remainingCount;
}
public void setRemainingCount(Integer remainingCount) {
this.remainingCount = remainingCount;
}
public List<MemberComboProject> getProjectList() {
return projectList;
}
public void setProjectList(List<MemberComboProject> projectList) {
this.projectList = projectList;
}
}
| 3,967 | 0.630349 | 0.626674 | 193 | 18.735752 | 17.864998 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341969 | false | false | 2 |
9af5f0f2608361f97eccafba724324fb070867d1 | 19,954,418,101,855 | 01269ec31954cc4ee3353572bfb34fdfa3150561 | /src/com/zcs/entity/Fenye.java | b5f1cd2bb2860e2a8a58b08bbe45c6b44ca69a3c | [] | no_license | sxm7/test | https://github.com/sxm7/test | bda6e3deef21fba8741f17b3c2f6548a58a31aa4 | 0b700eb375d5e8d8b3b11b73ea0090abd31cdfc8 | refs/heads/master | 2020-05-17T12:24:57.397000 | 2019-05-19T06:31:02 | 2019-05-19T06:31:09 | 183,547,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zcs.entity;
import java.util.List;
import org.springframework.stereotype.Controller;
@Controller
public class Fenye {
private Integer page;
private Integer pageSize;
private Integer total;
private List<Product> rows;
private String pname;
private Double startjiage;
private Double eddjiage;
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<Product> getRows() {
return rows;
}
public void setRows(List<Product> rows) {
this.rows = rows;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getStartjiage() {
return startjiage;
}
public void setStartjiage(Double startjiage) {
this.startjiage = startjiage;
}
public Double getEddjiage() {
return eddjiage;
}
public void setEddjiage(Double eddjiage) {
this.eddjiage = eddjiage;
}
}
| UTF-8 | Java | 1,221 | java | Fenye.java | Java | [] | null | [] | package com.zcs.entity;
import java.util.List;
import org.springframework.stereotype.Controller;
@Controller
public class Fenye {
private Integer page;
private Integer pageSize;
private Integer total;
private List<Product> rows;
private String pname;
private Double startjiage;
private Double eddjiage;
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<Product> getRows() {
return rows;
}
public void setRows(List<Product> rows) {
this.rows = rows;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getStartjiage() {
return startjiage;
}
public void setStartjiage(Double startjiage) {
this.startjiage = startjiage;
}
public Double getEddjiage() {
return eddjiage;
}
public void setEddjiage(Double eddjiage) {
this.eddjiage = eddjiage;
}
}
| 1,221 | 0.686323 | 0.686323 | 59 | 18.694916 | 14.070349 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.508475 | false | false | 2 |
9d12fc8074718822a067b2e2eb873ffd6393e2b5 | 23,759,759,127,059 | 46130c1d2388e245d43b00e150359702eeebe4eb | /hi_choi/spring/annotation/SungJukServiceImpl.java | a6d52c29c926100a0a79b2a3d627f737a27861a2 | [] | no_license | hi-choi/SpringBasic | https://github.com/hi-choi/SpringBasic | 062267fd211c512b06294f2d149b16d32b13918c | 1acbd62a9f4fab9efc1057254752c88ad68a735f | refs/heads/main | 2023-05-13T14:38:12.820000 | 2021-05-31T04:14:29 | 2021-05-31T04:14:29 | 371,634,736 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hi_choi.spring.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hi_choi.spring.sungjuk.SungJuk;
import hi_choi.spring.sungjuk.SungJukDAO;
import hi_choi.spring.sungjuk.SungJukService;
//SungJukService 인터페이스의 메서드를 구체화하는 클래스
@Service("sjsrv")
public class SungJukServiceImpl implements SungJukService {
@Autowired
private SungJukDAO sdao;
@Override
public void newSungJuk() {
SungJuk sj = new SungJuk("혜교",99,96,76);
System.out.println("성적 생성됨!");
// SungJukDAO로 생성한 객체 전달
// 이후, 이 전달된 값은 SungJukDAOImpl에서 사용됨
sdao.insertSungJuk(sj);
}
}
| UTF-8 | Java | 793 | java | SungJukServiceImpl.java | Java | [
{
"context": "d newSungJuk() {\r\n\t\t\r\n\t\tSungJuk sj = new SungJuk(\"혜교\",99,96,76);\r\n\t\t\r\n\t\tSystem.out.println(\"성적 생성됨!\");",
"end": 528,
"score": 0.7292467355728149,
"start": 526,
"tag": "NAME",
"value": "혜교"
}
] | null | [] | package hi_choi.spring.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hi_choi.spring.sungjuk.SungJuk;
import hi_choi.spring.sungjuk.SungJukDAO;
import hi_choi.spring.sungjuk.SungJukService;
//SungJukService 인터페이스의 메서드를 구체화하는 클래스
@Service("sjsrv")
public class SungJukServiceImpl implements SungJukService {
@Autowired
private SungJukDAO sdao;
@Override
public void newSungJuk() {
SungJuk sj = new SungJuk("혜교",99,96,76);
System.out.println("성적 생성됨!");
// SungJukDAO로 생성한 객체 전달
// 이후, 이 전달된 값은 SungJukDAOImpl에서 사용됨
sdao.insertSungJuk(sj);
}
}
| 793 | 0.710414 | 0.701854 | 35 | 18.028572 | 19.447344 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.171429 | false | false | 2 |
83216999e62e6b02e7f715ea1ad9d37bb3d6e498 | 13,675,175,900,985 | 83cc2eb6737625f5ff131ed867f14ea9b3e2cddb | /Multiplicationtable.java | c9487fdfd85d64b061714b948ffc3e96c0c33091 | [] | no_license | Vigneshutta/lk | https://github.com/Vigneshutta/lk | 906bd19c44e2404423c46dedcb32f53f4c59b895 | 5730b3c2371a85b053176a8976e0486e081e468e | refs/heads/master | 2020-12-02T11:06:11.492000 | 2017-07-08T06:26:22 | 2017-07-08T06:26:22 | 96,600,431 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
import java.io.*;
public class Multiplicationtable
{
public static void main(String[] args)throws IOException
{
int num;
BufferedReader vc=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a positive integer");
num=Integer.parseInt(vc.readLine());
for (int i = 1; i <= 10; ++i) {
System.out.printf("%d * %d = %d \n", num, i, num * i);
}
}
}
| UTF-8 | Java | 422 | java | Multiplicationtable.java | Java | [] | null | [] | import java.util.*;
import java.io.*;
public class Multiplicationtable
{
public static void main(String[] args)throws IOException
{
int num;
BufferedReader vc=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a positive integer");
num=Integer.parseInt(vc.readLine());
for (int i = 1; i <= 10; ++i) {
System.out.printf("%d * %d = %d \n", num, i, num * i);
}
}
}
| 422 | 0.649289 | 0.64218 | 16 | 25.375 | 24.173527 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 2 |
bec23cf9ca0ef397992f6f6e594cd2be6947c5d3 | 1,700,807,104,239 | 3ae5e9d5ef90a35b9e5cd72eb786f7544837ba8a | /35_1_多线程断点续传下载/src/com/cmcc/download/MultiDownload.java | 027dfd3b890eb684efbd932423a29b03d179c4fd | [
"MIT"
] | permissive | scoldfield/android | https://github.com/scoldfield/android | 36b08c821cf13f56d925153859c061c95962b809 | bd8b7bf2a5e4f264e611bf4184c4cb3ffa89361c | refs/heads/master | 2021-01-20T22:18:57.946000 | 2016-07-18T01:16:18 | 2016-07-18T01:16:18 | 63,559,931 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cmcc.download;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.cmcc.download.MultiDownload.ThreadDownload;
//文件的 多线程 + 断点续传 下载
public class MultiDownload {
private static String PATH = "http://localhost:8080/test.exe";
private static final int THREADCOUNT = 3; //开启3个线程用于下载
private static int runningThread = THREADCOUNT; //表示当前正在运行的线程
public static void main(String[] args) {
try {
//[1]获取服务器文件的大小,计算每个线程下载的开始位置和结束位置
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if(code == 200) {
//[1.1]获取文件的长度
int length = conn.getContentLength();
System.out.println("文件的长度为:"+length);
//[2]创建一个大小和服务器一模一样的文件。目的是提前把空间申请出来
RandomAccessFile raf = new RandomAccessFile("d:\\" + getFilename(PATH), "rw");
raf.setLength(length);
//[3]计算每个线程下载的开始位置和结束位置
//[3.1]每个线程下载的文件大小
int blockSize = length / THREADCOUNT;
for(int i = 0; i < THREADCOUNT; i++) {
//[3.2]每个线程下载的起始于结束位置
int startIndex = i * blockSize;
int endIndex = (i + 1) * blockSize - 1;
//[3.3]特殊情况:最后一个线程的结束位置肯定是文件末尾
if(i == THREADCOUNT - 1) {
endIndex = length - 1;
}
//[4]开启线程去服务器下载文件
ThreadDownload thread = new ThreadDownload(startIndex, endIndex, i);
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class ThreadDownload extends Thread{
private int startIndex;
private int endIndex;
private int threadId;
public ThreadDownload(int startIndex, int endIndex, int threadId) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
try {
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
//[4.1.1]这里需要判断存储下载位置的文件是否存在
File file = new File("d:\\" + getFilename(PATH) +"_" + threadId + ".txt");
if(file.exists() && file.length() > 0) {
//文件存在
BufferedReader reader = new BufferedReader(new FileReader(file));
String lastPosition = reader.readLine();
//将下载的起始位置换成上次记录的位置的下一位
startIndex = Integer.parseInt(lastPosition);
System.out.println("线程" + threadId + "真实下载位置:" + startIndex + "------" + endIndex);
reader.close();
}
//[4.1.2]设置一个请求头属性Range。告诉服务器从哪个位置开始下载,从哪个位置结束
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
int code = conn.getResponseCode();
//[4.2]200:表示获取服务器全部资源成功;206:表示获取服务器部分资源成功
if(code == 206) {
//[4.3]拿到已经创建的文件,准备向其中写入数据。注意:必须每个线程中单独获取该句柄,不能使用同一个,不知道为什么
RandomAccessFile raf = new RandomAccessFile("d:\\" + getFilename(PATH), "rw");
//[4.4]设置每个线程要从自己的位置开始写
raf.seek(startIndex);
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024*1024];
int len = -1;
//[4.5.1]currentPosition用来记录当前从服务器上下载到的文件的位置
int currentPosition = startIndex;
while((len = in.read(buffer)) != -1) {
raf.write(buffer, 0, len);
currentPosition += len;
//[4.6]将位置信息存储到外部文件中。使用RandomAccessFile类,而不是File类,因为File类会首先将信息存储到缓存中,一旦断电,可能来不及存储到硬盘中;而RandomAccessFile可以解决此问题,"rwd"方法会直接将数据存储到硬盘中,不经过缓存
RandomAccessFile raff = new RandomAccessFile("d:\\" + getFilename(PATH) +"_" + threadId+".txt", "rwd");
raff.write((currentPosition+"").getBytes());
raff.close();
}
raf.close();
System.out.println("线程"+threadId+"下载完成");
//[4.7]当所有线程下载完成后,把存储下载位置的文件.txt删除。通过runningThread来判断是否所有线程都下载完成
runningThread--;
if(runningThread == 0) {
//所有线程都执行完毕了
for(int i = 0; i < THREADCOUNT; i++) {
File file1 = new File("d:\\" + getFilename(PATH) +"_"+i+".txt");
file1.delete();
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
//获取文件名字:"http://localhost:8080/test.exe";
public static String getFilename(String path) {
return path.substring(path.lastIndexOf("/"));
}
}
| GB18030 | Java | 7,064 | java | MultiDownload.java | Java | [] | null | [] | package com.cmcc.download;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.cmcc.download.MultiDownload.ThreadDownload;
//文件的 多线程 + 断点续传 下载
public class MultiDownload {
private static String PATH = "http://localhost:8080/test.exe";
private static final int THREADCOUNT = 3; //开启3个线程用于下载
private static int runningThread = THREADCOUNT; //表示当前正在运行的线程
public static void main(String[] args) {
try {
//[1]获取服务器文件的大小,计算每个线程下载的开始位置和结束位置
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if(code == 200) {
//[1.1]获取文件的长度
int length = conn.getContentLength();
System.out.println("文件的长度为:"+length);
//[2]创建一个大小和服务器一模一样的文件。目的是提前把空间申请出来
RandomAccessFile raf = new RandomAccessFile("d:\\" + getFilename(PATH), "rw");
raf.setLength(length);
//[3]计算每个线程下载的开始位置和结束位置
//[3.1]每个线程下载的文件大小
int blockSize = length / THREADCOUNT;
for(int i = 0; i < THREADCOUNT; i++) {
//[3.2]每个线程下载的起始于结束位置
int startIndex = i * blockSize;
int endIndex = (i + 1) * blockSize - 1;
//[3.3]特殊情况:最后一个线程的结束位置肯定是文件末尾
if(i == THREADCOUNT - 1) {
endIndex = length - 1;
}
//[4]开启线程去服务器下载文件
ThreadDownload thread = new ThreadDownload(startIndex, endIndex, i);
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class ThreadDownload extends Thread{
private int startIndex;
private int endIndex;
private int threadId;
public ThreadDownload(int startIndex, int endIndex, int threadId) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
try {
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
//[4.1.1]这里需要判断存储下载位置的文件是否存在
File file = new File("d:\\" + getFilename(PATH) +"_" + threadId + ".txt");
if(file.exists() && file.length() > 0) {
//文件存在
BufferedReader reader = new BufferedReader(new FileReader(file));
String lastPosition = reader.readLine();
//将下载的起始位置换成上次记录的位置的下一位
startIndex = Integer.parseInt(lastPosition);
System.out.println("线程" + threadId + "真实下载位置:" + startIndex + "------" + endIndex);
reader.close();
}
//[4.1.2]设置一个请求头属性Range。告诉服务器从哪个位置开始下载,从哪个位置结束
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
int code = conn.getResponseCode();
//[4.2]200:表示获取服务器全部资源成功;206:表示获取服务器部分资源成功
if(code == 206) {
//[4.3]拿到已经创建的文件,准备向其中写入数据。注意:必须每个线程中单独获取该句柄,不能使用同一个,不知道为什么
RandomAccessFile raf = new RandomAccessFile("d:\\" + getFilename(PATH), "rw");
//[4.4]设置每个线程要从自己的位置开始写
raf.seek(startIndex);
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024*1024];
int len = -1;
//[4.5.1]currentPosition用来记录当前从服务器上下载到的文件的位置
int currentPosition = startIndex;
while((len = in.read(buffer)) != -1) {
raf.write(buffer, 0, len);
currentPosition += len;
//[4.6]将位置信息存储到外部文件中。使用RandomAccessFile类,而不是File类,因为File类会首先将信息存储到缓存中,一旦断电,可能来不及存储到硬盘中;而RandomAccessFile可以解决此问题,"rwd"方法会直接将数据存储到硬盘中,不经过缓存
RandomAccessFile raff = new RandomAccessFile("d:\\" + getFilename(PATH) +"_" + threadId+".txt", "rwd");
raff.write((currentPosition+"").getBytes());
raff.close();
}
raf.close();
System.out.println("线程"+threadId+"下载完成");
//[4.7]当所有线程下载完成后,把存储下载位置的文件.txt删除。通过runningThread来判断是否所有线程都下载完成
runningThread--;
if(runningThread == 0) {
//所有线程都执行完毕了
for(int i = 0; i < THREADCOUNT; i++) {
File file1 = new File("d:\\" + getFilename(PATH) +"_"+i+".txt");
file1.delete();
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
//获取文件名字:"http://localhost:8080/test.exe";
public static String getFilename(String path) {
return path.substring(path.lastIndexOf("/"));
}
}
| 7,064 | 0.483494 | 0.469823 | 145 | 39.365517 | 26.469193 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565517 | false | false | 2 |
aa573df27156d3ef95440f2992b88664a26cecde | 22,342,419,920,575 | 314a5c5f7f91ed46fa751cfe3f00505181c499c5 | /model/src/main/java/com/ewell/android/model/EMProperties.java | bc8acff1623cda3a603e701d622189fad2bebd0f | [] | no_license | djg2015/sleepcareforandroidphone | https://github.com/djg2015/sleepcareforandroidphone | db54e67a73ddb39ab8a3ef8903a3646859a3a4fc | ff86114844dee94ca10c314b10b7e49b0471955e | refs/heads/master | 2021-01-20T20:28:50.977000 | 2016-08-19T08:18:32 | 2016-08-19T08:18:32 | 63,292,835 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ewell.android.model;
import org.jdom.JDOMException;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by Dongjg on 2016-7-12.
*/
public class EMProperties extends BaseMessage {
private Map params = new HashMap();
public EMProperties(String operate, String bizCode) {
super(operate, bizCode);
}
/*
*设置键值
*/
public void AddKeyValue(String key, String value) {
this.params.put(key, value);
}
@Override
public String ToBodytXml() {
String bodyXml = "<EMProperties>";
Set ss=params.entrySet() ;//返回Map.Entry 接口实现
Iterator i=ss.iterator() ; //通过 Map.Entry静态接口 获取元素
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next() ;//强制转换
System.out.println(me.getKey()+":"+me.getValue());
bodyXml +="<EMProperty name=\""+ me.getKey() +"\" value=\""+ me.getValue() +"\" />";
}
bodyXml += "</EMProperties>";
return bodyXml;
}
}
| UTF-8 | Java | 1,190 | java | EMProperties.java | Java | [
{
"context": "util.Map;\nimport java.util.Set;\n\n/**\n * Created by Dongjg on 2016-7-12.\n */\npublic class EMProperties exten",
"end": 275,
"score": 0.9996225833892822,
"start": 269,
"tag": "USERNAME",
"value": "Dongjg"
}
] | null | [] | package com.ewell.android.model;
import org.jdom.JDOMException;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by Dongjg on 2016-7-12.
*/
public class EMProperties extends BaseMessage {
private Map params = new HashMap();
public EMProperties(String operate, String bizCode) {
super(operate, bizCode);
}
/*
*设置键值
*/
public void AddKeyValue(String key, String value) {
this.params.put(key, value);
}
@Override
public String ToBodytXml() {
String bodyXml = "<EMProperties>";
Set ss=params.entrySet() ;//返回Map.Entry 接口实现
Iterator i=ss.iterator() ; //通过 Map.Entry静态接口 获取元素
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next() ;//强制转换
System.out.println(me.getKey()+":"+me.getValue());
bodyXml +="<EMProperty name=\""+ me.getKey() +"\" value=\""+ me.getValue() +"\" />";
}
bodyXml += "</EMProperties>";
return bodyXml;
}
}
| 1,190 | 0.610333 | 0.604203 | 47 | 23.297873 | 21.849499 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510638 | false | false | 2 |
f372bf87d294890c82a19570123a9378920064f8 | 4,930,622,513,788 | 82417a8841353513159766d118698c822dafb9ba | /jrtr/src/jrtr/Leaf.java | a31ab737e6bf982bbbd780194afde37f267652ae | [] | no_license | shirsbrunner/CG | https://github.com/shirsbrunner/CG | 0f09a0f6b53f9d95f21674249702c5da80fb4034 | f0ef5f7f0c842e457d609fc65784164f8983ce6a | refs/heads/master | 2021-01-19T22:01:39.564000 | 2012-11-30T13:58:10 | 2012-11-30T13:58:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jrtr;
import java.util.LinkedList;
public abstract class Leaf implements INode{
@Override
public LinkedList<INode> getChildren() {
return null; //has no children
}
}
| UTF-8 | Java | 199 | java | Leaf.java | Java | [] | null | [] | package jrtr;
import java.util.LinkedList;
public abstract class Leaf implements INode{
@Override
public LinkedList<INode> getChildren() {
return null; //has no children
}
}
| 199 | 0.683417 | 0.683417 | 13 | 13.307693 | 16.169224 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 2 |
289d73ff7a501f5d84bd134a543afae5070732b3 | 4,930,622,510,013 | 617d4062b4280a5d131dce0038a41b225fefcdf4 | /src/org/sopiro/game/renderer/MasterRenderer.java | d3659fd47e365208555b6526989d768948e585d6 | [] | no_license | Sopiro/Java-OpenGL-Render-Engine | https://github.com/Sopiro/Java-OpenGL-Render-Engine | e0bbb3d7744d073d3be46ee3311096093d7263c1 | 46b3905f7c1bda53688b8c14adfe009be8068ed3 | refs/heads/master | 2020-11-26T12:00:22.588000 | 2020-03-17T19:42:39 | 2020-03-17T19:42:39 | 229,065,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sopiro.game.renderer;
import static org.lwjgl.opengl.GL11.*;
import java.lang.Math;
import java.util.*;
import org.joml.*;
import org.sopiro.game.*;
import org.sopiro.game.animation.AnimatedModel;
import org.sopiro.game.animation.AnimationRenderer;
import org.sopiro.game.animation.AnimationShader;
import org.sopiro.game.entities.*;
import org.sopiro.game.entities.light.*;
import org.sopiro.game.models.*;
import org.sopiro.game.postProcess.*;
import org.sopiro.game.shadow.*;
import org.sopiro.game.skyBox.*;
import org.sopiro.game.terrain.*;
import org.sopiro.game.texture.*;
import org.sopiro.game.utils.*;
public class MasterRenderer
{
public static final float FOV = (float) Math.toRadians(87);
public static final float NEAR_PLANE = 0.1f; //(float) (1.0 / Math.tan(FOV/2));
public static final float FAR_PLANE = 2000f;
private static final Vector3f FOG_COLOR = new Vector3f(185 / 255.0f, 223 / 255.0f, 253 / 255.0f);
private Matrix4f projectionMatrix;
private float time = 0;
private boolean postProcessEnabled = true;
private PostProcesser postProcesser;
private MultiSampleFrameBuffer msaa;
private EntityShader entityShader = new EntityShader();
private EntityRenderer entityRenderer;
private TerrainShader terrainShader = new TerrainShader();
private TerrainRenderer terrainRenderer;
private SkyBoxRenderer skyboxRenderer;
private ShadowMapRenderer shadowMapRenderer;
private int shadowMapSize = 6000;
private int shadowDistance = 500;
private int shadowOffset = 300;
private Map<TexturedModel, List<Entity>> entities = new HashMap<TexturedModel, List<Entity>>();
private List<Terrain> terrains = new ArrayList<Terrain>();
private AnimationShader animationShader = new AnimationShader();
private AnimationRenderer animationRenderer;
private AnimatedModel animatedModel;
public MasterRenderer(Loader loader)
{
GLUtills.initOpenGLSettings();
projectionMatrix = createProjectionMatrix();
entityRenderer = new EntityRenderer(entityShader, projectionMatrix);
terrainRenderer = new TerrainRenderer(terrainShader, projectionMatrix);
skyboxRenderer = new SkyBoxRenderer(loader, projectionMatrix);
shadowMapRenderer = new ShadowMapRenderer(shadowMapSize, shadowMapSize, shadowDistance, shadowOffset);
animationRenderer = new AnimationRenderer(animationShader, projectionMatrix);
msaa = new MultiSampleFrameBuffer();
postProcesser = new PostProcesser(loader);
}
public static void enableCulling()
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
public static void disableCulling()
{
glDisable(GL_CULL_FACE);
}
public void render(List<Light> lights, Camera camera)
{
time++;
Sun sun = (Sun) lights.get(0);
shadowMapRenderer.render(camera, sun, entities);
Texture shadowMap = new Texture(shadowMapRenderer.getShadowMap());
Matrix4f lightSpaceMatrix = shadowMapRenderer.getLightSpaceMatrix();
if (postProcessEnabled)
msaa.bind();
prepare();
terrainShader.start();
terrainShader.setSkyColor(FOG_COLOR);
terrainShader.setLights(lights);
terrainShader.setViewMatrix(camera);
terrainRenderer.setShadowMap(shadowMap, lightSpaceMatrix, shadowMapSize);
terrainRenderer.render(terrains);
terrainShader.stop();
entityShader.start();
entityShader.updateTime(time);
entityShader.setSkyColor(FOG_COLOR);
entityShader.setLights(lights);
entityShader.setViewMatrix(camera);
entityRenderer.setShadowMap(shadowMap, lightSpaceMatrix, shadowMapSize);
entityRenderer.render(entities);
entityShader.stop();
animationShader.start();
animationShader.setViewMatrix(camera);
animationShader.setTransformationMatrix(Maths.createTransformationMatrix(
new Vector3f(0, 0, 0),
new Vector3f(0, 0, 0),
10));
animationRenderer.render(animatedModel);
animationShader.stop();
skyboxRenderer.render(camera, FOG_COLOR, 2.5f);
terrains.clear();
entities.clear();
if (postProcessEnabled)
{
msaa.unbind();
int screenTexture = msaa.getScreenTexure();
postProcesser.postProcess(screenTexture);
}
}
private void prepare()
{
glClearColor(FOG_COLOR.x, FOG_COLOR.y, FOG_COLOR.z, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
public void processTerrain(Terrain terrain)
{
terrains.add(terrain);
}
public void processTerrain(List<Terrain> terrains)
{
this.terrains.addAll(terrains);
}
public void processEntity(Entity entity)
{
TexturedModel entityModel = entity.getModel();
List<Entity> batch = entities.get(entityModel);
if (batch != null)
{
batch.add(entity);
} else
{
List<Entity> newBatch = new ArrayList<Entity>();
newBatch.add(entity);
entities.put(entityModel, newBatch);
}
}
public void terminate()
{
shadowMapRenderer.terminate();
msaa.terminate();
postProcesser.terminate();
entityShader.terminate();
terrainShader.terminate();
animationShader.terminate();
}
public void zoom(float zoom)
{
this.projectionMatrix = new Matrix4f().perspective((float) Math.toRadians(zoom), Window.getWindowAspectRatio(), NEAR_PLANE, FAR_PLANE);
entityRenderer.setProjectionMatrix(projectionMatrix);
terrainRenderer.setProjectionMatrix(projectionMatrix);
}
public void resetZoom()
{
zoom(FOV);
}
private Matrix4f createProjectionMatrix()
{
// return new Matrix4f().ortho(-100, 100, -100, 100, 0.1f, 1000);
return new Matrix4f().perspective(FOV, Window.getWindowAspectRatio(), NEAR_PLANE, FAR_PLANE);
}
public void processAnimatedModel(AnimatedModel animatedModel)
{
this.animatedModel = animatedModel;
}
public void togglePostProcessEnabled()
{
if (postProcessEnabled)
{
setPostProcessEnabled(false);
} else
setPostProcessEnabled(true);
}
public void setPostProcessEnabled(boolean doPostProcess)
{
this.postProcessEnabled = doPostProcess;
}
}
| UTF-8 | Java | 6,590 | java | MasterRenderer.java | Java | [] | null | [] | package org.sopiro.game.renderer;
import static org.lwjgl.opengl.GL11.*;
import java.lang.Math;
import java.util.*;
import org.joml.*;
import org.sopiro.game.*;
import org.sopiro.game.animation.AnimatedModel;
import org.sopiro.game.animation.AnimationRenderer;
import org.sopiro.game.animation.AnimationShader;
import org.sopiro.game.entities.*;
import org.sopiro.game.entities.light.*;
import org.sopiro.game.models.*;
import org.sopiro.game.postProcess.*;
import org.sopiro.game.shadow.*;
import org.sopiro.game.skyBox.*;
import org.sopiro.game.terrain.*;
import org.sopiro.game.texture.*;
import org.sopiro.game.utils.*;
public class MasterRenderer
{
public static final float FOV = (float) Math.toRadians(87);
public static final float NEAR_PLANE = 0.1f; //(float) (1.0 / Math.tan(FOV/2));
public static final float FAR_PLANE = 2000f;
private static final Vector3f FOG_COLOR = new Vector3f(185 / 255.0f, 223 / 255.0f, 253 / 255.0f);
private Matrix4f projectionMatrix;
private float time = 0;
private boolean postProcessEnabled = true;
private PostProcesser postProcesser;
private MultiSampleFrameBuffer msaa;
private EntityShader entityShader = new EntityShader();
private EntityRenderer entityRenderer;
private TerrainShader terrainShader = new TerrainShader();
private TerrainRenderer terrainRenderer;
private SkyBoxRenderer skyboxRenderer;
private ShadowMapRenderer shadowMapRenderer;
private int shadowMapSize = 6000;
private int shadowDistance = 500;
private int shadowOffset = 300;
private Map<TexturedModel, List<Entity>> entities = new HashMap<TexturedModel, List<Entity>>();
private List<Terrain> terrains = new ArrayList<Terrain>();
private AnimationShader animationShader = new AnimationShader();
private AnimationRenderer animationRenderer;
private AnimatedModel animatedModel;
public MasterRenderer(Loader loader)
{
GLUtills.initOpenGLSettings();
projectionMatrix = createProjectionMatrix();
entityRenderer = new EntityRenderer(entityShader, projectionMatrix);
terrainRenderer = new TerrainRenderer(terrainShader, projectionMatrix);
skyboxRenderer = new SkyBoxRenderer(loader, projectionMatrix);
shadowMapRenderer = new ShadowMapRenderer(shadowMapSize, shadowMapSize, shadowDistance, shadowOffset);
animationRenderer = new AnimationRenderer(animationShader, projectionMatrix);
msaa = new MultiSampleFrameBuffer();
postProcesser = new PostProcesser(loader);
}
public static void enableCulling()
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
public static void disableCulling()
{
glDisable(GL_CULL_FACE);
}
public void render(List<Light> lights, Camera camera)
{
time++;
Sun sun = (Sun) lights.get(0);
shadowMapRenderer.render(camera, sun, entities);
Texture shadowMap = new Texture(shadowMapRenderer.getShadowMap());
Matrix4f lightSpaceMatrix = shadowMapRenderer.getLightSpaceMatrix();
if (postProcessEnabled)
msaa.bind();
prepare();
terrainShader.start();
terrainShader.setSkyColor(FOG_COLOR);
terrainShader.setLights(lights);
terrainShader.setViewMatrix(camera);
terrainRenderer.setShadowMap(shadowMap, lightSpaceMatrix, shadowMapSize);
terrainRenderer.render(terrains);
terrainShader.stop();
entityShader.start();
entityShader.updateTime(time);
entityShader.setSkyColor(FOG_COLOR);
entityShader.setLights(lights);
entityShader.setViewMatrix(camera);
entityRenderer.setShadowMap(shadowMap, lightSpaceMatrix, shadowMapSize);
entityRenderer.render(entities);
entityShader.stop();
animationShader.start();
animationShader.setViewMatrix(camera);
animationShader.setTransformationMatrix(Maths.createTransformationMatrix(
new Vector3f(0, 0, 0),
new Vector3f(0, 0, 0),
10));
animationRenderer.render(animatedModel);
animationShader.stop();
skyboxRenderer.render(camera, FOG_COLOR, 2.5f);
terrains.clear();
entities.clear();
if (postProcessEnabled)
{
msaa.unbind();
int screenTexture = msaa.getScreenTexure();
postProcesser.postProcess(screenTexture);
}
}
private void prepare()
{
glClearColor(FOG_COLOR.x, FOG_COLOR.y, FOG_COLOR.z, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
public void processTerrain(Terrain terrain)
{
terrains.add(terrain);
}
public void processTerrain(List<Terrain> terrains)
{
this.terrains.addAll(terrains);
}
public void processEntity(Entity entity)
{
TexturedModel entityModel = entity.getModel();
List<Entity> batch = entities.get(entityModel);
if (batch != null)
{
batch.add(entity);
} else
{
List<Entity> newBatch = new ArrayList<Entity>();
newBatch.add(entity);
entities.put(entityModel, newBatch);
}
}
public void terminate()
{
shadowMapRenderer.terminate();
msaa.terminate();
postProcesser.terminate();
entityShader.terminate();
terrainShader.terminate();
animationShader.terminate();
}
public void zoom(float zoom)
{
this.projectionMatrix = new Matrix4f().perspective((float) Math.toRadians(zoom), Window.getWindowAspectRatio(), NEAR_PLANE, FAR_PLANE);
entityRenderer.setProjectionMatrix(projectionMatrix);
terrainRenderer.setProjectionMatrix(projectionMatrix);
}
public void resetZoom()
{
zoom(FOV);
}
private Matrix4f createProjectionMatrix()
{
// return new Matrix4f().ortho(-100, 100, -100, 100, 0.1f, 1000);
return new Matrix4f().perspective(FOV, Window.getWindowAspectRatio(), NEAR_PLANE, FAR_PLANE);
}
public void processAnimatedModel(AnimatedModel animatedModel)
{
this.animatedModel = animatedModel;
}
public void togglePostProcessEnabled()
{
if (postProcessEnabled)
{
setPostProcessEnabled(false);
} else
setPostProcessEnabled(true);
}
public void setPostProcessEnabled(boolean doPostProcess)
{
this.postProcessEnabled = doPostProcess;
}
}
| 6,590 | 0.672079 | 0.659029 | 210 | 30.380953 | 26.171188 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752381 | false | false | 2 |
9718070a4f4c355f4f47492cee157ef9fda9b96a | 6,176,163,027,949 | 5544d207dc6cae9298c9702d6db318caf7af7d9a | /Middle Tier/import-data-and-redis-topic-redis/import-data-and-redis-topic-redis/src/main/java/vrbilby/importdata/service/MessageReceiver.java | 9a7109f888f0266ec3d9d3df9e20d27244c0b076 | [] | no_license | saierding/VR-lab-project | https://github.com/saierding/VR-lab-project | ec13b1e634bd52764c98db7c34ee5551d625bd8a | 94a44d076101c686a857abe84c6c1529c69b6863 | refs/heads/master | 2022-12-13T09:22:52.491000 | 2019-10-27T04:38:58 | 2019-10-27T04:38:58 | 216,013,599 | 0 | 0 | null | false | 2022-12-11T09:54:02 | 2019-10-18T11:57:09 | 2019-10-27T04:39:01 | 2022-12-11T09:54:01 | 9,628 | 0 | 0 | 8 | HTML | false | false | package vrbilby.importdata.service;
import org.springframework.stereotype.Component;
@Component
public class MessageReceiver {
/**function for receice message*/
public void receiveMessage(String message){
System.out.println("receive a message:"+message);
}
}
| UTF-8 | Java | 276 | java | MessageReceiver.java | Java | [] | null | [] | package vrbilby.importdata.service;
import org.springframework.stereotype.Component;
@Component
public class MessageReceiver {
/**function for receice message*/
public void receiveMessage(String message){
System.out.println("receive a message:"+message);
}
}
| 276 | 0.762774 | 0.762774 | 13 | 20 | 20.377213 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 2 |
3cdb97e42a4c64f4364e8a4a1dd2892fcd92651f | 32,624,571,591,081 | 2a70878ac7d1ef2856f1d326d6479970cd3864e5 | /src/my/DB_course_paper/DataForm.java | e3d0a9d7ec4a368c55b06ea91cbf8ebe3a61664d | [] | no_license | Zherr-shaal/DB_course_paper_project | https://github.com/Zherr-shaal/DB_course_paper_project | b26ed88b174edcb66a4441503a822eeefe5e4a63 | cad914d693e53f0a07a7a20a482d4fddcd9ff4f3 | refs/heads/master | 2022-11-16T06:32:48.822000 | 2020-06-26T01:21:13 | 2020-06-26T01:21:13 | 275,046,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package my.DB_course_paper;
import java.sql.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.swing.table.*;
/**
*
* @author Matt
*/
public class DataForm extends javax.swing.JDialog {//Форма приёма данных у пользователя
String SQL;
String[] signature;
DefaultTableModel base_table;
public int selected_id;
Connection connection;
/**
* Creates new form DataForm
*/
public DataForm(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public DataForm(java.awt.Frame parent, boolean modal,DefaultTableModel table_type, boolean rbuttons,String sql,String log,String pass, String[] sign,String mess,int type) {
super(parent, modal);
initComponents();
base_table=table_type;
jPanel1.setVisible(rbuttons);
jButton10.setVisible(false);
jLabel1.setText(mess);
SQL=sql;
signature=sign;
initConnection(log,pass);
first_view();
prepare_form();
set_titles(type);
}
public DataForm(java.awt.Frame parent, boolean modal,DefaultTableModel table_type, boolean rbuttons,String sql,String log,String pass, String[] sign,String mess,int type,Object[] params) {
super(parent, modal);
initComponents();
base_table=table_type;
jPanel1.setVisible(rbuttons);
jButton10.setVisible(false);
jLabel1.setText(mess);
SQL=sql;
signature=sign;
initConnection(log,pass);
first_view(params);
prepare_form();
set_titles(type);
}
private void first_view(){
Object[] parameters=parse_signature();
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
private void first_view(Object[] parameters){
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
private void prepare_form(){
if(signature.length<5){
this.jTextField48.setVisible(false);
this.jLabel56.setVisible(false);
if(signature.length<4){
this.jTextField47.setVisible(false);
this.jLabel55.setVisible(false);
if(signature.length<3){
this.jTextField46.setVisible(false);
this.jLabel54.setVisible(false);
if(signature.length<2){
this.jTextField45.setVisible(false);
this.jLabel53.setVisible(false);
this.jButton10.setText("Прекратить просмотр");
}
}
}
}
}
private void set_titles(int type){
if(type==0){
this.jLabel52.setText("Имя начальника");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Направление деятельности отдела");
}
if(type==1){
this.jLabel52.setText("Имя сотрудника");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
}
if(type==2){
this.jLabel52.setText("Тип оборудования");
this.jLabel53.setText("Производитель оборудования");
}
if(type==3){
this.jLabel52.setText("Имя");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Образование");
this.jLabel56.setText("Научная степень");
}
if(type==4){
jPanel21.setVisible(false);
}
if(type==5){
this.jLabel52.setText("Имя руководителя");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Заказчик");
this.jLabel56.setText("Телефон заказчика");
}
}
private void initConnection(String login,String password){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/db_course_paper?useUnicode=true&serverTimezone=Asia/Yekaterinburg", login, password);
}
catch(Exception ex){
String problem="<html>Ошибка подключения!<br>Проблема: "+ex.getMessage()+"<html>";
System.out.println(problem);
}
}
private ArrayList<Object[]> make_call_select(String SQL,String[] type_parameters,Object[] parameters,int num_of_cols){
ArrayList<Object[]> res=new ArrayList();
try{
CallableStatement call=connection.prepareCall(SQL);
for(int i=0;i<parameters.length;i++){
if(type_parameters[i]=="String"){
call.setString(i+1, (String)parameters[i]);
}
if(type_parameters[i]=="Int"){
call.setInt(i+1, (int)parameters[i]);
}
if(type_parameters[i]=="date"){
call.setDate(i+1, (Date)parameters[i]);
}
}
ResultSet result=call.executeQuery();
while(result.next()){
Object[] res_row=new Object[num_of_cols];
for(int j=0;j<num_of_cols;j++){
res_row[j]=result.getObject(j+1);
if(res_row[j]!=null){
if (res_row[j].toString().matches("....-..-..")){
res_row[j]=show_date(res_row[j].toString());
}
}
}
res.add(res_row);
}
result.close();
call.close();
}
catch(Exception ex){
String problem="<html>Ошибка выполнения запроса!<br>Проблема: "+ex.getMessage()+"<html>";
}
return res;
}
private DefaultTableModel fill_table(ArrayList<Object[]> data){
DefaultTableModel table=base_table;
table.setRowCount(0);
for(int i=0;i<data.size();i++){
table.insertRow(table.getRowCount(), data.get(i));
}
return table;
}
private String show_date(Object date){
String[] mas=date.toString().split("-");
return mas[2]+"-"+mas[1]+"-"+mas[0];
}
private Date make_date(String date){
String[] mas=date.split("-");
GregorianCalendar temp=new GregorianCalendar(Integer.parseInt(mas[2]),Integer.parseInt(mas[1]),Integer.parseInt(mas[0]));
return new Date(temp.getTime().getTime());
}
private Object[] parse_signature(){
int size=signature.length;
Object[] parameters=new Object[size];
String[] values={this.jTextField44.getText(),
this.jTextField45.getText(),
this.jTextField46.getText(),
this.jTextField47.getText(),
this.jTextField48.getText()};
for(int i=0;i<size;i++){
if(signature[i]=="Int"){
if(values[i].length()!=0) parameters[i]=Integer.parseInt(values[i]);
else parameters[i]=0;
}
if(signature[i]=="String"){
parameters[i]=values[i];
}
if(signature[i]=="Date"){
parameters[i]=make_date(values[i]);
}
}
return parameters;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane5 = new javax.swing.JScrollPane();
jTable4 = new javax.swing.JTable();
jPanel21 = new javax.swing.JPanel();
jLabel52 = new javax.swing.JLabel();
jTextField44 = new javax.swing.JTextField();
jLabel53 = new javax.swing.JLabel();
jTextField45 = new javax.swing.JTextField();
jLabel54 = new javax.swing.JLabel();
jTextField46 = new javax.swing.JTextField();
jLabel55 = new javax.swing.JLabel();
jTextField47 = new javax.swing.JTextField();
jLabel56 = new javax.swing.JLabel();
jTextField48 = new javax.swing.JTextField();
jButton11 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jRadioButton16 = new javax.swing.JRadioButton();
jRadioButton17 = new javax.swing.JRadioButton();
jRadioButton18 = new javax.swing.JRadioButton();
jRadioButton19 = new javax.swing.JRadioButton();
jRadioButton20 = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jButton10 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Ввод данных");
jTable4.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTable4.getTableHeader().setReorderingAllowed(false);
jTable4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable4MouseClicked(evt);
}
});
jScrollPane5.setViewportView(jTable4);
jLabel52.setText("Атрибут 1");
jTextField44.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel53.setText("Атрибут 2");
jTextField45.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel54.setText("Атрибут 3");
jTextField46.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel55.setText("Атрибут 4");
jTextField47.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel56.setText("Атрибут 5");
jTextField48.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jButton11.setText("Снять выделение");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel54)
.addComponent(jLabel53)
.addComponent(jLabel52)
.addComponent(jLabel55))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel21Layout.createSequentialGroup()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField44, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField45, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField46, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField47, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel21Layout.createSequentialGroup()
.addComponent(jLabel56)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jTextField48, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton11, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
.addContainerGap())
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addComponent(jLabel52)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel53)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel54)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel55)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel56)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton11)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonGroup1.add(jRadioButton16);
jRadioButton16.setText("Инженер");
buttonGroup1.add(jRadioButton17);
jRadioButton17.setText("Конструктор");
jRadioButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton17ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton18);
jRadioButton18.setText("Лаборант");
buttonGroup1.add(jRadioButton19);
jRadioButton19.setText("Техник");
buttonGroup1.add(jRadioButton20);
jRadioButton20.setText("Обслуживающий персонал");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jRadioButton16)
.addComponent(jRadioButton18)
.addComponent(jRadioButton17)
.addComponent(jRadioButton19)
.addComponent(jRadioButton20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jRadioButton16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton17)
.addGap(3, 3, 3)
.addComponent(jRadioButton18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton20)
.addContainerGap(104, Short.MAX_VALUE))
);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel1.setText("jLabel1");
jButton10.setText("Вввести данные");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 1200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel1)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jPanel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jButton10)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton17ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton17ActionPerformed
private void jTable4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable4MouseClicked
if(jTable4.getSelectedRows().length>1){
jButton10.setVisible(false);
jTable4.clearSelection();
evt.consume();
}
else{
jButton10.setVisible(true);
}
}//GEN-LAST:event_jTable4MouseClicked
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
selected_id=(int)jTable4.getModel().getValueAt(jTable4.getSelectedRow(), 0);
this.setVisible(false);
dispose();
}//GEN-LAST:event_jButton10ActionPerformed
private void jTextField44KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField44KeyReleased
if(this.jTable4.getSelectedRow()==-1){
Object[] parameters=parse_signature();
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
}//GEN-LAST:event_jTextField44KeyReleased
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
this.jTable4.clearSelection();
jButton10.setVisible(false);
}//GEN-LAST:event_jButton11ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DataForm dialog = new DataForm(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel52;
private javax.swing.JLabel jLabel53;
private javax.swing.JLabel jLabel54;
private javax.swing.JLabel jLabel55;
private javax.swing.JLabel jLabel56;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel21;
private javax.swing.JRadioButton jRadioButton16;
private javax.swing.JRadioButton jRadioButton17;
private javax.swing.JRadioButton jRadioButton18;
private javax.swing.JRadioButton jRadioButton19;
private javax.swing.JRadioButton jRadioButton20;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTable jTable4;
private javax.swing.JTextField jTextField44;
private javax.swing.JTextField jTextField45;
private javax.swing.JTextField jTextField46;
private javax.swing.JTextField jTextField47;
private javax.swing.JTextField jTextField48;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 26,256 | java | DataForm.java | Java | [
{
"context": "ar;\nimport javax.swing.table.*;\n\n/**\n *\n * @author Matt\n */\npublic class DataForm extends javax.swing.JDi",
"end": 369,
"score": 0.9996428489685059,
"start": 365,
"tag": "NAME",
"value": "Matt"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package my.DB_course_paper;
import java.sql.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.swing.table.*;
/**
*
* @author Matt
*/
public class DataForm extends javax.swing.JDialog {//Форма приёма данных у пользователя
String SQL;
String[] signature;
DefaultTableModel base_table;
public int selected_id;
Connection connection;
/**
* Creates new form DataForm
*/
public DataForm(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public DataForm(java.awt.Frame parent, boolean modal,DefaultTableModel table_type, boolean rbuttons,String sql,String log,String pass, String[] sign,String mess,int type) {
super(parent, modal);
initComponents();
base_table=table_type;
jPanel1.setVisible(rbuttons);
jButton10.setVisible(false);
jLabel1.setText(mess);
SQL=sql;
signature=sign;
initConnection(log,pass);
first_view();
prepare_form();
set_titles(type);
}
public DataForm(java.awt.Frame parent, boolean modal,DefaultTableModel table_type, boolean rbuttons,String sql,String log,String pass, String[] sign,String mess,int type,Object[] params) {
super(parent, modal);
initComponents();
base_table=table_type;
jPanel1.setVisible(rbuttons);
jButton10.setVisible(false);
jLabel1.setText(mess);
SQL=sql;
signature=sign;
initConnection(log,pass);
first_view(params);
prepare_form();
set_titles(type);
}
private void first_view(){
Object[] parameters=parse_signature();
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
private void first_view(Object[] parameters){
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
private void prepare_form(){
if(signature.length<5){
this.jTextField48.setVisible(false);
this.jLabel56.setVisible(false);
if(signature.length<4){
this.jTextField47.setVisible(false);
this.jLabel55.setVisible(false);
if(signature.length<3){
this.jTextField46.setVisible(false);
this.jLabel54.setVisible(false);
if(signature.length<2){
this.jTextField45.setVisible(false);
this.jLabel53.setVisible(false);
this.jButton10.setText("Прекратить просмотр");
}
}
}
}
}
private void set_titles(int type){
if(type==0){
this.jLabel52.setText("Имя начальника");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Направление деятельности отдела");
}
if(type==1){
this.jLabel52.setText("Имя сотрудника");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
}
if(type==2){
this.jLabel52.setText("Тип оборудования");
this.jLabel53.setText("Производитель оборудования");
}
if(type==3){
this.jLabel52.setText("Имя");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Образование");
this.jLabel56.setText("Научная степень");
}
if(type==4){
jPanel21.setVisible(false);
}
if(type==5){
this.jLabel52.setText("Имя руководителя");
this.jLabel53.setText("Фамилия");
this.jLabel54.setText("Отчество");
this.jLabel55.setText("Заказчик");
this.jLabel56.setText("Телефон заказчика");
}
}
private void initConnection(String login,String password){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/db_course_paper?useUnicode=true&serverTimezone=Asia/Yekaterinburg", login, password);
}
catch(Exception ex){
String problem="<html>Ошибка подключения!<br>Проблема: "+ex.getMessage()+"<html>";
System.out.println(problem);
}
}
private ArrayList<Object[]> make_call_select(String SQL,String[] type_parameters,Object[] parameters,int num_of_cols){
ArrayList<Object[]> res=new ArrayList();
try{
CallableStatement call=connection.prepareCall(SQL);
for(int i=0;i<parameters.length;i++){
if(type_parameters[i]=="String"){
call.setString(i+1, (String)parameters[i]);
}
if(type_parameters[i]=="Int"){
call.setInt(i+1, (int)parameters[i]);
}
if(type_parameters[i]=="date"){
call.setDate(i+1, (Date)parameters[i]);
}
}
ResultSet result=call.executeQuery();
while(result.next()){
Object[] res_row=new Object[num_of_cols];
for(int j=0;j<num_of_cols;j++){
res_row[j]=result.getObject(j+1);
if(res_row[j]!=null){
if (res_row[j].toString().matches("....-..-..")){
res_row[j]=show_date(res_row[j].toString());
}
}
}
res.add(res_row);
}
result.close();
call.close();
}
catch(Exception ex){
String problem="<html>Ошибка выполнения запроса!<br>Проблема: "+ex.getMessage()+"<html>";
}
return res;
}
private DefaultTableModel fill_table(ArrayList<Object[]> data){
DefaultTableModel table=base_table;
table.setRowCount(0);
for(int i=0;i<data.size();i++){
table.insertRow(table.getRowCount(), data.get(i));
}
return table;
}
private String show_date(Object date){
String[] mas=date.toString().split("-");
return mas[2]+"-"+mas[1]+"-"+mas[0];
}
private Date make_date(String date){
String[] mas=date.split("-");
GregorianCalendar temp=new GregorianCalendar(Integer.parseInt(mas[2]),Integer.parseInt(mas[1]),Integer.parseInt(mas[0]));
return new Date(temp.getTime().getTime());
}
private Object[] parse_signature(){
int size=signature.length;
Object[] parameters=new Object[size];
String[] values={this.jTextField44.getText(),
this.jTextField45.getText(),
this.jTextField46.getText(),
this.jTextField47.getText(),
this.jTextField48.getText()};
for(int i=0;i<size;i++){
if(signature[i]=="Int"){
if(values[i].length()!=0) parameters[i]=Integer.parseInt(values[i]);
else parameters[i]=0;
}
if(signature[i]=="String"){
parameters[i]=values[i];
}
if(signature[i]=="Date"){
parameters[i]=make_date(values[i]);
}
}
return parameters;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane5 = new javax.swing.JScrollPane();
jTable4 = new javax.swing.JTable();
jPanel21 = new javax.swing.JPanel();
jLabel52 = new javax.swing.JLabel();
jTextField44 = new javax.swing.JTextField();
jLabel53 = new javax.swing.JLabel();
jTextField45 = new javax.swing.JTextField();
jLabel54 = new javax.swing.JLabel();
jTextField46 = new javax.swing.JTextField();
jLabel55 = new javax.swing.JLabel();
jTextField47 = new javax.swing.JTextField();
jLabel56 = new javax.swing.JLabel();
jTextField48 = new javax.swing.JTextField();
jButton11 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jRadioButton16 = new javax.swing.JRadioButton();
jRadioButton17 = new javax.swing.JRadioButton();
jRadioButton18 = new javax.swing.JRadioButton();
jRadioButton19 = new javax.swing.JRadioButton();
jRadioButton20 = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jButton10 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Ввод данных");
jTable4.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTable4.getTableHeader().setReorderingAllowed(false);
jTable4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable4MouseClicked(evt);
}
});
jScrollPane5.setViewportView(jTable4);
jLabel52.setText("Атрибут 1");
jTextField44.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel53.setText("Атрибут 2");
jTextField45.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel54.setText("Атрибут 3");
jTextField46.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel55.setText("Атрибут 4");
jTextField47.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jLabel56.setText("Атрибут 5");
jTextField48.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField44KeyReleased(evt);
}
});
jButton11.setText("Снять выделение");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel54)
.addComponent(jLabel53)
.addComponent(jLabel52)
.addComponent(jLabel55))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel21Layout.createSequentialGroup()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField44, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField45, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField46, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField47, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel21Layout.createSequentialGroup()
.addComponent(jLabel56)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jTextField48, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton11, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
.addContainerGap())
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addComponent(jLabel52)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField44, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel53)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField45, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel54)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField46, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel55)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField47, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel56)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField48, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton11)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonGroup1.add(jRadioButton16);
jRadioButton16.setText("Инженер");
buttonGroup1.add(jRadioButton17);
jRadioButton17.setText("Конструктор");
jRadioButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton17ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton18);
jRadioButton18.setText("Лаборант");
buttonGroup1.add(jRadioButton19);
jRadioButton19.setText("Техник");
buttonGroup1.add(jRadioButton20);
jRadioButton20.setText("Обслуживающий персонал");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jRadioButton16)
.addComponent(jRadioButton18)
.addComponent(jRadioButton17)
.addComponent(jRadioButton19)
.addComponent(jRadioButton20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jRadioButton16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton17)
.addGap(3, 3, 3)
.addComponent(jRadioButton18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jRadioButton20)
.addContainerGap(104, Short.MAX_VALUE))
);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel1.setText("jLabel1");
jButton10.setText("Вввести данные");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 1200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel1)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jPanel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jButton10)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton17ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton17ActionPerformed
private void jTable4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable4MouseClicked
if(jTable4.getSelectedRows().length>1){
jButton10.setVisible(false);
jTable4.clearSelection();
evt.consume();
}
else{
jButton10.setVisible(true);
}
}//GEN-LAST:event_jTable4MouseClicked
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
selected_id=(int)jTable4.getModel().getValueAt(jTable4.getSelectedRow(), 0);
this.setVisible(false);
dispose();
}//GEN-LAST:event_jButton10ActionPerformed
private void jTextField44KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField44KeyReleased
if(this.jTable4.getSelectedRow()==-1){
Object[] parameters=parse_signature();
this.jTable4.setModel(fill_table(make_call_select(SQL,signature,parameters,base_table.getColumnCount())));
}
}//GEN-LAST:event_jTextField44KeyReleased
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
this.jTable4.clearSelection();
jButton10.setVisible(false);
}//GEN-LAST:event_jButton11ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DataForm dialog = new DataForm(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel52;
private javax.swing.JLabel jLabel53;
private javax.swing.JLabel jLabel54;
private javax.swing.JLabel jLabel55;
private javax.swing.JLabel jLabel56;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel21;
private javax.swing.JRadioButton jRadioButton16;
private javax.swing.JRadioButton jRadioButton17;
private javax.swing.JRadioButton jRadioButton18;
private javax.swing.JRadioButton jRadioButton19;
private javax.swing.JRadioButton jRadioButton20;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTable jTable4;
private javax.swing.JTextField jTextField44;
private javax.swing.JTextField jTextField45;
private javax.swing.JTextField jTextField46;
private javax.swing.JTextField jTextField47;
private javax.swing.JTextField jTextField48;
// End of variables declaration//GEN-END:variables
}
| 26,256 | 0.623678 | 0.604612 | 561 | 44.998219 | 34.438065 | 192 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.668449 | false | false | 2 |
ad87280f4fbd276c0d1377e503539f3b1dc4568a | 22,308,060,195,212 | 15c75fcd71d92db84b5da052e0f9b8abfcb8f805 | /presentation/src/main/java/com/github/hilo/mapper/UserModelDataMapper.java | 279b587808795db01ee5acf420c551faa191af22 | [] | no_license | hiloWang/MVP-DAGGER2-RETROFIT-RX | https://github.com/hiloWang/MVP-DAGGER2-RETROFIT-RX | 69d56e6f784b78ec04cbe272f9d85a89d10e68e3 | be2d38fda63434e2a4f1d74823e867e8028a4658 | refs/heads/master | 2021-01-21T14:58:36.421000 | 2016-07-19T09:21:44 | 2016-07-19T09:21:44 | 56,736,842 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.hilo.mapper;
import com.github.hilo.di.scope.PerActivity;
import com.github.hilo.domain.User;
import com.github.hilo.model.UserModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.inject.Inject;
@PerActivity
public class UserModelDataMapper {
@Inject UserModelDataMapper() {
}
/**
* Transform a {@link User} into an {@link UserModel}.
*
* @param user Object to be transformed.
* @return {@link UserModel}.
*/
public UserModel transform(User user) {
if (user == null) {
throw new IllegalArgumentException("Cannot transform a null value");
}
UserModel userModel = new UserModel();
userModel.setResults(user.getResults());
userModel.setError(user.isError());
return userModel;
}
/**
* Transform a Collection of {@link User} into a Collection of {@link UserModel}.
*
* @param usersCollection Objects to be transformed.
* @return List of {@link UserModel}.
*/
public Collection<UserModel> transform(Collection<User> usersCollection) {
Collection<UserModel> userModelsCollection;
if (usersCollection != null && !usersCollection.isEmpty()) {
userModelsCollection = new ArrayList<>();
for (User user : usersCollection) {
userModelsCollection.add(transform(user));
}
} else {
userModelsCollection = Collections.emptyList();
}
return userModelsCollection;
}
}
| UTF-8 | Java | 1,403 | java | UserModelDataMapper.java | Java | [] | null | [] | package com.github.hilo.mapper;
import com.github.hilo.di.scope.PerActivity;
import com.github.hilo.domain.User;
import com.github.hilo.model.UserModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.inject.Inject;
@PerActivity
public class UserModelDataMapper {
@Inject UserModelDataMapper() {
}
/**
* Transform a {@link User} into an {@link UserModel}.
*
* @param user Object to be transformed.
* @return {@link UserModel}.
*/
public UserModel transform(User user) {
if (user == null) {
throw new IllegalArgumentException("Cannot transform a null value");
}
UserModel userModel = new UserModel();
userModel.setResults(user.getResults());
userModel.setError(user.isError());
return userModel;
}
/**
* Transform a Collection of {@link User} into a Collection of {@link UserModel}.
*
* @param usersCollection Objects to be transformed.
* @return List of {@link UserModel}.
*/
public Collection<UserModel> transform(Collection<User> usersCollection) {
Collection<UserModel> userModelsCollection;
if (usersCollection != null && !usersCollection.isEmpty()) {
userModelsCollection = new ArrayList<>();
for (User user : usersCollection) {
userModelsCollection.add(transform(user));
}
} else {
userModelsCollection = Collections.emptyList();
}
return userModelsCollection;
}
}
| 1,403 | 0.722024 | 0.722024 | 57 | 23.614035 | 22.416906 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.350877 | false | false | 2 |
81a260843066041a3e061568cb40fa49e642425e | 2,388,001,861,010 | 37599e7dee1449a9e225425a0aff399fd8342771 | /src/Game.java | 3b642ae36859b976055b9d62e536be727b5bd5f8 | [] | no_license | WiredLotus/TextGame | https://github.com/WiredLotus/TextGame | 9a34f4e0b4d1ae0b8dd05c5c7bab8744c6b65356 | 89bc4a94e02103d9aa29802db7462823a03c04d7 | refs/heads/master | 2016-09-10T17:58:06.828000 | 2015-09-09T07:42:01 | 2015-09-09T07:42:01 | 42,163,746 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
/**
* Created by Lotus on 4/09/2015.
*/
public class Game {
public static void main(String [] args) {
int loop = 1;
Scanner input = new Scanner(System.in);
Character mc;
if (loop == 1) {
System.out.print("Please enter your name: ");
mc = new Character(input.next());
System.out.println("\nWelcome " + (char)27 + "[1m" + mc.getCharacterName() + (char)27 + "[0m\n");
System.out.println("** Insert Menu **");
}
}
}
| UTF-8 | Java | 542 | java | Game.java | Java | [
{
"context": "import java.util.Scanner;\n\n/**\n * Created by Lotus on 4/09/2015.\n */\npublic class Game {\n\n public",
"end": 50,
"score": 0.8461912274360657,
"start": 45,
"tag": "USERNAME",
"value": "Lotus"
}
] | null | [] | import java.util.Scanner;
/**
* Created by Lotus on 4/09/2015.
*/
public class Game {
public static void main(String [] args) {
int loop = 1;
Scanner input = new Scanner(System.in);
Character mc;
if (loop == 1) {
System.out.print("Please enter your name: ");
mc = new Character(input.next());
System.out.println("\nWelcome " + (char)27 + "[1m" + mc.getCharacterName() + (char)27 + "[0m\n");
System.out.println("** Insert Menu **");
}
}
}
| 542 | 0.527675 | 0.5 | 23 | 22.565218 | 26.407881 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 2 |
7a92abddcb4cd9ad5c07f25c20d7b1ec28022ed5 | 30,717,606,112,964 | 26218940c6e99ae62ae1dc72b3378b759b28032e | /src/sorting/package-info.java | d1b09bd7d723898cde48f581e444c93d5da535d2 | [] | no_license | su6a/AmazonQAE-Test | https://github.com/su6a/AmazonQAE-Test | a5dcbc9b7b2693706bc066c965ba638582e768cd | c626234308299d333d45f35e40846facae1ebcd7 | refs/heads/master | 2020-07-09T19:25:32.011000 | 2019-10-18T20:31:11 | 2019-10-18T20:31:11 | 204,061,793 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
/**
* @author Sura
*
*/
package sorting; | UTF-8 | Java | 55 | java | package-info.java | Java | [
{
"context": "/**\n * \n */\n/**\n * @author Sura\n *\n */\npackage sorting;",
"end": 31,
"score": 0.9993375539779663,
"start": 27,
"tag": "NAME",
"value": "Sura"
}
] | null | [] | /**
*
*/
/**
* @author Sura
*
*/
package sorting; | 55 | 0.436364 | 0.436364 | 8 | 6 | 5.5 | 16 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 2 |
74d5c278936c817acc16de2628985ab1a0958f7b | 10,840,497,466,653 | b18b35881e285cdc2a127a1864547129fb2d1fcb | /ModuleSDK/src/org/openvisko/module/operators/NCLOperator.java | b9566d1cfd84992bd962d98790cf4ce11ec807b7 | [] | no_license | openvisko/visko-packages | https://github.com/openvisko/visko-packages | 5ca11b5d683c8d27605cfd35e72dd134159a1241 | b8d12c13e77b37918d6aa32e2574e6d04762367e | refs/heads/master | 2021-01-16T20:38:02.789000 | 2012-11-21T01:26:14 | 2012-11-21T01:26:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.openvisko.module.operators;
import org.openvisko.module.util.AbstractOperatorFileUtils;
public abstract class NCLOperator extends ToolkitOperator
{
public NCLOperator(String inputDataURL, String baseInputFileName, boolean isTextualInput, boolean shouldBePersistedInMemory, String baseOutputFileName){
super(inputDataURL, baseInputFileName, isTextualInput, shouldBePersistedInMemory, baseOutputFileName);
}
protected void setUpOutputs(String baseOutputFileName){
String[] fileNameParts = baseOutputFileName.split("\\.");
String name = fileNameParts[0];
String extension = fileNameParts[1];
outputFileName = name + "_" + AbstractOperatorFileUtils.getRandomString();
outputPath = AbstractOperatorFileUtils.makeFullPath(AbstractOperatorFileUtils.getWorkspace(), outputFileName);
outputURL = AbstractOperatorFileUtils.getOutputURLPrefix() + outputFileName + "." + extension;
}
}
| UTF-8 | Java | 932 | java | NCLOperator.java | Java | [] | null | [] | package org.openvisko.module.operators;
import org.openvisko.module.util.AbstractOperatorFileUtils;
public abstract class NCLOperator extends ToolkitOperator
{
public NCLOperator(String inputDataURL, String baseInputFileName, boolean isTextualInput, boolean shouldBePersistedInMemory, String baseOutputFileName){
super(inputDataURL, baseInputFileName, isTextualInput, shouldBePersistedInMemory, baseOutputFileName);
}
protected void setUpOutputs(String baseOutputFileName){
String[] fileNameParts = baseOutputFileName.split("\\.");
String name = fileNameParts[0];
String extension = fileNameParts[1];
outputFileName = name + "_" + AbstractOperatorFileUtils.getRandomString();
outputPath = AbstractOperatorFileUtils.makeFullPath(AbstractOperatorFileUtils.getWorkspace(), outputFileName);
outputURL = AbstractOperatorFileUtils.getOutputURLPrefix() + outputFileName + "." + extension;
}
}
| 932 | 0.793991 | 0.791846 | 21 | 42.380951 | 44.431301 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.809524 | false | false | 2 |
5f20c288f2540b09d0aed039a7033bf862212157 | 4,123,168,615,424 | f7c2f1c1e6fa27374fce19f422e5fa86e1595990 | /my-admin-01/app-module/app-commons-module/app-db-core/src/main/java/org/yuan/boot/app/db/core/constants/CommonsConstants.java | 5bd056b000371cdbe9ae9a70eeb13457db46fc06 | [] | no_license | yuan50697105/my-admin-2019 | https://github.com/yuan50697105/my-admin-2019 | d3ecbe283fdcda67ad870bc436551eb5020f4944 | 29cc3e5e2e480277329352855c71eeacabec4314 | refs/heads/master | 2022-07-02T00:18:57.210000 | 2020-04-06T08:02:33 | 2020-04-06T08:02:33 | 253,431,240 | 0 | 0 | null | false | 2022-06-21T03:09:54 | 2020-04-06T07:53:13 | 2020-04-06T08:03:10 | 2022-06-21T03:09:54 | 670 | 0 | 0 | 2 | Java | false | false | package org.yuan.boot.app.db.core.constants;
/**
* @program: my-admin-shower
* @description:
* @author: yuane
* @create: 2020-02-25 19:55
*/
public class CommonsConstants {
public static final int ENABLE = 1;
public static final int DISABLE = 0;
public static final String ENABLE_STR = "1";
public static final int UPDATED_ENABLED = 1;
public static final int UPDATED_DISABLED = 0;
} | UTF-8 | Java | 409 | java | CommonsConstants.java | Java | [
{
"context": "gram: my-admin-shower\n * @description:\n * @author: yuane\n * @create: 2020-02-25 19:55\n */\npublic class Com",
"end": 113,
"score": 0.9995827674865723,
"start": 108,
"tag": "USERNAME",
"value": "yuane"
}
] | null | [] | package org.yuan.boot.app.db.core.constants;
/**
* @program: my-admin-shower
* @description:
* @author: yuane
* @create: 2020-02-25 19:55
*/
public class CommonsConstants {
public static final int ENABLE = 1;
public static final int DISABLE = 0;
public static final String ENABLE_STR = "1";
public static final int UPDATED_ENABLED = 1;
public static final int UPDATED_DISABLED = 0;
} | 409 | 0.689487 | 0.647922 | 15 | 26.333334 | 17.808861 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 2 |
6347e2db8060145f975ba925d7d80985c4728dd9 | 19,834,158,984,351 | ea07f92f08b36ab641ba98bf47ace90f252fb98a | /app/src/main/java/com/personalassistant/views/fragments/InComeDetailsFragment.java | cb0bef0e743c5f61b8e9b082e32f159cd84a3c37 | [] | no_license | ananthramasamy/personal-assistant | https://github.com/ananthramasamy/personal-assistant | 18e412054e327f1c8b1e69be9de5c3f7cab4e89e | 00d37bbf48948d9c198b75fad3e111e81f3d03b6 | refs/heads/master | 2020-03-30T11:13:02.115000 | 2018-10-13T03:34:06 | 2018-10-13T03:34:06 | 151,159,805 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.personalassistant.views.fragments;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.personalassistant.MyApplication;
import com.personalassistant.R;
import com.personalassistant.adapter.CategoriesRecyclerViewAdapter;
import com.personalassistant.adapter.IncomeAdapter;
import com.personalassistant.endpoint.EndPoints;
import com.personalassistant.endpoint.JsonRequest;
import com.personalassistant.enities.income.GetIncomeDetailsResult;
import com.personalassistant.interfaces.CategoriesInterfaces;
import com.personalassistant.interfaces.GetAllIncomeInterfaces;
import com.personalassistant.utils.BounceView;
import com.personalassistant.utils.Configuration;
import com.personalassistant.utils.Constants;
import com.personalassistant.utils.DividerVerticalItemDecoration;
import com.personalassistant.utils.JsonUtils;
import com.personalassistant.utils.MyRecyclerScroll;
import com.personalassistant.utils.Toasty;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Objects;
public class InComeDetailsFragment extends Fragment implements View.OnClickListener {
private Context mContext;
private String mTransactionType, mTransactionAmount, mTransactionDescription;
private RecyclerView mAllIncomeRecyclerView, mCategoriesRecyclerView;
private IncomeAdapter mIncomeAdapter;
private CategoriesRecyclerViewAdapter mCategoriesRecyclerViewAdapter;
private ArrayList<String> CategoriesArrayList;
private ArrayList<GetIncomeDetailsResult> getIncomeDetailsResultsList = new ArrayList<>();
private FloatingActionButton mAddIncomeFAB;
private EditText mCategoriesNameET, mTransactionAmountET, mTransactionDescET;
private TextInputLayout mCategoriesNameWrapper, mTransactionAmountWrapper, mTransactionDescWrapper;
private TextView mNoRecordFoundTV, mActualIncomeValueTV, mGoalIncomeValueTV;
private Dialog dialog;
private String mActualIncomeFormatted, mGoalIncomeFormatted;
private View dialogView;
private LinearLayout mTransitionsContainer;
private int onSelectedItemPosition, fabMargin;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_income_details_layout, container, false);
Toolbar toolbar = rootView.findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Objects.requireNonNull(getActivity()).finish();
}
});
mContext = getActivity();
fabMargin = getResources().getDimensionPixelSize(R.dimen.fab_margin);
initViews(rootView);
onPrePareAllIncomeData();
return rootView;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.add_income_fab:
onAddIncomeView();
break;
case R.id.income_submit_action_iv_btn:
mTransactionType = mCategoriesNameET.getText().toString().trim();
mTransactionDescription = mTransactionDescET.getText().toString().trim();
mTransactionAmount = mTransactionAmountET.getText().toString().trim();
if (Configuration.isEmptyValidation(mTransactionType)) {
mCategoriesNameWrapper.setError("Select Any one Category");
mCategoriesNameET.setFocusable(true);
} else if (Configuration.isEmptyValidation(mTransactionAmount)) {
mTransactionAmountWrapper.setError("Invalid Amount");
mTransactionAmountET.setFocusable(true);
} else if (Configuration.isEmptyZeroValidation(mTransactionAmount)) {
mTransactionAmountWrapper.setError("Invalid Amount");
mTransactionAmountET.setFocusable(true);
} else {
onPutIncomeRequest(mTransactionType, mTransactionDescription, mTransactionAmount);
}
break;
}
}
private void initViews(View rootView) {
mNoRecordFoundTV = rootView.findViewById(R.id.no_record_found_tv);
TextView mMonthNameTV = rootView.findViewById(R.id.month_name_tv);
TextView mSelectedYearTV = rootView.findViewById(R.id.year_tv);
if (!Configuration.isEmptyValidation(MyApplication.getYear())) {
mSelectedYearTV.setText(MyApplication.getYear());
}
if (!Configuration.isEmptyValidation(MyApplication.getMonthName())) {
mMonthNameTV.setText(MyApplication.getMonthName());
}
TextView mActualHintNameTV = rootView.findViewById(R.id.actual_name_tv);
TextView mGoalHintNameTV = rootView.findViewById(R.id.goal_name_tv);
mActualHintNameTV.setText(R.string.str_actual_income);
mGoalHintNameTV.setText(R.string.str_goals_income);
mGoalIncomeValueTV = rootView.findViewById(R.id.goals_value_tv);
mActualIncomeValueTV = rootView.findViewById(R.id.actual_value_tv);
if (!Configuration.isEmptyValidation(mActualIncomeFormatted)) {
mActualIncomeValueTV.setText(mActualIncomeFormatted);
}
if (!Configuration.isEmptyValidation(mGoalIncomeFormatted)) {
mGoalIncomeValueTV.setText(mGoalIncomeFormatted);
}
mAddIncomeFAB = rootView.findViewById(R.id.add_income_fab);
mAddIncomeFAB.setOnClickListener(this);
getIncomeDetailsResultsList = new ArrayList<>();
mAllIncomeRecyclerView = rootView.findViewById(R.id.income_details_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(mAllIncomeRecyclerView.getContext());
mAllIncomeRecyclerView.setLayoutManager(layoutManager);
mAllIncomeRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAllIncomeRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerVerticalItemDecoration(mContext);
mAllIncomeRecyclerView.addItemDecoration(itemDecoration);
mIncomeAdapter = new IncomeAdapter(mContext, getIncomeDetailsResultsList, new GetAllIncomeInterfaces() {
@Override
public void onSelectedIncome(String transactionId, int onSeletedPosition) {
onSelectedItemPosition = onSeletedPosition;
onDeleteTransaction(transactionId);
}
});
mAllIncomeRecyclerView.setAdapter(mIncomeAdapter);
mAllIncomeRecyclerView.addOnScrollListener(new MyRecyclerScroll() {
@Override
public void show() {
mAddIncomeFAB.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
@Override
public void hide() {
mAddIncomeFAB.animate().translationY(mAddIncomeFAB.getHeight() + fabMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
});
}
private void onDeleteTransaction(String transactionId) {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getString(R.string.str_loading));
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToDeleteTransactionJsonObject(transactionId);
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest DeleteTransactionRequest = new JsonRequest(Request.Method.POST, EndPoints.DELETE_INCOME_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onDeletedSuccessResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
DeleteTransactionRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
DeleteTransactionRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(DeleteTransactionRequest, Constants.GET_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onDeletedSuccessResponse(JSONObject response) {
try {
String mMessage = response.getString(Constants.MESSAGE_TAG);
onGetGoalIncomeData();
getIncomeDetailsResultsList.remove(onSelectedItemPosition);
if (getIncomeDetailsResultsList.size() > 0) {
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
mIncomeAdapter.notifyItemChanged(onSelectedItemPosition);
mAllIncomeRecyclerView.scrollToPosition(onSelectedItemPosition);
mAllIncomeRecyclerView.setVisibility(View.VISIBLE);
mNoRecordFoundTV.setVisibility(View.GONE);
} else {
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
}
Toasty.success(mContext, mMessage, 100, true).show();
Configuration.onAnimatedLoadingDismiss();
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void onPrePareAllIncomeData() {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getString(R.string.str_loading));
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToCommonTransactionJsonObject();
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, EndPoints.GET_INCOME_ALL_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onPrepareToParser(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.GET_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onPrepareToParser(JSONObject response) {
Configuration.onAnimatedLoadingDismiss();
getIncomeDetailsResultsList = new ArrayList<>();
try {
JSONArray mainArray = response.getJSONArray(Constants.INCOME_TRANSACTION_TAG);
if (mainArray.length() > 0) {
for (int i = 0; i < mainArray.length(); i++) {
JSONObject innerObject = mainArray.getJSONObject(i);
String transactionId = innerObject.getString(Constants.INCOME_TRANSACTION_ID_TAG);
String transactionType = innerObject.getString(Constants.INCOME_TRANSACTION_NAME_TAG);
String transactionDescription = innerObject.getString(Constants.INCOME_TRANSACTION_DESCRIPTION_TAG);
String transactionAmount = innerObject.getString(Constants.INCOME_TRANSACTION_AMOUNT_TAG);
String transactionAmountFormatted = innerObject.getString(Constants.INCOME_TRANSACTION_AMOUNT_FORMATTED_TAG);
getIncomeDetailsResultsList.add(new GetIncomeDetailsResult(transactionId, transactionType, transactionDescription,
transactionAmount, transactionAmountFormatted));
}
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
}
onGetGoalIncomeData();
if (getIncomeDetailsResultsList.size() > 0) {
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
Configuration.runLayoutAnimation(mAllIncomeRecyclerView);
mAllIncomeRecyclerView.setVisibility(View.VISIBLE);
mNoRecordFoundTV.setVisibility(View.GONE);
} else {
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void onGetGoalIncomeData() {
Configuration.onAnimatedLoadingDismiss();
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToCommonTransactionJsonObject();
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, EndPoints.GET_DASHBOARD_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onGetGoalIncomeResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.GET_INCOME_REQUESTS_TAG);
}
private void onGetGoalIncomeResponse(JSONObject response) {
try {
JSONObject mGoalsJsonObject = response.getJSONObject(Constants.DASHBOARD_TRANSACTION_GOALS_TAG);
mGoalIncomeFormatted = mGoalsJsonObject.getString(Constants.DASHBOARD_TRANSACTION_INCOME_FORMATTED_TAG);
JSONObject mActualJsonObject = response.getJSONObject(Constants.DASHBOARD_TRANSACTION_ACTUALS_TAG);
mActualIncomeFormatted = mActualJsonObject.getString(Constants.DASHBOARD_TRANSACTION_INCOME_FORMATTED_TAG);
mActualIncomeValueTV.setText(mActualIncomeFormatted);
mGoalIncomeValueTV.setText(mGoalIncomeFormatted);
Configuration.onAnimatedLoadingDismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void onAddIncomeView() {
dialogView = View.inflate(mContext, R.layout.fragement_dialog_add_income, null);
dialog = new Dialog(mContext, R.style.MyAlertDialogStyle);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(dialogView);
mTransitionsContainer = dialogView.findViewById(R.id.dialog);
mCategoriesRecyclerView = dialogView.findViewById(R.id.category_recycler_view);
mCategoriesNameET = dialogView.findViewById(R.id.category_name_et);
mTransactionAmountET = dialogView.findViewById(R.id.income_amount_et);
mTransactionDescET = dialogView.findViewById(R.id.income_description_et);
mCategoriesNameWrapper = dialogView.findViewById(R.id.category_name_wrapper);
mTransactionAmountWrapper = dialogView.findViewById(R.id.income_amount_wrapper);
mTransactionDescWrapper = dialogView.findViewById(R.id.income_description_wrapper);
Configuration.ResetTextInputLayout(mContext, mCategoriesNameWrapper, mCategoriesNameET);
Configuration.ResetTextInputLayout(mContext, mTransactionAmountWrapper, mTransactionAmountET);
Configuration.ResetTextInputLayout(mContext, mTransactionDescWrapper, mTransactionDescET);
ImageButton mIncomeSubmitBTN = dialogView.findViewById(R.id.income_submit_action_iv_btn);
mIncomeSubmitBTN.setOnClickListener(this);
BounceView.addAnimTo(mIncomeSubmitBTN);
CategoriesArrayList = new ArrayList<>();
CategoriesArrayList.add("Salary");
CategoriesArrayList.add("Investment");
CategoriesArrayList.add("Dividends");
CategoriesArrayList.add("Coupons");
CategoriesArrayList.add("Refunds");
CategoriesArrayList.add("Rental");
CategoriesArrayList.add("Sales");
CategoriesArrayList.add("Awards");
CategoriesArrayList.add("Other");
GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3);
mCategoriesRecyclerView.setLayoutManager(layoutManager);
mCategoriesRecyclerView.setHasFixedSize(true);
mCategoriesRecyclerViewAdapter = new CategoriesRecyclerViewAdapter(mContext, Constants.INCOME_COLORS, CategoriesArrayList, new CategoriesInterfaces() {
@Override
public void onSelectedItem(int position, String CategoriesName) {
mTransactionType = CategoriesName;
if (!Configuration.isEmptyValidation(mTransactionType)) {
mCategoriesNameET.setText(mTransactionType);
mTransactionAmountET.setFocusable(true);
}
}
});
mCategoriesRecyclerView.setAdapter(mCategoriesRecyclerViewAdapter);
mCategoriesRecyclerViewAdapter.onNotifyDataSetChanged(CategoriesArrayList);
Configuration.runLayoutAnimation(mCategoriesRecyclerView);
ImageView imageView = dialog.findViewById(R.id.closeDialogImg);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
onPrePareAllIncomeData();
}
}, 1500);
revealShow(dialogView, false, dialog);
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
revealShow(dialogView, true, null);
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK) {
revealShow(dialogView, false, dialog);
return true;
}
return false;
}
});
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
private void onPutIncomeRequest(String transactionType, String mTransactionDesc, String mTransactionAmount) {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getResources().getString(R.string.str_loading));
String url = EndPoints.PUT_INCOME_REQUEST;
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestPutTransactionJsonObject(transactionType, mTransactionDesc, mTransactionAmount);
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onSuccessResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.PUT_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onSuccessResponse(JSONObject response) {
try {
final String mMessage = response.getString("message");
Configuration.onAnimatedLoadingDismiss();
onUserConfirmationWarningAlert(mContext, mMessage);
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void onFailureResponse(VolleyError error) {
String errorData = new String(error.networkResponse.data);
try {
JSONObject jsonObject = new JSONObject(errorData);
String mMessage = jsonObject.getString("message");
Configuration.onAnimatedLoadingDismiss();
Configuration.onWarningAlertDialog(mContext, getString(R.string.str_alert), mMessage);
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void revealShow(View dialogView, boolean b, final Dialog dialog) {
final View view = dialogView.findViewById(R.id.dialog);
int w = view.getWidth();
int h = view.getHeight();
int endRadius = (int) Math.hypot(w, h);
int cx = (int) (mAddIncomeFAB.getX() + (mAddIncomeFAB.getWidth() / 2));
int cy = (int) (mAddIncomeFAB.getY()) + mAddIncomeFAB.getHeight() + 54;
if (b) {
Animator revealAnimator = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, endRadius);
view.setVisibility(View.VISIBLE);
revealAnimator.setDuration(800);
revealAnimator.start();
} else {
Animator anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, endRadius, 0);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
dialog.dismiss();
view.setVisibility(View.INVISIBLE);
}
});
anim.setDuration(800);
anim.start();
}
}
@SuppressLint("SetTextI18n")
private void onUserConfirmationWarningAlert(Context mContext, String mMessage) {
final Dialog WarningAlertDialog;
try {
WarningAlertDialog = new Dialog(mContext);
WarningAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
WarningAlertDialog.setContentView(R.layout.dialog_warning_confirmation_layout);
TextView WarningAlertTittleTV = WarningAlertDialog.findViewById(R.id.warning_tittle_tv);
TextView WarningAlertMsgTV = WarningAlertDialog.findViewById(R.id.warning_msg_tv);
Button mPositiveActionBTN = WarningAlertDialog.findViewById(R.id.positive_action_btn);
mPositiveActionBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WarningAlertDialog.dismiss();
mCategoriesNameET.setText("");
mTransactionAmountET.setText("");
mTransactionDescET.setText("");
mCategoriesRecyclerViewAdapter.onNotifyDataSetChanged(CategoriesArrayList);
}
});
Button CloseBTN = WarningAlertDialog.findViewById(R.id.negative_action_btn);
Objects.requireNonNull(WarningAlertDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
WarningAlertDialog.setCancelable(false);
WarningAlertDialog.setCanceledOnTouchOutside(false);
WarningAlertMsgTV.setText(mMessage + ". Do You wish to add another income?");
WarningAlertTittleTV.setText("Alert");
CloseBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCategoriesNameET.setText("");
mTransactionAmountET.setText("");
mTransactionDescET.setText("");
WarningAlertDialog.dismiss();
new Handler().postDelayed(new Runnable() {
public void run() {
onPrePareAllIncomeData();
}
}, 1500);
revealShow(dialogView, false, dialog);
}
});
WarningAlertDialog.show();
BounceView.addAnimTo(WarningAlertDialog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 26,892 | java | InComeDetailsFragment.java | Java | [] | null | [] | package com.personalassistant.views.fragments;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.personalassistant.MyApplication;
import com.personalassistant.R;
import com.personalassistant.adapter.CategoriesRecyclerViewAdapter;
import com.personalassistant.adapter.IncomeAdapter;
import com.personalassistant.endpoint.EndPoints;
import com.personalassistant.endpoint.JsonRequest;
import com.personalassistant.enities.income.GetIncomeDetailsResult;
import com.personalassistant.interfaces.CategoriesInterfaces;
import com.personalassistant.interfaces.GetAllIncomeInterfaces;
import com.personalassistant.utils.BounceView;
import com.personalassistant.utils.Configuration;
import com.personalassistant.utils.Constants;
import com.personalassistant.utils.DividerVerticalItemDecoration;
import com.personalassistant.utils.JsonUtils;
import com.personalassistant.utils.MyRecyclerScroll;
import com.personalassistant.utils.Toasty;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Objects;
public class InComeDetailsFragment extends Fragment implements View.OnClickListener {
private Context mContext;
private String mTransactionType, mTransactionAmount, mTransactionDescription;
private RecyclerView mAllIncomeRecyclerView, mCategoriesRecyclerView;
private IncomeAdapter mIncomeAdapter;
private CategoriesRecyclerViewAdapter mCategoriesRecyclerViewAdapter;
private ArrayList<String> CategoriesArrayList;
private ArrayList<GetIncomeDetailsResult> getIncomeDetailsResultsList = new ArrayList<>();
private FloatingActionButton mAddIncomeFAB;
private EditText mCategoriesNameET, mTransactionAmountET, mTransactionDescET;
private TextInputLayout mCategoriesNameWrapper, mTransactionAmountWrapper, mTransactionDescWrapper;
private TextView mNoRecordFoundTV, mActualIncomeValueTV, mGoalIncomeValueTV;
private Dialog dialog;
private String mActualIncomeFormatted, mGoalIncomeFormatted;
private View dialogView;
private LinearLayout mTransitionsContainer;
private int onSelectedItemPosition, fabMargin;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_income_details_layout, container, false);
Toolbar toolbar = rootView.findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Objects.requireNonNull(getActivity()).finish();
}
});
mContext = getActivity();
fabMargin = getResources().getDimensionPixelSize(R.dimen.fab_margin);
initViews(rootView);
onPrePareAllIncomeData();
return rootView;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.add_income_fab:
onAddIncomeView();
break;
case R.id.income_submit_action_iv_btn:
mTransactionType = mCategoriesNameET.getText().toString().trim();
mTransactionDescription = mTransactionDescET.getText().toString().trim();
mTransactionAmount = mTransactionAmountET.getText().toString().trim();
if (Configuration.isEmptyValidation(mTransactionType)) {
mCategoriesNameWrapper.setError("Select Any one Category");
mCategoriesNameET.setFocusable(true);
} else if (Configuration.isEmptyValidation(mTransactionAmount)) {
mTransactionAmountWrapper.setError("Invalid Amount");
mTransactionAmountET.setFocusable(true);
} else if (Configuration.isEmptyZeroValidation(mTransactionAmount)) {
mTransactionAmountWrapper.setError("Invalid Amount");
mTransactionAmountET.setFocusable(true);
} else {
onPutIncomeRequest(mTransactionType, mTransactionDescription, mTransactionAmount);
}
break;
}
}
private void initViews(View rootView) {
mNoRecordFoundTV = rootView.findViewById(R.id.no_record_found_tv);
TextView mMonthNameTV = rootView.findViewById(R.id.month_name_tv);
TextView mSelectedYearTV = rootView.findViewById(R.id.year_tv);
if (!Configuration.isEmptyValidation(MyApplication.getYear())) {
mSelectedYearTV.setText(MyApplication.getYear());
}
if (!Configuration.isEmptyValidation(MyApplication.getMonthName())) {
mMonthNameTV.setText(MyApplication.getMonthName());
}
TextView mActualHintNameTV = rootView.findViewById(R.id.actual_name_tv);
TextView mGoalHintNameTV = rootView.findViewById(R.id.goal_name_tv);
mActualHintNameTV.setText(R.string.str_actual_income);
mGoalHintNameTV.setText(R.string.str_goals_income);
mGoalIncomeValueTV = rootView.findViewById(R.id.goals_value_tv);
mActualIncomeValueTV = rootView.findViewById(R.id.actual_value_tv);
if (!Configuration.isEmptyValidation(mActualIncomeFormatted)) {
mActualIncomeValueTV.setText(mActualIncomeFormatted);
}
if (!Configuration.isEmptyValidation(mGoalIncomeFormatted)) {
mGoalIncomeValueTV.setText(mGoalIncomeFormatted);
}
mAddIncomeFAB = rootView.findViewById(R.id.add_income_fab);
mAddIncomeFAB.setOnClickListener(this);
getIncomeDetailsResultsList = new ArrayList<>();
mAllIncomeRecyclerView = rootView.findViewById(R.id.income_details_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(mAllIncomeRecyclerView.getContext());
mAllIncomeRecyclerView.setLayoutManager(layoutManager);
mAllIncomeRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAllIncomeRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerVerticalItemDecoration(mContext);
mAllIncomeRecyclerView.addItemDecoration(itemDecoration);
mIncomeAdapter = new IncomeAdapter(mContext, getIncomeDetailsResultsList, new GetAllIncomeInterfaces() {
@Override
public void onSelectedIncome(String transactionId, int onSeletedPosition) {
onSelectedItemPosition = onSeletedPosition;
onDeleteTransaction(transactionId);
}
});
mAllIncomeRecyclerView.setAdapter(mIncomeAdapter);
mAllIncomeRecyclerView.addOnScrollListener(new MyRecyclerScroll() {
@Override
public void show() {
mAddIncomeFAB.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
@Override
public void hide() {
mAddIncomeFAB.animate().translationY(mAddIncomeFAB.getHeight() + fabMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
});
}
private void onDeleteTransaction(String transactionId) {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getString(R.string.str_loading));
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToDeleteTransactionJsonObject(transactionId);
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest DeleteTransactionRequest = new JsonRequest(Request.Method.POST, EndPoints.DELETE_INCOME_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onDeletedSuccessResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
DeleteTransactionRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
DeleteTransactionRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(DeleteTransactionRequest, Constants.GET_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onDeletedSuccessResponse(JSONObject response) {
try {
String mMessage = response.getString(Constants.MESSAGE_TAG);
onGetGoalIncomeData();
getIncomeDetailsResultsList.remove(onSelectedItemPosition);
if (getIncomeDetailsResultsList.size() > 0) {
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
mIncomeAdapter.notifyItemChanged(onSelectedItemPosition);
mAllIncomeRecyclerView.scrollToPosition(onSelectedItemPosition);
mAllIncomeRecyclerView.setVisibility(View.VISIBLE);
mNoRecordFoundTV.setVisibility(View.GONE);
} else {
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
}
Toasty.success(mContext, mMessage, 100, true).show();
Configuration.onAnimatedLoadingDismiss();
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void onPrePareAllIncomeData() {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getString(R.string.str_loading));
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToCommonTransactionJsonObject();
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, EndPoints.GET_INCOME_ALL_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onPrepareToParser(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.GET_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onPrepareToParser(JSONObject response) {
Configuration.onAnimatedLoadingDismiss();
getIncomeDetailsResultsList = new ArrayList<>();
try {
JSONArray mainArray = response.getJSONArray(Constants.INCOME_TRANSACTION_TAG);
if (mainArray.length() > 0) {
for (int i = 0; i < mainArray.length(); i++) {
JSONObject innerObject = mainArray.getJSONObject(i);
String transactionId = innerObject.getString(Constants.INCOME_TRANSACTION_ID_TAG);
String transactionType = innerObject.getString(Constants.INCOME_TRANSACTION_NAME_TAG);
String transactionDescription = innerObject.getString(Constants.INCOME_TRANSACTION_DESCRIPTION_TAG);
String transactionAmount = innerObject.getString(Constants.INCOME_TRANSACTION_AMOUNT_TAG);
String transactionAmountFormatted = innerObject.getString(Constants.INCOME_TRANSACTION_AMOUNT_FORMATTED_TAG);
getIncomeDetailsResultsList.add(new GetIncomeDetailsResult(transactionId, transactionType, transactionDescription,
transactionAmount, transactionAmountFormatted));
}
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
}
onGetGoalIncomeData();
if (getIncomeDetailsResultsList.size() > 0) {
mIncomeAdapter.onNotifyDataSetChanged(getIncomeDetailsResultsList);
Configuration.runLayoutAnimation(mAllIncomeRecyclerView);
mAllIncomeRecyclerView.setVisibility(View.VISIBLE);
mNoRecordFoundTV.setVisibility(View.GONE);
} else {
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void onGetGoalIncomeData() {
Configuration.onAnimatedLoadingDismiss();
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestToCommonTransactionJsonObject();
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, EndPoints.GET_DASHBOARD_REQUEST, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onGetGoalIncomeResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.GET_INCOME_REQUESTS_TAG);
}
private void onGetGoalIncomeResponse(JSONObject response) {
try {
JSONObject mGoalsJsonObject = response.getJSONObject(Constants.DASHBOARD_TRANSACTION_GOALS_TAG);
mGoalIncomeFormatted = mGoalsJsonObject.getString(Constants.DASHBOARD_TRANSACTION_INCOME_FORMATTED_TAG);
JSONObject mActualJsonObject = response.getJSONObject(Constants.DASHBOARD_TRANSACTION_ACTUALS_TAG);
mActualIncomeFormatted = mActualJsonObject.getString(Constants.DASHBOARD_TRANSACTION_INCOME_FORMATTED_TAG);
mActualIncomeValueTV.setText(mActualIncomeFormatted);
mGoalIncomeValueTV.setText(mGoalIncomeFormatted);
Configuration.onAnimatedLoadingDismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void onAddIncomeView() {
dialogView = View.inflate(mContext, R.layout.fragement_dialog_add_income, null);
dialog = new Dialog(mContext, R.style.MyAlertDialogStyle);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(dialogView);
mTransitionsContainer = dialogView.findViewById(R.id.dialog);
mCategoriesRecyclerView = dialogView.findViewById(R.id.category_recycler_view);
mCategoriesNameET = dialogView.findViewById(R.id.category_name_et);
mTransactionAmountET = dialogView.findViewById(R.id.income_amount_et);
mTransactionDescET = dialogView.findViewById(R.id.income_description_et);
mCategoriesNameWrapper = dialogView.findViewById(R.id.category_name_wrapper);
mTransactionAmountWrapper = dialogView.findViewById(R.id.income_amount_wrapper);
mTransactionDescWrapper = dialogView.findViewById(R.id.income_description_wrapper);
Configuration.ResetTextInputLayout(mContext, mCategoriesNameWrapper, mCategoriesNameET);
Configuration.ResetTextInputLayout(mContext, mTransactionAmountWrapper, mTransactionAmountET);
Configuration.ResetTextInputLayout(mContext, mTransactionDescWrapper, mTransactionDescET);
ImageButton mIncomeSubmitBTN = dialogView.findViewById(R.id.income_submit_action_iv_btn);
mIncomeSubmitBTN.setOnClickListener(this);
BounceView.addAnimTo(mIncomeSubmitBTN);
CategoriesArrayList = new ArrayList<>();
CategoriesArrayList.add("Salary");
CategoriesArrayList.add("Investment");
CategoriesArrayList.add("Dividends");
CategoriesArrayList.add("Coupons");
CategoriesArrayList.add("Refunds");
CategoriesArrayList.add("Rental");
CategoriesArrayList.add("Sales");
CategoriesArrayList.add("Awards");
CategoriesArrayList.add("Other");
GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3);
mCategoriesRecyclerView.setLayoutManager(layoutManager);
mCategoriesRecyclerView.setHasFixedSize(true);
mCategoriesRecyclerViewAdapter = new CategoriesRecyclerViewAdapter(mContext, Constants.INCOME_COLORS, CategoriesArrayList, new CategoriesInterfaces() {
@Override
public void onSelectedItem(int position, String CategoriesName) {
mTransactionType = CategoriesName;
if (!Configuration.isEmptyValidation(mTransactionType)) {
mCategoriesNameET.setText(mTransactionType);
mTransactionAmountET.setFocusable(true);
}
}
});
mCategoriesRecyclerView.setAdapter(mCategoriesRecyclerViewAdapter);
mCategoriesRecyclerViewAdapter.onNotifyDataSetChanged(CategoriesArrayList);
Configuration.runLayoutAnimation(mCategoriesRecyclerView);
ImageView imageView = dialog.findViewById(R.id.closeDialogImg);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
onPrePareAllIncomeData();
}
}, 1500);
revealShow(dialogView, false, dialog);
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
revealShow(dialogView, true, null);
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK) {
revealShow(dialogView, false, dialog);
return true;
}
return false;
}
});
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
private void onPutIncomeRequest(String transactionType, String mTransactionDesc, String mTransactionAmount) {
if (Configuration.isConnected(Objects.requireNonNull(getActivity()))) {
Configuration.onAnimatedLoadingShow(mContext, getResources().getString(R.string.str_loading));
String url = EndPoints.PUT_INCOME_REQUEST;
JSONObject jsonObject = null;
try {
jsonObject = JsonUtils.RequestPutTransactionJsonObject(transactionType, mTransactionDesc, mTransactionAmount);
} catch (JSONException e) {
e.printStackTrace();
}
JsonRequest AddIncomeRequest = new JsonRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
onSuccessResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onFailureResponse(error);
}
});
AddIncomeRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
AddIncomeRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(AddIncomeRequest, Constants.PUT_INCOME_REQUESTS_TAG);
} else {
Configuration.onWarningAlertDialog(mContext, "Alert", getString(R.string.str_no_internet_connection));
}
}
private void onSuccessResponse(JSONObject response) {
try {
final String mMessage = response.getString("message");
Configuration.onAnimatedLoadingDismiss();
onUserConfirmationWarningAlert(mContext, mMessage);
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void onFailureResponse(VolleyError error) {
String errorData = new String(error.networkResponse.data);
try {
JSONObject jsonObject = new JSONObject(errorData);
String mMessage = jsonObject.getString("message");
Configuration.onAnimatedLoadingDismiss();
Configuration.onWarningAlertDialog(mContext, getString(R.string.str_alert), mMessage);
mAllIncomeRecyclerView.setVisibility(View.GONE);
mNoRecordFoundTV.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
Configuration.onAnimatedLoadingDismiss();
}
}
private void revealShow(View dialogView, boolean b, final Dialog dialog) {
final View view = dialogView.findViewById(R.id.dialog);
int w = view.getWidth();
int h = view.getHeight();
int endRadius = (int) Math.hypot(w, h);
int cx = (int) (mAddIncomeFAB.getX() + (mAddIncomeFAB.getWidth() / 2));
int cy = (int) (mAddIncomeFAB.getY()) + mAddIncomeFAB.getHeight() + 54;
if (b) {
Animator revealAnimator = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, endRadius);
view.setVisibility(View.VISIBLE);
revealAnimator.setDuration(800);
revealAnimator.start();
} else {
Animator anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, endRadius, 0);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
dialog.dismiss();
view.setVisibility(View.INVISIBLE);
}
});
anim.setDuration(800);
anim.start();
}
}
@SuppressLint("SetTextI18n")
private void onUserConfirmationWarningAlert(Context mContext, String mMessage) {
final Dialog WarningAlertDialog;
try {
WarningAlertDialog = new Dialog(mContext);
WarningAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
WarningAlertDialog.setContentView(R.layout.dialog_warning_confirmation_layout);
TextView WarningAlertTittleTV = WarningAlertDialog.findViewById(R.id.warning_tittle_tv);
TextView WarningAlertMsgTV = WarningAlertDialog.findViewById(R.id.warning_msg_tv);
Button mPositiveActionBTN = WarningAlertDialog.findViewById(R.id.positive_action_btn);
mPositiveActionBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WarningAlertDialog.dismiss();
mCategoriesNameET.setText("");
mTransactionAmountET.setText("");
mTransactionDescET.setText("");
mCategoriesRecyclerViewAdapter.onNotifyDataSetChanged(CategoriesArrayList);
}
});
Button CloseBTN = WarningAlertDialog.findViewById(R.id.negative_action_btn);
Objects.requireNonNull(WarningAlertDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
WarningAlertDialog.setCancelable(false);
WarningAlertDialog.setCanceledOnTouchOutside(false);
WarningAlertMsgTV.setText(mMessage + ". Do You wish to add another income?");
WarningAlertTittleTV.setText("Alert");
CloseBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCategoriesNameET.setText("");
mTransactionAmountET.setText("");
mTransactionDescET.setText("");
WarningAlertDialog.dismiss();
new Handler().postDelayed(new Runnable() {
public void run() {
onPrePareAllIncomeData();
}
}, 1500);
revealShow(dialogView, false, dialog);
}
});
WarningAlertDialog.show();
BounceView.addAnimTo(WarningAlertDialog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 26,892 | 0.668712 | 0.667299 | 579 | 45.445595 | 33.153877 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737478 | false | false | 2 |
d8b017113a40648357b9f736006ed53341268091 | 24,215,025,628,263 | 25575baf61df02e002babc49b874e10f9f0c9710 | /src/main/java/com/darttc/interceptor/interceptor/LoggedInterceptor.java | 5a225c5196f237a0189c07329358229dcfea7a7b | [] | no_license | boriswaguia/getting-started-interceptor | https://github.com/boriswaguia/getting-started-interceptor | 5ea7e1130c7838868957eca8a673ae464694cb2b | fd6f7cadb5ae5747c0c47fc76c5aaaa51f4a5d9e | refs/heads/master | 2018-03-12T12:16:16.618000 | 2016-09-13T11:44:17 | 2016-09-13T11:44:17 | 68,102,566 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.darttc.interceptor.interceptor;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(LoggedInterceptor.class.getName());
public LoggedInterceptor() {
}
@AroundInvoke
public Object logMethodEntry (InvocationContext invocationContext)
throws Exception {
String methodName = invocationContext.getMethod().getName();
String className = invocationContext.getMethod().getDeclaringClass().getName();
LOG.log(Level.INFO, "La methode "+ methodName+ " de la classe "+ className
+" Viens d'etre invoquee.");
return invocationContext.proceed();
}
}
| UTF-8 | Java | 948 | java | LoggedInterceptor.java | Java | [] | null | [] | package com.darttc.interceptor.interceptor;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(LoggedInterceptor.class.getName());
public LoggedInterceptor() {
}
@AroundInvoke
public Object logMethodEntry (InvocationContext invocationContext)
throws Exception {
String methodName = invocationContext.getMethod().getName();
String className = invocationContext.getMethod().getDeclaringClass().getName();
LOG.log(Level.INFO, "La methode "+ methodName+ " de la classe "+ className
+" Viens d'etre invoquee.");
return invocationContext.proceed();
}
}
| 948 | 0.763713 | 0.762658 | 38 | 23.947369 | 26.099957 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.236842 | false | false | 2 |
e2973db29b10995a9e9a831c97bc46f7643db531 | 24,215,025,628,458 | 2ec905b5b130bed2aa6f1f37591317d80b7ce70d | /ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/math/filters/SimpleMovingAverageFilteredYoVariable.java | f39453303548c104dabd6b8cb67dae2f5500b28c | [
"Apache-2.0"
] | permissive | ihmcrobotics/ihmc-open-robotics-software | https://github.com/ihmcrobotics/ihmc-open-robotics-software | dbb1f9d7a4eaf01c08068b7233d1b01d25c5d037 | 42a4e385af75e8e13291d6156a5c7bebebbecbfd | refs/heads/develop | 2023-09-01T18:18:14.623000 | 2023-09-01T14:16:26 | 2023-09-01T14:16:26 | 50,613,360 | 227 | 91 | null | false | 2023-01-25T21:39:35 | 2016-01-28T21:00:16 | 2023-01-23T10:08:40 | 2023-01-25T21:39:32 | 980,849 | 195 | 77 | 30 | Java | false | false | package us.ihmc.robotics.math.filters;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.row.CommonOps_DDRM;
import us.ihmc.yoVariables.registry.YoRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoInteger;
/**
* Filter the given yoVariable using a moving average filter. This class is NOT REWINDABLE!
*/
public class SimpleMovingAverageFilteredYoVariable extends YoDouble
{
private final YoInteger windowSize;
private final YoDouble yoVariableToFilter;
private final DMatrixRMaj previousUpdateValues = new DMatrixRMaj(0, 0);
private int bufferPosition = 0;
private boolean bufferHasBeenFilled = false;
public SimpleMovingAverageFilteredYoVariable(String name, int windowSize, YoRegistry registry)
{
this(name, windowSize, null, registry);
}
public SimpleMovingAverageFilteredYoVariable(String name, int windowSize, YoDouble yoVariableToFilter, YoRegistry registry)
{
super(name, registry);
this.yoVariableToFilter = yoVariableToFilter;
this.windowSize = new YoInteger(name + "WindowSize", registry);
this.windowSize.set(windowSize);
previousUpdateValues.reshape(windowSize, 1);
CommonOps_DDRM.fill(previousUpdateValues, 0.0);
}
public void setWindowSize(int windowSize)
{
this.windowSize.set(windowSize);
reset();
}
public void update()
{
update(yoVariableToFilter.getDoubleValue());
}
public void update(double value)
{
if (previousUpdateValues.getNumRows() != windowSize.getIntegerValue())
{
reset();
}
previousUpdateValues.set(bufferPosition, 0, value);
bufferPosition++;
if (bufferPosition >= windowSize.getIntegerValue())
{
bufferPosition = 0;
bufferHasBeenFilled = true;
}
double average = 0;
for (int i = 0; i < windowSize.getIntegerValue(); i++)
{
average += previousUpdateValues.get(i, 0);
}
this.set(average / ((double) windowSize.getIntegerValue()));
}
public void reset()
{
bufferPosition = 0;
bufferHasBeenFilled = false;
previousUpdateValues.reshape(windowSize.getIntegerValue(), 1);
}
public boolean getHasBufferWindowFilled()
{
return bufferHasBeenFilled;
}
}
| UTF-8 | Java | 2,322 | java | SimpleMovingAverageFilteredYoVariable.java | Java | [] | null | [] | package us.ihmc.robotics.math.filters;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.row.CommonOps_DDRM;
import us.ihmc.yoVariables.registry.YoRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoInteger;
/**
* Filter the given yoVariable using a moving average filter. This class is NOT REWINDABLE!
*/
public class SimpleMovingAverageFilteredYoVariable extends YoDouble
{
private final YoInteger windowSize;
private final YoDouble yoVariableToFilter;
private final DMatrixRMaj previousUpdateValues = new DMatrixRMaj(0, 0);
private int bufferPosition = 0;
private boolean bufferHasBeenFilled = false;
public SimpleMovingAverageFilteredYoVariable(String name, int windowSize, YoRegistry registry)
{
this(name, windowSize, null, registry);
}
public SimpleMovingAverageFilteredYoVariable(String name, int windowSize, YoDouble yoVariableToFilter, YoRegistry registry)
{
super(name, registry);
this.yoVariableToFilter = yoVariableToFilter;
this.windowSize = new YoInteger(name + "WindowSize", registry);
this.windowSize.set(windowSize);
previousUpdateValues.reshape(windowSize, 1);
CommonOps_DDRM.fill(previousUpdateValues, 0.0);
}
public void setWindowSize(int windowSize)
{
this.windowSize.set(windowSize);
reset();
}
public void update()
{
update(yoVariableToFilter.getDoubleValue());
}
public void update(double value)
{
if (previousUpdateValues.getNumRows() != windowSize.getIntegerValue())
{
reset();
}
previousUpdateValues.set(bufferPosition, 0, value);
bufferPosition++;
if (bufferPosition >= windowSize.getIntegerValue())
{
bufferPosition = 0;
bufferHasBeenFilled = true;
}
double average = 0;
for (int i = 0; i < windowSize.getIntegerValue(); i++)
{
average += previousUpdateValues.get(i, 0);
}
this.set(average / ((double) windowSize.getIntegerValue()));
}
public void reset()
{
bufferPosition = 0;
bufferHasBeenFilled = false;
previousUpdateValues.reshape(windowSize.getIntegerValue(), 1);
}
public boolean getHasBufferWindowFilled()
{
return bufferHasBeenFilled;
}
}
| 2,322 | 0.695952 | 0.690353 | 87 | 25.689655 | 27.348879 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597701 | false | false | 2 |
3d6ca5143c3fc21ae679ee7271d8c7096e31a30e | 3,848,290,712,490 | 1c3458b233d4d4d95e410d6bc8bec8cf2545be72 | /src/easy/sql/Sql.java | 799bcc7af40dc19e58e01b1bdc343f24c530f7fe | [] | no_license | darkice1/EASYCORE | https://github.com/darkice1/EASYCORE | 3eeac7352760da01633729c8f4be122848982982 | d7cd3dc47a2761ee057ceb434b11bf7dbdc810be | refs/heads/master | 2021-01-17T10:10:34.529000 | 2016-04-06T09:06:52 | 2016-04-06T09:06:52 | 27,005,014 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package easy.sql;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import easy.config.Config;
import easy.io.JFile;
import easy.util.EDate;
import easy.util.Format;
import easy.util.Log;
/**
* <p>
* <i>Copyright: Easy (c) 2005-2005 <br>
* Company: Easy </i>
* </p>
*
* 数据库基类
*
* @version 1.0 ( <i>2005-7-5 neo </i>)
*/
public abstract class Sql
{
//System.getProperty("java.io.tmpdir"))
protected final String CACHEPATH = Config.getProperty("DBCACHE",System.getProperty("java.io.tmpdir"));
protected final long CACHEKEEPTIME = Long.parseLong(Config.getProperty("CACHEKEEPTIME","600000"));
protected Connection conn;
protected Statement stmt;
//protected ResultSet rs;
protected String user = "";
protected String password = "";
protected String db = "";
protected String host;
protected int port;
protected String jdbcurl = "";
protected PreparedStatement ps;
protected int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
protected int resultSetConncurrency = ResultSet.CONCUR_READ_ONLY;
protected Properties info = new Properties();
protected long upcount=0;
protected long insertcount=0;
protected long deltcount=0;
/**
* ������ݿ⣬�û�������,ip��
*/
protected abstract void init();
protected boolean isinit = false;
/**
* ��ʼ����ݿ�
*/
protected abstract void initdb();
protected void instance()
{
init();
initdb();
isinit = true;
}
public Sql()
{
}
public Sql(int resultSetType, int resultSetConncurrency)
{
this.resultSetType = resultSetType;
this.resultSetConncurrency = resultSetConncurrency;
instance();
}
public DataSet executeQuery(String formate,Object... strs) throws SQLException
{
String sql = String.format(formate,strs);
DataSet ds = executeQuery(sql);
sql = null;
return ds;
}
/**
* 数据库查询
* @param sql
* @return
* @throws SQLException
*/
public DataSet executeQuery(String sql) throws SQLException
{
try
{
Log.OutSql(sql);
ResultSet rs = getStmt().executeQuery(sql);
DataSet ds = new DataSet(rs);
rs.close();
rs=null;
return ds;
}
catch (SQLException ex)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
throw ex;
}
}
public DataSet executeQueryCache(String formate,Object... strs) throws SQLException, IOException
{
String sql = String.format(formate,strs);
DataSet ds = executeQueryCache(sql);
sql = null;
return ds;
}
public DataSet executeQueryCache(long keeptime,String formate,Object... strs) throws SQLException, IOException
{
String sql = String.format(formate,strs);
DataSet ds = executeQueryCache(sql,keeptime);
sql = null;
return ds;
}
public DataSet executeQueryCache(String sql) throws SQLException, IOException
{
return executeQueryCache(sql,CACHEKEEPTIME);
}
public DataSet executeQueryCache(String sql,long keeptime) throws SQLException, IOException
{
DataSet ds = null;
if (keeptime <= 0)
{
ds = executeQuery(sql);
}
else
{
File file = new File(CACHEPATH);
boolean pathok =false;
if (file.exists() == false)
{
pathok = file.mkdir();
}
else
{
if (file.isDirectory() == false)
{
file.delete();
pathok = file.mkdirs();
}
else
{
pathok = true;
}
}
if (pathok==false)
{
throw new IOException(String.format("%s not find.", CACHEPATH));
}
sql = sql.trim();
/*
user = Config.getProperty("DBUSER");
password = Config.getProperty("DBPASSWORD");
jdbcurl = Config.getProperty("DBURL");
dbclass = Config.getProperty("DBCLASS");
*/
String md5 = Format.Md5(String.format("%s %s %s %s %s",user,password,jdbcurl,jdbcurl, sql));
String path = String.format("%s/%s.db", CACHEPATH,md5);
//System.out.println(path);
boolean neednew = false;
if (JFile.exists(path))
{
try
{
CDataSet cds = (CDataSet)JFile.readGZipObject(path);
long now = System.currentTimeMillis();
long end = cds.getEndtime();
if (now > end)
{
neednew = true;
}
else
{
ds = new DataSet();
for (Row r: cds.getDataSet().getRowList())
{
ds.AddRow(r);
r = null;
}
EDate d = new EDate();
d.setTime(end);
Log.OutSql(String.format("[CACHE/%s]%s",d,sql));
d = null;
cds = null;
return ds;
}
cds = null;
}
catch (ClassNotFoundException e)
{
neednew = true;
}
catch (Exception e)
{
//Log.OutException(e);
neednew = true;
}
}
else
{
neednew = true;
}
if (neednew)
{
ds = executeQuery(sql);
CDataSet cds = new CDataSet();
long now = System.currentTimeMillis();
long endtime = now + keeptime;
cds.setStarttime(now);
cds.setEndtime(endtime);
cds.setDataSet(ds);
cds.setSql(sql);
FileOutputStream fo = new FileOutputStream(path);
try
{
FileLock fl = fo.getChannel().tryLock();
if (fl != null)
{
JFile.writeGZipObject(fo, cds);
}
}
catch (OverlappingFileLockException e)
{
//Log.OutException(e);
}
fo.close();
cds = null;
}
file = null;
md5 = null;
path = null;
}
return ds;
}
public void close()
{
// try
// {
// if (rs != null)
// {
// rs.close();
// }
// }
// catch (SQLException ex)
// {
// Log.OutException(ex);
// }
try
{
//&& stmt.isClosed()==false
if (stmt != null )
{
stmt.close();
stmt = null;
}
}
catch (SQLException ex)
{
Log.OutException(ex);
}
try
{
if (conn != null && conn.isClosed()==false)
{
conn.close();
conn = null;
}
}
catch (SQLException ex)
{
Log.OutException(ex, jdbcurl);
}
}
public boolean isClosed()
{
boolean re;
try
{
if (conn !=null)
{
re = conn.isClosed();
}
else
{
return true;
}
}
catch (Exception ex)
{
Log.OutException(ex);
return true;
}
return re;
}
public int executeUpdate(String formate,Object... strs)
{
String sql = String.format(formate,strs);
int re = executeUpdate(sql);
sql = null;
return re;
}
/**
* 数据库更新
* @param sql
* @return
*/
public int executeUpdate(String sql)
{
try
{
String sqlstr = checksql(sql);
Log.OutSql(sql);
int re = getStmt().executeUpdate(sqlstr);
sqlstr= null;
return re;
}
catch (SQLException ex)
{
if (ex.toString().indexOf("Data truncation: Data truncated for column") <= 0)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
}
return -1;
}
}
private Statement getStmt()
{
if (isinit == false)
{
instance();
isinit = true;
}
// if (stmt==null)
// {
// initdb();
// }
return stmt;
}
/**
* 数据库更新(返回异常)
* @param sql
* @return
* @throws SQLException
*/
public int executeUpdateEx(String sql) throws SQLException
{
String sqlstr = checksql(sql);
Log.OutSql(sql);
int re = getStmt().executeUpdate(sqlstr);
sqlstr = null;
return re;
}
// protected void finalize() throws Throwable
// {
// super.finalize();
// if (isClosed() == false)
// {
// close();
// }
// conn = null;
// stmt = null;
// user = null;
// password = null;
// db = null;
// host = null;
// jdbcurl = null;
// ps = null;
// info = null;
// }
protected String checksql(String sql)
{
char zero[] = { 0 };
sql.replaceAll(new String(zero), "");
zero = null;
return sql;
}
public DataSet getResultSet() throws SQLException
{
return new DataSet(getStmt().getResultSet());
}
public void addBatch(String sql)
{
try
{
if (sql.length()>6)
{
String t = sql.substring(0,6).toLowerCase();
if (t.equals("insert"))
{
insertcount++;
}
else if (t.equals("delete"))
{
deltcount++;
}
else if (t.equals("update"))
{
upcount++;
}
t = null;
}
getStmt().addBatch(sql);
Log.OutSql(sql);
}
catch (Exception ex)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
}
}
/**
* @return the upcount
*/
public long getUpcount()
{
return upcount;
}
/**
* @return the insertcount
*/
public long getInsertcount()
{
return insertcount;
}
/**
* @return the deltcount
*/
public long getDeltcount()
{
return deltcount;
}
public int[] executeBatch()
{
try
{
upcount=0;
insertcount=0;
deltcount=0;
return getStmt().executeBatch();
}
catch (Exception ex)
{
Log.OutException(ex, jdbcurl);
return null;
}
}
public Connection getConnection()
{
return conn;
}
public String getClobString(Clob clob)
{
try
{
return clob.getSubString(1l, (int) clob.length());
}
catch (Exception ex)
{
Log.OutException(ex);
return null;
}
}
public PreparedStatement createPstmt(String sql)
{
PreparedStatement pstmt = null;
try
{
pstmt = conn.prepareStatement(sql);
}
catch (Exception ex)
{
Log.OutException(ex);
}
return pstmt;
}
public void prepareStatement(String sql) throws SQLException
{
ps = conn.prepareStatement(sql);
}
public Statement getStatement()
{
return getStmt();
}
}
| UTF-8 | Java | 10,150 | java | Sql.java | Java | [
{
"context": "onfig.getProperty(\"DBUSER\");\r\n\t\t\tpassword = Config.getProperty(\"DBPASSWORD\");\r\n\t\t\tjdbcurl = Config.getProperty(\"",
"end": 3962,
"score": 0.5223796367645264,
"start": 3951,
"tag": "PASSWORD",
"value": "getProperty"
},
{
"context": "rty(\"DBUSER\");\r\n\t\t... | null | [] | package easy.sql;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import easy.config.Config;
import easy.io.JFile;
import easy.util.EDate;
import easy.util.Format;
import easy.util.Log;
/**
* <p>
* <i>Copyright: Easy (c) 2005-2005 <br>
* Company: Easy </i>
* </p>
*
* 数据库基类
*
* @version 1.0 ( <i>2005-7-5 neo </i>)
*/
public abstract class Sql
{
//System.getProperty("java.io.tmpdir"))
protected final String CACHEPATH = Config.getProperty("DBCACHE",System.getProperty("java.io.tmpdir"));
protected final long CACHEKEEPTIME = Long.parseLong(Config.getProperty("CACHEKEEPTIME","600000"));
protected Connection conn;
protected Statement stmt;
//protected ResultSet rs;
protected String user = "";
protected String password = "";
protected String db = "";
protected String host;
protected int port;
protected String jdbcurl = "";
protected PreparedStatement ps;
protected int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
protected int resultSetConncurrency = ResultSet.CONCUR_READ_ONLY;
protected Properties info = new Properties();
protected long upcount=0;
protected long insertcount=0;
protected long deltcount=0;
/**
* ������ݿ⣬�û�������,ip��
*/
protected abstract void init();
protected boolean isinit = false;
/**
* ��ʼ����ݿ�
*/
protected abstract void initdb();
protected void instance()
{
init();
initdb();
isinit = true;
}
public Sql()
{
}
public Sql(int resultSetType, int resultSetConncurrency)
{
this.resultSetType = resultSetType;
this.resultSetConncurrency = resultSetConncurrency;
instance();
}
public DataSet executeQuery(String formate,Object... strs) throws SQLException
{
String sql = String.format(formate,strs);
DataSet ds = executeQuery(sql);
sql = null;
return ds;
}
/**
* 数据库查询
* @param sql
* @return
* @throws SQLException
*/
public DataSet executeQuery(String sql) throws SQLException
{
try
{
Log.OutSql(sql);
ResultSet rs = getStmt().executeQuery(sql);
DataSet ds = new DataSet(rs);
rs.close();
rs=null;
return ds;
}
catch (SQLException ex)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
throw ex;
}
}
public DataSet executeQueryCache(String formate,Object... strs) throws SQLException, IOException
{
String sql = String.format(formate,strs);
DataSet ds = executeQueryCache(sql);
sql = null;
return ds;
}
public DataSet executeQueryCache(long keeptime,String formate,Object... strs) throws SQLException, IOException
{
String sql = String.format(formate,strs);
DataSet ds = executeQueryCache(sql,keeptime);
sql = null;
return ds;
}
public DataSet executeQueryCache(String sql) throws SQLException, IOException
{
return executeQueryCache(sql,CACHEKEEPTIME);
}
public DataSet executeQueryCache(String sql,long keeptime) throws SQLException, IOException
{
DataSet ds = null;
if (keeptime <= 0)
{
ds = executeQuery(sql);
}
else
{
File file = new File(CACHEPATH);
boolean pathok =false;
if (file.exists() == false)
{
pathok = file.mkdir();
}
else
{
if (file.isDirectory() == false)
{
file.delete();
pathok = file.mkdirs();
}
else
{
pathok = true;
}
}
if (pathok==false)
{
throw new IOException(String.format("%s not find.", CACHEPATH));
}
sql = sql.trim();
/*
user = Config.getProperty("DBUSER");
password = Config.<PASSWORD>("<PASSWORD>");
jdbcurl = Config.getProperty("DBURL");
dbclass = Config.getProperty("DBCLASS");
*/
String md5 = Format.Md5(String.format("%s %s %s %s %s",user,password,jdbcurl,jdbcurl, sql));
String path = String.format("%s/%s.db", CACHEPATH,md5);
//System.out.println(path);
boolean neednew = false;
if (JFile.exists(path))
{
try
{
CDataSet cds = (CDataSet)JFile.readGZipObject(path);
long now = System.currentTimeMillis();
long end = cds.getEndtime();
if (now > end)
{
neednew = true;
}
else
{
ds = new DataSet();
for (Row r: cds.getDataSet().getRowList())
{
ds.AddRow(r);
r = null;
}
EDate d = new EDate();
d.setTime(end);
Log.OutSql(String.format("[CACHE/%s]%s",d,sql));
d = null;
cds = null;
return ds;
}
cds = null;
}
catch (ClassNotFoundException e)
{
neednew = true;
}
catch (Exception e)
{
//Log.OutException(e);
neednew = true;
}
}
else
{
neednew = true;
}
if (neednew)
{
ds = executeQuery(sql);
CDataSet cds = new CDataSet();
long now = System.currentTimeMillis();
long endtime = now + keeptime;
cds.setStarttime(now);
cds.setEndtime(endtime);
cds.setDataSet(ds);
cds.setSql(sql);
FileOutputStream fo = new FileOutputStream(path);
try
{
FileLock fl = fo.getChannel().tryLock();
if (fl != null)
{
JFile.writeGZipObject(fo, cds);
}
}
catch (OverlappingFileLockException e)
{
//Log.OutException(e);
}
fo.close();
cds = null;
}
file = null;
md5 = null;
path = null;
}
return ds;
}
public void close()
{
// try
// {
// if (rs != null)
// {
// rs.close();
// }
// }
// catch (SQLException ex)
// {
// Log.OutException(ex);
// }
try
{
//&& stmt.isClosed()==false
if (stmt != null )
{
stmt.close();
stmt = null;
}
}
catch (SQLException ex)
{
Log.OutException(ex);
}
try
{
if (conn != null && conn.isClosed()==false)
{
conn.close();
conn = null;
}
}
catch (SQLException ex)
{
Log.OutException(ex, jdbcurl);
}
}
public boolean isClosed()
{
boolean re;
try
{
if (conn !=null)
{
re = conn.isClosed();
}
else
{
return true;
}
}
catch (Exception ex)
{
Log.OutException(ex);
return true;
}
return re;
}
public int executeUpdate(String formate,Object... strs)
{
String sql = String.format(formate,strs);
int re = executeUpdate(sql);
sql = null;
return re;
}
/**
* 数据库更新
* @param sql
* @return
*/
public int executeUpdate(String sql)
{
try
{
String sqlstr = checksql(sql);
Log.OutSql(sql);
int re = getStmt().executeUpdate(sqlstr);
sqlstr= null;
return re;
}
catch (SQLException ex)
{
if (ex.toString().indexOf("Data truncation: Data truncated for column") <= 0)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
}
return -1;
}
}
private Statement getStmt()
{
if (isinit == false)
{
instance();
isinit = true;
}
// if (stmt==null)
// {
// initdb();
// }
return stmt;
}
/**
* 数据库更新(返回异常)
* @param sql
* @return
* @throws SQLException
*/
public int executeUpdateEx(String sql) throws SQLException
{
String sqlstr = checksql(sql);
Log.OutSql(sql);
int re = getStmt().executeUpdate(sqlstr);
sqlstr = null;
return re;
}
// protected void finalize() throws Throwable
// {
// super.finalize();
// if (isClosed() == false)
// {
// close();
// }
// conn = null;
// stmt = null;
// user = null;
// password = <PASSWORD>;
// db = null;
// host = null;
// jdbcurl = null;
// ps = null;
// info = null;
// }
protected String checksql(String sql)
{
char zero[] = { 0 };
sql.replaceAll(new String(zero), "");
zero = null;
return sql;
}
public DataSet getResultSet() throws SQLException
{
return new DataSet(getStmt().getResultSet());
}
public void addBatch(String sql)
{
try
{
if (sql.length()>6)
{
String t = sql.substring(0,6).toLowerCase();
if (t.equals("insert"))
{
insertcount++;
}
else if (t.equals("delete"))
{
deltcount++;
}
else if (t.equals("update"))
{
upcount++;
}
t = null;
}
getStmt().addBatch(sql);
Log.OutSql(sql);
}
catch (Exception ex)
{
Log.OutException(ex, jdbcurl + "\r\n" + sql);
}
}
/**
* @return the upcount
*/
public long getUpcount()
{
return upcount;
}
/**
* @return the insertcount
*/
public long getInsertcount()
{
return insertcount;
}
/**
* @return the deltcount
*/
public long getDeltcount()
{
return deltcount;
}
public int[] executeBatch()
{
try
{
upcount=0;
insertcount=0;
deltcount=0;
return getStmt().executeBatch();
}
catch (Exception ex)
{
Log.OutException(ex, jdbcurl);
return null;
}
}
public Connection getConnection()
{
return conn;
}
public String getClobString(Clob clob)
{
try
{
return clob.getSubString(1l, (int) clob.length());
}
catch (Exception ex)
{
Log.OutException(ex);
return null;
}
}
public PreparedStatement createPstmt(String sql)
{
PreparedStatement pstmt = null;
try
{
pstmt = conn.prepareStatement(sql);
}
catch (Exception ex)
{
Log.OutException(ex);
}
return pstmt;
}
public void prepareStatement(String sql) throws SQLException
{
ps = conn.prepareStatement(sql);
}
public Statement getStatement()
{
return getStmt();
}
}
| 10,155 | 0.573661 | 0.569679 | 560 | 15.939285 | 17.705929 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.535714 | false | false | 2 |
bb7fa1192143c5e3b346af7bdce3ed421d2024c8 | 19,679,540,167,809 | 5da4861eed3a8e2209553f749b55cb9cb0f903c7 | /Happyhouse/src/main/java/_02_sellhouse/controller/SellHouseFilter.java | 6a7da8b9bee2233664f8898cd3da3bd14cca82f6 | [] | no_license | EEIT84-8GA9/RepositoryFinalProject | https://github.com/EEIT84-8GA9/RepositoryFinalProject | b7432c1d9112b7428c376fb051d3e1ec1675ffe6 | 34a7f4b64c6b6398e081ccda529d4eb191cea75e | refs/heads/master | 2021-01-01T03:43:27.705000 | 2016-05-03T13:21:33 | 2016-05-03T13:21:33 | 55,965,548 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package _02_sellhouse.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import _02_sellhouse.model.SellHouseBean;
import _02_sellhouse.model.SellHouseDAO;
import _02_sellhouse.model.SellHouseService;
import _02_sellhouse.model.dao.SellHouseDAOJdbc;
@WebFilter(
urlPatterns = { "/_02_sellhouse/SellHouseSearch.jsp" },
initParams = {
@WebInitParam(name ="sellhouse", value ="/_02_sellhouse/SellHouseSearch.jsp"),
}
)
public class SellHouseFilter implements Filter {
Collection<String> url = new ArrayList<String>();
String servletPath;
String contextPath;
String requestURI;
@Override
public void init(FilterConfig fConfig) throws ServletException {
Enumeration<String> e = fConfig.getInitParameterNames();
while (e.hasMoreElements()) {
String path = e.nextElement();
url.add(fConfig.getInitParameter(path));
}
System.out.println("AAAA"+url);
}
private boolean mustLogin(){
boolean login=false;
for(String sURL:url){
if(sURL.endsWith("*")){
sURL = sURL.substring(0, sURL.length() - 2);
if (servletPath.startsWith(sURL)) {
login = true;
break;
}
}else {
if (servletPath.equals(sURL)) {
login = true;
break;
}
}
}
return login;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session =req.getSession();
servletPath = req.getServletPath();
contextPath = req.getContextPath();
requestURI = req.getRequestURI();
SellHouseDAO dao=new SellHouseDAOJdbc();
//SellHouseBean bean=new SellHouseBean();
List<SellHouseBean> result =dao.SELECT_ALL();
session.removeAttribute("bean2");
req.setAttribute("select", result);
request.getRequestDispatcher("/_02_sellhouse/SellHouseSearch.jsp").forward(req, resp);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 2,720 | java | SellHouseFilter.java | Java | [] | null | [] | package _02_sellhouse.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import _02_sellhouse.model.SellHouseBean;
import _02_sellhouse.model.SellHouseDAO;
import _02_sellhouse.model.SellHouseService;
import _02_sellhouse.model.dao.SellHouseDAOJdbc;
@WebFilter(
urlPatterns = { "/_02_sellhouse/SellHouseSearch.jsp" },
initParams = {
@WebInitParam(name ="sellhouse", value ="/_02_sellhouse/SellHouseSearch.jsp"),
}
)
public class SellHouseFilter implements Filter {
Collection<String> url = new ArrayList<String>();
String servletPath;
String contextPath;
String requestURI;
@Override
public void init(FilterConfig fConfig) throws ServletException {
Enumeration<String> e = fConfig.getInitParameterNames();
while (e.hasMoreElements()) {
String path = e.nextElement();
url.add(fConfig.getInitParameter(path));
}
System.out.println("AAAA"+url);
}
private boolean mustLogin(){
boolean login=false;
for(String sURL:url){
if(sURL.endsWith("*")){
sURL = sURL.substring(0, sURL.length() - 2);
if (servletPath.startsWith(sURL)) {
login = true;
break;
}
}else {
if (servletPath.equals(sURL)) {
login = true;
break;
}
}
}
return login;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session =req.getSession();
servletPath = req.getServletPath();
contextPath = req.getContextPath();
requestURI = req.getRequestURI();
SellHouseDAO dao=new SellHouseDAOJdbc();
//SellHouseBean bean=new SellHouseBean();
List<SellHouseBean> result =dao.SELECT_ALL();
session.removeAttribute("bean2");
req.setAttribute("select", result);
request.getRequestDispatcher("/_02_sellhouse/SellHouseSearch.jsp").forward(req, resp);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
| 2,720 | 0.715441 | 0.708088 | 94 | 26.936171 | 20.763515 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.212766 | false | false | 2 |
1f2216d5001776484190bca35fb0a23d37694b4f | 5,420,248,742,252 | 7181f4289d1d934da97bf623468bccd2421cbfed | /src/main/java/cn/edu/hdu/service/impl/FileServiceImpl.java | 7d40d304f192d40bb312982e425c17eb6f3e50f6 | [] | no_license | xoo1996/huiermall | https://github.com/xoo1996/huiermall | f556768d26f9082d7a49f1402d43c9937ab25be9 | 40878ea0d0187c11733dd86997a43c0d5266c97d | refs/heads/master | 2020-04-16T03:49:14.142000 | 2019-01-11T13:14:53 | 2019-01-11T13:14:53 | 165,234,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.hdu.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.edu.hdu.Code.UploadCode;
import cn.edu.hdu.dao.impl.PictureDirDaoImpl;
import cn.edu.hdu.dto.PictureDirDto;
import cn.edu.hdu.pojo.Activity;
import cn.edu.hdu.pojo.PictureDir;
import cn.edu.hdu.service.FileService;
import cn.edu.hdu.service.impl.GenericService;
import cn.edu.hdu.util.FileUtil;
import cn.edu.hdu.util.StrUtil;
@Service(value="fileService")
public class FileServiceImpl extends GenericService<PictureDir> implements FileService {
private static Logger logger = Logger.getLogger(FileServiceImpl.class);
@Resource
private ActivityServiceImpl activityService;
@Resource
private FileService fileService;
public PictureDirDaoImpl getPictureDirDao() {
return (PictureDirDaoImpl)this.getGenericDao();
}
@Autowired
public void setPictureDirDao(PictureDirDaoImpl pictureDirDao) {
this.setGenericDao(pictureDirDao);
}
@Override
public Long saveImgPath(String path,String moduleName,Long seriesId) {
if(path == null || moduleName == null || seriesId == null){
return -1L;
}
Long id = null;
try {
id = this.getPictureDirDao().saveImgPath(path,moduleName, seriesId);
} catch (Exception e) {
return -1L;
}
if(id != null){
return id;
}else{
return -1L;
}
}
@Override
public List<String> getImgPath(String moduleName) {
if(moduleName == null){
return new ArrayList<String>();
}
List<String> imgs = new ArrayList<String>();
try {
imgs = this.getPictureDirDao().getImgPath(moduleName);
} catch (Exception e) {
logger.error(" getImgPath " + moduleName + "查询异常");
e.printStackTrace();
}
return imgs;
}
@Override
public List<String> getImgUrl(String moduleName) {
if(moduleName == null){
return new ArrayList<String>();
}
List<Long> idList = new ArrayList<Long>();
List<String> urlList = new ArrayList<String>();
try {
idList = this.getPictureDirDao().findByHql("select pd.id from PictureDir pd where pd.moduleName = ?"
+ "order by pd.picIndex asc", moduleName);
for(Long id:idList){
String s = FileUtil.getUrl(UploadCode.MODULE_LUNBO, id);
urlList.add(s);
}
} catch (Exception e) {
logger.error(" getImgUrl " + moduleName + "查询异常");
e.printStackTrace();
}
return urlList;
}
@Override
public Long saveImg(String moduleDir,String moduleName,
MultipartFile file, Long seriesId) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = FileUtil.getFilePath(moduleDir,fileName,seriesId);
FileUtil.saveImg(file, filePath); //保存到本地
Long id = fileService.saveImgPath(filePath,moduleName, seriesId);//保存本地路径
return id;
}
@Override
public List<PictureDirDto> getImgDir(String moduleName) {
if(moduleName == null){
return new ArrayList<PictureDirDto>();
}
List<PictureDir> pdList = new ArrayList<PictureDir>();
List<PictureDirDto> pddList = new ArrayList<PictureDirDto>();
try {
pdList = this.getPictureDirDao().findByHql(" from PictureDir pd where pd.moduleName = ? "
+ "order by pd.picIndex asc", moduleName);
for(PictureDir pd:pdList){
PictureDirDto pdd = PictureDirDto.getInstance(pd);
String s = FileUtil.getUrl(moduleName, pd.getId());
pdd.setUrl(s);
if(pdd.getActivityId() != null){
Activity act = activityService.findById(pdd.getActivityId());
pdd.setAct(act);
}
pddList.add(pdd);
}
} catch (Exception e) {
logger.error(" getImgUrl " + moduleName + "查询异常");
e.printStackTrace();
}
return pddList;
}
@Override
public boolean saveImgPath(String path, String moduleName, Long seriesId,
Long index) {
try {
Long id = this.saveImgPath(path, moduleName, seriesId);
this.findById(id).setPicIndex(index);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean correctLunboImgIndex() {
try {
List<PictureDir> pdList = null;
String moduleName = UploadCode.MODULE_LUNBO;
pdList = this.getPictureDirDao().findByHql(" from PictureDir pd where pd.moduleName = ? "
+ "order by pd.picIndex asc,pd.uploadDate desc", moduleName);
for(int i = 0;i < pdList.size();i++){
pdList.get(i).setPicIndex(Integer.valueOf(i + 1).longValue());
}
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean correctLunboImgIndex(String[] dataArray) {
try {
for(String data:dataArray){
if(data.equals("")){
continue;
}
String[] da = data.split("=");
Long id = Long.parseLong(da[0]);
Long index = Long.parseLong(da[1]);
PictureDir pd = this.findById(id);
if(pd != null){
pd.setPicIndex(index);
}
}
this.correctLunboImgIndex();
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public boolean deleteLocalImg(Long pictureId) {
try {
PictureDir pd = this.findById(pictureId);
String path = pd.getPath(); //活动图片服务器路径
FileUtil.deleteFile(path);
this.delete(pd);
return true;
} catch (Exception e) {
return false;
}
}
}
| UTF-8 | Java | 5,446 | java | FileServiceImpl.java | Java | [] | null | [] | package cn.edu.hdu.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.edu.hdu.Code.UploadCode;
import cn.edu.hdu.dao.impl.PictureDirDaoImpl;
import cn.edu.hdu.dto.PictureDirDto;
import cn.edu.hdu.pojo.Activity;
import cn.edu.hdu.pojo.PictureDir;
import cn.edu.hdu.service.FileService;
import cn.edu.hdu.service.impl.GenericService;
import cn.edu.hdu.util.FileUtil;
import cn.edu.hdu.util.StrUtil;
@Service(value="fileService")
public class FileServiceImpl extends GenericService<PictureDir> implements FileService {
private static Logger logger = Logger.getLogger(FileServiceImpl.class);
@Resource
private ActivityServiceImpl activityService;
@Resource
private FileService fileService;
public PictureDirDaoImpl getPictureDirDao() {
return (PictureDirDaoImpl)this.getGenericDao();
}
@Autowired
public void setPictureDirDao(PictureDirDaoImpl pictureDirDao) {
this.setGenericDao(pictureDirDao);
}
@Override
public Long saveImgPath(String path,String moduleName,Long seriesId) {
if(path == null || moduleName == null || seriesId == null){
return -1L;
}
Long id = null;
try {
id = this.getPictureDirDao().saveImgPath(path,moduleName, seriesId);
} catch (Exception e) {
return -1L;
}
if(id != null){
return id;
}else{
return -1L;
}
}
@Override
public List<String> getImgPath(String moduleName) {
if(moduleName == null){
return new ArrayList<String>();
}
List<String> imgs = new ArrayList<String>();
try {
imgs = this.getPictureDirDao().getImgPath(moduleName);
} catch (Exception e) {
logger.error(" getImgPath " + moduleName + "查询异常");
e.printStackTrace();
}
return imgs;
}
@Override
public List<String> getImgUrl(String moduleName) {
if(moduleName == null){
return new ArrayList<String>();
}
List<Long> idList = new ArrayList<Long>();
List<String> urlList = new ArrayList<String>();
try {
idList = this.getPictureDirDao().findByHql("select pd.id from PictureDir pd where pd.moduleName = ?"
+ "order by pd.picIndex asc", moduleName);
for(Long id:idList){
String s = FileUtil.getUrl(UploadCode.MODULE_LUNBO, id);
urlList.add(s);
}
} catch (Exception e) {
logger.error(" getImgUrl " + moduleName + "查询异常");
e.printStackTrace();
}
return urlList;
}
@Override
public Long saveImg(String moduleDir,String moduleName,
MultipartFile file, Long seriesId) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = FileUtil.getFilePath(moduleDir,fileName,seriesId);
FileUtil.saveImg(file, filePath); //保存到本地
Long id = fileService.saveImgPath(filePath,moduleName, seriesId);//保存本地路径
return id;
}
@Override
public List<PictureDirDto> getImgDir(String moduleName) {
if(moduleName == null){
return new ArrayList<PictureDirDto>();
}
List<PictureDir> pdList = new ArrayList<PictureDir>();
List<PictureDirDto> pddList = new ArrayList<PictureDirDto>();
try {
pdList = this.getPictureDirDao().findByHql(" from PictureDir pd where pd.moduleName = ? "
+ "order by pd.picIndex asc", moduleName);
for(PictureDir pd:pdList){
PictureDirDto pdd = PictureDirDto.getInstance(pd);
String s = FileUtil.getUrl(moduleName, pd.getId());
pdd.setUrl(s);
if(pdd.getActivityId() != null){
Activity act = activityService.findById(pdd.getActivityId());
pdd.setAct(act);
}
pddList.add(pdd);
}
} catch (Exception e) {
logger.error(" getImgUrl " + moduleName + "查询异常");
e.printStackTrace();
}
return pddList;
}
@Override
public boolean saveImgPath(String path, String moduleName, Long seriesId,
Long index) {
try {
Long id = this.saveImgPath(path, moduleName, seriesId);
this.findById(id).setPicIndex(index);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean correctLunboImgIndex() {
try {
List<PictureDir> pdList = null;
String moduleName = UploadCode.MODULE_LUNBO;
pdList = this.getPictureDirDao().findByHql(" from PictureDir pd where pd.moduleName = ? "
+ "order by pd.picIndex asc,pd.uploadDate desc", moduleName);
for(int i = 0;i < pdList.size();i++){
pdList.get(i).setPicIndex(Integer.valueOf(i + 1).longValue());
}
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean correctLunboImgIndex(String[] dataArray) {
try {
for(String data:dataArray){
if(data.equals("")){
continue;
}
String[] da = data.split("=");
Long id = Long.parseLong(da[0]);
Long index = Long.parseLong(da[1]);
PictureDir pd = this.findById(id);
if(pd != null){
pd.setPicIndex(index);
}
}
this.correctLunboImgIndex();
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public boolean deleteLocalImg(Long pictureId) {
try {
PictureDir pd = this.findById(pictureId);
String path = pd.getPath(); //活动图片服务器路径
FileUtil.deleteFile(path);
this.delete(pd);
return true;
} catch (Exception e) {
return false;
}
}
}
| 5,446 | 0.699368 | 0.697882 | 201 | 25.776119 | 22.941298 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.467662 | false | false | 2 |
662ccac0badb90d98a8006c1303d9d99f137a8ba | 10,660,108,844,476 | 62104ff488d7c8a64a1e05ef7e931d7acc3e1a59 | /src/de/act/blackbox/applayer/core/CasChecker.java | d22fec07d619420537f3b5d5c1e616b9888416c7 | [] | no_license | gregorylaksono/bb | https://github.com/gregorylaksono/bb | 3c90947175de33d1de530ca7397b5bd47e14e26b | 72b13312ae3e489380c5e9658fde2391b9f82fb3 | refs/heads/master | 2019-04-11T02:31:56.907000 | 2019-02-11T04:26:22 | 2019-02-11T04:26:22 | 91,416,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.act.blackbox.applayer.core;
import de.act.blackbox.dblayer.interfaces.IRuleDao;
import de.act.common.exceptions.MissingParameterException;
import de.act.common.types.CheckRuleParams;
import de.act.common.types.RRRules;
import de.act.common.types.RuleRet;
/**
* Class for checking carriers and geographic constraints together.
*
* @author OB
*/
public class CasChecker implements RuleChecker {
private final IRuleDao ruleDao;
CasChecker(final IRuleDao ruleDao) {
this.ruleDao = ruleDao;
}
/*
* (non-Javadoc)
*
* @see de.act.blackbox.applayer.core.RuleChecker#check(de.act.blackbox.applayer.core.RuleParams,
* de.act.blackbox.applayer.core.CRule, java.util.Date, java.util.Date,
* java.lang.String[], java.lang.String, java.lang.String[],
* java.lang.String, java.lang.String, char, java.lang.String, double)
*/
public RuleRet check(final RuleRet ret, final RRRules rule, final CheckRuleParams chkArgs, final double wgt) {
// handle the trivial (but very common) case first
if (rule.getCaBool() < 0) { return ret; }
final String[] cas = chkArgs.getCas();
final String awbCa = chkArgs.getAwbCa();
boolean bool = rule.getCaBool() > 0 ? true : false;
final boolean lock = rule.getCaLock() > 0 ? true : false;
final char sect = rule.getCaSect();
// check the input
if (sect == 'w' && awbCa == null || sect == 'a' && awbCa == null || sect != 'w' && cas == null) {
final MissingParameterException mpe = new MissingParameterException("The carriers are missing.");
mpe.setCa();
throw mpe;
}
// create and preset the cmps array with good values :-)
final boolean[] cmps = new boolean[cas.length];
boolean awbCmp = false;
// check for carrier rule
if (rule.getCaId() != null) {
final String caId = rule.getCaId();
if (caId.equals("000")) {
if (lock) {
ret.setLock();
}
if (!bool) {
ret.setRet((byte) 0);
}else{
ret.setRet((byte) 1);
}
return ret;
}
if (sect == 'w' || sect == 'a') {
awbCmp = caId.equals(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = caId.equals(cas[i]);
} // for i
}
}
else if (rule.getAllianceId() >= 0) {
final int allId = rule.getAllianceId();
if (sect == 'w' || sect == 'a') {
awbCmp = allId == this.ruleDao.getAlliance(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = allId == this.ruleDao.getAlliance(cas[i]);
} // for i
}
}
else if (rule.getIataStat() != '\0') {
final char iataStat = rule.getIataStat();
if (sect == 'w' || sect == 'a') {
awbCmp = iataStat == this.ruleDao.getIataStatus(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = iataStat == this.ruleDao.getIataStatus(cas[i]);
} // for i
}
}
//
// with the compare results we can now do the real checks
//
boolean check = false;
switch (sect) {
case 'w':
check = awbCmp;
case '\0':
for (final boolean tmp : cmps) {
if (tmp) {
check = true;
break;
}
}
break;
case 'a':
if (awbCmp) {
check = true;
for (boolean tmp : cmps) {
if (!tmp) {
check = false;
break;
}
}
}
break;
case 'f':
if (cmps[0]) {
check = true;
}
break;
case 'l':
if (cmps[cmps.length - 1]) {
check = true;
}
break;
default:
throw new RuntimeException("Unknown section for checking carriers: " + sect);
}
//
// now we have lock, bool and check to make the final decision
//
if (lock) {
if (check) {
ret.setLock();
if (!bool) {
ret.setRet((byte) 0);
}else{
ret.setRet((byte)1);
}
}
}
else {
if (check != bool) {
ret.setRet((byte) 0);
}
if( check && bool){
ret.setRet((byte)1);
}
}
System.out.println();
return ret;
}
} // class CasChecker
| UTF-8 | Java | 3,913 | java | CasChecker.java | Java | [
{
"context": "nd geographic constraints together.\n * \n * @author OB\n */\npublic class CasChecker implements RuleChecker",
"end": 356,
"score": 0.9037095308303833,
"start": 354,
"tag": "USERNAME",
"value": "OB"
}
] | null | [] | package de.act.blackbox.applayer.core;
import de.act.blackbox.dblayer.interfaces.IRuleDao;
import de.act.common.exceptions.MissingParameterException;
import de.act.common.types.CheckRuleParams;
import de.act.common.types.RRRules;
import de.act.common.types.RuleRet;
/**
* Class for checking carriers and geographic constraints together.
*
* @author OB
*/
public class CasChecker implements RuleChecker {
private final IRuleDao ruleDao;
CasChecker(final IRuleDao ruleDao) {
this.ruleDao = ruleDao;
}
/*
* (non-Javadoc)
*
* @see de.act.blackbox.applayer.core.RuleChecker#check(de.act.blackbox.applayer.core.RuleParams,
* de.act.blackbox.applayer.core.CRule, java.util.Date, java.util.Date,
* java.lang.String[], java.lang.String, java.lang.String[],
* java.lang.String, java.lang.String, char, java.lang.String, double)
*/
public RuleRet check(final RuleRet ret, final RRRules rule, final CheckRuleParams chkArgs, final double wgt) {
// handle the trivial (but very common) case first
if (rule.getCaBool() < 0) { return ret; }
final String[] cas = chkArgs.getCas();
final String awbCa = chkArgs.getAwbCa();
boolean bool = rule.getCaBool() > 0 ? true : false;
final boolean lock = rule.getCaLock() > 0 ? true : false;
final char sect = rule.getCaSect();
// check the input
if (sect == 'w' && awbCa == null || sect == 'a' && awbCa == null || sect != 'w' && cas == null) {
final MissingParameterException mpe = new MissingParameterException("The carriers are missing.");
mpe.setCa();
throw mpe;
}
// create and preset the cmps array with good values :-)
final boolean[] cmps = new boolean[cas.length];
boolean awbCmp = false;
// check for carrier rule
if (rule.getCaId() != null) {
final String caId = rule.getCaId();
if (caId.equals("000")) {
if (lock) {
ret.setLock();
}
if (!bool) {
ret.setRet((byte) 0);
}else{
ret.setRet((byte) 1);
}
return ret;
}
if (sect == 'w' || sect == 'a') {
awbCmp = caId.equals(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = caId.equals(cas[i]);
} // for i
}
}
else if (rule.getAllianceId() >= 0) {
final int allId = rule.getAllianceId();
if (sect == 'w' || sect == 'a') {
awbCmp = allId == this.ruleDao.getAlliance(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = allId == this.ruleDao.getAlliance(cas[i]);
} // for i
}
}
else if (rule.getIataStat() != '\0') {
final char iataStat = rule.getIataStat();
if (sect == 'w' || sect == 'a') {
awbCmp = iataStat == this.ruleDao.getIataStatus(awbCa);
}
if (sect != 'w') {
for (int i = 0; i < cas.length; i++) {
cmps[i] = iataStat == this.ruleDao.getIataStatus(cas[i]);
} // for i
}
}
//
// with the compare results we can now do the real checks
//
boolean check = false;
switch (sect) {
case 'w':
check = awbCmp;
case '\0':
for (final boolean tmp : cmps) {
if (tmp) {
check = true;
break;
}
}
break;
case 'a':
if (awbCmp) {
check = true;
for (boolean tmp : cmps) {
if (!tmp) {
check = false;
break;
}
}
}
break;
case 'f':
if (cmps[0]) {
check = true;
}
break;
case 'l':
if (cmps[cmps.length - 1]) {
check = true;
}
break;
default:
throw new RuntimeException("Unknown section for checking carriers: " + sect);
}
//
// now we have lock, bool and check to make the final decision
//
if (lock) {
if (check) {
ret.setLock();
if (!bool) {
ret.setRet((byte) 0);
}else{
ret.setRet((byte)1);
}
}
}
else {
if (check != bool) {
ret.setRet((byte) 0);
}
if( check && bool){
ret.setRet((byte)1);
}
}
System.out.println();
return ret;
}
} // class CasChecker
| 3,913 | 0.588807 | 0.583695 | 155 | 24.245161 | 22.72794 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.154839 | false | false | 2 |
da61d0c572ba859da8ab05d053cdabde7d07c47c | 4,647,154,632,171 | 6d3057a22e8a9de9c395fded12dc088f97f7603f | /src/main/java/winber/Final/persistent/web/TestSpringDataRedisController.java | 16e763670c227b15c92d8eb5b50c3b224dde2dea | [] | no_license | hanchao-c/Final | https://github.com/hanchao-c/Final | b672361b8ea7aead9b17102f568231f40fa47c5c | e743ee6603e020874a7d57a6865a6daec78d25df | refs/heads/master | 2018-01-01T14:19:17.537000 | 2017-04-18T03:57:53 | 2017-04-18T03:57:53 | 71,879,195 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package winber.Final.persistent.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import winber.Final.persistent.service.ITestSpringDataRedisService;
@RestController
@RequestMapping("/springDataRedis")
public class TestSpringDataRedisController {
@Autowired
private ITestSpringDataRedisService testSpringDataRedisService;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testSpringDataRedis() {
testSpringDataRedisService.testSpringDataRedis();
return Message.SUCCESS;
}
}
| UTF-8 | Java | 741 | java | TestSpringDataRedisController.java | Java | [] | null | [] | package winber.Final.persistent.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import winber.Final.persistent.service.ITestSpringDataRedisService;
@RestController
@RequestMapping("/springDataRedis")
public class TestSpringDataRedisController {
@Autowired
private ITestSpringDataRedisService testSpringDataRedisService;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testSpringDataRedis() {
testSpringDataRedisService.testSpringDataRedis();
return Message.SUCCESS;
}
}
| 741 | 0.815115 | 0.815115 | 22 | 31.681818 | 26.072254 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863636 | false | false | 2 |
07a4dcd3c69af27aed4dac47a56bf426324ee778 | 962,072,699,324 | 19d1fcb66dffda21a250a82bf31406508a5e9dcb | /ui-automation-framework/test-event-bus/src/test/java/com/ui/automation/app/eventBus/TestEventListener.java | 2b92877bffe99fa29e3657f4af66fde533c81efe | [] | no_license | hananmalka/UIAutoationFramework | https://github.com/hananmalka/UIAutoationFramework | 1dce7aa572e63efcd279325888571aec08d3d757 | 8cd220e447f09c83b6e55dc41bf5d13175398c89 | refs/heads/master | 2020-06-23T08:38:45.497000 | 2016-11-02T20:50:34 | 2016-11-02T20:50:34 | 198,573,191 | 0 | 0 | null | true | 2019-07-24T06:33:10 | 2019-07-24T06:33:10 | 2016-11-02T20:51:47 | 2016-11-02T20:51:43 | 203 | 0 | 0 | 0 | null | false | false | package com.ui.automation.app.eventBus;
/**
* Created with IntelliJ IDEA.
* User: coheney
* Date: 13/03/14
* Time: 16:56
* To change this template use File | Settings | File Templates.
*/
public interface TestEventListener {
void beforeEvent(TestEvent event);
void afterEvent(TestEvent event);
}
| UTF-8 | Java | 311 | java | TestEventListener.java | Java | [
{
"context": "tBus;\n\n/**\n * Created with IntelliJ IDEA.\n * User: coheney\n * Date: 13/03/14\n * Time: 16:56\n * To change thi",
"end": 92,
"score": 0.999474823474884,
"start": 85,
"tag": "USERNAME",
"value": "coheney"
}
] | null | [] | package com.ui.automation.app.eventBus;
/**
* Created with IntelliJ IDEA.
* User: coheney
* Date: 13/03/14
* Time: 16:56
* To change this template use File | Settings | File Templates.
*/
public interface TestEventListener {
void beforeEvent(TestEvent event);
void afterEvent(TestEvent event);
}
| 311 | 0.713826 | 0.681672 | 13 | 22.923077 | 18.718405 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 2 |
e31419085b72d382886fa80ddd7ac5a6d8f8b139 | 7,928,509,681,116 | b625158259d9db671ed84bd1c11685caaa8b1443 | /src/main/java/com/test/movierent/dao/MovieDao.java | e2fd84e39a9a56ad98bf269c405ea310133eb175 | [] | no_license | rodrigohernandezdev/movie-rent | https://github.com/rodrigohernandezdev/movie-rent | fe2454bfa2959ca5101d7273f95a3f79e7c892c3 | 29f0ac3a530f6451904ea8153671d67a7b0c851a | refs/heads/master | 2023-01-23T03:27:57.853000 | 2020-11-27T20:51:58 | 2020-11-27T20:51:58 | 316,130,585 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.movierent.dao;
import com.test.movierent.model.Movie;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
@Repository(value = "movieDao")
public interface MovieDao extends JpaRepository<Movie, Long> {
@NonNull
Page<Movie> findAll(@NonNull Pageable pageable);
Page<Movie> findAllByAvailability(Boolean availability, Pageable pageable);
Movie findByTittle(String tittle);
}
| UTF-8 | Java | 607 | java | MovieDao.java | Java | [] | null | [] | package com.test.movierent.dao;
import com.test.movierent.model.Movie;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
@Repository(value = "movieDao")
public interface MovieDao extends JpaRepository<Movie, Long> {
@NonNull
Page<Movie> findAll(@NonNull Pageable pageable);
Page<Movie> findAllByAvailability(Boolean availability, Pageable pageable);
Movie findByTittle(String tittle);
}
| 607 | 0.800659 | 0.800659 | 21 | 27.904762 | 25.216972 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
9adc2a2a34160504ab60d2e7dc6ff28caa9af89a | 33,621,004,046,655 | fbea9ad8fbd82e02089303dbb1ff016bf06b92bb | /src/edu/uoc/videojocs/core/ParallaxLayer.java | afb66ddf4743df5540ae73d478d072c187c73016 | [] | no_license | bromagosa/staruocs-submarine | https://github.com/bromagosa/staruocs-submarine | ff6a9d4ba500bfb34fc8f458b43026a84056e422 | c543e29fbabcd19ee7a33ee63f6c1347a5ed716b | refs/heads/master | 2015-08-11T02:03:23.598000 | 2014-05-03T18:10:38 | 2014-05-03T18:10:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.uoc.videojocs.core;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by heltena on 3/26/14.
*/
public class ParallaxLayer {
private float width;
private float height;
private float zValue;
private float blockWidth;
private float blockHeight;
private int rows;
private int cols;
private List<ParallaxLayerBlock> blocks;
public ParallaxLayer(float width, float height, float zValue, float blockWidth, float blockHeight) {
this.width = width;
this.height = height;
this.zValue = zValue;
this.blockWidth = blockWidth;
this.blockHeight = blockHeight;
this.blocks = new ArrayList<ParallaxLayerBlock>();
this.rows = (int)(width / blockWidth) + 1;
this.cols = (int)(height / blockHeight) + 1;
for (int j = 0; j < cols; j++)
for (int i = 0; i < rows; i++)
blocks.add(new ParallaxLayerBlock(i, j));
}
public void addSprite(RectangleMesh mesh, float x, float y) {
int row = (int) (x / blockWidth);
int col = (int) (y / blockHeight);
blocks.get(col + row * cols).addMesh(mesh, x, y);
}
public void draw(GL10 gl, float percentageX, float percentageY) {
gl.glPushMatrix();
gl.glTranslatef(- width * (percentageX + 0.5f), - height * (percentageY + 0.5f), zValue * 0.01f);
for (ParallaxLayerBlock block: blocks)
block.draw(gl);
gl.glPopMatrix();
}
} | UTF-8 | Java | 1,545 | java | ParallaxLayer.java | Java | [
{
"context": "oedition.khronos.opengles.GL10;\n\n/**\n * Created by heltena on 3/26/14.\n */\npublic class ParallaxLayer {\n\n ",
"end": 160,
"score": 0.999671995639801,
"start": 153,
"tag": "USERNAME",
"value": "heltena"
}
] | null | [] | package edu.uoc.videojocs.core;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by heltena on 3/26/14.
*/
public class ParallaxLayer {
private float width;
private float height;
private float zValue;
private float blockWidth;
private float blockHeight;
private int rows;
private int cols;
private List<ParallaxLayerBlock> blocks;
public ParallaxLayer(float width, float height, float zValue, float blockWidth, float blockHeight) {
this.width = width;
this.height = height;
this.zValue = zValue;
this.blockWidth = blockWidth;
this.blockHeight = blockHeight;
this.blocks = new ArrayList<ParallaxLayerBlock>();
this.rows = (int)(width / blockWidth) + 1;
this.cols = (int)(height / blockHeight) + 1;
for (int j = 0; j < cols; j++)
for (int i = 0; i < rows; i++)
blocks.add(new ParallaxLayerBlock(i, j));
}
public void addSprite(RectangleMesh mesh, float x, float y) {
int row = (int) (x / blockWidth);
int col = (int) (y / blockHeight);
blocks.get(col + row * cols).addMesh(mesh, x, y);
}
public void draw(GL10 gl, float percentageX, float percentageY) {
gl.glPushMatrix();
gl.glTranslatef(- width * (percentageX + 0.5f), - height * (percentageY + 0.5f), zValue * 0.01f);
for (ParallaxLayerBlock block: blocks)
block.draw(gl);
gl.glPopMatrix();
}
} | 1,545 | 0.619417 | 0.606472 | 51 | 29.313726 | 24.65407 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.882353 | false | false | 2 |
7c8d4173e6f8c246641aa33d30bcb9e2c16c2aa4 | 35,596,688,958,749 | bdcdcf52c63a1037786ac97fbb4da88a0682e0e8 | /src/test/java/io/akeyless/client/model/GatewayUpdateProducerNativeK8STest.java | 8eda2f5dd34b800300f321456c4ba16a1f1a8502 | [
"Apache-2.0"
] | permissive | akeylesslabs/akeyless-java | https://github.com/akeylesslabs/akeyless-java | 6e37d9ec59d734f9b14e475ce0fa3e4a48fc99ea | cfb00a0e2e90ffc5c375b62297ec64373892097b | refs/heads/master | 2023-08-03T15:06:06.802000 | 2023-07-30T11:59:23 | 2023-07-30T11:59:23 | 341,514,151 | 2 | 4 | Apache-2.0 | false | 2023-07-11T08:57:17 | 2021-02-23T10:22:38 | 2023-07-10T07:58:34 | 2023-07-11T08:57:15 | 3,756 | 3 | 2 | 5 | Java | false | false | /*
* Akeyless API
* The purpose of this application is to provide access to Akeyless API.
*
* The version of the OpenAPI document: 2.0
* Contact: support@akeyless.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.akeyless.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for GatewayUpdateProducerNativeK8S
*/
public class GatewayUpdateProducerNativeK8STest {
private final GatewayUpdateProducerNativeK8S model = new GatewayUpdateProducerNativeK8S();
/**
* Model tests for GatewayUpdateProducerNativeK8S
*/
@Test
public void testGatewayUpdateProducerNativeK8S() {
// TODO: test GatewayUpdateProducerNativeK8S
}
/**
* Test the property 'k8sClusterCaCert'
*/
@Test
public void k8sClusterCaCertTest() {
// TODO: test k8sClusterCaCert
}
/**
* Test the property 'k8sClusterEndpoint'
*/
@Test
public void k8sClusterEndpointTest() {
// TODO: test k8sClusterEndpoint
}
/**
* Test the property 'k8sClusterToken'
*/
@Test
public void k8sClusterTokenTest() {
// TODO: test k8sClusterToken
}
/**
* Test the property 'k8sNamespace'
*/
@Test
public void k8sNamespaceTest() {
// TODO: test k8sNamespace
}
/**
* Test the property 'k8sServiceAccount'
*/
@Test
public void k8sServiceAccountTest() {
// TODO: test k8sServiceAccount
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
/**
* Test the property 'newName'
*/
@Test
public void newNameTest() {
// TODO: test newName
}
/**
* Test the property 'password'
*/
@Test
public void passwordTest() {
// TODO: test password
}
/**
* Test the property 'producerEncryptionKeyName'
*/
@Test
public void producerEncryptionKeyNameTest() {
// TODO: test producerEncryptionKeyName
}
/**
* Test the property 'secureAccessAllowPortForwading'
*/
@Test
public void secureAccessAllowPortForwadingTest() {
// TODO: test secureAccessAllowPortForwading
}
/**
* Test the property 'secureAccessBastionIssuer'
*/
@Test
public void secureAccessBastionIssuerTest() {
// TODO: test secureAccessBastionIssuer
}
/**
* Test the property 'secureAccessClusterEndpoint'
*/
@Test
public void secureAccessClusterEndpointTest() {
// TODO: test secureAccessClusterEndpoint
}
/**
* Test the property 'secureAccessDashboardUrl'
*/
@Test
public void secureAccessDashboardUrlTest() {
// TODO: test secureAccessDashboardUrl
}
/**
* Test the property 'secureAccessEnable'
*/
@Test
public void secureAccessEnableTest() {
// TODO: test secureAccessEnable
}
/**
* Test the property 'secureAccessWeb'
*/
@Test
public void secureAccessWebTest() {
// TODO: test secureAccessWeb
}
/**
* Test the property 'secureAccessWebBrowsing'
*/
@Test
public void secureAccessWebBrowsingTest() {
// TODO: test secureAccessWebBrowsing
}
/**
* Test the property 'tags'
*/
@Test
public void tagsTest() {
// TODO: test tags
}
/**
* Test the property 'targetName'
*/
@Test
public void targetNameTest() {
// TODO: test targetName
}
/**
* Test the property 'token'
*/
@Test
public void tokenTest() {
// TODO: test token
}
/**
* Test the property 'uidToken'
*/
@Test
public void uidTokenTest() {
// TODO: test uidToken
}
/**
* Test the property 'userTtl'
*/
@Test
public void userTtlTest() {
// TODO: test userTtl
}
/**
* Test the property 'username'
*/
@Test
public void usernameTest() {
// TODO: test username
}
}
| UTF-8 | Java | 4,615 | java | GatewayUpdateProducerNativeK8STest.java | Java | [
{
"context": "e version of the OpenAPI document: 2.0\n * Contact: support@akeyless.io\n *\n * NOTE: This class is auto generated by OpenA",
"end": 170,
"score": 0.9999247193336487,
"start": 151,
"tag": "EMAIL",
"value": "support@akeyless.io"
}
] | null | [] | /*
* Akeyless API
* The purpose of this application is to provide access to Akeyless API.
*
* The version of the OpenAPI document: 2.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.akeyless.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for GatewayUpdateProducerNativeK8S
*/
public class GatewayUpdateProducerNativeK8STest {
private final GatewayUpdateProducerNativeK8S model = new GatewayUpdateProducerNativeK8S();
/**
* Model tests for GatewayUpdateProducerNativeK8S
*/
@Test
public void testGatewayUpdateProducerNativeK8S() {
// TODO: test GatewayUpdateProducerNativeK8S
}
/**
* Test the property 'k8sClusterCaCert'
*/
@Test
public void k8sClusterCaCertTest() {
// TODO: test k8sClusterCaCert
}
/**
* Test the property 'k8sClusterEndpoint'
*/
@Test
public void k8sClusterEndpointTest() {
// TODO: test k8sClusterEndpoint
}
/**
* Test the property 'k8sClusterToken'
*/
@Test
public void k8sClusterTokenTest() {
// TODO: test k8sClusterToken
}
/**
* Test the property 'k8sNamespace'
*/
@Test
public void k8sNamespaceTest() {
// TODO: test k8sNamespace
}
/**
* Test the property 'k8sServiceAccount'
*/
@Test
public void k8sServiceAccountTest() {
// TODO: test k8sServiceAccount
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
/**
* Test the property 'newName'
*/
@Test
public void newNameTest() {
// TODO: test newName
}
/**
* Test the property 'password'
*/
@Test
public void passwordTest() {
// TODO: test password
}
/**
* Test the property 'producerEncryptionKeyName'
*/
@Test
public void producerEncryptionKeyNameTest() {
// TODO: test producerEncryptionKeyName
}
/**
* Test the property 'secureAccessAllowPortForwading'
*/
@Test
public void secureAccessAllowPortForwadingTest() {
// TODO: test secureAccessAllowPortForwading
}
/**
* Test the property 'secureAccessBastionIssuer'
*/
@Test
public void secureAccessBastionIssuerTest() {
// TODO: test secureAccessBastionIssuer
}
/**
* Test the property 'secureAccessClusterEndpoint'
*/
@Test
public void secureAccessClusterEndpointTest() {
// TODO: test secureAccessClusterEndpoint
}
/**
* Test the property 'secureAccessDashboardUrl'
*/
@Test
public void secureAccessDashboardUrlTest() {
// TODO: test secureAccessDashboardUrl
}
/**
* Test the property 'secureAccessEnable'
*/
@Test
public void secureAccessEnableTest() {
// TODO: test secureAccessEnable
}
/**
* Test the property 'secureAccessWeb'
*/
@Test
public void secureAccessWebTest() {
// TODO: test secureAccessWeb
}
/**
* Test the property 'secureAccessWebBrowsing'
*/
@Test
public void secureAccessWebBrowsingTest() {
// TODO: test secureAccessWebBrowsing
}
/**
* Test the property 'tags'
*/
@Test
public void tagsTest() {
// TODO: test tags
}
/**
* Test the property 'targetName'
*/
@Test
public void targetNameTest() {
// TODO: test targetName
}
/**
* Test the property 'token'
*/
@Test
public void tokenTest() {
// TODO: test token
}
/**
* Test the property 'uidToken'
*/
@Test
public void uidTokenTest() {
// TODO: test uidToken
}
/**
* Test the property 'userTtl'
*/
@Test
public void userTtlTest() {
// TODO: test userTtl
}
/**
* Test the property 'username'
*/
@Test
public void usernameTest() {
// TODO: test username
}
}
| 4,603 | 0.613868 | 0.608667 | 221 | 19.882353 | 19.223022 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.067873 | false | false | 2 |
736a6308b6576ac9935f2207947e3a81327c93ac | 764,504,246,707 | 8d0233c39b553a36d749f7e5acef0019402d241c | /app/src/main/java/com/example/netcallback/ui/fragment/Fragment2.java | 902cecaffa445b3b2eb5fd981058d7d86ff045fb | [] | no_license | surpreme/stust | https://github.com/surpreme/stust | 8cbc8bd29f3847ff3aaab5ad63a68eb0b5d44b67 | d43df5137227e329edf4e2ac07d0cde3680de485 | refs/heads/master | 2020-07-31T06:12:19.494000 | 2019-09-24T04:44:53 | 2019-09-24T04:44:53 | 210,511,839 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.netcallback.ui.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.netcallback.R;
import com.example.netcallback.struct.FunctionManager;
public class Fragment2 extends BaseFragment{
public static final String INSTERFACE_RESULT=Fragment2.class.getName()+"withResult";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment2,container,false);
Button button= view.findViewById(R.id.frg2btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mFunctionManager == null) {
mFunctionManager = FunctionManager.getInstance();
}
String s=mFunctionManager.invokeFunction(INSTERFACE_RESULT,String.class);
Toast.makeText(getContext(),"Fragment*来自activity"+s,Toast.LENGTH_LONG).show();
}
});
return view;
}
}
| UTF-8 | Java | 1,321 | java | Fragment2.java | Java | [] | null | [] | package com.example.netcallback.ui.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.netcallback.R;
import com.example.netcallback.struct.FunctionManager;
public class Fragment2 extends BaseFragment{
public static final String INSTERFACE_RESULT=Fragment2.class.getName()+"withResult";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment2,container,false);
Button button= view.findViewById(R.id.frg2btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mFunctionManager == null) {
mFunctionManager = FunctionManager.getInstance();
}
String s=mFunctionManager.invokeFunction(INSTERFACE_RESULT,String.class);
Toast.makeText(getContext(),"Fragment*来自activity"+s,Toast.LENGTH_LONG).show();
}
});
return view;
}
}
| 1,321 | 0.702354 | 0.699317 | 37 | 34.594593 | 30.92577 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.702703 | false | false | 2 |
b1b73ac8a5af4b022754e790c6ebcd489a5237c0 | 9,414,568,377,872 | 2c08990d21485aca44e02596b5ec8998e67d6856 | /ChessEasierV1Skeletonised/src/test/piece/PieceTest_7_BlackPawn.java | 4cb117c60e6b5cf763befc2469c445ebf45db138 | [] | no_license | runlevelzero/TestAssignment | https://github.com/runlevelzero/TestAssignment | 59af2a3d2a37c4cf180599d1558c9c21ea60096e | 2970732c21bcf5a3851e75c51a303adb2a13bbfe | refs/heads/master | 2022-07-18T06:54:17.012000 | 2020-05-15T20:49:33 | 2020-05-15T20:49:33 | 264,251,124 | 0 | 0 | null | true | 2020-05-15T17:01:45 | 2020-05-15T17:01:44 | 2020-05-15T17:01:02 | 2020-05-15T17:00:59 | 135 | 0 | 0 | 0 | null | false | false | package test.piece;
import chess.GridPosition;
import chess.Player;
import chess.piece.Piece;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertArrayEquals;
/**
@author Jeffrey Ng
@created 2020-05-13 */
public class PieceTest_7_BlackPawn extends PieceTest_6_WhitePawn {
@Override
protected Piece getPieceFromTestName(String testName) throws ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
String classNameAux = testName.length() < 10 ? testName.substring(0, testName.length() - 2) :
testName.substring(5, testName.length() - 2);
char title = classNameAux.toUpperCase().charAt(0);
String restOfTheClassName = classNameAux.substring(1);
StringBuilder sb = new StringBuilder();
String className = sb.append(title).append(restOfTheClassName).toString();
Class<?> clazz = Class.forName(String.format("chess.piece.%s", className));
Constructor<?> constructor = clazz.getConstructor(Player.class);
return testName.length() < 10 ? (Piece) constructor.newInstance(Player.WHITE) :
(Piece) constructor.newInstance(Player.BLACK);
}
@Test
public void blackPawnA7() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {1, 1, 0, 0, 0, 0, 0, 0,},
new int[] {1, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
@Test
public void blackPawnA5() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {1, 1, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
@Test
public void blackPawnC1() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
}
| UTF-8 | Java | 4,311 | java | PieceTest_7_BlackPawn.java | Java | [
{
"context": " org.junit.Assert.assertArrayEquals;\n\n/**\n @author Jeffrey Ng\n @created 2020-05-13 */\npublic class PieceTest_7_",
"end": 284,
"score": 0.9991027116775513,
"start": 274,
"tag": "NAME",
"value": "Jeffrey Ng"
}
] | null | [] | package test.piece;
import chess.GridPosition;
import chess.Player;
import chess.piece.Piece;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertArrayEquals;
/**
@author <NAME>
@created 2020-05-13 */
public class PieceTest_7_BlackPawn extends PieceTest_6_WhitePawn {
@Override
protected Piece getPieceFromTestName(String testName) throws ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
String classNameAux = testName.length() < 10 ? testName.substring(0, testName.length() - 2) :
testName.substring(5, testName.length() - 2);
char title = classNameAux.toUpperCase().charAt(0);
String restOfTheClassName = classNameAux.substring(1);
StringBuilder sb = new StringBuilder();
String className = sb.append(title).append(restOfTheClassName).toString();
Class<?> clazz = Class.forName(String.format("chess.piece.%s", className));
Constructor<?> constructor = clazz.getConstructor(Player.class);
return testName.length() < 10 ? (Piece) constructor.newInstance(Player.WHITE) :
(Piece) constructor.newInstance(Player.BLACK);
}
@Test
public void blackPawnA7() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {1, 1, 0, 0, 0, 0, 0, 0,},
new int[] {1, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
@Test
public void blackPawnA5() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {1, 1, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
@Test
public void blackPawnC1() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
String testName = Thread.currentThread().getStackTrace()[1].getMethodName();
GridPosition gp = extractGridPositionFromTestName(testName);
Piece p = getPieceFromTestName(testName);
int[][] actual = p.getEndpointListFromCurrentPosition(gp);
int[][] expected = new int[][] {
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
new int[] {0, 0, 0, 0, 0, 0, 0, 0,},
};
assertArrayEquals(expected, actual);
}
}
| 4,307 | 0.566922 | 0.516353 | 99 | 42.545456 | 30.08247 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.747475 | false | false | 2 |
29183b6061d1b2e18d57d55be751f6ac1e377e92 | 11,252,814,364,192 | d00af6c547e629983ff777abe35fc9c36b3b2371 | /jboss-all/cluster/src/main/org/jbossmx/cluster/watchdog/mbean/watchdog/CorrectiveAction.java | b93434f3930b08a769dc53e3ed9f6f7d9062d74c | [] | no_license | aosm/JBoss | https://github.com/aosm/JBoss | e4afad3e0d6a50685a55a45209e99e7a92f974ea | 75a042bd25dd995392f3dbc05ddf4bbf9bdc8cd7 | refs/heads/master | 2023-07-08T21:50:23.795000 | 2013-03-20T07:43:51 | 2013-03-20T07:43:51 | 8,898,416 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license Version 2.1, February 1999.
* See terms of license at gnu.org.
*/
package org.jbossmx.cluster.watchdog.mbean.watchdog;
// Standard Java Packages
import java.util.Set;
/**
* Interface for corrective actions to take on MBeans
*/
public interface CorrectiveAction
extends Cloneable
{
/**
* Returns whether this CorrectiveAction can be applied.
*
* @return whether this CorrectiveAction can be applied.
*/
public boolean canApply();
/**
* Apply this CorrectiveAction.
*
* @return whether the corrective action succeeded.
* @throws Exception
*/
public boolean apply() throws Exception;
/**
* Determine if <code>correctiveAction</code> overides this one.
*
* @param correctiveActions the CorrectiveAction to compare with this one.
*
* @return whether <code>correctiveAction</code> overides this one.
*/
public boolean isOverridenBy(final CorrectiveAction correctiveAction);
/**
* Determine if any of the CorrectiveActions in <code>correctiveActions</code> overides this one.
*
* @param correctiveActions the Set of CorrectiveActions to compare with this one.
*
* @return true if any of the CorrectiveActions in <code>correctiveActions</code> overides this one.
*/
public boolean isOverridenBy(final Set correctiveActions);
/**
* Sets the CorrectiveActionContext of this CorrectiveAction
*
* @param correctiveActionContext the CorrectiveActionContext that this Corrective should use.
*
* @return this
*/
public CorrectiveAction setCorrectiveActionContext(CorrectiveActionContext correctiveActionContext);
/**
* Returns the CorrectiveActionContext of this CorrectiveAction
*
* @return the CorrectiveActionContext of this CorrectiveAction
*/
public CorrectiveActionContext getCorrectiveActionContext();
/**
* Sets the number of times this CorrectiveAction can be applied
*
* @param numberOfTimesToApply
*
* @return this
*/
public CorrectiveAction setNumberOfTimesToApply(final int numberOfTimesToApply);
/**
* Get the total number of times this CorrectiveAction can be applied.
*
* @return the total number of times this CorrectiveAction can be applied.
*/
public int getNumberOfTimesToApply();
}
/*
Example uses of Corrective Actions
<mbean code="org.jbossmx.cluster.watchdog.mbean.Watchdog"
archive="flibble.jar"
codebase="flobble/bobble">
<parameter name="frog" value="lizard"/>
<method name="addCorrectiveAction">
// Constructor params
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.InvokeMethodCorrectiveAction">
<param class="java.lang.Object[]">
<param class="java.lang.String">restartMBean</param>
<param class="java.lang.Object[]"/>
<param class="java.lang.String[]"/>
<param class="java.lang.Object">
<param class="Boolean">true</param>
</param>
</param>
</param>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">4</param>
</method>
<method name="addCorrectiveAction">
// Constructor Parameters for above CorrectiveAction
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.RestartAgentCorrectiveAction"/>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">4</param>
</method>
<method name="addCorrectiveAction">
// Constructor Parameters for above CorrectiveAction
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.CallScriptCorrectiveAction">
<param class="java.lang.Object[]">
<param class="java.lang.String">/apps/hermes/bin/restartMachine</param>
<param class="java.lang.Long">30000</param>
</param>
</param>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">
4
</param>
</method>
</mbean>
//*/
| UTF-8 | Java | 4,139 | java | CorrectiveAction.java | Java | [
{
"context": "lobble/bobble\">\n <parameter name=\"frog\" value=\"lizard\"/>\n <method name=\"addCorrectiveAction\">\n ",
"end": 2667,
"score": 0.8357031941413879,
"start": 2661,
"tag": "NAME",
"value": "lizard"
}
] | null | [] | /**
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license Version 2.1, February 1999.
* See terms of license at gnu.org.
*/
package org.jbossmx.cluster.watchdog.mbean.watchdog;
// Standard Java Packages
import java.util.Set;
/**
* Interface for corrective actions to take on MBeans
*/
public interface CorrectiveAction
extends Cloneable
{
/**
* Returns whether this CorrectiveAction can be applied.
*
* @return whether this CorrectiveAction can be applied.
*/
public boolean canApply();
/**
* Apply this CorrectiveAction.
*
* @return whether the corrective action succeeded.
* @throws Exception
*/
public boolean apply() throws Exception;
/**
* Determine if <code>correctiveAction</code> overides this one.
*
* @param correctiveActions the CorrectiveAction to compare with this one.
*
* @return whether <code>correctiveAction</code> overides this one.
*/
public boolean isOverridenBy(final CorrectiveAction correctiveAction);
/**
* Determine if any of the CorrectiveActions in <code>correctiveActions</code> overides this one.
*
* @param correctiveActions the Set of CorrectiveActions to compare with this one.
*
* @return true if any of the CorrectiveActions in <code>correctiveActions</code> overides this one.
*/
public boolean isOverridenBy(final Set correctiveActions);
/**
* Sets the CorrectiveActionContext of this CorrectiveAction
*
* @param correctiveActionContext the CorrectiveActionContext that this Corrective should use.
*
* @return this
*/
public CorrectiveAction setCorrectiveActionContext(CorrectiveActionContext correctiveActionContext);
/**
* Returns the CorrectiveActionContext of this CorrectiveAction
*
* @return the CorrectiveActionContext of this CorrectiveAction
*/
public CorrectiveActionContext getCorrectiveActionContext();
/**
* Sets the number of times this CorrectiveAction can be applied
*
* @param numberOfTimesToApply
*
* @return this
*/
public CorrectiveAction setNumberOfTimesToApply(final int numberOfTimesToApply);
/**
* Get the total number of times this CorrectiveAction can be applied.
*
* @return the total number of times this CorrectiveAction can be applied.
*/
public int getNumberOfTimesToApply();
}
/*
Example uses of Corrective Actions
<mbean code="org.jbossmx.cluster.watchdog.mbean.Watchdog"
archive="flibble.jar"
codebase="flobble/bobble">
<parameter name="frog" value="lizard"/>
<method name="addCorrectiveAction">
// Constructor params
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.InvokeMethodCorrectiveAction">
<param class="java.lang.Object[]">
<param class="java.lang.String">restartMBean</param>
<param class="java.lang.Object[]"/>
<param class="java.lang.String[]"/>
<param class="java.lang.Object">
<param class="Boolean">true</param>
</param>
</param>
</param>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">4</param>
</method>
<method name="addCorrectiveAction">
// Constructor Parameters for above CorrectiveAction
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.RestartAgentCorrectiveAction"/>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">4</param>
</method>
<method name="addCorrectiveAction">
// Constructor Parameters for above CorrectiveAction
<param class="org.jbossmx.cluster.watchdog.mbean.watchdog.CallScriptCorrectiveAction">
<param class="java.lang.Object[]">
<param class="java.lang.String">/apps/hermes/bin/restartMachine</param>
<param class="java.lang.Long">30000</param>
</param>
</param>
// Number of times to use CorrectiveAction
<param class="java.lang.Integer">
4
</param>
</method>
</mbean>
//*/
| 4,139 | 0.674076 | 0.670693 | 128 | 31.335938 | 29.450243 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.09375 | false | false | 2 |
8157407db20852c3400aa5b818189a5433329012 | 15,633,681,010,820 | cadf4786b1cd2881ba700ca5ce767e45cae51ffd | /fgc-manager/fgc-manager-service/src/main/java/com/fgc/service/receipt/impl/rule/BeforeReceiptSaveRule.java | 03e5d097ea0cbe83ec3369c7577640fbd86ed4a3 | [] | no_license | cshhappyboy/wljt_other | https://github.com/cshhappyboy/wljt_other | fe31d720b3b1539cddbe92ca12d10a81228b80d9 | 1d97aad4af7351918bda95580b8dbe9708586ce3 | refs/heads/master | 2020-04-02T03:34:20.510000 | 2018-08-15T01:52:25 | 2018-08-15T01:52:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fgc.service.receipt.impl.rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fgc.pojo.ReceiptHVO;
import com.fgc.service.billcode.IBillCodeService;
import com.fgc.service.pub.IPubInfoService;
import com.pub.rule.ISRule;
import com.pub.utils.MMStringUtil;
import com.pub.utils.MMValueUtils;
/**
* 保存前规则
*
* @开发者 ^_^ 张佳宾 *_*<br>
*
* @时间 2018年1月29日
*
* 未来离线需求
*/
@Component
public class BeforeReceiptSaveRule implements ISRule<ReceiptHVO> {
@Autowired
private IBillCodeService billCodeService;
@Autowired
private IPubInfoService pubInfoService;
@Override
public void process(ReceiptHVO hvo) throws Exception {
if (MMValueUtils.isNotEmpty(hvo)) {
// 设置集团组织
this.setDefaultValue(hvo);
// 生成有效订单号
this.generateEffectBillCode(hvo);
}
}
/**
* @param hvo
* @throws Exception
*/
private void generateEffectBillCode(ReceiptHVO hvo) throws Exception {
String effectbillcode = hvo.getEffectbillcode();
if (MMStringUtil.isEmpty(effectbillcode)) {
String generateEffectBillCode = billCodeService.generateEffectBillCode(hvo.getCdept());
hvo.setEffectbillcode(generateEffectBillCode);
}
}
/**
* @param hvo
* @throws
*/
private void setDefaultValue(ReceiptHVO hvo) {
hvo.setPkGroup(pubInfoService.getPk_group());
hvo.setPkOrg(pubInfoService.getPk_org());
}
}
| UTF-8 | Java | 1,544 | java | BeforeReceiptSaveRule.java | Java | [
{
"context": ".MMValueUtils;\r\n\r\n/**\r\n * 保存前规则\r\n * \r\n * @开发者 ^_^ 张佳宾 *_*<br>\r\n *\r\n * @时间 2018年1月29日\r\n *\r\n * 未来离线需求",
"end": 429,
"score": 0.9914165735244751,
"start": 426,
"tag": "NAME",
"value": "张佳宾"
}
] | null | [] | package com.fgc.service.receipt.impl.rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fgc.pojo.ReceiptHVO;
import com.fgc.service.billcode.IBillCodeService;
import com.fgc.service.pub.IPubInfoService;
import com.pub.rule.ISRule;
import com.pub.utils.MMStringUtil;
import com.pub.utils.MMValueUtils;
/**
* 保存前规则
*
* @开发者 ^_^ 张佳宾 *_*<br>
*
* @时间 2018年1月29日
*
* 未来离线需求
*/
@Component
public class BeforeReceiptSaveRule implements ISRule<ReceiptHVO> {
@Autowired
private IBillCodeService billCodeService;
@Autowired
private IPubInfoService pubInfoService;
@Override
public void process(ReceiptHVO hvo) throws Exception {
if (MMValueUtils.isNotEmpty(hvo)) {
// 设置集团组织
this.setDefaultValue(hvo);
// 生成有效订单号
this.generateEffectBillCode(hvo);
}
}
/**
* @param hvo
* @throws Exception
*/
private void generateEffectBillCode(ReceiptHVO hvo) throws Exception {
String effectbillcode = hvo.getEffectbillcode();
if (MMStringUtil.isEmpty(effectbillcode)) {
String generateEffectBillCode = billCodeService.generateEffectBillCode(hvo.getCdept());
hvo.setEffectbillcode(generateEffectBillCode);
}
}
/**
* @param hvo
* @throws
*/
private void setDefaultValue(ReceiptHVO hvo) {
hvo.setPkGroup(pubInfoService.getPk_group());
hvo.setPkOrg(pubInfoService.getPk_org());
}
}
| 1,544 | 0.714383 | 0.709634 | 62 | 21.774193 | 22.113649 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.16129 | false | false | 2 |
c9c6c28cce11a53cea1de6af31dd962a931ad22e | 12,713,103,258,519 | e775e660d0f68c7e51d93c6888689ccb39d1f1db | /JAVA/prj_jee/ProjectJ2EE_104/src/users_accounts/Account.java | 94c6ca28edeb216207006e84b02b49a6cbdb757b | [] | no_license | genose/progmatic_things | https://github.com/genose/progmatic_things | 5b95f7e90dbe5a14e0c819c7e076d626444e349a | ff256b1fcae30e3b06b9dbddfa81439c1c4adb8e | refs/heads/master | 2022-07-08T04:42:13.810000 | 2021-03-05T09:37:47 | 2021-03-05T09:37:47 | 114,885,484 | 3 | 0 | null | false | 2022-06-29T18:23:34 | 2017-12-20T12:33:48 | 2022-01-03T16:18:26 | 2022-06-29T18:23:34 | 508,638 | 2 | 0 | 6 | Java | false | false | package users_accounts;
import warehouse.*;
import java.io.Serializable;
import java.lang.Integer;
import java.util.Collection;
import java.util.Date;
import javax.persistence.*;
import org.eclipse.persistence.jpa.jpql.parser.DateTime;
/**
* Entity implementation class for Entity: account
*
*/
@Entity (name="ACCOUNTS")
public class Account {
/* ***************************** */
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY )
private Integer idAccount;
/* ***************************** */
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
/* ***************************** */
@Column(name = "account_type")
private Integer accountType;
/* ***************************** */
/* **** Foreign Keys ***** */
/* ***************************** */
@OneToOne(mappedBy = "accountInfo", targetEntity = Users.class)
private Users userInfo;
/* ***************************** */
@OneToMany(mappedBy = "accountInfo")
private Collection<Adresses> accountAdresses;
/* ***************************** */
@OneToMany(mappedBy = "accountInfo")
private Collection<Commandes> accountCommandes;
/* ***************************** */
private static final long serialVersionUID = 1L;
public Account() {
super();
this.creationDate = new Date();
}
@Override
public String toString() {
return String.format("Account [idAccount=%s, creationDate=%s, accountType=%s, userInfo=%s, accountAdresses=%s]",
idAccount, creationDate, accountType, userInfo, accountAdresses);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountAdresses == null) ? 0 : accountAdresses.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((idAccount == null) ? 0 : idAccount.hashCode());
result = prime * result + ((userInfo == null) ? 0 : userInfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (accountAdresses == null) {
if (other.accountAdresses != null)
return false;
} else if (!accountAdresses.equals(other.accountAdresses))
return false;
if (accountType == null) {
if (other.accountType != null)
return false;
} else if (!accountType.equals(other.accountType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (idAccount == null) {
if (other.idAccount != null)
return false;
} else if (!idAccount.equals(other.idAccount))
return false;
if (userInfo == null) {
if (other.userInfo != null)
return false;
} else if (!userInfo.equals(other.userInfo))
return false;
return true;
}
/**
* @return the user
*/
public Users getUser() {
return userInfo;
}
/**
* @param user the user to set
*/
public void setUser(Users user) {
this.userInfo = user;
}
public Integer getIdAccount() {
return this.idAccount;
}
public void setIdAccount(Integer idAccount) {
this.idAccount = idAccount;
}
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
| UTF-8 | Java | 3,496 | java | Account.java | Java | [] | null | [] | package users_accounts;
import warehouse.*;
import java.io.Serializable;
import java.lang.Integer;
import java.util.Collection;
import java.util.Date;
import javax.persistence.*;
import org.eclipse.persistence.jpa.jpql.parser.DateTime;
/**
* Entity implementation class for Entity: account
*
*/
@Entity (name="ACCOUNTS")
public class Account {
/* ***************************** */
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY )
private Integer idAccount;
/* ***************************** */
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
/* ***************************** */
@Column(name = "account_type")
private Integer accountType;
/* ***************************** */
/* **** Foreign Keys ***** */
/* ***************************** */
@OneToOne(mappedBy = "accountInfo", targetEntity = Users.class)
private Users userInfo;
/* ***************************** */
@OneToMany(mappedBy = "accountInfo")
private Collection<Adresses> accountAdresses;
/* ***************************** */
@OneToMany(mappedBy = "accountInfo")
private Collection<Commandes> accountCommandes;
/* ***************************** */
private static final long serialVersionUID = 1L;
public Account() {
super();
this.creationDate = new Date();
}
@Override
public String toString() {
return String.format("Account [idAccount=%s, creationDate=%s, accountType=%s, userInfo=%s, accountAdresses=%s]",
idAccount, creationDate, accountType, userInfo, accountAdresses);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountAdresses == null) ? 0 : accountAdresses.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((idAccount == null) ? 0 : idAccount.hashCode());
result = prime * result + ((userInfo == null) ? 0 : userInfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (accountAdresses == null) {
if (other.accountAdresses != null)
return false;
} else if (!accountAdresses.equals(other.accountAdresses))
return false;
if (accountType == null) {
if (other.accountType != null)
return false;
} else if (!accountType.equals(other.accountType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (idAccount == null) {
if (other.idAccount != null)
return false;
} else if (!idAccount.equals(other.idAccount))
return false;
if (userInfo == null) {
if (other.userInfo != null)
return false;
} else if (!userInfo.equals(other.userInfo))
return false;
return true;
}
/**
* @return the user
*/
public Users getUser() {
return userInfo;
}
/**
* @param user the user to set
*/
public void setUser(Users user) {
this.userInfo = user;
}
public Integer getIdAccount() {
return this.idAccount;
}
public void setIdAccount(Integer idAccount) {
this.idAccount = idAccount;
}
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
| 3,496 | 0.627002 | 0.624428 | 134 | 25.089552 | 21.162294 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.813433 | false | false | 2 |
7c8d670e7edcafa13c9de54aea71c78c0b407f1f | 7,138,235,676,541 | a2fdac62519f9417b4fbdfe2ebcfa0ebd29766e2 | /Restaurant/src/main/java/com/isa/dish/DishRepository.java | 73d156b3b6b074c31700c64cd67851da958d85b7 | [] | no_license | anamihajlovic/ISA | https://github.com/anamihajlovic/ISA | 6e081162113f592f69d917781ef4bbeae705b933 | eef74051e3b53ebf491b511984493cb051eb5089 | refs/heads/master | 2021-01-12T14:58:12.152000 | 2017-03-02T03:13:49 | 2017-03-02T03:13:49 | 71,654,956 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.isa.dish;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface DishRepository extends PagingAndSortingRepository<Dish, Integer>{
public Dish findByName(String name);
public Dish findOne(Integer id);
}
| UTF-8 | Java | 256 | java | DishRepository.java | Java | [] | null | [] | package com.isa.dish;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface DishRepository extends PagingAndSortingRepository<Dish, Integer>{
public Dish findByName(String name);
public Dish findOne(Integer id);
}
| 256 | 0.820313 | 0.820313 | 11 | 22.272728 | 28.712021 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 2 |
212b1d484342c7bc06ebe838f3099efbb742f1da | 7,464,653,184,763 | 0fe1f9be40127be88cfcc2ed63adb898f6fbb80b | /basic-information-8084/src/main/java/com/neusoft/basicinformation8084/product/mapper/ProductMapper.java | cc06de1badd3ded92227d7f8df465f4e35c65122 | [] | no_license | happyma23333/bsp-backend-springcloud | https://github.com/happyma23333/bsp-backend-springcloud | c59cd5ccf1426e4d39a91d5dcc0d50b33d3ccfe6 | 61f3864eac7e0d54cc083ec0bf6cc389dae7b891 | refs/heads/master | 2023-04-06T17:55:04.368000 | 2020-07-23T07:35:16 | 2020-07-23T07:35:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neusoft.basicinformation8084.product.mapper;
import com.neusoft.basicinformation8084.common.base.BaseMapper;
import com.neusoft.basicinformation8084.product.entity.Product;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductMapper extends BaseMapper<Integer, Product> {
}
| UTF-8 | Java | 322 | java | ProductMapper.java | Java | [] | null | [] | package com.neusoft.basicinformation8084.product.mapper;
import com.neusoft.basicinformation8084.common.base.BaseMapper;
import com.neusoft.basicinformation8084.product.entity.Product;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductMapper extends BaseMapper<Integer, Product> {
}
| 322 | 0.854037 | 0.81677 | 10 | 31.200001 | 29.365967 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
a6f0d1bf9413fcad9fbcd89274f1abbe9f7a8d69 | 20,040,317,429,874 | 26f493eb9dbda861a7869fd3c7dbfae9fc61eefc | /src/main/java/PolynomialCalculation.java | c4ec803271ad55d0f2de599f332c94bbd622fec2 | [] | no_license | tangzhankun/algorithm | https://github.com/tangzhankun/algorithm | 405ae1e901f3caee7b1e6bdbea0e86bdbf8c0425 | 0a821a2cb773c9863b91a3e453d3bd68722431e9 | refs/heads/master | 2021-01-02T23:15:29.257000 | 2018-04-26T10:35:25 | 2018-04-26T10:35:25 | 99,494,066 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* given a and x, calculate y
* y = a[n]*x^n + a[n-1]*x^(n-1) + ... + a[0]
*
* ANSWER:
* y = a[n]
* for (i=n-1; i>=0; i--) {
* y = x*y + a[i]
* }
*
* */
public class PolynomialCalculation {
}
| UTF-8 | Java | 207 | java | PolynomialCalculation.java | Java | [] | null | [] |
/**
* given a and x, calculate y
* y = a[n]*x^n + a[n-1]*x^(n-1) + ... + a[0]
*
* ANSWER:
* y = a[n]
* for (i=n-1; i>=0; i--) {
* y = x*y + a[i]
* }
*
* */
public class PolynomialCalculation {
}
| 207 | 0.425121 | 0.400966 | 13 | 14.846154 | 14.222659 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 2 |
d1802c7f899e59f22ea0a168ef776cd824cf0b43 | 22,170,621,201,028 | 88cd0caab5a067a821982c153d9b7a16cd482411 | /app/src/main/java/com/sanfinance/sisca/fragment/OtherExposureFragment.java | 4cd4587e2ef02f624e22312fe790cc6a1c067094 | [] | no_license | anton-khansa/SISCA | https://github.com/anton-khansa/SISCA | d87c0cb0cc6b28f743e86f2fec1d080c57ee481c | 6f318b7a588720a66406e78767062ff51049b63a | refs/heads/master | 2017-12-02T18:57:08.253000 | 2017-11-14T02:36:28 | 2017-11-14T02:36:28 | 85,467,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sanfinance.sisca.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sanfinance.sisca.R;
import com.sanfinance.sisca.entity.EntityOtherExposure;
import com.sanfinance.sisca.helper.ApiInterface;
import com.sanfinance.sisca.helper.JSONResponse;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class OtherExposureFragment extends Fragment {
private ArrayList<EntityOtherExposure> data;
private String br_id,reg_no,rev_no,type_oscar,cust_name;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.oscar_other_exposure, container, false);
br_id = getArguments().getString("br_id");
reg_no = getArguments().getString("reg_no");
rev_no = getArguments().getString("rev_no");
type_oscar = getArguments().getString("type_oscar");
cust_name= getArguments().getString("cust_name");
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initViews();
}
private void initViews(){
loadJSON();
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apps.sanfinance.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getOtherExposure(br_id,reg_no,rev_no,type_oscar);
call.enqueue(new Callback<JSONResponse>() {
@Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getOtherExposure()));
((TextView) getActivity().findViewById(R.id.oNAME1)).setText(data.get(0).getNAME1());
((TextView) getActivity().findViewById(R.id.oACT_CONT1)).setText(data.get(0).getACT_CONT1());
((TextView) getActivity().findViewById(R.id.oPAID_OFF1)).setText(data.get(0).getPAID_OFF1());
((TextView) getActivity().findViewById(R.id.oINSTALL1)).setText(data.get(0).getINSTALL1());
((TextView) getActivity().findViewById(R.id.oAR1)).setText(data.get(0).getAR1());
((TextView) getActivity().findViewById(R.id.oINST1)).setText(data.get(0).getINST1());
((TextView) getActivity().findViewById(R.id.oMAX_OVD1)).setText(data.get(0).getMAX_OVD1());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD1)).setText(data.get(0).getSTAT_OVD1());
((TextView) getActivity().findViewById(R.id.oVERIFIED1)).setText(data.get(0).getVERIFIED1());
((TextView) getActivity().findViewById(R.id.oNAME2)).setText(data.get(0).getNAME2());
((TextView) getActivity().findViewById(R.id.oACT_CONT2)).setText(data.get(0).getACTCONT2());
((TextView) getActivity().findViewById(R.id.oPAID_OFF2)).setText(data.get(0).getPAID_OFF2());
((TextView) getActivity().findViewById(R.id.oINSTALL2)).setText(data.get(0).getINSTALL2());
((TextView) getActivity().findViewById(R.id.oAR2)).setText(data.get(0).getAR2());
((TextView) getActivity().findViewById(R.id.oINST2)).setText(data.get(0).getINST2());
((TextView) getActivity().findViewById(R.id.oMAX_OVD2)).setText(data.get(0).getMAX_OVD2());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD2)).setText(data.get(0).getSTAT_OVD2());
((TextView) getActivity().findViewById(R.id.oVERIFIED2)).setText(data.get(0).getVERIFIED2());
((TextView) getActivity().findViewById(R.id.oNAME3)).setText(data.get(0).getNAME3());
((TextView) getActivity().findViewById(R.id.oACT_CONT3)).setText(data.get(0).getACT_CONT3());
((TextView) getActivity().findViewById(R.id.oPAID_OFF3)).setText(data.get(0).getPAID_OFF3());
((TextView) getActivity().findViewById(R.id.oINSTALL3)).setText(data.get(0).getINSTALL3());
((TextView) getActivity().findViewById(R.id.oAR3)).setText(data.get(0).getAR3());
((TextView) getActivity().findViewById(R.id.oINST3)).setText(data.get(0).getINST3());
((TextView) getActivity().findViewById(R.id.oMAX_OVD3)).setText(data.get(0).getMAX_OVD3());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD3)).setText(data.get(0).getSTAT_OVD3());
((TextView) getActivity().findViewById(R.id.oVERIFIED3)).setText(data.get(0).getVERIFIED3());
((TextView) getActivity().findViewById(R.id.oACT_CONT0)).setText(data.get(0).getACT_CONT0());
((TextView) getActivity().findViewById(R.id.oPAID_OFF0)).setText(data.get(0).getPAID_OFF0());
((TextView) getActivity().findViewById(R.id.oAR0)).setText(data.get(0).getAR0());
((TextView) getActivity().findViewById(R.id.oINST0)).setText(data.get(0).getINST0());
((TextView) getActivity().findViewById(R.id.oSUMMARY_CC)).setText(data.get(0).getSUMMARY_CC());
// if(data.get(0).getNAME1().trim().isEmpty()) {
// getActivity().findViewById(R.id.card1).setVisibility(View.GONE);
// }
// if(data.get(0).getNAME2().trim().isEmpty()) {
// (getActivity().findViewById(R.id.card2)).setVisibility(View.GONE);
// }
// if(data.get(0).getNAME3().trim().isEmpty()) {
// (getActivity().findViewById(R.id.card3)).setVisibility(View.GONE);
// }
}
@Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
| UTF-8 | Java | 6,478 | java | OtherExposureFragment.java | Java | [] | null | [] |
package com.sanfinance.sisca.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sanfinance.sisca.R;
import com.sanfinance.sisca.entity.EntityOtherExposure;
import com.sanfinance.sisca.helper.ApiInterface;
import com.sanfinance.sisca.helper.JSONResponse;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class OtherExposureFragment extends Fragment {
private ArrayList<EntityOtherExposure> data;
private String br_id,reg_no,rev_no,type_oscar,cust_name;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.oscar_other_exposure, container, false);
br_id = getArguments().getString("br_id");
reg_no = getArguments().getString("reg_no");
rev_no = getArguments().getString("rev_no");
type_oscar = getArguments().getString("type_oscar");
cust_name= getArguments().getString("cust_name");
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initViews();
}
private void initViews(){
loadJSON();
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apps.sanfinance.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getOtherExposure(br_id,reg_no,rev_no,type_oscar);
call.enqueue(new Callback<JSONResponse>() {
@Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getOtherExposure()));
((TextView) getActivity().findViewById(R.id.oNAME1)).setText(data.get(0).getNAME1());
((TextView) getActivity().findViewById(R.id.oACT_CONT1)).setText(data.get(0).getACT_CONT1());
((TextView) getActivity().findViewById(R.id.oPAID_OFF1)).setText(data.get(0).getPAID_OFF1());
((TextView) getActivity().findViewById(R.id.oINSTALL1)).setText(data.get(0).getINSTALL1());
((TextView) getActivity().findViewById(R.id.oAR1)).setText(data.get(0).getAR1());
((TextView) getActivity().findViewById(R.id.oINST1)).setText(data.get(0).getINST1());
((TextView) getActivity().findViewById(R.id.oMAX_OVD1)).setText(data.get(0).getMAX_OVD1());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD1)).setText(data.get(0).getSTAT_OVD1());
((TextView) getActivity().findViewById(R.id.oVERIFIED1)).setText(data.get(0).getVERIFIED1());
((TextView) getActivity().findViewById(R.id.oNAME2)).setText(data.get(0).getNAME2());
((TextView) getActivity().findViewById(R.id.oACT_CONT2)).setText(data.get(0).getACTCONT2());
((TextView) getActivity().findViewById(R.id.oPAID_OFF2)).setText(data.get(0).getPAID_OFF2());
((TextView) getActivity().findViewById(R.id.oINSTALL2)).setText(data.get(0).getINSTALL2());
((TextView) getActivity().findViewById(R.id.oAR2)).setText(data.get(0).getAR2());
((TextView) getActivity().findViewById(R.id.oINST2)).setText(data.get(0).getINST2());
((TextView) getActivity().findViewById(R.id.oMAX_OVD2)).setText(data.get(0).getMAX_OVD2());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD2)).setText(data.get(0).getSTAT_OVD2());
((TextView) getActivity().findViewById(R.id.oVERIFIED2)).setText(data.get(0).getVERIFIED2());
((TextView) getActivity().findViewById(R.id.oNAME3)).setText(data.get(0).getNAME3());
((TextView) getActivity().findViewById(R.id.oACT_CONT3)).setText(data.get(0).getACT_CONT3());
((TextView) getActivity().findViewById(R.id.oPAID_OFF3)).setText(data.get(0).getPAID_OFF3());
((TextView) getActivity().findViewById(R.id.oINSTALL3)).setText(data.get(0).getINSTALL3());
((TextView) getActivity().findViewById(R.id.oAR3)).setText(data.get(0).getAR3());
((TextView) getActivity().findViewById(R.id.oINST3)).setText(data.get(0).getINST3());
((TextView) getActivity().findViewById(R.id.oMAX_OVD3)).setText(data.get(0).getMAX_OVD3());
((TextView) getActivity().findViewById(R.id.oSTAT_OVD3)).setText(data.get(0).getSTAT_OVD3());
((TextView) getActivity().findViewById(R.id.oVERIFIED3)).setText(data.get(0).getVERIFIED3());
((TextView) getActivity().findViewById(R.id.oACT_CONT0)).setText(data.get(0).getACT_CONT0());
((TextView) getActivity().findViewById(R.id.oPAID_OFF0)).setText(data.get(0).getPAID_OFF0());
((TextView) getActivity().findViewById(R.id.oAR0)).setText(data.get(0).getAR0());
((TextView) getActivity().findViewById(R.id.oINST0)).setText(data.get(0).getINST0());
((TextView) getActivity().findViewById(R.id.oSUMMARY_CC)).setText(data.get(0).getSUMMARY_CC());
// if(data.get(0).getNAME1().trim().isEmpty()) {
// getActivity().findViewById(R.id.card1).setVisibility(View.GONE);
// }
// if(data.get(0).getNAME2().trim().isEmpty()) {
// (getActivity().findViewById(R.id.card2)).setVisibility(View.GONE);
// }
// if(data.get(0).getNAME3().trim().isEmpty()) {
// (getActivity().findViewById(R.id.card3)).setVisibility(View.GONE);
// }
}
@Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
| 6,478 | 0.636462 | 0.619636 | 129 | 49.209301 | 41.016289 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.682171 | false | false | 2 |
61957d65e0755930e992688aa25ec54e3e2b072b | 12,171,937,328,238 | e8e0997383c338807bc6629afd35df6c8880e026 | /app/src/main/java/com/itn/terranode/presentation/view/broadcast/RefreshTokenReceiver.java | 7687d24cf042df2d8c07c575e3bf43021ae2ded7 | [] | no_license | ase21/TerraNode | https://github.com/ase21/TerraNode | c034ad58a014f8d89686b684d92b85f68c80cbeb | 08924ced78bfdb35af94f2bfcca8396ba1899fcb | refs/heads/master | 2020-12-01T14:13:27.907000 | 2020-01-16T17:13:07 | 2020-01-16T17:13:07 | 230,658,177 | 0 | 1 | null | false | 2020-01-16T17:13:08 | 2019-12-28T19:48:40 | 2020-01-14T13:45:23 | 2020-01-16T17:13:07 | 411 | 0 | 0 | 0 | Java | false | false | package com.itn.terranode.presentation.view.broadcast;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.gson.Gson;
import com.itn.terranode.data.network.dtos.LoginSuccessResponse;
import com.itn.terranode.di.app.App;
import com.itn.terranode.domain.broadcast.ReceiverInteractor;
import java.util.Calendar;
import javax.inject.Inject;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
public class RefreshTokenReceiver extends BroadcastReceiver {
private final CompositeDisposable compositeDisposable;
@Inject
ReceiverInteractor interactor;
public RefreshTokenReceiver() {
this.compositeDisposable = new CompositeDisposable();
App.getInstance().plusReceiverComponent().inject(this);
}
@Override
public void onReceive(Context context, Intent intent) {
Disposable disposable = interactor
.refreshToken()
.subscribe(response -> {
if (response.code() == 200) {
LoginSuccessResponse successResponse = new Gson().fromJson(response.body().toString(), LoginSuccessResponse.class);
saveToken(successResponse.getData().getAccessToken());
setAlarm(context, (int)Float.parseFloat(successResponse.getData().getExpiresIn()));
} else {
clearAll(context);
}
},
throwable -> clearAll(context),
() -> {
}
);
compositeDisposable.add(disposable);
}
private void clearAll(Context context) {
cancelAlarm(context);
interactor.clearPrefs();
}
private void saveToken(String accessToken) {
compositeDisposable.add(interactor.saveToken(accessToken).subscribe(() -> {}, throwable -> {}));
}
public static void setAlarm(Context context, int min){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,0);
cal.set(Calendar.DATE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long intervalInMillis = cal.getTimeInMillis();
//получаем алармМенеджер
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RefreshTokenReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
Log.d("ase21", "установлен аларм");
}
public static void cancelAlarm(Context context){
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RefreshTokenReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);
}
}
| UTF-8 | Java | 3,381 | java | RefreshTokenReceiver.java | Java | [] | null | [] | package com.itn.terranode.presentation.view.broadcast;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.gson.Gson;
import com.itn.terranode.data.network.dtos.LoginSuccessResponse;
import com.itn.terranode.di.app.App;
import com.itn.terranode.domain.broadcast.ReceiverInteractor;
import java.util.Calendar;
import javax.inject.Inject;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
public class RefreshTokenReceiver extends BroadcastReceiver {
private final CompositeDisposable compositeDisposable;
@Inject
ReceiverInteractor interactor;
public RefreshTokenReceiver() {
this.compositeDisposable = new CompositeDisposable();
App.getInstance().plusReceiverComponent().inject(this);
}
@Override
public void onReceive(Context context, Intent intent) {
Disposable disposable = interactor
.refreshToken()
.subscribe(response -> {
if (response.code() == 200) {
LoginSuccessResponse successResponse = new Gson().fromJson(response.body().toString(), LoginSuccessResponse.class);
saveToken(successResponse.getData().getAccessToken());
setAlarm(context, (int)Float.parseFloat(successResponse.getData().getExpiresIn()));
} else {
clearAll(context);
}
},
throwable -> clearAll(context),
() -> {
}
);
compositeDisposable.add(disposable);
}
private void clearAll(Context context) {
cancelAlarm(context);
interactor.clearPrefs();
}
private void saveToken(String accessToken) {
compositeDisposable.add(interactor.saveToken(accessToken).subscribe(() -> {}, throwable -> {}));
}
public static void setAlarm(Context context, int min){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,0);
cal.set(Calendar.DATE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long intervalInMillis = cal.getTimeInMillis();
//получаем алармМенеджер
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RefreshTokenReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
Log.d("ase21", "установлен аларм");
}
public static void cancelAlarm(Context context){
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RefreshTokenReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);
}
}
| 3,381 | 0.649626 | 0.645441 | 90 | 36.166668 | 30.678349 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766667 | false | false | 2 |
c14115eda418ae857747bfdbfb86db92ace6ea99 | 17,686,675,344,153 | 684656f433324bea7a6ebda2c4516f4c22c6fe5f | /src/main/java/moxie/GroupImpl.java | 12d92df7160830a6e11735f3ebd4510e76fd6992 | [
"MIT"
] | permissive | pobrelkey/moxiemocks | https://github.com/pobrelkey/moxiemocks | 208adf131ea003ab2dcf0b0d59b387b8e911a7bd | d0dccc4d85b75c3a36b82c436b02ac0d0db331bd | refs/heads/master | 2021-01-22T02:33:52.166000 | 2020-10-16T08:14:51 | 2020-10-16T08:14:51 | 25,490,173 | 2 | 0 | MIT | false | 2020-10-16T08:14:53 | 2014-10-20T22:50:03 | 2019-12-03T20:57:35 | 2020-10-16T08:14:53 | 847 | 2 | 1 | 0 | Java | false | false | /*
* Copyright (c) 2010-2012 Moxie contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package moxie;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
class GroupImpl implements Group, Verifiable {
private final String name;
private final InstantiationStackTrace whereInstantiated;
private final List<ExpectationImpl> unorderedExpectations = new ArrayList<ExpectationImpl>();
private final List<ExpectationImpl> orderedExpectations = new ArrayList<ExpectationImpl>();
private final List<MoxieUnexpectedInvocationError> unexpectedInvocations = new ArrayList<MoxieUnexpectedInvocationError>();
private boolean defaultCardinality;
private CardinalityImpl cardinality;
private int cursor;
private int checkCursor;
private MoxieFlags flags;
GroupImpl(String name, MoxieFlags flags) {
this.name = name;
this.whereInstantiated = MoxieUtils.unbox(flags.isTracing(), false) ? new InstantiationStackTrace("sequence \"" + name + "\" was instantiated here") : null;
reset(flags);
}
public Cardinality<Group> willBeCalled() {
if (!flags.isStrictlyOrdered()) {
throw new MoxieSyntaxError("cannot set cardinality on an unordered method group");
}
if (!defaultCardinality) {
throw new MoxieSyntaxError("already specified number of times");
}
defaultCardinality = false;
CardinalityImpl<Group> result = new CardinalityImpl<Group>(this);
cardinality = result;
return result;
}
public void reset(MoxieFlags flags) {
if (flags != null) {
this.flags = this.flags != null ? MoxieOptions.mergeWithDefaults(this.flags, flags) : flags;
}
unorderedExpectations.clear();
orderedExpectations.clear();
defaultCardinality = true;
cardinality = new CardinalityImpl<CardinalityImpl>().once();
cursor = 0;
unexpectedInvocations.clear();
}
public Throwable getWhereInstantiated() {
return whereInstantiated;
}
public String getName() {
return name;
}
public void add(ExpectationImpl expectation) {
if (flags.isStrictlyOrdered() && !expectation.isUnordered()) {
orderedExpectations.add(expectation);
} else {
unorderedExpectations.add(expectation);
}
}
public void verify() {
// keep track of invocations so we can report them nicely when we fail
verify(null);
}
public void verifyNoBackgroundErrors() {
if (MoxieUtils.unbox(flags.isBackgroundAware(), true)) {
if (unexpectedInvocations.size() == 1) {
throw unexpectedInvocations.get(0);
} else if (unexpectedInvocations.size() > 1) {
throw new MoxieUnexpectedInvocationError(unexpectedInvocations);
}
}
}
void verify(List<Invocation> invocations) {
for (ExpectationImpl expectation : unorderedExpectations) {
if (!expectation.isSatisfied()) {
throwFailedVerificationError("not all expected methods invoked or cardinality not satisfied", invocations);
}
}
if (!orderedExpectations.isEmpty()) {
if (cursor == orderedExpectations.size() - 1 && orderedExpectations.get(cursor).isSatisfied()) {
cursor = 0;
cardinality.incrementCount();
}
if (cursor == 0 && cardinality.isSatisfied()) {
return;
}
throwFailedVerificationError("not all expected methods invoked or cardinality not satisfied", invocations);
}
}
@SuppressWarnings("unchecked")
public ExpectationImpl match(InvocableAdapter invocable, Object[] args, MethodBehavior behavior) {
ExpectationImpl result = null;
for (ExpectationImpl expectation : unorderedExpectations) {
if (expectation.match(invocable, args, behavior, this)) {
result = expectation;
break;
}
}
if (result == null && !orderedExpectations.isEmpty()) {
if (cardinality.isViable()) {
if (orderedExpectations.get(cursor).match(invocable, args, behavior, this)) {
result = orderedExpectations.get(cursor);
} else {
cursor++;
if (cursor == orderedExpectations.size()) {
cursor = 0;
cardinality.incrementCount();
}
if (cardinality.isViable() && orderedExpectations.get(cursor).match(invocable, args, behavior, this)) {
result = orderedExpectations.get(cursor);
}
}
}
}
if (result != null) {
for (GroupImpl group : (Set<GroupImpl>) result.getGroups()) {
group.match(result, invocable, args);
}
}
return result;
}
public void match(ExpectationImpl expectation, InvocableAdapter invocable, Object[] args) {
if (!orderedExpectations.isEmpty()) {
if (cardinality.isViable()) {
if (orderedExpectations.get(cursor) == expectation) {
return;
}
cursor++;
if (cursor == orderedExpectations.size()) {
cursor = 0;
cardinality.incrementCount();
}
if (cardinality.isViable() && orderedExpectations.get(cursor) == expectation) {
return;
}
}
throwUnexpectedInvocationError("out of sequence expectation or too many times through sequence", invocable, args);
}
}
int getCheckCursor() {
return checkCursor;
}
void setCheckCursor(int checkCursor) {
this.checkCursor = checkCursor;
}
boolean isStrictlyOrdered() {
return flags.isStrictlyOrdered();
}
void throwUnexpectedInvocationError(String message, InvocableAdapter invoked, Object[] invocationArgs) {
MoxieUnexpectedInvocationError moxieUnexpectedInvocationError = new MoxieUnexpectedInvocationError(message, name, invoked, invocationArgs, unorderedExpectations, orderedExpectations);
this.unexpectedInvocations.add(moxieUnexpectedInvocationError);
throw moxieUnexpectedInvocationError;
}
private void throwFailedVerificationError(String message, List<Invocation> invocations) {
throw new MoxieFailedVerificationError(message, name, invocations, unorderedExpectations, orderedExpectations);
}
} | UTF-8 | Java | 7,772 | java | GroupImpl.java | Java | [] | null | [] | /*
* Copyright (c) 2010-2012 Moxie contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package moxie;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
class GroupImpl implements Group, Verifiable {
private final String name;
private final InstantiationStackTrace whereInstantiated;
private final List<ExpectationImpl> unorderedExpectations = new ArrayList<ExpectationImpl>();
private final List<ExpectationImpl> orderedExpectations = new ArrayList<ExpectationImpl>();
private final List<MoxieUnexpectedInvocationError> unexpectedInvocations = new ArrayList<MoxieUnexpectedInvocationError>();
private boolean defaultCardinality;
private CardinalityImpl cardinality;
private int cursor;
private int checkCursor;
private MoxieFlags flags;
GroupImpl(String name, MoxieFlags flags) {
this.name = name;
this.whereInstantiated = MoxieUtils.unbox(flags.isTracing(), false) ? new InstantiationStackTrace("sequence \"" + name + "\" was instantiated here") : null;
reset(flags);
}
public Cardinality<Group> willBeCalled() {
if (!flags.isStrictlyOrdered()) {
throw new MoxieSyntaxError("cannot set cardinality on an unordered method group");
}
if (!defaultCardinality) {
throw new MoxieSyntaxError("already specified number of times");
}
defaultCardinality = false;
CardinalityImpl<Group> result = new CardinalityImpl<Group>(this);
cardinality = result;
return result;
}
public void reset(MoxieFlags flags) {
if (flags != null) {
this.flags = this.flags != null ? MoxieOptions.mergeWithDefaults(this.flags, flags) : flags;
}
unorderedExpectations.clear();
orderedExpectations.clear();
defaultCardinality = true;
cardinality = new CardinalityImpl<CardinalityImpl>().once();
cursor = 0;
unexpectedInvocations.clear();
}
public Throwable getWhereInstantiated() {
return whereInstantiated;
}
public String getName() {
return name;
}
public void add(ExpectationImpl expectation) {
if (flags.isStrictlyOrdered() && !expectation.isUnordered()) {
orderedExpectations.add(expectation);
} else {
unorderedExpectations.add(expectation);
}
}
public void verify() {
// keep track of invocations so we can report them nicely when we fail
verify(null);
}
public void verifyNoBackgroundErrors() {
if (MoxieUtils.unbox(flags.isBackgroundAware(), true)) {
if (unexpectedInvocations.size() == 1) {
throw unexpectedInvocations.get(0);
} else if (unexpectedInvocations.size() > 1) {
throw new MoxieUnexpectedInvocationError(unexpectedInvocations);
}
}
}
void verify(List<Invocation> invocations) {
for (ExpectationImpl expectation : unorderedExpectations) {
if (!expectation.isSatisfied()) {
throwFailedVerificationError("not all expected methods invoked or cardinality not satisfied", invocations);
}
}
if (!orderedExpectations.isEmpty()) {
if (cursor == orderedExpectations.size() - 1 && orderedExpectations.get(cursor).isSatisfied()) {
cursor = 0;
cardinality.incrementCount();
}
if (cursor == 0 && cardinality.isSatisfied()) {
return;
}
throwFailedVerificationError("not all expected methods invoked or cardinality not satisfied", invocations);
}
}
@SuppressWarnings("unchecked")
public ExpectationImpl match(InvocableAdapter invocable, Object[] args, MethodBehavior behavior) {
ExpectationImpl result = null;
for (ExpectationImpl expectation : unorderedExpectations) {
if (expectation.match(invocable, args, behavior, this)) {
result = expectation;
break;
}
}
if (result == null && !orderedExpectations.isEmpty()) {
if (cardinality.isViable()) {
if (orderedExpectations.get(cursor).match(invocable, args, behavior, this)) {
result = orderedExpectations.get(cursor);
} else {
cursor++;
if (cursor == orderedExpectations.size()) {
cursor = 0;
cardinality.incrementCount();
}
if (cardinality.isViable() && orderedExpectations.get(cursor).match(invocable, args, behavior, this)) {
result = orderedExpectations.get(cursor);
}
}
}
}
if (result != null) {
for (GroupImpl group : (Set<GroupImpl>) result.getGroups()) {
group.match(result, invocable, args);
}
}
return result;
}
public void match(ExpectationImpl expectation, InvocableAdapter invocable, Object[] args) {
if (!orderedExpectations.isEmpty()) {
if (cardinality.isViable()) {
if (orderedExpectations.get(cursor) == expectation) {
return;
}
cursor++;
if (cursor == orderedExpectations.size()) {
cursor = 0;
cardinality.incrementCount();
}
if (cardinality.isViable() && orderedExpectations.get(cursor) == expectation) {
return;
}
}
throwUnexpectedInvocationError("out of sequence expectation or too many times through sequence", invocable, args);
}
}
int getCheckCursor() {
return checkCursor;
}
void setCheckCursor(int checkCursor) {
this.checkCursor = checkCursor;
}
boolean isStrictlyOrdered() {
return flags.isStrictlyOrdered();
}
void throwUnexpectedInvocationError(String message, InvocableAdapter invoked, Object[] invocationArgs) {
MoxieUnexpectedInvocationError moxieUnexpectedInvocationError = new MoxieUnexpectedInvocationError(message, name, invoked, invocationArgs, unorderedExpectations, orderedExpectations);
this.unexpectedInvocations.add(moxieUnexpectedInvocationError);
throw moxieUnexpectedInvocationError;
}
private void throwFailedVerificationError(String message, List<Invocation> invocations) {
throw new MoxieFailedVerificationError(message, name, invocations, unorderedExpectations, orderedExpectations);
}
} | 7,772 | 0.635486 | 0.633299 | 197 | 38.456852 | 35.144871 | 191 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.624366 | false | false | 2 |
175eed6f919740ce33a153f22b3679c6803415a0 | 13,297,218,771,972 | 9140fab56a9ca4beaca4840378706b4c88e4ce1c | /src/main/java/com/example/springboothelloworld/SpringbootHelloworldApplication.java | 80a304fd56db30e8ab0f52d2d4e855b81a14d453 | [] | no_license | fingal2222/SpringBoot | https://github.com/fingal2222/SpringBoot | 69a4461c053946c134875d2260c38f2788d72a2b | 61e3b6e6cdc71c67ee3a5d96cab32ab6722d7361 | refs/heads/master | 2020-04-19T23:08:39.459000 | 2019-03-11T10:22:35 | 2019-03-11T10:22:35 | 168,487,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.springboothelloworld;
import com.example.springboothelloworld.dto.Consumer;
import com.example.springboothelloworld.dto.Producer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@Configuration
@EnableSwagger2
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.springboothelloworld"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("云外呼ftp服务")
.description("云外呼ftp服务Online API文档")
.version("1.0")
.build();
}
}
| UTF-8 | Java | 1,603 | java | SpringbootHelloworldApplication.java | Java | [] | null | [] | package com.example.springboothelloworld;
import com.example.springboothelloworld.dto.Consumer;
import com.example.springboothelloworld.dto.Producer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@Configuration
@EnableSwagger2
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.springboothelloworld"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("云外呼ftp服务")
.description("云外呼ftp服务Online API文档")
.version("1.0")
.build();
}
}
| 1,603 | 0.734642 | 0.730842 | 45 | 34.066666 | 24.433493 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 2 |
6e3f441428fb3404e1864b5bb808c114c4e9a5c5 | 12,000,138,645,174 | 8d0880f3843ff475adea8f007142a5a7ab2616e0 | /src/main/java/com/mybatis/enumdemo/typehandler/CityClassEnum.java | 879bec0ba3a08e4965b62dbf9901b203e14af79e | [] | no_license | yhb2010/spring_boot4 | https://github.com/yhb2010/spring_boot4 | 5b693860c2912044920e066d0fb30ab8eac5d066 | 92c68da24bb9e1ca20c292b741aea0d5dbcd51a7 | refs/heads/master | 2018-05-03T01:25:15.560000 | 2018-02-26T05:41:32 | 2018-02-26T05:41:32 | 81,709,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mybatis.enumdemo.typehandler;
public enum CityClassEnum implements DbEnum {
beijing((byte) 1),
tokyo((byte) 2),
solr((byte) 3);
CityClassEnum(byte cityClass) {
this.cityClass = cityClass;
}
private final byte cityClass;
@Override
public byte code() {
return cityClass;
}
}
| UTF-8 | Java | 324 | java | CityClassEnum.java | Java | [] | null | [] | package com.mybatis.enumdemo.typehandler;
public enum CityClassEnum implements DbEnum {
beijing((byte) 1),
tokyo((byte) 2),
solr((byte) 3);
CityClassEnum(byte cityClass) {
this.cityClass = cityClass;
}
private final byte cityClass;
@Override
public byte code() {
return cityClass;
}
}
| 324 | 0.666667 | 0.657407 | 20 | 14.2 | 14.586295 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
6c8d56256d696338dbd20fae1e1072259ed35ae7 | 30,975,304,155,364 | bf62a5004c70650c696879ba6391495cabcbb240 | /src/main/java/org/jmeld/vc/svn/DiffCmd.java | 3c7c7688d4858bcef8eabd66874066fbcb7369bf | [] | no_license | albfan/jmeld | https://github.com/albfan/jmeld | 756a0147d5cc0c0d54198a421610906489820556 | 66b98ddb96bab10823813d01024cb21f98149e58 | refs/heads/master | 2023-05-26T09:27:40.832000 | 2021-12-01T19:05:13 | 2021-12-01T19:05:25 | 26,455,671 | 42 | 34 | null | false | 2023-05-09T17:28:54 | 2014-11-10T21:05:51 | 2023-05-01T18:53:23 | 2023-05-09T17:28:54 | 18,309 | 40 | 29 | 29 | Java | false | false | package org.jmeld.vc.svn;
import org.jmeld.diff.*;
import org.jmeld.util.*;
import org.jmeld.vc.*;
import org.jmeld.vc.util.*;
import java.io.*;
import java.util.regex.*;
public class DiffCmd
extends VcCmd<DiffData>
{
// Instance variables:
private File file;
private boolean recursive;
private BufferedReader reader;
private String unreadLine;
public DiffCmd(File file, boolean recursive)
{
this.file = file;
this.recursive = recursive;
}
public Result execute()
{
super.execute("svn", "diff", "--non-interactive", "--no-diff-deleted",
recursive ? "" : "-N", file.getPath());
return getResult();
}
protected void build(byte[] data)
{
String path;
JMRevision revision;
JMDelta delta;
DiffData diffData;
diffData = new DiffData();
reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
data)));
try
{
for (;;)
{
path = readIndex();
if (path == null)
{
break;
}
System.out.println("path = " + path);
revision = new JMRevision(null, null);
diffData.addTarget(path, revision);
readLine(); // =====================================
readLine(); // --- <Path> (revision ...)
readLine(); // +++ <Path> (working copy)
for (;;)
{
delta = readDelta();
if (delta == null)
{
break;
}
revision.add(delta);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
setResult(Result.FALSE("Parse failed"));
}
setResultData(diffData);
}
private String readIndex()
throws IOException
{
final String indexMarker = "Index: ";
String line;
line = readLine();
if (line == null || !line.startsWith(indexMarker))
{
return null;
}
return line.substring(indexMarker.length());
}
private JMDelta readDelta()
throws IOException
{
final Pattern deltaPattern = Pattern
.compile("@@ -(\\d*),(\\d*) \\+(\\d*),(\\d*) @@");
String line;
Matcher m;
JMDelta delta;
JMChunk originalChunk;
JMChunk revisedChunk;
// @@ <LineNumberRevision>,<NumberOfLines> <lineNumberWorkingCopy>,<NumberOfLines> @@
line = readLine();
if (line == null)
{
return null;
}
m = deltaPattern.matcher(line);
if (!m.matches())
{
unreadLine(line);
return null;
}
originalChunk = new JMChunk(Integer.valueOf(m.group(1)), Integer.valueOf(m
.group(2)));
revisedChunk = new JMChunk(Integer.valueOf(m.group(3)), Integer.valueOf(m
.group(4)));
delta = new JMDelta(originalChunk, revisedChunk);
while ((line = readLine()) != null)
{
if (line.startsWith(" "))
{
continue;
}
if (line.startsWith("+"))
{
continue;
}
if (line.startsWith("-"))
{
continue;
}
unreadLine(line);
break;
}
System.out.println("delta = " + delta);
return delta;
}
private void unreadLine(String unreadLine)
{
this.unreadLine = unreadLine;
}
private String readLine()
throws IOException
{
String line;
if (unreadLine != null)
{
line = unreadLine;
unreadLine = null;
return line;
}
return reader.readLine();
}
public static void main(String[] args)
{
DiffCmd cmd;
DiffIF result;
File file = parseFile(args);
if (file == null) {
return;
}
result = new SubversionVersionControl()
.executeDiff(file, true);
if (result != null)
{
for (DiffIF.TargetIF target : result.getTargetList())
{
System.out.println(target.getPath() + " " + target.getRevision());
}
}
}
}
| UTF-8 | Java | 4,053 | java | DiffCmd.java | Java | [] | null | [] | package org.jmeld.vc.svn;
import org.jmeld.diff.*;
import org.jmeld.util.*;
import org.jmeld.vc.*;
import org.jmeld.vc.util.*;
import java.io.*;
import java.util.regex.*;
public class DiffCmd
extends VcCmd<DiffData>
{
// Instance variables:
private File file;
private boolean recursive;
private BufferedReader reader;
private String unreadLine;
public DiffCmd(File file, boolean recursive)
{
this.file = file;
this.recursive = recursive;
}
public Result execute()
{
super.execute("svn", "diff", "--non-interactive", "--no-diff-deleted",
recursive ? "" : "-N", file.getPath());
return getResult();
}
protected void build(byte[] data)
{
String path;
JMRevision revision;
JMDelta delta;
DiffData diffData;
diffData = new DiffData();
reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
data)));
try
{
for (;;)
{
path = readIndex();
if (path == null)
{
break;
}
System.out.println("path = " + path);
revision = new JMRevision(null, null);
diffData.addTarget(path, revision);
readLine(); // =====================================
readLine(); // --- <Path> (revision ...)
readLine(); // +++ <Path> (working copy)
for (;;)
{
delta = readDelta();
if (delta == null)
{
break;
}
revision.add(delta);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
setResult(Result.FALSE("Parse failed"));
}
setResultData(diffData);
}
private String readIndex()
throws IOException
{
final String indexMarker = "Index: ";
String line;
line = readLine();
if (line == null || !line.startsWith(indexMarker))
{
return null;
}
return line.substring(indexMarker.length());
}
private JMDelta readDelta()
throws IOException
{
final Pattern deltaPattern = Pattern
.compile("@@ -(\\d*),(\\d*) \\+(\\d*),(\\d*) @@");
String line;
Matcher m;
JMDelta delta;
JMChunk originalChunk;
JMChunk revisedChunk;
// @@ <LineNumberRevision>,<NumberOfLines> <lineNumberWorkingCopy>,<NumberOfLines> @@
line = readLine();
if (line == null)
{
return null;
}
m = deltaPattern.matcher(line);
if (!m.matches())
{
unreadLine(line);
return null;
}
originalChunk = new JMChunk(Integer.valueOf(m.group(1)), Integer.valueOf(m
.group(2)));
revisedChunk = new JMChunk(Integer.valueOf(m.group(3)), Integer.valueOf(m
.group(4)));
delta = new JMDelta(originalChunk, revisedChunk);
while ((line = readLine()) != null)
{
if (line.startsWith(" "))
{
continue;
}
if (line.startsWith("+"))
{
continue;
}
if (line.startsWith("-"))
{
continue;
}
unreadLine(line);
break;
}
System.out.println("delta = " + delta);
return delta;
}
private void unreadLine(String unreadLine)
{
this.unreadLine = unreadLine;
}
private String readLine()
throws IOException
{
String line;
if (unreadLine != null)
{
line = unreadLine;
unreadLine = null;
return line;
}
return reader.readLine();
}
public static void main(String[] args)
{
DiffCmd cmd;
DiffIF result;
File file = parseFile(args);
if (file == null) {
return;
}
result = new SubversionVersionControl()
.executeDiff(file, true);
if (result != null)
{
for (DiffIF.TargetIF target : result.getTargetList())
{
System.out.println(target.getPath() + " " + target.getRevision());
}
}
}
}
| 4,053 | 0.52529 | 0.524303 | 198 | 18.469696 | 18.280546 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479798 | false | false | 2 |
eaec88a39d79abe3cda3055b10ac43c96643dbaa | 7,980,049,263,892 | 326c1d6b502a4d8fa5f6e293197b0834d407ed87 | /app/src/main/java/com/wf/irulu/module/homenew1_3_0/Fragment/HomeDataListener.java | 609666315c34e2f6e76afd80139bf6b270edb811 | [] | no_license | dtwdtw/IruluNoRong | https://github.com/dtwdtw/IruluNoRong | 3cf0e883fcd8a48f347e4d1ccde1423aa337c8b3 | 7fd4e34517e9c3eba0c228b20256bd1afdaa29f2 | refs/heads/master | 2021-01-12T16:37:09.994000 | 2016-10-20T03:02:14 | 2016-10-20T03:02:14 | 71,419,566 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wf.irulu.module.homenew1_3_0.Fragment;
import com.wf.irulu.common.bean.HomeBean;
/**
* Created by dtw on 16/4/21.
*/
public interface HomeDataListener {
void onHomeBean(HomeBean homeBean);
}
| UTF-8 | Java | 211 | java | HomeDataListener.java | Java | [
{
"context": ".wf.irulu.common.bean.HomeBean;\n\n/**\n * Created by dtw on 16/4/21.\n */\npublic interface HomeDataListener",
"end": 116,
"score": 0.9996797442436218,
"start": 113,
"tag": "USERNAME",
"value": "dtw"
}
] | null | [] | package com.wf.irulu.module.homenew1_3_0.Fragment;
import com.wf.irulu.common.bean.HomeBean;
/**
* Created by dtw on 16/4/21.
*/
public interface HomeDataListener {
void onHomeBean(HomeBean homeBean);
}
| 211 | 0.734597 | 0.696682 | 10 | 20.1 | 19.356911 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 2 |
19d973bf2ccfa3dd922c68b64281d736441cceae | 1,683,627,237,703 | a781a4378987da697cb4f854214b032570f71056 | /Websockets/src/edu/ssu/Websockets/CubeSocketServer.java | d51b35325df7a6867d1ae4419ff0207446378756 | [] | no_license | WoberDesaad/ETEC2104_iCube_Merge | https://github.com/WoberDesaad/ETEC2104_iCube_Merge | 23170a40dcc73dce1b40ac92c019504456f1dd3b | 611f5ae93d0dfc60ec61c3b5ae088ae40d577983 | refs/heads/master | 2021-01-01T03:52:17.933000 | 2016-04-09T13:48:35 | 2016-04-09T13:48:35 | 56,622,616 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ssu.Websockets;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class CubeSocketServer extends WebSocketServer {
WebSocket openGLServer;
ArrayList<WebSocket> clients;
public CubeSocketServer(InetSocketAddress address) {
super(address);
clients = new ArrayList<>();
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("new connection to " + conn.getRemoteSocketAddress());
if(openGLServer == null)
{
this.openGLServer = conn;
}
else
{
if(this.openGLServer != conn)
{
if(this.clients.size() < 4)
{
if(!this.clients.contains(conn))
{
this.clients.add(conn);
}
else
{
conn.send("Connection already Established!");
}
}
else
{
conn.closeConnection(0, "Already too many clients connected!");
}
}
else
{
conn.send("Connection already Established!");
}
}
System.out.println(this.clients.size());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
if(this.clients.contains(conn))
{
this.clients.remove(conn);
}
else if(this.openGLServer == conn)
{
this.openGLServer = null;
for(WebSocket client : this.clients)
{
client.send("Server is down...");
}
}
}
@Override
public void onMessage(WebSocket conn, String message) {
if(conn == this.openGLServer)
{
for(WebSocket client : this.clients)
{
client.send("From Sever to clients: " + message);
}
}
else if(this.clients.contains(conn))
{
this.openGLServer.send("From Clients to server: " + message);
}
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
if(conn == this.openGLServer)
{
for(WebSocket client : this.clients)
{
client.send(message);
}
}
else if(this.clients.contains(conn))
{
this.openGLServer.send(message);
}
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("an error occured on connection " + conn.getRemoteSocketAddress() + ":" + ex);
}
public static void main(String[] args) {
String host = "localhost";
int port = 8887;
WebSocketServer server = new CubeSocketServer(new InetSocketAddress(host, port));
server.run();
}
} | UTF-8 | Java | 3,443 | java | CubeSocketServer.java | Java | [] | null | [] | package edu.ssu.Websockets;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class CubeSocketServer extends WebSocketServer {
WebSocket openGLServer;
ArrayList<WebSocket> clients;
public CubeSocketServer(InetSocketAddress address) {
super(address);
clients = new ArrayList<>();
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("new connection to " + conn.getRemoteSocketAddress());
if(openGLServer == null)
{
this.openGLServer = conn;
}
else
{
if(this.openGLServer != conn)
{
if(this.clients.size() < 4)
{
if(!this.clients.contains(conn))
{
this.clients.add(conn);
}
else
{
conn.send("Connection already Established!");
}
}
else
{
conn.closeConnection(0, "Already too many clients connected!");
}
}
else
{
conn.send("Connection already Established!");
}
}
System.out.println(this.clients.size());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
if(this.clients.contains(conn))
{
this.clients.remove(conn);
}
else if(this.openGLServer == conn)
{
this.openGLServer = null;
for(WebSocket client : this.clients)
{
client.send("Server is down...");
}
}
}
@Override
public void onMessage(WebSocket conn, String message) {
if(conn == this.openGLServer)
{
for(WebSocket client : this.clients)
{
client.send("From Sever to clients: " + message);
}
}
else if(this.clients.contains(conn))
{
this.openGLServer.send("From Clients to server: " + message);
}
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
if(conn == this.openGLServer)
{
for(WebSocket client : this.clients)
{
client.send(message);
}
}
else if(this.clients.contains(conn))
{
this.openGLServer.send(message);
}
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("an error occured on connection " + conn.getRemoteSocketAddress() + ":" + ex);
}
public static void main(String[] args) {
String host = "localhost";
int port = 8887;
WebSocketServer server = new CubeSocketServer(new InetSocketAddress(host, port));
server.run();
}
} | 3,443 | 0.507406 | 0.505664 | 115 | 27.956522 | 24.971773 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 2 |
50d41e26c0ffe25eee7bed1519223f7ce70c13b0 | 2,018,634,688,571 | 95d5bfaa29d739c1755a75029ab0c0a2f3d0286b | /src/com/flynneffectmusic/DMXOPCAdapter/programs/Program.java | 49654201714c896397fd5c5dc9b8ccf98d36f6b8 | [] | no_license | iKadmium/kadmium-artnet-opc | https://github.com/iKadmium/kadmium-artnet-opc | c59aea22913f39820b92b6f6d2a4c43351bf4ce7 | 145f2decc63e22ee28d38a4c53ab477ba7fe7708 | refs/heads/master | 2021-01-17T15:02:57.281000 | 2016-06-03T07:39:02 | 2016-06-03T07:39:02 | 34,435,173 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flynneffectmusic.DMXOPCAdapter.programs;
import com.flynneffectmusic.DMXOPCAdapter.programs.effects.PixelEffect;
import com.flynneffectmusic.DMXOPCAdapter.programs.generators.HSBGenerator;
import com.flynneffectmusic.DMXOPCAdapter.programs.generators.PixelGenerator;
import org.jdom2.Element;
import java.util.ArrayList;
/**
* Created by higginsonj on 1/06/2015.
*/
public class Program
{
PixelGenerator generator;
ArrayList<PixelEffect> effects;
PixelFixture fixture;
private float hue;
private float saturation;
private float brightness;
private Program(PixelFixture fixture, PixelGenerator generator, ArrayList<PixelEffect> effects)
{
this.fixture = fixture;
this.effects = effects;
this.generator = generator;
}
public void Solve(float offset)
{
generator.Generate(fixture, offset);
if (generator != null)
{
generator.Generate(fixture, offset);
}
effects.stream().forEach(effect -> effect.Apply(fixture, offset));
}
public float getHue()
{
return hue;
}
public void setHue(float hue)
{
this.hue = hue;
generator.SetHue(hue);
}
public float getSaturation()
{
return saturation;
}
public void setSaturation(float saturation)
{
this.saturation = saturation;
generator.SetSaturation(saturation);
}
public float getBrightness()
{
return brightness;
}
public void setBrightness(float brightness)
{
this.brightness = brightness;
generator.SetBrightness(brightness);
}
public static Program deserialize(PixelFixture fixture, Element programElement)
{
PixelGenerator generator = PixelGenerator.deserialize(programElement.getChildren().get(0));
Element effectsElement = programElement.getChild("effects");
ArrayList<PixelEffect> effects = new ArrayList<>();
for(Element effectElement : effectsElement.getChildren())
{
PixelEffect effect = PixelEffect.deserialize(effectElement);
effects.add(effect);
}
return new Program(fixture, generator, effects);
}
}
| UTF-8 | Java | 2,239 | java | Program.java | Java | [
{
"context": "t;\n\nimport java.util.ArrayList;\n\n/**\n * Created by higginsonj on 1/06/2015.\n */\npublic class Program\n{\n Pixe",
"end": 364,
"score": 0.9995620846748352,
"start": 354,
"tag": "USERNAME",
"value": "higginsonj"
}
] | null | [] | package com.flynneffectmusic.DMXOPCAdapter.programs;
import com.flynneffectmusic.DMXOPCAdapter.programs.effects.PixelEffect;
import com.flynneffectmusic.DMXOPCAdapter.programs.generators.HSBGenerator;
import com.flynneffectmusic.DMXOPCAdapter.programs.generators.PixelGenerator;
import org.jdom2.Element;
import java.util.ArrayList;
/**
* Created by higginsonj on 1/06/2015.
*/
public class Program
{
PixelGenerator generator;
ArrayList<PixelEffect> effects;
PixelFixture fixture;
private float hue;
private float saturation;
private float brightness;
private Program(PixelFixture fixture, PixelGenerator generator, ArrayList<PixelEffect> effects)
{
this.fixture = fixture;
this.effects = effects;
this.generator = generator;
}
public void Solve(float offset)
{
generator.Generate(fixture, offset);
if (generator != null)
{
generator.Generate(fixture, offset);
}
effects.stream().forEach(effect -> effect.Apply(fixture, offset));
}
public float getHue()
{
return hue;
}
public void setHue(float hue)
{
this.hue = hue;
generator.SetHue(hue);
}
public float getSaturation()
{
return saturation;
}
public void setSaturation(float saturation)
{
this.saturation = saturation;
generator.SetSaturation(saturation);
}
public float getBrightness()
{
return brightness;
}
public void setBrightness(float brightness)
{
this.brightness = brightness;
generator.SetBrightness(brightness);
}
public static Program deserialize(PixelFixture fixture, Element programElement)
{
PixelGenerator generator = PixelGenerator.deserialize(programElement.getChildren().get(0));
Element effectsElement = programElement.getChild("effects");
ArrayList<PixelEffect> effects = new ArrayList<>();
for(Element effectElement : effectsElement.getChildren())
{
PixelEffect effect = PixelEffect.deserialize(effectElement);
effects.add(effect);
}
return new Program(fixture, generator, effects);
}
}
| 2,239 | 0.668155 | 0.664136 | 88 | 24.443182 | 25.373508 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465909 | false | false | 2 |
2e1a6729cedf06e57943ae38ffe79f1faca3ce67 | 20,633,022,933,557 | 6aa5f8bfa92f0a095799fc51f71ab2ae8eddbb46 | /src/abstraction/eq2Producteur2/Producteur2Journaux.java | 9b4a639848a63517956467dcf92504059eaef52d | [] | no_license | Alb1x/CACAO2021 | https://github.com/Alb1x/CACAO2021 | f52dc8e4decd615dacfb5a9a1007bfd1c42d2063 | 145f34a132012154d2686e6865c230b47215f722 | refs/heads/master | 2023-05-24T09:27:55.875000 | 2021-06-09T06:42:52 | 2021-06-09T06:42:52 | 351,017,056 | 1 | 0 | null | true | 2021-04-18T13:56:29 | 2021-03-24T09:19:08 | 2021-04-14T19:07:53 | 2021-04-18T13:56:29 | 891 | 0 | 0 | 7 | Java | false | false | package abstraction.eq2Producteur2;
import java.util.ArrayList;
import java.util.List;
import abstraction.fourni.Filiere;
import abstraction.fourni.Journal;
import abstraction.fourni.Variable;
public abstract class Producteur2Journaux extends Producteur2Acteur {
protected Journal JournalProd, JournalVente, JournalCC,JournalLivraison, JournalStock, JournalPB;
// ensemble fait par DIM
public Producteur2Journaux() {
super();
this.JournalProd= new Journal(this.getNom()+" production", this);
this.JournalVente= new Journal(this.getNom()+" ventes", this);
this.JournalCC= new Journal(this.getNom()+" contrats", this);
this.JournalLivraison= new Journal(this.getNom()+" livraisons", this);
this.JournalStock= new Journal(this.getNom()+" stocks", this);
JournalPB = new Journal(this.getNom()+" révolution des producteurs & autres aléas", this);
}
public void initJournaux() {
this.JournalProd.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalVente.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalCC.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalLivraison.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalStock.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalPB.ajouter("=== initialisation du client "+this.getNom()+" ===");
}
public void majJournaux() {
this.JournalProd.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+ " " + Filiere.LA_FILIERE.getMois() + " ======================");
this.JournalVente.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalCC.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalLivraison.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalStock.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
}
public List<Journal> getJournaux() {
List<Journal> res=new ArrayList<Journal>();
res.add(JournalProd);
res.add(JournalVente);
res.add(JournalCC);
res.add(JournalLivraison);
res.add(JournalStock);
res.add(JournalPB);
return res;
}
} | UTF-8 | Java | 2,225 | java | Producteur2Journaux.java | Java | [] | null | [] | package abstraction.eq2Producteur2;
import java.util.ArrayList;
import java.util.List;
import abstraction.fourni.Filiere;
import abstraction.fourni.Journal;
import abstraction.fourni.Variable;
public abstract class Producteur2Journaux extends Producteur2Acteur {
protected Journal JournalProd, JournalVente, JournalCC,JournalLivraison, JournalStock, JournalPB;
// ensemble fait par DIM
public Producteur2Journaux() {
super();
this.JournalProd= new Journal(this.getNom()+" production", this);
this.JournalVente= new Journal(this.getNom()+" ventes", this);
this.JournalCC= new Journal(this.getNom()+" contrats", this);
this.JournalLivraison= new Journal(this.getNom()+" livraisons", this);
this.JournalStock= new Journal(this.getNom()+" stocks", this);
JournalPB = new Journal(this.getNom()+" révolution des producteurs & autres aléas", this);
}
public void initJournaux() {
this.JournalProd.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalVente.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalCC.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalLivraison.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalStock.ajouter("=== initialisation du client "+this.getNom()+" ===");
this.JournalPB.ajouter("=== initialisation du client "+this.getNom()+" ===");
}
public void majJournaux() {
this.JournalProd.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+ " " + Filiere.LA_FILIERE.getMois() + " ======================");
this.JournalVente.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalCC.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalLivraison.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
this.JournalStock.ajouter("=== Etape "+Filiere.LA_FILIERE.getEtape()+" ======================");
}
public List<Journal> getJournaux() {
List<Journal> res=new ArrayList<Journal>();
res.add(JournalProd);
res.add(JournalVente);
res.add(JournalCC);
res.add(JournalLivraison);
res.add(JournalStock);
res.add(JournalPB);
return res;
}
} | 2,225 | 0.672515 | 0.670265 | 54 | 40.185184 | 36.384811 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.12963 | false | false | 2 |
5f83d3dc5374c3702a4a60d4b6e8e32d41ddca79 | 137,438,979,609 | 8ad99001baa51350c87ba05cef35bf29124d1d71 | /src/main/java/com/zjasm/util/IdmConfigUtil.java | e602a012cd7eb6208017bac26c4dbe0c4432e482 | [
"Apache-2.0"
] | permissive | daix23/cas-overlay-template-5.3 | https://github.com/daix23/cas-overlay-template-5.3 | 9d75165d8e5548e69526140c61ea3eb34c164e10 | 33340bfc00e186839cd5f79235430ac7b754f338 | refs/heads/master | 2021-06-07T05:41:17.918000 | 2020-04-22T08:17:06 | 2020-04-22T08:17:06 | 146,862,964 | 0 | 6 | Apache-2.0 | false | 2020-07-01T20:49:07 | 2018-08-31T08:18:33 | 2020-04-22T08:18:09 | 2020-07-01T20:49:05 | 106,880 | 1 | 3 | 1 | CSS | false | false | package com.zjasm.util;
import com.commnetsoft.IDMConfig;
public class IdmConfigUtil {
private static IdmConfigUtil m_idmConfigUtil = null;
public final static String IDM_KEY_GOV = "idm_gov";
/**
* 获取唯一实例
* @return
*/
public static IdmConfigUtil getInstance(){
if(m_idmConfigUtil==null){
synchronized (IdmConfigUtil.class){
if(m_idmConfigUtil==null){
m_idmConfigUtil = new IdmConfigUtil();
}
}
}
return m_idmConfigUtil;
}
/**
* 构造方法
*/
private IdmConfigUtil(){
PropertiesLoaderUtil propertiesLoaderUtil = PropertiesLoaderUtil.getInstance();
try{
String idmUrl = propertiesLoaderUtil.getOneProp("idmUrl");
String servicecode = propertiesLoaderUtil.getOneProp("servicecode");
String servicepwd = propertiesLoaderUtil.getOneProp("servicepwd");
IDMConfig.createProp(IDM_KEY_GOV, idmUrl, servicecode, servicepwd);
}catch (Exception e){
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,135 | java | IdmConfigUtil.java | Java | [
{
"context": "l;\n\n public final static String IDM_KEY_GOV = \"idm_gov\";\n\n /**\n * 获取唯一实例\n * @return\n */\n ",
"end": 201,
"score": 0.9987748265266418,
"start": 194,
"tag": "KEY",
"value": "idm_gov"
}
] | null | [] | package com.zjasm.util;
import com.commnetsoft.IDMConfig;
public class IdmConfigUtil {
private static IdmConfigUtil m_idmConfigUtil = null;
public final static String IDM_KEY_GOV = "idm_gov";
/**
* 获取唯一实例
* @return
*/
public static IdmConfigUtil getInstance(){
if(m_idmConfigUtil==null){
synchronized (IdmConfigUtil.class){
if(m_idmConfigUtil==null){
m_idmConfigUtil = new IdmConfigUtil();
}
}
}
return m_idmConfigUtil;
}
/**
* 构造方法
*/
private IdmConfigUtil(){
PropertiesLoaderUtil propertiesLoaderUtil = PropertiesLoaderUtil.getInstance();
try{
String idmUrl = propertiesLoaderUtil.getOneProp("idmUrl");
String servicecode = propertiesLoaderUtil.getOneProp("servicecode");
String servicepwd = propertiesLoaderUtil.getOneProp("servicepwd");
IDMConfig.createProp(IDM_KEY_GOV, idmUrl, servicecode, servicepwd);
}catch (Exception e){
e.printStackTrace();
}
}
}
| 1,135 | 0.599103 | 0.599103 | 42 | 25.547619 | 25.847725 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 2 |
45e2ba55cbc52261e05acc6643b8861f974fbf94 | 27,831,388,093,398 | 0a5e60366a4ed63ae186de5ab7eb3fa59983f6d5 | /2.JavaCore/src/com/javarush/task/task18/task1823/Solution.java | 4459f3c2e70e1bd8a89758ba36823af189f7fe07 | [] | no_license | p-agapov/JavaRushTasks | https://github.com/p-agapov/JavaRushTasks | b2f45e648d18b10f28abf963cc6f0fa4a10cdf22 | 94fdfcdadd1876f465dc1bcf8f4d0eae4c06a839 | refs/heads/master | 2021-03-27T14:12:07.320000 | 2018-05-03T09:59:25 | 2018-05-03T09:59:25 | 95,984,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javarush.task.task18.task1823;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/*
Нити и байты
*/
public class Solution {
public static Map<String, Integer> resultMap = new HashMap<>();
public static void main(final String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String fileName;
while (true) {
fileName = bufferedReader.readLine();
if (fileName.equals("exit"))
break;
ReadThread readThread = new ReadThread(fileName);
readThread.start();
}
}
public static class ReadThread extends Thread {
private String fileName;
public ReadThread(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
super.run();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
Map<Byte, Integer> symbolMap = new HashMap<>();
while (fileInputStream.available() > 0) {
byte readerByte = (byte) fileInputStream.read();
if (symbolMap.containsKey(readerByte))
symbolMap.put(readerByte, symbolMap.get(readerByte) + 1);
else
symbolMap.put(readerByte, 1);
}
int max = 0;
int key = 0;
for (Map.Entry<Byte, Integer> entry: symbolMap.entrySet()) {
if (entry.getValue() > max) {
key = entry.getKey();
max = entry.getValue();
}
}
resultMap.put(fileName, key);
fileInputStream.close();
}
catch (Exception e) {}
}
}
}
| UTF-8 | Java | 2,004 | java | Solution.java | Java | [
{
"context": "port java.util.HashMap;\nimport java.util.Map;\n\n/*\nНити и байты\n*/\n\npublic class Solution {\n public st",
"end": 197,
"score": 0.9994611740112305,
"start": 193,
"tag": "NAME",
"value": "Нити"
},
{
"context": "ava.util.HashMap;\nimport java.util.Map;\n\n/*\nНити... | null | [] | package com.javarush.task.task18.task1823;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/*
Нити и байты
*/
public class Solution {
public static Map<String, Integer> resultMap = new HashMap<>();
public static void main(final String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String fileName;
while (true) {
fileName = bufferedReader.readLine();
if (fileName.equals("exit"))
break;
ReadThread readThread = new ReadThread(fileName);
readThread.start();
}
}
public static class ReadThread extends Thread {
private String fileName;
public ReadThread(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
super.run();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
Map<Byte, Integer> symbolMap = new HashMap<>();
while (fileInputStream.available() > 0) {
byte readerByte = (byte) fileInputStream.read();
if (symbolMap.containsKey(readerByte))
symbolMap.put(readerByte, symbolMap.get(readerByte) + 1);
else
symbolMap.put(readerByte, 1);
}
int max = 0;
int key = 0;
for (Map.Entry<Byte, Integer> entry: symbolMap.entrySet()) {
if (entry.getValue() > max) {
key = entry.getKey();
max = entry.getValue();
}
}
resultMap.put(fileName, key);
fileInputStream.close();
}
catch (Exception e) {}
}
}
}
| 2,004 | 0.529589 | 0.524072 | 66 | 29.212122 | 24.183964 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
32f90a62de0107c63771491f5af30c0e62f9471c | 6,648,609,413,223 | 7049ecd6bd4da9cd1416730edae245474d4f46c1 | /src/test/chapter3/ProcessorFile.java | 5e701bfcf4984389ece7d25548f846f980472179 | [] | no_license | demingyang/ThreadTest | https://github.com/demingyang/ThreadTest | 31995cfd39afdfce7e9777de923f0d6e5b6afaee | 6828a3dd6e9915e557442d92f82e21c16e1f891d | refs/heads/master | 2021-05-14T05:02:19.811000 | 2018-04-25T08:43:56 | 2018-04-25T08:43:56 | 116,658,565 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test.chapter3;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by YangDeming on 2017/12/19.
*/
public class ProcessorFile {
public static String processorFile(BufferReaderProcessor brp) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("E:/codeTest/src/data")));
return brp.process(br);
}
@Test
public void test() throws IOException {
String aline = processorFile((BufferedReader br) -> br.readLine());
System.out.println(aline);
}
}
| UTF-8 | Java | 632 | java | ProcessorFile.java | Java | [
{
"context": "er;\nimport java.io.IOException;\n\n/**\n * Created by YangDeming on 2017/12/19.\n */\npublic class ProcessorFile {\n ",
"end": 184,
"score": 0.993285596370697,
"start": 174,
"tag": "USERNAME",
"value": "YangDeming"
}
] | null | [] | package test.chapter3;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by YangDeming on 2017/12/19.
*/
public class ProcessorFile {
public static String processorFile(BufferReaderProcessor brp) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("E:/codeTest/src/data")));
return brp.process(br);
}
@Test
public void test() throws IOException {
String aline = processorFile((BufferedReader br) -> br.readLine());
System.out.println(aline);
}
}
| 632 | 0.699367 | 0.685127 | 24 | 25.25 | 26.788136 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 2 |
d2f97ace32339485b3902304f208c04a51e9f1d0 | 9,878,424,793,972 | 827436a167bcaed1003f8737cd904644ff1992d1 | /old/Nemesis/trunk/Nemesis/src/com/dudhoo/nemesis/swing/produto/categorias/event/SaveCategoriaAdapter.java | b081168401e5cc63dface0b4d17c5571374cfa5a | [] | no_license | edpichler/historyprojects | https://github.com/edpichler/historyprojects | 1a21d48484bda5a1115e87d8e1667cac7f8a410a | 4b2e109a102717a8223fff32295f45132354c7c2 | refs/heads/master | 2016-08-05T08:11:40.425000 | 2010-08-23T13:36:38 | 2010-08-23T13:36:38 | 33,085,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dudhoo.nemesis.swing.produto.categorias.event;
import com.dudhoo.evilframework.swing.EvilError;
import com.dudhoo.evilframework.swing.EvilInformation;
import com.dudhoo.nemesis.event.SavePressListener;
import com.dudhoo.nemesis.hibernate.CategoriaProdutoHome;
import com.dudhoo.nemesis.swing.StartFrame;
import com.dudhoo.nemesis.swing.produto.categorias.JDialogCategoria;
import com.dudhoo.nemesis.swing.produto.categorias.PanelCategoria;
public class SaveCategoriaAdapter implements SavePressListener {
JDialogCategoria dialog = null;
public SaveCategoriaAdapter(JDialogCategoria _dial) {
dialog = _dial;
}
public void doAfterClick() {
CategoriaProdutoHome home = new CategoriaProdutoHome();
try {
home.saveOrUpdate(dialog.getCategoriaProduto());
new EvilInformation(dialog).showMessage("Salvo com sucesso!");
dialog.close();
} catch (Exception ex) {
new EvilError(StartFrame.getCurrentInstance(), true,
ex).setVisible(true);
} finally {
home.closeSession();
}
}
}
| UTF-8 | Java | 1,173 | java | SaveCategoriaAdapter.java | Java | [] | null | [] | package com.dudhoo.nemesis.swing.produto.categorias.event;
import com.dudhoo.evilframework.swing.EvilError;
import com.dudhoo.evilframework.swing.EvilInformation;
import com.dudhoo.nemesis.event.SavePressListener;
import com.dudhoo.nemesis.hibernate.CategoriaProdutoHome;
import com.dudhoo.nemesis.swing.StartFrame;
import com.dudhoo.nemesis.swing.produto.categorias.JDialogCategoria;
import com.dudhoo.nemesis.swing.produto.categorias.PanelCategoria;
public class SaveCategoriaAdapter implements SavePressListener {
JDialogCategoria dialog = null;
public SaveCategoriaAdapter(JDialogCategoria _dial) {
dialog = _dial;
}
public void doAfterClick() {
CategoriaProdutoHome home = new CategoriaProdutoHome();
try {
home.saveOrUpdate(dialog.getCategoriaProduto());
new EvilInformation(dialog).showMessage("Salvo com sucesso!");
dialog.close();
} catch (Exception ex) {
new EvilError(StartFrame.getCurrentInstance(), true,
ex).setVisible(true);
} finally {
home.closeSession();
}
}
}
| 1,173 | 0.684569 | 0.684569 | 33 | 33.545456 | 25.267168 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 2 |
665cee8d3e1889aeefaae012b8c99cb25d0a81b8 | 14,688,788,163,830 | 857a460a6c8335e099a83d2e7b671618a71b0464 | /src/main/java/com/lb/member/model/MemberWithdraw.java | 87ebb9d08c9064805314b3ab60e5af9379eb54e7 | [] | no_license | zxcv1122BB/lb_n | https://github.com/zxcv1122BB/lb_n | bce2e7c456f4628d615b707f4931bc12c5feff52 | 9a0a3eb156bb94d66c9176de1e5d506fabecc50e | refs/heads/master | 2022-07-10T01:18:47.642000 | 2019-08-26T14:55:01 | 2019-08-26T14:55:01 | 203,388,208 | 1 | 1 | null | false | 2022-06-29T17:35:23 | 2019-08-20T14:01:58 | 2020-06-06T17:03:58 | 2022-06-29T17:35:21 | 17,955 | 1 | 0 | 7 | JavaScript | false | false | package com.lb.member.model;
import java.util.Date;
public class MemberWithdraw {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String orderId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Integer uid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte userType;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String userName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Float amount;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String accountId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String account;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String accountName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte state;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Date applyTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Long operateUid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String operateIp;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String operateUser;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Date operateTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte payType;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String info;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.id
*
* @return the value of member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.id
*
* @param id the value for member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.order_id
*
* @return the value of member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOrderId() {
return orderId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.order_id
*
* @param orderId the value for member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.uid
*
* @return the value of member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Integer getUid() {
return uid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.uid
*
* @param uid the value for member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUid(Integer uid) {
this.uid = uid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.user_type
*
* @return the value of member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getUserType() {
return userType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.user_type
*
* @param userType the value for member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUserType(Byte userType) {
this.userType = userType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.user_name
*
* @return the value of member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getUserName() {
return userName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.user_name
*
* @param userName the value for member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.name
*
* @return the value of member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.name
*
* @param name the value for member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.amount
*
* @return the value of member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Float getAmount() {
return amount;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.amount
*
* @param amount the value for member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAmount(Float amount) {
this.amount = amount;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account_Id
*
* @return the value of member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccountId() {
return accountId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account_Id
*
* @param accountId the value for member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccountId(String accountId) {
this.accountId = accountId == null ? null : accountId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account
*
* @return the value of member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccount() {
return account;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account
*
* @param account the value for member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account_name
*
* @return the value of member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccountName() {
return accountName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account_name
*
* @param accountName the value for member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccountName(String accountName) {
this.accountName = accountName == null ? null : accountName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.state
*
* @return the value of member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getState() {
return state;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.state
*
* @param state the value for member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setState(Byte state) {
this.state = state;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.apply_time
*
* @return the value of member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Date getApplyTime() {
return applyTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.apply_time
*
* @param applyTime the value for member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_uid
*
* @return the value of member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Long getOperateUid() {
return operateUid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_uid
*
* @param operateUid the value for member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateUid(Long operateUid) {
this.operateUid = operateUid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_ip
*
* @return the value of member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOperateIp() {
return operateIp;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_ip
*
* @param operateIp the value for member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateIp(String operateIp) {
this.operateIp = operateIp == null ? null : operateIp.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_user
*
* @return the value of member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOperateUser() {
return operateUser;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_user
*
* @param operateUser the value for member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateUser(String operateUser) {
this.operateUser = operateUser == null ? null : operateUser.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_time
*
* @return the value of member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Date getOperateTime() {
return operateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_time
*
* @param operateTime the value for member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateTime(Date operateTime) {
this.operateTime = operateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.pay_type
*
* @return the value of member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getPayType() {
return payType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.pay_type
*
* @param payType the value for member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setPayType(Byte payType) {
this.payType = payType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.info
*
* @return the value of member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getInfo() {
return info;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.info
*
* @param info the value for member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setInfo(String info) {
this.info = info == null ? null : info.trim();
}
} | UTF-8 | Java | 17,350 | java | MemberWithdraw.java | Java | [] | null | [] | package com.lb.member.model;
import java.util.Date;
public class MemberWithdraw {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String orderId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Integer uid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte userType;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String userName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Float amount;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String accountId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String account;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String accountName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte state;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Date applyTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Long operateUid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String operateIp;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String operateUser;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Date operateTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private Byte payType;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
private String info;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.id
*
* @return the value of member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.id
*
* @param id the value for member_withdraw.id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.order_id
*
* @return the value of member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOrderId() {
return orderId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.order_id
*
* @param orderId the value for member_withdraw.order_id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.uid
*
* @return the value of member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Integer getUid() {
return uid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.uid
*
* @param uid the value for member_withdraw.uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUid(Integer uid) {
this.uid = uid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.user_type
*
* @return the value of member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getUserType() {
return userType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.user_type
*
* @param userType the value for member_withdraw.user_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUserType(Byte userType) {
this.userType = userType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.user_name
*
* @return the value of member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getUserName() {
return userName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.user_name
*
* @param userName the value for member_withdraw.user_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.name
*
* @return the value of member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.name
*
* @param name the value for member_withdraw.name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.amount
*
* @return the value of member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Float getAmount() {
return amount;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.amount
*
* @param amount the value for member_withdraw.amount
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAmount(Float amount) {
this.amount = amount;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account_Id
*
* @return the value of member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccountId() {
return accountId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account_Id
*
* @param accountId the value for member_withdraw.account_Id
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccountId(String accountId) {
this.accountId = accountId == null ? null : accountId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account
*
* @return the value of member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccount() {
return account;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account
*
* @param account the value for member_withdraw.account
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.account_name
*
* @return the value of member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getAccountName() {
return accountName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.account_name
*
* @param accountName the value for member_withdraw.account_name
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setAccountName(String accountName) {
this.accountName = accountName == null ? null : accountName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.state
*
* @return the value of member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getState() {
return state;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.state
*
* @param state the value for member_withdraw.state
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setState(Byte state) {
this.state = state;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.apply_time
*
* @return the value of member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Date getApplyTime() {
return applyTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.apply_time
*
* @param applyTime the value for member_withdraw.apply_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_uid
*
* @return the value of member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Long getOperateUid() {
return operateUid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_uid
*
* @param operateUid the value for member_withdraw.operate_uid
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateUid(Long operateUid) {
this.operateUid = operateUid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_ip
*
* @return the value of member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOperateIp() {
return operateIp;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_ip
*
* @param operateIp the value for member_withdraw.operate_ip
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateIp(String operateIp) {
this.operateIp = operateIp == null ? null : operateIp.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_user
*
* @return the value of member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getOperateUser() {
return operateUser;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_user
*
* @param operateUser the value for member_withdraw.operate_user
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateUser(String operateUser) {
this.operateUser = operateUser == null ? null : operateUser.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.operate_time
*
* @return the value of member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Date getOperateTime() {
return operateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.operate_time
*
* @param operateTime the value for member_withdraw.operate_time
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setOperateTime(Date operateTime) {
this.operateTime = operateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.pay_type
*
* @return the value of member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public Byte getPayType() {
return payType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.pay_type
*
* @param payType the value for member_withdraw.pay_type
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setPayType(Byte payType) {
this.payType = payType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column member_withdraw.info
*
* @return the value of member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public String getInfo() {
return info;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column member_withdraw.info
*
* @param info the value for member_withdraw.info
*
* @mbg.generated Wed Nov 22 15:06:14 CST 2017
*/
public void setInfo(String info) {
this.info = info == null ? null : info.trim();
}
} | 17,350 | 0.630086 | 0.592738 | 599 | 27.966612 | 26.600405 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.093489 | false | false | 2 |
3466a04ea4877e388253ecc7f62373e1c02b861f | 1,254,130,460,791 | 8fa22f5aaf9f3bb83879267b586f3b7e3ac9e219 | /src/edu/cmu/tetrad/search/SepsetsConservativeConsumerProducer.java | e9e06fe42523ec5bc4d3ded730d132f586362ea2 | [] | no_license | tyler-lovelace1/tetrad-censored | https://github.com/tyler-lovelace1/tetrad-censored | 795e3970fbd562f07bd083ff3fa99d2eaf9f8162 | 94983ee578ddacec924048ba55b06844f26457f5 | refs/heads/master | 2023-01-16T08:23:41.174000 | 2020-11-13T22:29:01 | 2020-11-13T22:29:01 | 259,706,930 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.search;
import edu.cmu.tetrad.data.ContinuousVariable;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.GraphUtils;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.graph.Triple;
import edu.cmu.tetrad.util.ChoiceGenerator;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicIntegerArray;
/**
* Created by josephramsey on 3/24/15.
*/
public class SepsetsConservativeConsumerProducer implements SepsetProducer {
private final Graph graph;
private final IndependenceTest independenceTest;
private final SepsetMap extraSepsets;
private int depth = 3;
private boolean verbose = true;
// private ConcurrentMap<Triple, List<Integer>> tripleMap;
private ConcurrentMap<Triple, AtomicIntegerArray> tripleMap;
// private ConcurrentMap<Set<Node>, List<Node>> maxPSepsetMap;
private int parallelism;
private ExecutorService executorService;
// private double chunk = 5;
// private double factor = 1.25;
// private ForkJoinPool pool;
// private ForkJoinPool pool = ForkJoinPoolInstance.getInstance().getPool();
public SepsetsConservativeConsumerProducer(Graph graph, IndependenceTest independenceTest, SepsetMap extraSepsets, int depth) {
this.graph = graph;
this.independenceTest = independenceTest;
this.extraSepsets = extraSepsets;
this.depth = depth;
this.parallelism = Runtime.getRuntime().availableProcessors();
}
/**
* Pick out the sepset from among adj(i) or adj(k) with the highest p value.
*/
public List<Node> getSepset(Node i, Node k) {
double _p = 0.0;
List<Node> _v = null;
if (extraSepsets != null) {
final List<Node> possibleDsep = extraSepsets.get(i, k);
if (possibleDsep != null) {
independenceTest.isIndependent(i, k, possibleDsep);
_p = independenceTest.getPValue();
_v = possibleDsep;
}
}
List<Node> adji = graph.getAdjacentNodes(i);
List<Node> adjk = graph.getAdjacentNodes(k);
adji.remove(k);
adjk.remove(i);
for (int d = 0; d <= Math.min((depth == -1 ? 1000 : depth), Math.max(adji.size(), adjk.size())); d++) {
if (d <= adji.size()) {
ChoiceGenerator gen = new ChoiceGenerator(adji.size(), d);
int[] choice;
while ((choice = gen.next()) != null) {
List<Node> v = GraphUtils.asList(choice, adji);
if (getIndependenceTest().isIndependent(i, k, v)) {
double pValue = getIndependenceTest().getPValue();
if (pValue > _p) {
_p = pValue;
_v = v;
}
}
}
}
if (d <= adjk.size()) {
ChoiceGenerator gen = new ChoiceGenerator(adjk.size(), d);
int[] choice;
while ((choice = gen.next()) != null) {
List<Node> v = GraphUtils.asList(choice, adjk);
if (getIndependenceTest().isIndependent(i, k, v)) {
double pValue = getIndependenceTest().getPValue();
if (pValue > _p) {
_p = pValue;
_v = v;
}
}
}
}
}
return _v;
}
public boolean isCollider(Node i, Node j, Node k) {
if (j.getName()=="survival"){
System.out.println("checking for collider centered on survival");
}
AtomicIntegerArray ret = tripleMap.get(new Triple(i, j, k));
System.out.println(new Triple(i, j, k) + "\t\t" + ret);
if (j.getName()=="survival"){
System.out.println("number of sepsets with survival:\t" + ret.get(0));
System.out.println("number of sepsets without survival:\t" + ret.get(1));
}
if (ret == null) {
System.out.println("unknown triple being requested");
List<List<List<Node>>> sepsetsLists = getSepsetsLists(i, j, k, independenceTest, depth, true);
AtomicIntegerArray temp = new AtomicIntegerArray(2);
temp.set(0, sepsetsLists.get(0).size());
temp.set(1, sepsetsLists.get(1).size());
// if ((temp.get(0) == 0) & (temp.get(1) == 0)) {
// System.out.println("Added: " + i + " o-o " + k);
// graph.addNondirectedEdge(i, k);
// return false;
// }
tripleMap.put(new Triple(i, j, k), temp);
ret = temp;
System.out.println("unknown triple added");
}
return (ret.get(0) == 0) & (ret.get(1) != 0);
}
public boolean isNoncollider(Node i, Node j, Node k) {
// List<List<List<Node>>> ret = sepsetsListsMap.get(new Triple(i, j, k));
AtomicIntegerArray ret = tripleMap.get(new Triple(i, j, k));
if (ret == null) {
System.out.println("unknown triple being requested");
List<List<List<Node>>> sepsetsLists = getSepsetsLists(i, j, k, independenceTest, depth, true);
AtomicIntegerArray temp = new AtomicIntegerArray(2);
temp.set(0, sepsetsLists.get(0).size());
temp.set(1, sepsetsLists.get(1).size());
// if ((temp.get(0) == 0) & (temp.get(1) == 0)) {
// System.out.println("Added: " + i + " o-o " + k);
// graph.addNondirectedEdge(i, k);
// return true;
// }
tripleMap.put(new Triple(i, j, k), temp);
ret = temp;
// ret = getSepsetsLists(i, j, k, independenceTest, depth, true);
// sepsetsListsMap.put(new Triple(i, j, k), ret);
System.out.println("unknown triple added");
}
return (ret.get(0) != 0) & (ret.get(1) == 0);
}
// The published version.
public List<List<List<Node>>> getSepsetsLists(Node x, Node y, Node z,
IndependenceTest test, int depth,
boolean verbose) {
List<List<Node>> sepsetsContainingY = new ArrayList<>();
List<List<Node>> sepsetsNotContainingY = new ArrayList<>();
List<Node> _nodes = graph.getAdjacentNodes(x);
_nodes.remove(z);
int _depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
if (test.isIndependent(x, z, cond)) {
if (verbose) {
System.out.println("Indep: " + x + " _||_ " + z + " | " + cond);
}
if (cond.contains(y)) {
sepsetsContainingY.add(cond);
} else {
sepsetsNotContainingY.add(cond);
}
}
}
}
_nodes = graph.getAdjacentNodes(z);
_nodes.remove(x);
_depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
if (test.isIndependent(x, z, cond)) {
if (cond.contains(y)) {
sepsetsContainingY.add(cond);
} else {
sepsetsNotContainingY.add(cond);
}
}
}
}
List<List<List<Node>>> ret = new ArrayList<>();
ret.add(sepsetsContainingY);
ret.add(sepsetsNotContainingY);
return ret;
}
class ColliderTask {
public Triple triple;
public Node x;
public Node y;
public List<Node> z;
public ColliderTask(Triple triple, Node x, Node y, List<Node> z) {
this.triple = triple;
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (!(o instanceof ColliderTask)) {
return false;
} else if ( ((ColliderTask) o).triple != this.triple) {
return false;
} else if ( ((ColliderTask) o).x != this.x) {
return false;
} else if ( ((ColliderTask) o).y != this.y) {
return false;
} else if ( ((ColliderTask) o).z != this.z) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format(triple + " | " + z);
}
}
private class Broker {
private int capacity = 100000;
public LinkedBlockingQueue<ColliderTask> queue = new LinkedBlockingQueue<>(capacity);
public void put(ColliderTask task) throws InterruptedException {
queue.put(task);
}
public ColliderTask get() throws InterruptedException {
return queue.poll(1, TimeUnit.SECONDS);
}
}
private class SepsetsCountsProducer implements Runnable {
private Broker broker;
private ColliderTask poisonPill;
public SepsetsCountsProducer(Broker broker, final ColliderTask poisonPill) {
this.broker = broker;
this.poisonPill = poisonPill;
}
@Override
public void run() {
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsProducer Start");
final List<Node> nodes = graph.getNodes();
try {
for (int i = 0; i < nodes.size(); i ++) {
final Node b = nodes.get(i);
final List<Node> adjacent = graph.getAdjacentNodes(b);
//only compare to nodes less than it in index
if (adjacent.size() < 2)
continue;
ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(), 2);
int[] combination;
while ((combination = cg.next()) != null) {
final Node a = adjacent.get(combination[0]);
final Node c = adjacent.get(combination[1]);
if (graph.isAdjacentTo(a, c))
continue;
AtomicIntegerArray sepsetCounts = new AtomicIntegerArray(2);
// sepsetCounts.add(0);
// sepsetCounts.add(0);
Triple curTriple = new Triple(a, b, c);
tripleMap.put(curTriple, sepsetCounts);
List<Node> _nodes = graph.getAdjacentNodes(a);
_nodes.remove(c);
int _depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg2 = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg2.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
broker.put(new ColliderTask(curTriple, a, c, cond));
}
}
_nodes = graph.getAdjacentNodes(c);
_nodes.remove(a);
_depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg2 = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg2.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
broker.put(new ColliderTask(curTriple, a, c, cond));
}
}
}
}
broker.put(poisonPill);
broker.put(poisonPill);
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsProducer Finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class SepsetsCountsConsumer implements Runnable {
private Broker broker;
private ColliderTask poisonPill;
private IndependenceTest test;
public SepsetsCountsConsumer(Broker broker, IndependenceTest test, final ColliderTask poisonPill) {
this.broker = broker;
this.test = test;
this.poisonPill = poisonPill;
}
@Override
public void run() {
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsConsumer Start");
try {
ColliderTask task = broker.get();
while (task != poisonPill) {
if (task == null) {
task = broker.get();
continue;
}
if (test.isIndependent(task.x, task.y, task.z)) {
if (verbose) {
System.out.println("Indep: " + task.x + " _||_ " + task.y + " | " + task.z);
}
int idx = (task.z.contains(task.triple.getY())) ? 0 : 1;
int curr;
do {
curr = tripleMap.get(task.triple).get(idx);
} while (!tripleMap.get(task.triple).compareAndSet(idx, curr, curr+1));
// tripleMap.get(task.triple).incrementAndGet(idx);
// tripleMap.compute(task.triple, (k , v) -> {
// v.incrementAndGet(idx);
// return v;
// });
// if (task.z.contains(task.triple.getY())) {
// tripleMap.get(task.triple).set(0, tripleMap.get(task.triple).get(0)+1);
// } else {
// tripleMap.get(task.triple).set(1, tripleMap.get(task.triple).get(1)+1);
// }
}
task = broker.get();
}
broker.put(poisonPill);
broker.put(poisonPill);
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsConsumer Finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void fillSepsetsCountsMap() {
this.tripleMap = new ConcurrentHashMap<>();
this.executorService = Executors.newFixedThreadPool(parallelism+1);
System.out.println("Begin concurrent fillSepsetsCountsMap");
Broker broker = new Broker();
List<Future> status = new ArrayList<>();
Node x = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
Node y = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
Node z = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
ColliderTask poisonPill = new ColliderTask(new Triple(x,y,z), x, z, new ArrayList<>());
System.out.println("PoisonPill: " + poisonPill);
try {
status.add(executorService.submit(new SepsetsCountsProducer(broker, poisonPill)));
for (int i = 0; i < parallelism; i++) {
status.add(executorService.submit(new SepsetsCountsConsumer(broker, independenceTest.clone(), poisonPill)));
}
for (int i = 0; i < parallelism+1; i++) {
status.get(i).get();
}
} catch (Exception e) {
e.printStackTrace();
}
executorService.shutdown();
// boolean edgeAdded = false;
//
// List<Node> nodes = graph.getNodes();
// Map<Node, List<Node>> adjacencies = new HashMap<>();
//
// for (Node n : nodes) {
// adjacencies.put(n, new ArrayList<>(graph.getAdjacentNodes(n)));
// }
//
// for (int i = 0; i < nodes.size(); i ++) {
// final Node b = nodes.get(i);
// final List<Node> adjacent = adjacencies.get(b);
// //only compare to nodes less than it in index
// if (adjacent.size() < 2)
// continue;
// ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(), 2);
// int[] combination;
// while ((combination = cg.next()) != null) {
// final Node a = adjacent.get(combination[0]);
// final Node c = adjacent.get(combination[1]);
// if (adjacencies.get(a).contains(c) | adjacencies.get(c).contains(a))
// continue;
//
// Triple curTriple = new Triple(a, b, c);
//
// AtomicIntegerArray ret = tripleMap.get(curTriple);
// if ((ret.get(0) == 0) & (ret.get(1) == 0)) {
// System.out.println("Added: " + a + " --- " + c);
// graph.addUndirectedEdge(a, c);
// edgeAdded=true;
// }
// }
// }
System.out.println("End of concurrent fillSepsetsCountsMap");
// return edgeAdded;
// final HashMap<Integer,Integer> powerSetSizes = new HashMap<>();
// final List<Node> nodes = graph.getNodes();
// int sum = 0;
// int psSum;
// for(int i = 0; i < nodes.size();i++)
// {
// psSum = 0;
// List<Node> adjNodes = graph.getAdjacentNodes(nodes.get(i));
// for (int j = 0; j < adjNodes.size(); j++)
// {
// psSum += Math.pow(2, graph.getAdjacentNodes(adjNodes.get(j)).size()-1);
// }
// powerSetSizes.put(i, psSum);
// sum += psSum;
// }
// chunk = sum/(parallelism) * factor;
//
// class colliderTask extends RecursiveTask<Boolean> {
// private double chunk;
// private int from;
// private int to;
// public colliderTask(double chunk,int from, int to)
// {
// this.chunk = chunk;
// this.from = from;
// this.to = to;
// }
// protected Boolean compute()
// {
// int numTests = 0;
// for(int j = from; j < to; j++)
// {
// numTests += powerSetSizes.get(j);
// }
// if(to-from <= 2 || numTests <= chunk)
// {
// System.out.println(Thread.currentThread().getName() + ": " + numTests + " / " + chunk);
// for(int i = from; i < to; i ++)
// {
// final Node b = nodes.get(i);
// final List<Node> adjacent = graph.getAdjacentNodes(b);
// //only compare to nodes less than it in index
// if(adjacent.size()<2)
// continue;
// ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(),2);
// int [] combination;
// while((combination = cg.next()) != null)
// {
// final Node a = adjacent.get(combination[0]);
// final Node c = adjacent.get(combination[1]);
// if(graph.isAdjacentTo(a,c))
// continue;
//
// List<List<List<Node>>> ret = getSepsetsLists(a, b, c, independenceTest, depth, verbose);
//
// List<Integer> temp = new ArrayList<>();
// temp.add(ret.get(0).size());
// temp.add(ret.get(1).size());
// tripleMap.put(new Triple(a, b, c), temp);
//
// if (temp.get(0) == temp.get(1)) {
// System.out.println("Ambiguous Triple: " + new Triple(a, b, c) + ": " + temp.get(0) + ", " + temp.get(1));
// }
//
//// sepsetsListsMap.put(new Triple(a,b,c), ret);
// }
// }
// System.out.println(Thread.currentThread().getName() + ": Finished");
// return true;
// }
// else
// {
// List<colliderTask> tasks = new ArrayList<>();
// final int mid = (to+from)/2;
// colliderTask t1 = new colliderTask(chunk,from,mid);
// tasks.add(t1);
// colliderTask t2 = new colliderTask(chunk,mid,to);
// tasks.add(t2);
// invokeAll(tasks);
// return true;
// }
//
// }
// }
// pool.invoke(new colliderTask(chunk,0,nodes.size()));
}
@Override
public boolean isIndependent(Node a, Node b, List<Node> c) {
return independenceTest.isIndependent(a, b, c);
}
@Override
public double getPValue() {
return independenceTest.getPValue();
}
@Override
public double getScore() {
return -(independenceTest.getPValue() - independenceTest.getAlpha());
}
@Override
public List<Node> getVariables() {
return independenceTest.getVariables();
}
@Override
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public IndependenceTest getIndependenceTest() {
return independenceTest;
}
}
| UTF-8 | Java | 24,585 | java | SepsetsConservativeConsumerProducer.java | Java | [
{
"context": " //\n// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //\n// Ramsey, and Cla",
"end": 294,
"score": 0.9998379945755005,
"start": 281,
"tag": "NAME",
"value": "Peter Spirtes"
},
{
"context": "07, 2008, 2009, 2010, 2014, 2015 by Pet... | null | [] | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by <NAME>, <NAME>, Joseph //
// Ramsey, and <NAME>. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.search;
import edu.cmu.tetrad.data.ContinuousVariable;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.GraphUtils;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.graph.Triple;
import edu.cmu.tetrad.util.ChoiceGenerator;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicIntegerArray;
/**
* Created by josephramsey on 3/24/15.
*/
public class SepsetsConservativeConsumerProducer implements SepsetProducer {
private final Graph graph;
private final IndependenceTest independenceTest;
private final SepsetMap extraSepsets;
private int depth = 3;
private boolean verbose = true;
// private ConcurrentMap<Triple, List<Integer>> tripleMap;
private ConcurrentMap<Triple, AtomicIntegerArray> tripleMap;
// private ConcurrentMap<Set<Node>, List<Node>> maxPSepsetMap;
private int parallelism;
private ExecutorService executorService;
// private double chunk = 5;
// private double factor = 1.25;
// private ForkJoinPool pool;
// private ForkJoinPool pool = ForkJoinPoolInstance.getInstance().getPool();
public SepsetsConservativeConsumerProducer(Graph graph, IndependenceTest independenceTest, SepsetMap extraSepsets, int depth) {
this.graph = graph;
this.independenceTest = independenceTest;
this.extraSepsets = extraSepsets;
this.depth = depth;
this.parallelism = Runtime.getRuntime().availableProcessors();
}
/**
* Pick out the sepset from among adj(i) or adj(k) with the highest p value.
*/
public List<Node> getSepset(Node i, Node k) {
double _p = 0.0;
List<Node> _v = null;
if (extraSepsets != null) {
final List<Node> possibleDsep = extraSepsets.get(i, k);
if (possibleDsep != null) {
independenceTest.isIndependent(i, k, possibleDsep);
_p = independenceTest.getPValue();
_v = possibleDsep;
}
}
List<Node> adji = graph.getAdjacentNodes(i);
List<Node> adjk = graph.getAdjacentNodes(k);
adji.remove(k);
adjk.remove(i);
for (int d = 0; d <= Math.min((depth == -1 ? 1000 : depth), Math.max(adji.size(), adjk.size())); d++) {
if (d <= adji.size()) {
ChoiceGenerator gen = new ChoiceGenerator(adji.size(), d);
int[] choice;
while ((choice = gen.next()) != null) {
List<Node> v = GraphUtils.asList(choice, adji);
if (getIndependenceTest().isIndependent(i, k, v)) {
double pValue = getIndependenceTest().getPValue();
if (pValue > _p) {
_p = pValue;
_v = v;
}
}
}
}
if (d <= adjk.size()) {
ChoiceGenerator gen = new ChoiceGenerator(adjk.size(), d);
int[] choice;
while ((choice = gen.next()) != null) {
List<Node> v = GraphUtils.asList(choice, adjk);
if (getIndependenceTest().isIndependent(i, k, v)) {
double pValue = getIndependenceTest().getPValue();
if (pValue > _p) {
_p = pValue;
_v = v;
}
}
}
}
}
return _v;
}
public boolean isCollider(Node i, Node j, Node k) {
if (j.getName()=="survival"){
System.out.println("checking for collider centered on survival");
}
AtomicIntegerArray ret = tripleMap.get(new Triple(i, j, k));
System.out.println(new Triple(i, j, k) + "\t\t" + ret);
if (j.getName()=="survival"){
System.out.println("number of sepsets with survival:\t" + ret.get(0));
System.out.println("number of sepsets without survival:\t" + ret.get(1));
}
if (ret == null) {
System.out.println("unknown triple being requested");
List<List<List<Node>>> sepsetsLists = getSepsetsLists(i, j, k, independenceTest, depth, true);
AtomicIntegerArray temp = new AtomicIntegerArray(2);
temp.set(0, sepsetsLists.get(0).size());
temp.set(1, sepsetsLists.get(1).size());
// if ((temp.get(0) == 0) & (temp.get(1) == 0)) {
// System.out.println("Added: " + i + " o-o " + k);
// graph.addNondirectedEdge(i, k);
// return false;
// }
tripleMap.put(new Triple(i, j, k), temp);
ret = temp;
System.out.println("unknown triple added");
}
return (ret.get(0) == 0) & (ret.get(1) != 0);
}
public boolean isNoncollider(Node i, Node j, Node k) {
// List<List<List<Node>>> ret = sepsetsListsMap.get(new Triple(i, j, k));
AtomicIntegerArray ret = tripleMap.get(new Triple(i, j, k));
if (ret == null) {
System.out.println("unknown triple being requested");
List<List<List<Node>>> sepsetsLists = getSepsetsLists(i, j, k, independenceTest, depth, true);
AtomicIntegerArray temp = new AtomicIntegerArray(2);
temp.set(0, sepsetsLists.get(0).size());
temp.set(1, sepsetsLists.get(1).size());
// if ((temp.get(0) == 0) & (temp.get(1) == 0)) {
// System.out.println("Added: " + i + " o-o " + k);
// graph.addNondirectedEdge(i, k);
// return true;
// }
tripleMap.put(new Triple(i, j, k), temp);
ret = temp;
// ret = getSepsetsLists(i, j, k, independenceTest, depth, true);
// sepsetsListsMap.put(new Triple(i, j, k), ret);
System.out.println("unknown triple added");
}
return (ret.get(0) != 0) & (ret.get(1) == 0);
}
// The published version.
public List<List<List<Node>>> getSepsetsLists(Node x, Node y, Node z,
IndependenceTest test, int depth,
boolean verbose) {
List<List<Node>> sepsetsContainingY = new ArrayList<>();
List<List<Node>> sepsetsNotContainingY = new ArrayList<>();
List<Node> _nodes = graph.getAdjacentNodes(x);
_nodes.remove(z);
int _depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
if (test.isIndependent(x, z, cond)) {
if (verbose) {
System.out.println("Indep: " + x + " _||_ " + z + " | " + cond);
}
if (cond.contains(y)) {
sepsetsContainingY.add(cond);
} else {
sepsetsNotContainingY.add(cond);
}
}
}
}
_nodes = graph.getAdjacentNodes(z);
_nodes.remove(x);
_depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
if (test.isIndependent(x, z, cond)) {
if (cond.contains(y)) {
sepsetsContainingY.add(cond);
} else {
sepsetsNotContainingY.add(cond);
}
}
}
}
List<List<List<Node>>> ret = new ArrayList<>();
ret.add(sepsetsContainingY);
ret.add(sepsetsNotContainingY);
return ret;
}
class ColliderTask {
public Triple triple;
public Node x;
public Node y;
public List<Node> z;
public ColliderTask(Triple triple, Node x, Node y, List<Node> z) {
this.triple = triple;
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (!(o instanceof ColliderTask)) {
return false;
} else if ( ((ColliderTask) o).triple != this.triple) {
return false;
} else if ( ((ColliderTask) o).x != this.x) {
return false;
} else if ( ((ColliderTask) o).y != this.y) {
return false;
} else if ( ((ColliderTask) o).z != this.z) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format(triple + " | " + z);
}
}
private class Broker {
private int capacity = 100000;
public LinkedBlockingQueue<ColliderTask> queue = new LinkedBlockingQueue<>(capacity);
public void put(ColliderTask task) throws InterruptedException {
queue.put(task);
}
public ColliderTask get() throws InterruptedException {
return queue.poll(1, TimeUnit.SECONDS);
}
}
private class SepsetsCountsProducer implements Runnable {
private Broker broker;
private ColliderTask poisonPill;
public SepsetsCountsProducer(Broker broker, final ColliderTask poisonPill) {
this.broker = broker;
this.poisonPill = poisonPill;
}
@Override
public void run() {
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsProducer Start");
final List<Node> nodes = graph.getNodes();
try {
for (int i = 0; i < nodes.size(); i ++) {
final Node b = nodes.get(i);
final List<Node> adjacent = graph.getAdjacentNodes(b);
//only compare to nodes less than it in index
if (adjacent.size() < 2)
continue;
ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(), 2);
int[] combination;
while ((combination = cg.next()) != null) {
final Node a = adjacent.get(combination[0]);
final Node c = adjacent.get(combination[1]);
if (graph.isAdjacentTo(a, c))
continue;
AtomicIntegerArray sepsetCounts = new AtomicIntegerArray(2);
// sepsetCounts.add(0);
// sepsetCounts.add(0);
Triple curTriple = new Triple(a, b, c);
tripleMap.put(curTriple, sepsetCounts);
List<Node> _nodes = graph.getAdjacentNodes(a);
_nodes.remove(c);
int _depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg2 = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg2.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
broker.put(new ColliderTask(curTriple, a, c, cond));
}
}
_nodes = graph.getAdjacentNodes(c);
_nodes.remove(a);
_depth = depth;
if (_depth == -1) {
_depth = 1000;
}
_depth = Math.min(_depth, _nodes.size());
for (int d = 0; d <= _depth; d++) {
ChoiceGenerator cg2 = new ChoiceGenerator(_nodes.size(), d);
int[] choice;
while ((choice = cg2.next()) != null) {
List<Node> cond = GraphUtils.asList(choice, _nodes);
broker.put(new ColliderTask(curTriple, a, c, cond));
}
}
}
}
broker.put(poisonPill);
broker.put(poisonPill);
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsProducer Finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class SepsetsCountsConsumer implements Runnable {
private Broker broker;
private ColliderTask poisonPill;
private IndependenceTest test;
public SepsetsCountsConsumer(Broker broker, IndependenceTest test, final ColliderTask poisonPill) {
this.broker = broker;
this.test = test;
this.poisonPill = poisonPill;
}
@Override
public void run() {
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsConsumer Start");
try {
ColliderTask task = broker.get();
while (task != poisonPill) {
if (task == null) {
task = broker.get();
continue;
}
if (test.isIndependent(task.x, task.y, task.z)) {
if (verbose) {
System.out.println("Indep: " + task.x + " _||_ " + task.y + " | " + task.z);
}
int idx = (task.z.contains(task.triple.getY())) ? 0 : 1;
int curr;
do {
curr = tripleMap.get(task.triple).get(idx);
} while (!tripleMap.get(task.triple).compareAndSet(idx, curr, curr+1));
// tripleMap.get(task.triple).incrementAndGet(idx);
// tripleMap.compute(task.triple, (k , v) -> {
// v.incrementAndGet(idx);
// return v;
// });
// if (task.z.contains(task.triple.getY())) {
// tripleMap.get(task.triple).set(0, tripleMap.get(task.triple).get(0)+1);
// } else {
// tripleMap.get(task.triple).set(1, tripleMap.get(task.triple).get(1)+1);
// }
}
task = broker.get();
}
broker.put(poisonPill);
broker.put(poisonPill);
System.out.println("\t" + Thread.currentThread().getName() + ": SepsetsCountsConsumer Finish");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void fillSepsetsCountsMap() {
this.tripleMap = new ConcurrentHashMap<>();
this.executorService = Executors.newFixedThreadPool(parallelism+1);
System.out.println("Begin concurrent fillSepsetsCountsMap");
Broker broker = new Broker();
List<Future> status = new ArrayList<>();
Node x = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
Node y = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
Node z = new ContinuousVariable(RandomStringUtils.randomAlphabetic(15));
ColliderTask poisonPill = new ColliderTask(new Triple(x,y,z), x, z, new ArrayList<>());
System.out.println("PoisonPill: " + poisonPill);
try {
status.add(executorService.submit(new SepsetsCountsProducer(broker, poisonPill)));
for (int i = 0; i < parallelism; i++) {
status.add(executorService.submit(new SepsetsCountsConsumer(broker, independenceTest.clone(), poisonPill)));
}
for (int i = 0; i < parallelism+1; i++) {
status.get(i).get();
}
} catch (Exception e) {
e.printStackTrace();
}
executorService.shutdown();
// boolean edgeAdded = false;
//
// List<Node> nodes = graph.getNodes();
// Map<Node, List<Node>> adjacencies = new HashMap<>();
//
// for (Node n : nodes) {
// adjacencies.put(n, new ArrayList<>(graph.getAdjacentNodes(n)));
// }
//
// for (int i = 0; i < nodes.size(); i ++) {
// final Node b = nodes.get(i);
// final List<Node> adjacent = adjacencies.get(b);
// //only compare to nodes less than it in index
// if (adjacent.size() < 2)
// continue;
// ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(), 2);
// int[] combination;
// while ((combination = cg.next()) != null) {
// final Node a = adjacent.get(combination[0]);
// final Node c = adjacent.get(combination[1]);
// if (adjacencies.get(a).contains(c) | adjacencies.get(c).contains(a))
// continue;
//
// Triple curTriple = new Triple(a, b, c);
//
// AtomicIntegerArray ret = tripleMap.get(curTriple);
// if ((ret.get(0) == 0) & (ret.get(1) == 0)) {
// System.out.println("Added: " + a + " --- " + c);
// graph.addUndirectedEdge(a, c);
// edgeAdded=true;
// }
// }
// }
System.out.println("End of concurrent fillSepsetsCountsMap");
// return edgeAdded;
// final HashMap<Integer,Integer> powerSetSizes = new HashMap<>();
// final List<Node> nodes = graph.getNodes();
// int sum = 0;
// int psSum;
// for(int i = 0; i < nodes.size();i++)
// {
// psSum = 0;
// List<Node> adjNodes = graph.getAdjacentNodes(nodes.get(i));
// for (int j = 0; j < adjNodes.size(); j++)
// {
// psSum += Math.pow(2, graph.getAdjacentNodes(adjNodes.get(j)).size()-1);
// }
// powerSetSizes.put(i, psSum);
// sum += psSum;
// }
// chunk = sum/(parallelism) * factor;
//
// class colliderTask extends RecursiveTask<Boolean> {
// private double chunk;
// private int from;
// private int to;
// public colliderTask(double chunk,int from, int to)
// {
// this.chunk = chunk;
// this.from = from;
// this.to = to;
// }
// protected Boolean compute()
// {
// int numTests = 0;
// for(int j = from; j < to; j++)
// {
// numTests += powerSetSizes.get(j);
// }
// if(to-from <= 2 || numTests <= chunk)
// {
// System.out.println(Thread.currentThread().getName() + ": " + numTests + " / " + chunk);
// for(int i = from; i < to; i ++)
// {
// final Node b = nodes.get(i);
// final List<Node> adjacent = graph.getAdjacentNodes(b);
// //only compare to nodes less than it in index
// if(adjacent.size()<2)
// continue;
// ChoiceGenerator cg = new ChoiceGenerator(adjacent.size(),2);
// int [] combination;
// while((combination = cg.next()) != null)
// {
// final Node a = adjacent.get(combination[0]);
// final Node c = adjacent.get(combination[1]);
// if(graph.isAdjacentTo(a,c))
// continue;
//
// List<List<List<Node>>> ret = getSepsetsLists(a, b, c, independenceTest, depth, verbose);
//
// List<Integer> temp = new ArrayList<>();
// temp.add(ret.get(0).size());
// temp.add(ret.get(1).size());
// tripleMap.put(new Triple(a, b, c), temp);
//
// if (temp.get(0) == temp.get(1)) {
// System.out.println("Ambiguous Triple: " + new Triple(a, b, c) + ": " + temp.get(0) + ", " + temp.get(1));
// }
//
//// sepsetsListsMap.put(new Triple(a,b,c), ret);
// }
// }
// System.out.println(Thread.currentThread().getName() + ": Finished");
// return true;
// }
// else
// {
// List<colliderTask> tasks = new ArrayList<>();
// final int mid = (to+from)/2;
// colliderTask t1 = new colliderTask(chunk,from,mid);
// tasks.add(t1);
// colliderTask t2 = new colliderTask(chunk,mid,to);
// tasks.add(t2);
// invokeAll(tasks);
// return true;
// }
//
// }
// }
// pool.invoke(new colliderTask(chunk,0,nodes.size()));
}
@Override
public boolean isIndependent(Node a, Node b, List<Node> c) {
return independenceTest.isIndependent(a, b, c);
}
@Override
public double getPValue() {
return independenceTest.getPValue();
}
@Override
public double getScore() {
return -(independenceTest.getPValue() - independenceTest.getAlpha());
}
@Override
public List<Node> getVariables() {
return independenceTest.getVariables();
}
@Override
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public IndependenceTest getIndependenceTest() {
return independenceTest;
}
}
| 24,561 | 0.475493 | 0.466667 | 633 | 37.837284 | 28.585955 | 139 | false | false | 0 | 0 | 0 | 0 | 91 | 0.007037 | 0.802528 | false | false | 2 |
e0ff2c710f39ac9ccd9286e05d1aba3c04293f61 | 13,322,988,565,952 | 94e2f239425cfafa921eb686bf7697d92c7a8d74 | /src/com/shaubert/andcopter/Triangle.java | bb7d36768b5f1c55759bd1eef8cb3255c51b9e5a | [] | no_license | parthmpandya/and-copter | https://github.com/parthmpandya/and-copter | f7814abf9942f0b0797b640fccfb2b183296a405 | 551be6c170f7a6562d0f2f093d431878078151bc | refs/heads/master | 2020-05-31T13:27:38.418000 | 2011-07-20T18:50:07 | 2011-07-20T18:50:07 | 40,241,068 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shaubert.andcopter;
public class Triangle extends Mesh {
public Triangle() {
this(1f, 1);
}
public Triangle(float size, int segmentsInDimension) {
this(segmentsInDimension,
0, (float)(size / Math.sqrt(3)), 0
-size/2, (float)(-size/(2 * Math.sqrt(3))), 0,
size/2, (float)(-size/(2 * Math.sqrt(3))), 0);
}
public Triangle(int segmentsInDimension, float ... points) {
if (points.length != 9) {
throw new IllegalArgumentException("points count must be equal 9, not " + points.length);
}
float[] vertices = new float[((segmentsInDimension + 1) * ((segmentsInDimension + 1) + 2) / 2) * 3];
short[] indices = new short[segmentsInDimension * segmentsInDimension * 3];
int vCounter = 0;
int iCounter = 0;
for (int j = 0; j <= segmentsInDimension; j++) {
float part = (float)j / segmentsInDimension;
float leftPointX = getPart(getPointX(points, 0), getPointX(points, 1), part);
float leftPointY = getPart(getPointY(points, 0), getPointY(points, 1), part);
float leftPointZ = getPart(getPointZ(points, 0), getPointZ(points, 1), part);
float rightPointX = getPart(getPointX(points, 0), getPointX(points, 2), part);
float rightPointY = getPart(getPointY(points, 0), getPointY(points, 2), part);
float rightPointZ = getPart(getPointZ(points, 0), getPointZ(points, 2), part);
for (int i = 0; i <= j; i++) {
float part2 = j == 0 ? 0 : ((float)i / j);
vertices[vCounter++] = getPart(leftPointX, rightPointX, part2);
vertices[vCounter++] = getPart(leftPointY, rightPointY, part2);
vertices[vCounter++] = getPart(leftPointZ, rightPointZ, part2);
short dotIndex = (short)((vCounter - 1) / 3);
if (j < segmentsInDimension) {
indices[iCounter++] = dotIndex;
indices[iCounter++] = (short)(dotIndex + j + 1);
indices[iCounter++] = (short)(dotIndex + j + 2);
if (i > 0) {
indices[iCounter++] = (short)(dotIndex - 1);
indices[iCounter++] = (short)(dotIndex + j + 1);
indices[iCounter++] = (short)(dotIndex);
}
}
}
}
setVertices(vertices);
setIndices(indices);
}
private float getPart(float x1, float x2, float part) {
return x1 + (x2 - x1) * part;
}
private float getPointZ(float[] points, int index) {
return points[index * 3 + 2];
}
private float getPointY(float[] points, int index) {
return points[index * 3 + 1];
}
private float getPointX(float[] points, int index) {
return points[index * 3];
}
}
| UTF-8 | Java | 3,069 | java | Triangle.java | Java | [] | null | [] | package com.shaubert.andcopter;
public class Triangle extends Mesh {
public Triangle() {
this(1f, 1);
}
public Triangle(float size, int segmentsInDimension) {
this(segmentsInDimension,
0, (float)(size / Math.sqrt(3)), 0
-size/2, (float)(-size/(2 * Math.sqrt(3))), 0,
size/2, (float)(-size/(2 * Math.sqrt(3))), 0);
}
public Triangle(int segmentsInDimension, float ... points) {
if (points.length != 9) {
throw new IllegalArgumentException("points count must be equal 9, not " + points.length);
}
float[] vertices = new float[((segmentsInDimension + 1) * ((segmentsInDimension + 1) + 2) / 2) * 3];
short[] indices = new short[segmentsInDimension * segmentsInDimension * 3];
int vCounter = 0;
int iCounter = 0;
for (int j = 0; j <= segmentsInDimension; j++) {
float part = (float)j / segmentsInDimension;
float leftPointX = getPart(getPointX(points, 0), getPointX(points, 1), part);
float leftPointY = getPart(getPointY(points, 0), getPointY(points, 1), part);
float leftPointZ = getPart(getPointZ(points, 0), getPointZ(points, 1), part);
float rightPointX = getPart(getPointX(points, 0), getPointX(points, 2), part);
float rightPointY = getPart(getPointY(points, 0), getPointY(points, 2), part);
float rightPointZ = getPart(getPointZ(points, 0), getPointZ(points, 2), part);
for (int i = 0; i <= j; i++) {
float part2 = j == 0 ? 0 : ((float)i / j);
vertices[vCounter++] = getPart(leftPointX, rightPointX, part2);
vertices[vCounter++] = getPart(leftPointY, rightPointY, part2);
vertices[vCounter++] = getPart(leftPointZ, rightPointZ, part2);
short dotIndex = (short)((vCounter - 1) / 3);
if (j < segmentsInDimension) {
indices[iCounter++] = dotIndex;
indices[iCounter++] = (short)(dotIndex + j + 1);
indices[iCounter++] = (short)(dotIndex + j + 2);
if (i > 0) {
indices[iCounter++] = (short)(dotIndex - 1);
indices[iCounter++] = (short)(dotIndex + j + 1);
indices[iCounter++] = (short)(dotIndex);
}
}
}
}
setVertices(vertices);
setIndices(indices);
}
private float getPart(float x1, float x2, float part) {
return x1 + (x2 - x1) * part;
}
private float getPointZ(float[] points, int index) {
return points[index * 3 + 2];
}
private float getPointY(float[] points, int index) {
return points[index * 3 + 1];
}
private float getPointX(float[] points, int index) {
return points[index * 3];
}
}
| 3,069 | 0.515152 | 0.495601 | 72 | 40.625 | 30.502932 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.152778 | false | false | 2 |
7c0841e3fe1797c7737fc56c0c2cdcffc4fef1df | 25,374,666,796,410 | 5c1da0ff422137318c5380a9c6003a3276b34d00 | /app/src/main/java/com/aj/sendall/ui/adapter/PersonalInteractionsAdapter.java | 4725a3e3452741f101c3f1d73fec0562f51e7f40 | [] | no_license | ajilalma/SendAll | https://github.com/ajilalma/SendAll | 7045f3881259c6d622536cd63ad18375fd918d81 | b49f4e84045bcf28ca1afb790ae38d6fe0bba2f9 | refs/heads/master | 2022-12-02T11:57:39.304000 | 2018-03-31T09:00:46 | 2018-03-31T09:00:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aj.sendall.ui.adapter;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aj.sendall.R;
import com.aj.sendall.db.dto.FileInfoDTO;
import com.aj.sendall.db.dto.PersonalInteractionDTO;
import com.aj.sendall.db.enums.FileStatus;
import com.aj.sendall.events.EventRouter;
import com.aj.sendall.events.EventRouterFactory;
import com.aj.sendall.events.event.FileTransferStatusEvent;
import com.aj.sendall.ui.adapter.helper.AdapterHelper;
import com.aj.sendall.ui.adapter.helper.AdapterHelperFactory;
import com.aj.sendall.ui.consts.MediaConsts;
import com.aj.sendall.ui.interfaces.ItemSelectableView;
import com.aj.sendall.ui.utils.CommonUiUtils;
import com.aj.sendall.ui.utils.PersonalInteractionsUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PersonalInteractionsAdapter extends RecyclerView.Adapter<PersonalInteractionsAdapter.ViewHolder>{
private EventRouter eventRouter = EventRouterFactory.getInstance();
private Context context;
private List<PersonalInteractionDTO> personalInteractionDTOs;
private Set<FileInfoDTO> selectedFiles = new HashSet<>();
private long connectionId;
private ItemSelectableView parentItemSelectable;
private PersonalInteractionsUtil personalInteractionsUtil;
private Handler handler;
private Set<ViewHolder> allViewHolders = new HashSet<>();
public PersonalInteractionsAdapter(long connectionId, @NonNull Context context, ItemSelectableView parentItemSelectable, PersonalInteractionsUtil personalInteractionsUtil, Handler handler){
this.parentItemSelectable = parentItemSelectable;
this.context = context;
this.connectionId = connectionId;
this.personalInteractionsUtil = personalInteractionsUtil;
this.handler = handler;
initAdapter();
}
private void initAdapter(){
personalInteractionDTOs = personalInteractionsUtil.getFileInteractionsByConnectionId(connectionId);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.pers_inter_item, parent, false);
ViewHolder holder = new ViewHolder(rootView);
allViewHolders.add(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
PersonalInteractionDTO dto = personalInteractionDTOs.get(position);
AdapterHelper ah = AdapterHelperFactory.getInstance(dto.mediaType, context);
if(ah != null) {
ah.setThumbnail(holder.imgVwItemThumbnail,
MediaConsts.MEDIA_THUMBNAIL_WIDTH_BIG,
MediaConsts.MEDIA_THUMBNAIL_HEIGHT_BIG,
dto);
}
holder.txtVwFileName.setText(dto.title);
String size;
if(FileStatus.SENT.equals(dto.status) || FileStatus.RECEIVED.equals(dto.status)) {
size = CommonUiUtils.getFileSizeString(dto.size);
} else {
size = "Incomplete..";
}
holder.txtVwFileSize.setText(size);
holder.itemView.setTag(dto);
holder.subscribeEvents(dto);
setInteractionViewParams(holder, dto);
}
private void setInteractionViewParams(ViewHolder holder, PersonalInteractionDTO dto){
switch(dto.status){
case SENDING:
case SENT:
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).leftMargin = 75;
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).rightMargin = 0;
((LinearLayout)holder.itemView).setGravity(Gravity.END);
break;
case RECEIVING:
case RECEIVED:
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).leftMargin = 0;
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).rightMargin = 75;
((LinearLayout)holder.itemView).setGravity(Gravity.START);
break;
}
}
@Override
public int getItemCount() {
return personalInteractionDTOs != null ? personalInteractionDTOs.size() : 0;
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imgVwItemThumbnail;
private TextView txtVwFileName;
private TextView txtVwFileSize;
ViewHolder(View view){
super(view);
imgVwItemThumbnail = (ImageView) view.findViewById(R.id.img_vw_pers_inter_thumbnail);
txtVwFileName = (TextView) view.findViewById(R.id.txt_vw_pers_inter_file_name);
txtVwFileSize = (TextView) view.findViewById(R.id.txt_vw_pers_inter_file_size);
setClickListeners(view);
}
private void setClickListeners(View view){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PersonalInteractionDTO dto = (PersonalInteractionDTO)v.getTag();
dto.isSelected = !dto.isSelected;
CommonUiUtils.setViewSelectedAppearanceRoundEdged(v, dto.isSelected);
if(dto.isSelected){
selectedFiles.add(dto);
parentItemSelectable.incrementTotalNoOfSelections();
} else {
selectedFiles.remove(dto);
parentItemSelectable.decrementTotalNoOfSelections();
}
}
});
}
EventRouter.Receiver<FileTransferStatusEvent> receiver = null;
PersonalInteractionDTO currentDTO = null;
private void subscribeEvents(final PersonalInteractionDTO dto){
if(!dto.equals(currentDTO)){
unsubscribeEvents();//un-subscribe on recycling the view
currentDTO = dto;
}
if(FileStatus.RECEIVING.equals(dto.status) || FileStatus.SENDING.equals(dto.status)){
receiver = new EventRouter.Receiver<FileTransferStatusEvent>() {
@Override
public void receive(final FileTransferStatusEvent event) {
handler.post(new Runnable() {
@Override
public void run() {
if(event.connectionId.equals(dto.id) && txtVwFileName.getText().equals(event.fileName)){
if(event.totalTransferred != FileTransferStatusEvent.COMPLETED){
txtVwFileSize.setText(
CommonUiUtils.getFileSizeString(event.totalTransferred)
+ "/" + CommonUiUtils.getFileSizeString(dto.size)
);
} else {
txtVwFileSize.setText(CommonUiUtils.getFileSizeString(dto.size));
//change the status so that the dto won't subscribe again
if(FileStatus.RECEIVING.equals(dto.status)){
dto.status = FileStatus.RECEIVED;
} else {//else status must be SENDING as per the parent conditional
dto.status = FileStatus.SENT;
}
unsubscribeTheListener();
}
}
}
});
}
private void unsubscribeTheListener(){
eventRouter.unsubscribe(FileTransferStatusEvent.class, this);
}
};
eventRouter.subscribe(FileTransferStatusEvent.class, receiver);
}
}
void unsubscribeEvents(){
if(receiver != null){
eventRouter.unsubscribe(FileTransferStatusEvent.class, receiver);
receiver = null;
}
}
}
public void unsubscribeFileTransferStatusEvents(){
for(ViewHolder holder : allViewHolders){
holder.unsubscribeEvents();
}
}
public Set<FileInfoDTO> getSelectedFiles(){
return selectedFiles;
}
}
| UTF-8 | Java | 8,862 | java | PersonalInteractionsAdapter.java | Java | [] | null | [] | package com.aj.sendall.ui.adapter;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aj.sendall.R;
import com.aj.sendall.db.dto.FileInfoDTO;
import com.aj.sendall.db.dto.PersonalInteractionDTO;
import com.aj.sendall.db.enums.FileStatus;
import com.aj.sendall.events.EventRouter;
import com.aj.sendall.events.EventRouterFactory;
import com.aj.sendall.events.event.FileTransferStatusEvent;
import com.aj.sendall.ui.adapter.helper.AdapterHelper;
import com.aj.sendall.ui.adapter.helper.AdapterHelperFactory;
import com.aj.sendall.ui.consts.MediaConsts;
import com.aj.sendall.ui.interfaces.ItemSelectableView;
import com.aj.sendall.ui.utils.CommonUiUtils;
import com.aj.sendall.ui.utils.PersonalInteractionsUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PersonalInteractionsAdapter extends RecyclerView.Adapter<PersonalInteractionsAdapter.ViewHolder>{
private EventRouter eventRouter = EventRouterFactory.getInstance();
private Context context;
private List<PersonalInteractionDTO> personalInteractionDTOs;
private Set<FileInfoDTO> selectedFiles = new HashSet<>();
private long connectionId;
private ItemSelectableView parentItemSelectable;
private PersonalInteractionsUtil personalInteractionsUtil;
private Handler handler;
private Set<ViewHolder> allViewHolders = new HashSet<>();
public PersonalInteractionsAdapter(long connectionId, @NonNull Context context, ItemSelectableView parentItemSelectable, PersonalInteractionsUtil personalInteractionsUtil, Handler handler){
this.parentItemSelectable = parentItemSelectable;
this.context = context;
this.connectionId = connectionId;
this.personalInteractionsUtil = personalInteractionsUtil;
this.handler = handler;
initAdapter();
}
private void initAdapter(){
personalInteractionDTOs = personalInteractionsUtil.getFileInteractionsByConnectionId(connectionId);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.pers_inter_item, parent, false);
ViewHolder holder = new ViewHolder(rootView);
allViewHolders.add(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
PersonalInteractionDTO dto = personalInteractionDTOs.get(position);
AdapterHelper ah = AdapterHelperFactory.getInstance(dto.mediaType, context);
if(ah != null) {
ah.setThumbnail(holder.imgVwItemThumbnail,
MediaConsts.MEDIA_THUMBNAIL_WIDTH_BIG,
MediaConsts.MEDIA_THUMBNAIL_HEIGHT_BIG,
dto);
}
holder.txtVwFileName.setText(dto.title);
String size;
if(FileStatus.SENT.equals(dto.status) || FileStatus.RECEIVED.equals(dto.status)) {
size = CommonUiUtils.getFileSizeString(dto.size);
} else {
size = "Incomplete..";
}
holder.txtVwFileSize.setText(size);
holder.itemView.setTag(dto);
holder.subscribeEvents(dto);
setInteractionViewParams(holder, dto);
}
private void setInteractionViewParams(ViewHolder holder, PersonalInteractionDTO dto){
switch(dto.status){
case SENDING:
case SENT:
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).leftMargin = 75;
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).rightMargin = 0;
((LinearLayout)holder.itemView).setGravity(Gravity.END);
break;
case RECEIVING:
case RECEIVED:
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).leftMargin = 0;
((RecyclerView.LayoutParams)holder.itemView.getLayoutParams()).rightMargin = 75;
((LinearLayout)holder.itemView).setGravity(Gravity.START);
break;
}
}
@Override
public int getItemCount() {
return personalInteractionDTOs != null ? personalInteractionDTOs.size() : 0;
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imgVwItemThumbnail;
private TextView txtVwFileName;
private TextView txtVwFileSize;
ViewHolder(View view){
super(view);
imgVwItemThumbnail = (ImageView) view.findViewById(R.id.img_vw_pers_inter_thumbnail);
txtVwFileName = (TextView) view.findViewById(R.id.txt_vw_pers_inter_file_name);
txtVwFileSize = (TextView) view.findViewById(R.id.txt_vw_pers_inter_file_size);
setClickListeners(view);
}
private void setClickListeners(View view){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PersonalInteractionDTO dto = (PersonalInteractionDTO)v.getTag();
dto.isSelected = !dto.isSelected;
CommonUiUtils.setViewSelectedAppearanceRoundEdged(v, dto.isSelected);
if(dto.isSelected){
selectedFiles.add(dto);
parentItemSelectable.incrementTotalNoOfSelections();
} else {
selectedFiles.remove(dto);
parentItemSelectable.decrementTotalNoOfSelections();
}
}
});
}
EventRouter.Receiver<FileTransferStatusEvent> receiver = null;
PersonalInteractionDTO currentDTO = null;
private void subscribeEvents(final PersonalInteractionDTO dto){
if(!dto.equals(currentDTO)){
unsubscribeEvents();//un-subscribe on recycling the view
currentDTO = dto;
}
if(FileStatus.RECEIVING.equals(dto.status) || FileStatus.SENDING.equals(dto.status)){
receiver = new EventRouter.Receiver<FileTransferStatusEvent>() {
@Override
public void receive(final FileTransferStatusEvent event) {
handler.post(new Runnable() {
@Override
public void run() {
if(event.connectionId.equals(dto.id) && txtVwFileName.getText().equals(event.fileName)){
if(event.totalTransferred != FileTransferStatusEvent.COMPLETED){
txtVwFileSize.setText(
CommonUiUtils.getFileSizeString(event.totalTransferred)
+ "/" + CommonUiUtils.getFileSizeString(dto.size)
);
} else {
txtVwFileSize.setText(CommonUiUtils.getFileSizeString(dto.size));
//change the status so that the dto won't subscribe again
if(FileStatus.RECEIVING.equals(dto.status)){
dto.status = FileStatus.RECEIVED;
} else {//else status must be SENDING as per the parent conditional
dto.status = FileStatus.SENT;
}
unsubscribeTheListener();
}
}
}
});
}
private void unsubscribeTheListener(){
eventRouter.unsubscribe(FileTransferStatusEvent.class, this);
}
};
eventRouter.subscribe(FileTransferStatusEvent.class, receiver);
}
}
void unsubscribeEvents(){
if(receiver != null){
eventRouter.unsubscribe(FileTransferStatusEvent.class, receiver);
receiver = null;
}
}
}
public void unsubscribeFileTransferStatusEvents(){
for(ViewHolder holder : allViewHolders){
holder.unsubscribeEvents();
}
}
public Set<FileInfoDTO> getSelectedFiles(){
return selectedFiles;
}
}
| 8,862 | 0.610359 | 0.609456 | 207 | 41.811596 | 31.778799 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594203 | false | false | 2 |
1a0b1523113080950c1f3fc1c6dbe4a05f1d822a | 26,233,660,258,682 | 38a03ad3621a3b276f8e9782f6970caed438074d | /src/MissileSound.java | a290e9ed49f0d1114cd12997d8a704a196e6b18b | [] | no_license | bmatejek/Graphics | https://github.com/bmatejek/Graphics | 8f181062b433a4d5e857aee4227aaecaecaa4092 | f84062362ff0839bd5d0f6342ca32543a94a6bfa | refs/heads/master | 2021-05-29T19:20:57.459000 | 2013-05-14T05:12:08 | 2013-05-14T05:12:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class MissileSound {
public static void main(String[] args) {
StdAudio.play("Missile.wav");
StdAudio.close();
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
}
System.exit(0);
}
} | UTF-8 | Java | 220 | java | MissileSound.java | Java | [] | null | [] | public class MissileSound {
public static void main(String[] args) {
StdAudio.play("Missile.wav");
StdAudio.close();
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
}
System.exit(0);
}
} | 220 | 0.654545 | 0.631818 | 12 | 17.416666 | 14.26802 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.916667 | false | false | 2 |
624eca7e4911dc5e654df675e9d92c59481ae86c | 3,624,952,413,727 | 3969756510c32bc106ed3a9edbbf91a52f12b1bc | /src/org/retardants/adt/Strategy.java | 7143a3b828c25e1a4ba8c2a3efb1b2a78b37e97e | [] | no_license | retardants/retardants | https://github.com/retardants/retardants | 8a589e12f85f97e65b04df4d2ac965279b233df8 | 2305b67b72055b00be6a27a18c515ef68e606d12 | refs/heads/master | 2020-05-16T23:09:41.032000 | 2011-11-24T14:00:36 | 2011-11-24T14:00:36 | 2,801,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.retardants.adt;
public enum Strategy {
BATTLE_SHORTEST_EUCLIDEAN_ROUTE,
BATTLE_DIJKSTRAS_TILE_PATH,
FOOD_DIFFUSION_ONE_ANT_PER_FOOD, // one ant per food
FOOD_DIFFUSION_ALL_ANTS, // all ants go uphill
FOOD_SHORTEST_EUCLIDEAN_ROUTE, // one ant per food
EXPLORATION_NEAREST_UNSEEN,
EXPLORATION_LEAST_VISITED;
}
| UTF-8 | Java | 365 | java | Strategy.java | Java | [] | null | [] | package org.retardants.adt;
public enum Strategy {
BATTLE_SHORTEST_EUCLIDEAN_ROUTE,
BATTLE_DIJKSTRAS_TILE_PATH,
FOOD_DIFFUSION_ONE_ANT_PER_FOOD, // one ant per food
FOOD_DIFFUSION_ALL_ANTS, // all ants go uphill
FOOD_SHORTEST_EUCLIDEAN_ROUTE, // one ant per food
EXPLORATION_NEAREST_UNSEEN,
EXPLORATION_LEAST_VISITED;
}
| 365 | 0.690411 | 0.690411 | 15 | 23.333334 | 19.604988 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 2 |
b74315a50c4d53d5ba4b6b921853d902f03225d0 | 15,925,738,751,243 | b7a2cc3ac4138609154027436ed52a3a5b1fe567 | /src/client/Main.java | 61dbafd8532f78656ce8b6b2b9456427b2d2020e | [
"MIT"
] | permissive | Jayce132/File-Server | https://github.com/Jayce132/File-Server | aa1cd566656e0e77de118898e3bba104d22ddfde | 00413175995062f85509d1c8e5f273a810088799 | refs/heads/main | 2023-03-01T19:04:50.118000 | 2021-01-31T22:02:05 | 2021-01-31T22:02:05 | 331,725,387 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Client started!");
String address = "127.0.0.1";
int port = 23456;
try (
Socket socket = new Socket(InetAddress.getByName(address), port);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
System.out.print("Enter action (1 - get a file, 2 - create a file, 3 - delete a file): > ");
String action = scanner.nextLine();
switch (action) {
case "1":
System.out.print("Enter filename: > ");
String filename = scanner.nextLine();
output.writeUTF("get " + filename);
System.out.println("The request was sent.");
if (input.readInt() == 200) {
System.out.println("The content of the file is: " + input.readUTF());
} else {
System.out.println("The response says that the file was not found!");
}
break;
case "2":
System.out.print("Enter filename: > ");
filename = scanner.nextLine();
output.writeUTF("add " + filename);
if (input.readInt() == 403) {
System.out.println("The response says that creating the file was forbidden!");
} else {
System.out.println("Enter file content:");
String content = scanner.nextLine();
output.writeUTF(content);
System.out.println("The request was sent.");
System.out.println("The response says that file was created!");
}
break;
case "3":
System.out.print("Enter filename: > ");
filename = scanner.nextLine();
output.writeUTF("delete " + filename);
System.out.println("The request was sent.");
if (input.readInt() == 200) {
System.out.println("The response says that the file was successfully deleted!");
} else {
System.out.println("The response says that the file was not found!");
}
break;
case "exit":
output.writeUTF("exit program");
System.out.println("The request was sent.");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 3,050 | java | Main.java | Java | [
{
"context": "tln(\"Client started!\");\n String address = \"127.0.0.1\";\n int port = 23456;\n try (\n ",
"end": 360,
"score": 0.9996779561042786,
"start": 351,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null | [] | package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Client started!");
String address = "127.0.0.1";
int port = 23456;
try (
Socket socket = new Socket(InetAddress.getByName(address), port);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
System.out.print("Enter action (1 - get a file, 2 - create a file, 3 - delete a file): > ");
String action = scanner.nextLine();
switch (action) {
case "1":
System.out.print("Enter filename: > ");
String filename = scanner.nextLine();
output.writeUTF("get " + filename);
System.out.println("The request was sent.");
if (input.readInt() == 200) {
System.out.println("The content of the file is: " + input.readUTF());
} else {
System.out.println("The response says that the file was not found!");
}
break;
case "2":
System.out.print("Enter filename: > ");
filename = scanner.nextLine();
output.writeUTF("add " + filename);
if (input.readInt() == 403) {
System.out.println("The response says that creating the file was forbidden!");
} else {
System.out.println("Enter file content:");
String content = scanner.nextLine();
output.writeUTF(content);
System.out.println("The request was sent.");
System.out.println("The response says that file was created!");
}
break;
case "3":
System.out.print("Enter filename: > ");
filename = scanner.nextLine();
output.writeUTF("delete " + filename);
System.out.println("The request was sent.");
if (input.readInt() == 200) {
System.out.println("The response says that the file was successfully deleted!");
} else {
System.out.println("The response says that the file was not found!");
}
break;
case "exit":
output.writeUTF("exit program");
System.out.println("The request was sent.");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 3,050 | 0.485246 | 0.476721 | 74 | 40.229729 | 28.619379 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608108 | false | false | 2 |
21d7a90e88ff4266b16b7354f36df1ad6889a904 | 13,322,988,567,108 | 1a2e2580e18957cb5ad2aca0c0d92fb7ba934b44 | /src/main/java/com/daoliuhe/sell/model/Customer.java | 58e2958e0748828f9d7c71f01e7865a571c38504 | [] | no_license | hcray/sell | https://github.com/hcray/sell | 777001b52212cab84a99f733539042fc72933973 | 6b00a2f902601a3b7cfb445b64303e043735550b | refs/heads/master | 2021-01-13T03:34:30.888000 | 2017-04-09T07:24:22 | 2017-04-09T07:24:22 | 77,309,375 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.daoliuhe.sell.model;
import com.daoliuhe.sell.util.Utils;
import java.util.Date;
public class Customer extends BasePage {
/**
* id
*/
private Integer id;
/**
* 微信的open_id
*/
private String wechat;
/**
*微信昵称
*/
private String nick;
/**
* 分销商的id
*/
private Integer businessId;
/**
* 分销商名称
*/
private String businessName;
/**
* 手机号
*/
private String phone;
/**
* 生效时间
*/
private Date enableDate;
/**
* 生效时间字符串
*/
private String enableDateStr;
/**
* 失效时间
*/
private Date disableDate;
/**
* 失效时间字符串
*/
private String disableDateStr;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getEnableDate() {
return enableDate;
}
public void setEnableDate(Date enableDate) {
this.enableDate = enableDate;
if (null != enableDate) {
this.enableDateStr = Utils.dateFormat(enableDate);
}
}
public Date getDisableDate() {
return disableDate;
}
public void setDisableDate(Date disableDate) {
this.disableDate = disableDate;
if (null != disableDate) {
this.disableDateStr = Utils.dateFormat(disableDate);
}
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public Integer getBusinessId() {
return businessId;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
public String getEnableDateStr() {
return enableDateStr;
}
public void setEnableDateStr(String enableDateStr) {
this.enableDateStr = enableDateStr;
}
public String getDisableDateStr() {
return disableDateStr;
}
public void setDisableDateStr(String disableDateStr) {
this.disableDateStr = disableDateStr;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", wechat='" + wechat + '\'' +
", nick='" + nick + '\'' +
", businessId=" + businessId +
", businessName='" + businessName + '\'' +
", phone='" + phone + '\'' +
", enableDate=" + enableDate +
", disableDate=" + disableDate +
'}';
}
} | UTF-8 | Java | 3,077 | java | Customer.java | Java | [
{
"context": "='\" + wechat + '\\'' +\n \", nick='\" + nick + '\\'' +\n \", businessId=\" + busine",
"end": 2710,
"score": 0.7411141991615295,
"start": 2706,
"tag": "USERNAME",
"value": "nick"
}
] | null | [] | package com.daoliuhe.sell.model;
import com.daoliuhe.sell.util.Utils;
import java.util.Date;
public class Customer extends BasePage {
/**
* id
*/
private Integer id;
/**
* 微信的open_id
*/
private String wechat;
/**
*微信昵称
*/
private String nick;
/**
* 分销商的id
*/
private Integer businessId;
/**
* 分销商名称
*/
private String businessName;
/**
* 手机号
*/
private String phone;
/**
* 生效时间
*/
private Date enableDate;
/**
* 生效时间字符串
*/
private String enableDateStr;
/**
* 失效时间
*/
private Date disableDate;
/**
* 失效时间字符串
*/
private String disableDateStr;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getEnableDate() {
return enableDate;
}
public void setEnableDate(Date enableDate) {
this.enableDate = enableDate;
if (null != enableDate) {
this.enableDateStr = Utils.dateFormat(enableDate);
}
}
public Date getDisableDate() {
return disableDate;
}
public void setDisableDate(Date disableDate) {
this.disableDate = disableDate;
if (null != disableDate) {
this.disableDateStr = Utils.dateFormat(disableDate);
}
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public Integer getBusinessId() {
return businessId;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
public String getEnableDateStr() {
return enableDateStr;
}
public void setEnableDateStr(String enableDateStr) {
this.enableDateStr = enableDateStr;
}
public String getDisableDateStr() {
return disableDateStr;
}
public void setDisableDateStr(String disableDateStr) {
this.disableDateStr = disableDateStr;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", wechat='" + wechat + '\'' +
", nick='" + nick + '\'' +
", businessId=" + businessId +
", businessName='" + businessName + '\'' +
", phone='" + phone + '\'' +
", enableDate=" + enableDate +
", disableDate=" + disableDate +
'}';
}
} | 3,077 | 0.538898 | 0.538898 | 156 | 18.205128 | 17.172846 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275641 | false | false | 2 |
45bfdaf6013da36c2b802abeed33018dd198123e | 24,824,910,986,375 | b55c59f618bf51dea954a6f3a2595f03bcca82fa | /api/src/test/java/demo/kafka/app/HelloWorldImplTest.java | 498569484c85c754fed9629fc1d6e802eb0d4a6f | [
"Apache-2.0"
] | permissive | Hearen/kafka-demos | https://github.com/Hearen/kafka-demos | c0473c5a10700cc803e9689a86ad43ef95de4689 | c1609affb99558077b3ff1a2491d60239984590d | refs/heads/master | 2020-06-19T17:13:02.476000 | 2019-07-15T07:01:51 | 2019-07-15T07:01:51 | 196,797,007 | 0 | 0 | Apache-2.0 | false | 2019-07-14T06:43:00 | 2019-07-14T05:20:31 | 2019-07-14T05:20:34 | 2019-07-14T06:42:59 | 5 | 0 | 0 | 0 | null | false | false | package demo.kafka.app;
import demo.kafka.api.HelloWorldImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* 2019-07-15 12:07
*
* @author leiqi
*/
public class HelloWorldImplTest {
@Test
public void sayHello() {
assertEquals("Hello, Cattie", new HelloWorldImpl().sayHello("Cattie"));
}
} | UTF-8 | Java | 342 | java | HelloWorldImplTest.java | Java | [
{
"context": "sertEquals;\n\n/**\n * 2019-07-15 12:07\n *\n * @author leiqi\n */\npublic class HelloWorldImplTest {\n\n @Test\n",
"end": 176,
"score": 0.9902205467224121,
"start": 171,
"tag": "USERNAME",
"value": "leiqi"
},
{
"context": "lic void sayHello() {\n assertEquals... | null | [] | package demo.kafka.app;
import demo.kafka.api.HelloWorldImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* 2019-07-15 12:07
*
* @author leiqi
*/
public class HelloWorldImplTest {
@Test
public void sayHello() {
assertEquals("Hello, Cattie", new HelloWorldImpl().sayHello("Cattie"));
}
} | 342 | 0.687135 | 0.652047 | 19 | 17.052631 | 20.069546 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 2 |
a49ec4439f7d90926b5fd482f2c7592776f78429 | 11,261,404,272,226 | 5bb1a1eaa149284d8a249b871bfaf425e0425256 | /src/main/java/ThreadCliente.java | 9a4fcaca5d03361a8a82eb50b680475d974c7346 | [] | no_license | Leandroschwab/Server_farmasim | https://github.com/Leandroschwab/Server_farmasim | 3847616163566f9c7ba979541fdd6fd78db6acd9 | fba68d6a852c9cba472ab25e8f466994fb6fae14 | refs/heads/master | 2020-03-18T20:51:59.822000 | 2018-10-15T02:40:36 | 2018-10-15T02:40:36 | 135,243,387 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import _functions.ConnMySQL;
public class ThreadCliente extends Thread {
private Socket clientSocket;
public ThreadCliente(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
Scanner din = new Scanner(clientSocket.getInputStream());
String msgRecebida = din.nextLine();
System.out.println("Servidor: recebeu o valor " + msgRecebida);
String aMsgRec[] = msgRecebida.split("-;-");
System.out.println("Servidor: aMsgRec[0] " + aMsgRec[0]);
if (aMsgRec[0].equals("Login")) {
String msgEnviar = opLogin(aMsgRec[1], aMsgRec[2].toUpperCase());
PrintWriter dout = new PrintWriter(clientSocket.getOutputStream(), true);
dout.println(msgEnviar);
System.out.println("Servidor: enviou o valor " + msgEnviar);
} else if (aMsgRec[0].equals("Remedio")) {
String msgEnviar = opRemedio(aMsgRec[1]);
PrintWriter dout = new PrintWriter(clientSocket.getOutputStream(), true);
dout.println(msgEnviar);
System.out.println("Servidor: enviou o valor " + msgEnviar);
}
din.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String opRemedio(String id) {
String msgEnviar = new String();
try {
System.out.println("Servidor: opLogin...");
Connection conn = ConnMySQL.openConnMySQL();
String sql = "SELECT `Nome Remedio`, `cor`,`6:00`,`7:00`,`12:00`,`19:00`,`21:00` FROM `horarios` WHERE `id-receita`="
+ id + "";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
msgEnviar = rs.getString("Nome Remedio") + "-;-" + rs.getString("cor") + "-;-"
+ rs.getInt("6:00") + "-;-" + rs.getInt("7:00") + "-;-" + rs.getInt("12:00") + "-;-"
+ rs.getInt("19:00") + "-;-" + rs.getInt("21:00");
while (rs.next()) {
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
msgEnviar = msgEnviar + "-:-" + rs.getString("Nome Remedio") + "-;-" + rs.getString("cor")
+ "-;-" + rs.getInt("6:00") + "-;-" + rs.getInt("7:00") + "-;-" + rs.getInt("12:00")
+ "-;-" + rs.getInt("19:00") + "-;-" + rs.getInt("21:00");
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
return msgEnviar;
}
private String opLogin(String id, String senha) {
String msgEnviar = new String();
try {
System.out.println("Servidor: opLogin...");
Connection conn = ConnMySQL.openConnMySQL();
String sql = "SELECT `nome-paciente`, `password` FROM `receitas` WHERE `id-receita`=" + id + "";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
String senhaDB = rs.getString("password");
if (senhaDB.equals(senha)) {
String nomePaciente = rs.getString("nome-paciente");
System.out.println("=========================");
System.out.println("Nome = " + nomePaciente);
System.out.println("=========================");
msgEnviar = "login" + "-;-SucessoLogin-;-"+nomePaciente;
} else {
System.out.println("=========================");
System.out.println("Login invalido " + senha + " " + senhaDB);
System.out.println("=========================");
msgEnviar = "login" + "-;-FalhaLogin-;-Senha incorreta";
}
} else {
System.out.println("=========================");
System.out.println("Login invalido não encontrado");
System.out.println("=========================");
msgEnviar = "login" + "-;-FalhaLogin-;-Senha incorreta";
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgEnviar;
}
}
| ISO-8859-1 | Java | 4,409 | java | ThreadCliente.java | Java | [] | null | [] | import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import _functions.ConnMySQL;
public class ThreadCliente extends Thread {
private Socket clientSocket;
public ThreadCliente(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
Scanner din = new Scanner(clientSocket.getInputStream());
String msgRecebida = din.nextLine();
System.out.println("Servidor: recebeu o valor " + msgRecebida);
String aMsgRec[] = msgRecebida.split("-;-");
System.out.println("Servidor: aMsgRec[0] " + aMsgRec[0]);
if (aMsgRec[0].equals("Login")) {
String msgEnviar = opLogin(aMsgRec[1], aMsgRec[2].toUpperCase());
PrintWriter dout = new PrintWriter(clientSocket.getOutputStream(), true);
dout.println(msgEnviar);
System.out.println("Servidor: enviou o valor " + msgEnviar);
} else if (aMsgRec[0].equals("Remedio")) {
String msgEnviar = opRemedio(aMsgRec[1]);
PrintWriter dout = new PrintWriter(clientSocket.getOutputStream(), true);
dout.println(msgEnviar);
System.out.println("Servidor: enviou o valor " + msgEnviar);
}
din.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String opRemedio(String id) {
String msgEnviar = new String();
try {
System.out.println("Servidor: opLogin...");
Connection conn = ConnMySQL.openConnMySQL();
String sql = "SELECT `Nome Remedio`, `cor`,`6:00`,`7:00`,`12:00`,`19:00`,`21:00` FROM `horarios` WHERE `id-receita`="
+ id + "";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
msgEnviar = rs.getString("Nome Remedio") + "-;-" + rs.getString("cor") + "-;-"
+ rs.getInt("6:00") + "-;-" + rs.getInt("7:00") + "-;-" + rs.getInt("12:00") + "-;-"
+ rs.getInt("19:00") + "-;-" + rs.getInt("21:00");
while (rs.next()) {
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
msgEnviar = msgEnviar + "-:-" + rs.getString("Nome Remedio") + "-;-" + rs.getString("cor")
+ "-;-" + rs.getInt("6:00") + "-;-" + rs.getInt("7:00") + "-;-" + rs.getInt("12:00")
+ "-;-" + rs.getInt("19:00") + "-;-" + rs.getInt("21:00");
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("=========================");
System.out.println("msgEnviar = " + msgEnviar);
System.out.println("=========================");
return msgEnviar;
}
private String opLogin(String id, String senha) {
String msgEnviar = new String();
try {
System.out.println("Servidor: opLogin...");
Connection conn = ConnMySQL.openConnMySQL();
String sql = "SELECT `nome-paciente`, `password` FROM `receitas` WHERE `id-receita`=" + id + "";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
String senhaDB = rs.getString("password");
if (senhaDB.equals(senha)) {
String nomePaciente = rs.getString("nome-paciente");
System.out.println("=========================");
System.out.println("Nome = " + nomePaciente);
System.out.println("=========================");
msgEnviar = "login" + "-;-SucessoLogin-;-"+nomePaciente;
} else {
System.out.println("=========================");
System.out.println("Login invalido " + senha + " " + senhaDB);
System.out.println("=========================");
msgEnviar = "login" + "-;-FalhaLogin-;-Senha incorreta";
}
} else {
System.out.println("=========================");
System.out.println("Login invalido não encontrado");
System.out.println("=========================");
msgEnviar = "login" + "-;-FalhaLogin-;-Senha incorreta";
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgEnviar;
}
}
| 4,409 | 0.573276 | 0.559437 | 131 | 32.648853 | 27.029224 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.793893 | false | false | 2 |
3fd8d75106daa71390a68e051aacda8dfcae5bd3 | 14,285,061,246,379 | aacc3c2a07015b663d45a961e395c26d07cfd609 | /app/src/main/java/com/outfit/interview/detector/outfit7appdetector/models/AppData.java | e28a0c35df1de323a09cff09b2c67e43a285868a | [
"Apache-2.0"
] | permissive | dognjen/interview-android-app-detector | https://github.com/dognjen/interview-android-app-detector | d170fc3378a97741598866c079a5b1d5b54551b7 | c672e7922aad7cd733d579387308ac3069746dc2 | refs/heads/master | 2021-08-26T07:28:51.496000 | 2017-11-19T17:58:23 | 2017-11-19T17:58:23 | 111,314,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.outfit.interview.detector.outfit7appdetector.models;
import android.graphics.drawable.Drawable;
/**
* Created by Dejan on 18/11/2017.
*/
public class AppData {
private String applicationName;
private Integer applicationVersionCode;
private String applicationVersion;
private Drawable applicationLogo;
private String applicationPackage;
public AppData(String applicationName, Integer applicationVersionCode, String applicationVersion, Drawable applicationLogo, String applicationPackage) {
this.applicationName = applicationName;
this.applicationVersionCode = applicationVersionCode;
this.applicationVersion = applicationVersion;
this.applicationLogo = applicationLogo;
this.applicationPackage = applicationPackage;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public Integer getApplicationVersionCode() {
return applicationVersionCode;
}
public void setApplicationVersionCode(Integer applicationVersionCode) {
this.applicationVersionCode = applicationVersionCode;
}
public String getApplicationVersion() {
return applicationVersion;
}
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
public Drawable getApplicationLogo() {
return applicationLogo;
}
public void setApplicationLogo(Drawable applicationLogo) {
this.applicationLogo = applicationLogo;
}
public String getApplicationPackage() {
return applicationPackage;
}
public void setApplicationPackage(String applicationPackage) {
this.applicationPackage = applicationPackage;
}
}
| UTF-8 | Java | 1,874 | java | AppData.java | Java | [
{
"context": "oid.graphics.drawable.Drawable;\n\n/**\n * Created by Dejan on 18/11/2017.\n */\n\npublic class AppData {\n\n p",
"end": 133,
"score": 0.6730677485466003,
"start": 128,
"tag": "NAME",
"value": "Dejan"
}
] | null | [] | package com.outfit.interview.detector.outfit7appdetector.models;
import android.graphics.drawable.Drawable;
/**
* Created by Dejan on 18/11/2017.
*/
public class AppData {
private String applicationName;
private Integer applicationVersionCode;
private String applicationVersion;
private Drawable applicationLogo;
private String applicationPackage;
public AppData(String applicationName, Integer applicationVersionCode, String applicationVersion, Drawable applicationLogo, String applicationPackage) {
this.applicationName = applicationName;
this.applicationVersionCode = applicationVersionCode;
this.applicationVersion = applicationVersion;
this.applicationLogo = applicationLogo;
this.applicationPackage = applicationPackage;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public Integer getApplicationVersionCode() {
return applicationVersionCode;
}
public void setApplicationVersionCode(Integer applicationVersionCode) {
this.applicationVersionCode = applicationVersionCode;
}
public String getApplicationVersion() {
return applicationVersion;
}
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
public Drawable getApplicationLogo() {
return applicationLogo;
}
public void setApplicationLogo(Drawable applicationLogo) {
this.applicationLogo = applicationLogo;
}
public String getApplicationPackage() {
return applicationPackage;
}
public void setApplicationPackage(String applicationPackage) {
this.applicationPackage = applicationPackage;
}
}
| 1,874 | 0.734258 | 0.729456 | 68 | 26.558823 | 28.654833 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false | 2 |
ff00ecad337becfad9f76fe436fbd5922a613c82 | 16,862,041,629,731 | ac1577e7b2bc51e48ab206a446c7594c936ef2ae | /app/src/main/java/com/lol/ye0ye/whatmodd/model/ChooseMoodActivity.java | 96e6ef442d7ff0c14274804ad0926cd0f06f4fb7 | [] | no_license | ye0yeg/WhatModd | https://github.com/ye0yeg/WhatModd | 63bc665dba2d9dc6dec03b3d936de9178c2842b7 | 90d710e50d4978d0d59fe03ee867da1cfa654276 | refs/heads/master | 2021-01-01T16:33:05.673000 | 2017-07-21T16:29:35 | 2017-07-21T16:29:35 | 97,856,888 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lol.ye0ye.whatmodd.model;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.lol.ye0ye.whatmodd.R;
/**
* Created by ye0ye on 2017/7/20.
*/
public class ChooseMoodActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mood);
}
}
| UTF-8 | Java | 483 | java | ChooseMoodActivity.java | Java | [
{
"context": "mport com.lol.ye0ye.whatmodd.R;\n\n/**\n * Created by ye0ye on 2017/7/20.\n */\n\npublic class ChooseMoodActivit",
"end": 216,
"score": 0.999612033367157,
"start": 211,
"tag": "USERNAME",
"value": "ye0ye"
}
] | null | [] | package com.lol.ye0ye.whatmodd.model;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.lol.ye0ye.whatmodd.R;
/**
* Created by ye0ye on 2017/7/20.
*/
public class ChooseMoodActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mood);
}
}
| 483 | 0.755694 | 0.732919 | 19 | 24.421053 | 22.509216 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 2 |
0b46604dd4f36ede2fbd9eee6d85ea0d5c02cdc0 | 32,074,815,800,887 | 846997357358c3c8d3249873f8abf70a80c19b4d | /Span/src/main/java/Pages/Register.java | f31e18b8db26a59f45cd09e28579b3f5a609203b | [] | no_license | senfrendz/Simple-POM | https://github.com/senfrendz/Simple-POM | 8e05c4a5e20857db8084db81650a70d71733003b | a436144b72a2b016c9d51141fa0e68d28f95419d | refs/heads/main | 2023-02-09T09:17:58.704000 | 2020-12-29T15:46:41 | 2020-12-29T15:46:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Pages;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class Register extends Baseclass{
public static String emailID;
static String signup = Baseclass.properties.getProperty("Signup");
static String Next = Baseclass.properties.getProperty("Next");
static String fName = Baseclass.properties.getProperty("FirstName");
static String lName = Baseclass.properties.getProperty("LastName");
static String eMail = Baseclass.properties.getProperty("Email");
static String mobile = Baseclass.properties.getProperty("Phone");
static String country_choose = Baseclass.properties.getProperty("Country");
static String Gender = Baseclass.properties.getProperty("Gender");
static String Go = Baseclass.properties.getProperty("Submit");
public static void Signup(String SignUp_Email,String firstName,String lastName,String emailAddr,String phone,String countryName) throws IOException {
driver.findElement(By.xpath(signup)).sendKeys(SignUp_Email);
driver.findElement(By.xpath(Next)).click();
int fiName = firstName.length();
if (firstName.length() > 3) {
driver.findElement(By.xpath(fName)).sendKeys(firstName);
}
else
{
System.out.println("Assertion Failed....");
StatusWriteExcel.statusWrite("Fail");
assertEquals(fiName, fiName > 3);
}
driver.findElement(By.xpath(lName)).sendKeys(lastName);
driver.findElement(By.xpath(eMail)).sendKeys(emailAddr);
// String phoneNo = Integer.toString(phone);
//System.out.println(String.valueOf(phone).length());
if (String.valueOf(phone).length() == 10) {
driver.findElement(By.xpath(mobile)).sendKeys(String.valueOf(phone));
assertEquals(String.valueOf(phone).length(), 10);
}
else
{
StatusWriteExcel.statusWrite("Fail");
}
dropDownSelction(countryName);
driver.findElement(By.xpath(Gender)).click();
StatusWriteExcel.statusWrite("Pass");
}
public static void dropDownSelction(String countryName) {
WebElement cNames = driver.findElement(By.xpath(country_choose));
Select dropdownoptions = new Select(cNames);
dropdownoptions.selectByVisibleText(countryName);
}
}
| UTF-8 | Java | 2,375 | java | Register.java | Java | [] | null | [] | package Pages;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class Register extends Baseclass{
public static String emailID;
static String signup = Baseclass.properties.getProperty("Signup");
static String Next = Baseclass.properties.getProperty("Next");
static String fName = Baseclass.properties.getProperty("FirstName");
static String lName = Baseclass.properties.getProperty("LastName");
static String eMail = Baseclass.properties.getProperty("Email");
static String mobile = Baseclass.properties.getProperty("Phone");
static String country_choose = Baseclass.properties.getProperty("Country");
static String Gender = Baseclass.properties.getProperty("Gender");
static String Go = Baseclass.properties.getProperty("Submit");
public static void Signup(String SignUp_Email,String firstName,String lastName,String emailAddr,String phone,String countryName) throws IOException {
driver.findElement(By.xpath(signup)).sendKeys(SignUp_Email);
driver.findElement(By.xpath(Next)).click();
int fiName = firstName.length();
if (firstName.length() > 3) {
driver.findElement(By.xpath(fName)).sendKeys(firstName);
}
else
{
System.out.println("Assertion Failed....");
StatusWriteExcel.statusWrite("Fail");
assertEquals(fiName, fiName > 3);
}
driver.findElement(By.xpath(lName)).sendKeys(lastName);
driver.findElement(By.xpath(eMail)).sendKeys(emailAddr);
// String phoneNo = Integer.toString(phone);
//System.out.println(String.valueOf(phone).length());
if (String.valueOf(phone).length() == 10) {
driver.findElement(By.xpath(mobile)).sendKeys(String.valueOf(phone));
assertEquals(String.valueOf(phone).length(), 10);
}
else
{
StatusWriteExcel.statusWrite("Fail");
}
dropDownSelction(countryName);
driver.findElement(By.xpath(Gender)).click();
StatusWriteExcel.statusWrite("Pass");
}
public static void dropDownSelction(String countryName) {
WebElement cNames = driver.findElement(By.xpath(country_choose));
Select dropdownoptions = new Select(cNames);
dropdownoptions.selectByVisibleText(countryName);
}
}
| 2,375 | 0.716632 | 0.714105 | 78 | 28.423077 | 29.367485 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.089744 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.