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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed596be1945dc346dacb4728b54989c5d99f62f0 | 16,862,041,662,343 | b3c52bfaf5cf787e55b081d64adf87ba7dc8736d | /src/main/java/pl/dev/news/devnewsservice/security/TokenAuthenticationProvider.java | f4b23bd944385a0d9837df07d54dc8f522a1e4d6 | [] | no_license | artsemkniazeu/devnews-service | https://github.com/artsemkniazeu/devnews-service | 223ae3c99df3d820a3cfc5a410068d950daed47d | 89c1e58e998d4101638236cf3f2944bc2296dca8 | refs/heads/master | 2023-01-09T09:56:36.591000 | 2020-10-27T15:35:20 | 2020-10-27T15:35:20 | 307,744,442 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.dev.news.devnewsservice.security;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import pl.dev.news.devnewsservice.entity.UserEntity;
import pl.dev.news.devnewsservice.exception.NotFoundException;
import pl.dev.news.devnewsservice.exception.UnauthorizedException;
import pl.dev.news.devnewsservice.repository.UserRepository;
import java.util.UUID;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdIsLocked;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdIsNotEnabled;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdNotFound;
@Slf4j
@Component
@AllArgsConstructor
public class TokenAuthenticationProvider implements AuthenticationProvider {
private final TokenProvider tokenProvider;
private final TokenValidator tokenValidator;
private final UserRepository userRepository;
@Override
public Authentication authenticate(final Authentication authentication) {
final TokenAuthentication tokenAuthentication = (TokenAuthentication) authentication;
final String accessToken = tokenAuthentication.getName();
if (tokenValidator.validateAccessToken(accessToken)) {
final UUID userId = tokenProvider.buildUserEntityByToken(accessToken).getId();
final UserEntity user = userRepository.softFindById(userId)
.orElseThrow(() -> new NotFoundException(userWithIdNotFound, userId));
if (!user.isEnabled()) {
throw new UnauthorizedException(userWithIdIsNotEnabled, userId);
}
if (user.isLocked()) {
throw new UnauthorizedException(userWithIdIsLocked, userId);
}
tokenAuthentication.setUserDetails(user);
tokenAuthentication.setAuthenticated(true);
} else {
tokenAuthentication.setAuthenticated(false);
}
return tokenAuthentication;
}
@Override
public boolean supports(final Class<?> authentication) {
return TokenAuthentication.class.equals(authentication);
}
}
| UTF-8 | Java | 2,315 | java | TokenAuthenticationProvider.java | Java | [] | null | [] | package pl.dev.news.devnewsservice.security;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import pl.dev.news.devnewsservice.entity.UserEntity;
import pl.dev.news.devnewsservice.exception.NotFoundException;
import pl.dev.news.devnewsservice.exception.UnauthorizedException;
import pl.dev.news.devnewsservice.repository.UserRepository;
import java.util.UUID;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdIsLocked;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdIsNotEnabled;
import static pl.dev.news.devnewsservice.constants.ExceptionConstants.userWithIdNotFound;
@Slf4j
@Component
@AllArgsConstructor
public class TokenAuthenticationProvider implements AuthenticationProvider {
private final TokenProvider tokenProvider;
private final TokenValidator tokenValidator;
private final UserRepository userRepository;
@Override
public Authentication authenticate(final Authentication authentication) {
final TokenAuthentication tokenAuthentication = (TokenAuthentication) authentication;
final String accessToken = tokenAuthentication.getName();
if (tokenValidator.validateAccessToken(accessToken)) {
final UUID userId = tokenProvider.buildUserEntityByToken(accessToken).getId();
final UserEntity user = userRepository.softFindById(userId)
.orElseThrow(() -> new NotFoundException(userWithIdNotFound, userId));
if (!user.isEnabled()) {
throw new UnauthorizedException(userWithIdIsNotEnabled, userId);
}
if (user.isLocked()) {
throw new UnauthorizedException(userWithIdIsLocked, userId);
}
tokenAuthentication.setUserDetails(user);
tokenAuthentication.setAuthenticated(true);
} else {
tokenAuthentication.setAuthenticated(false);
}
return tokenAuthentication;
}
@Override
public boolean supports(final Class<?> authentication) {
return TokenAuthentication.class.equals(authentication);
}
}
| 2,315 | 0.757235 | 0.75594 | 56 | 40.339287 | 31.009951 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553571 | false | false | 4 |
77dc2709371410683b816353207f3687a21c226b | 23,158,463,719,704 | 8d41c27b8eb74fdbf81ecbee74fab76d30811138 | /Assignment 2/Assignment2.java | 093efb73eb1405e3c6be0c9049fcf07fa968b6b4 | [] | no_license | theduke55/CS-1400 | https://github.com/theduke55/CS-1400 | d00701b1bcb3e5b2b992a85248eedfbc292f57ac | 8b6c85a3988936344974849554f49e7ea1544a54 | refs/heads/master | 2020-09-05T13:13:07.857000 | 2020-01-02T17:21:28 | 2020-01-02T17:21:28 | 220,116,316 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Assignment2
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
//Setting up my variables
String month = "";
int day = 0;
int year = 0;
//Requesting Users DOB
System.out.println("Enter the month were you born: ");
month = in.nextLine();
System.out.println("Enter the day were you born: ");
day = in.nextInt();
System.out.println("Enter the year were you born:");
year = in.nextInt();
//Calculating retirement year
year = year + 67;
//Printing results
System.out.println("You will retire on " + month + " " + day + ", " + year + ".");
}
} | UTF-8 | Java | 883 | java | Assignment2.java | Java | [] | null | [] | import java.util.Scanner;
public class Assignment2
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
//Setting up my variables
String month = "";
int day = 0;
int year = 0;
//Requesting Users DOB
System.out.println("Enter the month were you born: ");
month = in.nextLine();
System.out.println("Enter the day were you born: ");
day = in.nextInt();
System.out.println("Enter the year were you born:");
year = in.nextInt();
//Calculating retirement year
year = year + 67;
//Printing results
System.out.println("You will retire on " + month + " " + day + ", " + year + ".");
}
} | 883 | 0.468856 | 0.463194 | 40 | 20.125 | 20.717369 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 4 |
99b3337b3969c721b190e8c1f9de1bc9b367e7d8 | 11,759,620,493,360 | 569b0874299591893c8b1e1ee3abb9f7ac65a81d | /app/src/main/java/com/whatthehealth/ui/shoppinglist/AddShoppingItemFragment.java | 6bbbfdba0e0c703e027fd44b858dec22e4259be4 | [] | no_license | sylwiaZon/What-the-health | https://github.com/sylwiaZon/What-the-health | e58f4e64c1fc622022575848fb1fe9fc6f75e368 | 398c6e46ad765795d8c1f35feaf198c127eeb7c5 | refs/heads/master | 2022-11-07T11:24:20.384000 | 2020-06-21T17:04:22 | 2020-06-21T17:04:22 | 270,711,817 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.whatthehealth.ui.shoppinglist;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.fragment.app.DialogFragment;
import com.whatthehealth.R;
public class AddShoppingItemFragment extends DialogFragment {
private AddItemDialogListener dialogListener;
public void setDialogListener(AddItemDialogListener dialogListener) {
this.dialogListener = dialogListener;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.add_item_dialog, null);
TextView textView = view.findViewById(R.id.new_item);
builder.setView(view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialogListener.onDialogPositiveClick(textView.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AddShoppingItemFragment.this.getDialog().cancel();
}
});
return builder.create();
}
public interface AddItemDialogListener {
void onDialogPositiveClick(String text);
}
}
| UTF-8 | Java | 1,694 | java | AddShoppingItemFragment.java | Java | [] | null | [] | package com.whatthehealth.ui.shoppinglist;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.fragment.app.DialogFragment;
import com.whatthehealth.R;
public class AddShoppingItemFragment extends DialogFragment {
private AddItemDialogListener dialogListener;
public void setDialogListener(AddItemDialogListener dialogListener) {
this.dialogListener = dialogListener;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.add_item_dialog, null);
TextView textView = view.findViewById(R.id.new_item);
builder.setView(view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialogListener.onDialogPositiveClick(textView.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AddShoppingItemFragment.this.getDialog().cancel();
}
});
return builder.create();
}
public interface AddItemDialogListener {
void onDialogPositiveClick(String text);
}
}
| 1,694 | 0.670012 | 0.670012 | 47 | 35.042553 | 28.021236 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553191 | false | false | 4 |
b714bd8aa30666b95433df7a2b0f1f148b964e27 | 11,759,620,493,913 | e6203fbbf0cd7575380c6df8d9249dfb7b61d86e | /algo/src/main/java/com/hl/algo/divideCity/Chrosome.java | c85425482ca982dac6872dd6492153f4616efeed | [] | no_license | hlherbert/experiment | https://github.com/hlherbert/experiment | 92393ea57283ba22848d00825b72661ebb8d0f95 | 6d74e92bfa7215c111deca2a4e0c6dda23190fe1 | refs/heads/master | 2020-04-14T14:48:30.194000 | 2019-12-06T12:58:08 | 2019-12-06T12:58:08 | 163,907,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hl.algo.divideCity;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* 染色体
*/
public class Chrosome {
// 随机发生器
private static Random rand = new Random();
// A点集
private List<Point> A = new ArrayList<>();
// B点集
private List<Point> B = new ArrayList<>();
// 边
private Edge[] edges;
// 适应度
private int fitness = -1;
// 用flood法求图(Points, Edges)的最大生成树的点数
public static List<Graph> divideConnectGraphs(Graph graph) {
// 候选点集:S,最先是所有点
// 已连通集:P
// i: 连通集的索引
// 0.当S为空时,跳到步骤5.
// 1.从S中任选一个点p, 加入P
// 2.判断S中是否有其他点p2和P相连,如果有,则将p2加入到P。
// 3.重复步骤2,直到没有可选的点能再加入P。
// 4.i++. 将P归为P[i],清空P,跳到步骤1
// 5.找出所有连通集P[i]中size最大值,做的最大生成树的点数。
Graph graphS = graph.clone();
List<Graph> listP = new ArrayList<>();
List<Point> S = graphS.getPoints();
while (!S.isEmpty()) {
List<Point> P = new ArrayList<>();
Point p = S.remove(rand.nextInt(S.size()));
P.add(p);
Point p2;
for (; ; ) {
p2 = findConnectPoint(S, P);
if (p2 == null) {
break;
}
S.remove(p2);
P.add(p2);
}
listP.add(new Graph(P));
}
return listP;
}
// 用flood法求图(Points, Edges)的最大生成树的点数
public static List<List<Point>> divideConnectGraphs(List<Point> S) {
// 候选点集:S,最先是所有点
// 已连通集:P
// i: 连通集的索引
// 0.当S为空时,跳到步骤5.
// 1.从S中任选一个点p, 加入P
// 2.判断S中是否有其他点p2和P相连,如果有,则将p2加入到P。
// 3.重复步骤2,直到没有可选的点能再加入P。
// 4.i++. 将P归为P[i],清空P,跳到步骤1
// 5.找出所有连通集P[i]中size最大值,做的最大生成树的点数。
List<List<Point>> listP = new ArrayList<>();
while (!S.isEmpty()) {
List<Point> P = new ArrayList<>();
Point p = S.remove(rand.nextInt(S.size()));
P.add(p);
Point p2;
for (; ; ) {
p2 = findConnectPoint(S, P);
if (p2 == null) {
break;
}
S.remove(p2);
P.add(p2);
}
listP.add(P);
}
return listP;
}
// 用flood法求图(Points, Edges)的最大生成树的点数
private static int floodTreeSize(List<Point> points) {
List<List<Point>> listP = divideConnectGraphs(points);
int maxSize = listP.stream().mapToInt(pts -> pts.size()).max().getAsInt();
return maxSize;
}
// 从集合S中找到一个点和集合P相连接
// 如果没找到返回null
private static Point findConnectPoint(List<Point> S, List<Point> P) {
for (Point p : S) {
if (isConnect(p, P)) {
return p;
}
}
return null;
}
// 判断点p是否和点集合P连通
private static boolean isConnect(Point p, List<Point> P) {
// 寻找p的所有相邻点,是否有P集合中的点
for (Point pnt : P) {
if (p.neighbourPoints.contains(pnt.getId())) {
return true;
}
}
return false;
}
// 交叉, 生成两个孩子
public static Pair<Chrosome> crossOver(Chrosome c1, Chrosome c2) {
// 单点交叉
// Because we use the Model1and its gene is permutation encoding (Each gene
// is unique in a chromosome), the single point crossover changes to:
// Single point crossover - one crossover point is selected, till this point
// the permutation is copied from the first parent, then the second parent
// is scanned and if the number is not yet in the offspring it is added
// E.g.
// ([1 2 3 4 5] 6 7 8 9) + ([4 5 3 6 8] 9 7 2 1) =>
// ([1 2 3 4 5] 6 8 9 7) + ([4 5 3 6 8] 1 2 7 9)
int nGene = c1.A.size() + c1.B.size();
int crossoverPnt = rand.nextInt(nGene);
Chrosome child1 = c1.clone();
Chrosome child2 = c2.clone();
for (int i = 0; i < crossoverPnt; i++) {
Point gene1 = c1.getGene(i);
Point gene2 = c2.getGene(i);
child1.setGene(i, gene1);
child2.setGene(i, gene2);
}
int k = crossoverPnt;
for (int i = 0; i < nGene && k < nGene; i++) {
Point gene2 = c2.getGene(i);
if (!child1.containGene(gene2, 0, crossoverPnt)) {
child1.setGene(k, gene2);
k++;
}
}
k = crossoverPnt;
for (int i = 0; i < nGene && k < nGene; i++) {
Point gene1 = c1.getGene(i);
if (!child2.containGene(gene1, 0, crossoverPnt)) {
child2.setGene(k, gene1);
k++;
}
}
Pair<Chrosome> pair = new Pair<>(child1, child2);
return pair;
}
// 克隆
public Chrosome clone() {
Chrosome c = new Chrosome();
c.A.addAll(A);
c.B.addAll(B);
c.edges = edges;
return c;
}
public List<Point> getA() {
return A;
}
public void setA(List<Point> a) {
A = a;
}
public List<Point> getB() {
return B;
}
public void setB(List<Point> b) {
B = b;
}
public Edge[] getEdges() {
return edges;
}
public void setEdges(Edge[] edges) {
this.edges = edges;
}
// 求适应度,值越大,适应度越高
public int fit() {
if (fitness >= 0) {
return fitness;
}
// 对本问题,适应度= A中连通点+B中连通点数
int aSize = floodTreeSize(A);
int bSize = floodTreeSize(B);
int fit = aSize + bSize;
fitness = fit;
return fit;
}
// 本染色体是否是可行解
public boolean isSolved(int fit) {
// 当适应度=size(A)+size(B)时,表示找到可行解
return fit == A.size() + B.size();
}
public Point getGene(int index) {
if (index < A.size()) {
return A.get(index);
} else {
return B.get(index - A.size());
}
}
public void setGene(int index, Point p) {
if (index < A.size()) {
A.set(index, p);
} else {
B.set(index - A.size(), p);
}
}
private boolean containGene(Point gene, int rangeLeft, int rangeRight) {
int id = gene.id;
for (int i = rangeLeft; i < rangeRight; i++) {
Point g = this.getGene(i);
if (g.id == id) {
return true;
}
}
return false;
}
// 变异
// 从A,B中各选一个点互相交换
public void mutation() {
int i = rand.nextInt(A.size());
int j = rand.nextInt(B.size());
Point pntA = A.get(i);
A.set(i, B.get(j));
B.set(j, pntA);
}
}
| UTF-8 | Java | 7,508 | java | Chrosome.java | Java | [] | null | [] | package com.hl.algo.divideCity;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* 染色体
*/
public class Chrosome {
// 随机发生器
private static Random rand = new Random();
// A点集
private List<Point> A = new ArrayList<>();
// B点集
private List<Point> B = new ArrayList<>();
// 边
private Edge[] edges;
// 适应度
private int fitness = -1;
// 用flood法求图(Points, Edges)的最大生成树的点数
public static List<Graph> divideConnectGraphs(Graph graph) {
// 候选点集:S,最先是所有点
// 已连通集:P
// i: 连通集的索引
// 0.当S为空时,跳到步骤5.
// 1.从S中任选一个点p, 加入P
// 2.判断S中是否有其他点p2和P相连,如果有,则将p2加入到P。
// 3.重复步骤2,直到没有可选的点能再加入P。
// 4.i++. 将P归为P[i],清空P,跳到步骤1
// 5.找出所有连通集P[i]中size最大值,做的最大生成树的点数。
Graph graphS = graph.clone();
List<Graph> listP = new ArrayList<>();
List<Point> S = graphS.getPoints();
while (!S.isEmpty()) {
List<Point> P = new ArrayList<>();
Point p = S.remove(rand.nextInt(S.size()));
P.add(p);
Point p2;
for (; ; ) {
p2 = findConnectPoint(S, P);
if (p2 == null) {
break;
}
S.remove(p2);
P.add(p2);
}
listP.add(new Graph(P));
}
return listP;
}
// 用flood法求图(Points, Edges)的最大生成树的点数
public static List<List<Point>> divideConnectGraphs(List<Point> S) {
// 候选点集:S,最先是所有点
// 已连通集:P
// i: 连通集的索引
// 0.当S为空时,跳到步骤5.
// 1.从S中任选一个点p, 加入P
// 2.判断S中是否有其他点p2和P相连,如果有,则将p2加入到P。
// 3.重复步骤2,直到没有可选的点能再加入P。
// 4.i++. 将P归为P[i],清空P,跳到步骤1
// 5.找出所有连通集P[i]中size最大值,做的最大生成树的点数。
List<List<Point>> listP = new ArrayList<>();
while (!S.isEmpty()) {
List<Point> P = new ArrayList<>();
Point p = S.remove(rand.nextInt(S.size()));
P.add(p);
Point p2;
for (; ; ) {
p2 = findConnectPoint(S, P);
if (p2 == null) {
break;
}
S.remove(p2);
P.add(p2);
}
listP.add(P);
}
return listP;
}
// 用flood法求图(Points, Edges)的最大生成树的点数
private static int floodTreeSize(List<Point> points) {
List<List<Point>> listP = divideConnectGraphs(points);
int maxSize = listP.stream().mapToInt(pts -> pts.size()).max().getAsInt();
return maxSize;
}
// 从集合S中找到一个点和集合P相连接
// 如果没找到返回null
private static Point findConnectPoint(List<Point> S, List<Point> P) {
for (Point p : S) {
if (isConnect(p, P)) {
return p;
}
}
return null;
}
// 判断点p是否和点集合P连通
private static boolean isConnect(Point p, List<Point> P) {
// 寻找p的所有相邻点,是否有P集合中的点
for (Point pnt : P) {
if (p.neighbourPoints.contains(pnt.getId())) {
return true;
}
}
return false;
}
// 交叉, 生成两个孩子
public static Pair<Chrosome> crossOver(Chrosome c1, Chrosome c2) {
// 单点交叉
// Because we use the Model1and its gene is permutation encoding (Each gene
// is unique in a chromosome), the single point crossover changes to:
// Single point crossover - one crossover point is selected, till this point
// the permutation is copied from the first parent, then the second parent
// is scanned and if the number is not yet in the offspring it is added
// E.g.
// ([1 2 3 4 5] 6 7 8 9) + ([4 5 3 6 8] 9 7 2 1) =>
// ([1 2 3 4 5] 6 8 9 7) + ([4 5 3 6 8] 1 2 7 9)
int nGene = c1.A.size() + c1.B.size();
int crossoverPnt = rand.nextInt(nGene);
Chrosome child1 = c1.clone();
Chrosome child2 = c2.clone();
for (int i = 0; i < crossoverPnt; i++) {
Point gene1 = c1.getGene(i);
Point gene2 = c2.getGene(i);
child1.setGene(i, gene1);
child2.setGene(i, gene2);
}
int k = crossoverPnt;
for (int i = 0; i < nGene && k < nGene; i++) {
Point gene2 = c2.getGene(i);
if (!child1.containGene(gene2, 0, crossoverPnt)) {
child1.setGene(k, gene2);
k++;
}
}
k = crossoverPnt;
for (int i = 0; i < nGene && k < nGene; i++) {
Point gene1 = c1.getGene(i);
if (!child2.containGene(gene1, 0, crossoverPnt)) {
child2.setGene(k, gene1);
k++;
}
}
Pair<Chrosome> pair = new Pair<>(child1, child2);
return pair;
}
// 克隆
public Chrosome clone() {
Chrosome c = new Chrosome();
c.A.addAll(A);
c.B.addAll(B);
c.edges = edges;
return c;
}
public List<Point> getA() {
return A;
}
public void setA(List<Point> a) {
A = a;
}
public List<Point> getB() {
return B;
}
public void setB(List<Point> b) {
B = b;
}
public Edge[] getEdges() {
return edges;
}
public void setEdges(Edge[] edges) {
this.edges = edges;
}
// 求适应度,值越大,适应度越高
public int fit() {
if (fitness >= 0) {
return fitness;
}
// 对本问题,适应度= A中连通点+B中连通点数
int aSize = floodTreeSize(A);
int bSize = floodTreeSize(B);
int fit = aSize + bSize;
fitness = fit;
return fit;
}
// 本染色体是否是可行解
public boolean isSolved(int fit) {
// 当适应度=size(A)+size(B)时,表示找到可行解
return fit == A.size() + B.size();
}
public Point getGene(int index) {
if (index < A.size()) {
return A.get(index);
} else {
return B.get(index - A.size());
}
}
public void setGene(int index, Point p) {
if (index < A.size()) {
A.set(index, p);
} else {
B.set(index - A.size(), p);
}
}
private boolean containGene(Point gene, int rangeLeft, int rangeRight) {
int id = gene.id;
for (int i = rangeLeft; i < rangeRight; i++) {
Point g = this.getGene(i);
if (g.id == id) {
return true;
}
}
return false;
}
// 变异
// 从A,B中各选一个点互相交换
public void mutation() {
int i = rand.nextInt(A.size());
int j = rand.nextInt(B.size());
Point pntA = A.get(i);
A.set(i, B.get(j));
B.set(j, pntA);
}
}
| 7,508 | 0.489489 | 0.473574 | 260 | 24.615385 | 19.322519 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573077 | false | false | 4 |
85f808fec55df8d385bf4a8646dd3692a81a6f53 | 7,937,099,590,945 | b6618b68bcfde72a71cd50bc22b76f34e3e528c0 | /tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/DefaultBeansTest.java | cf22ca867744156fb164cd36f0887443e583fe9c | [] | no_license | ibuziuk/jbosstools-integration-tests | https://github.com/ibuziuk/jbosstools-integration-tests | 55549324de5070d27255a88f369993c95a07484d | c832194438546d43f79abebe603d718583472582 | refs/heads/master | 2021-01-24T05:05:33.995000 | 2015-08-20T15:26:26 | 2015-08-31T12:20:50 | 41,677,117 | 1 | 0 | null | true | 2015-08-31T13:33:43 | 2015-08-31T13:33:43 | 2015-05-07T15:27:56 | 2015-08-31T12:21:19 | 103,505 | 0 | 0 | 0 | null | null | null | /*******************************************************************************
* Copyright (c) 2010-2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.seam3.bot.test.tests;
import static org.junit.Assert.*;
import java.util.List;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerReqType;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerRequirement;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerRequirement.JBossServer;
import org.jboss.reddeer.eclipse.jdt.ui.packageexplorer.PackageExplorer;
import org.jboss.reddeer.jface.text.contentassist.ContentAssistant;
import org.jboss.reddeer.junit.requirement.inject.InjectRequirement;
import org.jboss.reddeer.eclipse.ui.perspectives.JavaEEPerspective;
import org.jboss.reddeer.requirements.cleanworkspace.CleanWorkspaceRequirement.CleanWorkspace;
import org.jboss.reddeer.requirements.openperspective.OpenPerspectiveRequirement.OpenPerspective;
import org.jboss.reddeer.requirements.server.ServerReqState;
import org.jboss.reddeer.workbench.impl.editor.TextEditor;
import org.jboss.tools.cdi.reddeer.CDIConstants;
import org.jboss.tools.cdi.reddeer.cdi.ui.NewBeanCreationWizard;
import org.jboss.tools.cdi.seam3.bot.test.base.SolderAnnotationTestBase;
import org.jboss.tools.cdi.seam3.bot.test.uiutils.AssignableBeansDialogExt;
import org.jboss.tools.cdi.seam3.bot.test.util.SeamLibrary;
import org.junit.After;
import org.junit.Test;
/**
*
* @author jjankovi
*
*/
@CleanWorkspace
@OpenPerspective(JavaEEPerspective.class)
@JBossServer(state=ServerReqState.PRESENT, type=ServerReqType.AS7_1)
public class DefaultBeansTest extends SolderAnnotationTestBase {
private static String projectName = "defaultBeans";
@InjectRequirement
private ServerRequirement sr;
@After
public void waitForJobs() {
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.deleteAllProjects();
}
@Test
public void testProperAssign() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("DefaultOne.java");
}
@Test
public void testProperAssignAlternativesDeactive() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(true);
bw.setRegisterInBeans(false);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideUnavailableBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("DefaultOne"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("DefaultOne.java");
}
@Test
public void testProperUnassign() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(false);
bw.setRegisterInBeans(false);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideDefaultBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("ManagerImpl"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("ManagerImpl.java");
}
@Test
public void testProperUnassignAlternativesActive() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(true);
bw.setRegisterInBeans(true);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideDefaultBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assignDialog.showDefaultBeans();
assignDialog.hideAmbiguousBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("ManagerImpl"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("ManagerImpl.java");;
}
}
| UTF-8 | Java | 7,847 | java | DefaultBeansTest.java | Java | [
{
"context": ".After;\nimport org.junit.Test;\n\n/**\n * \n * @author jjankovi\n * \n */\n@CleanWorkspace\n@OpenPerspective(JavaEEPe",
"end": 1872,
"score": 0.9975890517234802,
"start": 1864,
"tag": "USERNAME",
"value": "jjankovi"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 2010-2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.seam3.bot.test.tests;
import static org.junit.Assert.*;
import java.util.List;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerReqType;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerRequirement;
import org.jboss.ide.eclipse.as.reddeer.server.requirement.ServerRequirement.JBossServer;
import org.jboss.reddeer.eclipse.jdt.ui.packageexplorer.PackageExplorer;
import org.jboss.reddeer.jface.text.contentassist.ContentAssistant;
import org.jboss.reddeer.junit.requirement.inject.InjectRequirement;
import org.jboss.reddeer.eclipse.ui.perspectives.JavaEEPerspective;
import org.jboss.reddeer.requirements.cleanworkspace.CleanWorkspaceRequirement.CleanWorkspace;
import org.jboss.reddeer.requirements.openperspective.OpenPerspectiveRequirement.OpenPerspective;
import org.jboss.reddeer.requirements.server.ServerReqState;
import org.jboss.reddeer.workbench.impl.editor.TextEditor;
import org.jboss.tools.cdi.reddeer.CDIConstants;
import org.jboss.tools.cdi.reddeer.cdi.ui.NewBeanCreationWizard;
import org.jboss.tools.cdi.seam3.bot.test.base.SolderAnnotationTestBase;
import org.jboss.tools.cdi.seam3.bot.test.uiutils.AssignableBeansDialogExt;
import org.jboss.tools.cdi.seam3.bot.test.util.SeamLibrary;
import org.junit.After;
import org.junit.Test;
/**
*
* @author jjankovi
*
*/
@CleanWorkspace
@OpenPerspective(JavaEEPerspective.class)
@JBossServer(state=ServerReqState.PRESENT, type=ServerReqType.AS7_1)
public class DefaultBeansTest extends SolderAnnotationTestBase {
private static String projectName = "defaultBeans";
@InjectRequirement
private ServerRequirement sr;
@After
public void waitForJobs() {
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.deleteAllProjects();
}
@Test
public void testProperAssign() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("DefaultOne.java");
}
@Test
public void testProperAssignAlternativesDeactive() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(true);
bw.setRegisterInBeans(false);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideUnavailableBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("DefaultOne"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("DefaultOne.java");
}
@Test
public void testProperUnassign() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(false);
bw.setRegisterInBeans(false);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideDefaultBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("ManagerImpl"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("ManagerImpl.java");
}
@Test
public void testProperUnassignAlternativesActive() {
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1, sr.getRuntimeNameLabelText(sr.getConfig()));
NewBeanCreationWizard bw = new NewBeanCreationWizard();
bw.open();
bw.setPackage(getPackageName());
bw.setName("ManagerImpl");
bw.setPublic(true);
bw.setAbstract(false);
bw.setFinal(false);
bw.setGenerateComments(false);
bw.setAlternative(true);
bw.setRegisterInBeans(true);
bw.addInterfaces("Manager");
bw.finish();
PackageExplorer pe = new PackageExplorer();
pe.open();
pe.getProject(projectName).getProjectItem(CDIConstants.SRC,getPackageName(), APPLICATION_CLASS).open();
TextEditor te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ContentAssistant ca = te.openOpenOnAssistant();
ca.chooseProposal(CDIConstants.SHOW_ALL_ASSIGNABLE);
AssignableBeansDialogExt assignDialog = new AssignableBeansDialogExt();
List<String> allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 2);
assignDialog.hideDefaultBeans();
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assignDialog.showDefaultBeans();
assignDialog.hideAmbiguousBeans();
assertTrue(allBeans.size() == 1);
allBeans = assignDialog.getAllBeans();
assertTrue(allBeans.size() == 1);
assertTrue(allBeans.get(0).contains("ManagerImpl"));
assignDialog.close();
te = new TextEditor(APPLICATION_CLASS);
te.selectText("managerImpl");
ca = te.openOpenOnAssistant();
for(String p: ca.getProposals()){
if(p.contains(CDIConstants.OPEN_INJECT_BEAN)){
ca.chooseProposal(p);
break;
}
}
new TextEditor("ManagerImpl.java");;
}
}
| 7,847 | 0.739901 | 0.734421 | 245 | 31.028572 | 26.967161 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.110204 | false | false | 4 |
52a9371edf8196526b361d54f471298948539908 | 1,537,598,319,271 | 6f6643bb625fc68b8a860d66978bb666c842ca09 | /Medium/NumberOfIslands.java | 1ecdde2d5bb3ebfbf48eb9eb2c9fb60d46b30a9c | [] | no_license | Uzairfaraz20/Leetcode_Solutions | https://github.com/Uzairfaraz20/Leetcode_Solutions | 6b0fd55d2df99683c3b66a9289871344c0092a05 | ac7b4ce3b683282f4abd8c8b1a85239d1e0be9f0 | refs/heads/master | 2022-11-27T11:57:30.325000 | 2020-08-06T15:27:09 | 2020-08-06T15:27:09 | 258,435,779 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
public int numIslands(char[][] grid) {
int count = 0; //total count of islands
//loop through all posiitons in the 2d array
for(int x = 0; x < grid.length; x++){
for(int y = 0; y < grid[x].length; y++){
//if we find a one
if(grid[x][y] == '1'){
//finding a 1 guarentees an island so increment
count += 1;
//call the bfs function on this position
zeroifyBFS(grid,x,y);
}
}
}
return count;
}
//bfs helper to clear out an island of ones
public void zeroifyBFS(char[][] grid, int x, int y){
//if the position is out of bounds or 0, then leave it alone
if(x < 0 || y < 0 || x >= grid.length || y >= grid[x].length || grid[x][y] == '0'){return;}
//clear the current position
grid[x][y] = '0';
//call bfs on all adjacent positions and clear out the island
zeroifyBFS(grid,x+1,y);
zeroifyBFS(grid,x-1,y);
zeroifyBFS(grid,x,y+1);
zeroifyBFS(grid,x,y-1);
}
} | UTF-8 | Java | 1,205 | java | NumberOfIslands.java | Java | [] | null | [] | class Solution {
public int numIslands(char[][] grid) {
int count = 0; //total count of islands
//loop through all posiitons in the 2d array
for(int x = 0; x < grid.length; x++){
for(int y = 0; y < grid[x].length; y++){
//if we find a one
if(grid[x][y] == '1'){
//finding a 1 guarentees an island so increment
count += 1;
//call the bfs function on this position
zeroifyBFS(grid,x,y);
}
}
}
return count;
}
//bfs helper to clear out an island of ones
public void zeroifyBFS(char[][] grid, int x, int y){
//if the position is out of bounds or 0, then leave it alone
if(x < 0 || y < 0 || x >= grid.length || y >= grid[x].length || grid[x][y] == '0'){return;}
//clear the current position
grid[x][y] = '0';
//call bfs on all adjacent positions and clear out the island
zeroifyBFS(grid,x+1,y);
zeroifyBFS(grid,x-1,y);
zeroifyBFS(grid,x,y+1);
zeroifyBFS(grid,x,y-1);
}
} | 1,205 | 0.473859 | 0.460581 | 38 | 30.736841 | 23.379799 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.921053 | false | false | 4 |
5e25ec737a013dbcd572e30cb1ef235feb6d3a22 | 2,456,721,360,603 | 70d2dab8fe9d7cac39bc371d009cfa4c7babf145 | /MagicRealm/src/lwjglview/controller/board/counter/LWJGLCounterCollection.java | a978f8d710f0876684b2cb3bfb06f628ce61869f | [] | no_license | elyas145/MagicRealm | https://github.com/elyas145/MagicRealm | 6c6eb63e2f6c75f11c74e6a0f42879e232f0e971 | cb2a1c0899222458dff58c698059515309877f54 | refs/heads/master | 2021-01-01T03:59:49.080000 | 2016-05-03T13:53:04 | 2016-05-03T13:53:04 | 57,972,244 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lwjglview.controller.board.counter;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import utils.math.linear.Matrix;
import utils.resources.LWJGLCounterGenerator;
import utils.resources.ResourceHandler;
import lwjglview.graphics.LWJGLDrawableNode;
import lwjglview.graphics.LWJGLGraphics;
import lwjglview.graphics.counters.LWJGLCounterDrawable;
import lwjglview.graphics.counters.LWJGLCounterLocator;
import lwjglview.graphics.shader.ShaderType;
import model.enums.CharacterType;
import model.enums.CounterType;
import model.enums.ValleyChit;
public class LWJGLCounterCollection extends LWJGLDrawableNode {
public LWJGLCounterCollection(LWJGLCounterLocator par, ResourceHandler res)
throws IOException {
super(par);
locations = par;
resources = res.getCounterGenerator();
counters = new HashMap<CounterType, LWJGLCounterDrawable>();
List<CounterType> counters = new ArrayList<CounterType>();
for (CharacterType ct : CharacterType.values()) {
counters.add(ct.toCounter());
}
for (ValleyChit vc : ValleyChit.values()) {
counters.add(vc.toCounterType());
}
}
public LWJGLCounterDrawable get(CounterType counter) {
return counters.get(counter);
}
public LWJGLCounterDrawable create(CounterType tp) {
synchronized (counters) {
counters.put(tp, resources.generate(tp, locations));
}
return get(tp);
}
public boolean contains(CounterType ct) {
synchronized (counters) {
return counters.containsKey(ct);
}
}
public void getVector(CounterType count, Matrix dest) {
get(count).getVector(dest);
}
public boolean isAnimationFinished(CounterType ct) {
return get(ct).isAnimationFinished();
}
public void moveTo(CounterType ct, Matrix pos) {
get(ct).moveTo(pos);
}
public void changeColour(CounterType ct, Color col) {
get(ct).changeColour(col);
}
@Override
public void updateNodeUniforms(LWJGLGraphics gfx) {
}
@Override
public void draw(LWJGLGraphics gfx) {
updateTransformation();
gfx.getShaders().useShaderProgram(ShaderType.CHIT_SHADER);
// draw all counters
synchronized (counters) {
for (LWJGLCounterDrawable counter : counters.values()) {
counter.draw(gfx);
}
}
}
private LWJGLCounterLocator locations;
private Map<CounterType, LWJGLCounterDrawable> counters;
private LWJGLCounterGenerator resources;
}
| UTF-8 | Java | 2,421 | java | LWJGLCounterCollection.java | Java | [] | null | [] | package lwjglview.controller.board.counter;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import utils.math.linear.Matrix;
import utils.resources.LWJGLCounterGenerator;
import utils.resources.ResourceHandler;
import lwjglview.graphics.LWJGLDrawableNode;
import lwjglview.graphics.LWJGLGraphics;
import lwjglview.graphics.counters.LWJGLCounterDrawable;
import lwjglview.graphics.counters.LWJGLCounterLocator;
import lwjglview.graphics.shader.ShaderType;
import model.enums.CharacterType;
import model.enums.CounterType;
import model.enums.ValleyChit;
public class LWJGLCounterCollection extends LWJGLDrawableNode {
public LWJGLCounterCollection(LWJGLCounterLocator par, ResourceHandler res)
throws IOException {
super(par);
locations = par;
resources = res.getCounterGenerator();
counters = new HashMap<CounterType, LWJGLCounterDrawable>();
List<CounterType> counters = new ArrayList<CounterType>();
for (CharacterType ct : CharacterType.values()) {
counters.add(ct.toCounter());
}
for (ValleyChit vc : ValleyChit.values()) {
counters.add(vc.toCounterType());
}
}
public LWJGLCounterDrawable get(CounterType counter) {
return counters.get(counter);
}
public LWJGLCounterDrawable create(CounterType tp) {
synchronized (counters) {
counters.put(tp, resources.generate(tp, locations));
}
return get(tp);
}
public boolean contains(CounterType ct) {
synchronized (counters) {
return counters.containsKey(ct);
}
}
public void getVector(CounterType count, Matrix dest) {
get(count).getVector(dest);
}
public boolean isAnimationFinished(CounterType ct) {
return get(ct).isAnimationFinished();
}
public void moveTo(CounterType ct, Matrix pos) {
get(ct).moveTo(pos);
}
public void changeColour(CounterType ct, Color col) {
get(ct).changeColour(col);
}
@Override
public void updateNodeUniforms(LWJGLGraphics gfx) {
}
@Override
public void draw(LWJGLGraphics gfx) {
updateTransformation();
gfx.getShaders().useShaderProgram(ShaderType.CHIT_SHADER);
// draw all counters
synchronized (counters) {
for (LWJGLCounterDrawable counter : counters.values()) {
counter.draw(gfx);
}
}
}
private LWJGLCounterLocator locations;
private Map<CounterType, LWJGLCounterDrawable> counters;
private LWJGLCounterGenerator resources;
}
| 2,421 | 0.768691 | 0.768691 | 92 | 25.315218 | 21.377522 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.576087 | false | false | 4 |
e72b5a3f1bd51022d872d075772072feaf6383f2 | 26,534,308,011,852 | e98d1862f614c0945d0d2556b6324a708b4bd811 | /Xulu 1.5.2/com/elementars/eclient/guirewrite/elements/TextNotes.java | 23fb47e4ee2756776c61645be623c4e99841c925 | [] | no_license | chocopie69/Minecraft-Modifications-Codes | https://github.com/chocopie69/Minecraft-Modifications-Codes | 946f7fd2b431b1e3c4272cf96d75460883468917 | a843aa9163e9e508e74dad10572d68477e5e38bf | refs/heads/main | 2023-08-27T08:46:06.036000 | 2022-06-25T14:35:06 | 2022-06-25T14:35:06 | 412,120,508 | 71 | 54 | null | false | 2022-01-11T15:55:25 | 2021-09-30T15:30:35 | 2022-01-10T04:52:49 | 2022-01-09T16:44:51 | 331,436 | 4 | 2 | 3 | null | false | false | //
// Decompiled by Procyon v0.5.36
//
package com.elementars.eclient.guirewrite.elements;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class TextNotes extends JFrame
{
JPanel jp;
JLabel jl;
JTextField jt;
JButton jb;
public TextNotes() {
this.jp = new JPanel();
this.jl = new JLabel();
this.jt = new JTextField(30);
this.jb = new JButton("Set Text");
this.setTitle("TextNotes");
this.setVisible(true);
this.setSize(400, 200);
this.setDefaultCloseOperation(1);
this.jp.add(this.jt);
this.jt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String input = TextNotes.this.jt.getText();
TextNotes.this.jl.setText(input);
}
});
this.jp.add(this.jb);
this.jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String input = TextNotes.this.jt.getText();
StickyNotes.processText(input);
}
});
this.jp.add(this.jl);
this.add(this.jp);
}
public static void initTextBox() {
final TextNotes t = new TextNotes();
}
}
| UTF-8 | Java | 1,543 | java | TextNotes.java | Java | [] | null | [] | //
// Decompiled by Procyon v0.5.36
//
package com.elementars.eclient.guirewrite.elements;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class TextNotes extends JFrame
{
JPanel jp;
JLabel jl;
JTextField jt;
JButton jb;
public TextNotes() {
this.jp = new JPanel();
this.jl = new JLabel();
this.jt = new JTextField(30);
this.jb = new JButton("Set Text");
this.setTitle("TextNotes");
this.setVisible(true);
this.setSize(400, 200);
this.setDefaultCloseOperation(1);
this.jp.add(this.jt);
this.jt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String input = TextNotes.this.jt.getText();
TextNotes.this.jl.setText(input);
}
});
this.jp.add(this.jb);
this.jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String input = TextNotes.this.jt.getText();
StickyNotes.processText(input);
}
});
this.jp.add(this.jl);
this.add(this.jp);
}
public static void initTextBox() {
final TextNotes t = new TextNotes();
}
}
| 1,543 | 0.604666 | 0.596241 | 55 | 27.054546 | 18.139278 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 4 |
748288fc762be27b989bce9df59fc707d20128c2 | 3,478,923,554,283 | 9a3d15777c25e585a2c00857c34e651ec5afa312 | /huiyi/src/main/java/com/mvc/member/service/BusinessTypeManager.java | e2fd27c0989d94567ff327c09ddffe44f4219a16 | [] | no_license | avords/huiyi | https://github.com/avords/huiyi | ce583098045f4923c634d3d16dcabe945b1c0699 | 41fa957bd27d1f2a231c53a05fb09f65dee5a760 | refs/heads/master | 2016-08-12T02:28:12.761000 | 2016-03-30T04:27:43 | 2016-03-30T04:27:43 | 55,032,156 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mvc.member.service;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Service;
import com.mvc.framework.service.BaseService;
import com.mvc.member.model.BusinessType;
@Service
public class BusinessTypeManager extends BaseService<BusinessType, Serializable>{
public List<BusinessType> getBusinessTypeByCompanyId(Long companyId){
return searchBySql("select A from " + BusinessType.class.getName() +" A where A.companyId = ?", companyId);
}
public void deleteByCompanyId(Long companyId){
super.deleteByWhere("companyId = " + companyId);
}
}
| UTF-8 | Java | 627 | java | BusinessTypeManager.java | Java | [] | null | [] | package com.mvc.member.service;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Service;
import com.mvc.framework.service.BaseService;
import com.mvc.member.model.BusinessType;
@Service
public class BusinessTypeManager extends BaseService<BusinessType, Serializable>{
public List<BusinessType> getBusinessTypeByCompanyId(Long companyId){
return searchBySql("select A from " + BusinessType.class.getName() +" A where A.companyId = ?", companyId);
}
public void deleteByCompanyId(Long companyId){
super.deleteByWhere("companyId = " + companyId);
}
}
| 627 | 0.759171 | 0.759171 | 21 | 27.857143 | 30.768391 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.952381 | false | false | 4 |
c4f639dd432366d0481560cfb68c72b8e0400da0 | 27,084,063,777,213 | 6a625032bbc989ca2a598f2ac8c29626369c3894 | /core/src/main/java/com/gapfyl/services/notifications/NotificationService.java | 3e03f48b7ec3da77bd5ae03d3e617e6d6256b8bd | [] | no_license | vigneshwaran26/gapfyl_application | https://github.com/vigneshwaran26/gapfyl_application | 037caf26d3916f5be127d8a33d3867d8e944ceff | b1c9e2fb5b6abaac665b51cac4957e10f5f284a6 | refs/heads/master | 2023-08-28T14:14:27.628000 | 2021-09-19T18:02:03 | 2021-09-19T18:02:03 | 408,198,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gapfyl.services.notifications;
import com.gapfyl.dto.notifications.Notification;
import com.gapfyl.models.users.UserEntity;
import java.util.List;
public interface NotificationService {
Notification createNotification(Notification notificationDTO, UserEntity userEntity);
List<Notification> fetchUserNotifications(UserEntity userEntity);
}
| UTF-8 | Java | 366 | java | NotificationService.java | Java | [] | null | [] | package com.gapfyl.services.notifications;
import com.gapfyl.dto.notifications.Notification;
import com.gapfyl.models.users.UserEntity;
import java.util.List;
public interface NotificationService {
Notification createNotification(Notification notificationDTO, UserEntity userEntity);
List<Notification> fetchUserNotifications(UserEntity userEntity);
}
| 366 | 0.827869 | 0.827869 | 14 | 25.142857 | 28.896013 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
8f247596d5fd4689e1f0286a6160ee6a0a2e2b44 | 21,328,807,632,922 | 72b968cf8e1d0378f4a94f498e5071f3e0d63e00 | /src/day14_StringClass/day14_StringClass.java | eef00aa36224d067de6b9e10ca643d0f8d68b86c | [] | no_license | gsaltug/Java2020Class | https://github.com/gsaltug/Java2020Class | c18544cfe2da727928fcb01667a025176856ac95 | dcee1d09c777dfedaa575a3a6435736ba789918e | refs/heads/master | 2022-07-10T19:18:58.875000 | 2020-05-17T20:51:29 | 2020-05-17T20:51:29 | 259,124,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day14_StringClass;
import java.util.Scanner;
public class day14_StringClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first word:");
String word1 = input.next();
System.out.println("Enter second word:");
String word2 =input.next();
/*
print one two two one
*/
String result = word1.concat(word2).concat(word2).concat(word1);
System.out.println(result);
System.out.println("Enter first word:");
String word3 = input.next();
word3= word3.substring(1, word3.length());
System.out.println("Enter second word:");
String word4 = input.next();
word4 = word4.substring(1, word4.length());
String result1 =word3+word4;
System.out.println(result1);
}
}
| UTF-8 | Java | 884 | java | day14_StringClass.java | Java | [] | null | [] | package day14_StringClass;
import java.util.Scanner;
public class day14_StringClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first word:");
String word1 = input.next();
System.out.println("Enter second word:");
String word2 =input.next();
/*
print one two two one
*/
String result = word1.concat(word2).concat(word2).concat(word1);
System.out.println(result);
System.out.println("Enter first word:");
String word3 = input.next();
word3= word3.substring(1, word3.length());
System.out.println("Enter second word:");
String word4 = input.next();
word4 = word4.substring(1, word4.length());
String result1 =word3+word4;
System.out.println(result1);
}
}
| 884 | 0.599548 | 0.572398 | 35 | 24.257143 | 21.24193 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.542857 | false | false | 4 |
b97d1f80d6942f7848e83324ad9549b6e3053ddd | 14,370,960,628,599 | 41c388c814e6e8bac76e4da9535d6f584e4907c5 | /project/prx-core/src/main/java/cn/sunline/prx/core/uid/id/RemoteIDService.java | 95c39e8a85ec44cfd5fc3080091364634366db78 | [] | no_license | sunline360/myprx | https://github.com/sunline360/myprx | acb934e2370e950d442d7df0048724355b5315f7 | 5c4befc710dd94747482312a20d86d926a48a63c | refs/heads/master | 2018-01-11T07:43:10.262000 | 2014-11-18T12:53:08 | 2014-11-18T12:53:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2014, prx-system[nic lee] All Rights Reserved.
*/
package cn.sunline.prx.core.uid.id;
import cn.sunline.prx.core.uid.UniqueIDGenerator;
import cn.sunline.prx.core.uid.UniqueIDService;
/**
* Function: TODO add funtion description. <br/>
* @author nic lee
* @since 0.0.1
* @see
*/
public class RemoteIDService implements UniqueIDService {
@Override
public UniqueIDGenerator getGenerator(String name) {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 523 | java | RemoteIDService.java | Java | [
{
"context": ": TODO add funtion description. <br/>\n * @author nic lee\n * @since 0.0.1\n * @see \t \n */\npublic class Re",
"end": 284,
"score": 0.9996891021728516,
"start": 277,
"tag": "NAME",
"value": "nic lee"
}
] | null | [] | /**
* Copyright (c) 2014, prx-system[nic lee] All Rights Reserved.
*/
package cn.sunline.prx.core.uid.id;
import cn.sunline.prx.core.uid.UniqueIDGenerator;
import cn.sunline.prx.core.uid.UniqueIDService;
/**
* Function: TODO add funtion description. <br/>
* @author <NAME>
* @since 0.0.1
* @see
*/
public class RemoteIDService implements UniqueIDService {
@Override
public UniqueIDGenerator getGenerator(String name) {
// TODO Auto-generated method stub
return null;
}
}
| 522 | 0.678776 | 0.665392 | 24 | 20.75 | 22.017511 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
d9567113cd93092ab0563013fb964c0cb945a4b5 | 20,031,727,507,695 | 97e92b8adb8cad8a5e3939c5023f06ff6ef57e69 | /src/heap/Test2.java | de896bb5bac1220435ff04d549e8b5c38b2d20f1 | [] | no_license | sport0102/algorithm-programmers | https://github.com/sport0102/algorithm-programmers | 9cd0ae70ec05b915c290e217ed8ea6d5ed3eda6a | 03737898003c4da9671821a3aec65bb57271846a | refs/heads/master | 2020-07-30T14:57:23.662000 | 2019-11-06T06:52:07 | 2019-11-06T06:52:07 | 210,269,901 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package heap;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
public class Test2 {
public static void main(String[] args) {
// int stock = 4;
// int[] dates = {4, 10, 15};
// int[] supplies = {20, 5, 10};
// int k = 30;
// 답 2
// int stock = 10;
// int[] dates = {5, 10};
// int[] supplies = {1, 100};
// int k = 100;
// 답 1
// int stock = 4;
// int[] dates = {1, 2, 3,4};
// int[] supplies = {10, 40, 20,30};
// int k = 100;
// 닶 4
int stock = 4;
int[] dates = {1, 2, 3, 4};
int[] supplies = {10, 40, 30, 20};
int k = 100;
// 닶 4
// int stock = 2;
// int[] dates = {1};
// int[] supplies = {10};
// int k = 10;
// 답 1
System.out.println(solution(stock, dates, supplies, k));
}
static int solution(int stock, int[] dates, int[] supplies, int k) {
PriorityQueue<Integer> pqSupplies = new PriorityQueue<>(Comparator.reverseOrder());
int spIdx = 0;
int cnt = 0;
for (int day = 0; day < k; day++) {
System.out.println("day : "+day);
if (spIdx < dates.length && day >= dates[spIdx]) {
pqSupplies.add(supplies[spIdx]);
System.out.println("supplies[spIdx] : "+supplies[spIdx]);
spIdx++;
System.out.println("spIdx : "+spIdx);
}
if (stock <= 0) {
stock += pqSupplies.remove();
System.out.println("0 stock : "+stock);
cnt++;
}
stock--;
System.out.println("stock : "+stock);
}
return cnt;
}
// static int solution(int stock, int[] dates, int[] supplies, int k) {
// int supplyCount = 0;
// int day = 1;
// LinkedList<Integer> dateQueue = new LinkedList<>();
// LinkedList<Integer> supplyQueue = new LinkedList<>();
// for (int i = 0; i < dates.length; i++) {
// dateQueue.add(dates[i]);
// supplyQueue.add(supplies[i]);
// }
// int supplyDate = 0;
// int supplyQuantity = 0;
// System.out.println("k : " + k);
// while (day < k) {
// System.out.println("day : " + day);
// stock--;
// System.out.println("stock : " + stock);
// if (stock == 0) {
// while (day > supplyDate && !dateQueue.isEmpty()) {
// supplyDate = dateQueue.poll();
// supplyQuantity = supplyQueue.poll();
// }
// System.out.println("supplyQuantity : " + supplyQuantity);
// stock += supplyQuantity;
// supplyCount++;
// System.out.println("supplyCount : " + supplyCount);
// }
// day++;
// }
// return supplyCount;
// }
}
| UTF-8 | Java | 2,997 | java | Test2.java | Java | [] | null | [] | package heap;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
public class Test2 {
public static void main(String[] args) {
// int stock = 4;
// int[] dates = {4, 10, 15};
// int[] supplies = {20, 5, 10};
// int k = 30;
// 답 2
// int stock = 10;
// int[] dates = {5, 10};
// int[] supplies = {1, 100};
// int k = 100;
// 답 1
// int stock = 4;
// int[] dates = {1, 2, 3,4};
// int[] supplies = {10, 40, 20,30};
// int k = 100;
// 닶 4
int stock = 4;
int[] dates = {1, 2, 3, 4};
int[] supplies = {10, 40, 30, 20};
int k = 100;
// 닶 4
// int stock = 2;
// int[] dates = {1};
// int[] supplies = {10};
// int k = 10;
// 답 1
System.out.println(solution(stock, dates, supplies, k));
}
static int solution(int stock, int[] dates, int[] supplies, int k) {
PriorityQueue<Integer> pqSupplies = new PriorityQueue<>(Comparator.reverseOrder());
int spIdx = 0;
int cnt = 0;
for (int day = 0; day < k; day++) {
System.out.println("day : "+day);
if (spIdx < dates.length && day >= dates[spIdx]) {
pqSupplies.add(supplies[spIdx]);
System.out.println("supplies[spIdx] : "+supplies[spIdx]);
spIdx++;
System.out.println("spIdx : "+spIdx);
}
if (stock <= 0) {
stock += pqSupplies.remove();
System.out.println("0 stock : "+stock);
cnt++;
}
stock--;
System.out.println("stock : "+stock);
}
return cnt;
}
// static int solution(int stock, int[] dates, int[] supplies, int k) {
// int supplyCount = 0;
// int day = 1;
// LinkedList<Integer> dateQueue = new LinkedList<>();
// LinkedList<Integer> supplyQueue = new LinkedList<>();
// for (int i = 0; i < dates.length; i++) {
// dateQueue.add(dates[i]);
// supplyQueue.add(supplies[i]);
// }
// int supplyDate = 0;
// int supplyQuantity = 0;
// System.out.println("k : " + k);
// while (day < k) {
// System.out.println("day : " + day);
// stock--;
// System.out.println("stock : " + stock);
// if (stock == 0) {
// while (day > supplyDate && !dateQueue.isEmpty()) {
// supplyDate = dateQueue.poll();
// supplyQuantity = supplyQueue.poll();
// }
// System.out.println("supplyQuantity : " + supplyQuantity);
// stock += supplyQuantity;
// supplyCount++;
// System.out.println("supplyCount : " + supplyCount);
// }
// day++;
// }
// return supplyCount;
// }
}
| 2,997 | 0.452963 | 0.42618 | 96 | 30.114584 | 20.803581 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false | 4 |
759d651e2ccd13ad62fb034198a4c7aebf63f9df | 10,067,403,385,773 | 806a5eacfc88121a594a81162a5b454ef5595169 | /src/test/java/ma/greensupply/erm/web/rest/ProprietaireActionResourceIT.java | 9a2e5f030d42de7ec82a9fdddf98d8e45c65d67d | [] | no_license | manalmadaniy/ERM | https://github.com/manalmadaniy/ERM | bb0e12ebf73be004d393eae5ea10c7da99b17487 | 5aa7c46d448c0332db69d8fefcd2df8e42f5babe | refs/heads/master | 2023-01-01T20:25:22.922000 | 2020-10-17T10:24:03 | 2020-10-17T10:24:03 | 294,349,422 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ma.greensupply.erm.web.rest;
import ma.greensupply.erm.KompliansApp;
import ma.greensupply.erm.domain.ProprietaireAction;
import ma.greensupply.erm.repository.ProprietaireActionRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link ProprietaireActionResource} REST controller.
*/
@SpringBootTest(classes = KompliansApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class ProprietaireActionResourceIT {
private static final String DEFAULT_NOM = "AAAAAAAAAA";
private static final String UPDATED_NOM = "BBBBBBBBBB";
private static final String DEFAULT_PRENOM = "AAAAAAAAAA";
private static final String UPDATED_PRENOM = "BBBBBBBBBB";
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
@Autowired
private ProprietaireActionRepository proprietaireActionRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restProprietaireActionMockMvc;
private ProprietaireAction proprietaireAction;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProprietaireAction createEntity(EntityManager em) {
ProprietaireAction proprietaireAction = new ProprietaireAction()
.nom(DEFAULT_NOM)
.prenom(DEFAULT_PRENOM)
.email(DEFAULT_EMAIL);
return proprietaireAction;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProprietaireAction createUpdatedEntity(EntityManager em) {
ProprietaireAction proprietaireAction = new ProprietaireAction()
.nom(UPDATED_NOM)
.prenom(UPDATED_PRENOM)
.email(UPDATED_EMAIL);
return proprietaireAction;
}
@BeforeEach
public void initTest() {
proprietaireAction = createEntity(em);
}
@Test
@Transactional
public void createProprietaireAction() throws Exception {
int databaseSizeBeforeCreate = proprietaireActionRepository.findAll().size();
// Create the ProprietaireAction
restProprietaireActionMockMvc.perform(post("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isCreated());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeCreate + 1);
ProprietaireAction testProprietaireAction = proprietaireActionList.get(proprietaireActionList.size() - 1);
assertThat(testProprietaireAction.getNom()).isEqualTo(DEFAULT_NOM);
assertThat(testProprietaireAction.getPrenom()).isEqualTo(DEFAULT_PRENOM);
assertThat(testProprietaireAction.getEmail()).isEqualTo(DEFAULT_EMAIL);
}
@Test
@Transactional
public void createProprietaireActionWithExistingId() throws Exception {
int databaseSizeBeforeCreate = proprietaireActionRepository.findAll().size();
// Create the ProprietaireAction with an existing ID
proprietaireAction.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restProprietaireActionMockMvc.perform(post("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isBadRequest());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllProprietaireActions() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
// Get all the proprietaireActionList
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(proprietaireAction.getId().intValue())))
.andExpect(jsonPath("$.[*].nom").value(hasItem(DEFAULT_NOM)))
.andExpect(jsonPath("$.[*].prenom").value(hasItem(DEFAULT_PRENOM)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)));
}
@Test
@Transactional
public void getProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
// Get the proprietaireAction
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions/{id}", proprietaireAction.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(proprietaireAction.getId().intValue()))
.andExpect(jsonPath("$.nom").value(DEFAULT_NOM))
.andExpect(jsonPath("$.prenom").value(DEFAULT_PRENOM))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL));
}
@Test
@Transactional
public void getNonExistingProprietaireAction() throws Exception {
// Get the proprietaireAction
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
int databaseSizeBeforeUpdate = proprietaireActionRepository.findAll().size();
// Update the proprietaireAction
ProprietaireAction updatedProprietaireAction = proprietaireActionRepository.findById(proprietaireAction.getId()).get();
// Disconnect from session so that the updates on updatedProprietaireAction are not directly saved in db
em.detach(updatedProprietaireAction);
updatedProprietaireAction
.nom(UPDATED_NOM)
.prenom(UPDATED_PRENOM)
.email(UPDATED_EMAIL);
restProprietaireActionMockMvc.perform(put("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedProprietaireAction)))
.andExpect(status().isOk());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeUpdate);
ProprietaireAction testProprietaireAction = proprietaireActionList.get(proprietaireActionList.size() - 1);
assertThat(testProprietaireAction.getNom()).isEqualTo(UPDATED_NOM);
assertThat(testProprietaireAction.getPrenom()).isEqualTo(UPDATED_PRENOM);
assertThat(testProprietaireAction.getEmail()).isEqualTo(UPDATED_EMAIL);
}
@Test
@Transactional
public void updateNonExistingProprietaireAction() throws Exception {
int databaseSizeBeforeUpdate = proprietaireActionRepository.findAll().size();
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProprietaireActionMockMvc.perform(put("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isBadRequest());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
int databaseSizeBeforeDelete = proprietaireActionRepository.findAll().size();
// Delete the proprietaireAction
restProprietaireActionMockMvc.perform(delete("/api/proprietaire-actions/{id}", proprietaireAction.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| UTF-8 | Java | 9,952 | java | ProprietaireActionResourceIT.java | Java | [] | null | [] | package ma.greensupply.erm.web.rest;
import ma.greensupply.erm.KompliansApp;
import ma.greensupply.erm.domain.ProprietaireAction;
import ma.greensupply.erm.repository.ProprietaireActionRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link ProprietaireActionResource} REST controller.
*/
@SpringBootTest(classes = KompliansApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class ProprietaireActionResourceIT {
private static final String DEFAULT_NOM = "AAAAAAAAAA";
private static final String UPDATED_NOM = "BBBBBBBBBB";
private static final String DEFAULT_PRENOM = "AAAAAAAAAA";
private static final String UPDATED_PRENOM = "BBBBBBBBBB";
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
@Autowired
private ProprietaireActionRepository proprietaireActionRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restProprietaireActionMockMvc;
private ProprietaireAction proprietaireAction;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProprietaireAction createEntity(EntityManager em) {
ProprietaireAction proprietaireAction = new ProprietaireAction()
.nom(DEFAULT_NOM)
.prenom(DEFAULT_PRENOM)
.email(DEFAULT_EMAIL);
return proprietaireAction;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProprietaireAction createUpdatedEntity(EntityManager em) {
ProprietaireAction proprietaireAction = new ProprietaireAction()
.nom(UPDATED_NOM)
.prenom(UPDATED_PRENOM)
.email(UPDATED_EMAIL);
return proprietaireAction;
}
@BeforeEach
public void initTest() {
proprietaireAction = createEntity(em);
}
@Test
@Transactional
public void createProprietaireAction() throws Exception {
int databaseSizeBeforeCreate = proprietaireActionRepository.findAll().size();
// Create the ProprietaireAction
restProprietaireActionMockMvc.perform(post("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isCreated());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeCreate + 1);
ProprietaireAction testProprietaireAction = proprietaireActionList.get(proprietaireActionList.size() - 1);
assertThat(testProprietaireAction.getNom()).isEqualTo(DEFAULT_NOM);
assertThat(testProprietaireAction.getPrenom()).isEqualTo(DEFAULT_PRENOM);
assertThat(testProprietaireAction.getEmail()).isEqualTo(DEFAULT_EMAIL);
}
@Test
@Transactional
public void createProprietaireActionWithExistingId() throws Exception {
int databaseSizeBeforeCreate = proprietaireActionRepository.findAll().size();
// Create the ProprietaireAction with an existing ID
proprietaireAction.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restProprietaireActionMockMvc.perform(post("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isBadRequest());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllProprietaireActions() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
// Get all the proprietaireActionList
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(proprietaireAction.getId().intValue())))
.andExpect(jsonPath("$.[*].nom").value(hasItem(DEFAULT_NOM)))
.andExpect(jsonPath("$.[*].prenom").value(hasItem(DEFAULT_PRENOM)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)));
}
@Test
@Transactional
public void getProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
// Get the proprietaireAction
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions/{id}", proprietaireAction.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(proprietaireAction.getId().intValue()))
.andExpect(jsonPath("$.nom").value(DEFAULT_NOM))
.andExpect(jsonPath("$.prenom").value(DEFAULT_PRENOM))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL));
}
@Test
@Transactional
public void getNonExistingProprietaireAction() throws Exception {
// Get the proprietaireAction
restProprietaireActionMockMvc.perform(get("/api/proprietaire-actions/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
int databaseSizeBeforeUpdate = proprietaireActionRepository.findAll().size();
// Update the proprietaireAction
ProprietaireAction updatedProprietaireAction = proprietaireActionRepository.findById(proprietaireAction.getId()).get();
// Disconnect from session so that the updates on updatedProprietaireAction are not directly saved in db
em.detach(updatedProprietaireAction);
updatedProprietaireAction
.nom(UPDATED_NOM)
.prenom(UPDATED_PRENOM)
.email(UPDATED_EMAIL);
restProprietaireActionMockMvc.perform(put("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedProprietaireAction)))
.andExpect(status().isOk());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeUpdate);
ProprietaireAction testProprietaireAction = proprietaireActionList.get(proprietaireActionList.size() - 1);
assertThat(testProprietaireAction.getNom()).isEqualTo(UPDATED_NOM);
assertThat(testProprietaireAction.getPrenom()).isEqualTo(UPDATED_PRENOM);
assertThat(testProprietaireAction.getEmail()).isEqualTo(UPDATED_EMAIL);
}
@Test
@Transactional
public void updateNonExistingProprietaireAction() throws Exception {
int databaseSizeBeforeUpdate = proprietaireActionRepository.findAll().size();
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProprietaireActionMockMvc.perform(put("/api/proprietaire-actions")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(proprietaireAction)))
.andExpect(status().isBadRequest());
// Validate the ProprietaireAction in the database
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteProprietaireAction() throws Exception {
// Initialize the database
proprietaireActionRepository.saveAndFlush(proprietaireAction);
int databaseSizeBeforeDelete = proprietaireActionRepository.findAll().size();
// Delete the proprietaireAction
restProprietaireActionMockMvc.perform(delete("/api/proprietaire-actions/{id}", proprietaireAction.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<ProprietaireAction> proprietaireActionList = proprietaireActionRepository.findAll();
assertThat(proprietaireActionList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| 9,952 | 0.724277 | 0.723774 | 226 | 43.035397 | 32.87693 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367257 | false | false | 4 |
cec3bcd10d73850a143cf40f4a6b3bb19625826c | 10,402,410,838,496 | 77bb365c341c7bfd6cf033fafe60989b042aa596 | /app/src/main/java/dev/journey/life/common/JuHeApiService.java | 42e413e39488273c5c36392dba464298bed6ec62 | [] | no_license | mwping/MvpSampleApp | https://github.com/mwping/MvpSampleApp | cc75f93b27ef458e1b7d5346275ff78fa9e03bc3 | 3eee9f2d30bb570a605e7b93165971ee13c8f427 | refs/heads/master | 2016-08-07T07:31:10.604000 | 2016-05-18T09:10:19 | 2016-05-18T09:10:19 | 59,098,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.journey.life.common;
/**
* Created by mwp on 16/5/16.
*/
public interface JuHeApiService {
}
| UTF-8 | Java | 108 | java | JuHeApiService.java | Java | [
{
"context": "ackage dev.journey.life.common;\n\n/**\n * Created by mwp on 16/5/16.\n */\npublic interface JuHeApiService {",
"end": 55,
"score": 0.9995744228363037,
"start": 52,
"tag": "USERNAME",
"value": "mwp"
}
] | null | [] | package dev.journey.life.common;
/**
* Created by mwp on 16/5/16.
*/
public interface JuHeApiService {
}
| 108 | 0.694444 | 0.648148 | 7 | 14.428572 | 14.714979 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 4 |
88c3424ba5d1589bb1fdb60cff9d757d930c4469 | 11,347,303,641,969 | 408d10920dfff9cca6f2c8dab9d45bb96dfca829 | /src/main/java/week3/day1/LearningWindows.java | 7baa3654d701e79d940bbd5f1f15e34ec6e990e5 | [] | no_license | Anbuselvam2018/Selenium_Anbu | https://github.com/Anbuselvam2018/Selenium_Anbu | a5c593aaa9cd32916e36e4f66129bb97faa64ae9 | c5f4fa5f2dcfb2442f7454c55e263e6e05c99117 | refs/heads/master | 2020-03-25T06:49:04.370000 | 2018-08-04T13:09:38 | 2018-08-04T13:09:38 | 143,525,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package week3.day1;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.chrome.ChromeDriver;
public class LearningWindows {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\DRIVERS\\chromedriver.exe");
ChromeDriver driver= new ChromeDriver();
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt");
driver.manage().window().maximize();
driver.switchTo().frame("iframeResult");
driver.findElementByXPath("/html/body/button").click();
Alert alertEle = driver.switchTo().alert();
alertEle.getText();
System.out.println(alertEle.getText());
alertEle.sendKeys("Week3");
alertEle.accept();
driver.switchTo().defaultContent();
driver.findElementByXPath("//*[@id='tryhome']").click();
Set<String> allWindowHandle = driver.getWindowHandles();
List<String> listOfAllWindowHandle = new ArrayList<String>();
listOfAllWindowHandle.addAll(allWindowHandle);
driver.switchTo().window(listOfAllWindowHandle.get(1));
driver.getTitle();
System.out.println(driver.getTitle());
driver.getCurrentUrl();
System.out.println(driver.getCurrentUrl());
driver.switchTo().window(listOfAllWindowHandle.get(0));
driver.getTitle();
System.out.println(driver.getTitle());
driver.getCurrentUrl();
System.out.println(driver.getCurrentUrl());
/* driver.close();
driver.quit();*/
}
}
| UTF-8 | Java | 1,535 | java | LearningWindows.java | Java | [] | null | [] | package week3.day1;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.chrome.ChromeDriver;
public class LearningWindows {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\DRIVERS\\chromedriver.exe");
ChromeDriver driver= new ChromeDriver();
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt");
driver.manage().window().maximize();
driver.switchTo().frame("iframeResult");
driver.findElementByXPath("/html/body/button").click();
Alert alertEle = driver.switchTo().alert();
alertEle.getText();
System.out.println(alertEle.getText());
alertEle.sendKeys("Week3");
alertEle.accept();
driver.switchTo().defaultContent();
driver.findElementByXPath("//*[@id='tryhome']").click();
Set<String> allWindowHandle = driver.getWindowHandles();
List<String> listOfAllWindowHandle = new ArrayList<String>();
listOfAllWindowHandle.addAll(allWindowHandle);
driver.switchTo().window(listOfAllWindowHandle.get(1));
driver.getTitle();
System.out.println(driver.getTitle());
driver.getCurrentUrl();
System.out.println(driver.getCurrentUrl());
driver.switchTo().window(listOfAllWindowHandle.get(0));
driver.getTitle();
System.out.println(driver.getTitle());
driver.getCurrentUrl();
System.out.println(driver.getCurrentUrl());
/* driver.close();
driver.quit();*/
}
}
| 1,535 | 0.703583 | 0.699674 | 51 | 28.09804 | 22.395075 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.137255 | false | false | 4 |
63afbd2310f76dabe1dfd46af948f86b3c2fbbc3 | 22,883,585,774,033 | 15621393e52f816ef3eb56f780439056ccd4ed69 | /src/main/java/com/nbui/employee/controller/EmpController.java | ccf3387898f2143203bd29e824303a187a999ca4 | [] | no_license | Echo-Mao/SpringBootTestProject | https://github.com/Echo-Mao/SpringBootTestProject | 0cb5c2d446878d906e30942b733331bb0dbb5e88 | 53a47285c0075a72bf7d161568b22bf045661060 | refs/heads/master | 2022-07-16T18:03:48.601000 | 2019-08-07T12:28:47 | 2019-08-07T12:28:47 | 173,556,406 | 0 | 0 | null | false | 2022-06-29T17:33:41 | 2019-03-03T09:46:22 | 2019-08-07T12:28:52 | 2022-06-29T17:33:41 | 4,800 | 0 | 0 | 7 | CSS | false | false | package com.nbui.employee.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.nbui.employee.condition.EmpCondition;
import com.nbui.employee.service.IEmpService;
import com.nbui.entity.City;
import com.nbui.entity.EmpInfo;
import com.nbui.entity.Province;
import com.nbui.entity.Role;
import com.nbui.provinceCity.service.ICityService;
import com.nbui.provinceCity.service.IProvinceService;
import com.nbui.role.service.IRoleService;
import com.nbui.util.DateUtils;
import com.nbui.util.MD5Utils;
import com.nbui.util.ret.RetResponse;
import com.nbui.util.ret.RetResult;
import net.sf.json.JSONArray;
/**
* 员工信息查询模块
* @author 雷石秀
* 员工查询Controller层:EmpQueryController
*
*/
@RestController
@RequestMapping("/emp")
public class EmpController {
@Autowired
private IEmpService empService;
@Autowired
private IRoleService roleService;
@Autowired
private IProvinceService provinceService;
@Autowired
private ICityService cityService;
/*
* 根据条件查询所有的员工信息,并且分页
* 用于分页显示
*/
@RequestMapping("/findAllEmpAndPage.action")
public RetResult<PageInfo<EmpInfo>> findAllEmpAndPage(@RequestParam(defaultValue="1") Integer pageIndex,@RequestParam(defaultValue="10")Integer pageSize,String empCondition) {
EmpCondition empConditionObject = JSONObject.parseObject(empCondition,EmpCondition.class);
PageInfo<EmpInfo> empInfo = empService.findAllAndPage(pageIndex, pageSize,empConditionObject);
return RetResponse.makeOKRsp(empInfo);
}
/*
* 根据条件查询所有的员工信息,不分页
* 用于导出员工信息表格文件
*/
@RequestMapping("/findAllEmp.action")
public HashMap<String,Object> findAllEmp(EmpCondition empCondition) {
List<EmpInfo> empList = empService.findAll(empCondition);
HashMap<String,Object> map = new HashMap<>();
map.put("empList", empList);
return map;
}
/*
* 查询权限选择列表和省信息
* 用于添加页面加载后初始化角色的选项和省的选项
*/
@RequestMapping("/findRoleAndProvince.action")
public HashMap<String,Object> findRoleAndProvince(String loginEmpId) {
HashMap<String,Object> map = new HashMap<>();
char[] array = loginEmpId.toCharArray();
for (char c : array) {
if (c<'0' || c>'9') {
map.put("findStatus", "fail");
return map;
}
}
Integer empIdInt = Integer.parseInt(loginEmpId);
List<Role> roleList = roleService.findAllByEmpId(empIdInt);
List<Province> provinceList = provinceService.findAll();
map.put("findStatus", "success");
map.put("roleList", roleList);
map.put("provinceList", provinceList);
return map;
}
/*
* 查询根据省id查询市信息
* 用于添加页面改变省的选项 后查询市选项
*/
@RequestMapping("/findCityByProvinceId.action")
public HashMap<String,Object> findCityByProvinceId(String proviceId) {
List<City> cityList = cityService.findAllByProviceId(proviceId);
HashMap<String,Object> map = new HashMap<>();
map.put("cityList", cityList);
return map;
}
/*
* 添加员工
*/
@RequestMapping("/addEmp.action")
public HashMap<String,Object> addEmp(String empInfo) {
EmpInfo empInfoObject = JSONObject.parseObject(empInfo,EmpInfo.class);
String phoneLast = empInfoObject.getPhoneNum().substring(5); //将密码设置为手机号后六位
empInfoObject.setLoginPwd(MD5Utils.MD5Encode(phoneLast, "utf-8"));
boolean addStatus = empService.addEmp(empInfoObject);
HashMap<String,Object> map = new HashMap<>();
if (addStatus) {
map.put("addStatus", "success");
}else {
map.put("addStatus", "fail");
}
return map;
}
/*
* 修改员工权限
* 注意,这里前端传入的参数只有权限Id和员工Id
*/
@RequestMapping("/updateRoleId.action")
public HashMap<String,Object> updateRoleId(EmpInfo empInfo) {
boolean updateStatus = empService.updateRoleId(empInfo);
HashMap<String,Object> map = new HashMap<>();
if (updateStatus) {
map.put("updateStatus", "success");
}else {
map.put("updateStatus", "fail");
}
return map;
}
/*
* 删除员工
*/
@RequestMapping("/deleteOneEmp.action")
public HashMap<String,Object> deleteOneEmp(Integer deleteId) {
boolean delelteStatus = empService.deleteOneByEmpId(deleteId);
HashMap<String,Object> map = new HashMap<>();
if (delelteStatus) {
map.put("deleteStatus", "success");
}else {
map.put("deletefailNum", "fail");
}
return map;
}
/* 批量删除 */
@RequestMapping("/deleteBatchEmp.action")
public HashMap<String,Object> deleteBatchEmp(String empIdArrStr) {
JSONArray jArray= JSONArray.fromObject(empIdArrStr);
boolean delelteStatus = empService.deleteBatchById(jArray);
HashMap<String,Object> map = new HashMap<>();
if (delelteStatus) {
map.put("deleteStatus", "success");
}else {
map.put("deletefailNum", "fail");
}
return map;
}
/*
* 查询员工
* 根据员工Id号查询员工信息
*/
@RequestMapping("/findByEmpId.action")
public HashMap<String,Object> findByEmpId(String empId) {
HashMap<String,Object> map = new HashMap<>();
char[] array = empId.toCharArray();
for (char c : array) {
if (c<'0' || c>'9') {
map.put("findStatus", "fail");
return map;
}
}
Integer empIdInt = Integer.parseInt(empId);
EmpInfo empInfo = empService.findByEmpId(empIdInt);
map.put("empInfo", empInfo);
if (empInfo==null) {
map.put("findStatus", "fail");
}else {
map.put("findStatus", "success");
}
return map;
}
/* 修改登录员工的个人信息 */
@RequestMapping("/updateEmpByEmpId.action")
public HashMap<String,Object> updateEmpByEmpId(String empInfo,HttpSession session) {
EmpInfo empInfoObject = JSONObject.parseObject(empInfo,EmpInfo.class);
boolean updateStatus = empService.updateEmp(empInfoObject);
HashMap<String,Object> map = new HashMap<>();
if (updateStatus) {
EmpInfo loginEmp = empService.findByEmpId(empInfoObject.getEmpId());
session.setAttribute("loginEmp", loginEmp);
map.put("updateStatus", "success");
}else {
map.put("updateStatus", "fail");
}
return map;
}
/* 下载报表 */
@RequestMapping(value = "empExcelDownload.action")
public void downloadAllClassmate(HttpServletResponse response,EmpCondition empCondition) throws IOException{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("信息表");
List<EmpInfo> empInfoList = empService.findAll(empCondition);
String fileName = "empinfo" + ".xls";//设置要导出的文件的名字
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = {"员工姓名","工号","手机号 ","年龄","所在区域","职务","是否在职"};
//headers表示excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
//在excel表中添加表头
for(int i=0;i<headers.length;i++){
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//在表中存放查询到的数据放入对应的列
for (EmpInfo empInfo : empInfoList) {
HSSFRow row1 = sheet.createRow(rowNum);//代表每次都只添加一行
row1.createCell(0).setCellValue(empInfo.getEmpName());
row1.createCell(1).setCellValue(empInfo.getLoginId()+"");
row1.createCell(2).setCellValue(empInfo.getPhoneNum());
row1.createCell(3).setCellValue(DateUtils.calculateAge(empInfo.getBirthday())+"");
row1.createCell(4).setCellValue(empInfo.getProvince().getProvince()+empInfo.getCity().getCity());
row1.createCell(5).setCellValue(empInfo.getRole().getRoleName());
row1.createCell(6).setCellValue(empInfo.getIncumbency()==1?"是":"否");
rowNum++;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
workbook.close();
}
}
| UTF-8 | Java | 9,225 | java | EmpController.java | Java | [
{
"context": ".sf.json.JSONArray;\r\n/**\r\n * 员工信息查询模块\r\n * @author 雷石秀\r\n * 员工查询Controller层:EmpQueryController\r\n * \r\n */\r",
"end": 1388,
"score": 0.9996365308761597,
"start": 1385,
"tag": "NAME",
"value": "雷石秀"
},
{
"context": " int rowNum = 1;\r\n String[] headers = {\"员工姓名\",\"工号\",\"手机号 \",\"年龄\",\"所在区域\",\"职务\",\"是否在职\"};\r\n /",
"end": 7218,
"score": 0.5826842784881592,
"start": 7215,
"tag": "NAME",
"value": "工姓名"
}
] | null | [] | package com.nbui.employee.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.nbui.employee.condition.EmpCondition;
import com.nbui.employee.service.IEmpService;
import com.nbui.entity.City;
import com.nbui.entity.EmpInfo;
import com.nbui.entity.Province;
import com.nbui.entity.Role;
import com.nbui.provinceCity.service.ICityService;
import com.nbui.provinceCity.service.IProvinceService;
import com.nbui.role.service.IRoleService;
import com.nbui.util.DateUtils;
import com.nbui.util.MD5Utils;
import com.nbui.util.ret.RetResponse;
import com.nbui.util.ret.RetResult;
import net.sf.json.JSONArray;
/**
* 员工信息查询模块
* @author 雷石秀
* 员工查询Controller层:EmpQueryController
*
*/
@RestController
@RequestMapping("/emp")
public class EmpController {
@Autowired
private IEmpService empService;
@Autowired
private IRoleService roleService;
@Autowired
private IProvinceService provinceService;
@Autowired
private ICityService cityService;
/*
* 根据条件查询所有的员工信息,并且分页
* 用于分页显示
*/
@RequestMapping("/findAllEmpAndPage.action")
public RetResult<PageInfo<EmpInfo>> findAllEmpAndPage(@RequestParam(defaultValue="1") Integer pageIndex,@RequestParam(defaultValue="10")Integer pageSize,String empCondition) {
EmpCondition empConditionObject = JSONObject.parseObject(empCondition,EmpCondition.class);
PageInfo<EmpInfo> empInfo = empService.findAllAndPage(pageIndex, pageSize,empConditionObject);
return RetResponse.makeOKRsp(empInfo);
}
/*
* 根据条件查询所有的员工信息,不分页
* 用于导出员工信息表格文件
*/
@RequestMapping("/findAllEmp.action")
public HashMap<String,Object> findAllEmp(EmpCondition empCondition) {
List<EmpInfo> empList = empService.findAll(empCondition);
HashMap<String,Object> map = new HashMap<>();
map.put("empList", empList);
return map;
}
/*
* 查询权限选择列表和省信息
* 用于添加页面加载后初始化角色的选项和省的选项
*/
@RequestMapping("/findRoleAndProvince.action")
public HashMap<String,Object> findRoleAndProvince(String loginEmpId) {
HashMap<String,Object> map = new HashMap<>();
char[] array = loginEmpId.toCharArray();
for (char c : array) {
if (c<'0' || c>'9') {
map.put("findStatus", "fail");
return map;
}
}
Integer empIdInt = Integer.parseInt(loginEmpId);
List<Role> roleList = roleService.findAllByEmpId(empIdInt);
List<Province> provinceList = provinceService.findAll();
map.put("findStatus", "success");
map.put("roleList", roleList);
map.put("provinceList", provinceList);
return map;
}
/*
* 查询根据省id查询市信息
* 用于添加页面改变省的选项 后查询市选项
*/
@RequestMapping("/findCityByProvinceId.action")
public HashMap<String,Object> findCityByProvinceId(String proviceId) {
List<City> cityList = cityService.findAllByProviceId(proviceId);
HashMap<String,Object> map = new HashMap<>();
map.put("cityList", cityList);
return map;
}
/*
* 添加员工
*/
@RequestMapping("/addEmp.action")
public HashMap<String,Object> addEmp(String empInfo) {
EmpInfo empInfoObject = JSONObject.parseObject(empInfo,EmpInfo.class);
String phoneLast = empInfoObject.getPhoneNum().substring(5); //将密码设置为手机号后六位
empInfoObject.setLoginPwd(MD5Utils.MD5Encode(phoneLast, "utf-8"));
boolean addStatus = empService.addEmp(empInfoObject);
HashMap<String,Object> map = new HashMap<>();
if (addStatus) {
map.put("addStatus", "success");
}else {
map.put("addStatus", "fail");
}
return map;
}
/*
* 修改员工权限
* 注意,这里前端传入的参数只有权限Id和员工Id
*/
@RequestMapping("/updateRoleId.action")
public HashMap<String,Object> updateRoleId(EmpInfo empInfo) {
boolean updateStatus = empService.updateRoleId(empInfo);
HashMap<String,Object> map = new HashMap<>();
if (updateStatus) {
map.put("updateStatus", "success");
}else {
map.put("updateStatus", "fail");
}
return map;
}
/*
* 删除员工
*/
@RequestMapping("/deleteOneEmp.action")
public HashMap<String,Object> deleteOneEmp(Integer deleteId) {
boolean delelteStatus = empService.deleteOneByEmpId(deleteId);
HashMap<String,Object> map = new HashMap<>();
if (delelteStatus) {
map.put("deleteStatus", "success");
}else {
map.put("deletefailNum", "fail");
}
return map;
}
/* 批量删除 */
@RequestMapping("/deleteBatchEmp.action")
public HashMap<String,Object> deleteBatchEmp(String empIdArrStr) {
JSONArray jArray= JSONArray.fromObject(empIdArrStr);
boolean delelteStatus = empService.deleteBatchById(jArray);
HashMap<String,Object> map = new HashMap<>();
if (delelteStatus) {
map.put("deleteStatus", "success");
}else {
map.put("deletefailNum", "fail");
}
return map;
}
/*
* 查询员工
* 根据员工Id号查询员工信息
*/
@RequestMapping("/findByEmpId.action")
public HashMap<String,Object> findByEmpId(String empId) {
HashMap<String,Object> map = new HashMap<>();
char[] array = empId.toCharArray();
for (char c : array) {
if (c<'0' || c>'9') {
map.put("findStatus", "fail");
return map;
}
}
Integer empIdInt = Integer.parseInt(empId);
EmpInfo empInfo = empService.findByEmpId(empIdInt);
map.put("empInfo", empInfo);
if (empInfo==null) {
map.put("findStatus", "fail");
}else {
map.put("findStatus", "success");
}
return map;
}
/* 修改登录员工的个人信息 */
@RequestMapping("/updateEmpByEmpId.action")
public HashMap<String,Object> updateEmpByEmpId(String empInfo,HttpSession session) {
EmpInfo empInfoObject = JSONObject.parseObject(empInfo,EmpInfo.class);
boolean updateStatus = empService.updateEmp(empInfoObject);
HashMap<String,Object> map = new HashMap<>();
if (updateStatus) {
EmpInfo loginEmp = empService.findByEmpId(empInfoObject.getEmpId());
session.setAttribute("loginEmp", loginEmp);
map.put("updateStatus", "success");
}else {
map.put("updateStatus", "fail");
}
return map;
}
/* 下载报表 */
@RequestMapping(value = "empExcelDownload.action")
public void downloadAllClassmate(HttpServletResponse response,EmpCondition empCondition) throws IOException{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("信息表");
List<EmpInfo> empInfoList = empService.findAll(empCondition);
String fileName = "empinfo" + ".xls";//设置要导出的文件的名字
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = {"员工姓名","工号","手机号 ","年龄","所在区域","职务","是否在职"};
//headers表示excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
//在excel表中添加表头
for(int i=0;i<headers.length;i++){
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//在表中存放查询到的数据放入对应的列
for (EmpInfo empInfo : empInfoList) {
HSSFRow row1 = sheet.createRow(rowNum);//代表每次都只添加一行
row1.createCell(0).setCellValue(empInfo.getEmpName());
row1.createCell(1).setCellValue(empInfo.getLoginId()+"");
row1.createCell(2).setCellValue(empInfo.getPhoneNum());
row1.createCell(3).setCellValue(DateUtils.calculateAge(empInfo.getBirthday())+"");
row1.createCell(4).setCellValue(empInfo.getProvince().getProvince()+empInfo.getCity().getCity());
row1.createCell(5).setCellValue(empInfo.getRole().getRoleName());
row1.createCell(6).setCellValue(empInfo.getIncumbency()==1?"是":"否");
rowNum++;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
workbook.close();
}
}
| 9,225 | 0.683544 | 0.679944 | 269 | 30.011152 | 26.157015 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.773234 | false | false | 4 |
1df47bf44706a1300a451c3c1870db8c858a854d | 23,295,902,673,330 | 336a42df03f3330b72f3c31a17e344f061f20f24 | /src/test/java/br/com/bluesoft/desafio/service/impl/PedidoServiceImplTest.java | e2c6c2c8c5296a64ba4c85844167b91b8efa4636 | [] | no_license | vezixtor/desafio-pedido-bluesoft | https://github.com/vezixtor/desafio-pedido-bluesoft | 086149ad0ed577ee4bb358a351493dbad9b004a3 | a52df41e840841eb424fb18f7435c01ec2c03fdd | refs/heads/master | 2020-07-31T19:50:08.347000 | 2019-09-24T04:10:24 | 2019-09-24T04:10:24 | 210,734,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.bluesoft.desafio.service.impl;
import br.com.bluesoft.desafio.dto.FornecedorDTO;
import br.com.bluesoft.desafio.dto.MelhorFornecedorDTO;
import br.com.bluesoft.desafio.dto.NovoPedidoDTO;
import br.com.bluesoft.desafio.dto.PrecoDTO;
import br.com.bluesoft.desafio.model.Fornecedor;
import br.com.bluesoft.desafio.model.Item;
import br.com.bluesoft.desafio.model.Pedido;
import br.com.bluesoft.desafio.model.Produto;
import br.com.bluesoft.desafio.repository.PedidoRepository;
import br.com.bluesoft.desafio.repository.ProdutoRepository;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PedidoServiceImplTest {
@InjectMocks
private PedidoServiceImpl service;
@Mock
private FornecedorServiceImpl fornecedorService;
@Mock
private ProdutoRepository produtoRepository;
@Mock
private PedidoRepository pedidoRepository;
@Test
public void filtrarPedidosOrcadosComOrcamento() {
Integer quantidadeItensOrcados = 3;
List<NovoPedidoDTO> pedidos = Arrays.asList(
new NovoPedidoDTO("x", 0),
new NovoPedidoDTO("y", 10),
new NovoPedidoDTO("z", 20),
new NovoPedidoDTO("a", 30)
);
List<NovoPedidoDTO> pedidosFiltrados = ReflectionTestUtils.invokeMethod(service, "filtrarPedidosOrcados", pedidos);
assertThat(quantidadeItensOrcados, equalTo(pedidosFiltrados.size()));
}
@Test
public void filtrarPedidosOrcadosSemOrcamento() {
Integer quantidadeItensOrcados = 0;
List<NovoPedidoDTO> pedidos = Arrays.asList(
new NovoPedidoDTO("x", 0),
new NovoPedidoDTO("y", 0),
new NovoPedidoDTO("z", 0),
new NovoPedidoDTO("a", 0)
);
List<NovoPedidoDTO> pedidosFiltrados = ReflectionTestUtils.invokeMethod(service, "filtrarPedidosOrcados", pedidos);
assertThat(quantidadeItensOrcados, equalTo(pedidosFiltrados.size()));
}
@Test
public void cotarFornecedores() {
String gtin = "7892840222949";
this.obterFornecedoresMock(gtin);
int quantidadeEsperada = 10;
MelhorFornecedorDTO melhorFornecedorDTO = ReflectionTestUtils.invokeMethod(service, "cotarFornecedores", new NovoPedidoDTO(gtin, quantidadeEsperada));
assertNotNull(melhorFornecedorDTO);
BigDecimal melhorPreco = new BigDecimal("4.13");
assertThat(melhorFornecedorDTO.getPreco(), equalTo(melhorPreco));
assertThat(melhorFornecedorDTO.getQuantidade_minima(), equalTo(quantidadeEsperada));
String melhorFornecedor = "Fornecedor 3";
assertThat(melhorFornecedorDTO.getNome(), equalTo(melhorFornecedor));
}
private void obterFornecedoresMock(String gtin) {
String json = "[{\"cnpj\": \"56.918.868/0001-20\", \"precos\": [{\"preco\": 4.5, \"quantidade_minima\": 1}, {\"preco\": 3.1, \"quantidade_minima\": 100}], \"nome\": \"Fornecedor 1\"}, {\"cnpj\": \"37.563.823/0001-35\", \"precos\": [{\"preco\": 4.5, \"quantidade_minima\": 10}, {\"preco\": 4.1, \"quantidade_minima\": 35}], \"nome\": \"Fornecedor 2\"}, {\"cnpj\": \"42.217.933/0001-85\", \"precos\": [{\"preco\": 4.13, \"quantidade_minima\": 10}, {\"preco\": 4.1, \"quantidade_minima\": 22}], \"nome\": \"Fornecedor 3\"}]";
Object value = null;
try {
value = new ObjectMapper().readValue(json, new TypeReference<List<FornecedorDTO>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
doReturn(value).when(fornecedorService).obterFornecedores(gtin);
}
@Test
public void cotarPrecos() {
List<PrecoDTO> precoDTOS = Arrays.asList(
new PrecoDTO(BigDecimal.TEN, 1),
new PrecoDTO(BigDecimal.ONE, 10)
);
PrecoDTO preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 1, precoDTOS);
assertThat(preco.getPreco(), equalTo(BigDecimal.TEN));
assertThat(preco.getQuantidade_minima(), equalTo(1));
preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 10, precoDTOS);
assertThat(preco.getPreco(), equalTo(BigDecimal.ONE));
assertThat(preco.getQuantidade_minima(), equalTo(10));
preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 100, precoDTOS);
assertNull(preco);
}
@Test(expected = RuntimeException.class)
public void validarFornecedorComErro() {
Produto produto = new Produto("7892840222949", "SALGADINHO FANDANGOS QUEIJO");
doReturn(produto).when(produtoRepository).findByGtin(produto.getGtin());
ReflectionTestUtils.invokeMethod(service, "validarFornecedor", new MelhorFornecedorDTO(), produto.getGtin());
}
@Test
public void validarFornecedorSemErro() {
Produto produto = new Produto("7892840222949", "SALGADINHO FANDANGOS QUEIJO");
doReturn(produto).when(produtoRepository).findByGtin(produto.getGtin());
ReflectionTestUtils.invokeMethod(service, "validarFornecedor", new MelhorFornecedorDTO("", "", BigDecimal.TEN, 10), produto.getGtin());
}
} | UTF-8 | Java | 5,927 | java | PedidoServiceImplTest.java | Java | [
{
"context": " Produto produto = new Produto(\"7892840222949\", \"SALGADINHO FANDANGOS QUEIJO\");\n doReturn(produto).when(produtoReposito",
"end": 5343,
"score": 0.9998416304588318,
"start": 5316,
"tag": "NAME",
"value": "SALGADINHO FANDANGOS QUEIJO"
},
{
"context": " Produto produto = new Produto(\"7892840222949\", \"SALGADINHO FANDANGOS QUEIJO\");\n doReturn(produto).when(produtoReposito",
"end": 5691,
"score": 0.9998610615730286,
"start": 5664,
"tag": "NAME",
"value": "SALGADINHO FANDANGOS QUEIJO"
}
] | null | [] | package br.com.bluesoft.desafio.service.impl;
import br.com.bluesoft.desafio.dto.FornecedorDTO;
import br.com.bluesoft.desafio.dto.MelhorFornecedorDTO;
import br.com.bluesoft.desafio.dto.NovoPedidoDTO;
import br.com.bluesoft.desafio.dto.PrecoDTO;
import br.com.bluesoft.desafio.model.Fornecedor;
import br.com.bluesoft.desafio.model.Item;
import br.com.bluesoft.desafio.model.Pedido;
import br.com.bluesoft.desafio.model.Produto;
import br.com.bluesoft.desafio.repository.PedidoRepository;
import br.com.bluesoft.desafio.repository.ProdutoRepository;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PedidoServiceImplTest {
@InjectMocks
private PedidoServiceImpl service;
@Mock
private FornecedorServiceImpl fornecedorService;
@Mock
private ProdutoRepository produtoRepository;
@Mock
private PedidoRepository pedidoRepository;
@Test
public void filtrarPedidosOrcadosComOrcamento() {
Integer quantidadeItensOrcados = 3;
List<NovoPedidoDTO> pedidos = Arrays.asList(
new NovoPedidoDTO("x", 0),
new NovoPedidoDTO("y", 10),
new NovoPedidoDTO("z", 20),
new NovoPedidoDTO("a", 30)
);
List<NovoPedidoDTO> pedidosFiltrados = ReflectionTestUtils.invokeMethod(service, "filtrarPedidosOrcados", pedidos);
assertThat(quantidadeItensOrcados, equalTo(pedidosFiltrados.size()));
}
@Test
public void filtrarPedidosOrcadosSemOrcamento() {
Integer quantidadeItensOrcados = 0;
List<NovoPedidoDTO> pedidos = Arrays.asList(
new NovoPedidoDTO("x", 0),
new NovoPedidoDTO("y", 0),
new NovoPedidoDTO("z", 0),
new NovoPedidoDTO("a", 0)
);
List<NovoPedidoDTO> pedidosFiltrados = ReflectionTestUtils.invokeMethod(service, "filtrarPedidosOrcados", pedidos);
assertThat(quantidadeItensOrcados, equalTo(pedidosFiltrados.size()));
}
@Test
public void cotarFornecedores() {
String gtin = "7892840222949";
this.obterFornecedoresMock(gtin);
int quantidadeEsperada = 10;
MelhorFornecedorDTO melhorFornecedorDTO = ReflectionTestUtils.invokeMethod(service, "cotarFornecedores", new NovoPedidoDTO(gtin, quantidadeEsperada));
assertNotNull(melhorFornecedorDTO);
BigDecimal melhorPreco = new BigDecimal("4.13");
assertThat(melhorFornecedorDTO.getPreco(), equalTo(melhorPreco));
assertThat(melhorFornecedorDTO.getQuantidade_minima(), equalTo(quantidadeEsperada));
String melhorFornecedor = "Fornecedor 3";
assertThat(melhorFornecedorDTO.getNome(), equalTo(melhorFornecedor));
}
private void obterFornecedoresMock(String gtin) {
String json = "[{\"cnpj\": \"56.918.868/0001-20\", \"precos\": [{\"preco\": 4.5, \"quantidade_minima\": 1}, {\"preco\": 3.1, \"quantidade_minima\": 100}], \"nome\": \"Fornecedor 1\"}, {\"cnpj\": \"37.563.823/0001-35\", \"precos\": [{\"preco\": 4.5, \"quantidade_minima\": 10}, {\"preco\": 4.1, \"quantidade_minima\": 35}], \"nome\": \"Fornecedor 2\"}, {\"cnpj\": \"42.217.933/0001-85\", \"precos\": [{\"preco\": 4.13, \"quantidade_minima\": 10}, {\"preco\": 4.1, \"quantidade_minima\": 22}], \"nome\": \"Fornecedor 3\"}]";
Object value = null;
try {
value = new ObjectMapper().readValue(json, new TypeReference<List<FornecedorDTO>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
doReturn(value).when(fornecedorService).obterFornecedores(gtin);
}
@Test
public void cotarPrecos() {
List<PrecoDTO> precoDTOS = Arrays.asList(
new PrecoDTO(BigDecimal.TEN, 1),
new PrecoDTO(BigDecimal.ONE, 10)
);
PrecoDTO preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 1, precoDTOS);
assertThat(preco.getPreco(), equalTo(BigDecimal.TEN));
assertThat(preco.getQuantidade_minima(), equalTo(1));
preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 10, precoDTOS);
assertThat(preco.getPreco(), equalTo(BigDecimal.ONE));
assertThat(preco.getQuantidade_minima(), equalTo(10));
preco = ReflectionTestUtils.invokeMethod(service, "cotarPrecos", 100, precoDTOS);
assertNull(preco);
}
@Test(expected = RuntimeException.class)
public void validarFornecedorComErro() {
Produto produto = new Produto("7892840222949", "<NAME>");
doReturn(produto).when(produtoRepository).findByGtin(produto.getGtin());
ReflectionTestUtils.invokeMethod(service, "validarFornecedor", new MelhorFornecedorDTO(), produto.getGtin());
}
@Test
public void validarFornecedorSemErro() {
Produto produto = new Produto("7892840222949", "<NAME>");
doReturn(produto).when(produtoRepository).findByGtin(produto.getGtin());
ReflectionTestUtils.invokeMethod(service, "validarFornecedor", new MelhorFornecedorDTO("", "", BigDecimal.TEN, 10), produto.getGtin());
}
} | 5,885 | 0.696642 | 0.672684 | 138 | 41.95652 | 52.101749 | 530 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.050725 | false | false | 4 |
2f3dbf248f00aef22b4ee1790904e2916e0c955f | 34,179,349,743,631 | 873bd9443c7f5742104e7ba0d391ea55519a7ee2 | /src/main/java/samurai/command/osu/Rank.java | 241b5fff8c5e213f39fc17deb11dc21c244d1bf0 | [
"Apache-2.0"
] | permissive | Cprovost9731/DiscordSamuraiBot | https://github.com/Cprovost9731/DiscordSamuraiBot | 560cd28edaef47b584f587c51fd35d2218165731 | 3901b70f09ea5c5161038389905cbd294cbc7ef7 | refs/heads/master | 2021-01-20T12:57:58.586000 | 2017-05-05T19:01:34 | 2017-05-05T19:01:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Copyright 2017 Ton Ly
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package samurai.command.osu;
import net.dv8tion.jda.core.entities.Member;
import samurai.command.Command;
import samurai.command.CommandContext;
import samurai.command.annotations.Key;
import samurai.database.objects.SamuraiGuild;
import samurai.database.objects.Player;
import samurai.messages.impl.FixedMessage;
import samurai.messages.base.SamuraiMessage;
import samurai.messages.impl.util.Book;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Optional;
@Key("rank")
public class Rank extends Command {
@Override
public SamuraiMessage execute(CommandContext context) {
final SamuraiGuild guild = context.getSamuraiGuild();
final List<Member> mentions = context.getMentionedMembers();
final List<Player> players = guild.getPlayers();
if (players.size() == 0) return FixedMessage.build("No users found.");
Optional<Player> playerOptional;
if (mentions.size() == 0) {
playerOptional = guild.getPlayer(context.getAuthorId());
if (!playerOptional.isPresent())
return FixedMessage.build("You have not linked an osu account to yourself yet.");
} else if (mentions.size() == 1) {
playerOptional = guild.getPlayer(mentions.get(0).getUser().getIdLong());
if (!playerOptional.isPresent())
return FixedMessage.build(String.format("**%s** does not have an osu account linked.", mentions.get(0).getEffectiveName()));
} else {
return null;
}
int listSize = players.size();
final Player targetPlayer = playerOptional.get();
int target = guild.getRankLocal(targetPlayer);
List<String> nameList = new ArrayList<>(listSize);
for (int i = 0; i < listSize; i++) {
final Player player = players.get(i);
final String name = context.getGuild().getMemberById(player.getDiscordId()).getEffectiveName();
final String osuName = player.getOsuName();
if (i != target) {
nameList.add(String.format("%d. %s : %s (#%d)%n", i, name, osuName, player.getGlobalRank()));
} else {
nameList.add(String.format("#%d %s : %s (#%d)%n", i, name, osuName, player.getGlobalRank()));
}
}
ListIterator<String> itr = nameList.listIterator();
int pageLen = listSize % 10 >= 5 ? listSize / 10 + 1 : listSize / 10;
ArrayList<String> book = new ArrayList<>(pageLen);
for (int i = 0; i < pageLen - 1; i++) {
StringBuilder sb = new StringBuilder(52 * listSize).append("```md\n");
int j = 0;
while (j++ < 10) {
sb.append(itr.next());
}
sb.append("```");
book.add(sb.toString());
}
StringBuilder sb = new StringBuilder(52 * listSize).append("```md\n");
itr.forEachRemaining(sb::append);
sb.append("```");
book.add(sb.toString());
return new Book(target / 10, book);
}
}
| UTF-8 | Java | 3,649 | java | Rank.java | Java | [
{
"context": "/* Copyright 2017 Ton Ly\n \n Licensed under the Apache License, Version 2.",
"end": 27,
"score": 0.9996419548988342,
"start": 21,
"tag": "NAME",
"value": "Ton Ly"
}
] | null | [] | /* Copyright 2017 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package samurai.command.osu;
import net.dv8tion.jda.core.entities.Member;
import samurai.command.Command;
import samurai.command.CommandContext;
import samurai.command.annotations.Key;
import samurai.database.objects.SamuraiGuild;
import samurai.database.objects.Player;
import samurai.messages.impl.FixedMessage;
import samurai.messages.base.SamuraiMessage;
import samurai.messages.impl.util.Book;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Optional;
@Key("rank")
public class Rank extends Command {
@Override
public SamuraiMessage execute(CommandContext context) {
final SamuraiGuild guild = context.getSamuraiGuild();
final List<Member> mentions = context.getMentionedMembers();
final List<Player> players = guild.getPlayers();
if (players.size() == 0) return FixedMessage.build("No users found.");
Optional<Player> playerOptional;
if (mentions.size() == 0) {
playerOptional = guild.getPlayer(context.getAuthorId());
if (!playerOptional.isPresent())
return FixedMessage.build("You have not linked an osu account to yourself yet.");
} else if (mentions.size() == 1) {
playerOptional = guild.getPlayer(mentions.get(0).getUser().getIdLong());
if (!playerOptional.isPresent())
return FixedMessage.build(String.format("**%s** does not have an osu account linked.", mentions.get(0).getEffectiveName()));
} else {
return null;
}
int listSize = players.size();
final Player targetPlayer = playerOptional.get();
int target = guild.getRankLocal(targetPlayer);
List<String> nameList = new ArrayList<>(listSize);
for (int i = 0; i < listSize; i++) {
final Player player = players.get(i);
final String name = context.getGuild().getMemberById(player.getDiscordId()).getEffectiveName();
final String osuName = player.getOsuName();
if (i != target) {
nameList.add(String.format("%d. %s : %s (#%d)%n", i, name, osuName, player.getGlobalRank()));
} else {
nameList.add(String.format("#%d %s : %s (#%d)%n", i, name, osuName, player.getGlobalRank()));
}
}
ListIterator<String> itr = nameList.listIterator();
int pageLen = listSize % 10 >= 5 ? listSize / 10 + 1 : listSize / 10;
ArrayList<String> book = new ArrayList<>(pageLen);
for (int i = 0; i < pageLen - 1; i++) {
StringBuilder sb = new StringBuilder(52 * listSize).append("```md\n");
int j = 0;
while (j++ < 10) {
sb.append(itr.next());
}
sb.append("```");
book.add(sb.toString());
}
StringBuilder sb = new StringBuilder(52 * listSize).append("```md\n");
itr.forEachRemaining(sb::append);
sb.append("```");
book.add(sb.toString());
return new Book(target / 10, book);
}
}
| 3,649 | 0.633872 | 0.624555 | 89 | 39.988766 | 29.154564 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730337 | false | false | 4 |
dabd79f71fefcc916e769abff1d83b1886cec5f7 | 26,130,581,081,785 | 0fafb94e7b876feffe2d4769225c3efcd2a71e59 | /app/src/main/java/com/hzj163/myhzjapp/adapter/PostInfoAdapter.java | bbb9d101942c59ef338debd5233b4e865336c279 | [] | no_license | lingluda/MyHzjApp17 | https://github.com/lingluda/MyHzjApp17 | 4713f077b5818f96daba9c6548ce9f74b01c827d | 42331de6528444c0588be0c7fb00317087df7249 | refs/heads/master | 2016-09-12T14:18:14.881000 | 2016-05-13T02:53:25 | 2016-05-13T02:53:25 | 58,694,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hzj163.myhzjapp.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hzj163.myhzjapp.R;
import com.hzj163.myhzjapp.app.MyApp;
import com.hzj163.myhzjapp.beans.Comment;
import com.hzj163.myhzjapp.beans.MyBBSData;
import com.hzj163.myhzjapp.beans.PostData;
import com.hzj163.myhzjapp.beans.PostPhoto;
import com.hzj163.myhzjapp.viewholder.CommentItemViewHolder;
import com.hzj163.myhzjapp.viewholder.MyBBSJoinItemViewHolder;
import com.hzj163.myhzjapp.viewholder.MyBBSTitleItemViewHolder;
import com.hzj163.myhzjapp.viewholder.PostInfoInfoViewHolder;
import com.hzj163.myhzjapp.viewholder.PostInfoPhotoViewHolder;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* 作者: 黄志江老师 on 2015/10/30.
* 网址: www.hzj163.com
* 网书: https://www.gitbook.com/@hzj163
* 邮箱: hzjlltj@163.com
*/
public class PostInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
ArrayList<MyBBSData> AllDatas;
public ArrayList<MyBBSData> getAllDatas() {
return AllDatas;
}
PostInfoInfoViewHolder.ItemClick postInfoInfoViewHolderItemClick;
Context context;
public enum ITEM_TYPE {
//帖子信息
ITEM_TYPE_POST_INFO,
//帖子图片
ITEM_TYPE_POST_PHOTO,
//打赏
ITEM_TYPE_POST_REWARD,
//标题
ITEM_TYPE_POST_TITLE,
//评论
ITEM_TYPE_POST_COMMENT
}
public PostInfoAdapter(PostInfoInfoViewHolder.ItemClick postInfoInfoViewHolderItemClick, PhotoOnClick postInfoAdapterPhotoOnClick) {
this.postInfoInfoViewHolderItemClick = postInfoInfoViewHolderItemClick;
this.postInfoAdapterPhotoOnClick = postInfoAdapterPhotoOnClick;
AllDatas = new ArrayList();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_INFO.ordinal()) {
View view = LayoutInflater.from(context).inflate(R.layout.post_info_info_item, parent, false);
PostInfoInfoViewHolder postInfoInfoViewHolder = new PostInfoInfoViewHolder(view, postInfoInfoViewHolderItemClick);
return postInfoInfoViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_PHOTO.ordinal()) {
View view = LayoutInflater.from(context).inflate(R.layout.post_info_photo_item, parent, false);
PostInfoPhotoViewHolder postInfoPhotoViewHolder = new PostInfoPhotoViewHolder(view);
return postInfoPhotoViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_TITLE.ordinal()) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.mybbs_title_item,parent,false);
MyBBSTitleItemViewHolder myBBSTitleItemViewHolder=new MyBBSTitleItemViewHolder(view);
return myBBSTitleItemViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_COMMENT.ordinal()) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item,parent,false);
CommentItemViewHolder commentItemViewHolder=new CommentItemViewHolder(view);
return commentItemViewHolder;
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof PostInfoInfoViewHolder) {
PostData temp = (PostData) AllDatas.get(position).getObject();
((PostInfoInfoViewHolder) holder).t_time.setText(temp.getPost().getCreatedAt());
((PostInfoInfoViewHolder) holder).t_title.setText(temp.getPost().getTitle());
((PostInfoInfoViewHolder) holder).t_nick.setText(temp.getPost().getUser().getNick());
((PostInfoInfoViewHolder) holder).t_info.setText(temp.getPost().getInfo());
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(((PostInfoInfoViewHolder) holder).image_icon, false);
myApp.getImageLoader().displayImage(temp.getPost().getUser().getFace(), imageAware, myApp.getFaceDisplayImageLoad());
}
if (holder instanceof PostInfoPhotoViewHolder) {
((PostInfoPhotoViewHolder) holder).root_view.removeAllViews();
ArrayList<PostPhoto> temp = (ArrayList<PostPhoto>) AllDatas.get(position).getObject();
Log.i("hzj","ArrayList<PostPhoto>:"+temp.size());
//获取手机宽
final int width = (MyApp.width - MyApp.dip2px(16, MyApp.density));
for (int i = 0; i < temp.size(); i++) {
//代码动态创建组件,而不是直接在xml里面布局
ImageView imageView = new ImageView(context);
imageView.setClickable(true);
imageView.setOnClickListener(this);
//这里需要把当前图片集合里面的下标传递给回调,提供外界使用
imageView.setTag(i);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, width);
layoutParams.setMargins(0, 0, 0, 15);
imageView.setLayoutParams(layoutParams);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(imageView, false);
String photoUrl = "http://file.bmob.cn/" + temp.get(i).getPhoto().getUrl();
//这里需要整理ImageView的高度【因为宽度已经固定为手机宽】
//主要利用Universal-Image-Loader加载完毕之后获得下载的图片额宽高比例
myApp.getImageLoader().displayImage(photoUrl, imageAware, myApp.getFaceDisplayImageLoad(), new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//下载成功
//计算原始图片的比例
float proportion = (loadedImage.getWidth() + 0.0f) / loadedImage.getHeight();
//从新计算显示图片的ImageView组件的高度【利用比例相除即可】
float height = width / proportion;
//重新动态修改ImageView组件的高度
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) view.getLayoutParams();
layoutParams1.height = (int) height;
view.setLayoutParams(layoutParams1);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
((PostInfoPhotoViewHolder) holder).root_view.addView(imageView);
}
((PostInfoPhotoViewHolder) holder).root_view.invalidate();
}
if (holder instanceof MyBBSTitleItemViewHolder) {
String temp=AllDatas.get(position).getObject().toString();
((MyBBSTitleItemViewHolder) holder).t_title.setText(temp);
}
if (holder instanceof CommentItemViewHolder) {
Comment temp=(Comment)AllDatas.get(position).getObject();
((CommentItemViewHolder) holder).t_nick.setText(temp.getUser().getNick());
((CommentItemViewHolder) holder).t_info.setText(temp.getInfo());
((CommentItemViewHolder) holder).t_date.setText(temp.getCreatedAt());
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(((CommentItemViewHolder) holder).image_icon, false);
myApp.getImageLoader().displayImage(temp.getUser().getFace(), imageAware, myApp.getFaceDisplayImageLoad());
}
}
@Override
public int getItemCount() {
return AllDatas.size();
}
@Override
public int getItemViewType(int position) {
return AllDatas.get(position).getItemType();
}
//图片点击的事件
PhotoOnClick postInfoAdapterPhotoOnClick;
public interface PhotoOnClick {
void photoOnClick(int index);
}
@Override
public void onClick(View v) {
if (postInfoAdapterPhotoOnClick == null) {
return;
}
postInfoAdapterPhotoOnClick.photoOnClick((int)v.getTag());
}
}
| UTF-8 | Java | 9,406 | java | PostInfoAdapter.java | Java | [
{
"context": "istener;\n\nimport java.util.ArrayList;\n\n/**\n * 作者: 黄志江老师 on 2015/10/30.\n * 网址: www.hzj163.com\n * 网书: https",
"end": 1274,
"score": 0.9941245317459106,
"start": 1269,
"tag": "NAME",
"value": "黄志江老师"
},
{
"context": " 网址: www.hzj163.com\n * 网书: https://www.gitbook.com/@hzj163\n * 邮箱: hzjlltj@163.com\n */\npublic class PostInfoA",
"end": 1350,
"score": 0.9996612668037415,
"start": 1343,
"tag": "USERNAME",
"value": "@hzj163"
},
{
"context": ".com\n * 网书: https://www.gitbook.com/@hzj163\n * 邮箱: hzjlltj@163.com\n */\npublic class PostInfoAdapter extends Recy",
"end": 1369,
"score": 0.9997706413269043,
"start": 1358,
"tag": "EMAIL",
"value": "hzjlltj@163"
}
] | null | [] | package com.hzj163.myhzjapp.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hzj163.myhzjapp.R;
import com.hzj163.myhzjapp.app.MyApp;
import com.hzj163.myhzjapp.beans.Comment;
import com.hzj163.myhzjapp.beans.MyBBSData;
import com.hzj163.myhzjapp.beans.PostData;
import com.hzj163.myhzjapp.beans.PostPhoto;
import com.hzj163.myhzjapp.viewholder.CommentItemViewHolder;
import com.hzj163.myhzjapp.viewholder.MyBBSJoinItemViewHolder;
import com.hzj163.myhzjapp.viewholder.MyBBSTitleItemViewHolder;
import com.hzj163.myhzjapp.viewholder.PostInfoInfoViewHolder;
import com.hzj163.myhzjapp.viewholder.PostInfoPhotoViewHolder;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* 作者: 黄志江老师 on 2015/10/30.
* 网址: www.hzj163.com
* 网书: https://www.gitbook.com/@hzj163
* 邮箱: <EMAIL>.com
*/
public class PostInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
ArrayList<MyBBSData> AllDatas;
public ArrayList<MyBBSData> getAllDatas() {
return AllDatas;
}
PostInfoInfoViewHolder.ItemClick postInfoInfoViewHolderItemClick;
Context context;
public enum ITEM_TYPE {
//帖子信息
ITEM_TYPE_POST_INFO,
//帖子图片
ITEM_TYPE_POST_PHOTO,
//打赏
ITEM_TYPE_POST_REWARD,
//标题
ITEM_TYPE_POST_TITLE,
//评论
ITEM_TYPE_POST_COMMENT
}
public PostInfoAdapter(PostInfoInfoViewHolder.ItemClick postInfoInfoViewHolderItemClick, PhotoOnClick postInfoAdapterPhotoOnClick) {
this.postInfoInfoViewHolderItemClick = postInfoInfoViewHolderItemClick;
this.postInfoAdapterPhotoOnClick = postInfoAdapterPhotoOnClick;
AllDatas = new ArrayList();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_INFO.ordinal()) {
View view = LayoutInflater.from(context).inflate(R.layout.post_info_info_item, parent, false);
PostInfoInfoViewHolder postInfoInfoViewHolder = new PostInfoInfoViewHolder(view, postInfoInfoViewHolderItemClick);
return postInfoInfoViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_PHOTO.ordinal()) {
View view = LayoutInflater.from(context).inflate(R.layout.post_info_photo_item, parent, false);
PostInfoPhotoViewHolder postInfoPhotoViewHolder = new PostInfoPhotoViewHolder(view);
return postInfoPhotoViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_TITLE.ordinal()) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.mybbs_title_item,parent,false);
MyBBSTitleItemViewHolder myBBSTitleItemViewHolder=new MyBBSTitleItemViewHolder(view);
return myBBSTitleItemViewHolder;
}
if (viewType == ITEM_TYPE.ITEM_TYPE_POST_COMMENT.ordinal()) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item,parent,false);
CommentItemViewHolder commentItemViewHolder=new CommentItemViewHolder(view);
return commentItemViewHolder;
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof PostInfoInfoViewHolder) {
PostData temp = (PostData) AllDatas.get(position).getObject();
((PostInfoInfoViewHolder) holder).t_time.setText(temp.getPost().getCreatedAt());
((PostInfoInfoViewHolder) holder).t_title.setText(temp.getPost().getTitle());
((PostInfoInfoViewHolder) holder).t_nick.setText(temp.getPost().getUser().getNick());
((PostInfoInfoViewHolder) holder).t_info.setText(temp.getPost().getInfo());
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(((PostInfoInfoViewHolder) holder).image_icon, false);
myApp.getImageLoader().displayImage(temp.getPost().getUser().getFace(), imageAware, myApp.getFaceDisplayImageLoad());
}
if (holder instanceof PostInfoPhotoViewHolder) {
((PostInfoPhotoViewHolder) holder).root_view.removeAllViews();
ArrayList<PostPhoto> temp = (ArrayList<PostPhoto>) AllDatas.get(position).getObject();
Log.i("hzj","ArrayList<PostPhoto>:"+temp.size());
//获取手机宽
final int width = (MyApp.width - MyApp.dip2px(16, MyApp.density));
for (int i = 0; i < temp.size(); i++) {
//代码动态创建组件,而不是直接在xml里面布局
ImageView imageView = new ImageView(context);
imageView.setClickable(true);
imageView.setOnClickListener(this);
//这里需要把当前图片集合里面的下标传递给回调,提供外界使用
imageView.setTag(i);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, width);
layoutParams.setMargins(0, 0, 0, 15);
imageView.setLayoutParams(layoutParams);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(imageView, false);
String photoUrl = "http://file.bmob.cn/" + temp.get(i).getPhoto().getUrl();
//这里需要整理ImageView的高度【因为宽度已经固定为手机宽】
//主要利用Universal-Image-Loader加载完毕之后获得下载的图片额宽高比例
myApp.getImageLoader().displayImage(photoUrl, imageAware, myApp.getFaceDisplayImageLoad(), new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//下载成功
//计算原始图片的比例
float proportion = (loadedImage.getWidth() + 0.0f) / loadedImage.getHeight();
//从新计算显示图片的ImageView组件的高度【利用比例相除即可】
float height = width / proportion;
//重新动态修改ImageView组件的高度
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) view.getLayoutParams();
layoutParams1.height = (int) height;
view.setLayoutParams(layoutParams1);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
((PostInfoPhotoViewHolder) holder).root_view.addView(imageView);
}
((PostInfoPhotoViewHolder) holder).root_view.invalidate();
}
if (holder instanceof MyBBSTitleItemViewHolder) {
String temp=AllDatas.get(position).getObject().toString();
((MyBBSTitleItemViewHolder) holder).t_title.setText(temp);
}
if (holder instanceof CommentItemViewHolder) {
Comment temp=(Comment)AllDatas.get(position).getObject();
((CommentItemViewHolder) holder).t_nick.setText(temp.getUser().getNick());
((CommentItemViewHolder) holder).t_info.setText(temp.getInfo());
((CommentItemViewHolder) holder).t_date.setText(temp.getCreatedAt());
MyApp myApp = (MyApp) context.getApplicationContext();
ImageAware imageAware = new ImageViewAware(((CommentItemViewHolder) holder).image_icon, false);
myApp.getImageLoader().displayImage(temp.getUser().getFace(), imageAware, myApp.getFaceDisplayImageLoad());
}
}
@Override
public int getItemCount() {
return AllDatas.size();
}
@Override
public int getItemViewType(int position) {
return AllDatas.get(position).getItemType();
}
//图片点击的事件
PhotoOnClick postInfoAdapterPhotoOnClick;
public interface PhotoOnClick {
void photoOnClick(int index);
}
@Override
public void onClick(View v) {
if (postInfoAdapterPhotoOnClick == null) {
return;
}
postInfoAdapterPhotoOnClick.photoOnClick((int)v.getTag());
}
}
| 9,402 | 0.658296 | 0.649779 | 236 | 37.305084 | 35.30653 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567797 | false | false | 4 |
ff63beff6925aadc912642ba4fa44e52c447c9f9 | 592,705,516,831 | 96c9b00094b201155f29f84ac3778abb85b4b06f | /src/AbstactFactoryPattern/ConfigClient.java | 0c53e3454f3fa4c0dd3bb60ad3c430bc4c9d7043 | [] | no_license | lixina/DesignPattern | https://github.com/lixina/DesignPattern | 1f7a9ea801afd5d7337be4a1409aa152803f15f8 | 8c8e2ecfaa54318d5c04dc29e056d35b428a09c0 | refs/heads/master | 2020-03-27T04:30:58.349000 | 2018-09-12T08:24:35 | 2018-09-13T01:12:02 | 145,947,094 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package AbstactFactoryPattern;
public class ConfigClient {
public static void main(String[] args) {
User user = new User();
ConfigDataDourse datasourse = new ConfigDataDourse();
IUser iUser;
try {
iUser = datasourse.CreateUser();
IDepartment iDepartment = datasourse.createDepartment();
iUser.insert(user);
iDepartment.update(1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 722 | java | ConfigClient.java | Java | [] | null | [] | package AbstactFactoryPattern;
public class ConfigClient {
public static void main(String[] args) {
User user = new User();
ConfigDataDourse datasourse = new ConfigDataDourse();
IUser iUser;
try {
iUser = datasourse.CreateUser();
IDepartment iDepartment = datasourse.createDepartment();
iUser.insert(user);
iDepartment.update(1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 722 | 0.655125 | 0.65374 | 32 | 20.5625 | 17.296925 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.40625 | false | false | 4 |
10a5bc7495276695037eef816e1b55216594f537 | 26,053,271,687,712 | f54cab13077db394ee32d5cf7dd9a96eea1c4876 | /FinalAssignment/R1315594_10_이호정/R1315594_10_이호정/src/PanelDrawing.java | c910a4a012d41c0c8a47d5f31f1dec2dc9b1a9a7 | [] | no_license | Hojeongleeee/BasicJavaProgramming-in-class | https://github.com/Hojeongleeee/BasicJavaProgramming-in-class | 2198fb3d878b24c17100346a92d2ead763a2cd14 | 1a5e81c726b6d98c7d1bc37d7b3fd02393561370 | refs/heads/master | 2021-01-10T17:52:31.948000 | 2016-02-15T08:53:48 | 2016-02-15T08:53:48 | 48,412,631 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/*
* 시계 배경 (동그라미) 그리기
* paintComponent(Graphics) - JPanel 메소드 오버라이드함. 그림그림
*
*/
class PanelDrawing extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//시계 배경 그리기
g.setColor(Color.orange);
g.drawOval(60, 100, 180, 150);
g.fillOval(60, 100, 180, 150);
}
} | UHC | Java | 453 | java | PanelDrawing.java | Java | [] | null | [] | import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/*
* 시계 배경 (동그라미) 그리기
* paintComponent(Graphics) - JPanel 메소드 오버라이드함. 그림그림
*
*/
class PanelDrawing extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//시계 배경 그리기
g.setColor(Color.orange);
g.drawOval(60, 100, 180, 150);
g.fillOval(60, 100, 180, 150);
}
} | 453 | 0.700767 | 0.644501 | 18 | 20.777779 | 14.953838 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 4 |
a31d48520ec6691f92e8ab7d660049caa6d33888 | 25,864,293,081,020 | 04122e1782d4226f5185b24a2685ed29bb232c84 | /Java/FastCampus/Lecture/ch05/s05/p01/Main.java | 923389c6212d4c2ac9e393118a3059c2b6f17008 | [] | no_license | limjoonchul/TIL | https://github.com/limjoonchul/TIL | ab1d4adaae7acd6337cc9c833e6afe730ad24704 | d92564ea4eeb37607af652c0af129ef23d4197ce | refs/heads/master | 2023-05-06T20:21:09.820000 | 2021-05-12T12:23:26 | 2021-05-12T12:23:26 | 274,395,769 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.s05.p01;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
/**
* 람다식 lambda expression
* jdk 1.8에서 추가된 함수형 프로그래밍 기법
* 함수형 프로그래밍이란? -> 객체지향 프로그래밍과 다르게, 비즈니스 로직만 빠르게 구현하는 방식
* (비즈니스로직이란 : 미션 크리티컬(Mission Critical한 부분 <= 돈이 되는 부분?
* 프로그램을 작성하고 서비스로 구현을하고 서비스가 돌아가고 하는 것은 어떻게 보면
* 돈을 버는 일이기 때문에 프로그래밍해서 돈을 못벌면 프로그래밍을 하는 이유가 없다
* 그래서 프로그램을 작성하고 프로그래밍 실제로 의미가 잇으려면 비즈니스로직을 갖춰야하고
* 실질적인 기능을 수행하는 부분, 사업적인 핵심적인 내용들
* ex) 얼굴인식 서비스를만들 때 서비스의 사업의 본질에 가까운 것을 비즈니스로직
* 미션크리티컬이라고 부른다, 원하는 동작만 빠르게 동작하도록 구현하는 것을 함수형프로그래밍이라고 부른다.
*
* 다시 람다식이라는 것은 객체지향 언어인 java에서 메소드를 함수처럼 사용하는 방식이다.
* java에는 함수라는게 없다. 그런데 함수형 프로그래밍을 하려면 1급 함수라는 개념이 필요하다.
* 이것이 가능하게 하는 것이 람다식이다.
* - 클래스 with 메소드 = 함수로 가정(메소드가 있는 클래스를 함수로 가정한다 일단 이정도만 이해해)
* - 1급 함수 : 자바에서 모든 것이 객체 또는 기초자료형 (프리미티브타입)으로 이루어져있다.
* 그래서 자바에선 1급 객체로 클래스를 통해서 생성한 객체가 모든 것의 기준이 된다.
* 우리가 메소드 콜을 할 때 method(Foo foo); 객체를 넘겨주서 객체를 활용한다
* 1급 객체로서 함수 ? 객체가 주가 되기도 하지만 함수라는 것이 객체와 동일시 될 수 있다
* 자바에서는 객체 안에 메소드가 있어서 메소드가 무언가를 수행하는 역할을 한다.
* 함수라는게 있어서 객체에 딸려있지 않고 자체로서 역할을 하는 메소드와 거의 유사한
* 함수라는 것이 잇을 수 있다.
*
* 그래서 1급 함수는 함수 콜을 하되, func(Func func) 함수를 입력으로 받아서
* 내부에서 함수를 활용을 할 수 있다 메소드에서 객체를 입력받아서 그안에서 객체를 사용하듯이
* 이렇게 함수를 입력받아 사용할 수 있다 함수를 객체처럼 입력을 받아서 활용을 하는 것이
* 1급 함수의 개념이다.
*/
public class Main {
public static void main(String[] args) {
// 람다식이 사용되는 대표적인 예
// 배열의 정렬
String [] strings = {"fast","campus","java","bacend","choigo","best","people"};
System.out.println(Arrays.toString(strings));
Arrays.sort(strings);// 정렬할 수 있다. 사전순으로 Arrays로 정렬하는거 하나 배움
System.out.println(Arrays.toString(strings));
// 방법 1. Comparator 클래스를 만들고, 객체를 생성하여 전달하는 방식이 있다.
class MyComparator implements Comparator<String> {
// string을 비교하기 위한 메소드를 인터페이스가 가지고 있어서
// 인터페이스를 구현하면 sort에 넘겨주면 사전순으로 되어있던걸
// 추가로 객체를 생성해서 넣어주면 새로 만든 메소드가 정렬하는 방식을 다르게 할 수 있다.
@Override
public int compare(String o1, String o2) {
return o1.substring(1).compareTo(o2.substring(1));
// 둘다 짤라서 시작문자가 1번 두번째 인덱스자리를 서로 비교하는 것
//commpareto는 comaprapble 인터페이스에있는것 을가져옴 이미 스트링에 정의되어있음
}
}
//기준을 바꾸고 싶을 때 방법은 새로운 comparator를 넣어줘서
// 객체를 정렬하는 방법을 할 수 있다.
Arrays.sort(strings, new MyComparator() );
System.out.println(Arrays.toString(strings));
// 방법2. 익명 내부 클래스를 이용할 수 있다.
// 상속하고 싶은 인터페이스든 클래스를 적어준다음에 블록을 열어서
// 오버라이드해주면 작성할 수 있다.
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.substring(2).compareTo(o2.substring(2)); //필요한 내용은 이것이다.
}
});
System.out.println(Arrays.toString(strings));
// 방법 3. 람다식을 이용한 방법.(클래스없이 작성이 가능한 익명내부클래스를 한번 더 줄임)
// 람다식을 이용하는게 가장 간단하고 하기 편함
// sort를 보면 하나만 입력을 받으면 자체를 하게되고 두개를 입력받으면 comparator??
//3:40
// 두번째 파라미터는 comparator를 구현한 람다식이라는 것을 알고 있다.
Arrays.sort(strings, (o1, o2) -> o1.substring(3).compareTo(o2.substring(3)));
// 이게 비즈니스로직 동작했으면 하는 코드만 작성하는 것
System.out.println(Arrays.toString(strings));
// 방법 4. comparable을 이용한 방법
class Hansol implements Comparable<Hansol>{
//String 을 상속이 안되서 따로 컴포지션해서 사용했다?
String value;
public Hansol(String value) {
this.value = value;
}
@Override
public int compareTo(Hansol o) {
return value.substring(1).compareTo(o.value.substring(1));
// 자기자신이갖고있는 value랑 외부에서들어온 객체 value랑 비교를 함.
//
}
@Override
public String toString(){
return value;
}
} //스트링이 됬다면 이런 부부느 안해도 됬다.
Hansol[] hansols = {new Hansol("fast"),new Hansol("campus"),new Hansol("backend"),new Hansol("java"),new Hansol("choigo"),new Hansol("best"),new Hansol("people")};
Arrays.sort(hansols);
System.out.println(Arrays.toString(hansols));
// 방법 4 if-Story ~String 상속이 가능했다면~
// 밑에 코드만 구현했으면 됬는데 string은 final로 되어있어서 상속이 안됨
// class Fansol extends String{
// @Override
// public int compareTo(String o){
//
// }
// }
}
}
| UTF-8 | Java | 6,978 | java | Main.java | Java | [] | null | [] | package com.company.s05.p01;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
/**
* 람다식 lambda expression
* jdk 1.8에서 추가된 함수형 프로그래밍 기법
* 함수형 프로그래밍이란? -> 객체지향 프로그래밍과 다르게, 비즈니스 로직만 빠르게 구현하는 방식
* (비즈니스로직이란 : 미션 크리티컬(Mission Critical한 부분 <= 돈이 되는 부분?
* 프로그램을 작성하고 서비스로 구현을하고 서비스가 돌아가고 하는 것은 어떻게 보면
* 돈을 버는 일이기 때문에 프로그래밍해서 돈을 못벌면 프로그래밍을 하는 이유가 없다
* 그래서 프로그램을 작성하고 프로그래밍 실제로 의미가 잇으려면 비즈니스로직을 갖춰야하고
* 실질적인 기능을 수행하는 부분, 사업적인 핵심적인 내용들
* ex) 얼굴인식 서비스를만들 때 서비스의 사업의 본질에 가까운 것을 비즈니스로직
* 미션크리티컬이라고 부른다, 원하는 동작만 빠르게 동작하도록 구현하는 것을 함수형프로그래밍이라고 부른다.
*
* 다시 람다식이라는 것은 객체지향 언어인 java에서 메소드를 함수처럼 사용하는 방식이다.
* java에는 함수라는게 없다. 그런데 함수형 프로그래밍을 하려면 1급 함수라는 개념이 필요하다.
* 이것이 가능하게 하는 것이 람다식이다.
* - 클래스 with 메소드 = 함수로 가정(메소드가 있는 클래스를 함수로 가정한다 일단 이정도만 이해해)
* - 1급 함수 : 자바에서 모든 것이 객체 또는 기초자료형 (프리미티브타입)으로 이루어져있다.
* 그래서 자바에선 1급 객체로 클래스를 통해서 생성한 객체가 모든 것의 기준이 된다.
* 우리가 메소드 콜을 할 때 method(Foo foo); 객체를 넘겨주서 객체를 활용한다
* 1급 객체로서 함수 ? 객체가 주가 되기도 하지만 함수라는 것이 객체와 동일시 될 수 있다
* 자바에서는 객체 안에 메소드가 있어서 메소드가 무언가를 수행하는 역할을 한다.
* 함수라는게 있어서 객체에 딸려있지 않고 자체로서 역할을 하는 메소드와 거의 유사한
* 함수라는 것이 잇을 수 있다.
*
* 그래서 1급 함수는 함수 콜을 하되, func(Func func) 함수를 입력으로 받아서
* 내부에서 함수를 활용을 할 수 있다 메소드에서 객체를 입력받아서 그안에서 객체를 사용하듯이
* 이렇게 함수를 입력받아 사용할 수 있다 함수를 객체처럼 입력을 받아서 활용을 하는 것이
* 1급 함수의 개념이다.
*/
public class Main {
public static void main(String[] args) {
// 람다식이 사용되는 대표적인 예
// 배열의 정렬
String [] strings = {"fast","campus","java","bacend","choigo","best","people"};
System.out.println(Arrays.toString(strings));
Arrays.sort(strings);// 정렬할 수 있다. 사전순으로 Arrays로 정렬하는거 하나 배움
System.out.println(Arrays.toString(strings));
// 방법 1. Comparator 클래스를 만들고, 객체를 생성하여 전달하는 방식이 있다.
class MyComparator implements Comparator<String> {
// string을 비교하기 위한 메소드를 인터페이스가 가지고 있어서
// 인터페이스를 구현하면 sort에 넘겨주면 사전순으로 되어있던걸
// 추가로 객체를 생성해서 넣어주면 새로 만든 메소드가 정렬하는 방식을 다르게 할 수 있다.
@Override
public int compare(String o1, String o2) {
return o1.substring(1).compareTo(o2.substring(1));
// 둘다 짤라서 시작문자가 1번 두번째 인덱스자리를 서로 비교하는 것
//commpareto는 comaprapble 인터페이스에있는것 을가져옴 이미 스트링에 정의되어있음
}
}
//기준을 바꾸고 싶을 때 방법은 새로운 comparator를 넣어줘서
// 객체를 정렬하는 방법을 할 수 있다.
Arrays.sort(strings, new MyComparator() );
System.out.println(Arrays.toString(strings));
// 방법2. 익명 내부 클래스를 이용할 수 있다.
// 상속하고 싶은 인터페이스든 클래스를 적어준다음에 블록을 열어서
// 오버라이드해주면 작성할 수 있다.
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.substring(2).compareTo(o2.substring(2)); //필요한 내용은 이것이다.
}
});
System.out.println(Arrays.toString(strings));
// 방법 3. 람다식을 이용한 방법.(클래스없이 작성이 가능한 익명내부클래스를 한번 더 줄임)
// 람다식을 이용하는게 가장 간단하고 하기 편함
// sort를 보면 하나만 입력을 받으면 자체를 하게되고 두개를 입력받으면 comparator??
//3:40
// 두번째 파라미터는 comparator를 구현한 람다식이라는 것을 알고 있다.
Arrays.sort(strings, (o1, o2) -> o1.substring(3).compareTo(o2.substring(3)));
// 이게 비즈니스로직 동작했으면 하는 코드만 작성하는 것
System.out.println(Arrays.toString(strings));
// 방법 4. comparable을 이용한 방법
class Hansol implements Comparable<Hansol>{
//String 을 상속이 안되서 따로 컴포지션해서 사용했다?
String value;
public Hansol(String value) {
this.value = value;
}
@Override
public int compareTo(Hansol o) {
return value.substring(1).compareTo(o.value.substring(1));
// 자기자신이갖고있는 value랑 외부에서들어온 객체 value랑 비교를 함.
//
}
@Override
public String toString(){
return value;
}
} //스트링이 됬다면 이런 부부느 안해도 됬다.
Hansol[] hansols = {new Hansol("fast"),new Hansol("campus"),new Hansol("backend"),new Hansol("java"),new Hansol("choigo"),new Hansol("best"),new Hansol("people")};
Arrays.sort(hansols);
System.out.println(Arrays.toString(hansols));
// 방법 4 if-Story ~String 상속이 가능했다면~
// 밑에 코드만 구현했으면 됬는데 string은 final로 되어있어서 상속이 안됨
// class Fansol extends String{
// @Override
// public int compareTo(String o){
//
// }
// }
}
}
| 6,978 | 0.593091 | 0.583894 | 127 | 34.102364 | 26.202673 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.377953 | false | false | 4 |
80957dc96a8df23977bcd3c9d08fcc02e850c983 | 24,369,644,478,700 | 116c4f3ec2b263f25204fc9d82d9ac81c3b373aa | /src/main/java/by/epam/javatraining/beseda/webproject/controller/command/implementation/get/LocaleChangerCommand.java | 2d7cbfb58d6f73e75a6b71319da1f6a13502a40b | [] | no_license | BesedaM/Autobase | https://github.com/BesedaM/Autobase | dd7e617cf425fd849ec2bfe245057fc99af00b40 | 57dca15c9872bb4fd182d9bdbb43ce77cbb21bd4 | refs/heads/master | 2022-09-28T16:54:01.672000 | 2020-03-25T20:16:42 | 2020-03-25T20:16:42 | 186,532,564 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.epam.javatraining.beseda.webproject.controller.command.implementation.get;
import by.epam.javatraining.beseda.webproject.controller.command.ActionCommand;
import by.epam.javatraining.beseda.webproject.controller.command.util.srcontent.SessionRequestContent;
import javax.servlet.http.HttpSession;
import java.util.Map;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPParameter.CURRENT_PAGE;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPParameter.LANGUAGE_SELECT;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPSessionAttribute.*;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.CommandConstant.CONTEXT_TO_REPLACE;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.CommandConstant.EMPTY_STRING;
public class LocaleChangerCommand implements ActionCommand {
@Override
public String execute(SessionRequestContent content) {
HttpSession session = content.getSession();
Map<String, String[]> data = content.requestParameters();
String language = data.get(LANGUAGE_SELECT)[0];
String locale = null;
session.setAttribute(LANGUAGE, language);
if (language.equals(LANGUAGE_EN)) {
locale = LOCALE_EN;
} else if (language.equals(LANGUAGE_RU)) {
locale = LOCALE_RU;
}
session.setAttribute(LOCALE_FILE, locale);
return data.get(CURRENT_PAGE)[0].replace(CONTEXT_TO_REPLACE, EMPTY_STRING);
}
} | UTF-8 | Java | 1,566 | java | LocaleChangerCommand.java | Java | [] | null | [] | package by.epam.javatraining.beseda.webproject.controller.command.implementation.get;
import by.epam.javatraining.beseda.webproject.controller.command.ActionCommand;
import by.epam.javatraining.beseda.webproject.controller.command.util.srcontent.SessionRequestContent;
import javax.servlet.http.HttpSession;
import java.util.Map;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPParameter.CURRENT_PAGE;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPParameter.LANGUAGE_SELECT;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.JSPSessionAttribute.*;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.CommandConstant.CONTEXT_TO_REPLACE;
import static by.epam.javatraining.beseda.webproject.controller.command.util.constant.CommandConstant.EMPTY_STRING;
public class LocaleChangerCommand implements ActionCommand {
@Override
public String execute(SessionRequestContent content) {
HttpSession session = content.getSession();
Map<String, String[]> data = content.requestParameters();
String language = data.get(LANGUAGE_SELECT)[0];
String locale = null;
session.setAttribute(LANGUAGE, language);
if (language.equals(LANGUAGE_EN)) {
locale = LOCALE_EN;
} else if (language.equals(LANGUAGE_RU)) {
locale = LOCALE_RU;
}
session.setAttribute(LOCALE_FILE, locale);
return data.get(CURRENT_PAGE)[0].replace(CONTEXT_TO_REPLACE, EMPTY_STRING);
}
} | 1,566 | 0.790549 | 0.789272 | 38 | 39.263157 | 40.273853 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.368421 | false | false | 4 |
a613c311ea1eb06fc71ea0c4cc379f83a8aa2bbc | 36,464,272,344,494 | 3c28c1830c6ac2fd44d7b6dab71198b4b9fe32f2 | /Part 30/src/Sprite.java | fd0cbc081f1b3cf2066934fd092bf4bc5427fe7e | [] | no_license | stemkoski/B.A.G.E.L.-Java | https://github.com/stemkoski/B.A.G.E.L.-Java | 9d8d769ed093e51c96cca86c9476edba905c9d8f | dd3db41f7e2619e38d42a04bb610a1a0208a699c | refs/heads/main | 2023-04-19T21:39:00.396000 | 2021-04-30T18:14:14 | 2021-04-30T18:14:14 | 336,272,280 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javafx.scene.canvas.GraphicsContext;
public class Sprite extends Entity
{
/**
* sprite location in game world
*/
public Vector position;
/**
* angle of rotation (in degrees) of the texture
*/
public double angle;
// reflect along x direction
public boolean mirrored;
// reflect along y direction
public boolean flipped;
/**
* image displayed when rendering this sprite
*/
public Texture texture;
/**
* shape used for collision
*/
public Rectangle boundary;
/**
* width of sprite
*/
public double width;
/**
* height of sprite
*/
public double height;
/**
* determines if sprite will be visible
*/
public boolean visible;
public Sprite()
{
position = new Vector();
angle = 0;
mirrored = false;
flipped = false;
texture = new Texture();
boundary = new Rectangle();
visible = true;
}
/**
* Set the coordinates of the center of this sprite.
* @param x x-coordinate of center of sprite
* @param y y-coordinate of center of sprite
*/
public void setPosition(double x, double y)
{
position.setValues(x, y);
boundary.setPosition(x, y);
}
/**
* Move this sprite by the specified amounts.
* @param dx amount to move sprite along x direction
* @param dy amount to move sprite along y direction
*/
public void moveBy(double dx, double dy)
{
position.addValues(dx, dy);
}
public void setAngle(double a)
{
angle = a;
}
/**
* Rotate sprite by the specified angle.
* @param da the angle (in degrees) to rotate this sprite
*/
public void rotateBy(double da)
{
angle += da;
}
/**
* Move sprite by the specified distance at the specified angle.
* @param dist the distance to move this sprite
* @param a the angle (in degrees) along which to move this sprite
*/
public void moveAtAngle(double dist, double a)
{
double A = Math.toRadians(a);
double dx = dist * Math.cos(A);
double dy = dist * Math.sin(A);
moveBy( dx, dy );
}
/**
* Move sprite forward by the specified distance at current angle.
* @param dist the distance to move this sprite
*/
public void moveForward(double dist)
{
moveAtAngle(dist, angle);
}
/**
* set the texture data used when drawing this sprite;
* also sets width and height of sprite
* @param tex texture data
*/
public void setTexture(Texture tex)
{
texture = tex;
width = texture.region.width;
height = texture.region.height;
boundary.setSize(width, height);
}
/**
* set the width and height of this sprite;
* used for drawing texture and collision rectangle
* @param width sprite width
* @param height sprite height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
boundary.setSize(width, height);
}
/**
* Get boundary shape for this sprite, adjusted according to current position.
* Angle of rotation has no effect on the boundary.
* @return boundary shape for this sprite
*/
public Rectangle getBoundary()
{
boundary.setPosition( position.x, position.y );
return boundary;
}
/**
* Check if this sprite is overlapping another sprite.
* @param other sprite to check for overlap with
* @return true if this sprite overlaps other sprite
*/
public boolean overlaps(Sprite other)
{
return this.getBoundary().overlaps( other.getBoundary() );
}
/**
* Prevent this sprite from overlapping another sprite
* by adjusting the position of this sprite.
* @param other sprite to prevent overlap with
*/
public void preventOverlap(Sprite other)
{
if (this.overlaps(other))
{
Vector mtv = this.getBoundary()
.getMinimumTranslationVector( other.getBoundary() );
this.position.addVector(mtv);
}
}
public void boundToScreen(int screenWidth, int screenHeight)
{
if (position.x < 0)
position.x = 0;
if (position.y < 0)
position.y = 0;
if (position.x + width > screenWidth)
position.x = screenWidth - width;
if (position.y + height > screenHeight)
position.y = screenHeight - height;
}
/**
* draw this sprite on the canvas
* @param context GraphicsContext object that handles drawing to the canvas
*/
public void draw(GraphicsContext context)
{
// if sprite is not visible, exit method
if (!this.visible)
return;
double A = Math.toRadians(angle);
double cosA = Math.cos(A);
double sinA = Math.sin(A);
double scaleX = 1;
if (mirrored)
scaleX = -1;
double scaleY = 1;
if (flipped)
scaleY = -1;
// apply rotation and translation to image
context.setTransform(
scaleX * cosA, scaleX * sinA,
scaleY * (-sinA), scaleY * cosA,
position.x, position.y );
// define source rectangle region of image
// and destination rectangle region of canvas
context.drawImage( texture.image,
texture.region.left, texture.region.top,
texture.region.width, texture.region.height,
-this.width/2, -this.height/2,
this.width, this.height );
}
}
| UTF-8 | Java | 5,773 | java | Sprite.java | Java | [] | null | [] |
import javafx.scene.canvas.GraphicsContext;
public class Sprite extends Entity
{
/**
* sprite location in game world
*/
public Vector position;
/**
* angle of rotation (in degrees) of the texture
*/
public double angle;
// reflect along x direction
public boolean mirrored;
// reflect along y direction
public boolean flipped;
/**
* image displayed when rendering this sprite
*/
public Texture texture;
/**
* shape used for collision
*/
public Rectangle boundary;
/**
* width of sprite
*/
public double width;
/**
* height of sprite
*/
public double height;
/**
* determines if sprite will be visible
*/
public boolean visible;
public Sprite()
{
position = new Vector();
angle = 0;
mirrored = false;
flipped = false;
texture = new Texture();
boundary = new Rectangle();
visible = true;
}
/**
* Set the coordinates of the center of this sprite.
* @param x x-coordinate of center of sprite
* @param y y-coordinate of center of sprite
*/
public void setPosition(double x, double y)
{
position.setValues(x, y);
boundary.setPosition(x, y);
}
/**
* Move this sprite by the specified amounts.
* @param dx amount to move sprite along x direction
* @param dy amount to move sprite along y direction
*/
public void moveBy(double dx, double dy)
{
position.addValues(dx, dy);
}
public void setAngle(double a)
{
angle = a;
}
/**
* Rotate sprite by the specified angle.
* @param da the angle (in degrees) to rotate this sprite
*/
public void rotateBy(double da)
{
angle += da;
}
/**
* Move sprite by the specified distance at the specified angle.
* @param dist the distance to move this sprite
* @param a the angle (in degrees) along which to move this sprite
*/
public void moveAtAngle(double dist, double a)
{
double A = Math.toRadians(a);
double dx = dist * Math.cos(A);
double dy = dist * Math.sin(A);
moveBy( dx, dy );
}
/**
* Move sprite forward by the specified distance at current angle.
* @param dist the distance to move this sprite
*/
public void moveForward(double dist)
{
moveAtAngle(dist, angle);
}
/**
* set the texture data used when drawing this sprite;
* also sets width and height of sprite
* @param tex texture data
*/
public void setTexture(Texture tex)
{
texture = tex;
width = texture.region.width;
height = texture.region.height;
boundary.setSize(width, height);
}
/**
* set the width and height of this sprite;
* used for drawing texture and collision rectangle
* @param width sprite width
* @param height sprite height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
boundary.setSize(width, height);
}
/**
* Get boundary shape for this sprite, adjusted according to current position.
* Angle of rotation has no effect on the boundary.
* @return boundary shape for this sprite
*/
public Rectangle getBoundary()
{
boundary.setPosition( position.x, position.y );
return boundary;
}
/**
* Check if this sprite is overlapping another sprite.
* @param other sprite to check for overlap with
* @return true if this sprite overlaps other sprite
*/
public boolean overlaps(Sprite other)
{
return this.getBoundary().overlaps( other.getBoundary() );
}
/**
* Prevent this sprite from overlapping another sprite
* by adjusting the position of this sprite.
* @param other sprite to prevent overlap with
*/
public void preventOverlap(Sprite other)
{
if (this.overlaps(other))
{
Vector mtv = this.getBoundary()
.getMinimumTranslationVector( other.getBoundary() );
this.position.addVector(mtv);
}
}
public void boundToScreen(int screenWidth, int screenHeight)
{
if (position.x < 0)
position.x = 0;
if (position.y < 0)
position.y = 0;
if (position.x + width > screenWidth)
position.x = screenWidth - width;
if (position.y + height > screenHeight)
position.y = screenHeight - height;
}
/**
* draw this sprite on the canvas
* @param context GraphicsContext object that handles drawing to the canvas
*/
public void draw(GraphicsContext context)
{
// if sprite is not visible, exit method
if (!this.visible)
return;
double A = Math.toRadians(angle);
double cosA = Math.cos(A);
double sinA = Math.sin(A);
double scaleX = 1;
if (mirrored)
scaleX = -1;
double scaleY = 1;
if (flipped)
scaleY = -1;
// apply rotation and translation to image
context.setTransform(
scaleX * cosA, scaleX * sinA,
scaleY * (-sinA), scaleY * cosA,
position.x, position.y );
// define source rectangle region of image
// and destination rectangle region of canvas
context.drawImage( texture.image,
texture.region.left, texture.region.top,
texture.region.width, texture.region.height,
-this.width/2, -this.height/2,
this.width, this.height );
}
}
| 5,773 | 0.578902 | 0.576996 | 224 | 24.763393 | 20.630514 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.370536 | false | false | 4 |
0eb2c0f9889bfabe479f6fbe2f000af1cf969fe9 | 19,894,288,560,502 | 8a0c601d38eabc62b7fbc8652515acb252cd6508 | /src/main/java/simbryo/dynamics/tissue/TissueDynamicsInterface.java | 6564e2ee5109ecfcecabc836fca35477683705a8 | [] | no_license | amytraylor/simbryo | https://github.com/amytraylor/simbryo | 771ed3088fedc5e3b9075c8abebec29849cb8395 | df7be8cb2ce4801507595c44011a8c6672afb107 | refs/heads/master | 2020-07-12T09:48:19.685000 | 2018-09-23T03:24:12 | 2018-09-23T03:24:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package simbryo.dynamics.tissue;
import java.io.Serializable;
import simbryo.SimulationInterface;
import simbryo.particles.ParticleSystemInterface;
/**
* Tissue dynamics interface
*
*
* @author royer
*/
public interface TissueDynamicsInterface extends
ParticleSystemInterface,
SimulationInterface,
Serializable
{
// nothing _yet_
}
| UTF-8 | Java | 467 | java | TissueDynamicsInterface.java | Java | [
{
"context": "/**\n * Tissue dynamics interface\n * \n *\n * @author royer\n */\npublic interface TissueDynamicsInterface exte",
"end": 207,
"score": 0.9962080121040344,
"start": 202,
"tag": "USERNAME",
"value": "royer"
}
] | null | [] | package simbryo.dynamics.tissue;
import java.io.Serializable;
import simbryo.SimulationInterface;
import simbryo.particles.ParticleSystemInterface;
/**
* Tissue dynamics interface
*
*
* @author royer
*/
public interface TissueDynamicsInterface extends
ParticleSystemInterface,
SimulationInterface,
Serializable
{
// nothing _yet_
}
| 467 | 0.582441 | 0.582441 | 21 | 21.238094 | 22.272991 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
bf32a78069a085b832eeb03bb772b7d05f40350a | 19,301,583,053,737 | da41237e18690fd89587ab0551c66580cd945536 | /DianCan/src/com/diancan/MainFirstPage.java | d1e709a008b8848b83ae938b3b6c75929f34686a | [] | no_license | langyan8973/AndroidDiancan | https://github.com/langyan8973/AndroidDiancan | 7f65ff2a828f1971f49b186b2eab1b8b17c27eac | 153e5221cfcca7012a188c90fd30b76c95a42369 | refs/heads/master | 2021-01-23T13:36:45.754000 | 2013-04-10T08:08:12 | 2013-04-10T08:08:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.diancan;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.diancan.Utils.BitmapUtil;
import com.diancan.Utils.FileUtils;
import com.diancan.Utils.JsonUtils;
import com.diancan.Utils.MenuUtils;
import com.diancan.diancanapp.AppDiancan;
import com.diancan.http.HttpCallback;
import com.diancan.http.HttpHandler;
import com.diancan.model.city;
import com.weibo.sdk.android.Oauth2AccessToken;
import android.app.Activity;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainFirstPage extends Activity implements OnClickListener,HttpCallback,MKSearchListener {
TextView cityTextView;
Button restaurantsBtn;
Button captrueBtn;
Button userBtn;
Button browseBtn;
Button searchBtn;
Button historyBtn;
AppDiancan appDiancan;
LocationListener mLocationListener=null;
/** 定义搜索服务类 */
HttpHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainfirst);
appDiancan = (AppDiancan)getApplicationContext();
mHandler = new HttpHandler(this);
cityTextView = (TextView)findViewById(R.id.selectcity_btn);
cityTextView.setOnClickListener(this);
restaurantsBtn=(Button)findViewById(R.id.toRestaurants);
restaurantsBtn.setOnClickListener(this);
captrueBtn=(Button)findViewById(R.id.toCapture);
captrueBtn.setOnClickListener(this);
userBtn = (Button)findViewById(R.id.user_btn);
userBtn.setOnClickListener(this);
browseBtn = (Button)findViewById(R.id.toBrowse);
browseBtn.setOnClickListener(this);
searchBtn = (Button)findViewById(R.id.search_btn);
searchBtn.setOnClickListener(this);
//历史订单
historyBtn = (Button)findViewById(R.id.toHistory);
historyBtn.setOnClickListener(this);
if(appDiancan.mBMapMan==null)
{
appDiancan.mBMapMan=new BMapManager(getApplicationContext());
appDiancan.mBMapMan.init(appDiancan.BMapKey, new AppDiancan.MyGeneralListener());
}
if(appDiancan.locationCity==null){
//定位监听器
mLocationListener=new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
(int)(location.getLongitude()*1e6));
/** 初始化MKSearch */
MKSearch mMKSearch = new MKSearch();
mMKSearch.init(appDiancan.mBMapMan, MainFirstPage.this);
mMKSearch.reverseGeocode(pt);
}
}
};
appDiancan.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
appDiancan.mBMapMan.start();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(appDiancan.selectedCity!=null){
cityTextView.setText(appDiancan.selectedCity.getName());
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mLocationListener = null;
mHandler = null;
System.gc();
BitmapUtil.destroyDrawable(cityTextView);
BitmapUtil.destroyDrawable(restaurantsBtn);
BitmapUtil.destroyDrawable(historyBtn);
BitmapUtil.destroyDrawable(browseBtn);
BitmapUtil.destroyDrawable(captrueBtn);
BitmapUtil.destroyDrawable(searchBtn);
BitmapUtil.destroyDrawable(userBtn);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(appDiancan.mBMapMan!=null){
appDiancan.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
appDiancan.mBMapMan.stop();
}
}
@Override
public void RequestComplete(Message msg) {
// TODO Auto-generated method stub
if(msg.what == HttpHandler.LOCATION_CITY){
city c = (city)msg.obj;
setCityName(c);
}
}
@Override
public void RequestError(String errString) {
// TODO Auto-generated method stub
ShowError(errString);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.toRestaurants){
if(appDiancan.selectedCity == null){
ShowError(getString(R.string.message_select_city));
return;
}
ToRestaurantsPage();
}
else if(v.getId()==R.id.toCapture){
ToCapturePage();
}
else if(v.getId()==R.id.toHistory){
ToHistoriesListPage();
}else if(v.getId()==R.id.user_btn){
ToUserInfoPage();
}
else if(v.getId()==R.id.toBrowse){
ToHisBrowse();
}
else if(v.getId()==R.id.search_btn){
if(appDiancan.selectedCity == null){
ShowError(getString(R.string.message_select_city));
return;
}
ToSearchPage();
}
else if(v.getId()==R.id.selectcity_btn){
Intent intent = new Intent(this,CityPage.class);
startActivity(intent);
}
}
/**
* 显示错误信息
* @param strMess
*/
public void ShowError(String strMess) {
Toast toast = Toast.makeText(MainFirstPage.this, strMess, Toast.LENGTH_SHORT);
toast.show();
}
private void setCityName(final city c){
if(appDiancan.selectedCity==null){
appDiancan.selectedCity = c;
cityTextView.setText(appDiancan.selectedCity.getName());
}
else{
if(!appDiancan.selectedCity.getId().equals(c.getId())){
final Dialog dialog = new Dialog(getParent(), R.style.MyDialog);
//设置它的ContentView
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog, null);
dialog.setContentView(layout);
String contentString = getString(R.string.message_locationcityis)+c.getName()+getString(R.string.message_areyouchange);
TextView contentView = (TextView)layout.findViewById(R.id.contentTxt);
TextView titleView = (TextView)layout.findViewById(R.id.dialog_title);
Button okBtn = (Button)layout.findViewById(R.id.dialog_button_ok);
okBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
appDiancan.selectedCity = c;
cityTextView.setText(appDiancan.selectedCity.getName());
}
});
Button cancelButton = (Button)layout.findViewById(R.id.dialog_button_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
titleView.setText(R.string.title_location);
contentView.setText(contentString);
contentView.setMovementMethod(ScrollingMovementMethod.getInstance());
dialog.show();
Animation animation = AnimationUtils.loadAnimation(MainFirstPage.this, R.anim.activity_in);
animation.setInterpolator(new OvershootInterpolator());
layout.startAnimation(animation);
}
}
}
private void ToRestaurantsPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), RestaurantActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_RESTAURANTACTIVITY, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToCapturePage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), CaptureActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_CAPTUREACTIVITY, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToHistoriesListPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), HistoryList.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_HISTORYLIST, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToUserInfoPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), UserInfoActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_USERINFO, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToHisBrowse(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), HisBrowse.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_HISBROWSE, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToSearchPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), SearchPage.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_SEARCHPAGE, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
public void RequestAllCities(final String cityName){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
String jsonString = MenuUtils.getAllCities();
if(!jsonString.isEmpty()){
List<city> cities = JsonUtils.parseJsonTocities(jsonString);
Iterator<city> iterator;
for(iterator=cities.iterator();iterator.hasNext();){
city c = iterator.next();
if(cityName.contains(c.getName())){
appDiancan.locationCity = c;
if(mHandler!=null){
mHandler.obtainMessage(HttpHandler.LOCATION_CITY, c).sendToTarget();
}
break;
}
}
FileUtils._cityFile=new File(Environment.getExternalStorageDirectory().getPath()+"/ChiHuoPro/city.txt");
FileUtils.SaveCity(FileUtils._cityFile.getAbsolutePath(), jsonString);
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}).start();
}
@Override
public void onGetAddrResult(MKAddrInfo result, int iError) {
// TODO Auto-generated method stub
if( iError != 0 || result == null){
Toast.makeText(MainFirstPage.this, getString(R.string.message_getcityinfo_fail), Toast.LENGTH_LONG).show();
}else {
String cityName =result.addressComponents.city;
if(FileUtils._cityFile.exists()){
try {
String jsonString = FileUtils.ReadCity(FileUtils._cityFile.getAbsolutePath());
List<city> cities = JsonUtils.parseJsonTocities(jsonString);
Iterator<city> iterator;
for(iterator=cities.iterator();iterator.hasNext();){
city c = iterator.next();
if(cityName.contains(c.getName())){
appDiancan.locationCity = c;
if (mHandler!=null) {
mHandler.obtainMessage(HttpHandler.LOCATION_CITY, c).sendToTarget();
}
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ShowError(e.getMessage());
}
}
else{
RequestAllCities(cityName);
}
}
}
@Override
public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiDetailSearchResult(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onGetRGCShareUrlResult(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 18,036 | java | MainFirstPage.java | Java | [] | null | [] | package com.diancan;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.diancan.Utils.BitmapUtil;
import com.diancan.Utils.FileUtils;
import com.diancan.Utils.JsonUtils;
import com.diancan.Utils.MenuUtils;
import com.diancan.diancanapp.AppDiancan;
import com.diancan.http.HttpCallback;
import com.diancan.http.HttpHandler;
import com.diancan.model.city;
import com.weibo.sdk.android.Oauth2AccessToken;
import android.app.Activity;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainFirstPage extends Activity implements OnClickListener,HttpCallback,MKSearchListener {
TextView cityTextView;
Button restaurantsBtn;
Button captrueBtn;
Button userBtn;
Button browseBtn;
Button searchBtn;
Button historyBtn;
AppDiancan appDiancan;
LocationListener mLocationListener=null;
/** 定义搜索服务类 */
HttpHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainfirst);
appDiancan = (AppDiancan)getApplicationContext();
mHandler = new HttpHandler(this);
cityTextView = (TextView)findViewById(R.id.selectcity_btn);
cityTextView.setOnClickListener(this);
restaurantsBtn=(Button)findViewById(R.id.toRestaurants);
restaurantsBtn.setOnClickListener(this);
captrueBtn=(Button)findViewById(R.id.toCapture);
captrueBtn.setOnClickListener(this);
userBtn = (Button)findViewById(R.id.user_btn);
userBtn.setOnClickListener(this);
browseBtn = (Button)findViewById(R.id.toBrowse);
browseBtn.setOnClickListener(this);
searchBtn = (Button)findViewById(R.id.search_btn);
searchBtn.setOnClickListener(this);
//历史订单
historyBtn = (Button)findViewById(R.id.toHistory);
historyBtn.setOnClickListener(this);
if(appDiancan.mBMapMan==null)
{
appDiancan.mBMapMan=new BMapManager(getApplicationContext());
appDiancan.mBMapMan.init(appDiancan.BMapKey, new AppDiancan.MyGeneralListener());
}
if(appDiancan.locationCity==null){
//定位监听器
mLocationListener=new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
(int)(location.getLongitude()*1e6));
/** 初始化MKSearch */
MKSearch mMKSearch = new MKSearch();
mMKSearch.init(appDiancan.mBMapMan, MainFirstPage.this);
mMKSearch.reverseGeocode(pt);
}
}
};
appDiancan.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
appDiancan.mBMapMan.start();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(appDiancan.selectedCity!=null){
cityTextView.setText(appDiancan.selectedCity.getName());
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mLocationListener = null;
mHandler = null;
System.gc();
BitmapUtil.destroyDrawable(cityTextView);
BitmapUtil.destroyDrawable(restaurantsBtn);
BitmapUtil.destroyDrawable(historyBtn);
BitmapUtil.destroyDrawable(browseBtn);
BitmapUtil.destroyDrawable(captrueBtn);
BitmapUtil.destroyDrawable(searchBtn);
BitmapUtil.destroyDrawable(userBtn);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(appDiancan.mBMapMan!=null){
appDiancan.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
appDiancan.mBMapMan.stop();
}
}
@Override
public void RequestComplete(Message msg) {
// TODO Auto-generated method stub
if(msg.what == HttpHandler.LOCATION_CITY){
city c = (city)msg.obj;
setCityName(c);
}
}
@Override
public void RequestError(String errString) {
// TODO Auto-generated method stub
ShowError(errString);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.toRestaurants){
if(appDiancan.selectedCity == null){
ShowError(getString(R.string.message_select_city));
return;
}
ToRestaurantsPage();
}
else if(v.getId()==R.id.toCapture){
ToCapturePage();
}
else if(v.getId()==R.id.toHistory){
ToHistoriesListPage();
}else if(v.getId()==R.id.user_btn){
ToUserInfoPage();
}
else if(v.getId()==R.id.toBrowse){
ToHisBrowse();
}
else if(v.getId()==R.id.search_btn){
if(appDiancan.selectedCity == null){
ShowError(getString(R.string.message_select_city));
return;
}
ToSearchPage();
}
else if(v.getId()==R.id.selectcity_btn){
Intent intent = new Intent(this,CityPage.class);
startActivity(intent);
}
}
/**
* 显示错误信息
* @param strMess
*/
public void ShowError(String strMess) {
Toast toast = Toast.makeText(MainFirstPage.this, strMess, Toast.LENGTH_SHORT);
toast.show();
}
private void setCityName(final city c){
if(appDiancan.selectedCity==null){
appDiancan.selectedCity = c;
cityTextView.setText(appDiancan.selectedCity.getName());
}
else{
if(!appDiancan.selectedCity.getId().equals(c.getId())){
final Dialog dialog = new Dialog(getParent(), R.style.MyDialog);
//设置它的ContentView
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog, null);
dialog.setContentView(layout);
String contentString = getString(R.string.message_locationcityis)+c.getName()+getString(R.string.message_areyouchange);
TextView contentView = (TextView)layout.findViewById(R.id.contentTxt);
TextView titleView = (TextView)layout.findViewById(R.id.dialog_title);
Button okBtn = (Button)layout.findViewById(R.id.dialog_button_ok);
okBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
appDiancan.selectedCity = c;
cityTextView.setText(appDiancan.selectedCity.getName());
}
});
Button cancelButton = (Button)layout.findViewById(R.id.dialog_button_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
titleView.setText(R.string.title_location);
contentView.setText(contentString);
contentView.setMovementMethod(ScrollingMovementMethod.getInstance());
dialog.show();
Animation animation = AnimationUtils.loadAnimation(MainFirstPage.this, R.anim.activity_in);
animation.setInterpolator(new OvershootInterpolator());
layout.startAnimation(animation);
}
}
}
private void ToRestaurantsPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), RestaurantActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_RESTAURANTACTIVITY, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToCapturePage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), CaptureActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_CAPTUREACTIVITY, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToHistoriesListPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), HistoryList.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_HISTORYLIST, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToUserInfoPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), UserInfoActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_USERINFO, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToHisBrowse(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), HisBrowse.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_HISBROWSE, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
private void ToSearchPage(){
MenuGroup parent = (MenuGroup)this.getParent();
LocalActivityManager manager = parent.getLocalActivityManager();
Activity activity=manager.getCurrentActivity();
Window w1=activity.getWindow();
View v1=w1.getDecorView();
Animation sAnimation=AnimationUtils.loadAnimation(this, R.anim.push_left_out);
v1.startAnimation(sAnimation);
final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
contain.removeAllViews();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
Intent in = new Intent(this.getParent(), SearchPage.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window window = manager.startActivity(MenuGroup.ID_SEARCHPAGE, in);
View view=window.getDecorView();
contain.addView(view);
LayoutParams params=(LayoutParams) view.getLayoutParams();
params.width=LayoutParams.FILL_PARENT;
params.height=LayoutParams.FILL_PARENT;
view.setLayoutParams(params);
view.startAnimation(animation);
}
public void RequestAllCities(final String cityName){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
String jsonString = MenuUtils.getAllCities();
if(!jsonString.isEmpty()){
List<city> cities = JsonUtils.parseJsonTocities(jsonString);
Iterator<city> iterator;
for(iterator=cities.iterator();iterator.hasNext();){
city c = iterator.next();
if(cityName.contains(c.getName())){
appDiancan.locationCity = c;
if(mHandler!=null){
mHandler.obtainMessage(HttpHandler.LOCATION_CITY, c).sendToTarget();
}
break;
}
}
FileUtils._cityFile=new File(Environment.getExternalStorageDirectory().getPath()+"/ChiHuoPro/city.txt");
FileUtils.SaveCity(FileUtils._cityFile.getAbsolutePath(), jsonString);
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}).start();
}
@Override
public void onGetAddrResult(MKAddrInfo result, int iError) {
// TODO Auto-generated method stub
if( iError != 0 || result == null){
Toast.makeText(MainFirstPage.this, getString(R.string.message_getcityinfo_fail), Toast.LENGTH_LONG).show();
}else {
String cityName =result.addressComponents.city;
if(FileUtils._cityFile.exists()){
try {
String jsonString = FileUtils.ReadCity(FileUtils._cityFile.getAbsolutePath());
List<city> cities = JsonUtils.parseJsonTocities(jsonString);
Iterator<city> iterator;
for(iterator=cities.iterator();iterator.hasNext();){
city c = iterator.next();
if(cityName.contains(c.getName())){
appDiancan.locationCity = c;
if (mHandler!=null) {
mHandler.obtainMessage(HttpHandler.LOCATION_CITY, c).sendToTarget();
}
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ShowError(e.getMessage());
}
}
else{
RequestAllCities(cityName);
}
}
}
@Override
public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiDetailSearchResult(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onGetRGCShareUrlResult(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
}
| 18,036 | 0.724052 | 0.721437 | 546 | 31.926741 | 24.897118 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.549451 | false | false | 4 |
5aabfc00b557abdd463ab87566346f178388c8fe | 34,445,637,732,135 | 714c8d38fcc683f06d192edad8adb31f80e9d7cf | /src/main/java/br/com/caelum/model/Produto.java | 424e48b4b24729d486989250cf92efa4940529f8 | [] | no_license | skatesham/loja-web-jpa-tomcat-maven | https://github.com/skatesham/loja-web-jpa-tomcat-maven | 6da556504a45951aa173204119496db490c6c1af | 1af7f31f15d437ba6f0cf2da74a10112be487277 | refs/heads/master | 2020-04-11T22:43:47.335000 | 2018-12-18T18:59:32 | 2018-12-18T18:59:32 | 162,146,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.caelum.model;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
//import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.Version;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Data;
// SOLUÇÃO PROBLEMA DE N+1 COM SOLUCÃO EM PRODUTODAO
@NamedEntityGraphs({
@NamedEntityGraph(name = "produtoComCategoria",
attributeNodes = {
@NamedAttributeNode("categorias")
})
})
@Entity
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public @Data class Produto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty
private String nome;
@NotEmpty
private String linkDaFoto;
@NotEmpty
@Column(columnDefinition = "TEXT")
private String descricao;
@Min(20)
private double preco;
@Valid
@ManyToOne
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Loja loja;
//@ManyToMany(fetch = FetchType.EAGER)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name="Produto_Categoria",
joinColumns = @JoinColumn(name="produto_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="categoria_id", referencedColumnName = "id"))
@ManyToMany
private List<Categoria> categorias = new LinkedList<>();
@Version
private Integer versao;
// método auxiliar para associar categorias com o produto
// se funcionar apos ter definido o relacionamento entre produto e categoria
public void adicionarCategorias(Categoria... categorias) {
for (Categoria categoria : categorias) {
this.categorias.add(categoria);
}
}
}
| UTF-8 | Java | 2,288 | java | Produto.java | Java | [] | null | [] |
package br.com.caelum.model;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
//import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.Version;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Data;
// SOLUÇÃO PROBLEMA DE N+1 COM SOLUCÃO EM PRODUTODAO
@NamedEntityGraphs({
@NamedEntityGraph(name = "produtoComCategoria",
attributeNodes = {
@NamedAttributeNode("categorias")
})
})
@Entity
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public @Data class Produto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty
private String nome;
@NotEmpty
private String linkDaFoto;
@NotEmpty
@Column(columnDefinition = "TEXT")
private String descricao;
@Min(20)
private double preco;
@Valid
@ManyToOne
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Loja loja;
//@ManyToMany(fetch = FetchType.EAGER)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name="Produto_Categoria",
joinColumns = @JoinColumn(name="produto_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="categoria_id", referencedColumnName = "id"))
@ManyToMany
private List<Categoria> categorias = new LinkedList<>();
@Version
private Integer versao;
// método auxiliar para associar categorias com o produto
// se funcionar apos ter definido o relacionamento entre produto e categoria
public void adicionarCategorias(Categoria... categorias) {
for (Categoria categoria : categorias) {
this.categorias.add(categoria);
}
}
}
| 2,288 | 0.767513 | 0.7662 | 83 | 26.506023 | 21.974998 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.975904 | false | false | 4 |
5cd35adc26db54fa252f4cc6827e125a542f9119 | 34,445,637,732,175 | 250aa2508e907317d748ec1b499590bf4c7d6109 | /src/main/java/ws/rocket/sqlstore/types/StringMapper.java | a785c152bc94f9001f4d34071710a1e66f587d49 | [
"Apache-2.0"
] | permissive | mrtamm/sqlstore | https://github.com/mrtamm/sqlstore | d5909f28e84508da59b8cdde47937ebd20242d91 | 8bb7ff4cab1ae747ab5b88c2ca489838e1f7656a | refs/heads/master | 2023-04-13T14:21:56.657000 | 2023-03-17T10:33:20 | 2023-03-17T10:33:20 | 29,619,582 | 4 | 0 | NOASSERTION | false | 2023-03-17T10:33:22 | 2015-01-21T21:57:04 | 2023-01-09T16:27:11 | 2023-03-17T10:33:21 | 466 | 2 | 0 | 2 | Java | false | false | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.rocket.sqlstore.types;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.rowset.serial.SerialClob;
/**
* Default value mapper for <code>java.lang.String</code>. This mapper does not make any
* restrictions on SQL type but defaults to <code>VARCHAR</code> when undefined.
*/
public final class StringMapper implements ValueMapper {
@Override
public boolean supports(Class<?> type) {
return String.class == type;
}
@Override
public int confirmSqlType(Integer providedType) {
return providedType != null ? providedType : Types.VARCHAR;
}
@Override
public void write(PreparedStatement ps, int index, Object value, int sqlType)
throws SQLException {
String str = (String) value;
if (str == null) {
ps.setNull(index, sqlType);
} else if (sqlType == Types.CLOB || sqlType == Types.NCLOB) {
ps.setClob(index, new SerialClob(str.toCharArray()));
} else {
ps.setString(index, str);
}
}
@Override
public String read(ResultSet rs, int index, int sqlType) throws SQLException {
if (sqlType == Types.CLOB) {
return readClob(rs.getClob(index));
} else if (sqlType == Types.NCLOB) {
return readClob(rs.getNClob(index));
}
return rs.getString(index);
}
@Override
public String read(CallableStatement stmt, int index, int sqlType) throws SQLException {
if (sqlType == Types.CLOB) {
return readClob(stmt.getClob(index));
} else if (sqlType == Types.NCLOB) {
return readClob(stmt.getNClob(index));
}
return stmt.getString(index);
}
private String readClob(Clob clob) throws SQLException {
if (clob == null || clob.length() == 0L) {
return null;
}
int len = EnvSupport.getInstance().getLobSizeForArray(clob.length());
return len < 0 ? null : clob.getSubString(0L, len);
}
}
| UTF-8 | Java | 2,599 | java | StringMapper.java | Java | [] | null | [] | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.rocket.sqlstore.types;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.rowset.serial.SerialClob;
/**
* Default value mapper for <code>java.lang.String</code>. This mapper does not make any
* restrictions on SQL type but defaults to <code>VARCHAR</code> when undefined.
*/
public final class StringMapper implements ValueMapper {
@Override
public boolean supports(Class<?> type) {
return String.class == type;
}
@Override
public int confirmSqlType(Integer providedType) {
return providedType != null ? providedType : Types.VARCHAR;
}
@Override
public void write(PreparedStatement ps, int index, Object value, int sqlType)
throws SQLException {
String str = (String) value;
if (str == null) {
ps.setNull(index, sqlType);
} else if (sqlType == Types.CLOB || sqlType == Types.NCLOB) {
ps.setClob(index, new SerialClob(str.toCharArray()));
} else {
ps.setString(index, str);
}
}
@Override
public String read(ResultSet rs, int index, int sqlType) throws SQLException {
if (sqlType == Types.CLOB) {
return readClob(rs.getClob(index));
} else if (sqlType == Types.NCLOB) {
return readClob(rs.getNClob(index));
}
return rs.getString(index);
}
@Override
public String read(CallableStatement stmt, int index, int sqlType) throws SQLException {
if (sqlType == Types.CLOB) {
return readClob(stmt.getClob(index));
} else if (sqlType == Types.NCLOB) {
return readClob(stmt.getNClob(index));
}
return stmt.getString(index);
}
private String readClob(Clob clob) throws SQLException {
if (clob == null || clob.length() == 0L) {
return null;
}
int len = EnvSupport.getInstance().getLobSizeForArray(clob.length());
return len < 0 ? null : clob.getSubString(0L, len);
}
}
| 2,599 | 0.693728 | 0.689496 | 87 | 28.873564 | 26.433958 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.494253 | false | false | 4 |
129b4f8dc2813f2686f02fcf8d5bcd2bbb505d43 | 12,309,376,315,042 | 594dbe9ad659263e560e2d84d02dae411e3ff2ca | /glaf-web/src/main/java/com/glaf/form/core/util/FormRuleDomainFactory.java | ee0fe3ae363862268365ff7a04cd89e247007034 | [] | no_license | eosite/openyourarm | https://github.com/eosite/openyourarm | 670b3739f9abb81b36a7d90846b6d2e68217b443 | 7098657ee60bf6749a13c0ea19d1ac1a42a684a0 | refs/heads/master | 2021-05-08T16:38:30.406000 | 2018-01-24T03:38:45 | 2018-01-24T03:38:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.glaf.form.core.util;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.glaf.core.base.DataRequest;
import com.glaf.core.base.DataRequest.FilterDescriptor;
import com.glaf.core.domain.ColumnDefinition;
import com.glaf.core.domain.TableDefinition;
import com.glaf.core.util.DBUtils;
/**
*
* 实体数据工厂类
*
*/
public class FormRuleDomainFactory {
public static final String TABLENAME = "FORM_RULE";
public static final ConcurrentMap<String, String> columnMap = new ConcurrentHashMap<String, String>();
public static final ConcurrentMap<String, String> javaTypeMap = new ConcurrentHashMap<String, String>();
static {
columnMap.put("id", "ID_");
columnMap.put("componentId", "COMPONENTID_");
columnMap.put("appId", "APPID_");
columnMap.put("pageId", "PAGEID_");
columnMap.put("deploymentId", "DEPLOYMENTID_");
columnMap.put("name", "NAME_");
columnMap.put("type", "TYPE_");
columnMap.put("value", "VALUE_");
columnMap.put("snapshot", "SNAPSHOT_");
columnMap.put("createDate", "CREATEDATE_");
columnMap.put("createBy", "CREATEBY_");
javaTypeMap.put("id", "String");
javaTypeMap.put("componentId", "Long");
javaTypeMap.put("appId", "String");
javaTypeMap.put("pageId", "String");
javaTypeMap.put("deploymentId", "String");
javaTypeMap.put("name", "String");
javaTypeMap.put("type", "String");
javaTypeMap.put("value", "String");
javaTypeMap.put("snapshot", "String");
javaTypeMap.put("createDate", "Date");
javaTypeMap.put("createBy", "String");
}
public static Map<String, String> getColumnMap() {
return columnMap;
}
public static Map<String, String> getJavaTypeMap() {
return javaTypeMap;
}
public static TableDefinition getTableDefinition() {
return getTableDefinition(TABLENAME);
}
public static TableDefinition getTableDefinition(String tableName) {
tableName = tableName.toUpperCase();
TableDefinition tableDefinition = new TableDefinition();
tableDefinition.setTableName(tableName);
tableDefinition.setName("FormRule");
ColumnDefinition idColumn = new ColumnDefinition();
idColumn.setName("id");
idColumn.setColumnName("ID_");
idColumn.setJavaType("String");
idColumn.setLength(50);
tableDefinition.setIdColumn(idColumn);
ColumnDefinition componentId = new ColumnDefinition();
componentId.setName("componentId");
componentId.setColumnName("COMPONENTID_");
componentId.setJavaType("Long");
tableDefinition.addColumn(componentId);
ColumnDefinition appId = new ColumnDefinition();
appId.setName("appId");
appId.setColumnName("APPID_");
appId.setJavaType("String");
appId.setLength(50);
tableDefinition.addColumn(appId);
ColumnDefinition pageId = new ColumnDefinition();
pageId.setName("pageId");
pageId.setColumnName("PAGEID_");
pageId.setJavaType("String");
pageId.setLength(50);
tableDefinition.addColumn(pageId);
ColumnDefinition deploymentId = new ColumnDefinition();
deploymentId.setName("deploymentId");
deploymentId.setColumnName("DEPLOYMENTID_");
deploymentId.setJavaType("String");
deploymentId.setLength(100);
tableDefinition.addColumn(deploymentId);
ColumnDefinition name = new ColumnDefinition();
name.setName("name");
name.setColumnName("NAME_");
name.setJavaType("String");
name.setLength(100);
tableDefinition.addColumn(name);
ColumnDefinition type = new ColumnDefinition();
type.setName("type");
type.setColumnName("TYPE_");
type.setJavaType("String");
type.setLength(50);
tableDefinition.addColumn(type);
ColumnDefinition value = new ColumnDefinition();
value.setName("value");
value.setColumnName("VALUE_");
value.setJavaType("String");
value.setLength(2000);
tableDefinition.addColumn(value);
ColumnDefinition snapshot = new ColumnDefinition();
snapshot.setName("snapshot");
snapshot.setColumnName("SNAPSHOT_");
snapshot.setJavaType("String");
snapshot.setLength(2000);
tableDefinition.addColumn(snapshot);
ColumnDefinition createDate = new ColumnDefinition();
createDate.setName("createDate");
createDate.setColumnName("CREATEDATE_");
createDate.setJavaType("Date");
tableDefinition.addColumn(createDate);
ColumnDefinition createBy = new ColumnDefinition();
createBy.setName("createBy");
createBy.setColumnName("CREATEBY_");
createBy.setJavaType("String");
createBy.setLength(50);
tableDefinition.addColumn(createBy);
return tableDefinition;
}
public static TableDefinition createTable() {
TableDefinition tableDefinition = getTableDefinition(TABLENAME);
if (!DBUtils.tableExists(TABLENAME)) {
DBUtils.createTable(tableDefinition);
} else {
DBUtils.alterTable(tableDefinition);
}
return tableDefinition;
}
public static TableDefinition createTable(String tableName) {
TableDefinition tableDefinition = getTableDefinition(tableName);
if (!DBUtils.tableExists(tableName)) {
DBUtils.createTable(tableDefinition);
} else {
DBUtils.alterTable(tableDefinition);
}
return tableDefinition;
}
public static void processDataRequest(DataRequest dataRequest) {
if (dataRequest != null) {
if (dataRequest.getFilter() != null) {
if (dataRequest.getFilter().getField() != null) {
dataRequest.getFilter().setColumn(
columnMap.get(dataRequest.getFilter().getField()));
dataRequest.getFilter()
.setJavaType(
javaTypeMap.get(dataRequest.getFilter()
.getField()));
}
List<FilterDescriptor> filters = dataRequest.getFilter()
.getFilters();
for (FilterDescriptor filter : filters) {
filter.setParent(dataRequest.getFilter());
if (filter.getField() != null) {
filter.setColumn(columnMap.get(filter.getField()));
filter.setJavaType(javaTypeMap.get(filter.getField()));
}
List<FilterDescriptor> subFilters = filter.getFilters();
for (FilterDescriptor f : subFilters) {
f.setColumn(columnMap.get(f.getField()));
f.setJavaType(javaTypeMap.get(f.getField()));
f.setParent(filter);
}
}
}
}
}
private FormRuleDomainFactory() {
}
}
| UTF-8 | Java | 6,128 | java | FormRuleDomainFactory.java | Java | [] | null | [] | package com.glaf.form.core.util;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.glaf.core.base.DataRequest;
import com.glaf.core.base.DataRequest.FilterDescriptor;
import com.glaf.core.domain.ColumnDefinition;
import com.glaf.core.domain.TableDefinition;
import com.glaf.core.util.DBUtils;
/**
*
* 实体数据工厂类
*
*/
public class FormRuleDomainFactory {
public static final String TABLENAME = "FORM_RULE";
public static final ConcurrentMap<String, String> columnMap = new ConcurrentHashMap<String, String>();
public static final ConcurrentMap<String, String> javaTypeMap = new ConcurrentHashMap<String, String>();
static {
columnMap.put("id", "ID_");
columnMap.put("componentId", "COMPONENTID_");
columnMap.put("appId", "APPID_");
columnMap.put("pageId", "PAGEID_");
columnMap.put("deploymentId", "DEPLOYMENTID_");
columnMap.put("name", "NAME_");
columnMap.put("type", "TYPE_");
columnMap.put("value", "VALUE_");
columnMap.put("snapshot", "SNAPSHOT_");
columnMap.put("createDate", "CREATEDATE_");
columnMap.put("createBy", "CREATEBY_");
javaTypeMap.put("id", "String");
javaTypeMap.put("componentId", "Long");
javaTypeMap.put("appId", "String");
javaTypeMap.put("pageId", "String");
javaTypeMap.put("deploymentId", "String");
javaTypeMap.put("name", "String");
javaTypeMap.put("type", "String");
javaTypeMap.put("value", "String");
javaTypeMap.put("snapshot", "String");
javaTypeMap.put("createDate", "Date");
javaTypeMap.put("createBy", "String");
}
public static Map<String, String> getColumnMap() {
return columnMap;
}
public static Map<String, String> getJavaTypeMap() {
return javaTypeMap;
}
public static TableDefinition getTableDefinition() {
return getTableDefinition(TABLENAME);
}
public static TableDefinition getTableDefinition(String tableName) {
tableName = tableName.toUpperCase();
TableDefinition tableDefinition = new TableDefinition();
tableDefinition.setTableName(tableName);
tableDefinition.setName("FormRule");
ColumnDefinition idColumn = new ColumnDefinition();
idColumn.setName("id");
idColumn.setColumnName("ID_");
idColumn.setJavaType("String");
idColumn.setLength(50);
tableDefinition.setIdColumn(idColumn);
ColumnDefinition componentId = new ColumnDefinition();
componentId.setName("componentId");
componentId.setColumnName("COMPONENTID_");
componentId.setJavaType("Long");
tableDefinition.addColumn(componentId);
ColumnDefinition appId = new ColumnDefinition();
appId.setName("appId");
appId.setColumnName("APPID_");
appId.setJavaType("String");
appId.setLength(50);
tableDefinition.addColumn(appId);
ColumnDefinition pageId = new ColumnDefinition();
pageId.setName("pageId");
pageId.setColumnName("PAGEID_");
pageId.setJavaType("String");
pageId.setLength(50);
tableDefinition.addColumn(pageId);
ColumnDefinition deploymentId = new ColumnDefinition();
deploymentId.setName("deploymentId");
deploymentId.setColumnName("DEPLOYMENTID_");
deploymentId.setJavaType("String");
deploymentId.setLength(100);
tableDefinition.addColumn(deploymentId);
ColumnDefinition name = new ColumnDefinition();
name.setName("name");
name.setColumnName("NAME_");
name.setJavaType("String");
name.setLength(100);
tableDefinition.addColumn(name);
ColumnDefinition type = new ColumnDefinition();
type.setName("type");
type.setColumnName("TYPE_");
type.setJavaType("String");
type.setLength(50);
tableDefinition.addColumn(type);
ColumnDefinition value = new ColumnDefinition();
value.setName("value");
value.setColumnName("VALUE_");
value.setJavaType("String");
value.setLength(2000);
tableDefinition.addColumn(value);
ColumnDefinition snapshot = new ColumnDefinition();
snapshot.setName("snapshot");
snapshot.setColumnName("SNAPSHOT_");
snapshot.setJavaType("String");
snapshot.setLength(2000);
tableDefinition.addColumn(snapshot);
ColumnDefinition createDate = new ColumnDefinition();
createDate.setName("createDate");
createDate.setColumnName("CREATEDATE_");
createDate.setJavaType("Date");
tableDefinition.addColumn(createDate);
ColumnDefinition createBy = new ColumnDefinition();
createBy.setName("createBy");
createBy.setColumnName("CREATEBY_");
createBy.setJavaType("String");
createBy.setLength(50);
tableDefinition.addColumn(createBy);
return tableDefinition;
}
public static TableDefinition createTable() {
TableDefinition tableDefinition = getTableDefinition(TABLENAME);
if (!DBUtils.tableExists(TABLENAME)) {
DBUtils.createTable(tableDefinition);
} else {
DBUtils.alterTable(tableDefinition);
}
return tableDefinition;
}
public static TableDefinition createTable(String tableName) {
TableDefinition tableDefinition = getTableDefinition(tableName);
if (!DBUtils.tableExists(tableName)) {
DBUtils.createTable(tableDefinition);
} else {
DBUtils.alterTable(tableDefinition);
}
return tableDefinition;
}
public static void processDataRequest(DataRequest dataRequest) {
if (dataRequest != null) {
if (dataRequest.getFilter() != null) {
if (dataRequest.getFilter().getField() != null) {
dataRequest.getFilter().setColumn(
columnMap.get(dataRequest.getFilter().getField()));
dataRequest.getFilter()
.setJavaType(
javaTypeMap.get(dataRequest.getFilter()
.getField()));
}
List<FilterDescriptor> filters = dataRequest.getFilter()
.getFilters();
for (FilterDescriptor filter : filters) {
filter.setParent(dataRequest.getFilter());
if (filter.getField() != null) {
filter.setColumn(columnMap.get(filter.getField()));
filter.setJavaType(javaTypeMap.get(filter.getField()));
}
List<FilterDescriptor> subFilters = filter.getFilters();
for (FilterDescriptor f : subFilters) {
f.setColumn(columnMap.get(f.getField()));
f.setJavaType(javaTypeMap.get(f.getField()));
f.setParent(filter);
}
}
}
}
}
private FormRuleDomainFactory() {
}
}
| 6,128 | 0.728001 | 0.724076 | 203 | 29.118227 | 20.560995 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.625616 | false | false | 4 |
5f37a839a14aa63762a9fbdfcd82de565326cad5 | 12,713,103,237,394 | 6cad0166f18be3d88024db93c74909db3d985df8 | /core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedReactiveResultSet.java | 07712f457fb378f7ebcabd05e1ba2d9df85aae7d | [
"Apache-2.0"
] | permissive | datastax/java-driver | https://github.com/datastax/java-driver | 7589a4cc8c3d51948aea68a196134ff860dc3a40 | d990f92ba01c3ecaaa3f31a0f1fb327f77a96617 | refs/heads/4.x | 2023-08-31T13:33:31.065000 | 2023-08-22T22:27:53 | 2023-08-22T22:27:53 | 6,765,281 | 1,065 | 763 | Apache-2.0 | false | 2023-09-12T01:40:18 | 2012-11-19T18:44:41 | 2023-09-01T02:20:53 | 2023-09-12T01:40:18 | 36,911 | 1,306 | 857 | 25 | Java | false | false | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.dse.driver.internal.core.cql.reactive;
import com.datastax.dse.driver.api.core.cql.continuous.reactive.ContinuousReactiveResultSet;
import com.datastax.dse.driver.api.core.cql.reactive.ReactiveResultSet;
import com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow;
import com.datastax.dse.driver.internal.core.cql.continuous.reactive.ContinuousCqlRequestReactiveProcessor;
import com.datastax.oss.driver.api.core.cql.ColumnDefinitions;
import com.datastax.oss.driver.api.core.cql.ExecutionInfo;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.reactivestreams.Publisher;
/**
* A {@link ReactiveResultSet} that immediately signals the error passed at instantiation to all its
* subscribers.
*
* @see CqlRequestReactiveProcessor#newFailure(java.lang.RuntimeException)
* @see ContinuousCqlRequestReactiveProcessor#newFailure(java.lang.RuntimeException)
*/
public class FailedReactiveResultSet extends FailedPublisher<ReactiveRow>
implements ReactiveResultSet, ContinuousReactiveResultSet {
public FailedReactiveResultSet(Throwable error) {
super(error);
}
@NonNull
@Override
public Publisher<? extends ColumnDefinitions> getColumnDefinitions() {
return new FailedPublisher<>(error);
}
@NonNull
@Override
public Publisher<? extends ExecutionInfo> getExecutionInfos() {
return new FailedPublisher<>(error);
}
@NonNull
@Override
public Publisher<Boolean> wasApplied() {
return new FailedPublisher<>(error);
}
}
| UTF-8 | Java | 2,090 | java | FailedReactiveResultSet.java | Java | [
{
"context": "/*\n * Copyright DataStax, Inc.\n *\n * Licensed under the Apache License",
"end": 20,
"score": 0.9458693861961365,
"start": 16,
"tag": "NAME",
"value": "Data"
},
{
"context": "/*\n * Copyright DataStax, Inc.\n *\n * Licensed under the Apache License, Ve",
"end": 24,
"score": 0.7021476030349731,
"start": 22,
"tag": "NAME",
"value": "ax"
}
] | null | [] | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.dse.driver.internal.core.cql.reactive;
import com.datastax.dse.driver.api.core.cql.continuous.reactive.ContinuousReactiveResultSet;
import com.datastax.dse.driver.api.core.cql.reactive.ReactiveResultSet;
import com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow;
import com.datastax.dse.driver.internal.core.cql.continuous.reactive.ContinuousCqlRequestReactiveProcessor;
import com.datastax.oss.driver.api.core.cql.ColumnDefinitions;
import com.datastax.oss.driver.api.core.cql.ExecutionInfo;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.reactivestreams.Publisher;
/**
* A {@link ReactiveResultSet} that immediately signals the error passed at instantiation to all its
* subscribers.
*
* @see CqlRequestReactiveProcessor#newFailure(java.lang.RuntimeException)
* @see ContinuousCqlRequestReactiveProcessor#newFailure(java.lang.RuntimeException)
*/
public class FailedReactiveResultSet extends FailedPublisher<ReactiveRow>
implements ReactiveResultSet, ContinuousReactiveResultSet {
public FailedReactiveResultSet(Throwable error) {
super(error);
}
@NonNull
@Override
public Publisher<? extends ColumnDefinitions> getColumnDefinitions() {
return new FailedPublisher<>(error);
}
@NonNull
@Override
public Publisher<? extends ExecutionInfo> getExecutionInfos() {
return new FailedPublisher<>(error);
}
@NonNull
@Override
public Publisher<Boolean> wasApplied() {
return new FailedPublisher<>(error);
}
}
| 2,090 | 0.78134 | 0.779426 | 58 | 35.034481 | 31.737591 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344828 | false | false | 4 |
1eca643dc8df0e0184911e7ae3397f583c8e7f2f | 30,382,598,679,339 | 1e19950a101f1f1d913c47d8f9e2a2ddcb508e09 | /app/src/main/java/com/udacity/bakeit/listeners/IRecipeStepItemClickListener.java | e2d2f2985856f867e645f936dd08c59dd68e7606 | [] | no_license | vijimscse/BakeIt | https://github.com/vijimscse/BakeIt | 4d697288a98cd22384f47c676aad59c67580573f | d06f53ea261240829e7722a7c6cbe5d1ea738a7f | refs/heads/master | 2021-01-20T05:40:47.957000 | 2017-09-16T17:18:56 | 2017-09-16T17:18:56 | 101,462,214 | 0 | 0 | null | false | 2017-08-30T08:46:53 | 2017-08-26T04:23:53 | 2017-08-26T04:24:26 | 2017-08-30T08:46:53 | 179 | 0 | 0 | 0 | Java | null | null | package com.udacity.bakeit.listeners;
/**
* Created by VijayaLakshmi.IN on 8/27/2017.
*/
public interface IRecipeStepItemClickListener {
void onStepClick(int position);
}
| UTF-8 | Java | 179 | java | IRecipeStepItemClickListener.java | Java | [
{
"context": "e com.udacity.bakeit.listeners;\n\n/**\n * Created by VijayaLakshmi.IN on 8/27/2017.\n */\n\npublic interface IRecipeStepIt",
"end": 73,
"score": 0.9996712803840637,
"start": 57,
"tag": "NAME",
"value": "VijayaLakshmi.IN"
}
] | null | [] | package com.udacity.bakeit.listeners;
/**
* Created by VijayaLakshmi.IN on 8/27/2017.
*/
public interface IRecipeStepItemClickListener {
void onStepClick(int position);
}
| 179 | 0.748603 | 0.709497 | 9 | 18.888889 | 19.851921 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 4 |
a90bfa82c6ee7684e57d217f4a0ee0f1d90383d1 | 34,505,767,274,899 | 7c76fd7f4719da7cc91694390f055eb1f2e0b2b0 | /app/src/main/java/com/alim/relhan/Adapter/NewsAdapter.java | 9f79bd9a40e21f7d368c73680747cbaf62c64a24 | [] | no_license | mark1Ultra/RelHan | https://github.com/mark1Ultra/RelHan | 5a6956c996a719f6c77ffe785f54fd6624e88a73 | 761497d22ccbc76f2518919228e2e1d78ce350b9 | refs/heads/master | 2023-07-24T12:25:00.237000 | 2020-11-26T18:50:13 | 2020-11-26T18:50:13 | 316,311,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alim.relhan.Adapter;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.alim.relhan.Activitys.MainActivity;
import com.alim.relhan.MyObject.News;
import com.alim.relhan.MyObject.Towns;
import com.alim.relhan.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
FirebaseStorage firebaseStorage;
StorageReference storageReference;
StorageReference ref;
private LayoutInflater inflater;
private List<News> lnews;
private String img_link="";
private final OnItemClickListener listener;
public NewsAdapter(Context context, List<News> lnews,OnItemClickListener listener) {
this.lnews = lnews;
this.inflater = LayoutInflater.from(context);
this.listener = listener;
storageReference = firebaseStorage.getInstance().getReference();
if(MainActivity.language.equals("ru"))
{
img_link="NewsImages/";
}else{
img_link="NewsImagesKz/";
}
}
@Override
public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_news, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final NewsAdapter.ViewHolder holder, int position) {
News news = lnews.get(position);
String nstr = news.getTitle();
if(nstr.length()>37){nstr = nstr.substring(0,37)+"...";}
holder.txv_title.setText(nstr);
holder.txv_date.setText(news.getDate());
ref = storageReference.child(img_link+news.getId_img()+".jpg");
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(holder.img_news);
}
});
holder.bind(news, listener);
}
@Override
public int getItemCount() {
return lnews.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img_news;
final TextView txv_title,txv_date;
ViewHolder(View view){
super(view);
img_news= (ImageView) view.findViewById(R.id.imv_news);
txv_title = (TextView) view.findViewById(R.id.txv_title);
txv_date = (TextView) view.findViewById(R.id.txv_date);
}
public void bind(final News news, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
listener.onItemClick(news);
}
});
}
}
}
| UTF-8 | Java | 3,188 | java | NewsAdapter.java | Java | [] | null | [] | package com.alim.relhan.Adapter;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.alim.relhan.Activitys.MainActivity;
import com.alim.relhan.MyObject.News;
import com.alim.relhan.MyObject.Towns;
import com.alim.relhan.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
FirebaseStorage firebaseStorage;
StorageReference storageReference;
StorageReference ref;
private LayoutInflater inflater;
private List<News> lnews;
private String img_link="";
private final OnItemClickListener listener;
public NewsAdapter(Context context, List<News> lnews,OnItemClickListener listener) {
this.lnews = lnews;
this.inflater = LayoutInflater.from(context);
this.listener = listener;
storageReference = firebaseStorage.getInstance().getReference();
if(MainActivity.language.equals("ru"))
{
img_link="NewsImages/";
}else{
img_link="NewsImagesKz/";
}
}
@Override
public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_news, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final NewsAdapter.ViewHolder holder, int position) {
News news = lnews.get(position);
String nstr = news.getTitle();
if(nstr.length()>37){nstr = nstr.substring(0,37)+"...";}
holder.txv_title.setText(nstr);
holder.txv_date.setText(news.getDate());
ref = storageReference.child(img_link+news.getId_img()+".jpg");
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(holder.img_news);
}
});
holder.bind(news, listener);
}
@Override
public int getItemCount() {
return lnews.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img_news;
final TextView txv_title,txv_date;
ViewHolder(View view){
super(view);
img_news= (ImageView) view.findViewById(R.id.imv_news);
txv_title = (TextView) view.findViewById(R.id.txv_title);
txv_date = (TextView) view.findViewById(R.id.txv_date);
}
public void bind(final News news, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
listener.onItemClick(news);
}
});
}
}
}
| 3,188 | 0.661857 | 0.659975 | 117 | 26.247864 | 25.23053 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529915 | false | false | 4 |
6e1ac1b2376de05650d321858be7bf9e68c57712 | 37,065,567,765,691 | 32a8f7bc502f1652c6db7980f1a3dcbdd7cf11b0 | /app/src/main/java/sems/activityrecognition/gui/result_receivers/ActivityTransitionResultReceiver.java | a244ca3f7f5c4a6bb38052c90181cf08eed7f0dd | [] | no_license | NielsHeltner/mobile-systems-assignment-5 | https://github.com/NielsHeltner/mobile-systems-assignment-5 | d35bf4ecc40171d0808c07127908165db7af2a62 | 1f64407335e28425abc7a76f2fd45f87a492ff80 | refs/heads/master | 2020-04-02T13:49:28.413000 | 2018-10-25T15:05:14 | 2018-10-25T15:05:14 | 154,498,912 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sems.activityrecognition.gui.result_receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import com.google.android.gms.location.ActivityTransitionResult;
import sems.activityrecognition.R;
import sems.activityrecognition.gui.MainActivity;
public class ActivityTransitionResultReceiver extends BroadcastReceiver {
private MainActivity parent;
private IntentFilter filter;
public ActivityTransitionResultReceiver(MainActivity parent) {
this.parent = parent;
filter = new IntentFilter();
filter.addAction(parent.getString(R.string.RECEIVER_TRANSITION_TAG));
}
@Override
public void onReceive(Context context, Intent intent) {
ActivityTransitionResult result = intent.getParcelableExtra(parent.getString(R.string.RESULT_TAG));
long timestamp = intent.getLongExtra(parent.getString(R.string.TIME_TAG), -1);
parent.onActivityTransitionResult(result, timestamp);
}
public void registerReceiver() {
parent.registerReceiver(this, filter);
}
}
| UTF-8 | Java | 1,168 | java | ActivityTransitionResultReceiver.java | Java | [] | null | [] | package sems.activityrecognition.gui.result_receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import com.google.android.gms.location.ActivityTransitionResult;
import sems.activityrecognition.R;
import sems.activityrecognition.gui.MainActivity;
public class ActivityTransitionResultReceiver extends BroadcastReceiver {
private MainActivity parent;
private IntentFilter filter;
public ActivityTransitionResultReceiver(MainActivity parent) {
this.parent = parent;
filter = new IntentFilter();
filter.addAction(parent.getString(R.string.RECEIVER_TRANSITION_TAG));
}
@Override
public void onReceive(Context context, Intent intent) {
ActivityTransitionResult result = intent.getParcelableExtra(parent.getString(R.string.RESULT_TAG));
long timestamp = intent.getLongExtra(parent.getString(R.string.TIME_TAG), -1);
parent.onActivityTransitionResult(result, timestamp);
}
public void registerReceiver() {
parent.registerReceiver(this, filter);
}
}
| 1,168 | 0.764555 | 0.763699 | 36 | 31.444445 | 28.81497 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 4 |
686702e64c7f121a32ed125abb0c7879837fe5ad | 10,196,252,430,085 | 69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e | /methods/Method_1019124.java | c06a555c4337659c1405ea1d2a1e03c4bcfec9f1 | [] | no_license | P79N6A/icse_20_user_study | https://github.com/P79N6A/icse_20_user_study | 5b9c42c6384502fdc9588430899f257761f1f506 | 8a3676bc96059ea2c4f6d209016f5088a5628f3c | refs/heads/master | 2020-06-24T08:25:22.606000 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | private void prepare(MarkdownEditText MarkdownEditText,MarkdownEditText.EditTextWatcher editTextWatcher){
mEditControllerList=new ArrayList<>();
mEditControllerList.add(new BlockQuotesLive());
mEditControllerList.add(new StyleLive());
mEditControllerList.add(new CenterAlignLive());
mEditControllerList.add(new HeaderLive());
mEditControllerList.add(new HorizontalRulesLive(MarkdownEditText));
mEditControllerList.add(new CodeLive());
mEditControllerList.add(new StrikeThroughLive());
mEditControllerList.add(new ListLive(MarkdownEditText,editTextWatcher));
mEditControllerList.add(new CodeBlockLive());
}
| UTF-8 | Java | 626 | java | Method_1019124.java | Java | [] | null | [] | private void prepare(MarkdownEditText MarkdownEditText,MarkdownEditText.EditTextWatcher editTextWatcher){
mEditControllerList=new ArrayList<>();
mEditControllerList.add(new BlockQuotesLive());
mEditControllerList.add(new StyleLive());
mEditControllerList.add(new CenterAlignLive());
mEditControllerList.add(new HeaderLive());
mEditControllerList.add(new HorizontalRulesLive(MarkdownEditText));
mEditControllerList.add(new CodeLive());
mEditControllerList.add(new StrikeThroughLive());
mEditControllerList.add(new ListLive(MarkdownEditText,editTextWatcher));
mEditControllerList.add(new CodeBlockLive());
}
| 626 | 0.819489 | 0.819489 | 12 | 51.166668 | 23.465696 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
b9a7da0cff20d43fcb60be3412b8d529348b9016 | 34,557,306,888,280 | a25dc12428680812b36774a29c659cfd50ae0b59 | /src/main/java/cn/com/servlet/adminservlet/AdminServlet.java | dcbf0efa52bb04209733c34f1746968dbe90d8fd | [] | no_license | Ryan0820/YPadWeb | https://github.com/Ryan0820/YPadWeb | 04f75db74a2647f4cfef8eb2725dcab9cba965d9 | 7f4828e387815892ee8cac7431c8483a2ccd1478 | refs/heads/master | 2020-04-26T16:15:05.278000 | 2019-03-04T04:20:29 | 2019-03-04T04:20:29 | 173,672,452 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.com.servlet.adminservlet;
import cn.com.domain.ADM;
import cn.com.service.admservice.ADMService;
import cn.com.service.admservice.impl.ADMServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1拿到表单提交的数据
request.setCharacterEncoding("utf-8");
String adname = request.getParameter("adname");
String adpass = request.getParameter("adpass");
//1.1获取用户提交的验证码
String verifycode = request.getParameter("verifycode");
//1.2验证码校验
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
request.removeAttribute("CHECKCODE_SERVER");
if (!checkcode_server.equalsIgnoreCase(verifycode)){
//验证码不正确
//提示信息
request.setAttribute("login_msg","验证码错误!");
//跳转登录页面
request.getRequestDispatcher(request.getContextPath() + "adpage/Adlogin.jsp").forward(request,response);
return;
}
//2管理员和密码与数据库做比较v
try {
if (adname != null || adpass != null) {
ADMService service = new ADMServiceImpl();
ADM adm = service.getAdmin(adname, adpass);
String adn = adm.getAdname();
String adp = adm.getAdpass();
if (adname.equals(adn) && adpass.equals(adp)) {
request.setAttribute("admin", adm);
request.getRequestDispatcher(request.getContextPath() + "adpage/websiteIndex.jsp").forward(request, response);
}
} else {
//不为空有错误转发
response.sendRedirect(request.getContextPath() + "adpage/Adlogin.jsp");
}
} catch (Exception e) {
//报错转发继续重新登录
response.sendRedirect(request.getContextPath() + "adpage/Adlogin.jsp");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
| UTF-8 | Java | 2,679 | java | AdminServlet.java | Java | [] | null | [] | package cn.com.servlet.adminservlet;
import cn.com.domain.ADM;
import cn.com.service.admservice.ADMService;
import cn.com.service.admservice.impl.ADMServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1拿到表单提交的数据
request.setCharacterEncoding("utf-8");
String adname = request.getParameter("adname");
String adpass = request.getParameter("adpass");
//1.1获取用户提交的验证码
String verifycode = request.getParameter("verifycode");
//1.2验证码校验
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
request.removeAttribute("CHECKCODE_SERVER");
if (!checkcode_server.equalsIgnoreCase(verifycode)){
//验证码不正确
//提示信息
request.setAttribute("login_msg","验证码错误!");
//跳转登录页面
request.getRequestDispatcher(request.getContextPath() + "adpage/Adlogin.jsp").forward(request,response);
return;
}
//2管理员和密码与数据库做比较v
try {
if (adname != null || adpass != null) {
ADMService service = new ADMServiceImpl();
ADM adm = service.getAdmin(adname, adpass);
String adn = adm.getAdname();
String adp = adm.getAdpass();
if (adname.equals(adn) && adpass.equals(adp)) {
request.setAttribute("admin", adm);
request.getRequestDispatcher(request.getContextPath() + "adpage/websiteIndex.jsp").forward(request, response);
}
} else {
//不为空有错误转发
response.sendRedirect(request.getContextPath() + "adpage/Adlogin.jsp");
}
} catch (Exception e) {
//报错转发继续重新登录
response.sendRedirect(request.getContextPath() + "adpage/Adlogin.jsp");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
| 2,679 | 0.645149 | 0.642376 | 65 | 37.846153 | 30.85162 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.646154 | false | false | 4 |
48fd9e4165217d950ef675f05396cb34bfc9db7b | 28,784,870,886,790 | 80d68d89129f754d060a05d4b80c0197c9fb1720 | /src/main/java/ch/heigvd/SwaggerConfig.java | ce7e1715beba2b3e97dad34eab4d986e8ef47340 | [] | no_license | limayankee/HEIG-AMT-Gamification | https://github.com/limayankee/HEIG-AMT-Gamification | ca4b1369c858f59840347bb9211c59a2b176865a | a1440b25082b3594bb1aa00589c58c0351fce49a | refs/heads/master | 2020-07-27T02:19:54.664000 | 2017-01-25T21:12:20 | 2017-01-25T21:12:20 | 73,705,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch.heigvd;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("GameCat")
.description("The cat's choice for a gamification platform")
.license("All the money in your pocket")
.version("0.0.1")
.contact(new Contact("", "", ""))
.build();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("ch.heigvd.api"))
.paths(PathSelectors.ant("/**"))
.build()
.apiInfo(apiInfo())
.useDefaultResponseMessages(false);
}
} | UTF-8 | Java | 1,280 | java | SwaggerConfig.java | Java | [] | null | [] | package ch.heigvd;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("GameCat")
.description("The cat's choice for a gamification platform")
.license("All the money in your pocket")
.version("0.0.1")
.contact(new Contact("", "", ""))
.build();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("ch.heigvd.api"))
.paths(PathSelectors.ant("/**"))
.build()
.apiInfo(apiInfo())
.useDefaultResponseMessages(false);
}
} | 1,280 | 0.657812 | 0.654688 | 38 | 32.710526 | 23.107197 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 4 |
eac997b6bb774e4f5d1575f679cac02bca53f994 | 20,486,994,052,343 | 2067fa08fc3649e9626d6b4119b92782dabaa49b | /src/main/java/com/example/spring/learn/demo/entity/Tiger.java | aef2946b5e901f9116e5b0fa311ea61ed02dfb77 | [] | no_license | 502636321/spring-learn-demo | https://github.com/502636321/spring-learn-demo | 2cb323096d2f32bd3bb10895f7fb442dca479df1 | 4a797335e2a751837fdcf8f5ccbb7907c1f25a46 | refs/heads/master | 2022-11-06T19:28:23.039000 | 2020-06-24T10:06:09 | 2020-06-24T10:06:09 | 274,372,160 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.spring.learn.demo.entity;
import org.springframework.stereotype.Component;
/**
* 老虎
*/
@Component
public class Tiger implements Animal {
private String name;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 351 | java | Tiger.java | Java | [] | null | [] | package com.example.spring.learn.demo.entity;
import org.springframework.stereotype.Component;
/**
* 老虎
*/
@Component
public class Tiger implements Animal {
private String name;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
| 351 | 0.648415 | 0.648415 | 22 | 14.772727 | 15.652278 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 4 |
b70e047f2d5fe5bacbdd5259a4750b34f59ec594 | 2,327,872,339,743 | 8a590cac69b915ef134552d1d7d0c1d7288ede6a | /muti_thread_and_high_concurrency/src/main/java/src/threadcoreknowledge/uncaughtexception/MyUncatchExceptionHandler.java | 2f8ab31671c2522820b8e2242f9281627cb818c9 | [] | no_license | yaopeng-coder/muti_thread_AND_hign_concurrency | https://github.com/yaopeng-coder/muti_thread_AND_hign_concurrency | e70899124de7a02e08e793ae2db729cd42458272 | d1087627bcc90f7e8fb6060e1d7b8467fc74bc84 | refs/heads/master | 2020-08-09T23:11:34.384000 | 2019-12-02T03:31:27 | 2019-12-02T03:31:27 | 214,197,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src.threadcoreknowledge.uncaughtexception;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @program: muti_thread_AND_hign_concurrency
* @author: yaopeng
* @create: 2019-10-23 08:20
**/
public class MyUncatchExceptionHandler implements Thread.UncaughtExceptionHandler {
private String name;
public MyUncatchExceptionHandler(String name) {
this.name = name;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING,"线程"+t.getName(),e);
System.out.println("捕获器"+name+"捕获了线程"+t.getName()+e);
}
}
| UTF-8 | Java | 688 | java | MyUncatchExceptionHandler.java | Java | [
{
"context": "gram: muti_thread_AND_hign_concurrency\n * @author: yaopeng\n * @create: 2019-10-23 08:20\n **/\npublic class My",
"end": 187,
"score": 0.9991250038146973,
"start": 180,
"tag": "USERNAME",
"value": "yaopeng"
}
] | null | [] | package src.threadcoreknowledge.uncaughtexception;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @program: muti_thread_AND_hign_concurrency
* @author: yaopeng
* @create: 2019-10-23 08:20
**/
public class MyUncatchExceptionHandler implements Thread.UncaughtExceptionHandler {
private String name;
public MyUncatchExceptionHandler(String name) {
this.name = name;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING,"线程"+t.getName(),e);
System.out.println("捕获器"+name+"捕获了线程"+t.getName()+e);
}
}
| 688 | 0.700599 | 0.682635 | 25 | 25.719999 | 24.208296 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 4 |
5d262fc14c51c3b8034da0fd27c29f05d6bff675 | 21,122,649,220,777 | 86e8c3a776882b98676100ae4007e5dfed401320 | /Barmaktar/src/com/barmaktar/trash/CloudEndpointUtils.java | ec09e08d3be1ae39d551bdf325b9d7bbb5439e6f | [] | no_license | ssymbol/barmaktar | https://github.com/ssymbol/barmaktar | d19b5f42ce2f029631cbbee806bc2cac2fe6ab64 | 18b2fb365ad0688b187ed481bd4aa2c7ad5bbf29 | refs/heads/master | 2016-07-30T05:37:37.022000 | 2014-05-13T18:36:46 | 2014-05-13T18:36:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.barmaktar.trash;
import com.barmaktar.utils.Const;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import android.app.Activity;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
public class CloudEndpointUtils {
/*
* The root URL of where your DevAppServer is running when it's being
* accessed via the Android emulator (if you're running the DevAppServer
* locally). In this case, you're running behind Android's virtual router.
* See
* http://developer.android.com/tools/devices/emulator.html#networkaddresses
* for more information.
*/
/**
* Updates the Google client builder to connect the appropriate server based
* on whether LOCAL_ANDROID_RUN is true or false.
*
* @param builder
* Google client builder
* @return same Google client builder
*/
public static <B extends AbstractGoogleClient.Builder> B updateBuilder(
B builder) {
if (Const.LOCAL_CONNECT) {
builder.setRootUrl(Const.LOCAL_APP_ENGINE_SERVER_URL_FOR_ANDROID
+ "/_ah/api/");
}
// only enable GZip when connecting to remote server
final boolean enableGZip = builder.getRootUrl().startsWith("https:");
builder.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
public void initialize(AbstractGoogleClientRequest<?> request)
throws IOException {
if (!enableGZip) {
request.setDisableGZipContent(true);
}
}
});
return builder;
}
public static String getServerUrl() {
if (Const.LOCAL_CONNECT) {
return Const.LOCAL_APP_ENGINE_SERVER_URL_FOR_ANDROID;
}
return Const.SERVER_DOMAIN;
}
public static String getImageServiceUrl() {
return getServerUrl() + "/image_service";
}
/**
* Logs the given message and shows an error alert dialog with it.
*
* @param activity
* activity
* @param tag
* log tag to use
* @param message
* message to log and show or {@code null} for none
*/
public static void logAndShow(Activity activity, String tag, String message) {
Log.e(tag, message);
showError(activity, message);
}
/**
* Logs the given throwable and shows an error alert dialog with its
* message.
*
* @param activity
* activity
* @param tag
* log tag to use
* @param t
* throwable to log and show
*/
public static void logAndShow(Activity activity, String tag, Throwable t) {
Log.e(tag, "Error", t);
String message = t.getMessage();
// Exceptions that occur in your Cloud Endpoint implementation classes
// are wrapped as GoogleJsonResponseExceptions
if (t instanceof GoogleJsonResponseException) {
GoogleJsonError details = ((GoogleJsonResponseException) t)
.getDetails();
if (details != null) {
message = details.getMessage();
}
}
showError(activity, message);
}
/**
* Shows an error alert dialog with the given message.
*
* @param activity
* activity
* @param message
* message to show or {@code null} for none
*/
public static void showError(final Activity activity, String message) {
final String errorMessage = message == null ? "Error" : "[Error ] "
+ message;
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show();
}
});
}
}
| UTF-8 | Java | 3,684 | java | CloudEndpointUtils.java | Java | [] | null | [] | package com.barmaktar.trash;
import com.barmaktar.utils.Const;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import android.app.Activity;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
public class CloudEndpointUtils {
/*
* The root URL of where your DevAppServer is running when it's being
* accessed via the Android emulator (if you're running the DevAppServer
* locally). In this case, you're running behind Android's virtual router.
* See
* http://developer.android.com/tools/devices/emulator.html#networkaddresses
* for more information.
*/
/**
* Updates the Google client builder to connect the appropriate server based
* on whether LOCAL_ANDROID_RUN is true or false.
*
* @param builder
* Google client builder
* @return same Google client builder
*/
public static <B extends AbstractGoogleClient.Builder> B updateBuilder(
B builder) {
if (Const.LOCAL_CONNECT) {
builder.setRootUrl(Const.LOCAL_APP_ENGINE_SERVER_URL_FOR_ANDROID
+ "/_ah/api/");
}
// only enable GZip when connecting to remote server
final boolean enableGZip = builder.getRootUrl().startsWith("https:");
builder.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
public void initialize(AbstractGoogleClientRequest<?> request)
throws IOException {
if (!enableGZip) {
request.setDisableGZipContent(true);
}
}
});
return builder;
}
public static String getServerUrl() {
if (Const.LOCAL_CONNECT) {
return Const.LOCAL_APP_ENGINE_SERVER_URL_FOR_ANDROID;
}
return Const.SERVER_DOMAIN;
}
public static String getImageServiceUrl() {
return getServerUrl() + "/image_service";
}
/**
* Logs the given message and shows an error alert dialog with it.
*
* @param activity
* activity
* @param tag
* log tag to use
* @param message
* message to log and show or {@code null} for none
*/
public static void logAndShow(Activity activity, String tag, String message) {
Log.e(tag, message);
showError(activity, message);
}
/**
* Logs the given throwable and shows an error alert dialog with its
* message.
*
* @param activity
* activity
* @param tag
* log tag to use
* @param t
* throwable to log and show
*/
public static void logAndShow(Activity activity, String tag, Throwable t) {
Log.e(tag, "Error", t);
String message = t.getMessage();
// Exceptions that occur in your Cloud Endpoint implementation classes
// are wrapped as GoogleJsonResponseExceptions
if (t instanceof GoogleJsonResponseException) {
GoogleJsonError details = ((GoogleJsonResponseException) t)
.getDetails();
if (details != null) {
message = details.getMessage();
}
}
showError(activity, message);
}
/**
* Shows an error alert dialog with the given message.
*
* @param activity
* activity
* @param message
* message to show or {@code null} for none
*/
public static void showError(final Activity activity, String message) {
final String errorMessage = message == null ? "Error" : "[Error ] "
+ message;
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show();
}
});
}
}
| 3,684 | 0.697883 | 0.697883 | 129 | 27.55814 | 25.89032 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.744186 | false | false | 4 |
f0b2febdfef7c510fa8c60d67ee5f260edb9d174 | 24,687,472,058,927 | 7ab01dbd607a572c61e34dd3cd4ccb22bd141afb | /Week04/NumberOfIslands.java | 19703b70a48a80a8fdf4c788d6200576fe604445 | [] | no_license | Luke-Lu2020/algorithm010 | https://github.com/Luke-Lu2020/algorithm010 | f1ee65806bee80a792e6911904c06b3f62067224 | 12a5788171c651c75d209deaae4808cc35d54eb7 | refs/heads/master | 2022-11-16T02:28:09.656000 | 2020-07-05T16:26:49 | 2020-07-05T16:26:49 | 270,375,162 | 0 | 0 | null | true | 2020-06-07T17:08:29 | 2020-06-07T17:08:29 | 2020-06-07T13:40:22 | 2020-06-02T04:38:10 | 4 | 0 | 0 | 0 | null | false | false | //给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
//
// 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
//
// 此外,你可以假设该网格的四条边均被水包围。
//
//
//
// 示例 1:
//
// 输入:
//[
//['1','1','1','1','0'],
//['1','1','0','1','0'],
//['1','1','0','0','0'],
//['0','0','0','0','0']
//]
//输出: 1
//
//
// 示例 2:
//
// 输入:
//[
//['1','1','0','0','0'],
//['1','1','0','0','0'],
//['0','0','1','0','0'],
//['0','0','0','1','1']
//]
//输出: 3
//解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
//
// Related Topics 深度优先搜索 广度优先搜索 并查集
package com.cute.leetcode.editor.cn;
public class NumberOfIslands {
public static void main(String[] args) {
Solution solution = new NumberOfIslands().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int num = 0;
int k = grid.length;
int h = grid[0].length;
for (int i = 0; i < k; i++) {
for (int j = 0; j < h; j++) {
if (grid[i][j] == '1') {
num++;
dfs(grid, i, j, k, h);
}
}
}
return num;
}
private void dfs(char[][] grid, int i, int j, int k, int h) {
if (i < 0 || j < 0 || i >= k || j >= h || grid[i][j] == '0' ) {
return ;
}
grid[i][j] = '0';
dfs(grid, i-1, j, k, h);
dfs(grid, i+1, j, k, h);
dfs(grid, i, j-1, k, h);
dfs(grid, i, j+1, k, h);
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | UTF-8 | Java | 1,923 | java | NumberOfIslands.java | Java | [] | null | [] | //给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
//
// 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
//
// 此外,你可以假设该网格的四条边均被水包围。
//
//
//
// 示例 1:
//
// 输入:
//[
//['1','1','1','1','0'],
//['1','1','0','1','0'],
//['1','1','0','0','0'],
//['0','0','0','0','0']
//]
//输出: 1
//
//
// 示例 2:
//
// 输入:
//[
//['1','1','0','0','0'],
//['1','1','0','0','0'],
//['0','0','1','0','0'],
//['0','0','0','1','1']
//]
//输出: 3
//解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
//
// Related Topics 深度优先搜索 广度优先搜索 并查集
package com.cute.leetcode.editor.cn;
public class NumberOfIslands {
public static void main(String[] args) {
Solution solution = new NumberOfIslands().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int num = 0;
int k = grid.length;
int h = grid[0].length;
for (int i = 0; i < k; i++) {
for (int j = 0; j < h; j++) {
if (grid[i][j] == '1') {
num++;
dfs(grid, i, j, k, h);
}
}
}
return num;
}
private void dfs(char[][] grid, int i, int j, int k, int h) {
if (i < 0 || j < 0 || i >= k || j >= h || grid[i][j] == '0' ) {
return ;
}
grid[i][j] = '0';
dfs(grid, i-1, j, k, h);
dfs(grid, i+1, j, k, h);
dfs(grid, i, j-1, k, h);
dfs(grid, i, j+1, k, h);
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 1,923 | 0.438424 | 0.400862 | 73 | 21.260275 | 18.70611 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.246575 | false | false | 4 |
ef9555107f933dd1cf25cf426c89071738270e35 | 10,977,936,465,739 | e44dc641f95d884bb4fd3a7579389e0cc91c25e3 | /taskgroup/src/main/java/com/cmos/audiotransfer/taskgroup/TaskListener.java | 473f4a21b383f4769bdf0e950ddb0041e5165f86 | [] | no_license | hejiew/audiotransfer | https://github.com/hejiew/audiotransfer | ce389cbf9e684af3319f04ef5886e617883b1fca | d3e6aa4cfa84be7ffd153ea5489d4eae0b0c3469 | refs/heads/master | 2018-10-15T21:01:34.426000 | 2018-09-10T07:05:55 | 2018-09-10T07:05:55 | 139,229,914 | 0 | 1 | null | false | 2018-08-01T08:59:32 | 2018-06-30T07:47:00 | 2018-08-01T06:27:07 | 2018-08-01T08:59:32 | 168 | 0 | 1 | 0 | Java | false | null | package com.cmos.audiotransfer.taskgroup;
import com.cmos.audiotransfer.taskgroup.filters.FilterConfigs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController public class TaskListener {
private static final Logger logger = LogManager.getLogger(TaskListener.class);
private final KafkaTemplate kafkaTemplate;
@Autowired private FilterConfigs config;
@Autowired public TaskListener(KafkaTemplate kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String addMessage() {
this.kafkaTemplate.send("task_origin", config.getMessage());
logger.info("发送一条消息到kafka");
return "success";
}
// ...
public FilterConfigs getConfig() {
return config;
}
public void setConfig(FilterConfigs config) {
this.config = config;
}
}
| UTF-8 | Java | 1,254 | java | TaskListener.java | Java | [] | null | [] | package com.cmos.audiotransfer.taskgroup;
import com.cmos.audiotransfer.taskgroup.filters.FilterConfigs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController public class TaskListener {
private static final Logger logger = LogManager.getLogger(TaskListener.class);
private final KafkaTemplate kafkaTemplate;
@Autowired private FilterConfigs config;
@Autowired public TaskListener(KafkaTemplate kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String addMessage() {
this.kafkaTemplate.send("task_origin", config.getMessage());
logger.info("发送一条消息到kafka");
return "success";
}
// ...
public FilterConfigs getConfig() {
return config;
}
public void setConfig(FilterConfigs config) {
this.config = config;
}
}
| 1,254 | 0.749194 | 0.747581 | 41 | 29.243902 | 27.60327 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487805 | false | false | 4 |
d3e514736500d6ff69997f14d9e1c368ceaa5e09 | 34,583,076,695,376 | a721307055c781ab85297cdb17d58d0e8e101a9c | /Service/src/com/laf/service/M22/BridgeM22.java | b7e3c19beafd5eda344438d982d84620388911d5 | [] | no_license | MarkeJave/laf | https://github.com/MarkeJave/laf | 4a981f026880a19a2db1e816f1f762099291cafc | 768de274ba5ffcec220fcbca6640063db4175076 | refs/heads/master | 2021-01-17T18:07:38.703000 | 2017-06-29T02:56:42 | 2017-06-29T02:56:42 | 57,199,148 | 25 | 12 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laf.service.M22;
import org.springframework.stereotype.Service;
import com.laf.service.IService;
@Service
public class BridgeM22 extends Method22_1_0 {
public IService matchVersion(String version){
IService service = super.matchVersion(version);
if(service == null){
service = this;
}
return service;
}
}
| UTF-8 | Java | 341 | java | BridgeM22.java | Java | [] | null | [] | package com.laf.service.M22;
import org.springframework.stereotype.Service;
import com.laf.service.IService;
@Service
public class BridgeM22 extends Method22_1_0 {
public IService matchVersion(String version){
IService service = super.matchVersion(version);
if(service == null){
service = this;
}
return service;
}
}
| 341 | 0.733138 | 0.709677 | 19 | 16.947369 | 18.187542 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.210526 | false | false | 4 |
b85a984576958288783d9cb8dd564b49fde5342d | 33,895,881,906,709 | e7f67c2d1e1c8ed74d7d01adb29e981c2787ebcb | /odcleanstore/core/src/main/java/cz/cuni/mff/odcleanstore/transformer/Transformer.java | 4f220637395a8d603b71774814468cc2b95c6f62 | [
"Apache-2.0"
] | permissive | ODCleanStore/ODCleanStore | https://github.com/ODCleanStore/ODCleanStore | 686d5b345b43c5d9a304b6e998b26c7ae8e70d30 | 3a68c345c5b67349447add8d61d97ae59edd8d7d | refs/heads/master | 2016-09-15T18:45:05.982000 | 2015-10-07T10:57:35 | 2015-10-07T10:57:35 | 8,683,537 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.cuni.mff.odcleanstore.transformer;
/**
* Interface of a custom transformer.
*
* The transformer can modify the given input named graph, attach a new named graph to the
* transformed graph (see {@link TransformedGraph#addAttachedGraph(String)}) or modify any of the
* already attached named graphs.
* The caller must ensure that the transformed named graphs (and the respective attached graphs) are
* not modified while the Transformer is working on it.
* A new instance of the transformer is created for each named graph to process.
*
* @author Jan Michelfeit
*/
public interface Transformer {
/**
* Transforms a graph.
* Whether the graph is a new incoming graph or an existing graph from clean database can be
* determined from context, however the transformed graph is always physically stored in the dirty database.
* @param inputGraph holder for the transformed graph.
* @param context context of the transformation
* @throws TransformerException exception
*/
void transformGraph(TransformedGraph inputGraph, TransformationContext context) throws TransformerException;
/**
* Called when the instance of the transformer is no longer needed.
* This method is suitable for releasing resources etc.
* @throws TransformerException exception
*/
void shutdown() throws TransformerException;
}
| UTF-8 | Java | 1,387 | java | Transformer.java | Java | [
{
"context": "ted for each named graph to process.\n *\n * @author Jan Michelfeit\n */\npublic interface Transformer {\n /**\n *",
"end": 581,
"score": 0.9998833537101746,
"start": 567,
"tag": "NAME",
"value": "Jan Michelfeit"
}
] | null | [] | package cz.cuni.mff.odcleanstore.transformer;
/**
* Interface of a custom transformer.
*
* The transformer can modify the given input named graph, attach a new named graph to the
* transformed graph (see {@link TransformedGraph#addAttachedGraph(String)}) or modify any of the
* already attached named graphs.
* The caller must ensure that the transformed named graphs (and the respective attached graphs) are
* not modified while the Transformer is working on it.
* A new instance of the transformer is created for each named graph to process.
*
* @author <NAME>
*/
public interface Transformer {
/**
* Transforms a graph.
* Whether the graph is a new incoming graph or an existing graph from clean database can be
* determined from context, however the transformed graph is always physically stored in the dirty database.
* @param inputGraph holder for the transformed graph.
* @param context context of the transformation
* @throws TransformerException exception
*/
void transformGraph(TransformedGraph inputGraph, TransformationContext context) throws TransformerException;
/**
* Called when the instance of the transformer is no longer needed.
* This method is suitable for releasing resources etc.
* @throws TransformerException exception
*/
void shutdown() throws TransformerException;
}
| 1,379 | 0.746936 | 0.746936 | 32 | 42.34375 | 36.143471 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 4 |
77e4b0f9df7cafd9309be3a6a8be7db59fe2be68 | 38,551,626,451,363 | 2454baff3fe16d860182de792a49ae216a0f40e3 | /HereAPI_v2Porting/src/com/example/hereapi_example/MarkerDemoActivity.java | 7873aa122fe9f79880a4bd941c9d05713f78b11c | [] | no_license | cha63506/NokiaX_Maps | https://github.com/cha63506/NokiaX_Maps | a2a8dbf0e17d8d6c91403f4a4ea76786c343b2a4 | 4d95f7cf705618e70b86d281600b65ff3aa6c3a8 | refs/heads/master | 2017-12-01T09:10:11.593000 | 2014-03-18T07:09:34 | 2014-03-18T07:09:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hereapi_example;
import java.util.List;
import java.util.Random;
import com.here.android.common.GeoCoordinate;
import com.here.android.common.Image;
import com.here.android.common.ViewObject;
import com.here.android.common.ViewObject.ViewObjectType;
import com.here.android.mapping.Map.InfoBubbleAdapter;
import com.here.android.mapping.FragmentInitListener;
import com.here.android.mapping.InitError;
import com.here.android.mapping.Map;
import com.here.android.mapping.MapAnimation;
import com.here.android.mapping.MapContainer;
import com.here.android.mapping.MapFactory;
import com.here.android.mapping.MapFragment;
import com.here.android.mapping.MapGestureListener;
import com.here.android.mapping.MapMarker;
import com.here.android.mapping.MapMarkerDragListener;
import com.here.android.mapping.MapObject;
import com.here.android.mapping.MapObjectType;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MarkerDemoActivity extends Activity
implements OnSeekBarChangeListener, MapGestureListener,MapMarkerDragListener{
private static final double BRISBANE_lat = -27.47093;
private static final double BRISBANE_lon = 153.0235;
private static final double MELBOURNE_lat = -37.81319;
private static final double MELBOURNE_lon = 144.96298;
private static final double SYDNEY_lat = -33.87365;
private static final double SYDNEY_lon = 151.20689;
private static final double ADELAIDE_lat = -34.92873;
private static final double ADELAIDE_lon = 138.59995;
private static final double PERTH_lat = -31.952854;
private static final double PERTH_lon = 115.857342;
/** Demonstrates customizing the info window and/or its contents. */
class CustomInfoWindowAdapter implements InfoBubbleAdapter {
private final RadioGroup mOptions;
// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private final View mWindow;
private final View mContents;
CustomInfoWindowAdapter() {
mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
}
private void render(MapMarker marker, View view) {
int badge;
// Use the equals() method on a Marker to check for equals. Do not use ==.
if (marker.equals(mBrisbane)) {
badge = R.drawable.badge_qld;
} else if (marker.equals(mAdelaide)) {
badge = R.drawable.badge_sa;
} else if (marker.equals(mSydney)) {
badge = R.drawable.badge_nsw;
} else if (marker.equals(mMelbourne)) {
badge = R.drawable.badge_victoria;
} else if (marker.equals(mPerth)) {
badge = R.drawable.badge_wa;
} else {
// Passing 0 to setImageResource will clear the image view.
badge = 0;
}
((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);
String title = marker.getTitle();
TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
// Spannable string allows us to edit the formatting of the text.
SpannableString titleText = new SpannableString(title);
titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
titleUi.setText(titleText);
} else {
titleUi.setText("");
}
String snippet = marker.getDescription();
TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
if (snippet != null && snippet.length() > 12) {
SpannableString snippetText = new SpannableString(snippet);
snippetText.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0, 10, 0);
snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12, snippet.length(), 0);
snippetUi.setText(snippetText);
} else {
snippetUi.setText("");
}
}
@Override
public View getInfoBubble(MapMarker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_window) {
// This means that getInfoContents will be called.
return null;
}
render(marker, mWindow);
return mWindow;
}
@Override
public View getInfoBubbleContents(MapMarker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_contents) {
// This means that the default info contents will be used.
return null;
}
render(marker, mContents);
return mContents;
}
}
Map HereMap = null;
MapContainer MapMarkers = null;
MapContainer RBMarkers = null;
private MapMarker mPerth;
private MapMarker mSydney;
private MapMarker mBrisbane;
private MapMarker mAdelaide;
private MapMarker mMelbourne;
private TextView mTopText;
private SeekBar mRotationBar;
// private CheckBox mFlatBox;
private final Random mRandom = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
mTopText = (TextView) findViewById(R.id.top_text);
mRotationBar = (SeekBar) findViewById(R.id.rotationSeekBar);
mRotationBar.setMax(360);
mRotationBar.setOnSeekBarChangeListener(this);
// mFlatBox = (CheckBox) findViewById(R.id.flat);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (HereMap == null) {
final MarkerDemoActivity that = this;
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
// initialize the Map Fragment to create a map and
// attached to the fragment
mapFragment.init(new FragmentInitListener() {
@Override
public void onFragmentInitializationCompleted(InitError error) {
if (error == InitError.NONE) {
HereMap = (Map) mapFragment.getMap();
mapFragment.getMapGesture().addMapGestureListener(that);
mapFragment.setMapMarkerDragListener(that);
//setOnInfoWindowClickListener(this);
setUpMap();
}else {
}
}
});
}
}
private void setUpMap() {
if (HereMap == null) {
return;
}
// Hide the zoom controls as the button panel will cover it.
//HereMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the contents and look of the
// info window.
// mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for their behavior.
// are set earlier already
// Pan to see all markers in view.
if(MapMarkers != null){
List<MapObject> addedMarkers = MapMarkers.getAllMapObjects();
boolean gotRect = false;
double north = 0;
double west = 0;
double south = 0;
double east = 0;
for (int i = 0; i < addedMarkers.size(); i++)
{
if(addedMarkers.get(i).getType() == MapObjectType.MARKER){
MapMarker MarkerElement = (MapMarker)addedMarkers.get(i);
if(MarkerElement != null){
if (!gotRect)
{
gotRect = true;
north = south = MarkerElement.getCoordinate().getLatitude();
west = east = MarkerElement.getCoordinate().getLongitude();
}
else
{
if (north < MarkerElement.getCoordinate().getLatitude()) north = MarkerElement.getCoordinate().getLatitude();
if (west > MarkerElement.getCoordinate().getLongitude()) west = MarkerElement.getCoordinate().getLongitude();
if (south > MarkerElement.getCoordinate().getLatitude()) south = MarkerElement.getCoordinate().getLatitude();
if (east < MarkerElement.getCoordinate().getLongitude()) east = MarkerElement.getCoordinate().getLongitude();
}
}
}
}
if(gotRect){
GeoCoordinate topLeft = MapFactory.createGeoCoordinate(north, west);
GeoCoordinate bottomRight= MapFactory.createGeoCoordinate(south, east);
HereMap.zoomTo(MapFactory.createGeoBoundingBox(topLeft, bottomRight), MapAnimation.NONE, 0);
}
}
}
private void addMarkersToMap() {
if(MapMarkers != null){
return;
}
MapMarkers = MapFactory.createMapContainer();
mBrisbane = MapFactory.createMapMarker(210.0f);
mBrisbane.setCoordinate(MapFactory.createGeoCoordinate(BRISBANE_lat, BRISBANE_lon));
mBrisbane.setTitle("Brisbane");
mBrisbane.setDescription("Population: 2,074,200");
mBrisbane.setDraggable(true);
MapMarkers.addMapObject(mBrisbane);
// Uses a custom icon with the info window popping out of the center of the icon.
mSydney = MapFactory.createMapMarker();
mSydney.setCoordinate(MapFactory.createGeoCoordinate(SYDNEY_lat, SYDNEY_lon));
Image imgSydney = MapFactory.createImage();
Bitmap bitSydney = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.arrow);
imgSydney.setBitmap(bitSydney);
mSydney.setIcon(imgSydney);
// .infoWindowAnchor(0.5f, 0.5f));
mSydney.setTitle("Sydney");
mSydney.setDescription("Population: 4,627,300");
mSydney.setDraggable(true);
MapMarkers.addMapObject(mSydney);
// Creates a draggable marker. Long press to drag.
mMelbourne = MapFactory.createMapMarker();
mMelbourne.setCoordinate(MapFactory.createGeoCoordinate(MELBOURNE_lat, MELBOURNE_lon));
mMelbourne.setTitle("Melbourne");
mMelbourne.setDescription("Population: 4,137,400");
mMelbourne.setDraggable(true);
MapMarkers.addMapObject(mMelbourne);
// A few more markers for good measure.
mPerth = MapFactory.createMapMarker();
mPerth.setCoordinate(MapFactory.createGeoCoordinate(PERTH_lat, PERTH_lon));
mPerth.setTitle("Perth");
mPerth.setDescription("Population: 1,738,800");
mPerth.setDraggable(true);
MapMarkers.addMapObject(mPerth);
mAdelaide = MapFactory.createMapMarker();
mAdelaide.setCoordinate(MapFactory.createGeoCoordinate(ADELAIDE_lat, ADELAIDE_lon));
mAdelaide.setTitle("Adelaide");
mAdelaide.setDescription("Population: 1,213,000");
mAdelaide.setDraggable(true);
MapMarkers.addMapObject(mAdelaide);
HereMap.addMapObject(MapMarkers);
RBMarkers = MapFactory.createMapContainer();
// float rotation = mRotationBar.getProgress();
// boolean flat = mFlatBox.isChecked();
int numMarkersInRainbow = 12;
for (int i = 0; i < numMarkersInRainbow; i++) {
double RBLat = -30 + 10 * Math.sin(i * Math.PI / (numMarkersInRainbow - 1));
double RBLon = 135 - 10 * Math.cos(i * Math.PI / (numMarkersInRainbow - 1));
MapMarker ReinbowMarker = MapFactory.createMapMarker((i * 360 / numMarkersInRainbow));
ReinbowMarker.setCoordinate(MapFactory.createGeoCoordinate(RBLat, RBLon));
ReinbowMarker.setTitle("Marker " + i);
RBMarkers.addMapObject(ReinbowMarker);
//.flat(flat)
//.rotation(rotation)));
}
HereMap.addMapObject(RBMarkers);
}
private boolean checkReady() {
if (HereMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/** Called when the Clear button is clicked. */
public void onClearMap(View view) {
if (!checkReady()) {
return;
}
if(RBMarkers != null){
HereMap.removeMapObject(RBMarkers);
RBMarkers = null;
}
if(MapMarkers != null){
HereMap.removeMapObject(MapMarkers);
MapMarkers = null;
}
}
/** Called when the Reset button is clicked. */
public void onResetMap(View view) {
if (!checkReady()) {
return;
}
// Clear the map because we don't want duplicates of the markers.
if(RBMarkers != null){
HereMap.removeMapObject(RBMarkers);
RBMarkers = null;
}
if(MapMarkers != null){
HereMap.removeMapObject(MapMarkers);
MapMarkers = null;
}
setUpMap();
}
/** Called when the Reset button is clicked. */
public void onToggleFlat(View view) {
if (!checkReady()) {
return;
}
/* boolean flat = mFlatBox.isChecked();
for (Marker marker : mMarkerRainbow) {
marker.setFlat(flat);
}*/
}
public MapMarker FindObject(MapMarker marker){
MapMarker ret = null;
List<MapObject> addedMarkers = MapMarkers.getAllMapObjects();
for (int i = 0; i < addedMarkers.size(); i++)
{
if (addedMarkers.get(i).hashCode() == marker.hashCode()) {
ret = (MapMarker) addedMarkers.get(i);
}
}
if(ret == null){
List<MapObject> ReinBMarkers = RBMarkers.getAllMapObjects();
for (int i = 0; i < ReinBMarkers.size(); i++)
{
if (ReinBMarkers.get(i).hashCode() == marker.hashCode()) {
ret = (MapMarker) ReinBMarkers.get(i);
}
}
}
return ret;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!checkReady()) {
return;
}
/* float rotation = seekBar.getProgress();
for (Marker marker : mMarkerRainbow) {
marker.setRotation(rotation);
}*/
}
@Override
public boolean onTapEvent(PointF p) {
if(HereMap != null){
List<ViewObject> objs = HereMap.getSelectedObjects(p);
for (ViewObject viewObject : objs) {
if (viewObject.getBaseType() == ViewObjectType.USER_OBJECT) {
MapObject mapObject = (MapObject) viewObject;
if (mapObject.getType() == MapObjectType.MARKER) {
MapMarker marker = (MapMarker) mapObject;
if (mPerth.hashCode() == marker.hashCode()) {
// This causes the marker at Perth to bounce into position when it is clicked.
final android.os.Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1500;
final BounceInterpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(1 - interpolator
.getInterpolation((float) elapsed / duration), 0);
PointF NewAnc = new PointF(0.5f,(1.0f + 2 * t));
mPerth.setAnchorPoint(NewAnc);
if (t > 0.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
} else if (mAdelaide.hashCode() == marker.hashCode()) {
// This causes the marker at Adelaide to change color and alpha.
if(MapMarkers != null){
MapMarkers.removeMapObject(mAdelaide);
mAdelaide.hideInfoBubble();
mAdelaide = null;
mAdelaide = MapFactory.createMapMarker(mRandom.nextFloat() * 360);
mAdelaide.setTransparency(mRandom.nextFloat());
mAdelaide.setCoordinate(MapFactory.createGeoCoordinate(ADELAIDE_lat, ADELAIDE_lon));
mAdelaide.setTitle("Adelaide");
mAdelaide.setDescription("Population: 1,213,000");
mAdelaide.setDraggable(true);
MapMarkers.addMapObject(mAdelaide);
}
}
}
}
}
}
return false;
}
@Override
public boolean onMapObjectsSelected(List<ViewObject> objects) {
// TODO Auto-generated method stub
for (ViewObject viewObject : objects) {
if (viewObject.getBaseType() == ViewObjectType.USER_OBJECT) {
MapObject mapObject = (MapObject) viewObject;
if (mapObject.getType() == MapObjectType.MARKER) {
MapMarker marker = FindObject((MapMarker) mapObject);
if(marker != null){
marker.showInfoBubble();
}
return false;
}
}
}
return false;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {// Do nothing.
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {// Do nothing.
}
@Override
public boolean onDoubleTapEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onLongPressEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPressRelease() {
// TODO Auto-generated method stub
}
@Override
public void onMultiFingerManipulationEnd() {
// TODO Auto-generated method stub
}
@Override
public void onMultiFingerManipulationStart() {
// TODO Auto-generated method stub
}
@Override
public void onPanEnd() {
// TODO Auto-generated method stub
}
@Override
public void onPanStart() {
// TODO Auto-generated method stub
}
@Override
public void onPinchLocked() {
// TODO Auto-generated method stub
}
@Override
public boolean onPinchZoomEvent(float scaleFactor, PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onRotateEvent(float rotateAngle) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onRotateLocked() {
// TODO Auto-generated method stub
}
@Override
public boolean onTiltEvent(float angle) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onTwoFingerTapEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onMarkerDrag(MapMarker marker) {
mTopText.setText("onMarkerDrag. Current Position: " + marker.getCoordinate());
}
@Override
public void onMarkerDragEnd(MapMarker marker) {
mTopText.setText("onMarkerDragEnd");
}
@Override
public void onMarkerDragStart(MapMarker marker) {
mTopText.setText("onMarkerDragStart");
}
}
| UTF-8 | Java | 20,496 | java | MarkerDemoActivity.java | Java | [] | null | [] | package com.example.hereapi_example;
import java.util.List;
import java.util.Random;
import com.here.android.common.GeoCoordinate;
import com.here.android.common.Image;
import com.here.android.common.ViewObject;
import com.here.android.common.ViewObject.ViewObjectType;
import com.here.android.mapping.Map.InfoBubbleAdapter;
import com.here.android.mapping.FragmentInitListener;
import com.here.android.mapping.InitError;
import com.here.android.mapping.Map;
import com.here.android.mapping.MapAnimation;
import com.here.android.mapping.MapContainer;
import com.here.android.mapping.MapFactory;
import com.here.android.mapping.MapFragment;
import com.here.android.mapping.MapGestureListener;
import com.here.android.mapping.MapMarker;
import com.here.android.mapping.MapMarkerDragListener;
import com.here.android.mapping.MapObject;
import com.here.android.mapping.MapObjectType;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MarkerDemoActivity extends Activity
implements OnSeekBarChangeListener, MapGestureListener,MapMarkerDragListener{
private static final double BRISBANE_lat = -27.47093;
private static final double BRISBANE_lon = 153.0235;
private static final double MELBOURNE_lat = -37.81319;
private static final double MELBOURNE_lon = 144.96298;
private static final double SYDNEY_lat = -33.87365;
private static final double SYDNEY_lon = 151.20689;
private static final double ADELAIDE_lat = -34.92873;
private static final double ADELAIDE_lon = 138.59995;
private static final double PERTH_lat = -31.952854;
private static final double PERTH_lon = 115.857342;
/** Demonstrates customizing the info window and/or its contents. */
class CustomInfoWindowAdapter implements InfoBubbleAdapter {
private final RadioGroup mOptions;
// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private final View mWindow;
private final View mContents;
CustomInfoWindowAdapter() {
mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
}
private void render(MapMarker marker, View view) {
int badge;
// Use the equals() method on a Marker to check for equals. Do not use ==.
if (marker.equals(mBrisbane)) {
badge = R.drawable.badge_qld;
} else if (marker.equals(mAdelaide)) {
badge = R.drawable.badge_sa;
} else if (marker.equals(mSydney)) {
badge = R.drawable.badge_nsw;
} else if (marker.equals(mMelbourne)) {
badge = R.drawable.badge_victoria;
} else if (marker.equals(mPerth)) {
badge = R.drawable.badge_wa;
} else {
// Passing 0 to setImageResource will clear the image view.
badge = 0;
}
((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);
String title = marker.getTitle();
TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
// Spannable string allows us to edit the formatting of the text.
SpannableString titleText = new SpannableString(title);
titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
titleUi.setText(titleText);
} else {
titleUi.setText("");
}
String snippet = marker.getDescription();
TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
if (snippet != null && snippet.length() > 12) {
SpannableString snippetText = new SpannableString(snippet);
snippetText.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0, 10, 0);
snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12, snippet.length(), 0);
snippetUi.setText(snippetText);
} else {
snippetUi.setText("");
}
}
@Override
public View getInfoBubble(MapMarker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_window) {
// This means that getInfoContents will be called.
return null;
}
render(marker, mWindow);
return mWindow;
}
@Override
public View getInfoBubbleContents(MapMarker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_contents) {
// This means that the default info contents will be used.
return null;
}
render(marker, mContents);
return mContents;
}
}
Map HereMap = null;
MapContainer MapMarkers = null;
MapContainer RBMarkers = null;
private MapMarker mPerth;
private MapMarker mSydney;
private MapMarker mBrisbane;
private MapMarker mAdelaide;
private MapMarker mMelbourne;
private TextView mTopText;
private SeekBar mRotationBar;
// private CheckBox mFlatBox;
private final Random mRandom = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
mTopText = (TextView) findViewById(R.id.top_text);
mRotationBar = (SeekBar) findViewById(R.id.rotationSeekBar);
mRotationBar.setMax(360);
mRotationBar.setOnSeekBarChangeListener(this);
// mFlatBox = (CheckBox) findViewById(R.id.flat);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (HereMap == null) {
final MarkerDemoActivity that = this;
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
// initialize the Map Fragment to create a map and
// attached to the fragment
mapFragment.init(new FragmentInitListener() {
@Override
public void onFragmentInitializationCompleted(InitError error) {
if (error == InitError.NONE) {
HereMap = (Map) mapFragment.getMap();
mapFragment.getMapGesture().addMapGestureListener(that);
mapFragment.setMapMarkerDragListener(that);
//setOnInfoWindowClickListener(this);
setUpMap();
}else {
}
}
});
}
}
private void setUpMap() {
if (HereMap == null) {
return;
}
// Hide the zoom controls as the button panel will cover it.
//HereMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the contents and look of the
// info window.
// mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for their behavior.
// are set earlier already
// Pan to see all markers in view.
if(MapMarkers != null){
List<MapObject> addedMarkers = MapMarkers.getAllMapObjects();
boolean gotRect = false;
double north = 0;
double west = 0;
double south = 0;
double east = 0;
for (int i = 0; i < addedMarkers.size(); i++)
{
if(addedMarkers.get(i).getType() == MapObjectType.MARKER){
MapMarker MarkerElement = (MapMarker)addedMarkers.get(i);
if(MarkerElement != null){
if (!gotRect)
{
gotRect = true;
north = south = MarkerElement.getCoordinate().getLatitude();
west = east = MarkerElement.getCoordinate().getLongitude();
}
else
{
if (north < MarkerElement.getCoordinate().getLatitude()) north = MarkerElement.getCoordinate().getLatitude();
if (west > MarkerElement.getCoordinate().getLongitude()) west = MarkerElement.getCoordinate().getLongitude();
if (south > MarkerElement.getCoordinate().getLatitude()) south = MarkerElement.getCoordinate().getLatitude();
if (east < MarkerElement.getCoordinate().getLongitude()) east = MarkerElement.getCoordinate().getLongitude();
}
}
}
}
if(gotRect){
GeoCoordinate topLeft = MapFactory.createGeoCoordinate(north, west);
GeoCoordinate bottomRight= MapFactory.createGeoCoordinate(south, east);
HereMap.zoomTo(MapFactory.createGeoBoundingBox(topLeft, bottomRight), MapAnimation.NONE, 0);
}
}
}
private void addMarkersToMap() {
if(MapMarkers != null){
return;
}
MapMarkers = MapFactory.createMapContainer();
mBrisbane = MapFactory.createMapMarker(210.0f);
mBrisbane.setCoordinate(MapFactory.createGeoCoordinate(BRISBANE_lat, BRISBANE_lon));
mBrisbane.setTitle("Brisbane");
mBrisbane.setDescription("Population: 2,074,200");
mBrisbane.setDraggable(true);
MapMarkers.addMapObject(mBrisbane);
// Uses a custom icon with the info window popping out of the center of the icon.
mSydney = MapFactory.createMapMarker();
mSydney.setCoordinate(MapFactory.createGeoCoordinate(SYDNEY_lat, SYDNEY_lon));
Image imgSydney = MapFactory.createImage();
Bitmap bitSydney = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.arrow);
imgSydney.setBitmap(bitSydney);
mSydney.setIcon(imgSydney);
// .infoWindowAnchor(0.5f, 0.5f));
mSydney.setTitle("Sydney");
mSydney.setDescription("Population: 4,627,300");
mSydney.setDraggable(true);
MapMarkers.addMapObject(mSydney);
// Creates a draggable marker. Long press to drag.
mMelbourne = MapFactory.createMapMarker();
mMelbourne.setCoordinate(MapFactory.createGeoCoordinate(MELBOURNE_lat, MELBOURNE_lon));
mMelbourne.setTitle("Melbourne");
mMelbourne.setDescription("Population: 4,137,400");
mMelbourne.setDraggable(true);
MapMarkers.addMapObject(mMelbourne);
// A few more markers for good measure.
mPerth = MapFactory.createMapMarker();
mPerth.setCoordinate(MapFactory.createGeoCoordinate(PERTH_lat, PERTH_lon));
mPerth.setTitle("Perth");
mPerth.setDescription("Population: 1,738,800");
mPerth.setDraggable(true);
MapMarkers.addMapObject(mPerth);
mAdelaide = MapFactory.createMapMarker();
mAdelaide.setCoordinate(MapFactory.createGeoCoordinate(ADELAIDE_lat, ADELAIDE_lon));
mAdelaide.setTitle("Adelaide");
mAdelaide.setDescription("Population: 1,213,000");
mAdelaide.setDraggable(true);
MapMarkers.addMapObject(mAdelaide);
HereMap.addMapObject(MapMarkers);
RBMarkers = MapFactory.createMapContainer();
// float rotation = mRotationBar.getProgress();
// boolean flat = mFlatBox.isChecked();
int numMarkersInRainbow = 12;
for (int i = 0; i < numMarkersInRainbow; i++) {
double RBLat = -30 + 10 * Math.sin(i * Math.PI / (numMarkersInRainbow - 1));
double RBLon = 135 - 10 * Math.cos(i * Math.PI / (numMarkersInRainbow - 1));
MapMarker ReinbowMarker = MapFactory.createMapMarker((i * 360 / numMarkersInRainbow));
ReinbowMarker.setCoordinate(MapFactory.createGeoCoordinate(RBLat, RBLon));
ReinbowMarker.setTitle("Marker " + i);
RBMarkers.addMapObject(ReinbowMarker);
//.flat(flat)
//.rotation(rotation)));
}
HereMap.addMapObject(RBMarkers);
}
private boolean checkReady() {
if (HereMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/** Called when the Clear button is clicked. */
public void onClearMap(View view) {
if (!checkReady()) {
return;
}
if(RBMarkers != null){
HereMap.removeMapObject(RBMarkers);
RBMarkers = null;
}
if(MapMarkers != null){
HereMap.removeMapObject(MapMarkers);
MapMarkers = null;
}
}
/** Called when the Reset button is clicked. */
public void onResetMap(View view) {
if (!checkReady()) {
return;
}
// Clear the map because we don't want duplicates of the markers.
if(RBMarkers != null){
HereMap.removeMapObject(RBMarkers);
RBMarkers = null;
}
if(MapMarkers != null){
HereMap.removeMapObject(MapMarkers);
MapMarkers = null;
}
setUpMap();
}
/** Called when the Reset button is clicked. */
public void onToggleFlat(View view) {
if (!checkReady()) {
return;
}
/* boolean flat = mFlatBox.isChecked();
for (Marker marker : mMarkerRainbow) {
marker.setFlat(flat);
}*/
}
public MapMarker FindObject(MapMarker marker){
MapMarker ret = null;
List<MapObject> addedMarkers = MapMarkers.getAllMapObjects();
for (int i = 0; i < addedMarkers.size(); i++)
{
if (addedMarkers.get(i).hashCode() == marker.hashCode()) {
ret = (MapMarker) addedMarkers.get(i);
}
}
if(ret == null){
List<MapObject> ReinBMarkers = RBMarkers.getAllMapObjects();
for (int i = 0; i < ReinBMarkers.size(); i++)
{
if (ReinBMarkers.get(i).hashCode() == marker.hashCode()) {
ret = (MapMarker) ReinBMarkers.get(i);
}
}
}
return ret;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!checkReady()) {
return;
}
/* float rotation = seekBar.getProgress();
for (Marker marker : mMarkerRainbow) {
marker.setRotation(rotation);
}*/
}
@Override
public boolean onTapEvent(PointF p) {
if(HereMap != null){
List<ViewObject> objs = HereMap.getSelectedObjects(p);
for (ViewObject viewObject : objs) {
if (viewObject.getBaseType() == ViewObjectType.USER_OBJECT) {
MapObject mapObject = (MapObject) viewObject;
if (mapObject.getType() == MapObjectType.MARKER) {
MapMarker marker = (MapMarker) mapObject;
if (mPerth.hashCode() == marker.hashCode()) {
// This causes the marker at Perth to bounce into position when it is clicked.
final android.os.Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1500;
final BounceInterpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(1 - interpolator
.getInterpolation((float) elapsed / duration), 0);
PointF NewAnc = new PointF(0.5f,(1.0f + 2 * t));
mPerth.setAnchorPoint(NewAnc);
if (t > 0.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
} else if (mAdelaide.hashCode() == marker.hashCode()) {
// This causes the marker at Adelaide to change color and alpha.
if(MapMarkers != null){
MapMarkers.removeMapObject(mAdelaide);
mAdelaide.hideInfoBubble();
mAdelaide = null;
mAdelaide = MapFactory.createMapMarker(mRandom.nextFloat() * 360);
mAdelaide.setTransparency(mRandom.nextFloat());
mAdelaide.setCoordinate(MapFactory.createGeoCoordinate(ADELAIDE_lat, ADELAIDE_lon));
mAdelaide.setTitle("Adelaide");
mAdelaide.setDescription("Population: 1,213,000");
mAdelaide.setDraggable(true);
MapMarkers.addMapObject(mAdelaide);
}
}
}
}
}
}
return false;
}
@Override
public boolean onMapObjectsSelected(List<ViewObject> objects) {
// TODO Auto-generated method stub
for (ViewObject viewObject : objects) {
if (viewObject.getBaseType() == ViewObjectType.USER_OBJECT) {
MapObject mapObject = (MapObject) viewObject;
if (mapObject.getType() == MapObjectType.MARKER) {
MapMarker marker = FindObject((MapMarker) mapObject);
if(marker != null){
marker.showInfoBubble();
}
return false;
}
}
}
return false;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {// Do nothing.
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {// Do nothing.
}
@Override
public boolean onDoubleTapEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onLongPressEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPressRelease() {
// TODO Auto-generated method stub
}
@Override
public void onMultiFingerManipulationEnd() {
// TODO Auto-generated method stub
}
@Override
public void onMultiFingerManipulationStart() {
// TODO Auto-generated method stub
}
@Override
public void onPanEnd() {
// TODO Auto-generated method stub
}
@Override
public void onPanStart() {
// TODO Auto-generated method stub
}
@Override
public void onPinchLocked() {
// TODO Auto-generated method stub
}
@Override
public boolean onPinchZoomEvent(float scaleFactor, PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onRotateEvent(float rotateAngle) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onRotateLocked() {
// TODO Auto-generated method stub
}
@Override
public boolean onTiltEvent(float angle) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onTwoFingerTapEvent(PointF p) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onMarkerDrag(MapMarker marker) {
mTopText.setText("onMarkerDrag. Current Position: " + marker.getCoordinate());
}
@Override
public void onMarkerDragEnd(MapMarker marker) {
mTopText.setText("onMarkerDragEnd");
}
@Override
public void onMarkerDragStart(MapMarker marker) {
mTopText.setText("onMarkerDragStart");
}
}
| 20,496 | 0.609534 | 0.60041 | 624 | 31.846153 | 26.709898 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.509615 | false | false | 4 |
282de3189bc7b1b78cb56a9cad0e05a23009c3c6 | 36,773,509,991,290 | 07ca6277c0a967df93bfd39e47e95f917ee07746 | /controller/datailController.java | 3076b249ccd3067d61fbec2428e967f2870057ac | [] | no_license | daheewoo/calendar_javaFx | https://github.com/daheewoo/calendar_javaFx | 9e75ad9096f39b15d2f8d3619d6b720009200864 | 75471e7a01d04dd7bb4eaf4fea8b9ad1269cf909 | refs/heads/master | 2020-11-28T07:37:19.466000 | 2020-01-18T02:45:21 | 2020-01-18T02:45:21 | 229,745,593 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package theBug.calendar.controller;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import theBug.calendar.service.CalendarService;
import theBug.calendar.service.ICalendarService;
import theBug.main.Main;
import theBug.vo.CalendarVO;
/**
* 캘린더의 특정 날짜를 클릭했을 때 세부사항을 출력해주는 클래스
* <pre>
* <b>History</b>
* 우다희 , 1.0, 2019.11.11, 최초작성
* </pre>
*
* @author 우다희
* @version 2.0 2019.11.22 소스 수정 완료
*/
public class datailController {
private List<calDateVO> detailList;
private ICalendarService service;
private int clickYear,
clickMonth,
clickDay;
@FXML
private Label lblDel;
@FXML
private Button btnUpdate;
@FXML
private Button btnComplete;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private TextField txtTitle;
@FXML
private Label lblDate;
@FXML
private TextArea txtareacont;
@FXML
void completeClick(ActionEvent event) {
CalendarVO calVo = null;
if((txtareacont.getText()).equals("내용없음")) {
String date = calendarController.clickDate;
if(date.length()==1) {
date = "0" + date;
}
//insert
String clickDate = Integer.toString(clickYear)+Integer.toString(clickMonth)+date;
calVo = new CalendarVO();
calVo.setCal_title(txtTitle.getText());
calVo.setCal_conn(txtareacont.getText());
calVo.setCal_edate(clickDate);
calVo.setCal_sdate(clickDate);
calVo.setEmp_id(Main.curEmp.getEmp_id());
service.insertCal(calVo);
}else {
//update
calVo = new CalendarVO();
calVo.setCal_title(txtTitle.getText());
calVo.setCal_conn(txtareacont.getText());
calVo.setCal_num(detailList.get(0).getCal_num());
service.updateDetail(calVo);
}
//수정되었습니다 띄우고 폼 닫기
infoMsg("수정완료", "수정되었습니다.");
Stage thisForm = (Stage) btnComplete.getScene().getWindow();
thisForm.close();
}
@FXML
void updateClick(ActionEvent event) {
txtTitle.setDisable(false);
txtareacont.setDisable(false);
btnComplete.setStyle("-fx-text-fill: #ee3737; -fx-background-color : white ;");
}
@FXML
void delClick(MouseEvent event) {
service.deleteCal(detailList.get(0).getCal_num());
infoMsg("삭제완료!", "삭제가 완료 되었습니다.");
Stage thisform = (Stage) lblDel.getScene().getWindow();
thisform.close();
}
@FXML
void initialize() throws IOException {
if(Main.curEmp.getDept_id()!=20) {
lblDel.setDisable(true);
btnUpdate.setDisable(true);
btnComplete.setDisable(true);
}
service = CalendarService.getInstance();
clickDay = Integer.parseInt(calendarController.clickDate);
clickMonth = calendarController.clickMonth+1;
clickYear = calendarController.clickYear;
lblDate.setText(clickYear + "." + clickMonth + "." + clickDay);
// //이거를 detail에서 부르기
Map<String, Integer> paramMap = new HashMap<String, Integer>();
paramMap.put("clickYear", clickYear);
paramMap.put("clickMonth", clickMonth);
paramMap.put("clickDay", clickDay);
detailList = service.getDetail(paramMap);
try {
txtTitle.setText(detailList.get(0).getClickTitle());
txtareacont.setText(detailList.get(0).getClickCont());
} catch (Exception e) {
txtTitle.setText("일정이 없습니다.");
txtareacont.setText("내용없음");
lblDate.setDisable(true);
lblDel.setStyle("-fx-opacity : 0.7;");
}
}
public void infoMsg(String head, String msg) {
Alert info = new Alert(AlertType.INFORMATION);
info.setHeaderText(head);
info.setContentText(msg);
info.showAndWait();
}
}
| UTF-8 | Java | 4,368 | java | datailController.java | Java | [
{
"context": "부사항을 출력해주는 클래스\n\t * <pre>\n\t * <b>History</b>\n\t * \t 우다희 , 1.0, 2019.11.11, 최초작성\n\t * </pre>\n\t * \n\t * @auth",
"end": 776,
"score": 0.6997034549713135,
"start": 773,
"tag": "NAME",
"value": "우다희"
},
{
"context": " 1.0, 2019.11.11, 최초작성\n\t * </pre>\n\t * \n\t * @author 우다희\n\t * @version 2.0 2019.11.22 소스 수정 완료 \n\t */\npublic",
"end": 832,
"score": 0.999832272529602,
"start": 829,
"tag": "NAME",
"value": "우다희"
}
] | null | [] | package theBug.calendar.controller;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import theBug.calendar.service.CalendarService;
import theBug.calendar.service.ICalendarService;
import theBug.main.Main;
import theBug.vo.CalendarVO;
/**
* 캘린더의 특정 날짜를 클릭했을 때 세부사항을 출력해주는 클래스
* <pre>
* <b>History</b>
* 우다희 , 1.0, 2019.11.11, 최초작성
* </pre>
*
* @author 우다희
* @version 2.0 2019.11.22 소스 수정 완료
*/
public class datailController {
private List<calDateVO> detailList;
private ICalendarService service;
private int clickYear,
clickMonth,
clickDay;
@FXML
private Label lblDel;
@FXML
private Button btnUpdate;
@FXML
private Button btnComplete;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private TextField txtTitle;
@FXML
private Label lblDate;
@FXML
private TextArea txtareacont;
@FXML
void completeClick(ActionEvent event) {
CalendarVO calVo = null;
if((txtareacont.getText()).equals("내용없음")) {
String date = calendarController.clickDate;
if(date.length()==1) {
date = "0" + date;
}
//insert
String clickDate = Integer.toString(clickYear)+Integer.toString(clickMonth)+date;
calVo = new CalendarVO();
calVo.setCal_title(txtTitle.getText());
calVo.setCal_conn(txtareacont.getText());
calVo.setCal_edate(clickDate);
calVo.setCal_sdate(clickDate);
calVo.setEmp_id(Main.curEmp.getEmp_id());
service.insertCal(calVo);
}else {
//update
calVo = new CalendarVO();
calVo.setCal_title(txtTitle.getText());
calVo.setCal_conn(txtareacont.getText());
calVo.setCal_num(detailList.get(0).getCal_num());
service.updateDetail(calVo);
}
//수정되었습니다 띄우고 폼 닫기
infoMsg("수정완료", "수정되었습니다.");
Stage thisForm = (Stage) btnComplete.getScene().getWindow();
thisForm.close();
}
@FXML
void updateClick(ActionEvent event) {
txtTitle.setDisable(false);
txtareacont.setDisable(false);
btnComplete.setStyle("-fx-text-fill: #ee3737; -fx-background-color : white ;");
}
@FXML
void delClick(MouseEvent event) {
service.deleteCal(detailList.get(0).getCal_num());
infoMsg("삭제완료!", "삭제가 완료 되었습니다.");
Stage thisform = (Stage) lblDel.getScene().getWindow();
thisform.close();
}
@FXML
void initialize() throws IOException {
if(Main.curEmp.getDept_id()!=20) {
lblDel.setDisable(true);
btnUpdate.setDisable(true);
btnComplete.setDisable(true);
}
service = CalendarService.getInstance();
clickDay = Integer.parseInt(calendarController.clickDate);
clickMonth = calendarController.clickMonth+1;
clickYear = calendarController.clickYear;
lblDate.setText(clickYear + "." + clickMonth + "." + clickDay);
// //이거를 detail에서 부르기
Map<String, Integer> paramMap = new HashMap<String, Integer>();
paramMap.put("clickYear", clickYear);
paramMap.put("clickMonth", clickMonth);
paramMap.put("clickDay", clickDay);
detailList = service.getDetail(paramMap);
try {
txtTitle.setText(detailList.get(0).getClickTitle());
txtareacont.setText(detailList.get(0).getClickCont());
} catch (Exception e) {
txtTitle.setText("일정이 없습니다.");
txtareacont.setText("내용없음");
lblDate.setDisable(true);
lblDel.setStyle("-fx-opacity : 0.7;");
}
}
public void infoMsg(String head, String msg) {
Alert info = new Alert(AlertType.INFORMATION);
info.setHeaderText(head);
info.setContentText(msg);
info.showAndWait();
}
}
| 4,368 | 0.665144 | 0.656731 | 154 | 26.012987 | 18.583258 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.590909 | false | false | 4 |
b287f3b8f7bd5ecb19b8344991d09ffee90a59b7 | 3,513,283,304,059 | 6832918e1b21bafdc9c9037cdfbcfe5838abddc4 | /jdk_8_maven/cs/rest/original/languagetool/languagetool-core/src/main/java/org/languagetool/rules/spelling/SpellingCheckRule.java | 0f4ea6e5ab119c859e9335370b915950cbf20f24 | [
"Apache-2.0",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LGPL-2.1-only"
] | permissive | EMResearch/EMB | https://github.com/EMResearch/EMB | 200c5693fb169d5f5462d9ebaf5b61c46d6f9ac9 | 092c92f7b44d6265f240bcf6b1c21b8a5cba0c7f | refs/heads/master | 2023-09-04T01:46:13.465000 | 2023-04-12T12:09:44 | 2023-04-12T12:09:44 | 94,008,854 | 25 | 14 | Apache-2.0 | false | 2023-09-13T11:23:37 | 2017-06-11T14:13:22 | 2023-08-20T08:44:30 | 2023-09-13T11:23:36 | 154,785 | 19 | 12 | 3 | Java | false | false | /* LanguageTool, a natural language style checker
* Copyright (C) 2012 Marcin Milkowski (http://www.languagetool.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.spelling;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.*;
import org.languagetool.rules.patterns.PatternToken;
import org.languagetool.rules.patterns.PatternTokenBuilder;
import org.languagetool.rules.spelling.suggestions.*;
import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule;
import org.languagetool.tokenizers.WordTokenizer;
import org.languagetool.tools.StringTools;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* An abstract rule for spellchecking rules.
*
* @author Marcin Miłkowski
*/
public abstract class SpellingCheckRule extends Rule {
/**
* The string {@code LanguageTool}.
* @since 2.3
*/
public static final String LANGUAGETOOL = "LanguageTool";
/**
* The string {@code LanguageTooler}.
* @since 4.4
*/
public static final String LANGUAGETOOLER = "LanguageTooler";
protected final Language language;
/**
* @since 4.5
* For rules from @see Language.getRelevantLanguageModelCapableRules
* Optional, allows e.g. better suggestions when set
*/
@Nullable
protected LanguageModel languageModel;
protected final CachingWordListLoader wordListLoader = new CachingWordListLoader();
private static final String SPELLING_IGNORE_FILE = "/hunspell/ignore.txt";
private static final String SPELLING_FILE = "/hunspell/spelling.txt";
private static final String CUSTOM_SPELLING_FILE = "/hunspell/spelling_custom.txt";
private static final String GLOBAL_SPELLING_FILE = "spelling_global.txt";
private static final String SPELLING_PROHIBIT_FILE = "/hunspell/prohibit.txt";
private static final String CUSTOM_SPELLING_PROHIBIT_FILE = "/hunspell/prohibit_custom.txt";
private static final String SPELLING_FILE_VARIANT = null;
private static final Comparator<String> STRING_LENGTH_COMPARATOR = Comparator.comparingInt(String::length);
private final UserConfig userConfig;
private final Set<String> wordsToBeProhibited = new THashSet<>();
private Map<String,Set<String>> wordsToBeIgnoredDictionary = new THashMap<>();
private Map<String,Set<String>> wordsToBeIgnoredDictionaryIgnoreCase = new THashMap<>();
private List<DisambiguationPatternRule> antiPatterns = new ArrayList<>();
private boolean considerIgnoreWords = true;
private boolean convertsCase = false;
protected final Set<String> wordsToBeIgnored = new HashSet<>();
protected int ignoreWordsWithLength = 0;
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig) {
this(messages, language, userConfig, Collections.emptyList());
}
/**
* @since 4.4
*/
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) {
this(messages, language, userConfig, altLanguages, null);
}
/**
* @since 4.5
*/
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, @Nullable LanguageModel languageModel) {
super(messages);
this.language = language;
this.userConfig = userConfig;
this.languageModel = languageModel;
if (userConfig != null) {
wordsToBeIgnored.addAll(userConfig.getAcceptedWords());
}
setLocQualityIssueType(ITSIssueType.Misspelling);
}
/**
* @param word misspelled word that suggestions should be generated for
* @param userCandidatesList candidates from personal dictionary
* @param candidatesList candidates from default dictionary
* @param orderer model to rank suggestions / extract features, or null
* @param match rule match to add suggestions to
*/
protected static void addSuggestionsToRuleMatch(String word, List<SuggestedReplacement> userCandidatesList, List<SuggestedReplacement> candidatesList,
@Nullable SuggestionsOrderer orderer, RuleMatch match) {
AnalyzedSentence sentence = match.getSentence();
List<String> userCandidates = userCandidatesList.stream().map(SuggestedReplacement::getReplacement).collect(Collectors.toList());
List<String> candidates = candidatesList.stream().map(SuggestedReplacement::getReplacement).collect(Collectors.toList());
int startPos = match.getFromPos();
//long startTime = System.currentTimeMillis();
if (orderer != null && orderer.isMlAvailable()) {
if (orderer instanceof SuggestionsRanker) {
// don't rank words form user dictionary, assign confidence 0.0, but add at start
// hard to ensure performance on unknown words
SuggestionsRanker ranker = (SuggestionsRanker) orderer;
List<SuggestedReplacement> defaultSuggestions = ranker.orderSuggestions(
candidates, word, sentence, startPos);
if (defaultSuggestions.isEmpty()) {
// could not rank for some reason
} else {
if (userCandidates.isEmpty()) {
match.setAutoCorrect(ranker.shouldAutoCorrect(defaultSuggestions));
match.setSuggestedReplacementObjects(defaultSuggestions);
} else {
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>();
for (String wordFromUserDict : userCandidates) {
SuggestedReplacement s = new SuggestedReplacement(wordFromUserDict);
// confidence is null
combinedSuggestions.add(s);
}
combinedSuggestions.addAll(defaultSuggestions);
match.setSuggestedReplacementObjects(combinedSuggestions);
// no auto correct when words from personal dictionaries are included
match.setAutoCorrect(false);
}
}
} else if (orderer instanceof SuggestionsOrdererFeatureExtractor) {
// disable user suggestions here
// problem: how to merge match features when ranking default and user suggestions separately?
if (userCandidates.size() != 0) {
throw new IllegalStateException(
"SuggestionsOrdererFeatureExtractor does not support suggestions from personal dictionaries at the moment.");
}
SuggestionsOrdererFeatureExtractor featureExtractor = (SuggestionsOrdererFeatureExtractor) orderer;
Pair<List<SuggestedReplacement>, SortedMap<String, Float>> suggestions =
featureExtractor.computeFeatures(candidates, word, sentence, startPos);
match.setSuggestedReplacementObjects(suggestions.getLeft());
match.setFeatures(suggestions.getRight());
} else {
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>();
combinedSuggestions.addAll(orderer.orderSuggestions(userCandidates, word, sentence, startPos));
combinedSuggestions.addAll(orderer.orderSuggestions(candidates, word, sentence, startPos));
match.setSuggestedReplacementObjects(combinedSuggestions);
}
} else { // no reranking
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>(match.getSuggestedReplacementObjects());
combinedSuggestions.addAll(userCandidatesList);
combinedSuggestions.addAll(candidatesList);
match.setSuggestedReplacementObjects(combinedSuggestions);
}
/*long timeDelta = System.currentTimeMillis() - startTime;
System.out.printf("Reordering %d suggestions took %d ms.%n", result.getSuggestedReplacements().size(), timeDelta);*/
}
protected RuleMatch createWrongSplitMatch(AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int pos, String coveredWord, String suggestion1, String suggestion2, int prevPos) {
if (ruleMatchesSoFar.size() > 0) {
RuleMatch prevMatch = ruleMatchesSoFar.get(ruleMatchesSoFar.size() - 1);
if (prevMatch.getFromPos() == prevPos) {
// we'll later create a new match that covers the previous misspelled word and the current one:
ruleMatchesSoFar.remove(ruleMatchesSoFar.size()-1);
}
}
RuleMatch ruleMatch = new RuleMatch(this, sentence, prevPos, pos + coveredWord.length(),
messages.getString("spelling"), messages.getString("desc_spelling_short"));
ruleMatch.setSuggestedReplacement((suggestion1 + " " + suggestion2).trim());
return ruleMatch;
}
@Override
public abstract String getId();
@Override
public abstract String getDescription();
@Override
public abstract RuleMatch[] match(AnalyzedSentence sentence) throws IOException;
/**
* @since 4.8
*/
@Experimental
public abstract boolean isMisspelled(String word) throws IOException;
@Override
public boolean isDictionaryBasedSpellingRule() {
return true;
}
/**
* Add the given words to the list of words to be ignored during spell check.
* You might want to use {@link #acceptPhrases(List)} instead, as only that
* can also deal with phrases.
*/
public void addIgnoreTokens(List<String> tokens) {
wordsToBeIgnored.addAll(tokens);
updateIgnoredWordDictionary();
}
//(re)create a Map<String, Set<String>> of all words to be ignored:
// The words' first char serves as key, and the Set<String> contains all Strings starting with this char
private void updateIgnoredWordDictionary() {
wordsToBeIgnoredDictionary = wordsToBeIgnored
.stream()
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toCollection(THashSet::new)));
wordsToBeIgnoredDictionaryIgnoreCase = wordsToBeIgnored
.stream()
.map(String::toLowerCase)
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toCollection(THashSet::new)));
}
/**
* Set whether the list of words to be explicitly ignored (set with {@link #addIgnoreTokens(List)}) is considered at all.
*/
public void setConsiderIgnoreWords(boolean considerIgnoreWords) {
this.considerIgnoreWords = considerIgnoreWords;
}
/**
* Get additional suggestions added before other suggestions (note the rule may choose to
* re-order the suggestions anyway). Only add suggestions here that you know are spelled correctly,
* they will not be checked again before being shown to the user.
*/
protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException {
List<String> moreSuggestions = new ArrayList<>();
if (("Languagetool".equals(word) || "languagetool".equals(word)) && suggestions.stream().noneMatch(k -> k.getReplacement().equals(LANGUAGETOOL))) {
moreSuggestions.add(LANGUAGETOOL);
}
if (("Languagetooler".equals(word) || "languagetooler".equals(word)) && suggestions.stream().noneMatch(k -> k.getReplacement().equals(LANGUAGETOOLER))) {
moreSuggestions.add(LANGUAGETOOLER);
}
return SuggestedReplacement.convert(moreSuggestions);
}
/**
* Get additional suggestions added after other suggestions (note the rule may choose to
* re-order the suggestions anyway).
*/
protected List<SuggestedReplacement> getAdditionalSuggestions(List<SuggestedReplacement> suggestions, String word) {
return Collections.emptyList();
}
/**
* Returns true iff the token at the given position should be ignored by the spell checker.
*/
protected boolean ignoreToken(AnalyzedTokenReadings[] tokens, int idx) throws IOException {
List<String> words = new ArrayList<>();
for (AnalyzedTokenReadings token : tokens) {
words.add(token.getToken());
}
return ignoreWord(words, idx);
}
/**
* Returns true iff the word should be ignored by the spell checker.
* If possible, use {@link #ignoreToken(AnalyzedTokenReadings[], int)} instead.
*/
protected boolean ignoreWord(String word) throws IOException {
if (!considerIgnoreWords) {
return false;
}
if (word.endsWith(".") && !wordsToBeIgnored.contains(word)) {
return isIgnoredNoCase(word.substring(0, word.length()-1)); // e.g. word at end of sentence
}
return isIgnoredNoCase(word);
}
private boolean isIgnoredNoCase(String word) {
return wordsToBeIgnored.contains(word) ||
(convertsCase && wordsToBeIgnored.contains(word.toLowerCase(language.getLocale()))) ||
(ignoreWordsWithLength > 0 && word.length() <= ignoreWordsWithLength);
}
/**
* Returns true iff the word at the given position should be ignored by the spell checker.
* If possible, use {@link #ignoreToken(AnalyzedTokenReadings[], int)} instead.
* @since 2.6
*/
protected boolean ignoreWord(List<String> words, int idx) throws IOException {
return ignoreWord(words.get(idx));
}
/**
* Used to determine whether the dictionary will use case conversions for
* spell checking.
* @param convertsCase if true, then conversions are used.
* @since 2.5
*/
public void setConvertsCase(boolean convertsCase) {
this.convertsCase = convertsCase;
}
protected boolean isUrl(String token) {
return WordTokenizer.isUrl(token);
}
protected boolean isEMail(String token) {
return WordTokenizer.isEMail(token);
}
protected <T> List<T> filterDupes(List<T> words) {
return words.stream().distinct().collect(Collectors.toList());
}
protected synchronized void init() throws IOException {
for (String ignoreWord : wordListLoader.loadWords(getIgnoreFileName())) {
addIgnoreWords(ignoreWord);
}
if (getSpellingFileName() != null) {
for (String ignoreWord : wordListLoader.loadWords(getSpellingFileName())) {
addIgnoreWords(ignoreWord);
}
}
for (String fileName : getAdditionalSpellingFileNames()) {
if (JLanguageTool.getDataBroker().resourceExists(fileName)) {
for (String ignoreWord : wordListLoader.loadWords(fileName)) {
addIgnoreWords(ignoreWord);
}
}
}
updateIgnoredWordDictionary();
for (String prohibitedWord : wordListLoader.loadWords(getProhibitFileName())) {
addProhibitedWords(expandLine(prohibitedWord));
}
for (String fileName : getAdditionalProhibitFileNames()) {
for (String prohibitedWord : wordListLoader.loadWords(fileName)) {
addProhibitedWords(expandLine(prohibitedWord));
}
}
}
/**
* Get the name of the ignore file, which lists words to be accepted, even
* when the spell checker would not accept them. Unlike with {@link #getSpellingFileName()}
* the words in this file will not be used for creating suggestions for misspelled words.
* @since 2.7
*/
protected String getIgnoreFileName() {
return language.getShortCode() + SPELLING_IGNORE_FILE;
}
/**
* Get the name of the spelling file, which lists words to be accepted
* and used for suggestions, even when the spell checker would not accept them.
* @since 2.9, public since 3.5
*/
public String getSpellingFileName() {
return language.getShortCode() + SPELLING_FILE;
}
/**
* Get the name of additional spelling file, which lists words to be accepted
* and used for suggestions, even when the spell checker would not accept them.
* @since 4.8
*/
public List<String> getAdditionalSpellingFileNames() {
// NOTE: also add to GermanSpellerRule.getSpeller() when adding items here:
return Arrays.asList(language.getShortCode() + CUSTOM_SPELLING_FILE, GLOBAL_SPELLING_FILE);
}
/**
*
* Get the name of the spelling file for a language variant (e.g., en-US or de-AT),
* which lists words to be accepted and used for suggestions, even when the spell
* checker would not accept them.
* @since 4.3
*/
public String getLanguageVariantSpellingFileName() {
return SPELLING_FILE_VARIANT;
}
/**
* Get the name of the prohibit file, which lists words not to be accepted, even
* when the spell checker would accept them.
* @since 2.8
*/
protected String getProhibitFileName() {
return language.getShortCode() + SPELLING_PROHIBIT_FILE;
}
/**
* Get the name of the prohibit file, which lists words not to be accepted, even
* when the spell checker would accept them.
* @since 2.8
*/
protected List<String> getAdditionalProhibitFileNames() {
return Arrays.asList(language.getShortCode() + CUSTOM_SPELLING_PROHIBIT_FILE);
}
/**
* Whether the word is prohibited, i.e. whether it should be marked as a spelling
* error even if the spell checker would accept it. (This is useful to improve our spell
* checker without waiting for the upstream checker to be updated.)
* @since 2.8
*/
protected boolean isProhibited(String word) {
return wordsToBeProhibited.contains(word);
}
/**
* Remove prohibited words from suggestions.
* @since 2.8
*/
protected List<SuggestedReplacement> filterSuggestions(List<SuggestedReplacement> suggestions, AnalyzedSentence sentence, int i) {
suggestions.removeIf(suggestion -> isProhibited(suggestion.getReplacement()));
List<SuggestedReplacement> newSuggestions = new ArrayList<>();
for (SuggestedReplacement suggestion : suggestions) {
String replacement = suggestion.getReplacement();
String suggestionWithoutS = replacement.length() > 3 ? replacement.substring(0, replacement.length() - 2) : "";
if (replacement.endsWith(" s") && isProperNoun(suggestionWithoutS)) {
// "Michael s" -> "Michael's"
//System.out.println("### " + suggestion + " => " + sentence.getText().replaceAll(suggestionWithoutS + "s", "**" + suggestionWithoutS + "s**"));
SuggestedReplacement sugg1 = new SuggestedReplacement(suggestionWithoutS);
sugg1.setType(SuggestedReplacement.SuggestionType.Curated);
newSuggestions.add(0, sugg1);
SuggestedReplacement sugg2 = new SuggestedReplacement(suggestionWithoutS + "'s");
sugg2.setType(SuggestedReplacement.SuggestionType.Curated);
newSuggestions.add(0, sugg2);
} else {
newSuggestions.add(suggestion);
}
}
newSuggestions = filterDupes(newSuggestions);
return newSuggestions;
}
private boolean isProperNoun(String wordWithoutS) {
try {
List<AnalyzedTokenReadings> tags = language.getTagger().tag(Collections.singletonList(wordWithoutS));
return tags.stream().anyMatch(k -> k.hasPosTag("NNP"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @param line the line as read from {@code spelling.txt}.
* @since 2.9, signature modified in 3.9
*/
protected void addIgnoreWords(String line) {
// if line consists of several words (separated by " "), a DisambiguationPatternRule
// will be created where each words serves as a case-sensitive and non-inflected PatternToken
// so that the entire multi-word entry is ignored by the spell checker
List<String> tokens = language.getWordTokenizer().tokenize(line);
if (tokens.size() > 1) {
List<PatternToken> patternTokens = new ArrayList<>(tokens.size());
for(String token : tokens) {
if (token.trim().isEmpty()) {
continue;
}
patternTokens.add(new PatternToken(token, true, false, false));
}
antiPatterns.add(new DisambiguationPatternRule("INTERNAL_ANTIPATTERN", "(no description)", language,
patternTokens, null, null, DisambiguationPatternRule.DisambiguatorAction.IGNORE_SPELLING));
} else {
wordsToBeIgnored.add(line);
}
}
/**
* @param words list of words to be prohibited.
* @since 4.2
*/
protected void addProhibitedWords(List<String> words) {
wordsToBeProhibited.addAll(words);
}
/**
* Expand suffixes in a line. By default, the line is not expanded.
* Implementations might e.g. turn {@code bicycle/S} into {@code [bicycle, bicycles]}.
* @since 3.0
*/
protected List<String> expandLine(String line) {
return Collections.singletonList(line);
}
/**
* Accept (case-sensitively, unless at the start of a sentence) the given phrases even though they
* are not in the built-in dictionary.
* Use this to avoid false alarms on e.g. names and technical terms. Unlike {@link #addIgnoreTokens(List)}
* this can deal with phrases. A way to call this is like this:
* <code>rule.acceptPhrases(Arrays.asList("duodenal atresia"))</code>
* This way, checking would not create an error for "duodenal atresia", but it would still
* create and error for "duodenal" or "atresia" if they appear on their own.
* @since 3.3
*/
public void acceptPhrases(List<String> phrases) {
List<List<PatternToken>> antiPatterns = new ArrayList<>();
for (String phrase : phrases) {
String[] parts = phrase.split(" ");
List<PatternToken> patternTokens = new ArrayList<>();
int i = 0;
boolean startsLowercase = false;
for (String part : parts) {
if (i == 0) {
String uppercased = StringTools.uppercaseFirstChar(part);
if (!uppercased.equals(part)) {
startsLowercase = true;
}
}
patternTokens.add(new PatternTokenBuilder().csToken(part).build());
i++;
}
antiPatterns.add(patternTokens);
if (startsLowercase) {
antiPatterns.add(getTokensForSentenceStart(parts));
}
}
this.antiPatterns = makeAntiPatterns(antiPatterns, language);
}
private List<PatternToken> getTokensForSentenceStart(String[] parts) {
List<PatternToken> ucPatternTokens = new ArrayList<>();
int j = 0;
for (String part : parts) {
if (j == 0) {
// at sentence start, we also need to accept a phrase that starts with an uppercase char:
String uppercased = StringTools.uppercaseFirstChar(part);
ucPatternTokens.add(new PatternTokenBuilder().posRegex(JLanguageTool.SENTENCE_START_TAGNAME).build());
ucPatternTokens.add(new PatternTokenBuilder().csToken(uppercased).build());
} else {
ucPatternTokens.add(new PatternTokenBuilder().csToken(part).build());
}
j++;
}
return ucPatternTokens;
}
@Override
public List<DisambiguationPatternRule> getAntiPatterns() {
return antiPatterns;
}
/**
* Checks whether a <code>word</code> starts with an ignored word.
* Note that a minimum <code>word</code>-length of 4 characters is expected.
* (This is for better performance. Moreover, such short words are most likely contained in the dictionary.)
* @param word - entire word
* @param caseSensitive - determines whether the check is case-sensitive
* @return length of the ignored word (i.e., return value is 0, if the word does not start with an ignored word).
* If there are several matches from the set of ignored words, the length of the longest matching word is returned.
* @since 3.5
*/
protected int startsWithIgnoredWord(String word, boolean caseSensitive) {
if (word.length() < 4) {
return 0;
}
Optional<String> match = Optional.empty();
if(caseSensitive) {
Set<String> subset = wordsToBeIgnoredDictionary.get(word.substring(0, 1));
if (subset != null) {
match = subset.stream().filter(s -> word.startsWith(s)).max(STRING_LENGTH_COMPARATOR);
}
} else {
String lowerCaseWord = word.toLowerCase();
Set<String> subset = wordsToBeIgnoredDictionaryIgnoreCase.get(lowerCaseWord.substring(0, 1));
if (subset != null) {
match = subset.stream().filter(s -> lowerCaseWord.startsWith(s)).max(STRING_LENGTH_COMPARATOR);
}
}
return match.isPresent() ? match.get().length() : 0;
}
}
| UTF-8 | Java | 24,633 | java | SpellingCheckRule.java | Java | [
{
"context": "ural language style checker \n * Copyright (C) 2012 Marcin Milkowski (http://www.languagetool.org)\n * \n * This library",
"end": 89,
"score": 0.9994713068008423,
"start": 73,
"tag": "NAME",
"value": "Marcin Milkowski"
},
{
"context": "stract rule for spellchecking rules.\n *\n * @author Marcin Miłkowski\n */\npublic abstract class SpellingCheckRule exten",
"end": 1668,
"score": 0.9995617866516113,
"start": 1652,
"tag": "NAME",
"value": "Marcin Miłkowski"
},
{
"context": "& isProperNoun(suggestionWithoutS)) {\n // \"Michael s\" -> \"Michael's\"\n //System.out.println(\"#",
"end": 18444,
"score": 0.9835264086723328,
"start": 18437,
"tag": "NAME",
"value": "Michael"
},
{
"context": "suggestionWithoutS)) {\n // \"Michael s\" -> \"Michael's\"\n //System.out.println(\"### \" + suggestion",
"end": 18461,
"score": 0.9222071766853333,
"start": 18452,
"tag": "NAME",
"value": "Michael's"
}
] | null | [] | /* LanguageTool, a natural language style checker
* Copyright (C) 2012 <NAME> (http://www.languagetool.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.spelling;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.*;
import org.languagetool.rules.patterns.PatternToken;
import org.languagetool.rules.patterns.PatternTokenBuilder;
import org.languagetool.rules.spelling.suggestions.*;
import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule;
import org.languagetool.tokenizers.WordTokenizer;
import org.languagetool.tools.StringTools;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* An abstract rule for spellchecking rules.
*
* @author <NAME>
*/
public abstract class SpellingCheckRule extends Rule {
/**
* The string {@code LanguageTool}.
* @since 2.3
*/
public static final String LANGUAGETOOL = "LanguageTool";
/**
* The string {@code LanguageTooler}.
* @since 4.4
*/
public static final String LANGUAGETOOLER = "LanguageTooler";
protected final Language language;
/**
* @since 4.5
* For rules from @see Language.getRelevantLanguageModelCapableRules
* Optional, allows e.g. better suggestions when set
*/
@Nullable
protected LanguageModel languageModel;
protected final CachingWordListLoader wordListLoader = new CachingWordListLoader();
private static final String SPELLING_IGNORE_FILE = "/hunspell/ignore.txt";
private static final String SPELLING_FILE = "/hunspell/spelling.txt";
private static final String CUSTOM_SPELLING_FILE = "/hunspell/spelling_custom.txt";
private static final String GLOBAL_SPELLING_FILE = "spelling_global.txt";
private static final String SPELLING_PROHIBIT_FILE = "/hunspell/prohibit.txt";
private static final String CUSTOM_SPELLING_PROHIBIT_FILE = "/hunspell/prohibit_custom.txt";
private static final String SPELLING_FILE_VARIANT = null;
private static final Comparator<String> STRING_LENGTH_COMPARATOR = Comparator.comparingInt(String::length);
private final UserConfig userConfig;
private final Set<String> wordsToBeProhibited = new THashSet<>();
private Map<String,Set<String>> wordsToBeIgnoredDictionary = new THashMap<>();
private Map<String,Set<String>> wordsToBeIgnoredDictionaryIgnoreCase = new THashMap<>();
private List<DisambiguationPatternRule> antiPatterns = new ArrayList<>();
private boolean considerIgnoreWords = true;
private boolean convertsCase = false;
protected final Set<String> wordsToBeIgnored = new HashSet<>();
protected int ignoreWordsWithLength = 0;
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig) {
this(messages, language, userConfig, Collections.emptyList());
}
/**
* @since 4.4
*/
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) {
this(messages, language, userConfig, altLanguages, null);
}
/**
* @since 4.5
*/
public SpellingCheckRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, @Nullable LanguageModel languageModel) {
super(messages);
this.language = language;
this.userConfig = userConfig;
this.languageModel = languageModel;
if (userConfig != null) {
wordsToBeIgnored.addAll(userConfig.getAcceptedWords());
}
setLocQualityIssueType(ITSIssueType.Misspelling);
}
/**
* @param word misspelled word that suggestions should be generated for
* @param userCandidatesList candidates from personal dictionary
* @param candidatesList candidates from default dictionary
* @param orderer model to rank suggestions / extract features, or null
* @param match rule match to add suggestions to
*/
protected static void addSuggestionsToRuleMatch(String word, List<SuggestedReplacement> userCandidatesList, List<SuggestedReplacement> candidatesList,
@Nullable SuggestionsOrderer orderer, RuleMatch match) {
AnalyzedSentence sentence = match.getSentence();
List<String> userCandidates = userCandidatesList.stream().map(SuggestedReplacement::getReplacement).collect(Collectors.toList());
List<String> candidates = candidatesList.stream().map(SuggestedReplacement::getReplacement).collect(Collectors.toList());
int startPos = match.getFromPos();
//long startTime = System.currentTimeMillis();
if (orderer != null && orderer.isMlAvailable()) {
if (orderer instanceof SuggestionsRanker) {
// don't rank words form user dictionary, assign confidence 0.0, but add at start
// hard to ensure performance on unknown words
SuggestionsRanker ranker = (SuggestionsRanker) orderer;
List<SuggestedReplacement> defaultSuggestions = ranker.orderSuggestions(
candidates, word, sentence, startPos);
if (defaultSuggestions.isEmpty()) {
// could not rank for some reason
} else {
if (userCandidates.isEmpty()) {
match.setAutoCorrect(ranker.shouldAutoCorrect(defaultSuggestions));
match.setSuggestedReplacementObjects(defaultSuggestions);
} else {
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>();
for (String wordFromUserDict : userCandidates) {
SuggestedReplacement s = new SuggestedReplacement(wordFromUserDict);
// confidence is null
combinedSuggestions.add(s);
}
combinedSuggestions.addAll(defaultSuggestions);
match.setSuggestedReplacementObjects(combinedSuggestions);
// no auto correct when words from personal dictionaries are included
match.setAutoCorrect(false);
}
}
} else if (orderer instanceof SuggestionsOrdererFeatureExtractor) {
// disable user suggestions here
// problem: how to merge match features when ranking default and user suggestions separately?
if (userCandidates.size() != 0) {
throw new IllegalStateException(
"SuggestionsOrdererFeatureExtractor does not support suggestions from personal dictionaries at the moment.");
}
SuggestionsOrdererFeatureExtractor featureExtractor = (SuggestionsOrdererFeatureExtractor) orderer;
Pair<List<SuggestedReplacement>, SortedMap<String, Float>> suggestions =
featureExtractor.computeFeatures(candidates, word, sentence, startPos);
match.setSuggestedReplacementObjects(suggestions.getLeft());
match.setFeatures(suggestions.getRight());
} else {
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>();
combinedSuggestions.addAll(orderer.orderSuggestions(userCandidates, word, sentence, startPos));
combinedSuggestions.addAll(orderer.orderSuggestions(candidates, word, sentence, startPos));
match.setSuggestedReplacementObjects(combinedSuggestions);
}
} else { // no reranking
List<SuggestedReplacement> combinedSuggestions = new ArrayList<>(match.getSuggestedReplacementObjects());
combinedSuggestions.addAll(userCandidatesList);
combinedSuggestions.addAll(candidatesList);
match.setSuggestedReplacementObjects(combinedSuggestions);
}
/*long timeDelta = System.currentTimeMillis() - startTime;
System.out.printf("Reordering %d suggestions took %d ms.%n", result.getSuggestedReplacements().size(), timeDelta);*/
}
protected RuleMatch createWrongSplitMatch(AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int pos, String coveredWord, String suggestion1, String suggestion2, int prevPos) {
if (ruleMatchesSoFar.size() > 0) {
RuleMatch prevMatch = ruleMatchesSoFar.get(ruleMatchesSoFar.size() - 1);
if (prevMatch.getFromPos() == prevPos) {
// we'll later create a new match that covers the previous misspelled word and the current one:
ruleMatchesSoFar.remove(ruleMatchesSoFar.size()-1);
}
}
RuleMatch ruleMatch = new RuleMatch(this, sentence, prevPos, pos + coveredWord.length(),
messages.getString("spelling"), messages.getString("desc_spelling_short"));
ruleMatch.setSuggestedReplacement((suggestion1 + " " + suggestion2).trim());
return ruleMatch;
}
@Override
public abstract String getId();
@Override
public abstract String getDescription();
@Override
public abstract RuleMatch[] match(AnalyzedSentence sentence) throws IOException;
/**
* @since 4.8
*/
@Experimental
public abstract boolean isMisspelled(String word) throws IOException;
@Override
public boolean isDictionaryBasedSpellingRule() {
return true;
}
/**
* Add the given words to the list of words to be ignored during spell check.
* You might want to use {@link #acceptPhrases(List)} instead, as only that
* can also deal with phrases.
*/
public void addIgnoreTokens(List<String> tokens) {
wordsToBeIgnored.addAll(tokens);
updateIgnoredWordDictionary();
}
//(re)create a Map<String, Set<String>> of all words to be ignored:
// The words' first char serves as key, and the Set<String> contains all Strings starting with this char
private void updateIgnoredWordDictionary() {
wordsToBeIgnoredDictionary = wordsToBeIgnored
.stream()
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toCollection(THashSet::new)));
wordsToBeIgnoredDictionaryIgnoreCase = wordsToBeIgnored
.stream()
.map(String::toLowerCase)
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toCollection(THashSet::new)));
}
/**
* Set whether the list of words to be explicitly ignored (set with {@link #addIgnoreTokens(List)}) is considered at all.
*/
public void setConsiderIgnoreWords(boolean considerIgnoreWords) {
this.considerIgnoreWords = considerIgnoreWords;
}
/**
* Get additional suggestions added before other suggestions (note the rule may choose to
* re-order the suggestions anyway). Only add suggestions here that you know are spelled correctly,
* they will not be checked again before being shown to the user.
*/
protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException {
List<String> moreSuggestions = new ArrayList<>();
if (("Languagetool".equals(word) || "languagetool".equals(word)) && suggestions.stream().noneMatch(k -> k.getReplacement().equals(LANGUAGETOOL))) {
moreSuggestions.add(LANGUAGETOOL);
}
if (("Languagetooler".equals(word) || "languagetooler".equals(word)) && suggestions.stream().noneMatch(k -> k.getReplacement().equals(LANGUAGETOOLER))) {
moreSuggestions.add(LANGUAGETOOLER);
}
return SuggestedReplacement.convert(moreSuggestions);
}
/**
* Get additional suggestions added after other suggestions (note the rule may choose to
* re-order the suggestions anyway).
*/
protected List<SuggestedReplacement> getAdditionalSuggestions(List<SuggestedReplacement> suggestions, String word) {
return Collections.emptyList();
}
/**
* Returns true iff the token at the given position should be ignored by the spell checker.
*/
protected boolean ignoreToken(AnalyzedTokenReadings[] tokens, int idx) throws IOException {
List<String> words = new ArrayList<>();
for (AnalyzedTokenReadings token : tokens) {
words.add(token.getToken());
}
return ignoreWord(words, idx);
}
/**
* Returns true iff the word should be ignored by the spell checker.
* If possible, use {@link #ignoreToken(AnalyzedTokenReadings[], int)} instead.
*/
protected boolean ignoreWord(String word) throws IOException {
if (!considerIgnoreWords) {
return false;
}
if (word.endsWith(".") && !wordsToBeIgnored.contains(word)) {
return isIgnoredNoCase(word.substring(0, word.length()-1)); // e.g. word at end of sentence
}
return isIgnoredNoCase(word);
}
private boolean isIgnoredNoCase(String word) {
return wordsToBeIgnored.contains(word) ||
(convertsCase && wordsToBeIgnored.contains(word.toLowerCase(language.getLocale()))) ||
(ignoreWordsWithLength > 0 && word.length() <= ignoreWordsWithLength);
}
/**
* Returns true iff the word at the given position should be ignored by the spell checker.
* If possible, use {@link #ignoreToken(AnalyzedTokenReadings[], int)} instead.
* @since 2.6
*/
protected boolean ignoreWord(List<String> words, int idx) throws IOException {
return ignoreWord(words.get(idx));
}
/**
* Used to determine whether the dictionary will use case conversions for
* spell checking.
* @param convertsCase if true, then conversions are used.
* @since 2.5
*/
public void setConvertsCase(boolean convertsCase) {
this.convertsCase = convertsCase;
}
protected boolean isUrl(String token) {
return WordTokenizer.isUrl(token);
}
protected boolean isEMail(String token) {
return WordTokenizer.isEMail(token);
}
protected <T> List<T> filterDupes(List<T> words) {
return words.stream().distinct().collect(Collectors.toList());
}
protected synchronized void init() throws IOException {
for (String ignoreWord : wordListLoader.loadWords(getIgnoreFileName())) {
addIgnoreWords(ignoreWord);
}
if (getSpellingFileName() != null) {
for (String ignoreWord : wordListLoader.loadWords(getSpellingFileName())) {
addIgnoreWords(ignoreWord);
}
}
for (String fileName : getAdditionalSpellingFileNames()) {
if (JLanguageTool.getDataBroker().resourceExists(fileName)) {
for (String ignoreWord : wordListLoader.loadWords(fileName)) {
addIgnoreWords(ignoreWord);
}
}
}
updateIgnoredWordDictionary();
for (String prohibitedWord : wordListLoader.loadWords(getProhibitFileName())) {
addProhibitedWords(expandLine(prohibitedWord));
}
for (String fileName : getAdditionalProhibitFileNames()) {
for (String prohibitedWord : wordListLoader.loadWords(fileName)) {
addProhibitedWords(expandLine(prohibitedWord));
}
}
}
/**
* Get the name of the ignore file, which lists words to be accepted, even
* when the spell checker would not accept them. Unlike with {@link #getSpellingFileName()}
* the words in this file will not be used for creating suggestions for misspelled words.
* @since 2.7
*/
protected String getIgnoreFileName() {
return language.getShortCode() + SPELLING_IGNORE_FILE;
}
/**
* Get the name of the spelling file, which lists words to be accepted
* and used for suggestions, even when the spell checker would not accept them.
* @since 2.9, public since 3.5
*/
public String getSpellingFileName() {
return language.getShortCode() + SPELLING_FILE;
}
/**
* Get the name of additional spelling file, which lists words to be accepted
* and used for suggestions, even when the spell checker would not accept them.
* @since 4.8
*/
public List<String> getAdditionalSpellingFileNames() {
// NOTE: also add to GermanSpellerRule.getSpeller() when adding items here:
return Arrays.asList(language.getShortCode() + CUSTOM_SPELLING_FILE, GLOBAL_SPELLING_FILE);
}
/**
*
* Get the name of the spelling file for a language variant (e.g., en-US or de-AT),
* which lists words to be accepted and used for suggestions, even when the spell
* checker would not accept them.
* @since 4.3
*/
public String getLanguageVariantSpellingFileName() {
return SPELLING_FILE_VARIANT;
}
/**
* Get the name of the prohibit file, which lists words not to be accepted, even
* when the spell checker would accept them.
* @since 2.8
*/
protected String getProhibitFileName() {
return language.getShortCode() + SPELLING_PROHIBIT_FILE;
}
/**
* Get the name of the prohibit file, which lists words not to be accepted, even
* when the spell checker would accept them.
* @since 2.8
*/
protected List<String> getAdditionalProhibitFileNames() {
return Arrays.asList(language.getShortCode() + CUSTOM_SPELLING_PROHIBIT_FILE);
}
/**
* Whether the word is prohibited, i.e. whether it should be marked as a spelling
* error even if the spell checker would accept it. (This is useful to improve our spell
* checker without waiting for the upstream checker to be updated.)
* @since 2.8
*/
protected boolean isProhibited(String word) {
return wordsToBeProhibited.contains(word);
}
/**
* Remove prohibited words from suggestions.
* @since 2.8
*/
protected List<SuggestedReplacement> filterSuggestions(List<SuggestedReplacement> suggestions, AnalyzedSentence sentence, int i) {
suggestions.removeIf(suggestion -> isProhibited(suggestion.getReplacement()));
List<SuggestedReplacement> newSuggestions = new ArrayList<>();
for (SuggestedReplacement suggestion : suggestions) {
String replacement = suggestion.getReplacement();
String suggestionWithoutS = replacement.length() > 3 ? replacement.substring(0, replacement.length() - 2) : "";
if (replacement.endsWith(" s") && isProperNoun(suggestionWithoutS)) {
// "Michael s" -> "Michael's"
//System.out.println("### " + suggestion + " => " + sentence.getText().replaceAll(suggestionWithoutS + "s", "**" + suggestionWithoutS + "s**"));
SuggestedReplacement sugg1 = new SuggestedReplacement(suggestionWithoutS);
sugg1.setType(SuggestedReplacement.SuggestionType.Curated);
newSuggestions.add(0, sugg1);
SuggestedReplacement sugg2 = new SuggestedReplacement(suggestionWithoutS + "'s");
sugg2.setType(SuggestedReplacement.SuggestionType.Curated);
newSuggestions.add(0, sugg2);
} else {
newSuggestions.add(suggestion);
}
}
newSuggestions = filterDupes(newSuggestions);
return newSuggestions;
}
private boolean isProperNoun(String wordWithoutS) {
try {
List<AnalyzedTokenReadings> tags = language.getTagger().tag(Collections.singletonList(wordWithoutS));
return tags.stream().anyMatch(k -> k.hasPosTag("NNP"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @param line the line as read from {@code spelling.txt}.
* @since 2.9, signature modified in 3.9
*/
protected void addIgnoreWords(String line) {
// if line consists of several words (separated by " "), a DisambiguationPatternRule
// will be created where each words serves as a case-sensitive and non-inflected PatternToken
// so that the entire multi-word entry is ignored by the spell checker
List<String> tokens = language.getWordTokenizer().tokenize(line);
if (tokens.size() > 1) {
List<PatternToken> patternTokens = new ArrayList<>(tokens.size());
for(String token : tokens) {
if (token.trim().isEmpty()) {
continue;
}
patternTokens.add(new PatternToken(token, true, false, false));
}
antiPatterns.add(new DisambiguationPatternRule("INTERNAL_ANTIPATTERN", "(no description)", language,
patternTokens, null, null, DisambiguationPatternRule.DisambiguatorAction.IGNORE_SPELLING));
} else {
wordsToBeIgnored.add(line);
}
}
/**
* @param words list of words to be prohibited.
* @since 4.2
*/
protected void addProhibitedWords(List<String> words) {
wordsToBeProhibited.addAll(words);
}
/**
* Expand suffixes in a line. By default, the line is not expanded.
* Implementations might e.g. turn {@code bicycle/S} into {@code [bicycle, bicycles]}.
* @since 3.0
*/
protected List<String> expandLine(String line) {
return Collections.singletonList(line);
}
/**
* Accept (case-sensitively, unless at the start of a sentence) the given phrases even though they
* are not in the built-in dictionary.
* Use this to avoid false alarms on e.g. names and technical terms. Unlike {@link #addIgnoreTokens(List)}
* this can deal with phrases. A way to call this is like this:
* <code>rule.acceptPhrases(Arrays.asList("duodenal atresia"))</code>
* This way, checking would not create an error for "duodenal atresia", but it would still
* create and error for "duodenal" or "atresia" if they appear on their own.
* @since 3.3
*/
public void acceptPhrases(List<String> phrases) {
List<List<PatternToken>> antiPatterns = new ArrayList<>();
for (String phrase : phrases) {
String[] parts = phrase.split(" ");
List<PatternToken> patternTokens = new ArrayList<>();
int i = 0;
boolean startsLowercase = false;
for (String part : parts) {
if (i == 0) {
String uppercased = StringTools.uppercaseFirstChar(part);
if (!uppercased.equals(part)) {
startsLowercase = true;
}
}
patternTokens.add(new PatternTokenBuilder().csToken(part).build());
i++;
}
antiPatterns.add(patternTokens);
if (startsLowercase) {
antiPatterns.add(getTokensForSentenceStart(parts));
}
}
this.antiPatterns = makeAntiPatterns(antiPatterns, language);
}
private List<PatternToken> getTokensForSentenceStart(String[] parts) {
List<PatternToken> ucPatternTokens = new ArrayList<>();
int j = 0;
for (String part : parts) {
if (j == 0) {
// at sentence start, we also need to accept a phrase that starts with an uppercase char:
String uppercased = StringTools.uppercaseFirstChar(part);
ucPatternTokens.add(new PatternTokenBuilder().posRegex(JLanguageTool.SENTENCE_START_TAGNAME).build());
ucPatternTokens.add(new PatternTokenBuilder().csToken(uppercased).build());
} else {
ucPatternTokens.add(new PatternTokenBuilder().csToken(part).build());
}
j++;
}
return ucPatternTokens;
}
@Override
public List<DisambiguationPatternRule> getAntiPatterns() {
return antiPatterns;
}
/**
* Checks whether a <code>word</code> starts with an ignored word.
* Note that a minimum <code>word</code>-length of 4 characters is expected.
* (This is for better performance. Moreover, such short words are most likely contained in the dictionary.)
* @param word - entire word
* @param caseSensitive - determines whether the check is case-sensitive
* @return length of the ignored word (i.e., return value is 0, if the word does not start with an ignored word).
* If there are several matches from the set of ignored words, the length of the longest matching word is returned.
* @since 3.5
*/
protected int startsWithIgnoredWord(String word, boolean caseSensitive) {
if (word.length() < 4) {
return 0;
}
Optional<String> match = Optional.empty();
if(caseSensitive) {
Set<String> subset = wordsToBeIgnoredDictionary.get(word.substring(0, 1));
if (subset != null) {
match = subset.stream().filter(s -> word.startsWith(s)).max(STRING_LENGTH_COMPARATOR);
}
} else {
String lowerCaseWord = word.toLowerCase();
Set<String> subset = wordsToBeIgnoredDictionaryIgnoreCase.get(lowerCaseWord.substring(0, 1));
if (subset != null) {
match = subset.stream().filter(s -> lowerCaseWord.startsWith(s)).max(STRING_LENGTH_COMPARATOR);
}
}
return match.isPresent() ? match.get().length() : 0;
}
}
| 24,612 | 0.701689 | 0.697345 | 592 | 40.608109 | 36.161308 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533784 | false | false | 4 |
a7a7876d1da608324eac0c53c3538938cd1700d7 | 37,898,791,430,065 | 7eefd0ddcf35d4903fd50fb685b24db7cf8f82b0 | /Level #1/Java Basics/IntroductionToJava/src/FiveSpecialLetters.java | c276955b43d972573a9bd15f18484c296aabef2f | [] | no_license | AlexKondov/SoftwareUniversity | https://github.com/AlexKondov/SoftwareUniversity | 04862a871d27686f62bce2832e4889d7ecc58b2a | 5e8e693d1dba38d8a0b34402419d23593772809a | refs/heads/master | 2016-09-15T06:47:36.870000 | 2016-04-25T08:41:03 | 2016-04-25T08:41:03 | 20,235,621 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class FiveSpecialLetters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start = in.nextInt();
int end = in.nextInt();
int count = 0;
for (char c1 = 'a'; c1 <= 'e'; c1++) {
for (char c2 = 'a'; c2 <= 'e'; c2++) {
for (char c3 = 'a'; c3 <= 'e'; c3++) {
for (char c4 = 'a'; c4 <= 'e'; c4++) {
for (char c5 = 'a'; c5 <= 'e'; c5++) {
String word = "" + c1 + c2 + c3 + c4 + c5;
long weight = calculateWeight(word);
if (weight >= start && weight <= end) {
System.out.println(word + " ");
}
}
}
}
}
}
}
public static int generateWeight (char letter) {
switch (letter) {
case 'a': return 5;
case 'b': return - 12;
case 'c': return 47;
case 'd': return 7;
case 'e': return -32;
}
return 0;
}
public static long calculateWeight (String word) {
boolean[] visited = new boolean[(int)'e' + 1];
long weight = 0;
int index = 1;
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
if (!visited[letter]) {
weight += index * generateWeight(letter);
visited[letter] = true;
index++;
}
}
return weight;
}
} | UTF-8 | Java | 1,233 | java | FiveSpecialLetters.java | Java | [] | null | [] | import java.util.Scanner;
public class FiveSpecialLetters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start = in.nextInt();
int end = in.nextInt();
int count = 0;
for (char c1 = 'a'; c1 <= 'e'; c1++) {
for (char c2 = 'a'; c2 <= 'e'; c2++) {
for (char c3 = 'a'; c3 <= 'e'; c3++) {
for (char c4 = 'a'; c4 <= 'e'; c4++) {
for (char c5 = 'a'; c5 <= 'e'; c5++) {
String word = "" + c1 + c2 + c3 + c4 + c5;
long weight = calculateWeight(word);
if (weight >= start && weight <= end) {
System.out.println(word + " ");
}
}
}
}
}
}
}
public static int generateWeight (char letter) {
switch (letter) {
case 'a': return 5;
case 'b': return - 12;
case 'c': return 47;
case 'd': return 7;
case 'e': return -32;
}
return 0;
}
public static long calculateWeight (String word) {
boolean[] visited = new boolean[(int)'e' + 1];
long weight = 0;
int index = 1;
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
if (!visited[letter]) {
weight += index * generateWeight(letter);
visited[letter] = true;
index++;
}
}
return weight;
}
} | 1,233 | 0.523925 | 0.49635 | 57 | 20.649122 | 17.155113 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.210526 | false | false | 4 |
2b5585efa44f5c1962173ac64d84bf3e960de9c1 | 36,601,711,297,075 | 89a7ac867ff2eb7743ebf3c323554ae76728534f | /src/main/groovy/com/server/core/utils/JwtFilter.java | 343c27a48b64c7ce9fe4734c04719dbdc09d8b62 | [] | no_license | navalta3030/spring_server | https://github.com/navalta3030/spring_server | 2a40f615601e15296c867a4deadde4487a4d84ae | 0dfc391fdf93b5486259c6ecfba1b42d6d0a15af | refs/heads/master | 2021-02-16T19:25:49.547000 | 2020-03-08T11:17:06 | 2020-03-08T11:17:06 | 245,037,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.server.core.utils;
import com.server.core.service.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
String role = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
role = jwtUtil.extractRole(jwt);
}
// Verify username and role are not empty
// Verify current Authentication is empty
if (username != null && role != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// is JWT token valid?
if (jwtUtil.validateToken(jwt)) {
// let's add if USER or ADMIN
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
list.add(new SimpleGrantedAuthority("ROLE_" + role));
// Keep user authenticated.
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
username, null, list);
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
| UTF-8 | Java | 2,774 | java | JwtFilter.java | Java | [] | null | [] | package com.server.core.utils;
import com.server.core.service.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
String role = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
role = jwtUtil.extractRole(jwt);
}
// Verify username and role are not empty
// Verify current Authentication is empty
if (username != null && role != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// is JWT token valid?
if (jwtUtil.validateToken(jwt)) {
// let's add if USER or ADMIN
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
list.add(new SimpleGrantedAuthority("ROLE_" + role));
// Keep user authenticated.
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
username, null, list);
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
| 2,774 | 0.724946 | 0.724585 | 68 | 39.794117 | 33.006489 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573529 | false | false | 4 |
522c772325db7ce2835f44bce6c33defcade9ad2 | 21,672,405,040,033 | 277cb244aae72cdcea4025811684a6c652df83ea | /DVN-root/DVN-web/src/main/java/edu/harvard/iq/dvn/api/datadeposit/CollectionDepositManagerImpl.java | a652d8378241221320bc18281f1af404e7b71c77 | [] | no_license | kcondon/maventest3 | https://github.com/kcondon/maventest3 | f94660cf8e1ee4aa8a7cf1ff62e98a634daff6ee | 4ab11c90828a5d21fd13bb496e94668bf31465bd | refs/heads/master | 2021-01-01T15:18:20.463000 | 2013-08-12T20:18:48 | 2013-08-12T20:18:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dvn.api.datadeposit;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Inject;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.commons.io.FileUtils;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.CollectionDepositManager;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
public class CollectionDepositManagerImpl implements CollectionDepositManager {
private static final Logger logger = Logger.getLogger(CollectionDepositManagerImpl.class.getCanonicalName());
@EJB
VDCServiceLocal vdcService;
@EJB
StudyServiceLocal studyService;
@Inject
SwordAuth swordAuth;
@Override
public DepositReceipt createNew(String collectionUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException {
VDCUser vdcUser = swordAuth.auth(authCredentials);
URI uriReference;
try {
uriReference = new URI(collectionUri);
} catch (URISyntaxException ex) {
throw new SwordServerException("problem with collection URI: " + collectionUri);
}
logger.info("collection URI path: " + uriReference.getPath());
String[] parts = uriReference.getPath().split("/");
String dvAlias;
try {
// 0 1 2 3 4 5 6 7
// for example: /dvn/api/data-deposit/swordv2/collection/dataverse/sword
dvAlias = parts[7];
} catch (ArrayIndexOutOfBoundsException ex) {
throw new SwordServerException("could not extract dataverse alias from collection URI: " + collectionUri);
}
logger.info("attempting deposit into this dataverse alias: " + dvAlias);
VDC dv = vdcService.findByAlias(dvAlias);
if (dv != null) {
boolean authorized = false;
List<VDC> userVDCs = vdcService.getUserVDCs(vdcUser.getId());
for (VDC userVdc : userVDCs) {
if (userVdc.equals(dv)) {
authorized = true;
break;
}
}
if (!authorized) {
throw new SwordServerException("user " + vdcUser.getUserName() + " is not authorized to modify dataverse " + dv.getAlias());
}
if (userVDCs.size() != 1) {
throw new SwordServerException("the account used to modify a Journal Dataverse can only have access to 1 dataverse, not " + userVDCs.size());
}
logger.info("multipart: " + deposit.isMultipart());
logger.info("binary only: " + deposit.isBinaryOnly());
logger.info("entry only: " + deposit.isEntryOnly());
logger.info("in progress: " + deposit.isInProgress());
logger.info("metadata relevant: " + deposit.isMetadataRelevant());
if (deposit.isEntryOnly()) {
// require title *and* exercise the SWORD jar a bit
Map<String, List<String>> dublinCore = deposit.getSwordEntry().getDublinCore();
if (dublinCore.get("title") == null || dublinCore.get("title").get(0) == null) {
throw new SwordError("title field is required");
}
// instead of writing a tmp file, maybe importStudy() could accept an InputStream?
String tmpDirectory = config.getTempDirectory();
String uploadDirPath = tmpDirectory + File.separator + "import" + File.separator + dv.getId();
File uploadDir = new File(uploadDirPath);
if (!uploadDir.exists()) {
if (!uploadDir.mkdirs()) {
throw new SwordServerException("couldn't create directory: " + uploadDir.getAbsolutePath());
}
}
String tmpFilePath = uploadDirPath + File.separator + "newStudyViaSwordv2.xml";
File tmpFile = new File(tmpFilePath);
try {
FileUtils.writeStringToFile(tmpFile, deposit.getSwordEntry().getEntry().toString());
} catch (IOException ex) {
throw new SwordServerException("Could write temporary file");
} finally {
uploadDir.delete();
}
Long dcmiTermsFormatId = new Long(4);
Study study;
try {
study = studyService.importStudy(tmpFile, dcmiTermsFormatId, dv.getId(), vdcUser.getId());
} catch (Exception ex) {
throw new SwordError("Couldn't import study: " + ex.getMessage());
} finally {
tmpFile.delete();
uploadDir.delete();
}
DepositReceipt depositReceipt = new DepositReceipt();
String hostName = System.getProperty("dvn.inetAddress");
int port = uriReference.getPort();
String baseUrl = "https://" + hostName + ":" + port + "/dvn/api/data-deposit/swordv2/";
depositReceipt.setLocation(new IRI("location" + baseUrl + study.getGlobalId()));
depositReceipt.setEditIRI(new IRI(baseUrl + "edit/" + study.getGlobalId()));
depositReceipt.setEditMediaIRI(new IRI(baseUrl + "edit-media/" + study.getGlobalId()));
depositReceipt.setVerboseDescription("Title: " + study.getLatestVersion().getMetadata().getTitle());
depositReceipt.setStatementURI("application/atom+xml;type=feed", baseUrl + "statement/" + study.getGlobalId());
return depositReceipt;
} else if (deposit.isBinaryOnly()) {
// get here with this:
// curl --insecure -s --data-binary "@example.zip" -H "Content-Disposition: filename=example.zip" -H "Content-Type: application/zip" https://sword:sword@localhost:8181/dvn/api/data-deposit/swordv2/collection/dataverse/sword/
throw new SwordError("Binary deposit to the collection IRI via POST is not supported. Please POST an Atom entry instead.");
} else if (deposit.isMultipart()) {
// get here with this:
// wget https://raw.github.com/swordapp/Simple-Sword-Server/master/tests/resources/multipart.dat
// curl --insecure --data-binary "@multipart.dat" -H 'Content-Type: multipart/related; boundary="===============0670350989=="' -H "MIME-Version: 1.0" https://sword:sword@localhost:8181/dvn/api/data-deposit/swordv2/collection/dataverse/sword/hdl:1902.1/12345
// but...
// "Yeah, multipart is critically broken across all implementations" -- http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00327.html
throw new UnsupportedOperationException("Not yet implemented");
} else {
throw new SwordError("expected deposit types are isEntryOnly, isBinaryOnly, and isMultiPart");
}
} else {
throw new SwordServerException("Could not find dataverse: " + dvAlias);
}
}
}
| UTF-8 | Java | 8,644 | java | CollectionDepositManagerImpl.java | Java | [
{
"context": "s:\n // wget https://raw.github.com/swordapp/Simple-Sword-Server/master/tests/resources/multip",
"end": 7774,
"score": 0.9993774890899658,
"start": 7766,
"tag": "USERNAME",
"value": "swordapp"
},
{
"context": "l implementations\" -- http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00327.html\n throw new Unsupport",
"end": 8284,
"score": 0.9710856080055237,
"start": 8248,
"tag": "EMAIL",
"value": "sword-app-tech@lists.sourceforge.net"
}
] | null | [] | /*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dvn.api.datadeposit;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Inject;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.commons.io.FileUtils;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.CollectionDepositManager;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
public class CollectionDepositManagerImpl implements CollectionDepositManager {
private static final Logger logger = Logger.getLogger(CollectionDepositManagerImpl.class.getCanonicalName());
@EJB
VDCServiceLocal vdcService;
@EJB
StudyServiceLocal studyService;
@Inject
SwordAuth swordAuth;
@Override
public DepositReceipt createNew(String collectionUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException {
VDCUser vdcUser = swordAuth.auth(authCredentials);
URI uriReference;
try {
uriReference = new URI(collectionUri);
} catch (URISyntaxException ex) {
throw new SwordServerException("problem with collection URI: " + collectionUri);
}
logger.info("collection URI path: " + uriReference.getPath());
String[] parts = uriReference.getPath().split("/");
String dvAlias;
try {
// 0 1 2 3 4 5 6 7
// for example: /dvn/api/data-deposit/swordv2/collection/dataverse/sword
dvAlias = parts[7];
} catch (ArrayIndexOutOfBoundsException ex) {
throw new SwordServerException("could not extract dataverse alias from collection URI: " + collectionUri);
}
logger.info("attempting deposit into this dataverse alias: " + dvAlias);
VDC dv = vdcService.findByAlias(dvAlias);
if (dv != null) {
boolean authorized = false;
List<VDC> userVDCs = vdcService.getUserVDCs(vdcUser.getId());
for (VDC userVdc : userVDCs) {
if (userVdc.equals(dv)) {
authorized = true;
break;
}
}
if (!authorized) {
throw new SwordServerException("user " + vdcUser.getUserName() + " is not authorized to modify dataverse " + dv.getAlias());
}
if (userVDCs.size() != 1) {
throw new SwordServerException("the account used to modify a Journal Dataverse can only have access to 1 dataverse, not " + userVDCs.size());
}
logger.info("multipart: " + deposit.isMultipart());
logger.info("binary only: " + deposit.isBinaryOnly());
logger.info("entry only: " + deposit.isEntryOnly());
logger.info("in progress: " + deposit.isInProgress());
logger.info("metadata relevant: " + deposit.isMetadataRelevant());
if (deposit.isEntryOnly()) {
// require title *and* exercise the SWORD jar a bit
Map<String, List<String>> dublinCore = deposit.getSwordEntry().getDublinCore();
if (dublinCore.get("title") == null || dublinCore.get("title").get(0) == null) {
throw new SwordError("title field is required");
}
// instead of writing a tmp file, maybe importStudy() could accept an InputStream?
String tmpDirectory = config.getTempDirectory();
String uploadDirPath = tmpDirectory + File.separator + "import" + File.separator + dv.getId();
File uploadDir = new File(uploadDirPath);
if (!uploadDir.exists()) {
if (!uploadDir.mkdirs()) {
throw new SwordServerException("couldn't create directory: " + uploadDir.getAbsolutePath());
}
}
String tmpFilePath = uploadDirPath + File.separator + "newStudyViaSwordv2.xml";
File tmpFile = new File(tmpFilePath);
try {
FileUtils.writeStringToFile(tmpFile, deposit.getSwordEntry().getEntry().toString());
} catch (IOException ex) {
throw new SwordServerException("Could write temporary file");
} finally {
uploadDir.delete();
}
Long dcmiTermsFormatId = new Long(4);
Study study;
try {
study = studyService.importStudy(tmpFile, dcmiTermsFormatId, dv.getId(), vdcUser.getId());
} catch (Exception ex) {
throw new SwordError("Couldn't import study: " + ex.getMessage());
} finally {
tmpFile.delete();
uploadDir.delete();
}
DepositReceipt depositReceipt = new DepositReceipt();
String hostName = System.getProperty("dvn.inetAddress");
int port = uriReference.getPort();
String baseUrl = "https://" + hostName + ":" + port + "/dvn/api/data-deposit/swordv2/";
depositReceipt.setLocation(new IRI("location" + baseUrl + study.getGlobalId()));
depositReceipt.setEditIRI(new IRI(baseUrl + "edit/" + study.getGlobalId()));
depositReceipt.setEditMediaIRI(new IRI(baseUrl + "edit-media/" + study.getGlobalId()));
depositReceipt.setVerboseDescription("Title: " + study.getLatestVersion().getMetadata().getTitle());
depositReceipt.setStatementURI("application/atom+xml;type=feed", baseUrl + "statement/" + study.getGlobalId());
return depositReceipt;
} else if (deposit.isBinaryOnly()) {
// get here with this:
// curl --insecure -s --data-binary "@example.zip" -H "Content-Disposition: filename=example.zip" -H "Content-Type: application/zip" https://sword:sword@localhost:8181/dvn/api/data-deposit/swordv2/collection/dataverse/sword/
throw new SwordError("Binary deposit to the collection IRI via POST is not supported. Please POST an Atom entry instead.");
} else if (deposit.isMultipart()) {
// get here with this:
// wget https://raw.github.com/swordapp/Simple-Sword-Server/master/tests/resources/multipart.dat
// curl --insecure --data-binary "@multipart.dat" -H 'Content-Type: multipart/related; boundary="===============0670350989=="' -H "MIME-Version: 1.0" https://sword:sword@localhost:8181/dvn/api/data-deposit/swordv2/collection/dataverse/sword/hdl:1902.1/12345
// but...
// "Yeah, multipart is critically broken across all implementations" -- http://www.mail-archive.com/<EMAIL>/msg00327.html
throw new UnsupportedOperationException("Not yet implemented");
} else {
throw new SwordError("expected deposit types are isEntryOnly, isBinaryOnly, and isMultiPart");
}
} else {
throw new SwordServerException("Could not find dataverse: " + dvAlias);
}
}
}
| 8,615 | 0.631189 | 0.623207 | 173 | 48.965317 | 42.736034 | 273 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641618 | false | false | 4 |
dc387d2fe845494aa51dcb1871ca3cd06c153e75 | 25,486,335,981,148 | 3c0f99a4ab28780424bfb31d71358888471f9863 | /src/main/java/com/ynz/Worker.java | 5070efe5debd482ef09f0096d5b4913457aa5551 | [] | no_license | yichunzhao/value-spel | https://github.com/yichunzhao/value-spel | 39bf90c435d8d70a8f9112f3595944fbb0ff8b5a | 931555a1e9843f8ab1f095c09365e38fb31a6508 | refs/heads/master | 2022-12-07T11:29:36.201000 | 2020-09-01T05:59:42 | 2020-09-01T05:59:42 | 290,070,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ynz;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@RequiredArgsConstructor
public class Worker {
private final Saw saw;
public void doTask() {
saw.cut();
}
}
| UTF-8 | Java | 289 | java | Worker.java | Java | [] | null | [] | package com.ynz;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@RequiredArgsConstructor
public class Worker {
private final Saw saw;
public void doTask() {
saw.cut();
}
}
| 289 | 0.737024 | 0.726644 | 17 | 16 | 14.544051 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 4 |
85fbaa4d794e5773330acd1696cd33034762644f | 37,726,992,737,411 | fcf6fe903ab18e0cd3e09b06d031aa18a6c6885a | /src/com/company/plants/PlantsSeeds.java | f7ac4d7d99fa952a00b5d87aabb8601c3c0ec3a1 | [] | no_license | ApictoSole/SimFarm | https://github.com/ApictoSole/SimFarm | 3e468111b3040097c65760cdf361683bed73d5e2 | c179cdb4573d3666ed4e21068017711fdb5adcc5 | refs/heads/master | 2022-12-20T23:55:13.957000 | 2020-09-20T14:38:01 | 2020-09-20T14:38:01 | 297,094,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.plants;
public class PlantsSeeds {
public PlantsValues values;
public Double amount;
public PlantsSeeds(PlantsValues values, Double amount) {
this.values = values;
this.amount = amount;
}
@Override
public String toString() {
return "PlantsSeeds{" +
"values=" + values.name +
", amount=" + amount +
'}';
}
}
| UTF-8 | Java | 430 | java | PlantsSeeds.java | Java | [] | null | [] | package com.company.plants;
public class PlantsSeeds {
public PlantsValues values;
public Double amount;
public PlantsSeeds(PlantsValues values, Double amount) {
this.values = values;
this.amount = amount;
}
@Override
public String toString() {
return "PlantsSeeds{" +
"values=" + values.name +
", amount=" + amount +
'}';
}
}
| 430 | 0.555814 | 0.555814 | 19 | 21.631578 | 16.203348 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 4 |
821001072d2b67d32c14e6e848529dbacaf28895 | 31,069,793,456,849 | 899ae5877be5b950db7b2ebeda1a17ecb16f4d40 | /CRS/feature/src/main/java/ca/mcgill/hci/crs_application/feature/WifiSwitchOrAdd.java | d6a843b99d2a23db647427d88972a37f06ff44d7 | [] | no_license | florencecyc/CRS | https://github.com/florencecyc/CRS | 83a57aaf4e4a84aab5d0ba047f0dc48ebfe75da9 | 96eb3df5188e44a202810c2893e31081ba2cd605 | refs/heads/master | 2020-09-24T05:51:13.793000 | 2019-11-24T00:40:07 | 2019-11-24T00:40:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ca.mcgill.hci.crs_application.feature;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.UUID;
public class WifiSwitchOrAdd extends CRSActivity {
private WifiManager wifiManager;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
setContentView(R.layout.activity_wifi_switch_or_add);
MaterialButton cancelButton = findViewById(R.id.wifiCancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
final UUID uuid = getWifiUUID();
if (uuid == null) {
Toast.makeText(getApplicationContext(), "Not Connected to WiFi!", Toast.LENGTH_SHORT).show();
finish();
} else {
// Check if the UUID is known
MaterialButton confirmButton = findViewById(R.id.wifiConfirmButton);
TextView tv = findViewById(R.id.wifiLocationView);
JSONObject location = SavedData.getLocation(this, uuid.toString());
if (location == null) {
tv.setText("Unknown Location! Press 'Confirm' to Add.");
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.current_location), uuid.toString());
if (preferences.contains(getString(R.string.override_mode))) {
editor.remove(getString(R.string.override_mode));
}
editor.apply();
Intent intent = new Intent(view.getContext(), Manage_Location.class);
intent.putExtra("uuid", uuid.toString());
startActivity(intent);
finish();
}
});
}
else {
try {
tv.setText("Switch to '" + location.getString("name") + "'?");
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.current_location), uuid.toString());
if (preferences.contains(getString(R.string.override_mode))) {
editor.remove(getString(R.string.override_mode));
}
editor.apply();
finish();
}
});
} catch (JSONException e) {
Log.d("JSON", e.getMessage());
}
}
}
}
private UUID getWifiUUID() {
WifiInfo info = wifiManager.getConnectionInfo();
String bssid = info.getBSSID();
if (bssid != null) {
UUID uuid = UUID.nameUUIDFromBytes(bssid.getBytes());
Log.d("BSSID", bssid);
return uuid;
}
return null;
}
}
| UTF-8 | Java | 4,131 | java | WifiSwitchOrAdd.java | Java | [] | null | [] | package ca.mcgill.hci.crs_application.feature;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.UUID;
public class WifiSwitchOrAdd extends CRSActivity {
private WifiManager wifiManager;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
setContentView(R.layout.activity_wifi_switch_or_add);
MaterialButton cancelButton = findViewById(R.id.wifiCancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
final UUID uuid = getWifiUUID();
if (uuid == null) {
Toast.makeText(getApplicationContext(), "Not Connected to WiFi!", Toast.LENGTH_SHORT).show();
finish();
} else {
// Check if the UUID is known
MaterialButton confirmButton = findViewById(R.id.wifiConfirmButton);
TextView tv = findViewById(R.id.wifiLocationView);
JSONObject location = SavedData.getLocation(this, uuid.toString());
if (location == null) {
tv.setText("Unknown Location! Press 'Confirm' to Add.");
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.current_location), uuid.toString());
if (preferences.contains(getString(R.string.override_mode))) {
editor.remove(getString(R.string.override_mode));
}
editor.apply();
Intent intent = new Intent(view.getContext(), Manage_Location.class);
intent.putExtra("uuid", uuid.toString());
startActivity(intent);
finish();
}
});
}
else {
try {
tv.setText("Switch to '" + location.getString("name") + "'?");
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.current_location), uuid.toString());
if (preferences.contains(getString(R.string.override_mode))) {
editor.remove(getString(R.string.override_mode));
}
editor.apply();
finish();
}
});
} catch (JSONException e) {
Log.d("JSON", e.getMessage());
}
}
}
}
private UUID getWifiUUID() {
WifiInfo info = wifiManager.getConnectionInfo();
String bssid = info.getBSSID();
if (bssid != null) {
UUID uuid = UUID.nameUUIDFromBytes(bssid.getBytes());
Log.d("BSSID", bssid);
return uuid;
}
return null;
}
}
| 4,131 | 0.563786 | 0.563786 | 103 | 39.106796 | 27.442406 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631068 | false | false | 4 |
140f8d42431c7f08cfa0ce40cdcca131c74928f8 | 4,758,823,822,194 | 0a4b7636cd35e54ae5a908c6fddb7802fbd43335 | /src/lexical_analysis/Lexer.java | 428c2289495ae2354c7df2391335d9b9f746013d | [] | no_license | suppressf0rce/groove | https://github.com/suppressf0rce/groove | 000f1c418786127012274c67d7659e0b341edf2a | 1d4641c419106184c7b746d22c7ac5d45b249479 | refs/heads/master | 2021-09-14T11:10:12.105000 | 2018-05-12T13:26:16 | 2018-05-12T13:26:16 | 115,052,203 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lexical_analysis;
import java.util.HashMap;
public class Lexer implements Cloneable{
//Variables
//------------------------------------------------------------------------------------------------------------------
private String text;
public int pos;
public Character current_char;
public int line;
private boolean throw_exceptions;
public HashMap<String, Token> RESERVED_KEYWORDS;
public Lexer(Lexer lexer){
this.text = lexer.text;
this.pos = lexer.pos;
this.current_char = lexer.current_char;
this.line = lexer.line;
this.throw_exceptions = lexer.isThrow_exceptions();
this.RESERVED_KEYWORDS = lexer.RESERVED_KEYWORDS;
}
public Lexer(String text, boolean throw_exceptions){
this.text = text;
this.throw_exceptions = throw_exceptions;
pos = 0;
current_char = text.charAt(pos);
line = 1;
RESERVED_KEYWORDS = new HashMap<>();
//Initializing HashMap of the keywords
RESERVED_KEYWORDS.put("void", new Token(TokenType.VOID, "void"));
RESERVED_KEYWORDS.put("boolean", new Token(TokenType.BOOLEAN, "boolean"));
RESERVED_KEYWORDS.put("int", new Token(TokenType.INT, "int"));
RESERVED_KEYWORDS.put("long", new Token(TokenType.LONG, "long"));
RESERVED_KEYWORDS.put("float", new Token(TokenType.FLOAT, "float"));
RESERVED_KEYWORDS.put("double", new Token(TokenType.DOUBLE, "double"));
RESERVED_KEYWORDS.put("char", new Token(TokenType.CHAR, "char"));
RESERVED_KEYWORDS.put("string", new Token(TokenType.STRING, "string"));
RESERVED_KEYWORDS.put("package", new Token(TokenType.PACKAGE, "package"));
RESERVED_KEYWORDS.put("import", new Token(TokenType.IMPORT, "import"));
RESERVED_KEYWORDS.put("let", new Token(TokenType.LET, "let"));
RESERVED_KEYWORDS.put("be", new Token(TokenType.BE, "be"));
RESERVED_KEYWORDS.put("function", new Token(TokenType.FUNCTION, "function"));
RESERVED_KEYWORDS.put("class", new Token(TokenType.CLASS, "class"));
RESERVED_KEYWORDS.put("interface", new Token(TokenType.INTERFACE, "interface"));
RESERVED_KEYWORDS.put("enum", new Token(TokenType.ENUM, "enum"));
RESERVED_KEYWORDS.put("extends", new Token(TokenType.EXTENDS, "extends"));
RESERVED_KEYWORDS.put("implements", new Token(TokenType.IMPLEMENTS, "implements"));
RESERVED_KEYWORDS.put("true", new Token(TokenType.BOOLEAN_CONST, "true"));
RESERVED_KEYWORDS.put("false", new Token(TokenType.BOOLEAN_CONST, "false"));
RESERVED_KEYWORDS.put("private", new Token(TokenType.PRIVATE, "private"));
RESERVED_KEYWORDS.put("public", new Token(TokenType.PUBLIC, "public"));
RESERVED_KEYWORDS.put("protected", new Token(TokenType.PROTECTED, "protected"));
RESERVED_KEYWORDS.put("abstract", new Token(TokenType.ABSTRACT, "abstract"));
RESERVED_KEYWORDS.put("static", new Token(TokenType.STATIC, "static"));
RESERVED_KEYWORDS.put("final", new Token(TokenType.FINAL, "final"));
RESERVED_KEYWORDS.put("super", new Token(TokenType.SUPER, "super"));
RESERVED_KEYWORDS.put("break", new Token(TokenType.BREAK, "break"));
RESERVED_KEYWORDS.put("continue", new Token(TokenType.CONTINUE, "continue"));
RESERVED_KEYWORDS.put("return", new Token(TokenType.RETURN, "return"));
RESERVED_KEYWORDS.put("if", new Token(TokenType.IF, "if"));
RESERVED_KEYWORDS.put("else", new Token(TokenType.ELSE, "else"));
RESERVED_KEYWORDS.put("switch", new Token(TokenType.SWITCH, "switch"));
RESERVED_KEYWORDS.put("case", new Token(TokenType.CASE, "case"));
RESERVED_KEYWORDS.put("default", new Token(TokenType.DEFAULT, "default"));
RESERVED_KEYWORDS.put("while", new Token(TokenType.WHILE, "while"));
RESERVED_KEYWORDS.put("for", new Token(TokenType.FOR, "for"));
RESERVED_KEYWORDS.put("do", new Token(TokenType.DO, "do"));
RESERVED_KEYWORDS.put("try", new Token(TokenType.TRY, "try"));
RESERVED_KEYWORDS.put("catch", new Token(TokenType.CATCH, "catch"));
RESERVED_KEYWORDS.put("throw", new Token(TokenType.THROW, "throw"));
RESERVED_KEYWORDS.put("throws", new Token(TokenType.THROWS, "throws"));
RESERVED_KEYWORDS.put("new", new Token(TokenType.NEW, "new"));
RESERVED_KEYWORDS.put("this", new Token(TokenType.THIS, "this"));
RESERVED_KEYWORDS.put("end", new Token(TokenType.END, "end"));
RESERVED_KEYWORDS.put("and", new Token(TokenType.LOG_AND_OP, "&&"));
RESERVED_KEYWORDS.put("or", new Token(TokenType.LOG_OR_OP, "||"));
RESERVED_KEYWORDS.put("is", new Token(TokenType.EQ_OP, "=="));
RESERVED_KEYWORDS.put("not", new Token(TokenType.NE_OP, "!="));
}
//Methods
//------------------------------------------------------------------------------------------------------------------
/**
* Throws and exception and exits compiler if attribute throw_exception
* is set to true other wise prints out the exception on the stderr
* @param message message that will be printed out on stderr
*/
private void error(String message){
if(throw_exceptions) {
try {
throw new Exception("Lexical error: "+message);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.flush();
System.exit(1);
}
}else{
System.err.println("Lexical error: "+message);
System.err.flush();
}
}
/**
* Advance the 'pos' pointer and set the 'current_char' variable.
*/
private void advance(){
pos++;
if(pos > text.length() - 1){
current_char = null;
}else{
current_char = text.charAt(pos);
}
}
/**
* Check next n-th char but don't change state.
* @param n-th number of the peek
* @return char of the peek
*/
public Character peek(int n){
int peek_pos = pos + n;
if(peek_pos > text.length() - 1)
return null;
else
return text.charAt(peek_pos);
}
/**
* Skip all whitespaces between tokens from input
*/
private void skip_whitespace(){
while (current_char != null && (Character.isSpaceChar(current_char) || current_char == '\t')) {
advance();
}
}
/**
* Return a (multi-digit) integer or float consumed from the input.
* @return number Token
*/
private Token number(){
StringBuilder result = new StringBuilder();
while(current_char != null && Character.isDigit(current_char)){
result.append(current_char);
advance();
}
if(current_char != null) {
if (current_char == '.') {
result.append(current_char);
advance();
while (current_char != null && Character.isDigit(current_char)) {
result.append(current_char);
advance();
}
return new Token(TokenType.REAL_CONST, result.toString());
}
}
return new Token(TokenType.INTEGER_CONST, result.toString());
}
/**
* @return String written in code without double quotes
*/
private String string(){
StringBuilder result = new StringBuilder();
advance();
while(current_char != '"'){
if(current_char == null || (peek(1) == '\n' && current_char != '\\'))
error("Unterminated string with '\"' at line: "+line);
result.append(current_char);
advance();
}
advance();
return result.toString();
}
/**
* Handle chars between single quotes
* @return string of that char
*/
private String character(){
advance();
String character = current_char+"";
advance();
if(current_char!=null && current_char != '\'')
error("Unclosed char constant at line: "+line);
advance();
return character;
}
/**
* Handle identifiers and reserved keywords
* @return Token of id
*/
private Token id(){
StringBuilder result = new StringBuilder();
while(current_char != null && Character.isLetterOrDigit(current_char)){
result.append(current_char);
advance();
}
Token token = new Token(TokenType.ID, result.toString());
if(RESERVED_KEYWORDS.containsKey(result.toString())){
token = RESERVED_KEYWORDS.get(result.toString());
}
return token;
}
/**
* Skips single line of the comment
*/
private void single_line_comment(){
while(current_char != '\n' && current_char != null)
advance();
while (current_char != null && current_char == '\n')
advance();
line++;
}
/**
* Skips multi line of the comments until it reaches the end of the comment
*/
private void multi_line_comment(){
advance();
advance();
while ((current_char != null && current_char != '*') || (peek(1) != null && peek(1) != '/')) {
advance();
if (current_char == '\n')
line++;
}
advance();
if(current_char !=null && current_char == '/')
advance();
while(current_char!= null && current_char == '\n')
advance();
}
/**
* Lexical analyzer (also known as scanner or tokenizer)
* This method is responsible for breaking a sentence
* apart into tokens. One token at a time.
* @return Token
*/
public Token get_next_token(){
while(current_char != null){
if(current_char == '\n'){
line ++;
advance();
return new Token(TokenType.EOL, "\n");
}
if (Character.isSpaceChar(current_char) || current_char == '\t') {
skip_whitespace();
continue;
}
if(Character.isLetter(current_char))
return id();
if(Character.isDigit(current_char))
return number();
if(current_char == '\"')
return new Token(TokenType.STRING_CONST, string());
if(current_char == '\'')
return new Token(TokenType.CHAR_CONST, character());
if(current_char == '/' && peek(1) == '/'){
single_line_comment();
continue;
}
if(current_char == '<' && peek(1) == '<' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.LEFT_ASSIGN, "<<=");
}
if(current_char == '>' && peek(1) == '>' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.RIGHT_ASSIGN, ">>=");
}
if(current_char == '*' && peek(1) == '*' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.POW_ASSIGN, "**=");
}
if(current_char == '+' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.ADD_ASSIGN, "+=");
}
if(current_char == '-' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.SUB_ASSIGN, "-=");
}
if(current_char == '*' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.MUL_ASSIGN, "*=");
}
if(current_char == '/' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.DIV_ASSIGN, "/=");
}
if(current_char == '%' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.MOD_ASSIGN, "%=");
}
if(current_char == '&' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.AND_ASSIGN, "&=");
}
if(current_char == '|' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.OR_ASSIGN, "|=");
}
if(current_char == '^' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.XOR_ASSIGN, "^=");
}
if(current_char == '<' && peek(1) == '<'){
advance();
advance();
return new Token(TokenType.LEFT_OP, "<<");
}
if(current_char == '>' && peek(1) == '>'){
advance();
advance();
return new Token(TokenType.RIGHT_OP, ">>");
}
if(current_char == '*' && peek(1) == '*'){
advance();
advance();
return new Token(TokenType.POW_OP, "**");
}
if(current_char == '+' && peek(1) == '+'){
advance();
advance();
return new Token(TokenType.INC_OP, "++");
}
if(current_char == '-' && peek(1) == '-'){
advance();
advance();
return new Token(TokenType.DEC_OP, "--");
}
if(current_char == '&' && peek(1) == '&'){
advance();
advance();
return new Token(TokenType.LOG_AND_OP, "&&");
}
if(current_char == '|' && peek(1) == '|'){
advance();
advance();
return new Token(TokenType.LOG_OR_OP, "||");
}
if(current_char == '<' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.LE_OP, "<=");
}
if(current_char == '>' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.GE_OP, ">=");
}
if(current_char == '=' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.EQ_OP, "==");
}
if(current_char == '!' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.NE_OP, "!=");
}
if(current_char == '/' && peek(1) == '*'){
multi_line_comment();
continue;
}
if(current_char == '<'){
advance();
return new Token(TokenType.LT_OP, "<");
}
if(current_char == '>'){
advance();
return new Token(TokenType.GT_OP, ">");
}
if(current_char == '='){
advance();
return new Token(TokenType.ASSIGN, "=");
}
if(current_char == '!'){
advance();
return new Token(TokenType.LOG_NEG, "!");
}
if(current_char == '&'){
advance();
return new Token(TokenType.AND_OP, "&");
}
if(current_char == '|'){
advance();
return new Token(TokenType.OR_OP, "|");
}
if(current_char == '^'){
advance();
return new Token(TokenType.XOR_OP, "^");
}
if(current_char == '+'){
advance();
return new Token(TokenType.ADD_OP, "+");
}
if(current_char == '-'){
advance();
return new Token(TokenType.SUB_OP, "-");
}
if(current_char == '*'){
advance();
return new Token(TokenType.MUL_OP, "*");
}
if(current_char == '/'){
advance();
return new Token(TokenType.DIV_OP, "/");
}
if(current_char == '%'){
advance();
return new Token(TokenType.MOD_OP, "%");
}
if(current_char == '('){
advance();
return new Token(TokenType.L_PAREN, "(");
}
if(current_char == ')'){
advance();
return new Token(TokenType.R_PAREN, ")");
}
if(current_char == ':'){
advance();
return new Token(TokenType.COLON, ":");
}
if (current_char == ';') {
advance();
return new Token(TokenType.SEMICOLON, ";");
}
if(current_char == '.'){
advance();
return new Token(TokenType.DOT, ".");
}
if(current_char == ','){
advance();
return new Token(TokenType.COMMA, ",");
}
if(current_char == '#'){
single_line_comment();
continue;
}
if(current_char == '?'){
advance();
return new Token(TokenType.QUESTION_MARK, "?");
}
error("Invalid char <"+current_char+"> at line: "+line);
}
return new Token(TokenType.EOF, null);
}
//Getters & setters
//------------------------------------------------------------------------------------------------------------------
public boolean isThrow_exceptions() {
return throw_exceptions;
}
}
| UTF-8 | Java | 18,161 | java | Lexer.java | Java | [] | null | [] | package lexical_analysis;
import java.util.HashMap;
public class Lexer implements Cloneable{
//Variables
//------------------------------------------------------------------------------------------------------------------
private String text;
public int pos;
public Character current_char;
public int line;
private boolean throw_exceptions;
public HashMap<String, Token> RESERVED_KEYWORDS;
public Lexer(Lexer lexer){
this.text = lexer.text;
this.pos = lexer.pos;
this.current_char = lexer.current_char;
this.line = lexer.line;
this.throw_exceptions = lexer.isThrow_exceptions();
this.RESERVED_KEYWORDS = lexer.RESERVED_KEYWORDS;
}
public Lexer(String text, boolean throw_exceptions){
this.text = text;
this.throw_exceptions = throw_exceptions;
pos = 0;
current_char = text.charAt(pos);
line = 1;
RESERVED_KEYWORDS = new HashMap<>();
//Initializing HashMap of the keywords
RESERVED_KEYWORDS.put("void", new Token(TokenType.VOID, "void"));
RESERVED_KEYWORDS.put("boolean", new Token(TokenType.BOOLEAN, "boolean"));
RESERVED_KEYWORDS.put("int", new Token(TokenType.INT, "int"));
RESERVED_KEYWORDS.put("long", new Token(TokenType.LONG, "long"));
RESERVED_KEYWORDS.put("float", new Token(TokenType.FLOAT, "float"));
RESERVED_KEYWORDS.put("double", new Token(TokenType.DOUBLE, "double"));
RESERVED_KEYWORDS.put("char", new Token(TokenType.CHAR, "char"));
RESERVED_KEYWORDS.put("string", new Token(TokenType.STRING, "string"));
RESERVED_KEYWORDS.put("package", new Token(TokenType.PACKAGE, "package"));
RESERVED_KEYWORDS.put("import", new Token(TokenType.IMPORT, "import"));
RESERVED_KEYWORDS.put("let", new Token(TokenType.LET, "let"));
RESERVED_KEYWORDS.put("be", new Token(TokenType.BE, "be"));
RESERVED_KEYWORDS.put("function", new Token(TokenType.FUNCTION, "function"));
RESERVED_KEYWORDS.put("class", new Token(TokenType.CLASS, "class"));
RESERVED_KEYWORDS.put("interface", new Token(TokenType.INTERFACE, "interface"));
RESERVED_KEYWORDS.put("enum", new Token(TokenType.ENUM, "enum"));
RESERVED_KEYWORDS.put("extends", new Token(TokenType.EXTENDS, "extends"));
RESERVED_KEYWORDS.put("implements", new Token(TokenType.IMPLEMENTS, "implements"));
RESERVED_KEYWORDS.put("true", new Token(TokenType.BOOLEAN_CONST, "true"));
RESERVED_KEYWORDS.put("false", new Token(TokenType.BOOLEAN_CONST, "false"));
RESERVED_KEYWORDS.put("private", new Token(TokenType.PRIVATE, "private"));
RESERVED_KEYWORDS.put("public", new Token(TokenType.PUBLIC, "public"));
RESERVED_KEYWORDS.put("protected", new Token(TokenType.PROTECTED, "protected"));
RESERVED_KEYWORDS.put("abstract", new Token(TokenType.ABSTRACT, "abstract"));
RESERVED_KEYWORDS.put("static", new Token(TokenType.STATIC, "static"));
RESERVED_KEYWORDS.put("final", new Token(TokenType.FINAL, "final"));
RESERVED_KEYWORDS.put("super", new Token(TokenType.SUPER, "super"));
RESERVED_KEYWORDS.put("break", new Token(TokenType.BREAK, "break"));
RESERVED_KEYWORDS.put("continue", new Token(TokenType.CONTINUE, "continue"));
RESERVED_KEYWORDS.put("return", new Token(TokenType.RETURN, "return"));
RESERVED_KEYWORDS.put("if", new Token(TokenType.IF, "if"));
RESERVED_KEYWORDS.put("else", new Token(TokenType.ELSE, "else"));
RESERVED_KEYWORDS.put("switch", new Token(TokenType.SWITCH, "switch"));
RESERVED_KEYWORDS.put("case", new Token(TokenType.CASE, "case"));
RESERVED_KEYWORDS.put("default", new Token(TokenType.DEFAULT, "default"));
RESERVED_KEYWORDS.put("while", new Token(TokenType.WHILE, "while"));
RESERVED_KEYWORDS.put("for", new Token(TokenType.FOR, "for"));
RESERVED_KEYWORDS.put("do", new Token(TokenType.DO, "do"));
RESERVED_KEYWORDS.put("try", new Token(TokenType.TRY, "try"));
RESERVED_KEYWORDS.put("catch", new Token(TokenType.CATCH, "catch"));
RESERVED_KEYWORDS.put("throw", new Token(TokenType.THROW, "throw"));
RESERVED_KEYWORDS.put("throws", new Token(TokenType.THROWS, "throws"));
RESERVED_KEYWORDS.put("new", new Token(TokenType.NEW, "new"));
RESERVED_KEYWORDS.put("this", new Token(TokenType.THIS, "this"));
RESERVED_KEYWORDS.put("end", new Token(TokenType.END, "end"));
RESERVED_KEYWORDS.put("and", new Token(TokenType.LOG_AND_OP, "&&"));
RESERVED_KEYWORDS.put("or", new Token(TokenType.LOG_OR_OP, "||"));
RESERVED_KEYWORDS.put("is", new Token(TokenType.EQ_OP, "=="));
RESERVED_KEYWORDS.put("not", new Token(TokenType.NE_OP, "!="));
}
//Methods
//------------------------------------------------------------------------------------------------------------------
/**
* Throws and exception and exits compiler if attribute throw_exception
* is set to true other wise prints out the exception on the stderr
* @param message message that will be printed out on stderr
*/
private void error(String message){
if(throw_exceptions) {
try {
throw new Exception("Lexical error: "+message);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.flush();
System.exit(1);
}
}else{
System.err.println("Lexical error: "+message);
System.err.flush();
}
}
/**
* Advance the 'pos' pointer and set the 'current_char' variable.
*/
private void advance(){
pos++;
if(pos > text.length() - 1){
current_char = null;
}else{
current_char = text.charAt(pos);
}
}
/**
* Check next n-th char but don't change state.
* @param n-th number of the peek
* @return char of the peek
*/
public Character peek(int n){
int peek_pos = pos + n;
if(peek_pos > text.length() - 1)
return null;
else
return text.charAt(peek_pos);
}
/**
* Skip all whitespaces between tokens from input
*/
private void skip_whitespace(){
while (current_char != null && (Character.isSpaceChar(current_char) || current_char == '\t')) {
advance();
}
}
/**
* Return a (multi-digit) integer or float consumed from the input.
* @return number Token
*/
private Token number(){
StringBuilder result = new StringBuilder();
while(current_char != null && Character.isDigit(current_char)){
result.append(current_char);
advance();
}
if(current_char != null) {
if (current_char == '.') {
result.append(current_char);
advance();
while (current_char != null && Character.isDigit(current_char)) {
result.append(current_char);
advance();
}
return new Token(TokenType.REAL_CONST, result.toString());
}
}
return new Token(TokenType.INTEGER_CONST, result.toString());
}
/**
* @return String written in code without double quotes
*/
private String string(){
StringBuilder result = new StringBuilder();
advance();
while(current_char != '"'){
if(current_char == null || (peek(1) == '\n' && current_char != '\\'))
error("Unterminated string with '\"' at line: "+line);
result.append(current_char);
advance();
}
advance();
return result.toString();
}
/**
* Handle chars between single quotes
* @return string of that char
*/
private String character(){
advance();
String character = current_char+"";
advance();
if(current_char!=null && current_char != '\'')
error("Unclosed char constant at line: "+line);
advance();
return character;
}
/**
* Handle identifiers and reserved keywords
* @return Token of id
*/
private Token id(){
StringBuilder result = new StringBuilder();
while(current_char != null && Character.isLetterOrDigit(current_char)){
result.append(current_char);
advance();
}
Token token = new Token(TokenType.ID, result.toString());
if(RESERVED_KEYWORDS.containsKey(result.toString())){
token = RESERVED_KEYWORDS.get(result.toString());
}
return token;
}
/**
* Skips single line of the comment
*/
private void single_line_comment(){
while(current_char != '\n' && current_char != null)
advance();
while (current_char != null && current_char == '\n')
advance();
line++;
}
/**
* Skips multi line of the comments until it reaches the end of the comment
*/
private void multi_line_comment(){
advance();
advance();
while ((current_char != null && current_char != '*') || (peek(1) != null && peek(1) != '/')) {
advance();
if (current_char == '\n')
line++;
}
advance();
if(current_char !=null && current_char == '/')
advance();
while(current_char!= null && current_char == '\n')
advance();
}
/**
* Lexical analyzer (also known as scanner or tokenizer)
* This method is responsible for breaking a sentence
* apart into tokens. One token at a time.
* @return Token
*/
public Token get_next_token(){
while(current_char != null){
if(current_char == '\n'){
line ++;
advance();
return new Token(TokenType.EOL, "\n");
}
if (Character.isSpaceChar(current_char) || current_char == '\t') {
skip_whitespace();
continue;
}
if(Character.isLetter(current_char))
return id();
if(Character.isDigit(current_char))
return number();
if(current_char == '\"')
return new Token(TokenType.STRING_CONST, string());
if(current_char == '\'')
return new Token(TokenType.CHAR_CONST, character());
if(current_char == '/' && peek(1) == '/'){
single_line_comment();
continue;
}
if(current_char == '<' && peek(1) == '<' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.LEFT_ASSIGN, "<<=");
}
if(current_char == '>' && peek(1) == '>' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.RIGHT_ASSIGN, ">>=");
}
if(current_char == '*' && peek(1) == '*' && peek(2) == '='){
advance();
advance();
advance();
return new Token(TokenType.POW_ASSIGN, "**=");
}
if(current_char == '+' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.ADD_ASSIGN, "+=");
}
if(current_char == '-' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.SUB_ASSIGN, "-=");
}
if(current_char == '*' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.MUL_ASSIGN, "*=");
}
if(current_char == '/' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.DIV_ASSIGN, "/=");
}
if(current_char == '%' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.MOD_ASSIGN, "%=");
}
if(current_char == '&' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.AND_ASSIGN, "&=");
}
if(current_char == '|' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.OR_ASSIGN, "|=");
}
if(current_char == '^' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.XOR_ASSIGN, "^=");
}
if(current_char == '<' && peek(1) == '<'){
advance();
advance();
return new Token(TokenType.LEFT_OP, "<<");
}
if(current_char == '>' && peek(1) == '>'){
advance();
advance();
return new Token(TokenType.RIGHT_OP, ">>");
}
if(current_char == '*' && peek(1) == '*'){
advance();
advance();
return new Token(TokenType.POW_OP, "**");
}
if(current_char == '+' && peek(1) == '+'){
advance();
advance();
return new Token(TokenType.INC_OP, "++");
}
if(current_char == '-' && peek(1) == '-'){
advance();
advance();
return new Token(TokenType.DEC_OP, "--");
}
if(current_char == '&' && peek(1) == '&'){
advance();
advance();
return new Token(TokenType.LOG_AND_OP, "&&");
}
if(current_char == '|' && peek(1) == '|'){
advance();
advance();
return new Token(TokenType.LOG_OR_OP, "||");
}
if(current_char == '<' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.LE_OP, "<=");
}
if(current_char == '>' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.GE_OP, ">=");
}
if(current_char == '=' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.EQ_OP, "==");
}
if(current_char == '!' && peek(1) == '='){
advance();
advance();
return new Token(TokenType.NE_OP, "!=");
}
if(current_char == '/' && peek(1) == '*'){
multi_line_comment();
continue;
}
if(current_char == '<'){
advance();
return new Token(TokenType.LT_OP, "<");
}
if(current_char == '>'){
advance();
return new Token(TokenType.GT_OP, ">");
}
if(current_char == '='){
advance();
return new Token(TokenType.ASSIGN, "=");
}
if(current_char == '!'){
advance();
return new Token(TokenType.LOG_NEG, "!");
}
if(current_char == '&'){
advance();
return new Token(TokenType.AND_OP, "&");
}
if(current_char == '|'){
advance();
return new Token(TokenType.OR_OP, "|");
}
if(current_char == '^'){
advance();
return new Token(TokenType.XOR_OP, "^");
}
if(current_char == '+'){
advance();
return new Token(TokenType.ADD_OP, "+");
}
if(current_char == '-'){
advance();
return new Token(TokenType.SUB_OP, "-");
}
if(current_char == '*'){
advance();
return new Token(TokenType.MUL_OP, "*");
}
if(current_char == '/'){
advance();
return new Token(TokenType.DIV_OP, "/");
}
if(current_char == '%'){
advance();
return new Token(TokenType.MOD_OP, "%");
}
if(current_char == '('){
advance();
return new Token(TokenType.L_PAREN, "(");
}
if(current_char == ')'){
advance();
return new Token(TokenType.R_PAREN, ")");
}
if(current_char == ':'){
advance();
return new Token(TokenType.COLON, ":");
}
if (current_char == ';') {
advance();
return new Token(TokenType.SEMICOLON, ";");
}
if(current_char == '.'){
advance();
return new Token(TokenType.DOT, ".");
}
if(current_char == ','){
advance();
return new Token(TokenType.COMMA, ",");
}
if(current_char == '#'){
single_line_comment();
continue;
}
if(current_char == '?'){
advance();
return new Token(TokenType.QUESTION_MARK, "?");
}
error("Invalid char <"+current_char+"> at line: "+line);
}
return new Token(TokenType.EOF, null);
}
//Getters & setters
//------------------------------------------------------------------------------------------------------------------
public boolean isThrow_exceptions() {
return throw_exceptions;
}
}
| 18,161 | 0.471064 | 0.469137 | 571 | 30.805605 | 26.3104 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.726795 | false | false | 4 |
c891a94dd48186a1d744c752531148efe5abee95 | 16,681,653,023,290 | 026e1c23c188a1dd55f28878ddd4d277cecba93f | /app/src/main/java/com/vietis/eatit/ShopDetailsActivity.java | 854c2ff5c3fab82dcf6a417748ead25db6740982 | [] | no_license | AnVuongVan/Grocery | https://github.com/AnVuongVan/Grocery | 9aa889a1218fc13794ebe84087f9b7cdc8a7e4f5 | dcad9e5597026890874af01556bdd207ea38edc3 | refs/heads/master | 2022-12-30T08:08:30.592000 | 2020-10-20T16:00:51 | 2020-10-20T16:00:51 | 305,761,247 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vietis.eatit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
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 com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.vietis.eatit.adapters.AdapterCartItem;
import com.vietis.eatit.adapters.ProductsUser;
import com.vietis.eatit.models.CartItem;
import com.vietis.eatit.models.Products;
import com.vietis.eatit.utils.Constants;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import p32929.androideasysql_library.Column;
import p32929.androideasysql_library.EasyDB;
public class ShopDetailsActivity extends AppCompatActivity {
private TextView shopNameTv, phoneTv, emailTv, openCloseTv, cartCountTv,
deliveryFeeTv, addressTv, filteredProductsTv;
private ImageView shopIv;
private EditText searchProductEt;
private RatingBar ratingBar;
private ImageButton backBtn, callBtn, mapBtn, cartBtn, filterProductBtn, reviewersBtn;
private RecyclerView productsRv;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private List<Products> productsList;
private List<CartItem> cartItemList;
private ProductsUser adapter;
private EasyDB easyDB;
private double myLatitude = 0.0, myLongitude = 0.0;
private String myPhone;
private double shopLatitude, shopLongitude;
private String shopUid, shopName, shopEmail, shopPhone, shopAddress;
private float ratingSum;
public double totalPrice;
public String deliveryFee, promoId, promoTimestamp, promoCode, promoDescription,
promoExpDate, promoMinimumOrderPrice, promoPrice;
public EditText promoCodeEt;
public Button applyBtn;
public boolean isPromoCodeApplied;
public TextView sTotalTv, dFeeTv, totalPriceTv, promoDescriptionTv, discountTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_details);
mapper();
loadMyInfo();
loadShopDetails();
loadShopProducts();
loadReviews();
easyDB = EasyDB.init(this, "ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", "text", "unique"))
.addColumn(new Column("Item_PID", "text", "not null"))
.addColumn(new Column("Item_Name", "text", "not null"))
.addColumn(new Column("Item_Price_Each", "text", "not null"))
.addColumn(new Column("Item_Price", "text", "not null"))
.addColumn(new Column("Item_Quantity", "text", "not null"))
.doneTableColumn();
removeCartData();
cartCount();
searchProductEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
try {
adapter.getFilter().filter(charSequence);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCartDialog();
}
});
callBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialPhone();
}
});
mapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openMap();
}
});
filterProductBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShopDetailsActivity.this);
builder.setTitle("Choose Category")
.setItems(Constants.productAllCategories, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String selected = Constants.productAllCategories[i];
filteredProductsTv.setText(selected);
if (selected.equals("All")) {
loadShopProducts();
} else {
adapter.getFilter().filter(selected);
}
}
}).show();
}
});
reviewersBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ShopDetailsActivity.this, ShopReviewersActivity.class);
intent.putExtra("shopUid", shopUid);
startActivity(intent);
}
});
}
private void loadReviews() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Ratings")
.addValueEventListener(new ValueEventListener() {
@SuppressLint({"DefaultLocale", "SetTextI18n"})
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
ratingSum = 0;
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
float rating = Float.parseFloat((String) Objects.requireNonNull(dataSnapshot.child("ratings").getValue()));
ratingSum += rating;
}
long numberOfReviews = snapshot.getChildrenCount();
float avgRatings = ratingSum/numberOfReviews;
ratingBar.setRating(avgRatings);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void cartCount() {
int count = easyDB.getAllData().getCount();
if (count <= 0) {
cartCountTv.setVisibility(View.GONE);
} else {
cartCountTv.setVisibility(View.VISIBLE);
cartCountTv.setText(String.valueOf(count));
}
}
private void removeCartData() {
easyDB.deleteAllDataFromTable();
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void showCartDialog() {
cartItemList = new ArrayList<>();
View view = LayoutInflater.from(this).inflate(R.layout.dialog_cart, null);
TextView shopNameTv = view.findViewById(R.id.shopNameTv);
sTotalTv = view.findViewById(R.id.sTotalTv);
dFeeTv = view.findViewById(R.id.dFeeTv);
totalPriceTv = view.findViewById(R.id.totalTv);
promoCodeEt = view.findViewById(R.id.promoCodeEt);
promoDescriptionTv = view.findViewById(R.id.promoDescriptionTv);
discountTv = view.findViewById(R.id.discountTv);
FloatingActionButton validateBtn = view.findViewById(R.id.validateBtn);
applyBtn = view.findViewById(R.id.applyBtn);
RecyclerView cartItemRv = view.findViewById(R.id.cartItemsRv);
Button checkoutBtn = view.findViewById(R.id.checkoutBtn);
if (isPromoCodeApplied) {
promoDescriptionTv.setVisibility(View.VISIBLE);
applyBtn.setVisibility(View.VISIBLE);
applyBtn.setText("Applied");
promoCodeEt.setText(promoCode);
promoDescriptionTv.setText(promoDescription);
} else {
promoDescriptionTv.setVisibility(View.GONE);
applyBtn.setVisibility(View.GONE);
applyBtn.setText("Apply Now");
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
shopNameTv.setText(shopName);
EasyDB easyDB = EasyDB.init(this, "ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", "text", "unique"))
.addColumn(new Column("Item_PID", "text", "not null"))
.addColumn(new Column("Item_Name", "text", "not null"))
.addColumn(new Column("Item_Price_Each", "text", "not null"))
.addColumn(new Column("Item_Price", "text", "not null"))
.addColumn(new Column("Item_Quantity", "text", "not null"))
.doneTableColumn();
Cursor cursor = easyDB.getAllData();
while (cursor.moveToNext()) {
String id = cursor.getString(1);
String pId = cursor.getString(2);
String name = cursor.getString(3);
String price = cursor.getString(4);
String cost = cursor.getString(5);
String quantity = cursor.getString(6);
totalPrice += Double.parseDouble(cost);
CartItem cartItem = new CartItem(id, pId, name, price, cost, quantity);
cartItemList.add(cartItem);
}
AdapterCartItem adapterCartItem = new AdapterCartItem(ShopDetailsActivity.this, cartItemList);
cartItemRv.setAdapter(adapterCartItem);
if (isPromoCodeApplied) {
priceWithDiscount();
} else {
priceWithoutDiscount();
}
AlertDialog dialog = builder.create();
dialog.show();
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
totalPrice = 0.00;
}
});
checkoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (myLatitude == 0.0 || myLongitude == 0.0) {
Toast.makeText(ShopDetailsActivity.this, "Please enter your address in your profile", Toast.LENGTH_SHORT).show();
return;
}
if (myPhone == null || myPhone.equals("")) {
Toast.makeText(ShopDetailsActivity.this, "Please enter your phone in your profile", Toast.LENGTH_SHORT).show();
return;
}
if (cartItemList.size() == 0) {
Toast.makeText(ShopDetailsActivity.this, "No product in your cart", Toast.LENGTH_SHORT).show();
return;
}
submitOrder();
}
});
validateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String promotionCode = promoCodeEt.getText().toString().trim();
if (TextUtils.isEmpty(promotionCode)) {
Toast.makeText(ShopDetailsActivity.this, "Please enter promotion code", Toast.LENGTH_SHORT).show();
} else {
checkCodeAvailability(promotionCode);
}
}
});
applyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isPromoCodeApplied = true;
applyBtn.setText("Applied");
priceWithDiscount();
}
});
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void priceWithDiscount() {
discountTv.setText("$" + promoPrice);
dFeeTv.setText("$" + deliveryFee);
sTotalTv.setText("$" + String.format("%.2f", totalPrice));
totalPriceTv.setText("$" + (totalPrice + Double.parseDouble(deliveryFee.replaceAll("$", "")) - Double.parseDouble(promoPrice)));
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void priceWithoutDiscount() {
discountTv.setText("$0");
dFeeTv.setText("$" + deliveryFee);
sTotalTv.setText("$" + String.format("%.2f", totalPrice));
totalPriceTv.setText("$" + (totalPrice + Double.parseDouble(deliveryFee.replaceAll("$", ""))));
}
@SuppressLint("SetTextI18n")
private void checkCodeAvailability(String promotionCode) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Checking promotion code");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
isPromoCodeApplied = false;
applyBtn.setText("Apply Now");
priceWithoutDiscount();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Promotions").orderByChild("promoCode").equalTo(promotionCode)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
progressDialog.dismiss();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
promoId = (String) dataSnapshot.child("id").getValue();
promoTimestamp = (String) dataSnapshot.child("timestamp").getValue();
promoCode = (String) dataSnapshot.child("promoCode").getValue();
promoDescription = (String) dataSnapshot.child("description").getValue();
promoExpDate = (String) dataSnapshot.child("expireDate").getValue();
promoMinimumOrderPrice = (String) dataSnapshot.child("minimumOrderPrice").getValue();
promoPrice = (String) dataSnapshot.child("promoPrice").getValue();
checkCodeExpireDate();
}
} else {
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Invalid promotion code", Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void checkCodeExpireDate() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String todayDate = day + "/" + month + "/" + year;
try {
@SuppressLint("SimpleDateFormat")
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate = simpleDateFormat.parse(todayDate);
Date expireDate = simpleDateFormat.parse(promoExpDate);
assert expireDate != null;
if (expireDate.compareTo(currentDate) >= 0) {
checkMinimumOrderPrice();
} else if (expireDate.compareTo(currentDate) < 0) {
Toast.makeText(this, "The promotion code is expired on", Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
} catch (Exception e) {
e.printStackTrace();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
}
@SuppressLint("DefaultLocale")
private void checkMinimumOrderPrice() {
if (Double.parseDouble(String.format("%.2f", totalPrice)) < Double.parseDouble(promoMinimumOrderPrice)) {
Toast.makeText(this, "This code is valid for order with minimum amount: $" + promoMinimumOrderPrice, Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
} else {
applyBtn.setVisibility(View.VISIBLE);
promoDescriptionTv.setVisibility(View.VISIBLE);
promoDescriptionTv.setText(promoDescription);
}
}
private void submitOrder() {
progressDialog.setMessage("Placing your order...");
progressDialog.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String cost = totalPriceTv.getText().toString().trim().replace("$", "");
Map<String, Object> map = new HashMap<>();
map.put("orderId", timestamp);
map.put("orderTime", timestamp);
map.put("orderStatus", "In Progress");
map.put("orderCost", cost);
map.put("orderBy", firebaseAuth.getUid());
map.put("orderTo", shopUid);
map.put("latitude", myLatitude);
map.put("longitude", myLongitude);
map.put("deliveryFee", deliveryFee);
if (isPromoCodeApplied) {
map.put("discount", promoPrice);
} else {
map.put("discount", "0");
}
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(shopUid).child("Orders");
reference.child(timestamp).setValue(map)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
for (int i = 0; i < cartItemList.size(); i++) {
String pId = cartItemList.get(i).getpId();
String name = cartItemList.get(i).getName();
String cost = cartItemList.get(i).getCost();
String price = cartItemList.get(i).getPrice();
String quantity = cartItemList.get(i).getQuantity();
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("pId", pId);
hashMap.put("name", name);
hashMap.put("cost", cost);
hashMap.put("price", price);
hashMap.put("quantity", quantity);
reference.child(timestamp).child("Items").child(pId).setValue(hashMap);
}
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Your order placed successfully", Toast.LENGTH_SHORT).show();
prepareNotificationMessage(timestamp);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void dialPhone() {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(shopPhone))));
Toast.makeText(this, "Tel: " + shopPhone, Toast.LENGTH_SHORT).show();
}
private void openMap() {
String address = "https://maps.google.com/maps?saddr=" + myLatitude + "," + myLongitude + "&daddr=" + shopLatitude + "," + shopLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(address));
startActivity(intent);
}
private void loadMyInfo() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
myPhone = (String) dataSnapshot.child("phone").getValue();
myLatitude = (double) dataSnapshot.child("latitude").getValue();
myLongitude = (double) dataSnapshot.child("longitude").getValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void loadShopDetails() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).addValueEventListener(new ValueEventListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
shopName = (String) snapshot.child("shopName").getValue();
shopEmail = (String) snapshot.child("email").getValue();
shopPhone = (String) snapshot.child("phone").getValue();
shopAddress = (String) snapshot.child("address").getValue();
shopLatitude = (double) snapshot.child("latitude").getValue();
shopLongitude = (double) snapshot.child("longitude").getValue();
deliveryFee = (String) snapshot.child("deliveryFee").getValue();
String profileImage = (String) snapshot.child("profileImage").getValue();
boolean shopOpen = (boolean) snapshot.child("shopOpen").getValue();
shopNameTv.setText(shopName);
emailTv.setText(shopEmail);
phoneTv.setText(shopPhone);
addressTv.setText(shopAddress);
deliveryFeeTv.setText("Delivery Fee: $" + deliveryFee);
if (shopOpen) {
openCloseTv.setText("Open");
} else {
openCloseTv.setText("Closed");
}
try {
Picasso.get().load(profileImage).placeholder(R.drawable.ic_store_gray)
.into(shopIv);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void loadShopProducts() {
productsList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Products")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
productsList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Products model = dataSnapshot.getValue(Products.class);
productsList.add(model);
}
adapter = new ProductsUser(ShopDetailsActivity.this, productsList);
productsRv.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void prepareNotificationMessage(String orderId) {
String NOTIFICATION_TOPIC = "/topics/" + Constants.FCM_TOPIC;
String NOTIFICATION_TITLE = "New Order " + orderId;
String NOTIFICATION_MESSAGE = "Congratulations...! You have a new order";
String NOTIFICATION_TYPE = "NewOrder";
JSONObject notificationJo = new JSONObject();
JSONObject notificationBodyJo = new JSONObject();
try {
notificationBodyJo.put("notificationType", NOTIFICATION_TYPE);
notificationBodyJo.put("buyerUid", firebaseAuth.getUid());
notificationBodyJo.put("sellerUid", shopUid);
notificationBodyJo.put("orderId", orderId);
notificationBodyJo.put("notificationTitle", NOTIFICATION_TITLE);
notificationBodyJo.put("notificationMessage", NOTIFICATION_MESSAGE);
notificationJo.put("to", NOTIFICATION_TOPIC);
notificationJo.put("data", notificationBodyJo);
} catch (Exception e) {
e.printStackTrace();
}
sendFcmNotification(notificationJo, orderId);
}
private void sendFcmNotification(JSONObject notificationJo, final String orderId) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
intent.putExtra("orderTo", shopUid);
intent.putExtra("orderId", orderId);
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
intent.putExtra("orderTo", shopUid);
intent.putExtra("orderId", orderId);
startActivity(intent);
}
}){
@Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "key=" + Constants.FCM_KEY);
return headers;
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
private void mapper() {
shopNameTv = findViewById(R.id.shopNameTv);
phoneTv = findViewById(R.id.phoneTv);
emailTv = findViewById(R.id.emailTv);
openCloseTv = findViewById(R.id.openCloseTv);
deliveryFeeTv = findViewById(R.id.deliveryFeeTv);
addressTv = findViewById(R.id.addressTv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
cartCountTv = findViewById(R.id.cartCountTv);
shopIv = findViewById(R.id.shopIv);
searchProductEt = findViewById(R.id.searchProductEt);
ratingBar = findViewById(R.id.ratingBar);
backBtn = findViewById(R.id.backBtn);
callBtn = findViewById(R.id.callBtn);
mapBtn = findViewById(R.id.mapBtn);
cartBtn = findViewById(R.id.cartBtn);
reviewersBtn = findViewById(R.id.reviewersBtn);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
firebaseAuth = FirebaseAuth.getInstance();
shopUid = getIntent().getStringExtra("shopUid");
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
}
} | UTF-8 | Java | 29,522 | java | ShopDetailsActivity.java | Java | [] | null | [] | package com.vietis.eatit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
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 com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.vietis.eatit.adapters.AdapterCartItem;
import com.vietis.eatit.adapters.ProductsUser;
import com.vietis.eatit.models.CartItem;
import com.vietis.eatit.models.Products;
import com.vietis.eatit.utils.Constants;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import p32929.androideasysql_library.Column;
import p32929.androideasysql_library.EasyDB;
public class ShopDetailsActivity extends AppCompatActivity {
private TextView shopNameTv, phoneTv, emailTv, openCloseTv, cartCountTv,
deliveryFeeTv, addressTv, filteredProductsTv;
private ImageView shopIv;
private EditText searchProductEt;
private RatingBar ratingBar;
private ImageButton backBtn, callBtn, mapBtn, cartBtn, filterProductBtn, reviewersBtn;
private RecyclerView productsRv;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private List<Products> productsList;
private List<CartItem> cartItemList;
private ProductsUser adapter;
private EasyDB easyDB;
private double myLatitude = 0.0, myLongitude = 0.0;
private String myPhone;
private double shopLatitude, shopLongitude;
private String shopUid, shopName, shopEmail, shopPhone, shopAddress;
private float ratingSum;
public double totalPrice;
public String deliveryFee, promoId, promoTimestamp, promoCode, promoDescription,
promoExpDate, promoMinimumOrderPrice, promoPrice;
public EditText promoCodeEt;
public Button applyBtn;
public boolean isPromoCodeApplied;
public TextView sTotalTv, dFeeTv, totalPriceTv, promoDescriptionTv, discountTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_details);
mapper();
loadMyInfo();
loadShopDetails();
loadShopProducts();
loadReviews();
easyDB = EasyDB.init(this, "ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", "text", "unique"))
.addColumn(new Column("Item_PID", "text", "not null"))
.addColumn(new Column("Item_Name", "text", "not null"))
.addColumn(new Column("Item_Price_Each", "text", "not null"))
.addColumn(new Column("Item_Price", "text", "not null"))
.addColumn(new Column("Item_Quantity", "text", "not null"))
.doneTableColumn();
removeCartData();
cartCount();
searchProductEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
try {
adapter.getFilter().filter(charSequence);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCartDialog();
}
});
callBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialPhone();
}
});
mapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openMap();
}
});
filterProductBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShopDetailsActivity.this);
builder.setTitle("Choose Category")
.setItems(Constants.productAllCategories, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String selected = Constants.productAllCategories[i];
filteredProductsTv.setText(selected);
if (selected.equals("All")) {
loadShopProducts();
} else {
adapter.getFilter().filter(selected);
}
}
}).show();
}
});
reviewersBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ShopDetailsActivity.this, ShopReviewersActivity.class);
intent.putExtra("shopUid", shopUid);
startActivity(intent);
}
});
}
private void loadReviews() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Ratings")
.addValueEventListener(new ValueEventListener() {
@SuppressLint({"DefaultLocale", "SetTextI18n"})
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
ratingSum = 0;
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
float rating = Float.parseFloat((String) Objects.requireNonNull(dataSnapshot.child("ratings").getValue()));
ratingSum += rating;
}
long numberOfReviews = snapshot.getChildrenCount();
float avgRatings = ratingSum/numberOfReviews;
ratingBar.setRating(avgRatings);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void cartCount() {
int count = easyDB.getAllData().getCount();
if (count <= 0) {
cartCountTv.setVisibility(View.GONE);
} else {
cartCountTv.setVisibility(View.VISIBLE);
cartCountTv.setText(String.valueOf(count));
}
}
private void removeCartData() {
easyDB.deleteAllDataFromTable();
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void showCartDialog() {
cartItemList = new ArrayList<>();
View view = LayoutInflater.from(this).inflate(R.layout.dialog_cart, null);
TextView shopNameTv = view.findViewById(R.id.shopNameTv);
sTotalTv = view.findViewById(R.id.sTotalTv);
dFeeTv = view.findViewById(R.id.dFeeTv);
totalPriceTv = view.findViewById(R.id.totalTv);
promoCodeEt = view.findViewById(R.id.promoCodeEt);
promoDescriptionTv = view.findViewById(R.id.promoDescriptionTv);
discountTv = view.findViewById(R.id.discountTv);
FloatingActionButton validateBtn = view.findViewById(R.id.validateBtn);
applyBtn = view.findViewById(R.id.applyBtn);
RecyclerView cartItemRv = view.findViewById(R.id.cartItemsRv);
Button checkoutBtn = view.findViewById(R.id.checkoutBtn);
if (isPromoCodeApplied) {
promoDescriptionTv.setVisibility(View.VISIBLE);
applyBtn.setVisibility(View.VISIBLE);
applyBtn.setText("Applied");
promoCodeEt.setText(promoCode);
promoDescriptionTv.setText(promoDescription);
} else {
promoDescriptionTv.setVisibility(View.GONE);
applyBtn.setVisibility(View.GONE);
applyBtn.setText("Apply Now");
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
shopNameTv.setText(shopName);
EasyDB easyDB = EasyDB.init(this, "ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", "text", "unique"))
.addColumn(new Column("Item_PID", "text", "not null"))
.addColumn(new Column("Item_Name", "text", "not null"))
.addColumn(new Column("Item_Price_Each", "text", "not null"))
.addColumn(new Column("Item_Price", "text", "not null"))
.addColumn(new Column("Item_Quantity", "text", "not null"))
.doneTableColumn();
Cursor cursor = easyDB.getAllData();
while (cursor.moveToNext()) {
String id = cursor.getString(1);
String pId = cursor.getString(2);
String name = cursor.getString(3);
String price = cursor.getString(4);
String cost = cursor.getString(5);
String quantity = cursor.getString(6);
totalPrice += Double.parseDouble(cost);
CartItem cartItem = new CartItem(id, pId, name, price, cost, quantity);
cartItemList.add(cartItem);
}
AdapterCartItem adapterCartItem = new AdapterCartItem(ShopDetailsActivity.this, cartItemList);
cartItemRv.setAdapter(adapterCartItem);
if (isPromoCodeApplied) {
priceWithDiscount();
} else {
priceWithoutDiscount();
}
AlertDialog dialog = builder.create();
dialog.show();
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
totalPrice = 0.00;
}
});
checkoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (myLatitude == 0.0 || myLongitude == 0.0) {
Toast.makeText(ShopDetailsActivity.this, "Please enter your address in your profile", Toast.LENGTH_SHORT).show();
return;
}
if (myPhone == null || myPhone.equals("")) {
Toast.makeText(ShopDetailsActivity.this, "Please enter your phone in your profile", Toast.LENGTH_SHORT).show();
return;
}
if (cartItemList.size() == 0) {
Toast.makeText(ShopDetailsActivity.this, "No product in your cart", Toast.LENGTH_SHORT).show();
return;
}
submitOrder();
}
});
validateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String promotionCode = promoCodeEt.getText().toString().trim();
if (TextUtils.isEmpty(promotionCode)) {
Toast.makeText(ShopDetailsActivity.this, "Please enter promotion code", Toast.LENGTH_SHORT).show();
} else {
checkCodeAvailability(promotionCode);
}
}
});
applyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isPromoCodeApplied = true;
applyBtn.setText("Applied");
priceWithDiscount();
}
});
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void priceWithDiscount() {
discountTv.setText("$" + promoPrice);
dFeeTv.setText("$" + deliveryFee);
sTotalTv.setText("$" + String.format("%.2f", totalPrice));
totalPriceTv.setText("$" + (totalPrice + Double.parseDouble(deliveryFee.replaceAll("$", "")) - Double.parseDouble(promoPrice)));
}
@SuppressLint({"SetTextI18n", "DefaultLocale"})
private void priceWithoutDiscount() {
discountTv.setText("$0");
dFeeTv.setText("$" + deliveryFee);
sTotalTv.setText("$" + String.format("%.2f", totalPrice));
totalPriceTv.setText("$" + (totalPrice + Double.parseDouble(deliveryFee.replaceAll("$", ""))));
}
@SuppressLint("SetTextI18n")
private void checkCodeAvailability(String promotionCode) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Checking promotion code");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
isPromoCodeApplied = false;
applyBtn.setText("Apply Now");
priceWithoutDiscount();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Promotions").orderByChild("promoCode").equalTo(promotionCode)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
progressDialog.dismiss();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
promoId = (String) dataSnapshot.child("id").getValue();
promoTimestamp = (String) dataSnapshot.child("timestamp").getValue();
promoCode = (String) dataSnapshot.child("promoCode").getValue();
promoDescription = (String) dataSnapshot.child("description").getValue();
promoExpDate = (String) dataSnapshot.child("expireDate").getValue();
promoMinimumOrderPrice = (String) dataSnapshot.child("minimumOrderPrice").getValue();
promoPrice = (String) dataSnapshot.child("promoPrice").getValue();
checkCodeExpireDate();
}
} else {
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Invalid promotion code", Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void checkCodeExpireDate() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String todayDate = day + "/" + month + "/" + year;
try {
@SuppressLint("SimpleDateFormat")
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate = simpleDateFormat.parse(todayDate);
Date expireDate = simpleDateFormat.parse(promoExpDate);
assert expireDate != null;
if (expireDate.compareTo(currentDate) >= 0) {
checkMinimumOrderPrice();
} else if (expireDate.compareTo(currentDate) < 0) {
Toast.makeText(this, "The promotion code is expired on", Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
} catch (Exception e) {
e.printStackTrace();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
}
}
@SuppressLint("DefaultLocale")
private void checkMinimumOrderPrice() {
if (Double.parseDouble(String.format("%.2f", totalPrice)) < Double.parseDouble(promoMinimumOrderPrice)) {
Toast.makeText(this, "This code is valid for order with minimum amount: $" + promoMinimumOrderPrice, Toast.LENGTH_SHORT).show();
applyBtn.setVisibility(View.GONE);
promoDescriptionTv.setVisibility(View.GONE);
promoDescriptionTv.setText("");
} else {
applyBtn.setVisibility(View.VISIBLE);
promoDescriptionTv.setVisibility(View.VISIBLE);
promoDescriptionTv.setText(promoDescription);
}
}
private void submitOrder() {
progressDialog.setMessage("Placing your order...");
progressDialog.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String cost = totalPriceTv.getText().toString().trim().replace("$", "");
Map<String, Object> map = new HashMap<>();
map.put("orderId", timestamp);
map.put("orderTime", timestamp);
map.put("orderStatus", "In Progress");
map.put("orderCost", cost);
map.put("orderBy", firebaseAuth.getUid());
map.put("orderTo", shopUid);
map.put("latitude", myLatitude);
map.put("longitude", myLongitude);
map.put("deliveryFee", deliveryFee);
if (isPromoCodeApplied) {
map.put("discount", promoPrice);
} else {
map.put("discount", "0");
}
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(shopUid).child("Orders");
reference.child(timestamp).setValue(map)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
for (int i = 0; i < cartItemList.size(); i++) {
String pId = cartItemList.get(i).getpId();
String name = cartItemList.get(i).getName();
String cost = cartItemList.get(i).getCost();
String price = cartItemList.get(i).getPrice();
String quantity = cartItemList.get(i).getQuantity();
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("pId", pId);
hashMap.put("name", name);
hashMap.put("cost", cost);
hashMap.put("price", price);
hashMap.put("quantity", quantity);
reference.child(timestamp).child("Items").child(pId).setValue(hashMap);
}
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Your order placed successfully", Toast.LENGTH_SHORT).show();
prepareNotificationMessage(timestamp);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void dialPhone() {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(shopPhone))));
Toast.makeText(this, "Tel: " + shopPhone, Toast.LENGTH_SHORT).show();
}
private void openMap() {
String address = "https://maps.google.com/maps?saddr=" + myLatitude + "," + myLongitude + "&daddr=" + shopLatitude + "," + shopLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(address));
startActivity(intent);
}
private void loadMyInfo() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
myPhone = (String) dataSnapshot.child("phone").getValue();
myLatitude = (double) dataSnapshot.child("latitude").getValue();
myLongitude = (double) dataSnapshot.child("longitude").getValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void loadShopDetails() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).addValueEventListener(new ValueEventListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
shopName = (String) snapshot.child("shopName").getValue();
shopEmail = (String) snapshot.child("email").getValue();
shopPhone = (String) snapshot.child("phone").getValue();
shopAddress = (String) snapshot.child("address").getValue();
shopLatitude = (double) snapshot.child("latitude").getValue();
shopLongitude = (double) snapshot.child("longitude").getValue();
deliveryFee = (String) snapshot.child("deliveryFee").getValue();
String profileImage = (String) snapshot.child("profileImage").getValue();
boolean shopOpen = (boolean) snapshot.child("shopOpen").getValue();
shopNameTv.setText(shopName);
emailTv.setText(shopEmail);
phoneTv.setText(shopPhone);
addressTv.setText(shopAddress);
deliveryFeeTv.setText("Delivery Fee: $" + deliveryFee);
if (shopOpen) {
openCloseTv.setText("Open");
} else {
openCloseTv.setText("Closed");
}
try {
Picasso.get().load(profileImage).placeholder(R.drawable.ic_store_gray)
.into(shopIv);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void loadShopProducts() {
productsList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Products")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
productsList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Products model = dataSnapshot.getValue(Products.class);
productsList.add(model);
}
adapter = new ProductsUser(ShopDetailsActivity.this, productsList);
productsRv.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void prepareNotificationMessage(String orderId) {
String NOTIFICATION_TOPIC = "/topics/" + Constants.FCM_TOPIC;
String NOTIFICATION_TITLE = "New Order " + orderId;
String NOTIFICATION_MESSAGE = "Congratulations...! You have a new order";
String NOTIFICATION_TYPE = "NewOrder";
JSONObject notificationJo = new JSONObject();
JSONObject notificationBodyJo = new JSONObject();
try {
notificationBodyJo.put("notificationType", NOTIFICATION_TYPE);
notificationBodyJo.put("buyerUid", firebaseAuth.getUid());
notificationBodyJo.put("sellerUid", shopUid);
notificationBodyJo.put("orderId", orderId);
notificationBodyJo.put("notificationTitle", NOTIFICATION_TITLE);
notificationBodyJo.put("notificationMessage", NOTIFICATION_MESSAGE);
notificationJo.put("to", NOTIFICATION_TOPIC);
notificationJo.put("data", notificationBodyJo);
} catch (Exception e) {
e.printStackTrace();
}
sendFcmNotification(notificationJo, orderId);
}
private void sendFcmNotification(JSONObject notificationJo, final String orderId) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
intent.putExtra("orderTo", shopUid);
intent.putExtra("orderId", orderId);
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
intent.putExtra("orderTo", shopUid);
intent.putExtra("orderId", orderId);
startActivity(intent);
}
}){
@Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "key=" + Constants.FCM_KEY);
return headers;
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
private void mapper() {
shopNameTv = findViewById(R.id.shopNameTv);
phoneTv = findViewById(R.id.phoneTv);
emailTv = findViewById(R.id.emailTv);
openCloseTv = findViewById(R.id.openCloseTv);
deliveryFeeTv = findViewById(R.id.deliveryFeeTv);
addressTv = findViewById(R.id.addressTv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
cartCountTv = findViewById(R.id.cartCountTv);
shopIv = findViewById(R.id.shopIv);
searchProductEt = findViewById(R.id.searchProductEt);
ratingBar = findViewById(R.id.ratingBar);
backBtn = findViewById(R.id.backBtn);
callBtn = findViewById(R.id.callBtn);
mapBtn = findViewById(R.id.mapBtn);
cartBtn = findViewById(R.id.cartBtn);
reviewersBtn = findViewById(R.id.reviewersBtn);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
firebaseAuth = FirebaseAuth.getInstance();
shopUid = getIntent().getStringExtra("shopUid");
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
}
} | 29,522 | 0.586207 | 0.584479 | 693 | 41.60173 | 29.40291 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747475 | false | false | 4 |
1df551380a06ba49a21dad711124f065cfbc3862 | 7,267,084,665,378 | 3f87df2a878de64eccdcac22bb09b8944ba06fd4 | /java/other/jsonrpc/src/main/java/com/example/jsonrpc/demo/ServerAPIImpl.java | 648eeca52d5b29cb7313e5fc7749dd2b088971b7 | [] | no_license | juncevich/workshop | https://github.com/juncevich/workshop | 621d1262a616ea4664198338b712898af9e61a76 | fbaeecfb399be65a315c60d0aa24ecae4067918d | refs/heads/master | 2023-04-30T14:53:43.154000 | 2023-04-15T17:26:53 | 2023-04-15T17:26:53 | 78,441,425 | 0 | 0 | null | false | 2023-03-28T20:52:35 | 2017-01-09T15:27:29 | 2022-01-10T20:51:12 | 2023-03-28T20:52:34 | 100,702 | 0 | 0 | 238 | JavaScript | false | false | package com.example.jsonrpc.demo;
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl;
import org.springframework.stereotype.Service;
@Service
@AutoJsonRpcServiceImpl
public class ServerAPIImpl implements ServerAPI {
@Override
public String concateStrings(String firstString, String secondString) {
return firstString + " " + secondString;
}
}
| UTF-8 | Java | 376 | java | ServerAPIImpl.java | Java | [] | null | [] | package com.example.jsonrpc.demo;
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl;
import org.springframework.stereotype.Service;
@Service
@AutoJsonRpcServiceImpl
public class ServerAPIImpl implements ServerAPI {
@Override
public String concateStrings(String firstString, String secondString) {
return firstString + " " + secondString;
}
}
| 376 | 0.784574 | 0.781915 | 13 | 27.923077 | 24.854845 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 4 |
787c3fe8c67ab842fa11e8badf3ad62e913c007f | 7,267,084,667,018 | 3db9d692c83c9f0da875fd33dd6e0369cbe2bdd7 | /src/main/java/UpdatableFalse/User.java | 96174c3bf044b41428d1f8469999edb4f30211f9 | [] | no_license | dangoldipu/basicHibernate | https://github.com/dangoldipu/basicHibernate | 8df9cd6be72611cc28bffc271c06295432226c7e | 25bd4c5be86fd5f70fa022d2a8dc5f0f2c560c53 | refs/heads/master | 2020-03-07T06:16:56.940000 | 2018-03-29T16:24:09 | 2018-03-29T16:24:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package UpdatableFalse;
import lombok.*;
import org.hibernate.annotations.Formula;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(updatable = false)
private LocalDate creationDate;
}
| UTF-8 | Java | 390 | java | User.java | Java | [] | null | [] | package UpdatableFalse;
import lombok.*;
import org.hibernate.annotations.Formula;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(updatable = false)
private LocalDate creationDate;
}
| 390 | 0.748718 | 0.748718 | 22 | 16.681818 | 14.894741 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 4 |
665dc0ef9b1fd0907937fec567a907f145558736 | 8,830,452,806,046 | afb98455eabb44371be50f34d7b77d1572d9477e | /app/src/main/java/com/tools/security/settings/AboutUsActivity.java | 427df617b009a698a32f975c936f79c9729980ca | [] | no_license | BCsl/private_security | https://github.com/BCsl/private_security | 5070b42377d7b5fe0d8a635b0abea6e00dd7563f | 5680bb85702830d62506f53d2ff1308e819d7aef | refs/heads/master | 2020-03-26T11:17:54.244000 | 2017-10-14T00:22:15 | 2017-10-14T00:22:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tools.security.settings;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.tools.security.R;
import com.tools.security.common.AppConstants;
import com.tools.security.common.BaseActivity;
import com.tools.security.common.SecurityApplication;
import com.tools.security.common.WebActivity;
import com.tools.security.utils.FaceBookShareUtils;
import com.tools.security.utils.KochavaUtils;
import com.tools.security.utils.ToastUtil;
/**
* description:关于我们
* author: xiaodifu
* date: 2016/12/13.
*/
public class AboutUsActivity extends BaseActivity implements View.OnClickListener {
private TextView mVersionName;
private static final int SHARE_COMPLETE = 0; //成功
private static final int SHARE_CANCEL = 1; //取消
private static final int SHARE_ERROR = 2; //错误
private TextView mPrivacyPolicyBtn, mEulaBtn;
private CallbackManager callbackManager ;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SHARE_COMPLETE:
break;
case SHARE_CANCEL:
break;
case SHARE_ERROR:
ToastUtil.showShort("Network is weak, please try again");
break;
default:
break;
}
}
};
private FacebookCallback facebookCallback = new FacebookCallback() {
@Override
public void onSuccess(Object o) {
mHandler.sendEmptyMessage(SHARE_COMPLETE);
}
@Override
public void onCancel() {
mHandler.sendEmptyMessage(SHARE_CANCEL);
}
@Override
public void onError(FacebookException error) {
mHandler.sendEmptyMessage(SHARE_ERROR);
Log.i("facebook_error", error.toString());
}
};
@Override
protected int getContentViewId() {
return R.layout.activity_about;
}
@Override
protected void init() {
mVersionName = (TextView) findViewById(R.id.version_name);
mPrivacyPolicyBtn = (TextView) findViewById(R.id.privacy_policy_btn);
mEulaBtn = (TextView) findViewById(R.id.eula_btn);
mVersionName.setText("Version " + SecurityApplication.getInstance().getVersionName());
mPrivacyPolicyBtn.setOnClickListener(this);
mEulaBtn.setOnClickListener(this);
}
@Override
protected int getOptionsMenuId() {
return R.menu.menu_about_share_facebook;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_share_facebook) {
callbackManager= CallbackManager.Factory.create();
new FaceBookShareUtils(this,callbackManager,facebookCallback)
.share("Ultra Security-Antivirus&App Lock on Google Play",
getResources().getString(R.string.share_facebook_content_dec),
AppConstants.GOOGLE_PLAY_URL);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(AboutUsActivity.this, WebActivity.class);
String url = "";
String title = "";
switch (v.getId()) {
case R.id.privacy_policy_btn:
KochavaUtils.tracker(AppConstants.CLICK_ABOUT_PRIVACY);
url = AppConstants.PROVACY_POLICY_URL;
title = getString(R.string.privacy_policy);
break;
case R.id.eula_btn:
KochavaUtils.tracker(AppConstants.CLICK_ABOUT_EULA);
url = AppConstants.EULA_URL;
title = getString(R.string.eula);
break;
}
intent.putExtra("url", url);
intent.putExtra("title", title);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}
| UTF-8 | Java | 4,640 | java | AboutUsActivity.java | Java | [
{
"context": "ls.ToastUtil;\n\n\n/**\n * description:关于我们\n * author: xiaodifu\n * date: 2016/12/13.\n */\n\npublic class AboutUsAct",
"end": 760,
"score": 0.9995790719985962,
"start": 752,
"tag": "USERNAME",
"value": "xiaodifu"
}
] | null | [] | package com.tools.security.settings;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.tools.security.R;
import com.tools.security.common.AppConstants;
import com.tools.security.common.BaseActivity;
import com.tools.security.common.SecurityApplication;
import com.tools.security.common.WebActivity;
import com.tools.security.utils.FaceBookShareUtils;
import com.tools.security.utils.KochavaUtils;
import com.tools.security.utils.ToastUtil;
/**
* description:关于我们
* author: xiaodifu
* date: 2016/12/13.
*/
public class AboutUsActivity extends BaseActivity implements View.OnClickListener {
private TextView mVersionName;
private static final int SHARE_COMPLETE = 0; //成功
private static final int SHARE_CANCEL = 1; //取消
private static final int SHARE_ERROR = 2; //错误
private TextView mPrivacyPolicyBtn, mEulaBtn;
private CallbackManager callbackManager ;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SHARE_COMPLETE:
break;
case SHARE_CANCEL:
break;
case SHARE_ERROR:
ToastUtil.showShort("Network is weak, please try again");
break;
default:
break;
}
}
};
private FacebookCallback facebookCallback = new FacebookCallback() {
@Override
public void onSuccess(Object o) {
mHandler.sendEmptyMessage(SHARE_COMPLETE);
}
@Override
public void onCancel() {
mHandler.sendEmptyMessage(SHARE_CANCEL);
}
@Override
public void onError(FacebookException error) {
mHandler.sendEmptyMessage(SHARE_ERROR);
Log.i("facebook_error", error.toString());
}
};
@Override
protected int getContentViewId() {
return R.layout.activity_about;
}
@Override
protected void init() {
mVersionName = (TextView) findViewById(R.id.version_name);
mPrivacyPolicyBtn = (TextView) findViewById(R.id.privacy_policy_btn);
mEulaBtn = (TextView) findViewById(R.id.eula_btn);
mVersionName.setText("Version " + SecurityApplication.getInstance().getVersionName());
mPrivacyPolicyBtn.setOnClickListener(this);
mEulaBtn.setOnClickListener(this);
}
@Override
protected int getOptionsMenuId() {
return R.menu.menu_about_share_facebook;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_share_facebook) {
callbackManager= CallbackManager.Factory.create();
new FaceBookShareUtils(this,callbackManager,facebookCallback)
.share("Ultra Security-Antivirus&App Lock on Google Play",
getResources().getString(R.string.share_facebook_content_dec),
AppConstants.GOOGLE_PLAY_URL);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(AboutUsActivity.this, WebActivity.class);
String url = "";
String title = "";
switch (v.getId()) {
case R.id.privacy_policy_btn:
KochavaUtils.tracker(AppConstants.CLICK_ABOUT_PRIVACY);
url = AppConstants.PROVACY_POLICY_URL;
title = getString(R.string.privacy_policy);
break;
case R.id.eula_btn:
KochavaUtils.tracker(AppConstants.CLICK_ABOUT_EULA);
url = AppConstants.EULA_URL;
title = getString(R.string.eula);
break;
}
intent.putExtra("url", url);
intent.putExtra("title", title);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}
| 4,640 | 0.633117 | 0.630736 | 143 | 31.307692 | 23.920683 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573427 | false | false | 4 |
d5c279582f3a2b12dafa944b7754346985f1f4ed | 34,222,299,464,008 | 6b7232478718ecf23ea33f86820c6440782de3d6 | /src/HashTable/No349IntersectionOfTwoArrays.java | e3f16474a30b30ec41a483d22770272c78f92860 | [] | no_license | shirleywan/leetcode | https://github.com/shirleywan/leetcode | c930b29f77ca36b899ad4456da60adda674a8b81 | d470f8cb6805a9759d961ee36969c84984b66ab4 | refs/heads/master | 2020-03-19T18:05:11.728000 | 2019-05-02T06:04:59 | 2019-05-02T06:04:59 | 136,787,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package HashTable;
import java.lang.reflect.Array;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 349. Intersection of Two Arrays
* Given two arrays, write a function to compute their intersection.
*
* Example 1:
* Input: nums1 = [1,2,2,1], nums2 = [2,2]
* Output: [2]
* Example 2:
* Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* Output: [9,4]
* Note:
* Each element in the result must be unique.!!!
* The result can be in any order.
*/
class Solution349{
/**
* method 1 : two pointer
* 9ms , 12.68%
*/
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
int[] result = {};
return result;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int p = 0 , q = 0;
List<Integer> list = new ArrayList<>();
for( ; p < nums1.length && q < nums2.length ; ){
if(nums1[p] == nums2[q]) {
if(!list.contains(nums1[p])) list.add(nums1[p]);
p++;q++;
}
else{
if(nums1[p] < nums2[q]) p++;
else q++;
}
}
int[] result = new int[list.size()];
for(int i = 0 ; i < result.length ; i++){
result[i] = list.get(i);
}
return result;
}
/**
* method 2 : hashmap
* 7ms , 16.82%
*/
public int[] intersection1(int[] nums1, int[] nums2) {
if(nums1== null || nums1.length==0 || nums2 == null || nums2.length == 0) {
int[] result = {};
return result;
}
Map<Integer , Integer> map = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<>();
int count = 0;
for(int n : nums1){
if(!map.containsKey(n)) {map.put(n , 1);}
}
for(int n : nums2){
if(map.containsKey(n)){
if(!list.contains(n)) list.add(n);
}
}
int[] result = new int[list.size()];
for(int i = 0 ; i < result.length ; i++){
result[i] = list.get(i);
}
return result;
}
/**
* method 3 : hashset
* O(n) -- 2ms , 98.72%
*/
public int[] intersection2(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
intersect.add(nums2[i]);
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (Integer num : intersect) {
result[i++] = num;
}
return result;
}
}
public class No349IntersectionOfTwoArrays {
public static void main(String[] args){
int[] num1 = {1,2,2,1};
int[] num2 = {2,2};
System.out.println(Arrays.toString(new Solution349().intersection(num1 , num2)));
}
}
| UTF-8 | Java | 3,199 | java | No349IntersectionOfTwoArrays.java | Java | [] | null | [] | package HashTable;
import java.lang.reflect.Array;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 349. Intersection of Two Arrays
* Given two arrays, write a function to compute their intersection.
*
* Example 1:
* Input: nums1 = [1,2,2,1], nums2 = [2,2]
* Output: [2]
* Example 2:
* Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* Output: [9,4]
* Note:
* Each element in the result must be unique.!!!
* The result can be in any order.
*/
class Solution349{
/**
* method 1 : two pointer
* 9ms , 12.68%
*/
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
int[] result = {};
return result;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int p = 0 , q = 0;
List<Integer> list = new ArrayList<>();
for( ; p < nums1.length && q < nums2.length ; ){
if(nums1[p] == nums2[q]) {
if(!list.contains(nums1[p])) list.add(nums1[p]);
p++;q++;
}
else{
if(nums1[p] < nums2[q]) p++;
else q++;
}
}
int[] result = new int[list.size()];
for(int i = 0 ; i < result.length ; i++){
result[i] = list.get(i);
}
return result;
}
/**
* method 2 : hashmap
* 7ms , 16.82%
*/
public int[] intersection1(int[] nums1, int[] nums2) {
if(nums1== null || nums1.length==0 || nums2 == null || nums2.length == 0) {
int[] result = {};
return result;
}
Map<Integer , Integer> map = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<>();
int count = 0;
for(int n : nums1){
if(!map.containsKey(n)) {map.put(n , 1);}
}
for(int n : nums2){
if(map.containsKey(n)){
if(!list.contains(n)) list.add(n);
}
}
int[] result = new int[list.size()];
for(int i = 0 ; i < result.length ; i++){
result[i] = list.get(i);
}
return result;
}
/**
* method 3 : hashset
* O(n) -- 2ms , 98.72%
*/
public int[] intersection2(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
intersect.add(nums2[i]);
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (Integer num : intersect) {
result[i++] = num;
}
return result;
}
}
public class No349IntersectionOfTwoArrays {
public static void main(String[] args){
int[] num1 = {1,2,2,1};
int[] num2 = {2,2};
System.out.println(Arrays.toString(new Solution349().intersection(num1 , num2)));
}
}
| 3,199 | 0.481052 | 0.446915 | 109 | 28.293577 | 19.763418 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.853211 | false | false | 4 |
ab703893928ebb05557072d422984022c60bd60e | 34,084,860,498,289 | f3afde981fa2bef8e49323a13896bb4dcf74320e | /src/main/java/pages/StatusCodePage.java | 9d55859f65d12f3f1e28a4bbee415b08d5c5f17e | [] | no_license | dimiksonkha/web-automation-selenium-testng | https://github.com/dimiksonkha/web-automation-selenium-testng | 422218e189ffde727096865277f88969b9bad516 | ec7c22b46600ae660d7ce64a2b6fc22028cd2ac7 | refs/heads/main | 2023-07-01T08:01:56.610000 | 2021-08-09T16:44:44 | 2021-08-09T16:44:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class StatusCodePage {
private WebDriver driver;
private By statusOkPageLink = By.cssSelector("a[href=\"status_codes/200\"]");
public StatusCodePage(WebDriver driver){
this.driver = driver;
}
public StatusOkPage clickStatusOKPageLink(){
driver.findElement(statusOkPageLink).click();
return new StatusOkPage(driver);
}
}
| UTF-8 | Java | 465 | java | StatusCodePage.java | Java | [] | null | [] | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class StatusCodePage {
private WebDriver driver;
private By statusOkPageLink = By.cssSelector("a[href=\"status_codes/200\"]");
public StatusCodePage(WebDriver driver){
this.driver = driver;
}
public StatusOkPage clickStatusOKPageLink(){
driver.findElement(statusOkPageLink).click();
return new StatusOkPage(driver);
}
}
| 465 | 0.705376 | 0.698925 | 20 | 22.25 | 22.746153 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
a9f4d1a2e86e544bf766727275ead57aadb92c62 | 38,414,187,517,139 | 7a0d5942b014a547a3e2f9e18af970628a99a4b6 | /src/a8/GOLGameFrame.java | 3af48236d7ce59315d3c95445d95a8cd1bdf0fdd | [] | no_license | quyiyao1999/a8-quyiyao1999 | https://github.com/quyiyao1999/a8-quyiyao1999 | acc73c0d70fd57472b1ea51c862c8cefee5211d1 | 5373b2e60e3a0b8b26509ecb3551ac44f5ec318c | refs/heads/master | 2020-09-24T08:11:19.937000 | 2019-12-04T23:16:11 | 2019-12-04T23:16:11 | 225,710,648 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package a8;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class GOLGameFrame extends JFrame implements Runnable {
private GOLModel model;
GridView grid;
private boolean isRun = false;
private boolean isTorus = false;
protected JButton buttonRun;
protected JButton buttonstep;
protected JButton buttonRandom;
protected JButton buttonTorus;
protected JButton buttonClear;
public GOLGameFrame(GOLModel m) {
super();
this.model = m;
grid = new GridView(model);
getContentPane().add(BorderLayout.CENTER, grid);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
buttonRun = new JButton("Run");
buttonRun.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
if(isRun) {
stopGame();
} else {
startGame();
}
}
});
panel.add(buttonRun);
buttonstep = new JButton("step");
buttonstep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
step();
}
});
panel.add(buttonstep);
buttonRandom = new JButton("Random");
buttonRandom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setRandom();
}
});
panel.add(buttonRandom);
buttonTorus = new JButton("torusOFF");
buttonTorus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isTorus();
}
});
panel.add(buttonTorus);
buttonClear = new JButton("Clear");
buttonClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopGame();
model.setClear();
grid.repaint();
}
});
panel.add(buttonClear);
getContentPane().add(BorderLayout.NORTH, panel);
this.setSize(grid.getPreferredSize());
this.setResizable(true);
WindowListener listener = new WindowAdapter() {
public void windowClosing(WindowEvent w) {
isRun = false;
}
};
this.addWindowListener(listener);
}
public GOLModel getModel() {
return model;
}
public void startGame() {
isRun = true;
Thread t = new Thread(this);
t.start();
buttonRun.setText("Stop");
}
public void step() {
isRun = true;
Thread t = new Thread(this);
t.start();
setTimeout(() -> isRun = false, 5);
}
public void stopGame() {
isRun = false;
buttonRun.setText("Run");
}
public void setRandom() {
model.setRandom();
grid.repaint();
}
public void run() {
if (!isTorus) {
while(isRun) {
try {
model.stepLife();
grid.repaint();
Thread.sleep(model.getDelay());
if(model.getChange() == false) {
this.stopGame();
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
else if (isTorus) {
while(isRun) {
try {
model.stepLifeTorus();
grid.repaint();
Thread.sleep(model.getDelay());
if(model.getChange() == false) {
this.stopGame();
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public void isTorus() {
if (!isTorus) {
isTorus = true;
buttonTorus.setText("torusON");
}
else if (isTorus) {
isTorus = false;
buttonTorus.setText("torusOFF");
}
}
public static void setTimeout(Runnable runnable, int delay){
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
}
catch (Exception e){
System.err.println(e);
}
}).start();
}
}
| UTF-8 | Java | 4,562 | java | GOLGameFrame.java | Java | [] | null | [] | package a8;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class GOLGameFrame extends JFrame implements Runnable {
private GOLModel model;
GridView grid;
private boolean isRun = false;
private boolean isTorus = false;
protected JButton buttonRun;
protected JButton buttonstep;
protected JButton buttonRandom;
protected JButton buttonTorus;
protected JButton buttonClear;
public GOLGameFrame(GOLModel m) {
super();
this.model = m;
grid = new GridView(model);
getContentPane().add(BorderLayout.CENTER, grid);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
buttonRun = new JButton("Run");
buttonRun.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
if(isRun) {
stopGame();
} else {
startGame();
}
}
});
panel.add(buttonRun);
buttonstep = new JButton("step");
buttonstep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
step();
}
});
panel.add(buttonstep);
buttonRandom = new JButton("Random");
buttonRandom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setRandom();
}
});
panel.add(buttonRandom);
buttonTorus = new JButton("torusOFF");
buttonTorus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isTorus();
}
});
panel.add(buttonTorus);
buttonClear = new JButton("Clear");
buttonClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopGame();
model.setClear();
grid.repaint();
}
});
panel.add(buttonClear);
getContentPane().add(BorderLayout.NORTH, panel);
this.setSize(grid.getPreferredSize());
this.setResizable(true);
WindowListener listener = new WindowAdapter() {
public void windowClosing(WindowEvent w) {
isRun = false;
}
};
this.addWindowListener(listener);
}
public GOLModel getModel() {
return model;
}
public void startGame() {
isRun = true;
Thread t = new Thread(this);
t.start();
buttonRun.setText("Stop");
}
public void step() {
isRun = true;
Thread t = new Thread(this);
t.start();
setTimeout(() -> isRun = false, 5);
}
public void stopGame() {
isRun = false;
buttonRun.setText("Run");
}
public void setRandom() {
model.setRandom();
grid.repaint();
}
public void run() {
if (!isTorus) {
while(isRun) {
try {
model.stepLife();
grid.repaint();
Thread.sleep(model.getDelay());
if(model.getChange() == false) {
this.stopGame();
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
else if (isTorus) {
while(isRun) {
try {
model.stepLifeTorus();
grid.repaint();
Thread.sleep(model.getDelay());
if(model.getChange() == false) {
this.stopGame();
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public void isTorus() {
if (!isTorus) {
isTorus = true;
buttonTorus.setText("torusON");
}
else if (isTorus) {
isTorus = false;
buttonTorus.setText("torusOFF");
}
}
public static void setTimeout(Runnable runnable, int delay){
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
}
catch (Exception e){
System.err.println(e);
}
}).start();
}
}
| 4,562 | 0.486629 | 0.48619 | 176 | 24.920454 | 16.905298 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795455 | false | false | 4 |
ec701fd66b18cedc50dd5890d4d761a9ceb14f54 | 36,172,214,603,358 | e43360f16d8139392c7da37cd25e7e3e8e697eb9 | /src/main/java/Basic/DataStructure/StackSequence.java | 0b4a631d8cb47e94b0c81c004fa0e55c4e78f45b | [] | no_license | KBY-TECH/codingTest | https://github.com/KBY-TECH/codingTest | 3b0b73d1907b3ae04c51dbc8c1b4ec9ee916b165 | a4eb5aba9d6cae50a2fa7f82e9521f5de6d09977 | refs/heads/master | 2023-03-24T12:23:14.301000 | 2023-03-24T09:19:30 | 2023-03-24T09:19:30 | 304,711,348 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Basic.DataStructure;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class StackSequence {
public static void main(String args[]) {
ArrayList<Character> ans=new ArrayList<Character>();
Stack<Integer> s = new Stack<Integer>();
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int k = 0;
while (N--> 0) {
int in = sc.nextInt();
if (in > k) {
while (k < in) {
s.push(++k);
ans.add('+');
}
s.pop();
ans.add('-');
}
else {
boolean flag = false;
if(!s.isEmpty())
{
int peek=s.pop();
ans.add('-');
if(in==peek)
{
flag=true;
}
}
if(!flag)
{
System.out.print("NO");
return;
}
}
}
for (char c:ans) {
System.out.println(c);
}
}
} | UTF-8 | Java | 1,208 | java | StackSequence.java | Java | [] | null | [] | package Basic.DataStructure;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class StackSequence {
public static void main(String args[]) {
ArrayList<Character> ans=new ArrayList<Character>();
Stack<Integer> s = new Stack<Integer>();
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int k = 0;
while (N--> 0) {
int in = sc.nextInt();
if (in > k) {
while (k < in) {
s.push(++k);
ans.add('+');
}
s.pop();
ans.add('-');
}
else {
boolean flag = false;
if(!s.isEmpty())
{
int peek=s.pop();
ans.add('-');
if(in==peek)
{
flag=true;
}
}
if(!flag)
{
System.out.print("NO");
return;
}
}
}
for (char c:ans) {
System.out.println(c);
}
}
} | 1,208 | 0.357616 | 0.35596 | 47 | 24.723404 | 12.896811 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446809 | false | false | 4 |
ca48b20f49cf32ec9fd32c5193d6a9594c615406 | 37,967,510,916,237 | c724c0ddb000db6e3c5c24147b67f5935bfc533a | /src/test/java/runnerAndSteps/RunnerTest.java | 4e7485b6aa5077204146e81c1a710b2525c12548 | [] | no_license | hemantshori/GessitAutomatedTests | https://github.com/hemantshori/GessitAutomatedTests | 9549b9b4cbc2dbd1468d260bc59003f610abdd51 | 7d8146937ce5089b8dbc78388908112b6ff3a1d7 | refs/heads/master | 2019-07-27T08:01:58.540000 | 2017-07-04T23:04:38 | 2017-07-04T23:04:38 | 86,405,430 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package runnerAndSteps;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
// This is Runner and the tests will be run from here......Right click and Run as Junit tests
@RunWith(Cucumber.class)
@CucumberOptions
// ************************************** CSS Portal as on 17/10/2016
// OCT***********************************
(format = { "pretty", "html:target/html/result.html" }, tags = { "@Gessit_Regression" },
// *********************for
// SHAKEOUT*************************************
// features = "src/test/resource/com/GESSIT/SanityTestScript.feature")
// ****************for Regression****************************
features = "src/test/resource/com/GESSIT/Gessit_Regression_Suite.feature")
// ********************for wip********************************
// features = "src/test/resource/com/GESSIT/wip.feature")
// ***************************for algo**************************
// features = "src/test/resource/com/GESSIT/algo.feature")
// ********************for wip********************************
// features = "src/test/resource/com/GESSIT/algo.feature")
//******************************************* CSS **************************************
//features = "src/test/resource/com/CSS/Regression_2017.feature")
// ****************************************************************************************
public class RunnerTest {
}
| UTF-8 | Java | 1,420 | java | RunnerTest.java | Java | [] | null | [] | package runnerAndSteps;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
// This is Runner and the tests will be run from here......Right click and Run as Junit tests
@RunWith(Cucumber.class)
@CucumberOptions
// ************************************** CSS Portal as on 17/10/2016
// OCT***********************************
(format = { "pretty", "html:target/html/result.html" }, tags = { "@Gessit_Regression" },
// *********************for
// SHAKEOUT*************************************
// features = "src/test/resource/com/GESSIT/SanityTestScript.feature")
// ****************for Regression****************************
features = "src/test/resource/com/GESSIT/Gessit_Regression_Suite.feature")
// ********************for wip********************************
// features = "src/test/resource/com/GESSIT/wip.feature")
// ***************************for algo**************************
// features = "src/test/resource/com/GESSIT/algo.feature")
// ********************for wip********************************
// features = "src/test/resource/com/GESSIT/algo.feature")
//******************************************* CSS **************************************
//features = "src/test/resource/com/CSS/Regression_2017.feature")
// ****************************************************************************************
public class RunnerTest {
}
| 1,420 | 0.459859 | 0.451408 | 39 | 35.410255 | 32.071011 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 4 |
4da6691e603b22400b281dd637e2f12752f76bc2 | 34,969,623,764,109 | 4213c34fc368fa765fd73770cc59c2e20e7e78b8 | /Level1/Advanced DS/Graphs/countIslands.java | 87cc365e81689960e5fc65397db03676f5332af2 | [] | no_license | shivamgupta57121/PlacementProgram | https://github.com/shivamgupta57121/PlacementProgram | 427a9fa68ec876623bc0c3ff17f9b21b91533efc | c6ea46b5201863fd718afbe957bef8074951776a | refs/heads/master | 2023-04-16T07:33:56.026000 | 2022-01-23T12:10:39 | 2022-01-23T12:10:39 | 343,877,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[m][n];
for (int i = 0; i < arr.length; i++) {
String parts = br.readLine();
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = Integer.parseInt(parts.split(" ")[j]);
}
}
// write your code here
System.out.println(numberOfIslands(arr));
}
public static int numberOfIslands(int arr[][]) {
int nr = arr.length;
int nc = arr[0].length;
boolean visited [][] = new boolean[nr][nc];
int count = 0;
for(int i = 0; i < nr; i++){
for(int j = 0; j < nc; j++){
if(arr[i][j] == 0 && visited[i][j] == false){
markAllConnected(arr, visited, i, j);
count++;
}
}
}
return count;
}
public static void markAllConnected(int arr[][], boolean visited[][], int r, int c){
if(r < 0 || r >= arr.length || c < 0 || c >= arr[0].length || arr[r][c] == 1 || visited[r][c] == true){
return ;
}
visited[r][c] = true;
markAllConnected(arr, visited, r-1, c); // north
markAllConnected(arr, visited, r, c+1); // east
markAllConnected(arr, visited, r+1, c); // south
markAllConnected(arr, visited, r, c-1); // west
// do nothing while returning
}
} | UTF-8 | Java | 1,635 | java | countIslands.java | Java | [] | null | [] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[m][n];
for (int i = 0; i < arr.length; i++) {
String parts = br.readLine();
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = Integer.parseInt(parts.split(" ")[j]);
}
}
// write your code here
System.out.println(numberOfIslands(arr));
}
public static int numberOfIslands(int arr[][]) {
int nr = arr.length;
int nc = arr[0].length;
boolean visited [][] = new boolean[nr][nc];
int count = 0;
for(int i = 0; i < nr; i++){
for(int j = 0; j < nc; j++){
if(arr[i][j] == 0 && visited[i][j] == false){
markAllConnected(arr, visited, i, j);
count++;
}
}
}
return count;
}
public static void markAllConnected(int arr[][], boolean visited[][], int r, int c){
if(r < 0 || r >= arr.length || c < 0 || c >= arr[0].length || arr[r][c] == 1 || visited[r][c] == true){
return ;
}
visited[r][c] = true;
markAllConnected(arr, visited, r-1, c); // north
markAllConnected(arr, visited, r, c+1); // east
markAllConnected(arr, visited, r+1, c); // south
markAllConnected(arr, visited, r, c-1); // west
// do nothing while returning
}
} | 1,635 | 0.510703 | 0.500917 | 51 | 31.078432 | 25.241457 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.137255 | false | false | 4 |
cbfb46d3636d389339eb35d10b102fbaace0eb83 | 36,386,962,969,378 | 415af878b1644b3b68eff7dfc6da4acaa42b7796 | /src/main/java/Entity/Role.java | bfb7b19bc029baacbbf31ed245a6a900294e996f | [] | no_license | PillowCrusher/Kwitter | https://github.com/PillowCrusher/Kwitter | 0c4e40d1fa8fc330560dfc417dc351faac9795c7 | 50882d7552bb9e3fc4060dee1bd19e3a1056d4dc | refs/heads/master | 2022-06-27T07:41:08.598000 | 2019-06-11T16:45:14 | 2019-06-11T16:45:14 | 190,813,045 | 0 | 0 | null | false | 2020-10-13T13:45:10 | 2019-06-07T21:49:10 | 2019-06-11T16:45:30 | 2020-10-13T13:45:09 | 19,368 | 0 | 0 | 2 | Java | false | false | package Entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;
@NamedQueries(
{
@NamedQuery(
name = "kwetterRole.getRole",
query = "SELECT r FROM kwetterRole r WHERE r.email = :email"
)
}
)
@Entity(name = "kwetterRole")
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull
private String email;
@NotNull
private String rolename;
public Role() {
}
public Role(@NotNull String rolename) {
this.rolename = rolename;
this.email = "test";
}
public Role(String rolename, String email) {
this.rolename = rolename;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Role role = (Role) o;
return Objects.equals(getEmail(), role.getEmail()) &&
Objects.equals(getRolename(), role.getRolename());
}
@Override
public int hashCode() {
return Objects.hash(getEmail(), getRolename());
}
}
| UTF-8 | Java | 1,700 | java | Role.java | Java | [] | null | [] | package Entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;
@NamedQueries(
{
@NamedQuery(
name = "kwetterRole.getRole",
query = "SELECT r FROM kwetterRole r WHERE r.email = :email"
)
}
)
@Entity(name = "kwetterRole")
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull
private String email;
@NotNull
private String rolename;
public Role() {
}
public Role(@NotNull String rolename) {
this.rolename = rolename;
this.email = "test";
}
public Role(String rolename, String email) {
this.rolename = rolename;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Role role = (Role) o;
return Objects.equals(getEmail(), role.getEmail()) &&
Objects.equals(getRolename(), role.getRolename());
}
@Override
public int hashCode() {
return Objects.hash(getEmail(), getRolename());
}
}
| 1,700 | 0.572353 | 0.572353 | 79 | 20.518988 | 19.304266 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.379747 | false | false | 4 |
33a1f89f6afaec10115f855b0b23647b158761d5 | 35,519,379,575,915 | 7b263c3da72fe63a09b886d47b18ef59696e723d | /workspace_8/course/src/shoppingCart/VacationScaleTest.java | 09a971cacea9b58f7a581da5f29d47fad92c29b4 | [] | no_license | lindalinda12/Java1 | https://github.com/lindalinda12/Java1 | 1374a7d5b2ff7f011266ec846be25fe3932ec28e | e6168906a5e6019db94060629f67ac227369a39e | refs/heads/master | 2018-01-01T03:24:58.621000 | 2017-11-17T14:37:13 | 2017-11-17T14:37:13 | 69,605,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package shoppingCart;
public class VacationScaleTest {
public static void main(String[] args) {
VacationScale vacation = new VacationScale();
vacation.yearsOfService = 2;
vacation.setVacationScale();
vacation.displayVacationDays();
}
}
| UTF-8 | Java | 259 | java | VacationScaleTest.java | Java | [] | null | [] | package shoppingCart;
public class VacationScaleTest {
public static void main(String[] args) {
VacationScale vacation = new VacationScale();
vacation.yearsOfService = 2;
vacation.setVacationScale();
vacation.displayVacationDays();
}
}
| 259 | 0.725869 | 0.722008 | 16 | 15.1875 | 16.901253 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3125 | false | false | 4 |
9f63fc82367ab4dca478baa1365ccf53117bbbf2 | 38,010,460,595,331 | 69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e | /methods/Method_26243.java | dfc0dca6e5411917d4f8719b65d2800ee1bd51c5 | [] | no_license | P79N6A/icse_20_user_study | https://github.com/P79N6A/icse_20_user_study | 5b9c42c6384502fdc9588430899f257761f1f506 | 8a3676bc96059ea2c4f6d209016f5088a5628f3c | refs/heads/master | 2020-06-24T08:25:22.606000 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | @Override public Description matchMethod(MethodTree tree,VisitorState state){
List<? extends ExpressionTree> thrown=tree.getThrows();
if (thrown.isEmpty()) {
return NO_MATCH;
}
SetMultimap<Symbol,ExpressionTree> exceptionsBySuper=LinkedHashMultimap.create();
for ( ExpressionTree exception : thrown) {
Type type=getType(exception);
do {
type=state.getTypes().supertype(type);
exceptionsBySuper.put(type.tsym,exception);
}
while (!state.getTypes().isSameType(type,state.getSymtab().objectType));
}
Set<ExpressionTree> toRemove=new HashSet<>();
List<String> messages=new ArrayList<>();
for ( ExpressionTree exception : thrown) {
Symbol sym=getSymbol(exception);
if (exceptionsBySuper.containsKey(sym)) {
Set<ExpressionTree> sub=exceptionsBySuper.get(sym);
messages.add(String.format("%s %s of %s",oxfordJoin(", ",sub),sub.size() == 1 ? "is a subtype" : "are subtypes",sym.getSimpleName()));
toRemove.addAll(sub);
}
}
if (toRemove.isEmpty()) {
return NO_MATCH;
}
List<ExpressionTree> delete=ImmutableList.<ExpressionTree>copyOf(Iterables.filter(tree.getThrows(),Predicates.in(toRemove)));
return buildDescription(delete.get(0)).setMessage("Redundant throws clause: " + oxfordJoin("; ",messages)).addFix(SuggestedFixes.deleteExceptions(tree,state,delete)).build();
}
| UTF-8 | Java | 1,356 | java | Method_26243.java | Java | [] | null | [] | @Override public Description matchMethod(MethodTree tree,VisitorState state){
List<? extends ExpressionTree> thrown=tree.getThrows();
if (thrown.isEmpty()) {
return NO_MATCH;
}
SetMultimap<Symbol,ExpressionTree> exceptionsBySuper=LinkedHashMultimap.create();
for ( ExpressionTree exception : thrown) {
Type type=getType(exception);
do {
type=state.getTypes().supertype(type);
exceptionsBySuper.put(type.tsym,exception);
}
while (!state.getTypes().isSameType(type,state.getSymtab().objectType));
}
Set<ExpressionTree> toRemove=new HashSet<>();
List<String> messages=new ArrayList<>();
for ( ExpressionTree exception : thrown) {
Symbol sym=getSymbol(exception);
if (exceptionsBySuper.containsKey(sym)) {
Set<ExpressionTree> sub=exceptionsBySuper.get(sym);
messages.add(String.format("%s %s of %s",oxfordJoin(", ",sub),sub.size() == 1 ? "is a subtype" : "are subtypes",sym.getSimpleName()));
toRemove.addAll(sub);
}
}
if (toRemove.isEmpty()) {
return NO_MATCH;
}
List<ExpressionTree> delete=ImmutableList.<ExpressionTree>copyOf(Iterables.filter(tree.getThrows(),Predicates.in(toRemove)));
return buildDescription(delete.get(0)).setMessage("Redundant throws clause: " + oxfordJoin("; ",messages)).addFix(SuggestedFixes.deleteExceptions(tree,state,delete)).build();
}
| 1,356 | 0.713127 | 0.711652 | 30 | 44.200001 | 41.850845 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 8 |
0ad9aa7f94187a490ff5a664277843fcf7502a1d | 38,414,187,518,916 | 154f12236b3aae62e8c74615ea0e85101601734d | /src/main/java/com/meetu/console/domain/EasyUIResult.java | 7447c180c5c35ad273a33d035d6e4fcaddf364f4 | [] | no_license | StarFire996/meetu_console | https://github.com/StarFire996/meetu_console | c2895b722327b03c909a0efd9fa6529c5ac45709 | fd01fc1bbc1b3018cd158b4a7c352d8834cd4f9e | refs/heads/master | 2021-01-09T20:26:27.318000 | 2016-06-07T02:02:05 | 2016-06-07T02:02:05 | 60,574,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meetu.console.domain;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class EasyUIResult {
private static final ObjectMapper MAPPER = new ObjectMapper();
private Long total;
private List<?> rows;
public EasyUIResult() {
super();
}
public EasyUIResult(Long total, List<?> rows) {
super();
this.total = total;
this.rows = rows;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<?> getRows() {
return rows;
}
public void setRows(List<?> rows) {
this.rows = rows;
}
/**
* 把json格式的数据反序列化为EasyUIResult对象
*
* @param jsonData json格式的数据
* @param clazz 结果集中的元素的类
* @return
*/
public static EasyUIResult formatJsonToEasyUIResult(String jsonData, Class<?> clazz) {
// 判断jsonData不为空
if (StringUtils.isNotBlank(jsonData)) {
try {
// 转换jsonNode,方便解析
JsonNode jsonNode = MAPPER.readTree(jsonData);
// 获取数据总条数
Long total = jsonNode.get("total").asLong();
// 解析rows
// 获取arrayNode,强转
ArrayNode arrayNode = (ArrayNode) jsonNode.get("rows");
// 获取rows
List<?> list = null;
if (arrayNode.isArray()) {
// 使用反序列化方法获取集合
list = MAPPER.readValue(arrayNode.traverse(), MAPPER.getTypeFactory()
.constructCollectionType(List.class, clazz));
}
// 创建EasyUIResult对象
EasyUIResult easyUIResult = new EasyUIResult(total, list);
return easyUIResult;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 如果有问题就返回null
return null;
}
}
| UTF-8 | Java | 2,418 | java | EasyUIResult.java | Java | [] | null | [] | package com.meetu.console.domain;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class EasyUIResult {
private static final ObjectMapper MAPPER = new ObjectMapper();
private Long total;
private List<?> rows;
public EasyUIResult() {
super();
}
public EasyUIResult(Long total, List<?> rows) {
super();
this.total = total;
this.rows = rows;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<?> getRows() {
return rows;
}
public void setRows(List<?> rows) {
this.rows = rows;
}
/**
* 把json格式的数据反序列化为EasyUIResult对象
*
* @param jsonData json格式的数据
* @param clazz 结果集中的元素的类
* @return
*/
public static EasyUIResult formatJsonToEasyUIResult(String jsonData, Class<?> clazz) {
// 判断jsonData不为空
if (StringUtils.isNotBlank(jsonData)) {
try {
// 转换jsonNode,方便解析
JsonNode jsonNode = MAPPER.readTree(jsonData);
// 获取数据总条数
Long total = jsonNode.get("total").asLong();
// 解析rows
// 获取arrayNode,强转
ArrayNode arrayNode = (ArrayNode) jsonNode.get("rows");
// 获取rows
List<?> list = null;
if (arrayNode.isArray()) {
// 使用反序列化方法获取集合
list = MAPPER.readValue(arrayNode.traverse(), MAPPER.getTypeFactory()
.constructCollectionType(List.class, clazz));
}
// 创建EasyUIResult对象
EasyUIResult easyUIResult = new EasyUIResult(total, list);
return easyUIResult;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 如果有问题就返回null
return null;
}
}
| 2,418 | 0.527876 | 0.527434 | 87 | 23.977011 | 22.211615 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.356322 | false | false | 8 |
5d49c86edcae7af46e030277d9078e477c4be485 | 37,692,633,007,042 | e42d699d95bf9ce8cd1927a33c03ad26cf4659e8 | /sst0405/src/main/java/com/jwkj/adapter/YzwAdapter.java | 544a613884bdbc862860e0d089f8b97ef260608b | [
"Apache-2.0"
] | permissive | bingo1118/SST_AS | https://github.com/bingo1118/SST_AS | 4417636503dcfe13d861e5e76c4f735a9b0e2941 | 7577c7fb4190a02ed9abb75a95bec386960ff0df | refs/heads/master | 2020-05-15T11:17:45.614000 | 2019-04-19T07:13:59 | 2019-04-19T07:13:59 | 182,219,314 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jwkj.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.test.jpushServer.R;
import com.jwkj.global.Constants;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class YzwAdapter extends BaseAdapter{
Context context;
String[] str;
HashMap<String, Boolean> states = new HashMap<String, Boolean>();
public YzwAdapter() {
super();
}
public YzwAdapter(Context context, String[] str) {
super();
this.context = context;
this.str = str;
}
class ViewHolder{
public RadioButton mRadioButton;
public TextView mTextView;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return str.length;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return str[arg0];
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(null==convertView){
convertView = LayoutInflater.from(context).inflate(R.layout.list_alarm_type_item, null);
holder = new ViewHolder();
holder.mRadioButton=(RadioButton)convertView.findViewById(R.id.alarm_type_radio);
holder.mTextView=(TextView)convertView.findViewById(R.id.alarm_type_tv);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.mTextView.setText(str[position]);
holder.mRadioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (String key : states.keySet()) {
states.put(key, false);
}
states.put(String.valueOf(position), holder.mRadioButton.isChecked());
YzwAdapter.this.notifyDataSetChanged();
String yuzhiweiNum = holder.mTextView.getText().toString().trim();
Intent intent = new Intent();
intent.setAction("YZWCODE_ACTION");
intent.putExtra("yuzhiweiNum", yuzhiweiNum);
context.sendBroadcast(intent);
}
});
boolean res = false;
if (states.get(String.valueOf(position)) == null
|| states.get(String.valueOf(position)) == false) {
res = false;
states.put(String.valueOf(position), false);
} else{
res = true;
}
holder.mRadioButton.setChecked(res);
return convertView;
}
}
| UTF-8 | Java | 2,867 | java | YzwAdapter.java | Java | [] | null | [] | package com.jwkj.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.test.jpushServer.R;
import com.jwkj.global.Constants;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class YzwAdapter extends BaseAdapter{
Context context;
String[] str;
HashMap<String, Boolean> states = new HashMap<String, Boolean>();
public YzwAdapter() {
super();
}
public YzwAdapter(Context context, String[] str) {
super();
this.context = context;
this.str = str;
}
class ViewHolder{
public RadioButton mRadioButton;
public TextView mTextView;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return str.length;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return str[arg0];
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(null==convertView){
convertView = LayoutInflater.from(context).inflate(R.layout.list_alarm_type_item, null);
holder = new ViewHolder();
holder.mRadioButton=(RadioButton)convertView.findViewById(R.id.alarm_type_radio);
holder.mTextView=(TextView)convertView.findViewById(R.id.alarm_type_tv);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.mTextView.setText(str[position]);
holder.mRadioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (String key : states.keySet()) {
states.put(key, false);
}
states.put(String.valueOf(position), holder.mRadioButton.isChecked());
YzwAdapter.this.notifyDataSetChanged();
String yuzhiweiNum = holder.mTextView.getText().toString().trim();
Intent intent = new Intent();
intent.setAction("YZWCODE_ACTION");
intent.putExtra("yuzhiweiNum", yuzhiweiNum);
context.sendBroadcast(intent);
}
});
boolean res = false;
if (states.get(String.valueOf(position)) == null
|| states.get(String.valueOf(position)) == false) {
res = false;
states.put(String.valueOf(position), false);
} else{
res = true;
}
holder.mRadioButton.setChecked(res);
return convertView;
}
}
| 2,867 | 0.706313 | 0.704569 | 108 | 25.546297 | 21.458998 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.907407 | false | false | 8 |
4a911815e3db862d43979c86b444526b1f080863 | 25,537,875,592,828 | b7f7890e7e9da002c39c25b5d7446e17201cd499 | /Simple Banking System/task/src/banking/CardRepo.java | fbf679f0d51456894854613f6cbde1cbe4caef36 | [] | no_license | ac6776/SimpleBankingSystem | https://github.com/ac6776/SimpleBankingSystem | 8b2cc89ebeda51d190316cf0d3d219e27189d7dd | 46ab1bc5c323c7062cc5d9f2d16792c8b52e147b | refs/heads/master | 2023-02-13T05:37:17.844000 | 2021-01-21T14:05:19 | 2021-01-21T14:05:19 | 331,646,144 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package banking;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CardRepo {
private DBService service;
public CardRepo(String dbName) {
service = DBService.getInstance(dbName);
service.modifyData("CREATE TABLE IF NOT EXISTS card(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"number VARCHAR(16) NOT NULL," +
"pin VARCHAR(4) NOT NULL," +
"balance INTEGER DEFAULT 0)");
}
public void save(String number, String pin) {
service.modifyData(String.format("INSERT INTO card (number, pin) VALUES ('%s', '%s')", number, pin));
}
public Card getCardByNumber(String number) {
Card card = null;
try (ResultSet rs = service.extractData(String.format("SELECT * FROM card WHERE number = %s", number))) {
int id = rs.getInt("id");
String num = rs.getString("number");
String pin = rs.getString("pin");
int balance = rs.getInt("balance");
card = new Card(id, num, pin, balance);
} catch (SQLException e) {
e.printStackTrace();
}
return card;
}
public Integer getBalance(String number) {
try (ResultSet rs = service.extractData(String.format("SELECT * FROM card WHERE number = %s", number))) {
return rs.getInt("balance");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void deposit(Card card, int amount) {
service.modifyData(String.format("UPDATE card SET balance = balance + %d WHERE id = %d", amount, card.getId()));
}
public void delete(Card card) {
service.modifyData(String.format("DELETE FROM card WHERE id = %d", card.getId()));
}
public boolean transfer(Card cardFrom, Card cardTo, int amount) {
try(Connection connection = service.getConnection();
Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
int res = statement.executeUpdate(String.format("UPDATE card SET balance = balance - %d WHERE id = %d AND balance - %d >= 0", amount, cardFrom.getId(), amount));
statement.executeUpdate(String.format("UPDATE card SET balance = balance + %d WHERE id = %d", amount, cardTo.getId()));
if (res == 0) {
connection.rollback();
return false;
}
connection.commit();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
| UTF-8 | Java | 2,682 | java | CardRepo.java | Java | [] | null | [] | package banking;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CardRepo {
private DBService service;
public CardRepo(String dbName) {
service = DBService.getInstance(dbName);
service.modifyData("CREATE TABLE IF NOT EXISTS card(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"number VARCHAR(16) NOT NULL," +
"pin VARCHAR(4) NOT NULL," +
"balance INTEGER DEFAULT 0)");
}
public void save(String number, String pin) {
service.modifyData(String.format("INSERT INTO card (number, pin) VALUES ('%s', '%s')", number, pin));
}
public Card getCardByNumber(String number) {
Card card = null;
try (ResultSet rs = service.extractData(String.format("SELECT * FROM card WHERE number = %s", number))) {
int id = rs.getInt("id");
String num = rs.getString("number");
String pin = rs.getString("pin");
int balance = rs.getInt("balance");
card = new Card(id, num, pin, balance);
} catch (SQLException e) {
e.printStackTrace();
}
return card;
}
public Integer getBalance(String number) {
try (ResultSet rs = service.extractData(String.format("SELECT * FROM card WHERE number = %s", number))) {
return rs.getInt("balance");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void deposit(Card card, int amount) {
service.modifyData(String.format("UPDATE card SET balance = balance + %d WHERE id = %d", amount, card.getId()));
}
public void delete(Card card) {
service.modifyData(String.format("DELETE FROM card WHERE id = %d", card.getId()));
}
public boolean transfer(Card cardFrom, Card cardTo, int amount) {
try(Connection connection = service.getConnection();
Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
int res = statement.executeUpdate(String.format("UPDATE card SET balance = balance - %d WHERE id = %d AND balance - %d >= 0", amount, cardFrom.getId(), amount));
statement.executeUpdate(String.format("UPDATE card SET balance = balance + %d WHERE id = %d", amount, cardTo.getId()));
if (res == 0) {
connection.rollback();
return false;
}
connection.commit();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
| 2,682 | 0.588367 | 0.58613 | 72 | 36.25 | 34.311787 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 8 |
5a3be5d5a5a54c472c18736f990342f1fdd541f3 | 35,296,041,280,381 | e6650815bd64d76d5749058a3f6f8af94267baa6 | /src/test/org/apache/hadoop/conf/TestJsonConfiguration.java | c5dc2943e1ae0b9b5b5cbc6d4a2f46e49895643f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | ymmah/hadoop-20 | https://github.com/ymmah/hadoop-20 | 1763fd3b2ac41e3b59dd4d6cc9f47a04f38193bf | 8987caf62c9f0b87bc9767c5510146c83f205285 | refs/heads/master | 2020-03-27T13:50:43.264000 | 2018-08-29T17:10:21 | 2018-08-29T17:10:21 | 146,631,291 | 0 | 0 | Apache-2.0 | true | 2018-08-29T16:55:33 | 2018-08-29T16:55:33 | 2018-08-29T12:04:21 | 2014-10-10T18:40:53 | 56,550 | 0 | 0 | 0 | null | false | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.conf;
import org.json.JSONObject;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestJsonConfiguration {
private JSONObject createFinalJsonObject() throws Exception {
// Construct json object for core_site
JSONObject core_site = new JSONObject();
core_site.put("io_file_buffer_size", 65536);
core_site.put("hadoop_disable_shell", true);
core_site.put("fs_hdfs_impl", "org.apache.hadoop.hdfs.DistributedAvatarFileSystem");
// Construct json object for hdfs_site
JSONObject hdfs_site = new JSONObject();
hdfs_site.put("fs_ha_retrywrites", true);
hdfs_site.put("dfs_replication", 3);
hdfs_site.put("dfs_replication_max", 512);
hdfs_site.put("dfs_replication_min", 1);
// Construct the final json object consisting for core-site and hdfs-site
JSONObject json = new JSONObject();
json.put("core-site", core_site);
json.put("hdfs-site", hdfs_site);
return json;
}
private void verifyConfigurations(Configuration conf) throws Exception {
// Verify all the configurations are correct.
assertEquals(7, conf.size());
assertEquals(65536, conf.getInt("io.file.buffer.size", -1));
assertEquals(true, conf.getBoolean("hadoop.disable.shell", false));
assertEquals("org.apache.hadoop.hdfs.DistributedAvatarFileSystem",
conf.get("fs.hdfs.impl"));
assertEquals(true, conf.getBoolean("fs.ha.retrywrites", false));
assertEquals(3, conf.getInt("dfs.replication", -1));
assertEquals(512, conf.getInt("dfs.replication.max", -1));
assertEquals(1, conf.getInt("dfs.replication.min", -1));
}
@Test
public void testJsonObject() throws Exception {
verifyConfigurations(new Configuration(createFinalJsonObject()));
}
}
| UTF-8 | Java | 2,580 | java | TestJsonConfiguration.java | Java | [] | null | [] | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.conf;
import org.json.JSONObject;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestJsonConfiguration {
private JSONObject createFinalJsonObject() throws Exception {
// Construct json object for core_site
JSONObject core_site = new JSONObject();
core_site.put("io_file_buffer_size", 65536);
core_site.put("hadoop_disable_shell", true);
core_site.put("fs_hdfs_impl", "org.apache.hadoop.hdfs.DistributedAvatarFileSystem");
// Construct json object for hdfs_site
JSONObject hdfs_site = new JSONObject();
hdfs_site.put("fs_ha_retrywrites", true);
hdfs_site.put("dfs_replication", 3);
hdfs_site.put("dfs_replication_max", 512);
hdfs_site.put("dfs_replication_min", 1);
// Construct the final json object consisting for core-site and hdfs-site
JSONObject json = new JSONObject();
json.put("core-site", core_site);
json.put("hdfs-site", hdfs_site);
return json;
}
private void verifyConfigurations(Configuration conf) throws Exception {
// Verify all the configurations are correct.
assertEquals(7, conf.size());
assertEquals(65536, conf.getInt("io.file.buffer.size", -1));
assertEquals(true, conf.getBoolean("hadoop.disable.shell", false));
assertEquals("org.apache.hadoop.hdfs.DistributedAvatarFileSystem",
conf.get("fs.hdfs.impl"));
assertEquals(true, conf.getBoolean("fs.ha.retrywrites", false));
assertEquals(3, conf.getInt("dfs.replication", -1));
assertEquals(512, conf.getInt("dfs.replication.max", -1));
assertEquals(1, conf.getInt("dfs.replication.min", -1));
}
@Test
public void testJsonObject() throws Exception {
verifyConfigurations(new Configuration(createFinalJsonObject()));
}
}
| 2,580 | 0.721318 | 0.710078 | 65 | 38.692307 | 26.002913 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.830769 | false | false | 8 |
3af6b88c0239cf2d82a41b111590236ef2a98ad9 | 39,324,720,595,886 | 6107626d1648ed8b7a88204d4d3b171706cf61bb | /src/main/java/org/inayat/novo/ringelweb/model/MessageModel.java | d14a8d56c7bf9b52086be0bde36237846adb39ff | [] | no_license | ringelweb/lovewar | https://github.com/ringelweb/lovewar | 7850d6c03dc0ba4c3db5378511d4db9b7d392581 | ecd5ebe11a192aec9e3a8cdb9b4319b2400e02ba | refs/heads/master | 2021-09-13T02:09:19.951000 | 2018-04-23T20:27:07 | 2018-04-23T20:27:07 | 117,245,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.inayat.novo.ringelweb.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "Messages")
@Table(name = "Messages")
public class MessageModel {
@Id
@GeneratedValue
private int msgid;
private int senderId;
private int receiverId;
private String message;
private String returnedMsg;
private String exception;
private Date createdon;
private Boolean success;
public int getMsgid() {
return msgid;
}
public void setMsgid(int msgid) {
this.msgid = msgid;
}
public String getReturnedMsg() {
return returnedMsg;
}
public void setReturnedMsg(String returnedMsg) {
this.returnedMsg = returnedMsg;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
public Date getCreatedon() {
return createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public int getSenderId() {
return senderId;
}
public void setSenderId(int senderId) {
this.senderId = senderId;
}
public int getReceiverId() {
return receiverId;
}
public void setReceiverId(int receiverId) {
this.receiverId = receiverId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| UTF-8 | Java | 1,613 | java | MessageModel.java | Java | [] | null | [] | package org.inayat.novo.ringelweb.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "Messages")
@Table(name = "Messages")
public class MessageModel {
@Id
@GeneratedValue
private int msgid;
private int senderId;
private int receiverId;
private String message;
private String returnedMsg;
private String exception;
private Date createdon;
private Boolean success;
public int getMsgid() {
return msgid;
}
public void setMsgid(int msgid) {
this.msgid = msgid;
}
public String getReturnedMsg() {
return returnedMsg;
}
public void setReturnedMsg(String returnedMsg) {
this.returnedMsg = returnedMsg;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
public Date getCreatedon() {
return createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public int getSenderId() {
return senderId;
}
public void setSenderId(int senderId) {
this.senderId = senderId;
}
public int getReceiverId() {
return receiverId;
}
public void setReceiverId(int receiverId) {
this.receiverId = receiverId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 1,613 | 0.699938 | 0.699938 | 78 | 18.679487 | 14.455497 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.397436 | false | false | 8 |
2d64eb11b947347241aceaf2091f4059dc2484bb | 34,102,040,384,963 | 56f6305a1943bcd63fbd5dead12355d75e865805 | /SelectMultipleFromList/app/src/main/java/craterzone/selectmultiplefromlist/model/Country.java | bc6a81dc7694a31a8b8e38dccd2902b3da060836 | [] | no_license | amanag395/android-projects | https://github.com/amanag395/android-projects | 646f7619609bc6aba4e67a1830e9d7dabe334ae6 | d006f79f938af762d27a6dd1af5c42c79031de08 | refs/heads/master | 2021-01-23T07:49:46.166000 | 2017-04-08T08:09:09 | 2017-04-08T08:09:09 | 86,448,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package craterzone.selectmultiplefromlist.model;
import android.support.annotation.NonNull;
import java.util.Comparator;
/**
* Created by aMAN GUPTA on 3/6/2017.
*/
public class Country {
private String name;
private boolean isSlected;
public Country(String name) {
this.name = name.toUpperCase();
this.isSlected = false;
}
public boolean isSlected() {
return isSlected;
}
public void setSlected() {
isSlected = !isSlected;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
| UTF-8 | Java | 633 | java | Country.java | Java | [
{
"context": ";\n\nimport java.util.Comparator;\n\n/**\n * Created by aMAN GUPTA on 3/6/2017.\n */\n\npublic class Country {\n priv",
"end": 152,
"score": 0.9951959848403931,
"start": 142,
"tag": "NAME",
"value": "aMAN GUPTA"
}
] | null | [] | package craterzone.selectmultiplefromlist.model;
import android.support.annotation.NonNull;
import java.util.Comparator;
/**
* Created by <NAME> on 3/6/2017.
*/
public class Country {
private String name;
private boolean isSlected;
public Country(String name) {
this.name = name.toUpperCase();
this.isSlected = false;
}
public boolean isSlected() {
return isSlected;
}
public void setSlected() {
isSlected = !isSlected;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
| 629 | 0.624013 | 0.614534 | 37 | 16.108109 | 15.170712 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297297 | false | false | 8 |
878e3640aa078198cbee3f8ccd1572562c066975 | 16,836,271,845,008 | 542f0cc719f1ede8cd255686971912af158cda15 | /StopLimit2/src/stoplimit2/CoinRobot.java | ba5df33fcfb00357fb832c3776c304816a1725fd | [] | no_license | yaakoubox/stoplimit2 | https://github.com/yaakoubox/stoplimit2 | e33c056d833012da1c0bf138707c67ef894146fd | 780b2dd72c6dbf4747783f473d0444be37c35625 | refs/heads/master | 2020-04-04T17:13:26.169000 | 2018-11-04T18:31:27 | 2018-11-04T18:31:27 | 156,112,261 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
package stoplimit2;
import java.awt.event.MouseEvent;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
//import javafx.scene.input.KeyCode;
import static javafx.scene.input.KeyCode.PERIOD;
public class CoinRobot {
public static Robot r;
////////////////////////////////////////////////////////////////////////////////
public CoinRobot() throws AWTException {
this.r = new Robot();
}
////////////////////////////////////////////////////////////////////////////////
public void oneLeftClickWithMouse(int x, int y) {
r.mouseMove(x, y);
r.delay(1000);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
//r.mousePress(InputEvent.BUTTON1_MASK);
//r.mouseRelease(InputEvent.BUTTON1_MASK);
}
////////////////////////////////////////////////////////////////////////////////
public void Typing(String s) {
byte[] bytes = s.getBytes();
for (byte b : bytes) {
int code = b;
if (code > 96 && code < 123) {
code = code - 32;
r.delay(5);
r.keyPress(code);
r.keyRelease(code);
} else if (code == 45) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_6);
r.keyRelease(KeyEvent.VK_6);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 46) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 47) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 58) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_COLON);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
if (code == 95) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_8);
r.keyRelease(KeyEvent.VK_8);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
//System.out.println(code);
if (code == 48) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD0);
r.keyRelease(KeyEvent.VK_NUMPAD0);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 49) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD1);
r.keyRelease(KeyEvent.VK_NUMPAD1);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 50) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD2);
r.keyRelease(KeyEvent.VK_NUMPAD2);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 51) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD3);
r.keyRelease(KeyEvent.VK_NUMPAD3);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 52) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD4);
r.keyRelease(KeyEvent.VK_NUMPAD4);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 53) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD5);
r.keyRelease(KeyEvent.VK_NUMPAD5);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 54) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD6);
r.keyRelease(KeyEvent.VK_NUMPAD6);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 55) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD7);
r.keyRelease(KeyEvent.VK_NUMPAD7);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 56) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD8);
r.keyRelease(KeyEvent.VK_NUMPAD8);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 57) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD9);
r.keyRelease(KeyEvent.VK_NUMPAD9);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
public void wait(int time) {
r.delay(time);
}
////////////////////////////////////////////////////////////////////////////////
public void pressKeybord(int keyevent) {
r.keyPress(keyevent);
r.keyRelease(keyevent);
}
public void HoldKeybord(int keyevent) {
r.keyPress(keyevent);
}
public void LetHoldKeybord(int keyevent) {
r.keyRelease(keyevent);
}
public void MouseMove(int x, int y) {
r.mouseMove(x, y);
}
public void oneLeftPressWithMouse(int x, int y) {
r.mouseMove(x, y);
r.mousePress(InputEvent.BUTTON1_MASK);
}
public void LetHoldMouse() {
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
public void HoldMouse() {
r.mousePress(InputEvent.BUTTON1_MASK);
}
public void OneRightClickWithMouse() {
r.mousePress(InputEvent.BUTTON3_MASK);
r.mouseRelease(InputEvent.BUTTON3_MASK);
}
public void PressCopy() {
try {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_CONTROL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public void PressPaste() {
try {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 10,323 | java | CoinRobot.java | Java | [] | null | [] | //
package stoplimit2;
import java.awt.event.MouseEvent;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
//import javafx.scene.input.KeyCode;
import static javafx.scene.input.KeyCode.PERIOD;
public class CoinRobot {
public static Robot r;
////////////////////////////////////////////////////////////////////////////////
public CoinRobot() throws AWTException {
this.r = new Robot();
}
////////////////////////////////////////////////////////////////////////////////
public void oneLeftClickWithMouse(int x, int y) {
r.mouseMove(x, y);
r.delay(1000);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
//r.mousePress(InputEvent.BUTTON1_MASK);
//r.mouseRelease(InputEvent.BUTTON1_MASK);
}
////////////////////////////////////////////////////////////////////////////////
public void Typing(String s) {
byte[] bytes = s.getBytes();
for (byte b : bytes) {
int code = b;
if (code > 96 && code < 123) {
code = code - 32;
r.delay(5);
r.keyPress(code);
r.keyRelease(code);
} else if (code == 45) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_6);
r.keyRelease(KeyEvent.VK_6);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 46) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 47) {
try {
r.delay(5);
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
} else if (code == 58) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_COLON);
r.keyRelease(KeyEvent.VK_COLON);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
if (code == 95) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_8);
r.keyRelease(KeyEvent.VK_8);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
//System.out.println(code);
if (code == 48) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD0);
r.keyRelease(KeyEvent.VK_NUMPAD0);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 49) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD1);
r.keyRelease(KeyEvent.VK_NUMPAD1);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 50) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD2);
r.keyRelease(KeyEvent.VK_NUMPAD2);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 51) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD3);
r.keyRelease(KeyEvent.VK_NUMPAD3);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 52) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD4);
r.keyRelease(KeyEvent.VK_NUMPAD4);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 53) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD5);
r.keyRelease(KeyEvent.VK_NUMPAD5);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 54) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD6);
r.keyRelease(KeyEvent.VK_NUMPAD6);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 55) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD7);
r.keyRelease(KeyEvent.VK_NUMPAD7);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 56) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD8);
r.keyRelease(KeyEvent.VK_NUMPAD8);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
if (code == 57) {
try {
r.delay(5);
//r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_NUMPAD9);
r.keyRelease(KeyEvent.VK_NUMPAD9);
//r.keyRelease(KeyEvent.VK_SHIFT);
} catch (IllegalArgumentException e) {
e.printStackTrace();
//System.out.println("");
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
public void wait(int time) {
r.delay(time);
}
////////////////////////////////////////////////////////////////////////////////
public void pressKeybord(int keyevent) {
r.keyPress(keyevent);
r.keyRelease(keyevent);
}
public void HoldKeybord(int keyevent) {
r.keyPress(keyevent);
}
public void LetHoldKeybord(int keyevent) {
r.keyRelease(keyevent);
}
public void MouseMove(int x, int y) {
r.mouseMove(x, y);
}
public void oneLeftPressWithMouse(int x, int y) {
r.mouseMove(x, y);
r.mousePress(InputEvent.BUTTON1_MASK);
}
public void LetHoldMouse() {
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
public void HoldMouse() {
r.mousePress(InputEvent.BUTTON1_MASK);
}
public void OneRightClickWithMouse() {
r.mousePress(InputEvent.BUTTON3_MASK);
r.mouseRelease(InputEvent.BUTTON3_MASK);
}
public void PressCopy() {
try {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_CONTROL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public void PressPaste() {
try {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
| 10,323 | 0.399496 | 0.390681 | 301 | 32.295681 | 18.739931 | 80 | false | false | 0 | 0 | 0 | 0 | 81 | 0.039233 | 0.498339 | false | false | 8 |
d2e2f1bae7465677766a9a472b2205929295cf3d | 14,310,831,048,896 | a2f6fa1bf2a45e9dbd1365f239bf833638ba83df | /反射/day17/MyInvocationTest.java | 17ab8b8d98337d3bda9da6f616ec3f2432e6433e | [] | no_license | Follow-your-body/JavaLearnBasic | https://github.com/Follow-your-body/JavaLearnBasic | 4f8a070dad347686e06c3bd7a106f98ddfe2f31c | cbe24213f6621870b9ac9a970ff15ab37c7f1146 | refs/heads/master | 2021-01-18T16:53:13.730000 | 2017-04-16T05:29:45 | 2017-04-16T05:29:45 | 86,778,360 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 用动态代理类的格式输出:
* ****************(静态)
* 信息工程学院(静态)
* ****************(静态)
* 自动化(动态)
* ****************(静态)
* */
package day17;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface School {
void perfession(String str);
}
// 被代理类
class Spcialty implements School {
@Override
public void perfession(String str) {
System.out.println(" " + str);
}
}
// 静态代理类
class Bift {
public void bift1() {
System.out.println("**********");
}
public void bift2() {
System.out.println(" 信息工程学院");
}
}
// 代理类
class Proxy1 implements InvocationHandler {
Object obj;
// 获取被代理类对象
public Object getProxy(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Bift bift = new Bift();
bift.bift1();
bift.bift2();
bift.bift1();
Object returnVal = method.invoke(obj, args);
bift.bift1();
return returnVal;
}
}
public class MyInvocationTest {
public static void main(String[] args) {
Spcialty spcialty = new Spcialty();
Proxy1 proxy = new Proxy1();
Object obj = proxy.getProxy(spcialty);
School school = (School)obj;
school.perfession("自动化");
}
}
| GB18030 | Java | 1,488 | java | MyInvocationTest.java | Java | [] | null | [] | /*
* 用动态代理类的格式输出:
* ****************(静态)
* 信息工程学院(静态)
* ****************(静态)
* 自动化(动态)
* ****************(静态)
* */
package day17;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface School {
void perfession(String str);
}
// 被代理类
class Spcialty implements School {
@Override
public void perfession(String str) {
System.out.println(" " + str);
}
}
// 静态代理类
class Bift {
public void bift1() {
System.out.println("**********");
}
public void bift2() {
System.out.println(" 信息工程学院");
}
}
// 代理类
class Proxy1 implements InvocationHandler {
Object obj;
// 获取被代理类对象
public Object getProxy(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Bift bift = new Bift();
bift.bift1();
bift.bift2();
bift.bift1();
Object returnVal = method.invoke(obj, args);
bift.bift1();
return returnVal;
}
}
public class MyInvocationTest {
public static void main(String[] args) {
Spcialty spcialty = new Spcialty();
Proxy1 proxy = new Proxy1();
Object obj = proxy.getProxy(spcialty);
School school = (School)obj;
school.perfession("自动化");
}
}
| 1,488 | 0.643175 | 0.635015 | 69 | 18.536232 | 17.273235 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.246377 | false | false | 8 |
63f146d2f909a46df509bb938637c5b5f7b9fa88 | 15,324,443,315,570 | caa64876e9a42a8720dcbaf28edd1da6828a70c4 | /com/google/common/reflect/TypeCapture.java | 5221de2a1c14943d8d885d0e77bc8600bc454b38 | [] | no_license | linouxis9/mc-dev-1.10.2 | https://github.com/linouxis9/mc-dev-1.10.2 | 488bb40d6823a1a78e752de350ca7270ac689240 | ba3498c936b28fd4bdfa2fb74e97e85f13d8a1a4 | refs/heads/master | 2016-09-22T12:49:41.289000 | 2016-07-03T16:32:17 | 2016-07-03T16:32:17 | 62,504,260 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.common.reflect;
import com.google.common.base.Preconditions;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
abstract class TypeCapture<T> {
TypeCapture() {}
final Type capture() {
Type type = this.getClass().getGenericSuperclass();
Preconditions.checkArgument(type instanceof ParameterizedType, "%s isn\'t parameterized", new Object[] { type});
return ((ParameterizedType) type).getActualTypeArguments()[0];
}
}
| UTF-8 | Java | 500 | java | TypeCapture.java | Java | [] | null | [] | package com.google.common.reflect;
import com.google.common.base.Preconditions;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
abstract class TypeCapture<T> {
TypeCapture() {}
final Type capture() {
Type type = this.getClass().getGenericSuperclass();
Preconditions.checkArgument(type instanceof ParameterizedType, "%s isn\'t parameterized", new Object[] { type});
return ((ParameterizedType) type).getActualTypeArguments()[0];
}
}
| 500 | 0.72 | 0.718 | 17 | 28.411764 | 31.587523 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 8 |
d1ef2aa05e33f7a5cf7d59eed4e7ed8804bca453 | 1,168,231,156,807 | 318b918b520f494fc4cc22e353d5e29126de843c | /work-task/src/main/java/com/example/demo/controller/AdminController.java | 0211e1b34d0724ef47f3c70cbcf8cd3ec1d9adea | [] | no_license | zzzNightlights/work-task-manage | https://github.com/zzzNightlights/work-task-manage | d9199f01fac51d9e4bcaf6ef9d27fb6373e34433 | 927617a7878f2d73ccc84d84115bca69ea5b8c39 | refs/heads/master | 2020-06-23T08:59:29.384000 | 2019-07-29T10:00:29 | 2019-07-29T10:00:29 | 198,578,078 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.controller;
import com.example.demo.entity.Mail;
import com.example.demo.entity.Notice;
import com.example.demo.entity.Task;
import com.example.demo.entity.User;
import com.example.demo.service.NoticeService;
import com.example.demo.service.TaskService;
import com.example.demo.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("/admin")
@Controller
public class AdminController {
@Autowired
NoticeService noticeService;
@Autowired
UserService userService;
@Autowired
TaskService taskService;
@Autowired
RabbitTemplate rabbitTemplate;
@RequestMapping("/admin-index")
public String adminIndex(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
List<Task> newTaskList = taskService.getNewTask();
List<Task> myTaskList = taskService.getTaskByUserId(user.getUserId());
List<User> userList = userService.findAllUserInfo();
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
model.addAttribute("userListSize",userList.size());
model.addAttribute("newTaskListSize",newTaskList.size());
model.addAttribute("myTaskListSize",myTaskList.size());
model.addAttribute("user",user);
return "admin-index";
}
@RequestMapping("/admin-user")
public String adminUser(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-user";
}
@RequestMapping("/admin-notice")
public String adminNotice(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-notice";
}
@RequestMapping("/add-notice.html")
public String addNotice(Model model, HttpSession session){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-add-notice";
}
@RequestMapping("/add-user.html")
public String addUser(Model model, HttpSession session){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-add-user";
}
@RequestMapping("/modify-user")
public String modifyUser(int userId, Model model, HttpSession session){
User userinfo = userService.findUserById(userId);
User user = (User) session.getAttribute("user");
model.addAttribute("userInfo",userinfo);
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-modify-user";
}
@ResponseBody
@RequestMapping("/user-list")
private Map<String,Object> ListUser(){
Map<String,Object> modelMap = new HashMap<String, Object>();
List<User> list = userService.findAllUserInfo();
modelMap.put("userList",list);
return modelMap;
}
@ResponseBody
@RequestMapping("/delete-user")
public String deleteTask(int userId){
boolean flag = userService.removeUserById(userId);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/update-user")
public String updateUser(User user){
User userInfo = userService.findUserById(user.getUserId());
user.setPassword(userInfo.getPassword());
boolean flag = userService.modifyUserInfo(user);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/add-user")
public String addUser(User user){
User userInfo = userService.findUserByUserName(user.getUsername());
if (userInfo!=null){
return "duplicate";
}
boolean flag = userService.addUser(user);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/notice-list")
private Map<String,Object> noticeList(){
Map<String,Object> modelMap = new HashMap<String, Object>();
List<Notice> list = noticeService.findNoticeList();
modelMap.put("noticeList",list);
return modelMap;
}
@ResponseBody
@RequestMapping("/delete-notice")
public String deleteNotice(int noticeId){
boolean flag = noticeService.removeNotice(noticeId);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/add-notice")
public String addTask(Notice notice, HttpSession session){
User user = (User)session.getAttribute("user");
notice.setUserId(user.getUserId());
boolean flag = noticeService.addNotice(notice);
if (flag){
return "success";
}
return "error";
}
@RequestMapping(value = "/logout")
public String logOut(HttpSession session){
session.removeAttribute("user");
return "redirect:../login";
}
@RequestMapping("/admin-message")
public String adminMsg(HttpSession session, Model model, int taskId){
Task task = taskService.getTaskById(taskId);
User user = (User) session.getAttribute("user");
model.addAttribute("task",task);
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-message";
}
@ResponseBody
@RequestMapping("/send-message")
public String sendMsg(Mail mail, int userId, HttpSession session){
User user = userService.findUserById(userId);
User admin = (User)session.getAttribute("user");
mail.setAddress(user.getMail());
mail.setSubject(mail.getSubject()+"-【"+admin.getName()+"】");
rabbitTemplate.convertAndSend("exchange.work-task","work-task",mail);
return "success";
}
}
| UTF-8 | Java | 6,811 | java | AdminController.java | Java | [] | null | [] | package com.example.demo.controller;
import com.example.demo.entity.Mail;
import com.example.demo.entity.Notice;
import com.example.demo.entity.Task;
import com.example.demo.entity.User;
import com.example.demo.service.NoticeService;
import com.example.demo.service.TaskService;
import com.example.demo.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("/admin")
@Controller
public class AdminController {
@Autowired
NoticeService noticeService;
@Autowired
UserService userService;
@Autowired
TaskService taskService;
@Autowired
RabbitTemplate rabbitTemplate;
@RequestMapping("/admin-index")
public String adminIndex(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
List<Task> newTaskList = taskService.getNewTask();
List<Task> myTaskList = taskService.getTaskByUserId(user.getUserId());
List<User> userList = userService.findAllUserInfo();
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
model.addAttribute("userListSize",userList.size());
model.addAttribute("newTaskListSize",newTaskList.size());
model.addAttribute("myTaskListSize",myTaskList.size());
model.addAttribute("user",user);
return "admin-index";
}
@RequestMapping("/admin-user")
public String adminUser(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-user";
}
@RequestMapping("/admin-notice")
public String adminNotice(HttpSession session, Model model){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-notice";
}
@RequestMapping("/add-notice.html")
public String addNotice(Model model, HttpSession session){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-add-notice";
}
@RequestMapping("/add-user.html")
public String addUser(Model model, HttpSession session){
User user = (User) session.getAttribute("user");
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-add-user";
}
@RequestMapping("/modify-user")
public String modifyUser(int userId, Model model, HttpSession session){
User userinfo = userService.findUserById(userId);
User user = (User) session.getAttribute("user");
model.addAttribute("userInfo",userinfo);
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-modify-user";
}
@ResponseBody
@RequestMapping("/user-list")
private Map<String,Object> ListUser(){
Map<String,Object> modelMap = new HashMap<String, Object>();
List<User> list = userService.findAllUserInfo();
modelMap.put("userList",list);
return modelMap;
}
@ResponseBody
@RequestMapping("/delete-user")
public String deleteTask(int userId){
boolean flag = userService.removeUserById(userId);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/update-user")
public String updateUser(User user){
User userInfo = userService.findUserById(user.getUserId());
user.setPassword(userInfo.getPassword());
boolean flag = userService.modifyUserInfo(user);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/add-user")
public String addUser(User user){
User userInfo = userService.findUserByUserName(user.getUsername());
if (userInfo!=null){
return "duplicate";
}
boolean flag = userService.addUser(user);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/notice-list")
private Map<String,Object> noticeList(){
Map<String,Object> modelMap = new HashMap<String, Object>();
List<Notice> list = noticeService.findNoticeList();
modelMap.put("noticeList",list);
return modelMap;
}
@ResponseBody
@RequestMapping("/delete-notice")
public String deleteNotice(int noticeId){
boolean flag = noticeService.removeNotice(noticeId);
if (flag){
return "success";
}
return "error";
}
@ResponseBody
@RequestMapping("/add-notice")
public String addTask(Notice notice, HttpSession session){
User user = (User)session.getAttribute("user");
notice.setUserId(user.getUserId());
boolean flag = noticeService.addNotice(notice);
if (flag){
return "success";
}
return "error";
}
@RequestMapping(value = "/logout")
public String logOut(HttpSession session){
session.removeAttribute("user");
return "redirect:../login";
}
@RequestMapping("/admin-message")
public String adminMsg(HttpSession session, Model model, int taskId){
Task task = taskService.getTaskById(taskId);
User user = (User) session.getAttribute("user");
model.addAttribute("task",task);
model.addAttribute("user",user);
Notice notice = noticeService.findNewNotice();
model.addAttribute("notice",notice);
return "admin-message";
}
@ResponseBody
@RequestMapping("/send-message")
public String sendMsg(Mail mail, int userId, HttpSession session){
User user = userService.findUserById(userId);
User admin = (User)session.getAttribute("user");
mail.setAddress(user.getMail());
mail.setSubject(mail.getSubject()+"-【"+admin.getName()+"】");
rabbitTemplate.convertAndSend("exchange.work-task","work-task",mail);
return "success";
}
}
| 6,811 | 0.661525 | 0.661525 | 184 | 35.994564 | 19.524649 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.788043 | false | false | 8 |
ca15367d64fffbf33085a5b4b944d8f052ad149d | 29,566,554,921,493 | e1446bb45de9adda3d9ddc09d492ae759771a8f5 | /app/src/main/java/com/helha/tacotel/ArticlesPaiementArrayAdapter.java | f21c889073e4dcaf25686848f404037ee9cfd339 | [] | no_license | Melisson-Verstraete/TacotelRepo | https://github.com/Melisson-Verstraete/TacotelRepo | 6d4caae9ce18574d436595d94d6833336e1a18fe | 0b407eadbb7f90d893a7ad02976409d4fc907bc5 | refs/heads/master | 2023-07-18T22:04:41.604000 | 2021-08-16T20:25:58 | 2021-08-16T20:25:58 | 390,723,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.helha.tacotel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import java.text.DecimalFormat;
import java.util.List;
import model.Article;
import model.DownloadImageTask;
public class ArticlesPaiementArrayAdapter extends ArrayAdapter<Article> {
int quantite = 0;
double prixTotal = 0;
public ArticlesPaiementArrayAdapter(@NonNull Context context, int resource, @NonNull List<Article> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @NonNull View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater
.from(getContext())
.inflate(R.layout.list_item_articles_panier, parent, false);
}
final Article article = getItem(position);
populateView(convertView, article);
return convertView;
}
private void populateView(View view, Article article) {
for (int j=0;j<FormPaiementValidationActivity.contients.size();j++) {
if (FormPaiementValidationActivity.contients.get(j).getArticle().getIdArticle() == article.getIdArticle()) {
quantite = FormPaiementValidationActivity.contients.get(j).getQteArticleChoisi();
prixTotal = article.getPrix() * quantite;
}
}
ImageView imgItem = view.findViewById(R.id.img_item_panier);
TextView tvNomItem = view.findViewById(R.id.tv_nom_item_panier);
TextView tvPrixUniItem = view.findViewById(R.id.tv_prix_item_panier);
TextView tvPrixTotItem = view.findViewById(R.id.tv_prix_total_item_panier);
TextView tvQteItem = view.findViewById(R.id.tv_qte_item_panier);
DecimalFormat df = new DecimalFormat("#.00");
tvNomItem.setText(article.getLibelle());
tvPrixUniItem.setText("€ " + article.getPrix() + " HTVA");
tvPrixTotItem.setText("€ " + df.format(prixTotal) + " HTVA");
tvQteItem.setText("x" + quantite);
// CACHER LES BOUTONS
EditText etQteItem = view.findViewById(R.id.et_qte_item_panier);
etQteItem.setVisibility(View.GONE);
ImageView img_supprimer = view.findViewById(R.id.img_supprimer_item_panier);
img_supprimer.setVisibility(View.GONE);
ImageView img_modifier = view.findViewById(R.id.img_modifier_item_panier);
img_modifier.setVisibility(View.GONE);
if(article.getImageURL() != null) {
new DownloadImageTask(imgItem)
.execute(article.getImageURL());
}
}
} | UTF-8 | Java | 2,857 | java | ArticlesPaiementArrayAdapter.java | Java | [] | null | [] | package com.helha.tacotel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import java.text.DecimalFormat;
import java.util.List;
import model.Article;
import model.DownloadImageTask;
public class ArticlesPaiementArrayAdapter extends ArrayAdapter<Article> {
int quantite = 0;
double prixTotal = 0;
public ArticlesPaiementArrayAdapter(@NonNull Context context, int resource, @NonNull List<Article> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @NonNull View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater
.from(getContext())
.inflate(R.layout.list_item_articles_panier, parent, false);
}
final Article article = getItem(position);
populateView(convertView, article);
return convertView;
}
private void populateView(View view, Article article) {
for (int j=0;j<FormPaiementValidationActivity.contients.size();j++) {
if (FormPaiementValidationActivity.contients.get(j).getArticle().getIdArticle() == article.getIdArticle()) {
quantite = FormPaiementValidationActivity.contients.get(j).getQteArticleChoisi();
prixTotal = article.getPrix() * quantite;
}
}
ImageView imgItem = view.findViewById(R.id.img_item_panier);
TextView tvNomItem = view.findViewById(R.id.tv_nom_item_panier);
TextView tvPrixUniItem = view.findViewById(R.id.tv_prix_item_panier);
TextView tvPrixTotItem = view.findViewById(R.id.tv_prix_total_item_panier);
TextView tvQteItem = view.findViewById(R.id.tv_qte_item_panier);
DecimalFormat df = new DecimalFormat("#.00");
tvNomItem.setText(article.getLibelle());
tvPrixUniItem.setText("€ " + article.getPrix() + " HTVA");
tvPrixTotItem.setText("€ " + df.format(prixTotal) + " HTVA");
tvQteItem.setText("x" + quantite);
// CACHER LES BOUTONS
EditText etQteItem = view.findViewById(R.id.et_qte_item_panier);
etQteItem.setVisibility(View.GONE);
ImageView img_supprimer = view.findViewById(R.id.img_supprimer_item_panier);
img_supprimer.setVisibility(View.GONE);
ImageView img_modifier = view.findViewById(R.id.img_modifier_item_panier);
img_modifier.setVisibility(View.GONE);
if(article.getImageURL() != null) {
new DownloadImageTask(imgItem)
.execute(article.getImageURL());
}
}
} | 2,857 | 0.675079 | 0.673326 | 77 | 36.064934 | 30.403921 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675325 | false | false | 8 |
52549b6522f151c9662d3af8ed705df9d58412a4 | 7,387,343,761,673 | 8ffa8357cad7ae2f57c5dbb929671ea6339fe024 | /src/main/java/com/cesi/seatingplan/SeatingPlanApplication.java | e21c8ce6d429678d6c0f07876f363d77d8208da0 | [] | no_license | Retchen/seatingplan | https://github.com/Retchen/seatingplan | 1396baede3f8cce3ee6a3b7aa9aa2950a5feb4f2 | 7a46d9f4bcac467c1ca394023991bf44a9abc47d | refs/heads/master | 2021-07-07T03:06:51.019000 | 2017-10-04T14:51:04 | 2017-10-04T14:51:04 | 105,778,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cesi.seatingplan;
import com.cesi.seatingplan.dao.model.Batiment;
import com.cesi.seatingplan.dao.model.Materiel;
import com.cesi.seatingplan.dao.model.Type;
import com.cesi.seatingplan.dao.repository.BatimentRepository;
import com.cesi.seatingplan.dao.repository.TypeRepository;
import com.cesi.seatingplan.dao.repository.MaterielRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class SeatingPlanApplication implements CommandLineRunner {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Autowired
BatimentRepository batimentRepository;
@Autowired
TypeRepository typeRepository;
@Autowired
MaterielRepository materielRepository;
public static void main(String[] args) {
SpringApplication.run(SeatingPlanApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
LOG.info("Construction table BATIMENT");
List<Batiment> batiments = new ArrayList<>();
batiments.add(new Batiment("Batiment A"));
batiments.add(new Batiment("Batiment B"));
batimentRepository.save(batiments);
LOG.info("FIN == Construction table BATIMENT");
LOG.info("Construction table TYPE");
List<Type> types = new ArrayList<>();
types.add(new Type("Bureau"));
types.add(new Type("Chaise"));
typeRepository.save(types);
LOG.info("FIN == Construction table TYPE");
LOG.info("Construction table MATERIEL");
List<Materiel> materiels = new ArrayList<>();
materiels.add(new Materiel("Materiel 1"));
materiels.add(new Materiel("Materiel 2"));
materielRepository.save(materiels);
LOG.info("FIN == Construction table MATERIEL");
}
} | UTF-8 | Java | 2,099 | java | SeatingPlanApplication.java | Java | [
{
"context": "ateriel 1\"));\n materiels.add(new Materiel(\"Materiel 2\"));\n materielRepository.save(materiels);\n ",
"end": 1983,
"score": 0.9862110018730164,
"start": 1973,
"tag": "NAME",
"value": "Materiel 2"
}
] | null | [] | package com.cesi.seatingplan;
import com.cesi.seatingplan.dao.model.Batiment;
import com.cesi.seatingplan.dao.model.Materiel;
import com.cesi.seatingplan.dao.model.Type;
import com.cesi.seatingplan.dao.repository.BatimentRepository;
import com.cesi.seatingplan.dao.repository.TypeRepository;
import com.cesi.seatingplan.dao.repository.MaterielRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class SeatingPlanApplication implements CommandLineRunner {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Autowired
BatimentRepository batimentRepository;
@Autowired
TypeRepository typeRepository;
@Autowired
MaterielRepository materielRepository;
public static void main(String[] args) {
SpringApplication.run(SeatingPlanApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
LOG.info("Construction table BATIMENT");
List<Batiment> batiments = new ArrayList<>();
batiments.add(new Batiment("Batiment A"));
batiments.add(new Batiment("Batiment B"));
batimentRepository.save(batiments);
LOG.info("FIN == Construction table BATIMENT");
LOG.info("Construction table TYPE");
List<Type> types = new ArrayList<>();
types.add(new Type("Bureau"));
types.add(new Type("Chaise"));
typeRepository.save(types);
LOG.info("FIN == Construction table TYPE");
LOG.info("Construction table MATERIEL");
List<Materiel> materiels = new ArrayList<>();
materiels.add(new Materiel("Materiel 1"));
materiels.add(new Materiel("<NAME>"));
materielRepository.save(materiels);
LOG.info("FIN == Construction table MATERIEL");
}
} | 2,095 | 0.725107 | 0.723202 | 66 | 30.818182 | 23.475267 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 8 |
f630cb268450a7b1497a51f93b95ba39faed3e92 | 2,834,678,475,615 | 4d5929164bcafdde945ded1c1760d8795d49d2f0 | /src/main/java/com/dream/interceptor/ExceptionInterceptor.java | e873dd8f06ce4682a3b4b7454f781305ed0ca5d4 | [] | no_license | duelgenji/china-dream | https://github.com/duelgenji/china-dream | dff4dc27f031308280172cc6f3804520ffc2b084 | cd1cbbb783746b827bd66c31d03e74dcd75620f8 | refs/heads/master | 2020-12-30T15:31:08.064000 | 2018-04-10T15:02:27 | 2018-04-10T15:02:27 | 91,156,235 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dream.interceptor;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
/**
* Created by knight on 16/5/4.
*/
//@ControllerAdvice
public class ExceptionInterceptor {
@ResponseStatus(value= HttpStatus.OK)
public static class UserNotFoundException extends RuntimeException {}
@ExceptionHandler(HttpSessionRequiredException.class)
@ResponseBody
public Object handleConflict(HttpSessionRequiredException exception) throws HttpSessionRequiredException {
System.out.println(exception.getLocalizedMessage());
if(exception.getMessage().contains("currentManager")){
Map<String, Object> res = new HashMap<>();
res.put("success",0);
res.put("message","请先登录");
res.put("error","000");
return res;
}else{
throw exception;
}
}
}
| UTF-8 | Java | 1,163 | java | ExceptionInterceptor.java | Java | [
{
"context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by knight on 16/5/4.\n */\n//@ControllerAdvice\npublic class E",
"end": 400,
"score": 0.9996578693389893,
"start": 394,
"tag": "USERNAME",
"value": "knight"
}
] | null | [] | package com.dream.interceptor;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
/**
* Created by knight on 16/5/4.
*/
//@ControllerAdvice
public class ExceptionInterceptor {
@ResponseStatus(value= HttpStatus.OK)
public static class UserNotFoundException extends RuntimeException {}
@ExceptionHandler(HttpSessionRequiredException.class)
@ResponseBody
public Object handleConflict(HttpSessionRequiredException exception) throws HttpSessionRequiredException {
System.out.println(exception.getLocalizedMessage());
if(exception.getMessage().contains("currentManager")){
Map<String, Object> res = new HashMap<>();
res.put("success",0);
res.put("message","请先登录");
res.put("error","000");
return res;
}else{
throw exception;
}
}
}
| 1,163 | 0.716017 | 0.709091 | 39 | 28.615385 | 26.778881 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487179 | false | false | 8 |
859dad5033ecc3559593e30e83bb71c39ecf32df | 31,671,088,848,149 | a109d961775e2c22005a09ba5fe7e14dc448b6ec | /src/main/java/it/isuri/flightsearch/repository/FlightRepository.java | 8b771b232d3d114c7d67743d27b3fefcdd898498 | [] | no_license | isuri1/flight-search | https://github.com/isuri1/flight-search | fe2902b722506eb5449a46f3c531e3ae6a0dca62 | 8d2567e320881f3fec7f52c16975d59987f8faa9 | refs/heads/master | 2021-06-27T08:00:01.268000 | 2019-11-14T16:12:05 | 2019-11-14T16:12:05 | 220,808,495 | 0 | 0 | null | false | 2021-03-05T07:39:50 | 2019-11-10T15:21:08 | 2019-11-14T16:12:46 | 2021-03-05T07:39:19 | 67 | 0 | 0 | 1 | Java | false | false | package it.isuri.flightsearch.repository;
import it.isuri.flightsearch.model.FlightEntity;
import it.isuri.flightsearch.model.FlightType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.time.LocalDate;
@Repository
public interface FlightRepository extends PagingAndSortingRepository<FlightEntity, Long> {
@Query("SELECT f FROM FlightEntity f WHERE (:departure is null or f.departure = :departure) AND "
+ "(:arrival is null or f.arrival = :arrival) AND "
+ "(:date is null or (f.departureDate BETWEEN :date AND :endDate))")
Page<FlightEntity> findAllByDepartureAndArrivalAndDepartureDate(String departure, String arrival, LocalDate date, LocalDate endDate, Pageable pageable);
@Modifying
@Transactional
@Query(value = "DELETE FROM FlightEntity f WHERE f.flightType = :flightType AND f.id < :id")
void deleteByTypeAndId(@Param("flightType") FlightType flightType, @Param("id") Long id);
}
| UTF-8 | Java | 1,328 | java | FlightRepository.java | Java | [] | null | [] | package it.isuri.flightsearch.repository;
import it.isuri.flightsearch.model.FlightEntity;
import it.isuri.flightsearch.model.FlightType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.time.LocalDate;
@Repository
public interface FlightRepository extends PagingAndSortingRepository<FlightEntity, Long> {
@Query("SELECT f FROM FlightEntity f WHERE (:departure is null or f.departure = :departure) AND "
+ "(:arrival is null or f.arrival = :arrival) AND "
+ "(:date is null or (f.departureDate BETWEEN :date AND :endDate))")
Page<FlightEntity> findAllByDepartureAndArrivalAndDepartureDate(String departure, String arrival, LocalDate date, LocalDate endDate, Pageable pageable);
@Modifying
@Transactional
@Query(value = "DELETE FROM FlightEntity f WHERE f.flightType = :flightType AND f.id < :id")
void deleteByTypeAndId(@Param("flightType") FlightType flightType, @Param("id") Long id);
}
| 1,328 | 0.784639 | 0.784639 | 28 | 46.42857 | 37.858219 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 8 |
fc370d44f3d36c3ae73763d95ae7a0d83835ea2b | 33,019,708,600,263 | d7be0cf96dae35a98dc1643011e025a28e3c92bd | /QZComm/src/main/java/com/ks/protocol/vo/arena/ArenaInfoVO.java | 140cb7ae98284686dad0141a0385c050589ba70d | [] | no_license | liaohanjie/QZStore | https://github.com/liaohanjie/QZStore | 8ab5827138266dc88179ee2cfb94c98d391c39be | 698d1e7d8386bca3b15fd4b3ea3020e5b9cc3c43 | refs/heads/master | 2021-01-10T18:35:14.604000 | 2016-05-31T05:17:50 | 2016-05-31T05:17:50 | 59,005,984 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ks.protocol.vo.arena;
import java.util.List;
import com.ks.protocol.FieldDesc;
import com.ks.protocol.Message;
import com.ks.protocol.vo.user.UserBaseinfoVO;
public abstract class ArenaInfoVO extends Message {
private static final long serialVersionUID = 1L;
@FieldDesc(desc="自己的竞技场")
private ArenaVO myArena;
@FieldDesc(desc="对手的竞技场")
private List<UserBaseinfoVO> rivals;
@FieldDesc(desc="对手刷新时间")
private long rivalRefTime;
public List<UserBaseinfoVO> getRivals() {
return rivals;
}
public void setRivals(List<UserBaseinfoVO> rivals) {
this.rivals = rivals;
}
public ArenaVO getMyArena() {
return myArena;
}
public void setMyArena(ArenaVO myArena) {
this.myArena = myArena;
}
public long getRivalRefTime() {
return rivalRefTime;
}
public void setRivalRefTime(long rivalRefTime) {
this.rivalRefTime = rivalRefTime;
}
}
| UTF-8 | Java | 903 | java | ArenaInfoVO.java | Java | [] | null | [] | package com.ks.protocol.vo.arena;
import java.util.List;
import com.ks.protocol.FieldDesc;
import com.ks.protocol.Message;
import com.ks.protocol.vo.user.UserBaseinfoVO;
public abstract class ArenaInfoVO extends Message {
private static final long serialVersionUID = 1L;
@FieldDesc(desc="自己的竞技场")
private ArenaVO myArena;
@FieldDesc(desc="对手的竞技场")
private List<UserBaseinfoVO> rivals;
@FieldDesc(desc="对手刷新时间")
private long rivalRefTime;
public List<UserBaseinfoVO> getRivals() {
return rivals;
}
public void setRivals(List<UserBaseinfoVO> rivals) {
this.rivals = rivals;
}
public ArenaVO getMyArena() {
return myArena;
}
public void setMyArena(ArenaVO myArena) {
this.myArena = myArena;
}
public long getRivalRefTime() {
return rivalRefTime;
}
public void setRivalRefTime(long rivalRefTime) {
this.rivalRefTime = rivalRefTime;
}
}
| 903 | 0.758939 | 0.757785 | 36 | 23.083334 | 17.000612 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 8 |
75c21175bca24bc1bca63968835b4f4643ec414f | 5,497,558,159,022 | ca9f86ab38f5951daca02d8e68395e1af7d028a9 | /Proces2/src/com/company/SJF.java | d2cf7035690f408008b3828b3aa74c1bbc872d00 | [] | no_license | matswierczynski/Idea-Projects | https://github.com/matswierczynski/Idea-Projects | d1aa1108a6fa52af1f179b1a0628981e0f3619ad | 4fc7d6dce9142a6675eab1e98589a097d93e60ed | refs/heads/master | 2022-05-04T03:58:21.452000 | 2017-04-07T19:30:45 | 2017-04-07T19:30:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.util.Date;
/**
* Created by matik on 04.03.2017.
*/
public class SJF {
Date date;
long time;
Queue queue;
public SJF(Queue q){
queue = q;
}
public int run()
{
date=new Date();
time=date.getTime();
long summary=0;
for (int i=0;i<queue.getSize();i++)
{
date=new Date();
long wT=date.getTime();
Process pr=queue.getProcess(i);
pr.setPickedUp(i+1);
int initialValue=pr.getLength();
for(int k=0;k<pr.getLength();k++){
pr.decreaseLength();
}
long waitingTime=wT-time;
pr.setWaitingTime(waitingTime);
pr.setLength(initialValue);
summary+=waitingTime;
}
return (int)summary/queue.getSize();
}
}
| UTF-8 | Java | 874 | java | SJF.java | Java | [
{
"context": "ompany;\n\nimport java.util.Date;\n\n/**\n * Created by matik on 04.03.2017.\n */\npublic class SJF {\n Date da",
"end": 69,
"score": 0.9989379644393921,
"start": 64,
"tag": "USERNAME",
"value": "matik"
}
] | null | [] | package com.company;
import java.util.Date;
/**
* Created by matik on 04.03.2017.
*/
public class SJF {
Date date;
long time;
Queue queue;
public SJF(Queue q){
queue = q;
}
public int run()
{
date=new Date();
time=date.getTime();
long summary=0;
for (int i=0;i<queue.getSize();i++)
{
date=new Date();
long wT=date.getTime();
Process pr=queue.getProcess(i);
pr.setPickedUp(i+1);
int initialValue=pr.getLength();
for(int k=0;k<pr.getLength();k++){
pr.decreaseLength();
}
long waitingTime=wT-time;
pr.setWaitingTime(waitingTime);
pr.setLength(initialValue);
summary+=waitingTime;
}
return (int)summary/queue.getSize();
}
}
| 874 | 0.503433 | 0.489703 | 43 | 19.325581 | 15.558922 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55814 | false | false | 8 |
a178fceac549aec4dfc20f9c0723011198d3e949 | 30,940,944,418,013 | 46debc8dc8a9ec5b14ddd8f1dbf299fc5e50258d | /src/main/java/harbour/shared/domain/NodeGroup.java | 1f99fb2ed3df7ec273126a2e7fd7dfe231ac884a | [] | no_license | welvet/docker-harbour | https://github.com/welvet/docker-harbour | 647cd4375fb1314a9896ccc19c06a738503c3a06 | 04373dfab96c9b7f43afe008d0a376ac5df9fa12 | refs/heads/master | 2016-08-06T21:52:39.054000 | 2014-12-22T12:43:28 | 2014-12-22T12:43:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package harbour.shared.domain;
import java.io.Serializable;
/**
* Created by akutuzov on 05/11/14.
*/
public class NodeGroup extends AbstractNode implements Serializable {
}
| UTF-8 | Java | 178 | java | NodeGroup.java | Java | [
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by akutuzov on 05/11/14.\n */\npublic class NodeGroup extends A",
"end": 88,
"score": 0.9991947412490845,
"start": 80,
"tag": "USERNAME",
"value": "akutuzov"
}
] | null | [] | package harbour.shared.domain;
import java.io.Serializable;
/**
* Created by akutuzov on 05/11/14.
*/
public class NodeGroup extends AbstractNode implements Serializable {
}
| 178 | 0.764045 | 0.730337 | 9 | 18.777779 | 22.399294 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 8 |
35e5352d737fa819e3008a2648c5fb2985f66feb | 30,743,375,911,839 | b1d74bd8800ad0081a49ca2acce7b2a9dd350e04 | /src/test/Units/Mage.java | b3590f2091d5f6a712e24fbd1d5c1da481f019ef | [] | no_license | CristianPantilie/Game | https://github.com/CristianPantilie/Game | bc470d52cd85ca049f090e36cc5b702b1b904bc4 | 486cd635cf7799ad2457ecf690c204e9b8d3ade9 | refs/heads/master | 2022-03-04T21:27:48.921000 | 2019-08-06T07:33:59 | 2019-08-06T07:33:59 | 198,370,898 | 0 | 1 | null | false | 2019-08-06T07:34:01 | 2019-07-23T06:55:33 | 2019-07-31T11:34:20 | 2019-08-06T07:34:00 | 82 | 0 | 1 | 1 | Java | false | false | package test.Units;
public class Mage extends Hero {
public Mage(int level) {
super(level);
}
}
| UTF-8 | Java | 113 | java | Mage.java | Java | [] | null | [] | package test.Units;
public class Mage extends Hero {
public Mage(int level) {
super(level);
}
}
| 113 | 0.619469 | 0.619469 | 7 | 15.142858 | 12.135292 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 8 |
e4acac9a934255a82ed022e323d2ad713385b024 | 16,312,285,794,598 | cfe7a28a9cf22cf221cdaa59f6cd55ef6c1ee0e0 | /src/test/java/fr/univtlse3/m2dl/magnetrade/request/RequestTest.java | d07003f9af0697d82e2b337fa6be4c7eab1024af | [
"MIT"
] | permissive | M2DL/2019-ivvq-magnetrade | https://github.com/M2DL/2019-ivvq-magnetrade | ce15b036b8022cccc73b89f340b0faf76f1a8ce8 | 4c959ff226f426441bde15d7c7458f8987d78048 | refs/heads/master | 2020-04-22T20:56:28.807000 | 2020-03-20T00:47:01 | 2020-03-20T00:47:01 | 170,657,186 | 0 | 3 | MIT | false | 2020-03-20T00:47:02 | 2019-02-14T08:41:24 | 2019-05-15T20:33:39 | 2020-03-20T00:47:01 | 1,698 | 0 | 3 | 3 | Java | false | false | package fr.univtlse3.m2dl.magnetrade.request;
import fr.univtlse3.m2dl.magnetrade.comment.Comment;
import fr.univtlse3.m2dl.magnetrade.magnet.Magnet;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
public class RequestTest {
private Date nowDate;
private Request request;
@Before
public void setUp() throws Exception {
nowDate = new Date();
request = new Request(1L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
}
@Test
public void testConstructor() throws Exception {
Request request1 = new Request("pic", "content", nowDate, new ArrayList<>());
assertThat(request1, IsEqual.equalTo(request));
}
@Test
public void testGetId() throws Exception {
assertThat(request.getId(), IsEqual.equalTo(1L));
}
@Test
public void testSetId() throws Exception {
request.setId(2L);
assertThat(request.getId(), IsEqual.equalTo(2L));
}
@Test
public void testGetActive() throws Exception {
assertThat(request.getActive(), IsEqual.equalTo(true));
}
@Test
public void testSetActive() throws Exception {
request.setActive(false);
assertThat(request.getActive(), IsEqual.equalTo(false));
}
@Test
public void testGetPicture() throws Exception {
assertThat(request.getPicture(), IsEqual.equalTo("pic"));
}
@Test
public void testSetPicture() throws Exception {
request.setPicture("new_pic");
assertThat(request.getPicture(), IsEqual.equalTo("new_pic"));
}
@Test
public void testGetText() throws Exception {
assertThat(request.getText(), IsEqual.equalTo("content"));
}
@Test
public void testSetText() throws Exception {
request.setText("new_content");
assertThat(request.getText(), IsEqual.equalTo("new_content"));
}
@Test
public void testGetCreationDate() throws Exception {
assertThat(request.getCreationDate(), IsEqual.equalTo(nowDate));
}
@Test
public void testSetCreationDate() throws Exception {
Date date = new Date();
request.setCreationDate(date);
assertThat(request.getCreationDate(), IsEqual.equalTo(date));
}
@Test
public void testGetMagnets() throws Exception {
assertThat(request.getMagnets(), IsEqual.equalTo(new ArrayList<>()));
}
@Test
public void testSetMagnets() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
magnets.add(new Magnet());
request.setMagnets(magnets);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
}
@Test
public void testAddMagnet() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
Magnet m1 = new Magnet();
magnets.add(m1);
request.addMagnet(m1);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
}
@Test
public void testRemoveMagnet() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
Magnet m1 = new Magnet();
magnets.add(m1);
request.setMagnets(magnets);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
request.removeMagnet(m1);
assertThat(request.getMagnets(), IsEqual.equalTo(new ArrayList<Magnet>()));
}
@Test
public void testGetComments() throws Exception {
assertThat(request.getComments(), IsEqual.equalTo(new ArrayList<>()));
}
@Test
public void testSetComments() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
comments.add(new Comment());
request.setComments(comments);
assertThat(request.getComments(), IsEqual.equalTo(comments));
}
@Test
public void testAddComment() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
Comment c1 = new Comment();
comments.add(c1);
request.addComment(c1);
assertThat(request.getComments(), IsEqual.equalTo(comments));
}
@Test
public void testRemoveComment() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
Comment c1 = new Comment();
comments.add(c1);
request.setComments(comments);
assertThat(request.getComments(), IsEqual.equalTo(comments));
request.removeComment(c1);
assertThat(request.getComments(), IsEqual.equalTo(new ArrayList<Comment>()));
}
@Test
public void testEquals() throws Exception {
Date date = new Date(155409322);
// same attributes
Request req = new Request(2L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
// different creationDate
Request req2 = new Request(3L, true, "pic", "content", date, new ArrayList<>(), new ArrayList<>());
// different text
Request req3 = new Request(4L, true, "pic", "other", date, new ArrayList<>(), new ArrayList<>());
// text null
Request req4 = new Request(5L, true, "pic", null, date, new ArrayList<>(), new ArrayList<>());
// different picture
Request req5 = new Request(4L, true, "other", "content", date, new ArrayList<>(), new ArrayList<>());
// picture null
Request req6 = new Request(5L, true, null, "content", date, new ArrayList<>(), new ArrayList<>());
// different isActive
Request req7 = new Request(6L, false, "pic", "content", date, new ArrayList<>(), new ArrayList<>());
assertTrue(request.equals(req));
assertTrue(request.equals(request));
assertFalse(request.equals(null));
assertFalse(request.equals(""));
assertFalse(request.equals(req2));
assertFalse(request.equals(req3));
assertFalse(request.equals(req4));
assertFalse(request.equals(req5));
assertFalse(request.equals(req6));
assertFalse(request.equals(req7));
}
@Test
public void testToString() throws Exception {
assertThat(request.toString(), IsEqual.equalTo("Request{" +
"isActive=" + true +
", picture='" + "pic" + '\'' +
", text='" + "content" + '\'' +
", creationDate=" + nowDate +
", magnets=" + new ArrayList<>() +
", comments=" + new ArrayList<>() +
'}'));
}
@Test
public void testHashCode() throws Exception {
Request req = new Request(2L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
assertThat(request.hashCode(), IsEqual.equalTo(req.hashCode()));
}
} | UTF-8 | Java | 6,781 | java | RequestTest.java | Java | [] | null | [] | package fr.univtlse3.m2dl.magnetrade.request;
import fr.univtlse3.m2dl.magnetrade.comment.Comment;
import fr.univtlse3.m2dl.magnetrade.magnet.Magnet;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
public class RequestTest {
private Date nowDate;
private Request request;
@Before
public void setUp() throws Exception {
nowDate = new Date();
request = new Request(1L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
}
@Test
public void testConstructor() throws Exception {
Request request1 = new Request("pic", "content", nowDate, new ArrayList<>());
assertThat(request1, IsEqual.equalTo(request));
}
@Test
public void testGetId() throws Exception {
assertThat(request.getId(), IsEqual.equalTo(1L));
}
@Test
public void testSetId() throws Exception {
request.setId(2L);
assertThat(request.getId(), IsEqual.equalTo(2L));
}
@Test
public void testGetActive() throws Exception {
assertThat(request.getActive(), IsEqual.equalTo(true));
}
@Test
public void testSetActive() throws Exception {
request.setActive(false);
assertThat(request.getActive(), IsEqual.equalTo(false));
}
@Test
public void testGetPicture() throws Exception {
assertThat(request.getPicture(), IsEqual.equalTo("pic"));
}
@Test
public void testSetPicture() throws Exception {
request.setPicture("new_pic");
assertThat(request.getPicture(), IsEqual.equalTo("new_pic"));
}
@Test
public void testGetText() throws Exception {
assertThat(request.getText(), IsEqual.equalTo("content"));
}
@Test
public void testSetText() throws Exception {
request.setText("new_content");
assertThat(request.getText(), IsEqual.equalTo("new_content"));
}
@Test
public void testGetCreationDate() throws Exception {
assertThat(request.getCreationDate(), IsEqual.equalTo(nowDate));
}
@Test
public void testSetCreationDate() throws Exception {
Date date = new Date();
request.setCreationDate(date);
assertThat(request.getCreationDate(), IsEqual.equalTo(date));
}
@Test
public void testGetMagnets() throws Exception {
assertThat(request.getMagnets(), IsEqual.equalTo(new ArrayList<>()));
}
@Test
public void testSetMagnets() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
magnets.add(new Magnet());
request.setMagnets(magnets);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
}
@Test
public void testAddMagnet() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
Magnet m1 = new Magnet();
magnets.add(m1);
request.addMagnet(m1);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
}
@Test
public void testRemoveMagnet() throws Exception {
ArrayList<Magnet> magnets = new ArrayList<>();
Magnet m1 = new Magnet();
magnets.add(m1);
request.setMagnets(magnets);
assertThat(request.getMagnets(), IsEqual.equalTo(magnets));
request.removeMagnet(m1);
assertThat(request.getMagnets(), IsEqual.equalTo(new ArrayList<Magnet>()));
}
@Test
public void testGetComments() throws Exception {
assertThat(request.getComments(), IsEqual.equalTo(new ArrayList<>()));
}
@Test
public void testSetComments() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
comments.add(new Comment());
request.setComments(comments);
assertThat(request.getComments(), IsEqual.equalTo(comments));
}
@Test
public void testAddComment() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
Comment c1 = new Comment();
comments.add(c1);
request.addComment(c1);
assertThat(request.getComments(), IsEqual.equalTo(comments));
}
@Test
public void testRemoveComment() throws Exception {
ArrayList<Comment> comments = new ArrayList<>();
Comment c1 = new Comment();
comments.add(c1);
request.setComments(comments);
assertThat(request.getComments(), IsEqual.equalTo(comments));
request.removeComment(c1);
assertThat(request.getComments(), IsEqual.equalTo(new ArrayList<Comment>()));
}
@Test
public void testEquals() throws Exception {
Date date = new Date(155409322);
// same attributes
Request req = new Request(2L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
// different creationDate
Request req2 = new Request(3L, true, "pic", "content", date, new ArrayList<>(), new ArrayList<>());
// different text
Request req3 = new Request(4L, true, "pic", "other", date, new ArrayList<>(), new ArrayList<>());
// text null
Request req4 = new Request(5L, true, "pic", null, date, new ArrayList<>(), new ArrayList<>());
// different picture
Request req5 = new Request(4L, true, "other", "content", date, new ArrayList<>(), new ArrayList<>());
// picture null
Request req6 = new Request(5L, true, null, "content", date, new ArrayList<>(), new ArrayList<>());
// different isActive
Request req7 = new Request(6L, false, "pic", "content", date, new ArrayList<>(), new ArrayList<>());
assertTrue(request.equals(req));
assertTrue(request.equals(request));
assertFalse(request.equals(null));
assertFalse(request.equals(""));
assertFalse(request.equals(req2));
assertFalse(request.equals(req3));
assertFalse(request.equals(req4));
assertFalse(request.equals(req5));
assertFalse(request.equals(req6));
assertFalse(request.equals(req7));
}
@Test
public void testToString() throws Exception {
assertThat(request.toString(), IsEqual.equalTo("Request{" +
"isActive=" + true +
", picture='" + "pic" + '\'' +
", text='" + "content" + '\'' +
", creationDate=" + nowDate +
", magnets=" + new ArrayList<>() +
", comments=" + new ArrayList<>() +
'}'));
}
@Test
public void testHashCode() throws Exception {
Request req = new Request(2L, true, "pic", "content", nowDate, new ArrayList<>(), new ArrayList<>());
assertThat(request.hashCode(), IsEqual.equalTo(req.hashCode()));
}
} | 6,781 | 0.622769 | 0.614954 | 210 | 31.295238 | 28.47352 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.814286 | false | false | 8 |
0aa288b92a55765ec06488fec703060e52c459e5 | 25,589,415,164,086 | 7e5e1b44d0c2d04a06ae85ea3bd93485f93107de | /CarTracker1.0/src/com/cartracker/mobile/android/ui/EmergencyActivity.java | ffd8b27f5e1daa56ed25c3c772a3653dc4321983 | [
"IJG"
] | permissive | bigdog001/carFinder | https://github.com/bigdog001/carFinder | e2707d065a689159b3bc542e769303c75f93c05d | 5741365316b006fc92542d56d195e51f16bb2778 | refs/heads/master | 2021-01-20T20:38:59.299000 | 2016-07-24T00:06:39 | 2016-07-24T00:06:39 | 60,020,429 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cartracker.mobile.android.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.cartracker.mobile.android.R;
import com.cartracker.mobile.android.config.VariableKeeper;
import com.cartracker.mobile.android.data.beans.EmergencyAdaptor;
import com.cartracker.mobile.android.ui.base.BaseActivity;
import com.cartracker.mobile.android.ui.review.MyTitlebar;
import com.cartracker.mobile.android.util.SystemUtil;
import com.cartracker.mobile.android.util.handler.InterfaceGen;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jw362j on 10/13/2014.
*/
public class EmergencyActivity extends BaseActivity implements View.OnClickListener, InterfaceGen.itemsRefreshListener {
private View contentView;
private MyTitlebar rvt;
private ListView user_emergency_phone_number_lists;
private EditText user_emergency_phone_number;
private Button emergency_sms_save;
private EmergencyAdaptor emergencyAdaptor;
private List<String> phone_numbers;
private Dialog dialog_ = null;
private Spinner sms_send_frequence_id, sms_stop_time_id;
private Animation mAnimation ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contentView = View.inflate(EmergencyActivity.this, R.layout.emergency_help, null);
setContentView(contentView);
LinearLayout detect_view_title = (LinearLayout) findViewById(R.id.record_view_titlebar);
initTitle();
detect_view_title.addView(rvt.getRecord_view_titlebar());
initView();
}
private void initView() {
user_emergency_phone_number = (EditText) contentView.findViewById(R.id.user_emergency_phone_number);
user_emergency_phone_number.setInputType(EditorInfo.TYPE_CLASS_PHONE);
emergency_sms_save = (Button) contentView.findViewById(R.id.emergency_sms_save);
emergency_sms_save.setOnClickListener(EmergencyActivity.this);
//判断用户之前是否设置过紧急救援联系人
LoadNumber();
if (phone_numbers == null || phone_numbers.size() == 0) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.emergency_sms_number_empty_title_tips), getResources().getString(R.string.emergency_sms_no_phonenumber_text));
}
user_emergency_phone_number_lists = (ListView) contentView.findViewById(R.id.user_emergency_phone_number_lists);
emergencyAdaptor = new EmergencyAdaptor(EmergencyActivity.this, phone_numbers, EmergencyActivity.this);
user_emergency_phone_number_lists.setAdapter(emergencyAdaptor);
}
private void LoadNumber() {
String cellphone_Numbers = VariableKeeper.mSp.getString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, null);
if ("".equals(cellphone_Numbers) || cellphone_Numbers == null)
return;
if (cellphone_Numbers.contains(",")) {
//说明有多个号码
String[] numbers = cellphone_Numbers.split(",");
if (numbers != null && numbers.length > 0) {
phone_numbers = new ArrayList<String>();
for (String number : numbers) {
phone_numbers.add(number);
}
}
} else {
//说明只有一个号码
phone_numbers = new ArrayList<String>();
phone_numbers.add(cellphone_Numbers);
}
}
private void savePhoneNumbers() {
if (phone_numbers == null || phone_numbers.size() == 0) {
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, "");
editor.commit();
return;
}
int size = phone_numbers.size();
String target = "";
for (int i = 0; i < size; i++) {
if (i == size - 1) {
target = target + phone_numbers.get(i);
} else {
target = target + phone_numbers.get(i) + ",";
}
}
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, target);
editor.commit();
}
private void savePhoneNumber(String number) {
if ("".equals(number) || number == null) {
SystemUtil.MyToast(getResources().getString(R.string.emergency_sms_number_empty));
return;
}
String cellphone_Numbers = VariableKeeper.mSp.getString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, null);
if ("".equals(cellphone_Numbers) || cellphone_Numbers == null) {
//第一次设置紧急联络人
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, number);
editor.commit();
user_emergency_phone_number.setText("");
SystemUtil.MyToast(number + getResources().getString(R.string.emergency_sms_save_sucess_exist));
} else {
if (cellphone_Numbers.contains(number)) {
SystemUtil.MyToast(getResources().getString(R.string.emergency_sms_save_already_exist));
return;
}
//取出旧值然后和新值拼接起来重新保存
String newValues = cellphone_Numbers + "," + number;
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, newValues);
editor.commit();
user_emergency_phone_number.setText("");
SystemUtil.MyToast(number + getResources().getString(R.string.emergency_sms_save_sucess_exist));
SystemUtil.log("new emergency phone numbers:" + newValues);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id_selected = item.getItemId();
switch (id_selected) {
case R.id.menu_emergency_help_settings_send_frequence_id:
//弹出设置短信发送频率和结束条件的对话框
openSmsSendFrequenceSettingDialog();
break;
case R.id.menu_emergency_stop_id:
//判断当前是否处于紧急危机遇险模式
boolean is_emergency = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);
if (is_emergency) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyActivity.this);
builder.setTitle(getResources().getString(R.string.dialog_tips_title)).setMessage(getResources().getString(R.string.menu_emergency_stop_tips_text)).setPositiveButton(getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);//false表示当前已经不处于紧急危险模式 用户成功脱险
editor.commit();
SystemUtil.MyToast(getResources().getString(R.string.menu_emergency_stop_success_toast_msg));
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
} else {
SystemUtil.MyToast(getResources().getString(R.string.menu_emergency_stop_error_text));
}
break;
}
return super.onOptionsItemSelected(item);
}
private void openSmsSendFrequenceSettingDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyActivity.this);
final View view_title = View.inflate(EmergencyActivity.this, R.layout.emergency_help_menu_setting_title, null);
final View view_body = View.inflate(EmergencyActivity.this, R.layout.emergency_help_menu_setting_body, null);
sms_send_frequence_id = (Spinner) view_body.findViewById(R.id.sms_send_frequence_id);
sms_stop_time_id = (Spinner) view_body.findViewById(R.id.sms_stop_time_id);
setUpSpinner();
Button setting_sms_save = (Button) view_body.findViewById(R.id.setting_sms_save);
Button setting_sms_cancel = (Button) view_body.findViewById(R.id.setting_sms_cancel);
TextView menu_emergency_help_settings_send_frequence_title_close = (TextView) view_title.findViewById(R.id.menu_emergency_help_settings_send_frequence_title_close);
setting_sms_save.setOnClickListener(EmergencyActivity.this);
setting_sms_cancel.setOnClickListener(EmergencyActivity.this);
menu_emergency_help_settings_send_frequence_title_close.setOnClickListener(EmergencyActivity.this);
builder.setCustomTitle(view_title);
builder.setView(view_body);
dialog_ = builder.create();
dialog_.show();
}
private void setUpSpinner() {
// sms_send_frequence_id = (Spinner) view_body.findViewById(R.id.sms_send_frequence_id);
// sms_stop_time_id = (Spinner) view_body.findViewById(R.id.sms_stop_time_id);
//取出对应的设置
long sms_send_frequence_time = VariableKeeper.mSp.getLong(VariableKeeper.APP_CONSTANT.sms_send_frequence_sp_name, 0);
long sms_stop_time = VariableKeeper.mSp.getLong(VariableKeeper.APP_CONSTANT.sms_stop_during_sp_name, 0);
if (sms_send_frequence_time == 0) {
//默认每五分钟一次 即选中第0项
sms_send_frequence_id.setSelection(0, true);
} else if (sms_send_frequence_time == 5) {
//默认每五分钟一次 即选中第0项
sms_send_frequence_id.setSelection(0, true);
} else if (sms_send_frequence_time == 10) {
sms_send_frequence_id.setSelection(1, true);
} else if (sms_send_frequence_time == 60) {
sms_send_frequence_id.setSelection(2, true);
} else if (sms_send_frequence_time == 120) {
sms_send_frequence_id.setSelection(3, true);
} else if (sms_send_frequence_time == 300) {
sms_send_frequence_id.setSelection(4, true);
}
if (sms_stop_time == 0) {
//默认为5小时后(300分钟) 即选中第2项
sms_stop_time_id.setSelection(2, true);
} else if (sms_stop_time == 20) {
sms_stop_time_id.setSelection(0, true);
} else if (sms_stop_time == 120) {
sms_stop_time_id.setSelection(1, true);
} else if (sms_stop_time == 300) {
sms_stop_time_id.setSelection(2, true);
} else if (sms_stop_time == 600) {
sms_stop_time_id.setSelection(3, true);
} else if (sms_stop_time == 888) {
sms_stop_time_id.setSelection(4, true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emergency_help_menu, menu);
SystemUtil.log("menu is here in emergency...");
return super.onCreateOptionsMenu(menu);
}
private void initTitle() {
rvt = new MyTitlebar(EmergencyActivity.this);
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
rvt.setShowRightBtn(true);
rvt.setRightBtnOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean ison_ = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
if (ison_) {
//当前已经开启 进入关闭状态
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setTitle(getResources().getString(R.string.emergency_sms_right_btn_emergency_off_title))
.setMessage(getResources().getString(R.string.emergency_sms_right_btn_emergency_off_msg))
.setPositiveButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_on_tips));
rvt.setTitle(getResources().getString(R.string.title_emergency_off));
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
editor.commit();
}
}).setNegativeButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
}
});
dialog = builder.create();
dialog.show();
} else {
//当前已经关闭 进入开启状态 首先要判断是否设定了紧急联络号码
LoadNumber();
if (phone_numbers == null || phone_numbers.size() == 0) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.emergency_sms_right_btn_emergency_on_error_titel), getResources().getString(R.string.emergency_sms_right_btn_emergency_on_error_msg));
} else if (!VariableKeeper.simStatus) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.dialog_tips_title), getResources().getString(R.string.emergency_sms_no_sim_error_msg));
} else {
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_off_tips));
rvt.setTitle(getResources().getString(R.string.title_emergency_on));
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, true);
editor.commit();
}
}
}
});
if (ison) {
//开启
rvt.setTitle(getResources().getString(R.string.title_emergency_on));
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_off_tips));
//紧急救援模式如果正在运行时即用户当前遭遇危险 则标题闪动 提示用户当前已经在向亲人报告坐标位置了
// mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.record_item_alpha)
} else {
//关闭
rvt.setTitle(getResources().getString(R.string.title_emergency_off));
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_on_tips));
}
rvt.setLeftBtnShow(true);
rvt.setLeftBtnOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
//紧急救援模式如果正在运行时即用户当前遭遇危险 则标题闪动 提示用户当前已经在向亲人报告坐标位置了
TextView tv_title = null;
if(ison){
boolean isEmergency_now = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);
if(isEmergency_now){
tv_title = rvt.getTv_title();
if (tv_title != null) {
mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.record_item_alpha);
tv_title.setTextColor(Color.RED);
tv_title.startAnimation(mAnimation);
}else {
tv_title.setTextColor(Color.WHITE);
tv_title.clearAnimation();
}
}
}else {
tv_title = rvt.getTv_title();
if (tv_title != null) {
tv_title.setTextColor(Color.WHITE);
tv_title.clearAnimation();
}
}
}
@Override
public void stopAll() {
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.emergency_sms_save:
String phoneNumer = user_emergency_phone_number.getText().toString();
if (SystemUtil.phoneNumberCheck(phoneNumer)) {
savePhoneNumber(phoneNumer);
LoadNumber();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
break;
case R.id.setting_sms_save:
saveSmsSeting();
closeSettingDialog();
break;
case R.id.setting_sms_cancel:
closeSettingDialog();
break;
case R.id.menu_emergency_help_settings_send_frequence_title_close:
closeSettingDialog();
break;
}
}
private void saveSmsSeting() {
if (sms_stop_time_id != null && sms_send_frequence_id != null) {
long send_setting_id = sms_send_frequence_id.getSelectedItemId();
long stop_setting_id = sms_stop_time_id.getSelectedItemId();
//send_setting_id ===> 5分钟 ,10分钟 ,60分钟, 120分钟, 300分钟
//stop_setting_id ===> 20分钟, 120分钟, 300分钟, 600分钟
if (send_setting_id == 0) {
send_setting_id = 5;
} else if (send_setting_id == 1) {
send_setting_id = 10;
} else if (send_setting_id == 2) {
send_setting_id = 60;
} else if (send_setting_id == 3) {
send_setting_id = 120;
} else if (send_setting_id == 4) {
send_setting_id = 300;
}
if (stop_setting_id == 0) {
stop_setting_id = 20;
} else if (stop_setting_id == 1) {
stop_setting_id = 120;
} else if (stop_setting_id == 2) {
stop_setting_id = 300;
} else if (stop_setting_id == 3) {
stop_setting_id = 600;
} else if (stop_setting_id == 4) {
stop_setting_id = 888;//此值表示用户会手工停止(以后会加入远程短信的方式来停止 即解除紧急救援模式)
}
SystemUtil.log("send_setting_id:" + send_setting_id + ",stop_setting_id:" + stop_setting_id);
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putLong(VariableKeeper.APP_CONSTANT.sms_send_frequence_sp_name, send_setting_id);
editor.putLong(VariableKeeper.APP_CONSTANT.sms_stop_during_sp_name, stop_setting_id);
editor.commit();
SystemUtil.MyToast(getResources().getString(R.string.emergency_help_settings_success));
}
}
private void closeSettingDialog() {
if (dialog_ != null && dialog_.isShowing()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog_.dismiss();
}
});
}
}
@Override
public void onRefresh(final int position, Object data) {
//刷新紧急联系人列表listview,flag为删除的是第几项
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setTitle(getResources().getString(R.string.dialog_tips_title))
.setMessage(getResources().getString(R.string.emergency_sms_phone_delete_confirm_msg))
.setPositiveButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
if (ison) {
if (phone_numbers.size() == 1) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.dialog_tips_title), getResources().getString(R.string.emergency_sms_phone_delete_error_msg));
} else {
phone_numbers.remove(position);//更新数据
savePhoneNumbers();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
} else {
phone_numbers.remove(position);//更新数据
savePhoneNumbers();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
}
}).setNegativeButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
}
});
dialog = builder.create();
dialog.show();
}
});
}
}
| UTF-8 | Java | 23,784 | java | EmergencyActivity.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by jw362j on 10/13/2014.\n */\npublic class EmergencyActivity",
"end": 958,
"score": 0.999589741230011,
"start": 952,
"tag": "USERNAME",
"value": "jw362j"
}
] | null | [] | package com.cartracker.mobile.android.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.cartracker.mobile.android.R;
import com.cartracker.mobile.android.config.VariableKeeper;
import com.cartracker.mobile.android.data.beans.EmergencyAdaptor;
import com.cartracker.mobile.android.ui.base.BaseActivity;
import com.cartracker.mobile.android.ui.review.MyTitlebar;
import com.cartracker.mobile.android.util.SystemUtil;
import com.cartracker.mobile.android.util.handler.InterfaceGen;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jw362j on 10/13/2014.
*/
public class EmergencyActivity extends BaseActivity implements View.OnClickListener, InterfaceGen.itemsRefreshListener {
private View contentView;
private MyTitlebar rvt;
private ListView user_emergency_phone_number_lists;
private EditText user_emergency_phone_number;
private Button emergency_sms_save;
private EmergencyAdaptor emergencyAdaptor;
private List<String> phone_numbers;
private Dialog dialog_ = null;
private Spinner sms_send_frequence_id, sms_stop_time_id;
private Animation mAnimation ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contentView = View.inflate(EmergencyActivity.this, R.layout.emergency_help, null);
setContentView(contentView);
LinearLayout detect_view_title = (LinearLayout) findViewById(R.id.record_view_titlebar);
initTitle();
detect_view_title.addView(rvt.getRecord_view_titlebar());
initView();
}
private void initView() {
user_emergency_phone_number = (EditText) contentView.findViewById(R.id.user_emergency_phone_number);
user_emergency_phone_number.setInputType(EditorInfo.TYPE_CLASS_PHONE);
emergency_sms_save = (Button) contentView.findViewById(R.id.emergency_sms_save);
emergency_sms_save.setOnClickListener(EmergencyActivity.this);
//判断用户之前是否设置过紧急救援联系人
LoadNumber();
if (phone_numbers == null || phone_numbers.size() == 0) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.emergency_sms_number_empty_title_tips), getResources().getString(R.string.emergency_sms_no_phonenumber_text));
}
user_emergency_phone_number_lists = (ListView) contentView.findViewById(R.id.user_emergency_phone_number_lists);
emergencyAdaptor = new EmergencyAdaptor(EmergencyActivity.this, phone_numbers, EmergencyActivity.this);
user_emergency_phone_number_lists.setAdapter(emergencyAdaptor);
}
private void LoadNumber() {
String cellphone_Numbers = VariableKeeper.mSp.getString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, null);
if ("".equals(cellphone_Numbers) || cellphone_Numbers == null)
return;
if (cellphone_Numbers.contains(",")) {
//说明有多个号码
String[] numbers = cellphone_Numbers.split(",");
if (numbers != null && numbers.length > 0) {
phone_numbers = new ArrayList<String>();
for (String number : numbers) {
phone_numbers.add(number);
}
}
} else {
//说明只有一个号码
phone_numbers = new ArrayList<String>();
phone_numbers.add(cellphone_Numbers);
}
}
private void savePhoneNumbers() {
if (phone_numbers == null || phone_numbers.size() == 0) {
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, "");
editor.commit();
return;
}
int size = phone_numbers.size();
String target = "";
for (int i = 0; i < size; i++) {
if (i == size - 1) {
target = target + phone_numbers.get(i);
} else {
target = target + phone_numbers.get(i) + ",";
}
}
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, target);
editor.commit();
}
private void savePhoneNumber(String number) {
if ("".equals(number) || number == null) {
SystemUtil.MyToast(getResources().getString(R.string.emergency_sms_number_empty));
return;
}
String cellphone_Numbers = VariableKeeper.mSp.getString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, null);
if ("".equals(cellphone_Numbers) || cellphone_Numbers == null) {
//第一次设置紧急联络人
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, number);
editor.commit();
user_emergency_phone_number.setText("");
SystemUtil.MyToast(number + getResources().getString(R.string.emergency_sms_save_sucess_exist));
} else {
if (cellphone_Numbers.contains(number)) {
SystemUtil.MyToast(getResources().getString(R.string.emergency_sms_save_already_exist));
return;
}
//取出旧值然后和新值拼接起来重新保存
String newValues = cellphone_Numbers + "," + number;
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.APP_CONSTANT.sp_name_emergency_number, newValues);
editor.commit();
user_emergency_phone_number.setText("");
SystemUtil.MyToast(number + getResources().getString(R.string.emergency_sms_save_sucess_exist));
SystemUtil.log("new emergency phone numbers:" + newValues);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id_selected = item.getItemId();
switch (id_selected) {
case R.id.menu_emergency_help_settings_send_frequence_id:
//弹出设置短信发送频率和结束条件的对话框
openSmsSendFrequenceSettingDialog();
break;
case R.id.menu_emergency_stop_id:
//判断当前是否处于紧急危机遇险模式
boolean is_emergency = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);
if (is_emergency) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyActivity.this);
builder.setTitle(getResources().getString(R.string.dialog_tips_title)).setMessage(getResources().getString(R.string.menu_emergency_stop_tips_text)).setPositiveButton(getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);//false表示当前已经不处于紧急危险模式 用户成功脱险
editor.commit();
SystemUtil.MyToast(getResources().getString(R.string.menu_emergency_stop_success_toast_msg));
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
} else {
SystemUtil.MyToast(getResources().getString(R.string.menu_emergency_stop_error_text));
}
break;
}
return super.onOptionsItemSelected(item);
}
private void openSmsSendFrequenceSettingDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyActivity.this);
final View view_title = View.inflate(EmergencyActivity.this, R.layout.emergency_help_menu_setting_title, null);
final View view_body = View.inflate(EmergencyActivity.this, R.layout.emergency_help_menu_setting_body, null);
sms_send_frequence_id = (Spinner) view_body.findViewById(R.id.sms_send_frequence_id);
sms_stop_time_id = (Spinner) view_body.findViewById(R.id.sms_stop_time_id);
setUpSpinner();
Button setting_sms_save = (Button) view_body.findViewById(R.id.setting_sms_save);
Button setting_sms_cancel = (Button) view_body.findViewById(R.id.setting_sms_cancel);
TextView menu_emergency_help_settings_send_frequence_title_close = (TextView) view_title.findViewById(R.id.menu_emergency_help_settings_send_frequence_title_close);
setting_sms_save.setOnClickListener(EmergencyActivity.this);
setting_sms_cancel.setOnClickListener(EmergencyActivity.this);
menu_emergency_help_settings_send_frequence_title_close.setOnClickListener(EmergencyActivity.this);
builder.setCustomTitle(view_title);
builder.setView(view_body);
dialog_ = builder.create();
dialog_.show();
}
private void setUpSpinner() {
// sms_send_frequence_id = (Spinner) view_body.findViewById(R.id.sms_send_frequence_id);
// sms_stop_time_id = (Spinner) view_body.findViewById(R.id.sms_stop_time_id);
//取出对应的设置
long sms_send_frequence_time = VariableKeeper.mSp.getLong(VariableKeeper.APP_CONSTANT.sms_send_frequence_sp_name, 0);
long sms_stop_time = VariableKeeper.mSp.getLong(VariableKeeper.APP_CONSTANT.sms_stop_during_sp_name, 0);
if (sms_send_frequence_time == 0) {
//默认每五分钟一次 即选中第0项
sms_send_frequence_id.setSelection(0, true);
} else if (sms_send_frequence_time == 5) {
//默认每五分钟一次 即选中第0项
sms_send_frequence_id.setSelection(0, true);
} else if (sms_send_frequence_time == 10) {
sms_send_frequence_id.setSelection(1, true);
} else if (sms_send_frequence_time == 60) {
sms_send_frequence_id.setSelection(2, true);
} else if (sms_send_frequence_time == 120) {
sms_send_frequence_id.setSelection(3, true);
} else if (sms_send_frequence_time == 300) {
sms_send_frequence_id.setSelection(4, true);
}
if (sms_stop_time == 0) {
//默认为5小时后(300分钟) 即选中第2项
sms_stop_time_id.setSelection(2, true);
} else if (sms_stop_time == 20) {
sms_stop_time_id.setSelection(0, true);
} else if (sms_stop_time == 120) {
sms_stop_time_id.setSelection(1, true);
} else if (sms_stop_time == 300) {
sms_stop_time_id.setSelection(2, true);
} else if (sms_stop_time == 600) {
sms_stop_time_id.setSelection(3, true);
} else if (sms_stop_time == 888) {
sms_stop_time_id.setSelection(4, true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emergency_help_menu, menu);
SystemUtil.log("menu is here in emergency...");
return super.onCreateOptionsMenu(menu);
}
private void initTitle() {
rvt = new MyTitlebar(EmergencyActivity.this);
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
rvt.setShowRightBtn(true);
rvt.setRightBtnOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean ison_ = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
if (ison_) {
//当前已经开启 进入关闭状态
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setTitle(getResources().getString(R.string.emergency_sms_right_btn_emergency_off_title))
.setMessage(getResources().getString(R.string.emergency_sms_right_btn_emergency_off_msg))
.setPositiveButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_on_tips));
rvt.setTitle(getResources().getString(R.string.title_emergency_off));
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
editor.commit();
}
}).setNegativeButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
}
});
dialog = builder.create();
dialog.show();
} else {
//当前已经关闭 进入开启状态 首先要判断是否设定了紧急联络号码
LoadNumber();
if (phone_numbers == null || phone_numbers.size() == 0) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.emergency_sms_right_btn_emergency_on_error_titel), getResources().getString(R.string.emergency_sms_right_btn_emergency_on_error_msg));
} else if (!VariableKeeper.simStatus) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.dialog_tips_title), getResources().getString(R.string.emergency_sms_no_sim_error_msg));
} else {
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_off_tips));
rvt.setTitle(getResources().getString(R.string.title_emergency_on));
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, true);
editor.commit();
}
}
}
});
if (ison) {
//开启
rvt.setTitle(getResources().getString(R.string.title_emergency_on));
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_off_tips));
//紧急救援模式如果正在运行时即用户当前遭遇危险 则标题闪动 提示用户当前已经在向亲人报告坐标位置了
// mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.record_item_alpha)
} else {
//关闭
rvt.setTitle(getResources().getString(R.string.title_emergency_off));
rvt.setTextRightBtn(getResources().getString(R.string.emergency_sms_right_btn_on_tips));
}
rvt.setLeftBtnShow(true);
rvt.setLeftBtnOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
//紧急救援模式如果正在运行时即用户当前遭遇危险 则标题闪动 提示用户当前已经在向亲人报告坐标位置了
TextView tv_title = null;
if(ison){
boolean isEmergency_now = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.is_emergency_model_now_sp_name, false);
if(isEmergency_now){
tv_title = rvt.getTv_title();
if (tv_title != null) {
mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.record_item_alpha);
tv_title.setTextColor(Color.RED);
tv_title.startAnimation(mAnimation);
}else {
tv_title.setTextColor(Color.WHITE);
tv_title.clearAnimation();
}
}
}else {
tv_title = rvt.getTv_title();
if (tv_title != null) {
tv_title.setTextColor(Color.WHITE);
tv_title.clearAnimation();
}
}
}
@Override
public void stopAll() {
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.emergency_sms_save:
String phoneNumer = user_emergency_phone_number.getText().toString();
if (SystemUtil.phoneNumberCheck(phoneNumer)) {
savePhoneNumber(phoneNumer);
LoadNumber();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
break;
case R.id.setting_sms_save:
saveSmsSeting();
closeSettingDialog();
break;
case R.id.setting_sms_cancel:
closeSettingDialog();
break;
case R.id.menu_emergency_help_settings_send_frequence_title_close:
closeSettingDialog();
break;
}
}
private void saveSmsSeting() {
if (sms_stop_time_id != null && sms_send_frequence_id != null) {
long send_setting_id = sms_send_frequence_id.getSelectedItemId();
long stop_setting_id = sms_stop_time_id.getSelectedItemId();
//send_setting_id ===> 5分钟 ,10分钟 ,60分钟, 120分钟, 300分钟
//stop_setting_id ===> 20分钟, 120分钟, 300分钟, 600分钟
if (send_setting_id == 0) {
send_setting_id = 5;
} else if (send_setting_id == 1) {
send_setting_id = 10;
} else if (send_setting_id == 2) {
send_setting_id = 60;
} else if (send_setting_id == 3) {
send_setting_id = 120;
} else if (send_setting_id == 4) {
send_setting_id = 300;
}
if (stop_setting_id == 0) {
stop_setting_id = 20;
} else if (stop_setting_id == 1) {
stop_setting_id = 120;
} else if (stop_setting_id == 2) {
stop_setting_id = 300;
} else if (stop_setting_id == 3) {
stop_setting_id = 600;
} else if (stop_setting_id == 4) {
stop_setting_id = 888;//此值表示用户会手工停止(以后会加入远程短信的方式来停止 即解除紧急救援模式)
}
SystemUtil.log("send_setting_id:" + send_setting_id + ",stop_setting_id:" + stop_setting_id);
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putLong(VariableKeeper.APP_CONSTANT.sms_send_frequence_sp_name, send_setting_id);
editor.putLong(VariableKeeper.APP_CONSTANT.sms_stop_during_sp_name, stop_setting_id);
editor.commit();
SystemUtil.MyToast(getResources().getString(R.string.emergency_help_settings_success));
}
}
private void closeSettingDialog() {
if (dialog_ != null && dialog_.isShowing()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog_.dismiss();
}
});
}
}
@Override
public void onRefresh(final int position, Object data) {
//刷新紧急联系人列表listview,flag为删除的是第几项
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setTitle(getResources().getString(R.string.dialog_tips_title))
.setMessage(getResources().getString(R.string.emergency_sms_phone_delete_confirm_msg))
.setPositiveButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
boolean ison = VariableKeeper.mSp.getBoolean(VariableKeeper.APP_CONSTANT.sp_name_emergency_isOn, false);
if (ison) {
if (phone_numbers.size() == 1) {
SystemUtil.dialogJust4TipsShow(getResources().getString(R.string.dialog_tips_title), getResources().getString(R.string.emergency_sms_phone_delete_error_msg));
} else {
phone_numbers.remove(position);//更新数据
savePhoneNumbers();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
} else {
phone_numbers.remove(position);//更新数据
savePhoneNumbers();
emergencyAdaptor.dataReload(phone_numbers);
emergencyAdaptor.notifyDataSetChanged();
}
}
}).setNegativeButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
}
});
dialog = builder.create();
dialog.show();
}
});
}
}
| 23,784 | 0.579802 | 0.574288 | 480 | 46.983334 | 38.297787 | 269 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677083 | false | false | 8 |
c892564afda2161ae0ca3619fb4c9665e8596542 | 8,675,834,008,087 | aa0086f1b3ac00ed1346e7e4ee9affe08ea756b6 | /kzdoctorapp/src/main/java/com/tongxinyiliao/kzdoctorapp/main/MainActivity.java | 8300d12566be75e9e3971f38072c26dd4f97f68c | [] | no_license | guoyoujin/gz | https://github.com/guoyoujin/gz | 33ea48db6d9ebefded1dfc2a4d52613f6d5bab61 | 1e222fa92d1b442d490c0a7ca029021148235d35 | refs/heads/master | 2016-09-05T18:03:53.868000 | 2015-08-26T02:28:30 | 2015-08-26T02:28:30 | 37,524,125 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tongxinyiliao.kzdoctorapp.main;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.tongxinyiliao.kzdoctorapp.R;
import com.tongxinyiliao.kzdoctorapp.base.activity.BaseMyFragmentActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.HomeActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.MeActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.MessageActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.Order1Activity;
import java.util.ArrayList;
import java.util.List;
@SuppressLint("NewApi")
public class MainActivity extends BaseMyFragmentActivity implements OnPageChangeListener {
//initView
private ViewPager mViewPager;
private ImageView tab_img_message, tab_img_order, tab_img_me, tab_img_home;
TextView tv_titlebar_center,tv_titlebar_left;
//initData
ImageView[] tabs;
List<Fragment> fTabs = new ArrayList<Fragment>();
private FragmentPagerAdapter mAdapter;
String [] titleString={"首页","订单","消息","个人"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.app_img_loading)// 加载失败的时候
.cacheOnDisc().cacheInMemory().imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
initView();
initEvent();
initData();
}
/**
* 初始化界面
*/
protected void initView() {
mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
mViewPager.setOnPageChangeListener(this);
tv_titlebar_center= (TextView) findViewById(R.id.titlebar_tv_center);
tv_titlebar_center.setText("首页");
//设置titlebarleft隐藏
tv_titlebar_left= (TextView) findViewById(R.id.titlebar_tv_left);
tv_titlebar_left.setVisibility(View.INVISIBLE);
initTab();
}
@Override
protected void initEvent() {
}
;
/**
* 初始化界面
*/
void initTab() {
tab_img_home = (ImageView) findViewById(R.id.tab_img_home);
tab_img_home.setOnClickListener(this);
tab_img_order = (ImageView) findViewById(R.id.tab_img_order);
tab_img_order.setOnClickListener(this);
tab_img_message = (ImageView) findViewById(R.id.tab_img_message);
tab_img_message.setOnClickListener(this);
tab_img_me= (ImageView) findViewById(R.id.tab_img_me);
tab_img_me.setOnClickListener(this);
tabs = new ImageView[4];
tabs[0] = tab_img_home;
tabs[1] = tab_img_order;
tabs[2] = tab_img_message;
tabs[3] = tab_img_me;
tabs[0].setSelected(true);
}
/**
* 初始化数据
*/
protected void initData() {
HomeActivity homeActivity=new HomeActivity();
Order1Activity order1Activity =new Order1Activity();
MessageActivity messageActivity=new MessageActivity();
MeActivity meActivity=new MeActivity();
//设置三个界面
fTabs.add(homeActivity);
fTabs.add(order1Activity);
fTabs.add(messageActivity);
fTabs.add(meActivity);
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public int getCount() {
return fTabs.size();
}
@Override
public Fragment getItem(int position) {
return fTabs.get(position);
}
};
//设置viewpager的缓存页面的个数
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(mAdapter);
}
//tab的点击事件
@Override
public void onClick(View v) {
int vid = v.getId();
switch (vid) {
case R.id.tab_img_home: {
selectedTab(0);
break;
}
case R.id.tab_img_order: {
selectedTab(1);
break;
}
case R.id.tab_img_message: {
selectedTab(2);
break;
}
case R.id.tab_img_me: {
selectedTab(3);
break;
}
default:
selectedTab(0);
break;
}
}
/**
* 选择了那一项
*
* @param select
*/
void selectedTab(int select) {
for (int i = 0; i < tabs.length; i++) {
if (i == select) {
tabs[i].setSelected(true);
mViewPager.setCurrentItem(select, false);
} else {
tabs[i].setSelected(false);
}
}
//设置titlebar
tv_titlebar_center.setText(titleString[select]);
}
//viewpager 界面改变
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//界面发生改变时选择当前页面
selectedTab(position);
}
}
| UTF-8 | Java | 5,946 | java | MainActivity.java | Java | [] | null | [] | package com.tongxinyiliao.kzdoctorapp.main;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.tongxinyiliao.kzdoctorapp.R;
import com.tongxinyiliao.kzdoctorapp.base.activity.BaseMyFragmentActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.HomeActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.MeActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.MessageActivity;
import com.tongxinyiliao.kzdoctorapp.viewpager.Order1Activity;
import java.util.ArrayList;
import java.util.List;
@SuppressLint("NewApi")
public class MainActivity extends BaseMyFragmentActivity implements OnPageChangeListener {
//initView
private ViewPager mViewPager;
private ImageView tab_img_message, tab_img_order, tab_img_me, tab_img_home;
TextView tv_titlebar_center,tv_titlebar_left;
//initData
ImageView[] tabs;
List<Fragment> fTabs = new ArrayList<Fragment>();
private FragmentPagerAdapter mAdapter;
String [] titleString={"首页","订单","消息","个人"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.app_img_loading)// 加载失败的时候
.cacheOnDisc().cacheInMemory().imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
initView();
initEvent();
initData();
}
/**
* 初始化界面
*/
protected void initView() {
mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
mViewPager.setOnPageChangeListener(this);
tv_titlebar_center= (TextView) findViewById(R.id.titlebar_tv_center);
tv_titlebar_center.setText("首页");
//设置titlebarleft隐藏
tv_titlebar_left= (TextView) findViewById(R.id.titlebar_tv_left);
tv_titlebar_left.setVisibility(View.INVISIBLE);
initTab();
}
@Override
protected void initEvent() {
}
;
/**
* 初始化界面
*/
void initTab() {
tab_img_home = (ImageView) findViewById(R.id.tab_img_home);
tab_img_home.setOnClickListener(this);
tab_img_order = (ImageView) findViewById(R.id.tab_img_order);
tab_img_order.setOnClickListener(this);
tab_img_message = (ImageView) findViewById(R.id.tab_img_message);
tab_img_message.setOnClickListener(this);
tab_img_me= (ImageView) findViewById(R.id.tab_img_me);
tab_img_me.setOnClickListener(this);
tabs = new ImageView[4];
tabs[0] = tab_img_home;
tabs[1] = tab_img_order;
tabs[2] = tab_img_message;
tabs[3] = tab_img_me;
tabs[0].setSelected(true);
}
/**
* 初始化数据
*/
protected void initData() {
HomeActivity homeActivity=new HomeActivity();
Order1Activity order1Activity =new Order1Activity();
MessageActivity messageActivity=new MessageActivity();
MeActivity meActivity=new MeActivity();
//设置三个界面
fTabs.add(homeActivity);
fTabs.add(order1Activity);
fTabs.add(messageActivity);
fTabs.add(meActivity);
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public int getCount() {
return fTabs.size();
}
@Override
public Fragment getItem(int position) {
return fTabs.get(position);
}
};
//设置viewpager的缓存页面的个数
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(mAdapter);
}
//tab的点击事件
@Override
public void onClick(View v) {
int vid = v.getId();
switch (vid) {
case R.id.tab_img_home: {
selectedTab(0);
break;
}
case R.id.tab_img_order: {
selectedTab(1);
break;
}
case R.id.tab_img_message: {
selectedTab(2);
break;
}
case R.id.tab_img_me: {
selectedTab(3);
break;
}
default:
selectedTab(0);
break;
}
}
/**
* 选择了那一项
*
* @param select
*/
void selectedTab(int select) {
for (int i = 0; i < tabs.length; i++) {
if (i == select) {
tabs[i].setSelected(true);
mViewPager.setCurrentItem(select, false);
} else {
tabs[i].setSelected(false);
}
}
//设置titlebar
tv_titlebar_center.setText(titleString[select]);
}
//viewpager 界面改变
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//界面发生改变时选择当前页面
selectedTab(position);
}
}
| 5,946 | 0.632307 | 0.627119 | 189 | 29.592592 | 24.767878 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529101 | false | false | 8 |
18c6a54ca61fe634840cbe2bf3e532a687946d09 | 11,201,274,713,337 | 05be63d920085c326ca906b7d46a35065e6873a3 | /app/src/main/java/com/apsit/toll/data/network/pojo/toll/Toll.java | dcb811bc934251dc6c2174bccc03fd0a0280a727 | [] | no_license | adibaba1995/Toll | https://github.com/adibaba1995/Toll | 59b5c495fa4147ef5d9a6cfb2d4e8cb1387f73ae | 114ba0b79cb0627aa19edad3f47af3a49127bf9b | refs/heads/master | 2021-03-30T15:32:23.279000 | 2017-04-02T11:26:46 | 2017-04-02T11:26:46 | 85,519,568 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.apsit.toll.data.network.pojo.toll;
import android.util.Log;
public class Toll {
public static final int SELECT_TYPE_TWO_AXLE = 1;
public static final int SELECT_TYPE_TWO_AXLE_HEAVY = 2;
public static final int SELECT_TYPE_LCV = 3;
public static final int SELECT_TYPE_UPTO_THREE_AXLE = 4;
public static final int SELECT_TYPE_FOUR_AXLE_MORE = 5;
private boolean selected, paid;
public static int selectType;
private long id;
private String place_id;
private double upto_three_axle;
private double four_axle_more;
private String address;
private String name;
private double two_axle_heavy;
private String state;
private double longitude;
private double latitude;
private double LCV;
private double two_axle;
private String country;
public Toll() {
super();
selected = true;
paid = false;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlace_id ()
{
return place_id;
}
public void setPlace_id (String place_id)
{
this.place_id = place_id;
}
public double getUpto_three_axle() {
return upto_three_axle;
}
public void setUpto_three_axle(double upto_three_axle) {
this.upto_three_axle = upto_three_axle;
}
public double getFour_axle_more() {
return four_axle_more;
}
public void setFour_axle_more(double four_axle_more) {
this.four_axle_more = four_axle_more;
}
public double getTwo_axle_heavy() {
return two_axle_heavy;
}
public void setTwo_axle_heavy(double two_axle_heavy) {
this.two_axle_heavy = two_axle_heavy;
}
public double getTwo_axle() {
return two_axle;
}
public void setTwo_axle(double two_axle) {
this.two_axle = two_axle;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getState ()
{
return state;
}
public void setState (String state)
{
this.state = state;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLCV() {
return LCV;
}
public void setLCV(double LCV) {
this.LCV = LCV;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isPaid() {
return paid;
}
public void setPaid(boolean paid) {
this.paid = paid;
}
public double getPrice() {
switch (selectType) {
case Toll.SELECT_TYPE_TWO_AXLE:
return getTwo_axle();
case Toll.SELECT_TYPE_TWO_AXLE_HEAVY:
return getTwo_axle_heavy();
case Toll.SELECT_TYPE_LCV:
return getLCV();
case Toll.SELECT_TYPE_UPTO_THREE_AXLE:
return getUpto_three_axle();
case Toll.SELECT_TYPE_FOUR_AXLE_MORE:
return getFour_axle_more();
default:
return 0;
}
}
@Override
public String toString()
{
return "ClassPojo [id = "+id+", place_id = "+place_id+", upto_three_axle = "+upto_three_axle+", four_axle_more = "+four_axle_more+", address = "+address+", name = "+name+", two_axle_heavy = "+two_axle_heavy+", state = "+state+", longitude = "+longitude+", latitude = "+latitude+", LCV = "+LCV+", two_axle = "+two_axle+", country = "+country+"]";
}
} | UTF-8 | Java | 4,239 | java | Toll.java | Java | [] | null | [] | package com.apsit.toll.data.network.pojo.toll;
import android.util.Log;
public class Toll {
public static final int SELECT_TYPE_TWO_AXLE = 1;
public static final int SELECT_TYPE_TWO_AXLE_HEAVY = 2;
public static final int SELECT_TYPE_LCV = 3;
public static final int SELECT_TYPE_UPTO_THREE_AXLE = 4;
public static final int SELECT_TYPE_FOUR_AXLE_MORE = 5;
private boolean selected, paid;
public static int selectType;
private long id;
private String place_id;
private double upto_three_axle;
private double four_axle_more;
private String address;
private String name;
private double two_axle_heavy;
private String state;
private double longitude;
private double latitude;
private double LCV;
private double two_axle;
private String country;
public Toll() {
super();
selected = true;
paid = false;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlace_id ()
{
return place_id;
}
public void setPlace_id (String place_id)
{
this.place_id = place_id;
}
public double getUpto_three_axle() {
return upto_three_axle;
}
public void setUpto_three_axle(double upto_three_axle) {
this.upto_three_axle = upto_three_axle;
}
public double getFour_axle_more() {
return four_axle_more;
}
public void setFour_axle_more(double four_axle_more) {
this.four_axle_more = four_axle_more;
}
public double getTwo_axle_heavy() {
return two_axle_heavy;
}
public void setTwo_axle_heavy(double two_axle_heavy) {
this.two_axle_heavy = two_axle_heavy;
}
public double getTwo_axle() {
return two_axle;
}
public void setTwo_axle(double two_axle) {
this.two_axle = two_axle;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getState ()
{
return state;
}
public void setState (String state)
{
this.state = state;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLCV() {
return LCV;
}
public void setLCV(double LCV) {
this.LCV = LCV;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isPaid() {
return paid;
}
public void setPaid(boolean paid) {
this.paid = paid;
}
public double getPrice() {
switch (selectType) {
case Toll.SELECT_TYPE_TWO_AXLE:
return getTwo_axle();
case Toll.SELECT_TYPE_TWO_AXLE_HEAVY:
return getTwo_axle_heavy();
case Toll.SELECT_TYPE_LCV:
return getLCV();
case Toll.SELECT_TYPE_UPTO_THREE_AXLE:
return getUpto_three_axle();
case Toll.SELECT_TYPE_FOUR_AXLE_MORE:
return getFour_axle_more();
default:
return 0;
}
}
@Override
public String toString()
{
return "ClassPojo [id = "+id+", place_id = "+place_id+", upto_three_axle = "+upto_three_axle+", four_axle_more = "+four_axle_more+", address = "+address+", name = "+name+", two_axle_heavy = "+two_axle_heavy+", state = "+state+", longitude = "+longitude+", latitude = "+latitude+", LCV = "+LCV+", two_axle = "+two_axle+", country = "+country+"]";
}
} | 4,239 | 0.576787 | 0.575372 | 202 | 19.990099 | 29.282169 | 353 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371287 | false | false | 8 |
44f2082866e2b34588431880a9588188b587e544 | 9,302,899,179,627 | 6c707137cc87139c6840a974eb823938514cff8d | /Java Basics/ConstructorChaining.java | ce0c6a544f06aab9f5bb8d15ca9746dbf1cbf36a | [] | no_license | dominant001/Java-Learning | https://github.com/dominant001/Java-Learning | bd26d11e2f1b1b43ca4b8150106e712f237b026a | c1cd71debb3336ba3d7a5d901d25dd3fef61a1b6 | refs/heads/main | 2023-06-06T03:01:02.151000 | 2021-06-26T19:49:58 | 2021-06-26T19:49:58 | 380,571,667 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
class Ax{
public Ax(){
System.out.println("A1");
}
}
class Bx extends Ax{
public Bx(){
this(5);// call the second Bx constructer
System.out.println("B1");
}
public Bx(int x){
super();// call the parent class constructer
System.out.println("B2");
}
}
public class ConstructorChaining {
public static void main(String[] args){
Bx obj = new Bx();
}
}
//if we not write the super or this the compiler already write super in sub class to call the parent class constructer
//but if we want to call the other constructer of the same class instead of parent class so we can write this. | UTF-8 | Java | 715 | java | ConstructorChaining.java | Java | [] | null | [] | package com.company;
class Ax{
public Ax(){
System.out.println("A1");
}
}
class Bx extends Ax{
public Bx(){
this(5);// call the second Bx constructer
System.out.println("B1");
}
public Bx(int x){
super();// call the parent class constructer
System.out.println("B2");
}
}
public class ConstructorChaining {
public static void main(String[] args){
Bx obj = new Bx();
}
}
//if we not write the super or this the compiler already write super in sub class to call the parent class constructer
//but if we want to call the other constructer of the same class instead of parent class so we can write this. | 715 | 0.612587 | 0.606993 | 30 | 21.9 | 29.352285 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.233333 | false | false | 8 |
c87359493108e391eb68f3581f2ecb2c4a1b1c6e | 24,970,939,873,721 | 4782ba235d0ad171c597408e998800da58438874 | /src/data_structures/linked_list/Queue.java | 39c66549e8140f05759592142c7a488c6db76bad | [] | no_license | KaranRohra/Data-Structures-and-Algorithm-in-Java | https://github.com/KaranRohra/Data-Structures-and-Algorithm-in-Java | 773b109b72298812a7c98937a678e8abe18431ca | db1683b870a8cddba36a4f83bab9cc99d27eac61 | refs/heads/master | 2023-02-12T15:34:47.215000 | 2021-01-17T10:58:47 | 2021-01-17T10:58:47 | 323,531,189 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package data_structures.linked_list;
interface QueueADT<T>{
void add(T data);
T remove();
T getFirst();
T getLast();
boolean isEmpty();
int size();
void addLast(T data);
T removeFirst();
}
public class Queue<T> implements QueueADT<T>{
private Node<T> front;
private Node<T> rear;
private int size;
@Override
public void add(T data){
Node<T> toInsert=new Node<>(data);
if(front==null)
front=toInsert;
else
rear.next=toInsert;
size++;
rear=toInsert;
}
@Override
public T remove(){
if(front==null)
return null;
Node<T> toDelete=front;
front=front.next;
if(front==null)
rear=null;
toDelete.next=null;
size--;
return toDelete.data;
}
@Override
public T getFirst() {
return front.data;
}
@Override
public T getLast() {
return rear.data;
}
@Override
public boolean isEmpty(){
return size==0;
}
@Override
public int size() {
return size;
}
@Override
public void addLast(T data){
add(data);
}
@Override
public T removeFirst() {
return remove();
}
@Override
public String toString() {
return new ToStringClass().toString(size,front);
}
}
| UTF-8 | Java | 1,392 | java | Queue.java | Java | [] | null | [] | package data_structures.linked_list;
interface QueueADT<T>{
void add(T data);
T remove();
T getFirst();
T getLast();
boolean isEmpty();
int size();
void addLast(T data);
T removeFirst();
}
public class Queue<T> implements QueueADT<T>{
private Node<T> front;
private Node<T> rear;
private int size;
@Override
public void add(T data){
Node<T> toInsert=new Node<>(data);
if(front==null)
front=toInsert;
else
rear.next=toInsert;
size++;
rear=toInsert;
}
@Override
public T remove(){
if(front==null)
return null;
Node<T> toDelete=front;
front=front.next;
if(front==null)
rear=null;
toDelete.next=null;
size--;
return toDelete.data;
}
@Override
public T getFirst() {
return front.data;
}
@Override
public T getLast() {
return rear.data;
}
@Override
public boolean isEmpty(){
return size==0;
}
@Override
public int size() {
return size;
}
@Override
public void addLast(T data){
add(data);
}
@Override
public T removeFirst() {
return remove();
}
@Override
public String toString() {
return new ToStringClass().toString(size,front);
}
}
| 1,392 | 0.534483 | 0.533764 | 78 | 16.846153 | 12.010761 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 8 |
b6f3e8e7795526d6ef637aaef1f5ba793e2fa747 | 14,242,111,558,702 | 0354f2bd4220f4be82d3f5171f8c7736ecb55957 | /Java/Java Projects/SourceCode/Chapter_10/Example10_19/TrafficLightPolymorphism.java | d4213f7a75d30b70ad959fb4f047dd47feadf40d | [] | no_license | CableX88/Projects | https://github.com/CableX88/Projects | 8e57bf1a98fe655ffa5f95d6b5c04ba4cde046ef | 53eab0f3189239a590faab0f637b033c75c32514 | refs/heads/master | 2022-04-14T08:40:07.112000 | 2020-03-09T19:50:42 | 2020-03-09T19:50:42 | 101,965,196 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Figure Hierarchy Client using Polymorphism
* Anderson, Franceschi
*/
import javax.swing.JFrame;
import java.awt.*;
import java.util.ArrayList;
public class TrafficLightPolymorphism extends JFrame
{
private ArrayList<Figure> figuresList;
public TrafficLightPolymorphism( )
{
figuresList = new ArrayList<Figure>( );
figuresList.add( new Square( 150, 100, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 110, Color.RED, 10 ) );
figuresList.add( new Square( 150, 140, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 150, Color.YELLOW, 10 ) );
figuresList.add( new Square( 150, 180, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 190, Color.GREEN, 10 ) );
}
public void paint( Graphics g )
{
for ( Figure f : figuresList )
f.draw( g );
}
public static void main( String [] args )
{
TrafficLightPolymorphism app = new TrafficLightPolymorphism( );
app.setSize( 340, 300 );
app.setVisible( true );
}
}
| UTF-8 | Java | 1,001 | java | TrafficLightPolymorphism.java | Java | [
{
"context": "/* Figure Hierarchy Client using Polymorphism\n * Anderson, Franceschi\n*/\nimport javax.swing.JFrame;\nimport j",
"end": 57,
"score": 0.9859922528266907,
"start": 49,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "e Hierarchy Client using Polymorphism\n * Anderson, Franceschi\n*/\nimport javax.swing.JFrame;\nimport java.awt.*;\n",
"end": 69,
"score": 0.9271948337554932,
"start": 59,
"tag": "NAME",
"value": "Franceschi"
}
] | null | [] | /* Figure Hierarchy Client using Polymorphism
* Anderson, Franceschi
*/
import javax.swing.JFrame;
import java.awt.*;
import java.util.ArrayList;
public class TrafficLightPolymorphism extends JFrame
{
private ArrayList<Figure> figuresList;
public TrafficLightPolymorphism( )
{
figuresList = new ArrayList<Figure>( );
figuresList.add( new Square( 150, 100, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 110, Color.RED, 10 ) );
figuresList.add( new Square( 150, 140, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 150, Color.YELLOW, 10 ) );
figuresList.add( new Square( 150, 180, Color.BLACK, 40 ) );
figuresList.add( new Circle( 160, 190, Color.GREEN, 10 ) );
}
public void paint( Graphics g )
{
for ( Figure f : figuresList )
f.draw( g );
}
public static void main( String [] args )
{
TrafficLightPolymorphism app = new TrafficLightPolymorphism( );
app.setSize( 340, 300 );
app.setVisible( true );
}
}
| 1,001 | 0.666334 | 0.612388 | 37 | 26.054054 | 23.772511 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.945946 | false | false | 8 |
5af7a822cbfedf1815997712992c04ce4d480cbb | 11,278,584,135,402 | 53cdcbf9e4f3c2baf340fd41c3af57556d85dcf5 | /app/src/main/java/com/miapple/myapplication/MainActivity.java | 4d52a0fac9898d77ee00529e823f766fa784a351 | [] | no_license | turboburst/MyApplication3 | https://github.com/turboburst/MyApplication3 | f43a47cd40624719b0c87dd911c8140626547a09 | bb907612bf910721a31b91244df7a9d2b92315b4 | refs/heads/master | 2016-06-14T14:24:58.058000 | 2016-05-08T12:24:02 | 2016-05-08T12:24:02 | 58,310,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.miapple.myapplication;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private TextView MondayCourse1, MondayCourse2, MondayCourse3, MondayCourse4, MondayCourse5, MondayCourse6,
MondayCourse7, MondayCourse8, MondayCourse9, MondayCourse10, MondayCourse11, MondayCourse12,
TuesdayCourse1, TuesdayCourse2, TuesdayCourse3, TuesdayCourse4, TuesdayCourse5, TuesdayCourse6,
TuesdayCourse7, TuesdayCourse8, TuesdayCourse9, TuesdayCourse10, TuesdayCourse11, TuesdayCourse12,
WednesdayCourse1, WednesdayCourse2, WednesdayCourse3, WednesdayCourse4, WednesdayCourse5, WednesdayCourse6,
WednesdayCourse7, WednesdayCourse8, WednesdayCourse9, WednesdayCourse10, WednesdayCourse11, WednesdayCourse12,
ThursdayCourse1, ThursdayCourse2, ThursdayCourse3, ThursdayCourse4, ThursdayCourse5, ThursdayCourse6,
ThursdayCourse7, ThursdayCourse8, ThursdayCourse9, ThursdayCourse10, ThursdayCourse11, ThursdayCourse12,
FridayCourse1, FridayCourse2, FridayCourse3, FridayCourse4, FridayCourse5, FridayCourse6, FridayCourse7,
FridayCourse8, FridayCourse9, FridayCourse10, FridayCourse11, FridayCourse12,
SaturdayCourse1, SaturdayCourse2, SaturdayCourse3, SaturdayCourse4, SaturdayCourse5,SaturdayCourse6,
SaturdayCourse7, SaturdayCourse8, SaturdayCourse9, SaturdayCourse10, SaturdayCourse11, SaturdayCourse12,
SundayCourse1, SundayCourse2, SundayCourse3, SundayCourse4, SundayCourse5, SundayCourse6, SundayCourse7,
SundayCourse8, SundayCourse9, SundayCourse10, SundayCourse11, SundayCourse12;
private TextView[] theTextViewArray;
private Map<Integer, TextView> theTextViewMap;
private LinkedList theLinkedList;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MondayCourse1 = (TextView)findViewById(R.id.MondayFirstCourseID);
MondayCourse2 = (TextView)findViewById(R.id.MondaySecondCourseID);
MondayCourse3 = (TextView)findViewById(R.id.MondayThirdCourseID);
MondayCourse4 = (TextView)findViewById(R.id.MondayFourthCourseID);
MondayCourse5 = (TextView)findViewById(R.id.MondayFivethCourseID);
MondayCourse6 = (TextView)findViewById(R.id.MondaySixthCourseID);
MondayCourse7 = (TextView)findViewById(R.id.MondaySeventhCourseID);
MondayCourse8 = (TextView)findViewById(R.id.MondayEightthCourseID);
MondayCourse9 = (TextView)findViewById(R.id.MondayNinethCourseID);
MondayCourse10 = (TextView)findViewById(R.id.MondayTenthCourseID);
MondayCourse11 = (TextView)findViewById(R.id.MondayEleventhCourseID);
MondayCourse12 = (TextView)findViewById(R.id.MondayTwelvethCourseID);
TuesdayCourse1 = (TextView)findViewById(R.id.TuesdayFirstCourseID);
TuesdayCourse2 = (TextView)findViewById(R.id.TuesdaySecondCourseID);
TuesdayCourse3 = (TextView)findViewById(R.id.TuesdayThirdCourseID);
TuesdayCourse4 = (TextView)findViewById(R.id.TuesdayFourthCourseID);
TuesdayCourse5 = (TextView)findViewById(R.id.TuesdayFivethCourseID);
TuesdayCourse6 = (TextView)findViewById(R.id.TuesdaySixthCourseID);
TuesdayCourse7 = (TextView)findViewById(R.id.TuesdaySeventhCourseID);
TuesdayCourse8 = (TextView)findViewById(R.id.TuesdayEightthCourseID);
TuesdayCourse9 = (TextView)findViewById(R.id.TuesdayNinethCourseID);
TuesdayCourse10 = (TextView)findViewById(R.id.TuesdayTenthCourseID);
TuesdayCourse11 = (TextView)findViewById(R.id.TuesdayEleventhCourseID);
TuesdayCourse12 = (TextView)findViewById(R.id.TuesdayTwelvethCourseID);
WednesdayCourse1 = (TextView)findViewById(R.id.WednesdayFirstCourseID);
WednesdayCourse2 = (TextView)findViewById(R.id.WednesdaySecondCourseID);
WednesdayCourse3 = (TextView)findViewById(R.id.WednesdayThirdCourseID);
WednesdayCourse4 = (TextView)findViewById(R.id.WednesdayFourthCourseID);
WednesdayCourse5 = (TextView)findViewById(R.id.WednesdayFivethCourseID);
WednesdayCourse6 = (TextView)findViewById(R.id.WednesdaySixthCourseID);
WednesdayCourse7 = (TextView)findViewById(R.id.WednesdaySeventhCourseID);
WednesdayCourse8 = (TextView)findViewById(R.id.WednesdayEightthCourseID);
WednesdayCourse9 = (TextView)findViewById(R.id.WednesdayNinethCourseID);
WednesdayCourse10 = (TextView)findViewById(R.id.WednesdayTenthCourseID);
WednesdayCourse11 = (TextView)findViewById(R.id.WednesdayEleventhCourseID);
WednesdayCourse12 = (TextView)findViewById(R.id.WednesdayTwelvethCourseID);
ThursdayCourse1 = (TextView)findViewById(R.id.ThursdayFirstCourseID);
ThursdayCourse2 = (TextView)findViewById(R.id.ThursdaySecondCourseID);
ThursdayCourse3 = (TextView)findViewById(R.id.ThursdayThirdCourseID);
ThursdayCourse4 = (TextView)findViewById(R.id.ThursdayFourthCourseID);
ThursdayCourse5 = (TextView)findViewById(R.id.ThursdayFivethCourseID);
ThursdayCourse6 = (TextView)findViewById(R.id.ThursdaySixthCourseID);
ThursdayCourse7 = (TextView)findViewById(R.id.ThursdaySeventhCourseID);
ThursdayCourse8 = (TextView)findViewById(R.id.ThursdayEightthCourseID);
ThursdayCourse9 = (TextView)findViewById(R.id.ThursdayNinethCourseID);
ThursdayCourse10 = (TextView)findViewById(R.id.ThursdayTenthCourseID);
ThursdayCourse11 = (TextView)findViewById(R.id.ThursdayEleventhCourseID);
ThursdayCourse12 = (TextView)findViewById(R.id.ThursdayTwelvethCourseID);
FridayCourse1 = (TextView)findViewById(R.id.FridayFirstCourseID);
FridayCourse2 = (TextView)findViewById(R.id.FridaySecondCourseID);
FridayCourse3 = (TextView)findViewById(R.id.FridayThirdCourseID);
FridayCourse4 = (TextView)findViewById(R.id.FridayFourthCourseID);
FridayCourse5 = (TextView)findViewById(R.id.FridayFivethCourseID);
FridayCourse6 = (TextView)findViewById(R.id.FridaySixthCourseID);
FridayCourse7 = (TextView)findViewById(R.id.FridaySeventhCourseID);
FridayCourse8 = (TextView)findViewById(R.id.FridayEightthCourseID);
FridayCourse9 = (TextView)findViewById(R.id.FridayNinethCourseID);
FridayCourse10 = (TextView)findViewById(R.id.FridayTenthCourseID);
FridayCourse11 = (TextView)findViewById(R.id.FridayEleventhCourseID);
FridayCourse12 = (TextView)findViewById(R.id.FridayTwelvethCourseID);
SaturdayCourse1 = (TextView)findViewById(R.id.SaturdayFirstCourseID);
SaturdayCourse2 = (TextView)findViewById(R.id.SaturdaySecondCourseID);
SaturdayCourse3 = (TextView)findViewById(R.id.SaturdayThirdCourseID);
SaturdayCourse4 = (TextView)findViewById(R.id.SaturdayFourthCourseID);
SaturdayCourse5 = (TextView)findViewById(R.id.SaturdayFivethCourseID);
SaturdayCourse6 = (TextView)findViewById(R.id.SaturdaySixthCourseID);
SaturdayCourse7 = (TextView)findViewById(R.id.SaturdaySeventhCourseID);
SaturdayCourse8 = (TextView)findViewById(R.id.SaturdayEightthCourseID);
SaturdayCourse9 = (TextView)findViewById(R.id.SaturdayNinethCourseID);
SaturdayCourse10 = (TextView)findViewById(R.id.SaturdayTenthCourseID);
SaturdayCourse11 = (TextView)findViewById(R.id.SaturdayEleventhCourseID);
SaturdayCourse12 = (TextView)findViewById(R.id.SaturdayTwelvethCourseID);
SundayCourse1 = (TextView)findViewById(R.id.SundayFirstCourseID);
SundayCourse2 = (TextView)findViewById(R.id.SundaySecondCourseID);
SundayCourse3 = (TextView)findViewById(R.id.SundayThirdCourseID);
SundayCourse4 = (TextView)findViewById(R.id.SundayFourthCourseID);
SundayCourse5 = (TextView)findViewById(R.id.SundayFivethCourseID);
SundayCourse6 = (TextView)findViewById(R.id.SundaySixthCourseID);
SundayCourse7 = (TextView)findViewById(R.id.SundaySeventhCourseID);
SundayCourse8 = (TextView)findViewById(R.id.SundayEightthCourseID);
SundayCourse9 = (TextView)findViewById(R.id.SundayNinethCourseID);
SundayCourse10 = (TextView)findViewById(R.id.SundayTenthCourseID);
SundayCourse11 = (TextView)findViewById(R.id.SundayEleventhCourseID);
SundayCourse12 = (TextView)findViewById(R.id.SundayTwelvethCourseID);
theTextViewArray = new TextView[]{MondayCourse1, MondayCourse2, MondayCourse3, MondayCourse4, MondayCourse5, MondayCourse6,
MondayCourse7, MondayCourse8, MondayCourse9, MondayCourse10, MondayCourse11, MondayCourse12,
TuesdayCourse1, TuesdayCourse2, TuesdayCourse3, TuesdayCourse4, TuesdayCourse5, TuesdayCourse6,
TuesdayCourse7, TuesdayCourse8, TuesdayCourse9, TuesdayCourse10, TuesdayCourse11, TuesdayCourse12,
WednesdayCourse1, WednesdayCourse2, WednesdayCourse3, WednesdayCourse4, WednesdayCourse5, WednesdayCourse6,
WednesdayCourse7, WednesdayCourse8, WednesdayCourse9, WednesdayCourse10, WednesdayCourse11, WednesdayCourse12,
ThursdayCourse1, ThursdayCourse2, ThursdayCourse3, ThursdayCourse4, ThursdayCourse5, ThursdayCourse6,
ThursdayCourse7, ThursdayCourse8, ThursdayCourse9, ThursdayCourse10, ThursdayCourse11, ThursdayCourse12,
FridayCourse1, FridayCourse2, FridayCourse3, FridayCourse4, FridayCourse5, FridayCourse6, FridayCourse7,
FridayCourse8, FridayCourse9, FridayCourse10, FridayCourse11, FridayCourse12,
SaturdayCourse1, SaturdayCourse2, SaturdayCourse3, SaturdayCourse4, SaturdayCourse5,SaturdayCourse6,
SaturdayCourse7, SaturdayCourse8, SaturdayCourse9, SaturdayCourse10, SaturdayCourse11, SaturdayCourse12,
SundayCourse1, SundayCourse2, SundayCourse3, SundayCourse4, SundayCourse5, SundayCourse6, SundayCourse7,
SundayCourse8, SundayCourse9, SundayCourse10, SundayCourse11, SundayCourse12};
LinkedList theLinkedList = new LinkedList<>();
for(int i = 1; i <= theTextViewArray.length; i++)
{
TextView tempTextView = theTextViewArray[i - 1];
/*theTextViewMap.put(i, tempTextView);*/
//theLinkedList.add(tempTextView);
tempTextView.setBackgroundResource(R.drawable.course_textview_border);
tempTextView.setText("course" + i);
tempTextView.setMaxEms(4);
tempTextView.setEllipsize(TextUtils.TruncateAt.END);
tempTextView.setMaxLines(1);
tempTextView.setOnClickListener(this);
}
}
@Override
public void onClick(View v)
{
MondayCourse2.setVisibility(View.GONE);
float scale = MainActivity.this.getResources().getDisplayMetrics().density;
MondayCourse1.getLayoutParams().height = (int) (120 * scale + 0.5f);
Toast.makeText(MainActivity.this, v.getClass().getSimpleName(), Toast.LENGTH_LONG).show();
}
}
| UTF-8 | Java | 11,548 | java | MainActivity.java | Java | [] | null | [] | package com.miapple.myapplication;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private TextView MondayCourse1, MondayCourse2, MondayCourse3, MondayCourse4, MondayCourse5, MondayCourse6,
MondayCourse7, MondayCourse8, MondayCourse9, MondayCourse10, MondayCourse11, MondayCourse12,
TuesdayCourse1, TuesdayCourse2, TuesdayCourse3, TuesdayCourse4, TuesdayCourse5, TuesdayCourse6,
TuesdayCourse7, TuesdayCourse8, TuesdayCourse9, TuesdayCourse10, TuesdayCourse11, TuesdayCourse12,
WednesdayCourse1, WednesdayCourse2, WednesdayCourse3, WednesdayCourse4, WednesdayCourse5, WednesdayCourse6,
WednesdayCourse7, WednesdayCourse8, WednesdayCourse9, WednesdayCourse10, WednesdayCourse11, WednesdayCourse12,
ThursdayCourse1, ThursdayCourse2, ThursdayCourse3, ThursdayCourse4, ThursdayCourse5, ThursdayCourse6,
ThursdayCourse7, ThursdayCourse8, ThursdayCourse9, ThursdayCourse10, ThursdayCourse11, ThursdayCourse12,
FridayCourse1, FridayCourse2, FridayCourse3, FridayCourse4, FridayCourse5, FridayCourse6, FridayCourse7,
FridayCourse8, FridayCourse9, FridayCourse10, FridayCourse11, FridayCourse12,
SaturdayCourse1, SaturdayCourse2, SaturdayCourse3, SaturdayCourse4, SaturdayCourse5,SaturdayCourse6,
SaturdayCourse7, SaturdayCourse8, SaturdayCourse9, SaturdayCourse10, SaturdayCourse11, SaturdayCourse12,
SundayCourse1, SundayCourse2, SundayCourse3, SundayCourse4, SundayCourse5, SundayCourse6, SundayCourse7,
SundayCourse8, SundayCourse9, SundayCourse10, SundayCourse11, SundayCourse12;
private TextView[] theTextViewArray;
private Map<Integer, TextView> theTextViewMap;
private LinkedList theLinkedList;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MondayCourse1 = (TextView)findViewById(R.id.MondayFirstCourseID);
MondayCourse2 = (TextView)findViewById(R.id.MondaySecondCourseID);
MondayCourse3 = (TextView)findViewById(R.id.MondayThirdCourseID);
MondayCourse4 = (TextView)findViewById(R.id.MondayFourthCourseID);
MondayCourse5 = (TextView)findViewById(R.id.MondayFivethCourseID);
MondayCourse6 = (TextView)findViewById(R.id.MondaySixthCourseID);
MondayCourse7 = (TextView)findViewById(R.id.MondaySeventhCourseID);
MondayCourse8 = (TextView)findViewById(R.id.MondayEightthCourseID);
MondayCourse9 = (TextView)findViewById(R.id.MondayNinethCourseID);
MondayCourse10 = (TextView)findViewById(R.id.MondayTenthCourseID);
MondayCourse11 = (TextView)findViewById(R.id.MondayEleventhCourseID);
MondayCourse12 = (TextView)findViewById(R.id.MondayTwelvethCourseID);
TuesdayCourse1 = (TextView)findViewById(R.id.TuesdayFirstCourseID);
TuesdayCourse2 = (TextView)findViewById(R.id.TuesdaySecondCourseID);
TuesdayCourse3 = (TextView)findViewById(R.id.TuesdayThirdCourseID);
TuesdayCourse4 = (TextView)findViewById(R.id.TuesdayFourthCourseID);
TuesdayCourse5 = (TextView)findViewById(R.id.TuesdayFivethCourseID);
TuesdayCourse6 = (TextView)findViewById(R.id.TuesdaySixthCourseID);
TuesdayCourse7 = (TextView)findViewById(R.id.TuesdaySeventhCourseID);
TuesdayCourse8 = (TextView)findViewById(R.id.TuesdayEightthCourseID);
TuesdayCourse9 = (TextView)findViewById(R.id.TuesdayNinethCourseID);
TuesdayCourse10 = (TextView)findViewById(R.id.TuesdayTenthCourseID);
TuesdayCourse11 = (TextView)findViewById(R.id.TuesdayEleventhCourseID);
TuesdayCourse12 = (TextView)findViewById(R.id.TuesdayTwelvethCourseID);
WednesdayCourse1 = (TextView)findViewById(R.id.WednesdayFirstCourseID);
WednesdayCourse2 = (TextView)findViewById(R.id.WednesdaySecondCourseID);
WednesdayCourse3 = (TextView)findViewById(R.id.WednesdayThirdCourseID);
WednesdayCourse4 = (TextView)findViewById(R.id.WednesdayFourthCourseID);
WednesdayCourse5 = (TextView)findViewById(R.id.WednesdayFivethCourseID);
WednesdayCourse6 = (TextView)findViewById(R.id.WednesdaySixthCourseID);
WednesdayCourse7 = (TextView)findViewById(R.id.WednesdaySeventhCourseID);
WednesdayCourse8 = (TextView)findViewById(R.id.WednesdayEightthCourseID);
WednesdayCourse9 = (TextView)findViewById(R.id.WednesdayNinethCourseID);
WednesdayCourse10 = (TextView)findViewById(R.id.WednesdayTenthCourseID);
WednesdayCourse11 = (TextView)findViewById(R.id.WednesdayEleventhCourseID);
WednesdayCourse12 = (TextView)findViewById(R.id.WednesdayTwelvethCourseID);
ThursdayCourse1 = (TextView)findViewById(R.id.ThursdayFirstCourseID);
ThursdayCourse2 = (TextView)findViewById(R.id.ThursdaySecondCourseID);
ThursdayCourse3 = (TextView)findViewById(R.id.ThursdayThirdCourseID);
ThursdayCourse4 = (TextView)findViewById(R.id.ThursdayFourthCourseID);
ThursdayCourse5 = (TextView)findViewById(R.id.ThursdayFivethCourseID);
ThursdayCourse6 = (TextView)findViewById(R.id.ThursdaySixthCourseID);
ThursdayCourse7 = (TextView)findViewById(R.id.ThursdaySeventhCourseID);
ThursdayCourse8 = (TextView)findViewById(R.id.ThursdayEightthCourseID);
ThursdayCourse9 = (TextView)findViewById(R.id.ThursdayNinethCourseID);
ThursdayCourse10 = (TextView)findViewById(R.id.ThursdayTenthCourseID);
ThursdayCourse11 = (TextView)findViewById(R.id.ThursdayEleventhCourseID);
ThursdayCourse12 = (TextView)findViewById(R.id.ThursdayTwelvethCourseID);
FridayCourse1 = (TextView)findViewById(R.id.FridayFirstCourseID);
FridayCourse2 = (TextView)findViewById(R.id.FridaySecondCourseID);
FridayCourse3 = (TextView)findViewById(R.id.FridayThirdCourseID);
FridayCourse4 = (TextView)findViewById(R.id.FridayFourthCourseID);
FridayCourse5 = (TextView)findViewById(R.id.FridayFivethCourseID);
FridayCourse6 = (TextView)findViewById(R.id.FridaySixthCourseID);
FridayCourse7 = (TextView)findViewById(R.id.FridaySeventhCourseID);
FridayCourse8 = (TextView)findViewById(R.id.FridayEightthCourseID);
FridayCourse9 = (TextView)findViewById(R.id.FridayNinethCourseID);
FridayCourse10 = (TextView)findViewById(R.id.FridayTenthCourseID);
FridayCourse11 = (TextView)findViewById(R.id.FridayEleventhCourseID);
FridayCourse12 = (TextView)findViewById(R.id.FridayTwelvethCourseID);
SaturdayCourse1 = (TextView)findViewById(R.id.SaturdayFirstCourseID);
SaturdayCourse2 = (TextView)findViewById(R.id.SaturdaySecondCourseID);
SaturdayCourse3 = (TextView)findViewById(R.id.SaturdayThirdCourseID);
SaturdayCourse4 = (TextView)findViewById(R.id.SaturdayFourthCourseID);
SaturdayCourse5 = (TextView)findViewById(R.id.SaturdayFivethCourseID);
SaturdayCourse6 = (TextView)findViewById(R.id.SaturdaySixthCourseID);
SaturdayCourse7 = (TextView)findViewById(R.id.SaturdaySeventhCourseID);
SaturdayCourse8 = (TextView)findViewById(R.id.SaturdayEightthCourseID);
SaturdayCourse9 = (TextView)findViewById(R.id.SaturdayNinethCourseID);
SaturdayCourse10 = (TextView)findViewById(R.id.SaturdayTenthCourseID);
SaturdayCourse11 = (TextView)findViewById(R.id.SaturdayEleventhCourseID);
SaturdayCourse12 = (TextView)findViewById(R.id.SaturdayTwelvethCourseID);
SundayCourse1 = (TextView)findViewById(R.id.SundayFirstCourseID);
SundayCourse2 = (TextView)findViewById(R.id.SundaySecondCourseID);
SundayCourse3 = (TextView)findViewById(R.id.SundayThirdCourseID);
SundayCourse4 = (TextView)findViewById(R.id.SundayFourthCourseID);
SundayCourse5 = (TextView)findViewById(R.id.SundayFivethCourseID);
SundayCourse6 = (TextView)findViewById(R.id.SundaySixthCourseID);
SundayCourse7 = (TextView)findViewById(R.id.SundaySeventhCourseID);
SundayCourse8 = (TextView)findViewById(R.id.SundayEightthCourseID);
SundayCourse9 = (TextView)findViewById(R.id.SundayNinethCourseID);
SundayCourse10 = (TextView)findViewById(R.id.SundayTenthCourseID);
SundayCourse11 = (TextView)findViewById(R.id.SundayEleventhCourseID);
SundayCourse12 = (TextView)findViewById(R.id.SundayTwelvethCourseID);
theTextViewArray = new TextView[]{MondayCourse1, MondayCourse2, MondayCourse3, MondayCourse4, MondayCourse5, MondayCourse6,
MondayCourse7, MondayCourse8, MondayCourse9, MondayCourse10, MondayCourse11, MondayCourse12,
TuesdayCourse1, TuesdayCourse2, TuesdayCourse3, TuesdayCourse4, TuesdayCourse5, TuesdayCourse6,
TuesdayCourse7, TuesdayCourse8, TuesdayCourse9, TuesdayCourse10, TuesdayCourse11, TuesdayCourse12,
WednesdayCourse1, WednesdayCourse2, WednesdayCourse3, WednesdayCourse4, WednesdayCourse5, WednesdayCourse6,
WednesdayCourse7, WednesdayCourse8, WednesdayCourse9, WednesdayCourse10, WednesdayCourse11, WednesdayCourse12,
ThursdayCourse1, ThursdayCourse2, ThursdayCourse3, ThursdayCourse4, ThursdayCourse5, ThursdayCourse6,
ThursdayCourse7, ThursdayCourse8, ThursdayCourse9, ThursdayCourse10, ThursdayCourse11, ThursdayCourse12,
FridayCourse1, FridayCourse2, FridayCourse3, FridayCourse4, FridayCourse5, FridayCourse6, FridayCourse7,
FridayCourse8, FridayCourse9, FridayCourse10, FridayCourse11, FridayCourse12,
SaturdayCourse1, SaturdayCourse2, SaturdayCourse3, SaturdayCourse4, SaturdayCourse5,SaturdayCourse6,
SaturdayCourse7, SaturdayCourse8, SaturdayCourse9, SaturdayCourse10, SaturdayCourse11, SaturdayCourse12,
SundayCourse1, SundayCourse2, SundayCourse3, SundayCourse4, SundayCourse5, SundayCourse6, SundayCourse7,
SundayCourse8, SundayCourse9, SundayCourse10, SundayCourse11, SundayCourse12};
LinkedList theLinkedList = new LinkedList<>();
for(int i = 1; i <= theTextViewArray.length; i++)
{
TextView tempTextView = theTextViewArray[i - 1];
/*theTextViewMap.put(i, tempTextView);*/
//theLinkedList.add(tempTextView);
tempTextView.setBackgroundResource(R.drawable.course_textview_border);
tempTextView.setText("course" + i);
tempTextView.setMaxEms(4);
tempTextView.setEllipsize(TextUtils.TruncateAt.END);
tempTextView.setMaxLines(1);
tempTextView.setOnClickListener(this);
}
}
@Override
public void onClick(View v)
{
MondayCourse2.setVisibility(View.GONE);
float scale = MainActivity.this.getResources().getDisplayMetrics().density;
MondayCourse1.getLayoutParams().height = (int) (120 * scale + 0.5f);
Toast.makeText(MainActivity.this, v.getClass().getSimpleName(), Toast.LENGTH_LONG).show();
}
}
| 11,548 | 0.750953 | 0.722636 | 179 | 63.513966 | 35.330421 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.620112 | false | false | 8 |
d8328006d696875b54fdd528c0d5d5aae6806630 | 5,248,450,057,441 | 037637a2c0d177362285e0608d4f4f00dc4cfce9 | /components/camel-avro/src/main/java/org/apache/camel/component/avro/AvroNettyEndpoint.java | 8cec7251799f892e77ff08d92da5d0f87a5de888 | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | dmgerman/camel | https://github.com/dmgerman/camel | 07379b6a1d191078b085b62bbb0a6732141994aa | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | refs/heads/master | 2023-01-03T23:00:15.190000 | 2019-12-20T08:30:29 | 2019-12-20T08:30:29 | 230,528,998 | 0 | 0 | Apache-2.0 | false | 2023-01-02T22:14:35 | 2019-12-27T22:50:51 | 2019-12-28T01:30:10 | 2023-01-02T22:14:34 | 129,843 | 0 | 0 | 3 | Java | false | false | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.component.avro
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|avro
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Component
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Producer
import|;
end_import
begin_class
DECL|class|AvroNettyEndpoint
specifier|public
class|class
name|AvroNettyEndpoint
extends|extends
name|AvroEndpoint
block|{
comment|/** * Constructs a fully-initialized DefaultEndpoint instance. This is the * preferred method of constructing an object from Java code (as opposed to * Spring beans, etc.). * * @param endpointUri the full URI used to create this endpoint * @param component the component that created this endpoint */
DECL|method|AvroNettyEndpoint (String endpointUri, Component component, AvroConfiguration configuration)
specifier|public
name|AvroNettyEndpoint
parameter_list|(
name|String
name|endpointUri
parameter_list|,
name|Component
name|component
parameter_list|,
name|AvroConfiguration
name|configuration
parameter_list|)
block|{
name|super
argument_list|(
name|endpointUri
argument_list|,
name|component
argument_list|,
name|configuration
argument_list|)
expr_stmt|;
block|}
comment|/** * Creates a new producer which is used send messages into the endpoint * * @return a newly created producer * @throws Exception can be thrown */
annotation|@
name|Override
DECL|method|createProducer ()
specifier|public
name|Producer
name|createProducer
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|AvroNettyProducer
argument_list|(
name|this
argument_list|)
return|;
block|}
block|}
end_class
end_unit
| UTF-8 | Java | 2,785 | java | AvroNettyEndpoint.java | Java | [] | null | [] | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.component.avro
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|avro
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Component
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Producer
import|;
end_import
begin_class
DECL|class|AvroNettyEndpoint
specifier|public
class|class
name|AvroNettyEndpoint
extends|extends
name|AvroEndpoint
block|{
comment|/** * Constructs a fully-initialized DefaultEndpoint instance. This is the * preferred method of constructing an object from Java code (as opposed to * Spring beans, etc.). * * @param endpointUri the full URI used to create this endpoint * @param component the component that created this endpoint */
DECL|method|AvroNettyEndpoint (String endpointUri, Component component, AvroConfiguration configuration)
specifier|public
name|AvroNettyEndpoint
parameter_list|(
name|String
name|endpointUri
parameter_list|,
name|Component
name|component
parameter_list|,
name|AvroConfiguration
name|configuration
parameter_list|)
block|{
name|super
argument_list|(
name|endpointUri
argument_list|,
name|component
argument_list|,
name|configuration
argument_list|)
expr_stmt|;
block|}
comment|/** * Creates a new producer which is used send messages into the endpoint * * @return a newly created producer * @throws Exception can be thrown */
annotation|@
name|Override
DECL|method|createProducer ()
specifier|public
name|Producer
name|createProducer
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|AvroNettyProducer
argument_list|(
name|this
argument_list|)
return|;
block|}
block|}
end_class
end_unit
| 2,785 | 0.771275 | 0.767684 | 100 | 26.84 | 87.662956 | 810 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.07 | false | false | 8 |
3725e934e9da7a02ed61824b8ebbe587cd8a942d | 10,703,058,529,100 | c5155d951792f8bb3cc3c0c8fc471b29a9c85df4 | /cloud-yunying-module8005/src/main/java/com/donglan/Module8005Application.java | 87fd88b2e8ecfeee51cb10a5a24bf18fd8f4b14d | [] | no_license | taojian9706/springcloud-2021 | https://github.com/taojian9706/springcloud-2021 | 23b88e514ef265ee34a6b6446618a0ef5c00a0e5 | 63a6619aec197b8ed89e3cd16ff64e735938bfdd | refs/heads/master | 2023-02-27T06:58:13.215000 | 2021-02-03T03:17:48 | 2021-02-03T03:17:48 | 332,134,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.donglan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author TAOJIAN
* @version 1.0
* @since 2021-01-25 11:02:22
*/
@SpringBootApplication
@EnableEurekaClient
@MapperScan(basePackages = "com.donglan.dao")
public class Module8005Application {
public static void main(String[] args) {
SpringApplication.run(Module8005Application.class, args);
}
}
| UTF-8 | Java | 579 | java | Module8005Application.java | Java | [
{
"context": "netflix.eureka.EnableEurekaClient;\n\n/**\n * @author TAOJIAN\n * @version 1.0\n * @since 2021-01-25 11:02:22\n */",
"end": 282,
"score": 0.9992183446884155,
"start": 275,
"tag": "NAME",
"value": "TAOJIAN"
}
] | null | [] | package com.donglan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author TAOJIAN
* @version 1.0
* @since 2021-01-25 11:02:22
*/
@SpringBootApplication
@EnableEurekaClient
@MapperScan(basePackages = "com.donglan.dao")
public class Module8005Application {
public static void main(String[] args) {
SpringApplication.run(Module8005Application.class, args);
}
}
| 579 | 0.782383 | 0.740933 | 21 | 26.571428 | 23.146679 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 8 |
91c3c84b0c632968e6ee464f211df8d9890513e2 | 32,890,859,574,523 | d7acd55b04bdd18c06f6c9af000a4408675dc86b | /Lista6/LocadoraVeiculos/Passeio.java | 4cd3ead62cb69d8df9cc71dc1174389513d825b3 | [] | no_license | andr3m0ur4/Java-Exercicios-OO | https://github.com/andr3m0ur4/Java-Exercicios-OO | 987e4a2d0a992a521ee181548e4858731754dd9f | 47f51db47ffb76baf52e5a65f19b2104397c684b | refs/heads/master | 2023-04-29T22:16:39.025000 | 2021-05-23T01:03:05 | 2021-05-23T01:03:05 | 357,344,592 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Passeio extends Veiculo {
private boolean arCondicionado;
private int portas;
public Passeio () {
super();
arCondicionado = true;
portas = 4;
}
public void setArCondicionado ( boolean arCondicionado ) {
this.arCondicionado = arCondicionado;
}
public void setPortas ( int portas ) {
if ( portas >= 1 ) {
this.portas = portas;
}
}
public boolean hasArCondicionado () {
return arCondicionado;
}
public int getPortas () {
return portas;
}
@Override
public String toString() {
return super.toString() + "\n" +
(arCondicionado?"Tem ":"Nao tem ") +
"ar-condicionado";
}
}
| UTF-8 | Java | 651 | java | Passeio.java | Java | [] | null | [] | public class Passeio extends Veiculo {
private boolean arCondicionado;
private int portas;
public Passeio () {
super();
arCondicionado = true;
portas = 4;
}
public void setArCondicionado ( boolean arCondicionado ) {
this.arCondicionado = arCondicionado;
}
public void setPortas ( int portas ) {
if ( portas >= 1 ) {
this.portas = portas;
}
}
public boolean hasArCondicionado () {
return arCondicionado;
}
public int getPortas () {
return portas;
}
@Override
public String toString() {
return super.toString() + "\n" +
(arCondicionado?"Tem ":"Nao tem ") +
"ar-condicionado";
}
}
| 651 | 0.640553 | 0.637481 | 35 | 17.6 | 16.062735 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.542857 | false | false | 8 |
532edbc71b8d4d7db47d2506716c11cf900f4fe0 | 4,166,118,302,959 | ee5a8d71a580ddb64df96ce75769f97317f3d4ff | /src/MultiTasking/ThreadSequence/Shop.java | 4648419b5c2bd17a06347b239611681a9d267af9 | [] | no_license | charbori/Algorithm_workspace | https://github.com/charbori/Algorithm_workspace | 2740ebd9a4a8536a82873be60756e521bd626ef2 | 46efbe9f6a246f532f4385fc74fed7e044a5e656 | refs/heads/master | 2023-01-11T23:46:01.504000 | 2020-11-09T15:29:24 | 2020-11-09T15:29:24 | 297,359,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package MultiTasking.ThreadSequence;
public class Shop {
int price;
String name;
public Shop(int price, String name){
this.price = price;
this.name = name;
}
}
| UTF-8 | Java | 193 | java | Shop.java | Java | [] | null | [] | package MultiTasking.ThreadSequence;
public class Shop {
int price;
String name;
public Shop(int price, String name){
this.price = price;
this.name = name;
}
}
| 193 | 0.621762 | 0.621762 | 10 | 18.299999 | 13.191285 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 8 |
30925036720a82208cc4e353632907c5efdf888d | 23,390,391,942,618 | b2b11b1993aee07df8f43005ce47bcffdf6a23dc | /MICProject/src/com/bontsi/micproject/main/activity/MVP_Main.java | a2503dc78766b60a7ab9affdfaafc4657533baf5 | [] | no_license | ngbontsi/HomeWork | https://github.com/ngbontsi/HomeWork | 1f85770e7bc980f6cfd69dd1e5b21c79d589c454 | 4dc086cff45447843b6d7c2cd1c2eb5d6457bd3c | refs/heads/master | 2021-01-12T12:43:07.674000 | 2017-07-24T10:54:30 | 2017-07-24T10:54:30 | 69,661,192 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bontsi.micproject.main.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.bontsi.micproject.main.activity.view.recycler.NotesViewHolder;
import com.bontsi.micproject.models.Note;
/**
* Holder interface that contains all interfaces responsible to maintain
* communication between Model View Presenter layers. Each layer implements its
* respective interface: View implements RequiredViewOps Presenter implements
* ProvidedPresenterOps, RequiredPresenterOps Model implements ProvidedModelOps
*
* --------------------------------------------------- Created by Tin Megali on
* 18/03/16. Project: tuts+mvp_sample
* --------------------------------------------------- <a
* href="http://www.tinmegali.com">tinmegali.com</a> <a
* href="http://www.github.com/tinmegali>github</a>
* ---------------------------------------------------
*/
public interface MVP_Main {
/**
* Required View methods available to Presenter. A passive layer,
* responsible to show data and receive user interactions Presenter to View
*/
interface RequiredViewOps {
Context getAppContext();
Context getActivityContext();
void showToast(Toast toast);
void showProgress();
void hideProgress();
void showAlert(AlertDialog dialog);
void notifyItemRemoved(int position);
void notifyDataSetChanged();
void notifyItemInserted(int layoutPosition);
void notifyItemRangeChanged(int positionStart, int itemCount);
void clearEditText();
}
/**
* Operations offered to View to communicate with Presenter. Process user
* interaction, sends data requests to Model, etc. View to Presenter
*/
interface ProvidedPresenterOps {
void onDestroy(boolean isChangingConfiguration);
void setView(RequiredViewOps view);
NotesViewHolder createViewHolder(ViewGroup parent, int viewType);
void bindViewHolder(NotesViewHolder holder, int position);
int getNotesCount();
void clickNewNote(EditText editText);
void clickDeleteNote(Note note, int adapterPos, int layoutPos);
}
/**
* Required Presenter methods available to Model. Model to Presenter
*/
interface RequiredPresenterOps {
Context getAppContext();
Context getActivityContext();
}
/**
* Operations offered to Model to communicate with Presenter Handles all
* data business logic. Presenter to Model
*/
interface ProvidedModelOps {
void onDestroy(boolean isChangingConfiguration);
int insertNote(Note note);
boolean loadData();
Note getNote(int position);
boolean deleteNote(Note note, int adapterPos);
int getNotesCount();
}
}
| UTF-8 | Java | 2,684 | java | MVP_Main.java | Java | [
{
"context": "--------------------------------------- Created by Tin Megali on\n * 18/03/16. Project: tuts+mvp_sample\n * -----",
"end": 715,
"score": 0.9998720288276672,
"start": 705,
"tag": "NAME",
"value": "Tin Megali"
},
{
"context": "nmegali.com</a> <a\n * href=\"http://www.github.com/tinmegali>github</a>\n * -----------------------------------",
"end": 911,
"score": 0.9997137188911438,
"start": 902,
"tag": "USERNAME",
"value": "tinmegali"
}
] | null | [] | package com.bontsi.micproject.main.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.bontsi.micproject.main.activity.view.recycler.NotesViewHolder;
import com.bontsi.micproject.models.Note;
/**
* Holder interface that contains all interfaces responsible to maintain
* communication between Model View Presenter layers. Each layer implements its
* respective interface: View implements RequiredViewOps Presenter implements
* ProvidedPresenterOps, RequiredPresenterOps Model implements ProvidedModelOps
*
* --------------------------------------------------- Created by <NAME> on
* 18/03/16. Project: tuts+mvp_sample
* --------------------------------------------------- <a
* href="http://www.tinmegali.com">tinmegali.com</a> <a
* href="http://www.github.com/tinmegali>github</a>
* ---------------------------------------------------
*/
public interface MVP_Main {
/**
* Required View methods available to Presenter. A passive layer,
* responsible to show data and receive user interactions Presenter to View
*/
interface RequiredViewOps {
Context getAppContext();
Context getActivityContext();
void showToast(Toast toast);
void showProgress();
void hideProgress();
void showAlert(AlertDialog dialog);
void notifyItemRemoved(int position);
void notifyDataSetChanged();
void notifyItemInserted(int layoutPosition);
void notifyItemRangeChanged(int positionStart, int itemCount);
void clearEditText();
}
/**
* Operations offered to View to communicate with Presenter. Process user
* interaction, sends data requests to Model, etc. View to Presenter
*/
interface ProvidedPresenterOps {
void onDestroy(boolean isChangingConfiguration);
void setView(RequiredViewOps view);
NotesViewHolder createViewHolder(ViewGroup parent, int viewType);
void bindViewHolder(NotesViewHolder holder, int position);
int getNotesCount();
void clickNewNote(EditText editText);
void clickDeleteNote(Note note, int adapterPos, int layoutPos);
}
/**
* Required Presenter methods available to Model. Model to Presenter
*/
interface RequiredPresenterOps {
Context getAppContext();
Context getActivityContext();
}
/**
* Operations offered to Model to communicate with Presenter Handles all
* data business logic. Presenter to Model
*/
interface ProvidedModelOps {
void onDestroy(boolean isChangingConfiguration);
int insertNote(Note note);
boolean loadData();
Note getNote(int position);
boolean deleteNote(Note note, int adapterPos);
int getNotesCount();
}
}
| 2,680 | 0.720566 | 0.718331 | 100 | 25.84 | 26.070183 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.19 | false | false | 8 |
b1cef9dfe66c40927ce7197302000f4041b0d7a3 | 5,377,299,062,872 | 011236854e0d64bfe7b66e0b453b79798aa57869 | /DesignPatternExample/src/DesignPattern/IteratorPattern/IteratorPatternDemo.java | 115c8a05ff289160fde6418d85713c1159e0ddb5 | [] | no_license | sachingarg123/designPatternsExample | https://github.com/sachingarg123/designPatternsExample | 057ab33d32322863ecc3704b225cb4274f82b15a | 32f5e4895d3fd17f2c944226abb9b3cf76a90a04 | refs/heads/master | 2021-01-09T20:43:35.818000 | 2016-06-24T07:21:46 | 2016-06-24T07:21:46 | 61,863,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //**********************************************************************
// Copyright (c) 2016 Telefonaktiebolaget LM Ericsson, Sweden.
// All rights reserved.
// The Copyright to the computer program(s) herein is the property of
// Telefonaktiebolaget LM Ericsson, Sweden.
// The program(s) may be used and/or copied with the written permission
// from Telefonaktiebolaget LM Ericsson or in accordance with the terms
// and conditions stipulated in the agreement/contract under which the
// program(s) have been supplied.
// **********************************************************************
package DesignPattern.IteratorPattern;
import java.util.Iterator;
public class IteratorPatternDemo
{
public static void main(String arg[])
{
Item i1 = new Item("spaghetti", 7.50f);
Item i2 = new Item("hamburger", 6.00f);
Item i3 = new Item("chicken sandwich", 6.50f);
Menu<Item> menu = new Menu<Item>();
menu.addItems(i1);
menu.addItems(i2);
menu.addItems(i3);
System.out.println("Displaying Menu:");
Iterator<Item> iterator = menu.iterator();
while (iterator.hasNext())
{
Item item = iterator.next();
System.out.println(item);
}
System.out.println("\nRemoving last item returned");
iterator.remove();
System.out.println("\nDisplaying Menu:");
iterator = menu.iterator();
while (iterator.hasNext())
{
Item item = iterator.next();
System.out.println(item);
}
}
}
| UTF-8 | Java | 1,576 | java | IteratorPatternDemo.java | Java | [] | null | [] | //**********************************************************************
// Copyright (c) 2016 Telefonaktiebolaget LM Ericsson, Sweden.
// All rights reserved.
// The Copyright to the computer program(s) herein is the property of
// Telefonaktiebolaget LM Ericsson, Sweden.
// The program(s) may be used and/or copied with the written permission
// from Telefonaktiebolaget LM Ericsson or in accordance with the terms
// and conditions stipulated in the agreement/contract under which the
// program(s) have been supplied.
// **********************************************************************
package DesignPattern.IteratorPattern;
import java.util.Iterator;
public class IteratorPatternDemo
{
public static void main(String arg[])
{
Item i1 = new Item("spaghetti", 7.50f);
Item i2 = new Item("hamburger", 6.00f);
Item i3 = new Item("chicken sandwich", 6.50f);
Menu<Item> menu = new Menu<Item>();
menu.addItems(i1);
menu.addItems(i2);
menu.addItems(i3);
System.out.println("Displaying Menu:");
Iterator<Item> iterator = menu.iterator();
while (iterator.hasNext())
{
Item item = iterator.next();
System.out.println(item);
}
System.out.println("\nRemoving last item returned");
iterator.remove();
System.out.println("\nDisplaying Menu:");
iterator = menu.iterator();
while (iterator.hasNext())
{
Item item = iterator.next();
System.out.println(item);
}
}
}
| 1,576 | 0.573604 | 0.561548 | 46 | 33.260868 | 22.818218 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 8 |
6b5fc029586715ecc363ae137864cadff7eca99e | 17,617,955,881,193 | d8b06d3f54efb389e4d29f70de30e8974efbdb4a | /SDM/Millionaires/app/src/main/java/labs/sdm/millionaires/database/MySQLiteOpenHelper.java | 0edf6b066daf64a17192a3be1f68bc7d20918f51 | [] | no_license | Radahal/UPV | https://github.com/Radahal/UPV | da6fa4b004cf0ffda9c1e829d5138b52d2385318 | d704fd9a55d2670549919b73b115e23ebba3c78a | refs/heads/master | 2021-05-08T11:13:39.737000 | 2018-10-11T21:11:47 | 2018-10-11T21:11:47 | 119,887,698 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package labs.sdm.millionaires.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Rafal on 2018-03-04.
*/
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(Context context) {
super(context,"millionaire_db",null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//
try {
//create DB - table with results
db.execSQL("CREATE TABLE score (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, score TEXT NOT NULL);");
db.execSQL("CREATE TABLE friendship (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username1 TEXT NOT NULL, username2 TEXT NOT NULL);");
db.close();
} catch (SQLiteException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
}
}
| UTF-8 | Java | 1,079 | java | MySQLiteOpenHelper.java | Java | [
{
"context": "tabase.sqlite.SQLiteOpenHelper;\n\n/**\n * Created by Rafal on 2018-03-04.\n */\n\npublic class MySQLiteOpenHelp",
"end": 241,
"score": 0.9985762238502502,
"start": 236,
"tag": "NAME",
"value": "Rafal"
}
] | null | [] | package labs.sdm.millionaires.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Rafal on 2018-03-04.
*/
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(Context context) {
super(context,"millionaire_db",null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//
try {
//create DB - table with results
db.execSQL("CREATE TABLE score (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, score TEXT NOT NULL);");
db.execSQL("CREATE TABLE friendship (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username1 TEXT NOT NULL, username2 TEXT NOT NULL);");
db.close();
} catch (SQLiteException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
}
}
| 1,079 | 0.668211 | 0.658017 | 40 | 25.975 | 34.111206 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.