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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b2b4e94a0e4e43886e4e83e66b3cf9f73f9e5df | 25,537,875,579,225 | fe08cf9d0c20181250f1d4ca3910c9c3ead4c585 | /module/core/src/main/java/zut/cs/core/service/TableMessageManager.java | 723b1bf1311170d32b240dce6c9c8fc3ac417291 | [] | no_license | zut-huangtang/zutnp_paltform | https://github.com/zut-huangtang/zutnp_paltform | 7d1c97bd889192ed2048baf4613702e6f5d8e7b9 | 47277aa20a0aaaaa2d5fe33c4841a0efc721d7fc | refs/heads/master | 2020-08-10T20:55:36.237000 | 2019-10-11T08:12:48 | 2019-10-11T08:12:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zut.cs.core.service;
import zut.cs.core.base.service.GenericTreeManager;
import zut.cs.core.domain.Connection;
import zut.cs.core.domain.Props;
import zut.cs.core.domain.TableMessage;
import java.util.List;
public interface TableMessageManager extends GenericTreeManager<TableMessage, Long> {
TableMessage findByTableName(String TableName);
List<Props> findAllprops(String TableName);
Boolean updata(TableMessage tableMessage);
List<Connection> findAllConnections(String TableName);
}
| UTF-8 | Java | 515 | java | TableMessageManager.java | Java | [] | null | [] | package zut.cs.core.service;
import zut.cs.core.base.service.GenericTreeManager;
import zut.cs.core.domain.Connection;
import zut.cs.core.domain.Props;
import zut.cs.core.domain.TableMessage;
import java.util.List;
public interface TableMessageManager extends GenericTreeManager<TableMessage, Long> {
TableMessage findByTableName(String TableName);
List<Props> findAllprops(String TableName);
Boolean updata(TableMessage tableMessage);
List<Connection> findAllConnections(String TableName);
}
| 515 | 0.8 | 0.8 | 18 | 27.611111 | 25.35994 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 15 |
1e2b04a239904de44a6b110894bd9825e1af1ad5 | 34,325,378,660,945 | 074314134bf21bfe13250a6219f95d1f2836ad10 | /TP1/com/player/Play.java | da7f97aec40889fce8a9b4bc64fd2561b9c84997 | [] | no_license | bernardoabreu/PM | https://github.com/bernardoabreu/PM | 36c2bf41ccc9b318fa67bb8f81c93974f3b3e83c | bdb284ed2143d1a1df9fe935e4662e7d986fe24e | refs/heads/master | 2021-06-17T08:33:08.870000 | 2017-05-10T01:41:28 | 2017-05-10T01:41:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.player;
import com.structure.Board;
import com.structure.Position;
import com.utils.Stats;
/**
* Created by math on 4/6/17.
*/
public class Play {
private int playerId;
private int diceValue;
public Play(int playerId, int diceValue) { //Initialize play
this.playerId = playerId;
this.diceValue = diceValue;
}
public int run(Player[] players, Board board, Stats[] stats){
Player curPlayer = players[this.playerId-1];
int eliminated = 0;
int nroundTrips = 0;
//If this player is not on the game anymore, ignore the play
if (!curPlayer.isPlaying()) return eliminated;
//Otherwise, walk the player
nroundTrips = curPlayer.walk(this.diceValue, board.getBoardSize());
if( nroundTrips != 0) { //Player completed a number of trips around the board.
stats[curPlayer.getId()].incnCompletedRounds(nroundTrips);
curPlayer.deposit(nroundTrips*500); //Gets reward
}
Position curPosition = board.getPosition(curPlayer.getPosition());
//Polymorphic call depends on position type.
if(!curPosition.play(curPlayer, stats)) eliminated++;
return eliminated;
}
}
| UTF-8 | Java | 1,233 | java | Play.java | Java | [
{
"context": "sition;\nimport com.utils.Stats;\n\n/**\n * Created by math on 4/6/17.\n */\npublic class Play {\n private in",
"end": 127,
"score": 0.9918410778045654,
"start": 123,
"tag": "USERNAME",
"value": "math"
}
] | null | [] | package com.player;
import com.structure.Board;
import com.structure.Position;
import com.utils.Stats;
/**
* Created by math on 4/6/17.
*/
public class Play {
private int playerId;
private int diceValue;
public Play(int playerId, int diceValue) { //Initialize play
this.playerId = playerId;
this.diceValue = diceValue;
}
public int run(Player[] players, Board board, Stats[] stats){
Player curPlayer = players[this.playerId-1];
int eliminated = 0;
int nroundTrips = 0;
//If this player is not on the game anymore, ignore the play
if (!curPlayer.isPlaying()) return eliminated;
//Otherwise, walk the player
nroundTrips = curPlayer.walk(this.diceValue, board.getBoardSize());
if( nroundTrips != 0) { //Player completed a number of trips around the board.
stats[curPlayer.getId()].incnCompletedRounds(nroundTrips);
curPlayer.deposit(nroundTrips*500); //Gets reward
}
Position curPosition = board.getPosition(curPlayer.getPosition());
//Polymorphic call depends on position type.
if(!curPosition.play(curPlayer, stats)) eliminated++;
return eliminated;
}
}
| 1,233 | 0.652879 | 0.643958 | 42 | 28.357143 | 26.415022 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595238 | false | false | 15 |
6f9319c9f56e1262d61fbb86b364f17f44f851ca | 38,749,194,955,452 | a383177f4e89b7690615995e6db1a13ae1532128 | /src/exercicios/aula13/Ex5.java | 41e6cc4c194f2a45c1a517f50251b70e7235b74a | [] | no_license | Luan3642/javaBasico | https://github.com/Luan3642/javaBasico | ff9fbc7937284b44fade6ac827ac633fdf531a5d | 73940de3333de0a9a78915133e6377c79bcddfe6 | refs/heads/master | 2023-03-10T15:53:13.314000 | 2022-07-27T21:02:51 | 2022-07-27T21:02:51 | 327,383,358 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exercicios.aula13;
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("entre com o tamanho em metros: ");
int metros = scan.nextInt();
float centrimetros = metros * 100;
System.out.println(+metros +" metros"+ " equivale a " + centrimetros+" centrimetros");
}
}
| UTF-8 | Java | 633 | java | Ex5.java | Java | [] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exercicios.aula13;
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("entre com o tamanho em metros: ");
int metros = scan.nextInt();
float centrimetros = metros * 100;
System.out.println(+metros +" metros"+ " equivale a " + centrimetros+" centrimetros");
}
}
| 633 | 0.633491 | 0.624013 | 22 | 27.772728 | 26.75976 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 15 |
a103a4e35e5ab0fe713241eca3ee2b34a913cbd0 | 37,254,546,359,977 | 9ed1f8be81f227a381df33217b96c6162d553c8f | /src/main/java/com/imooc/security/core/validate/code/SmsCodeAuthenticationSecutiryConfig.java | 71f8e037a3d182c2b3d7b92cd244839c4de39271 | [] | no_license | cys101/imooc-security-core | https://github.com/cys101/imooc-security-core | 2104dd3e1317237274f7cab9291b75c204341636 | af21a46ae8ad3a77b1f311861531a787702b218c | refs/heads/master | 2020-04-07T04:43:02.057000 | 2018-11-20T14:50:45 | 2018-11-20T14:50:45 | 158,068,675 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.imooc.security.core.validate.code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import com.imooc.security.core.authentication.mobile.SmsCodeAuthencationFilter;
import com.imooc.security.core.authentication.mobile.SmsCodeAuthenticationProvider;
@Component
public class SmsCodeAuthenticationSecutiryConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>{
@Autowired
private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler imoocAuthenticationFailureHandler;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(HttpSecurity http) throws Exception {
SmsCodeAuthencationFilter smsCodeAuthencationFilter = new SmsCodeAuthencationFilter();
smsCodeAuthencationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
smsCodeAuthencationFilter.setAuthenticationSuccessHandler(imoocAuthenticationSuccessHandler);
smsCodeAuthencationFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
http.authenticationProvider(smsCodeAuthenticationProvider)
.addFilterAfter(smsCodeAuthencationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
| UTF-8 | Java | 2,187 | java | SmsCodeAuthenticationSecutiryConfig.java | Java | [] | null | [] | package com.imooc.security.core.validate.code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import com.imooc.security.core.authentication.mobile.SmsCodeAuthencationFilter;
import com.imooc.security.core.authentication.mobile.SmsCodeAuthenticationProvider;
@Component
public class SmsCodeAuthenticationSecutiryConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>{
@Autowired
private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler imoocAuthenticationFailureHandler;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(HttpSecurity http) throws Exception {
SmsCodeAuthencationFilter smsCodeAuthencationFilter = new SmsCodeAuthencationFilter();
smsCodeAuthencationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
smsCodeAuthencationFilter.setAuthenticationSuccessHandler(imoocAuthenticationSuccessHandler);
smsCodeAuthencationFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
http.authenticationProvider(smsCodeAuthenticationProvider)
.addFilterAfter(smsCodeAuthencationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
| 2,187 | 0.864655 | 0.864655 | 43 | 48.860466 | 39.181499 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.372093 | false | false | 15 |
8189df03f717d5298f8d076e82c526191916d025 | 38,173,669,352,115 | 34635bf12ff17993b483f5950367e134d79ff697 | /PrintLargestAndSmallest.java | 564f8e46c8b4f513d9204aabdc53713aaa408b31 | [] | no_license | BahnimanBorah/Simple-Text-Manipulation | https://github.com/BahnimanBorah/Simple-Text-Manipulation | ad4216222ee1de2f1f4d40f2f716147181ff1f97 | 418dfb6bf6f4d1534b9f200c2fca3de0dce0bd92 | refs/heads/master | 2020-05-04T20:19:58.030000 | 2019-04-04T06:17:31 | 2019-04-04T06:17:31 | 179,433,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Java10Marks;
import java.util.Scanner;
/*
* Input a number and get it's largest and smallest DIGIT
*/
public class PrintLargestAndSmallest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int num = in.nextInt();
in.close();
int min=9;
int max=0;
int n=0;
while(num>10) {
n=num%10;
if(n<min) {
min=n;
}
if(n>max) {
max=n;
}
num=num/10;
}
if(num<min)
min=num;
if(num>max)
max=num;
System.out.println("Min: "+min+"\nMax: "+max);
}
}
| UTF-8 | Java | 588 | java | PrintLargestAndSmallest.java | Java | [] | null | [] | package Java10Marks;
import java.util.Scanner;
/*
* Input a number and get it's largest and smallest DIGIT
*/
public class PrintLargestAndSmallest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int num = in.nextInt();
in.close();
int min=9;
int max=0;
int n=0;
while(num>10) {
n=num%10;
if(n<min) {
min=n;
}
if(n>max) {
max=n;
}
num=num/10;
}
if(num<min)
min=num;
if(num>max)
max=num;
System.out.println("Min: "+min+"\nMax: "+max);
}
}
| 588 | 0.583333 | 0.564626 | 41 | 13.341463 | 14.38429 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.04878 | false | false | 15 |
0da07661475b63eac15de4f3c7afd10e63a6f208 | 39,230,231,290,004 | a7ff00e126154fdbc24a905d18b6acda0aae927d | /FinalProject/src/business/organization/distributor/ReservationManagementOrganization.java | e90d00cee947942ba0753c1566fd901070441a9f | [] | no_license | ppoptani/Medical-Device-Management | https://github.com/ppoptani/Medical-Device-Management | 1218d76e3dd609f9928880ef139972a1fe8c9051 | 600f16db666bc4d0c6a0f01a888b053868a3c970 | refs/heads/master | 2021-01-10T05:18:48.079000 | 2016-01-22T20:29:24 | 2016-01-22T20:29:24 | 50,193,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package business.organization.distributor;
import business.organization.Organization;
import business.role.InventoryStaffRole;
import business.role.ReservationStaffRole;
import business.role.Role;
import java.util.ArrayList;
/**
*
* @author pu
*/
public class ReservationManagementOrganization extends Organization{
public ReservationManagementOrganization(String organizationName, String organizationType) {
super(organizationName, organizationType);
}
@Override
public ArrayList<Role> getSupportedRole() {
ArrayList<Role> role = new ArrayList<Role>();
role.add(new ReservationStaffRole());
return role;//To change body of generated methods, choose Tools | Templates.
}
}
| UTF-8 | Java | 923 | java | ReservationManagementOrganization.java | Java | [
{
"context": "le;\nimport java.util.ArrayList;\n\n/**\n *\n * @author pu\n */\npublic class ReservationManagementOrganization",
"end": 432,
"score": 0.9724030494689941,
"start": 430,
"tag": "USERNAME",
"value": "pu"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package business.organization.distributor;
import business.organization.Organization;
import business.role.InventoryStaffRole;
import business.role.ReservationStaffRole;
import business.role.Role;
import java.util.ArrayList;
/**
*
* @author pu
*/
public class ReservationManagementOrganization extends Organization{
public ReservationManagementOrganization(String organizationName, String organizationType) {
super(organizationName, organizationType);
}
@Override
public ArrayList<Role> getSupportedRole() {
ArrayList<Role> role = new ArrayList<Role>();
role.add(new ReservationStaffRole());
return role;//To change body of generated methods, choose Tools | Templates.
}
}
| 923 | 0.746479 | 0.746479 | 31 | 28.774193 | 28.185686 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 15 |
26e3aa5d1690f74e515690591d00339ae957e721 | 5,446,018,599,457 | 33fe6e2a113d18a063f68a0be83d74a98a15ff99 | /src/com/jetbrains/ther/psi/references/TheRReferenceImpl.java | e9fdd7f8fd3b0cebfbc63257db8a493e0b867629 | [
"MIT"
] | permissive | Avila-Diego/TheRPlugin | https://github.com/Avila-Diego/TheRPlugin | 848240d35689006ab8496f274157683b3415ea44 | be2593c26dee8f6287d5ec0a82aebbca9c74f657 | refs/heads/master | 2023-03-19T19:59:18.881000 | 2016-07-05T13:08:10 | 2016-07-05T13:08:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jetbrains.ther.psi.references;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.module.impl.scopes.LibraryScope;
import com.intellij.openapi.roots.ModifiableModelsProvider;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.ther.TheRElementGenerator;
import com.jetbrains.ther.TheRPsiUtils;
import com.jetbrains.ther.interpreter.TheRInterpreterConfigurable;
import com.jetbrains.ther.interpreter.TheRInterpreterService;
import com.jetbrains.ther.interpreter.TheRSkeletonGenerator;
import com.jetbrains.ther.parsing.TheRElementTypes;
import com.jetbrains.ther.psi.api.*;
import com.jetbrains.ther.psi.stubs.TheRAssignmentNameIndex;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class TheRReferenceImpl implements PsiPolyVariantReference {
protected final TheRReferenceExpression myElement;
public TheRReferenceImpl(TheRReferenceExpression element) {
myElement = element;
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
final List<ResolveResult> result = new ArrayList<ResolveResult>();
if (TheRPsiUtils.isNamedArgument(myElement)) {
TheRResolver.resolveNameArgument(myElement, myElement.getName(), result);
return result.toArray(new ResolveResult[result.size()]);
}
final String namespace = myElement.getNamespace();
final String name = myElement.getName();
if (name == null) return ResolveResult.EMPTY_ARRAY;
if (namespace != null) {
TheRResolver.resolveWithNamespace(myElement.getProject(), name, namespace, result);
}
TheRResolver.resolveFunction(myElement, name, result);
if (!result.isEmpty()) {
return result.toArray(new ResolveResult[result.size()]);
}
TheRResolver.resolveWithoutNamespaceInFile(myElement, name, result);
if (!result.isEmpty()) {
return result.toArray(new ResolveResult[result.size()]);
}
TheRResolver.addFromSkeletonsAndRLibrary(myElement, result, name);
return result.toArray(new ResolveResult[result.size()]);
}
@Override
public PsiElement getElement() {
return myElement;
}
@Override
public TextRange getRangeInElement() {
final TextRange range = myElement.getNode().getTextRange();
return range.shiftRight(-myElement.getNode().getStartOffset());
}
@Nullable
@Override
public PsiElement resolve() {
final ResolveResult[] results = multiResolve(false);
return results.length >= 1 ? results[0].getElement() : null;
}
@NotNull
@Override
public String getCanonicalText() {
return getElement().getText();
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
final ASTNode oldNameIdentifier = getElement().getNode().findChildByType(TheRElementTypes.THE_R_IDENTIFIER);
if (oldNameIdentifier != null) {
final PsiFile dummyFile = TheRElementGenerator.createDummyFile(newElementName, false, getElement().getProject());
ASTNode identifier = dummyFile.getNode().getFirstChildNode().findChildByType(TheRElementTypes.THE_R_IDENTIFIER);
if (identifier != null) {
getElement().getNode().replaceChild(oldNameIdentifier, identifier);
}
}
return getElement();
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public boolean isReferenceTo(PsiElement element) {
//TODO: check some conditions
return resolve() == element;
}
@NotNull
@Override
public Object[] getVariants() {
List<LookupElement> result = new ArrayList<LookupElement>();
final String name = myElement.getName();
if (myElement.getParent() instanceof TheRReferenceExpression) return ResolveResult.EMPTY_ARRAY;
if (name == null) return ResolveResult.EMPTY_ARRAY;
TheRBlockExpression rBlock = PsiTreeUtil.getParentOfType(myElement, TheRBlockExpression.class);
while (rBlock != null) {
final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(rBlock, TheRAssignmentStatement.class);
if (statements != null) {
for (TheRAssignmentStatement statement : statements) {
final PsiElement assignee = statement.getAssignee();
if (assignee != null) {
result.add(LookupElementBuilder.create(assignee.getText()));
}
}
}
rBlock = PsiTreeUtil.getParentOfType(rBlock, TheRBlockExpression.class);
}
final TheRFunctionExpression rFunction = PsiTreeUtil.getParentOfType(myElement, TheRFunctionExpression.class);
if (rFunction != null) {
final TheRParameterList list = rFunction.getParameterList();
for (TheRParameter parameter : list.getParameterList()) {
result.add(LookupElementBuilder.create(parameter));
}
}
final PsiFile file = myElement.getContainingFile();
final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(file, TheRAssignmentStatement.class);
if (statements != null) {
for (TheRAssignmentStatement statement : statements) {
final PsiElement assignee = statement.getAssignee();
if (assignee != null) {
result.add(LookupElementBuilder.create(assignee.getText()));
}
}
}
addVariantsFromSkeletons(result);
return result.toArray();
}
private void addVariantsFromSkeletons(@NotNull final List<LookupElement> result) {
final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance();
final LibraryTable.ModifiableModel model = modelsProvider.getLibraryTableModifiableModel(myElement.getProject());
if (model != null) {
final Library library = model.getLibraryByName(TheRInterpreterConfigurable.THE_R_SKELETONS);
final String skeletonsDir = TheRSkeletonGenerator.getSkeletonsPath(TheRInterpreterService.getInstance().getInterpreterPath());
if (library != null) {
final Collection<String> assignmentStatements = TheRAssignmentNameIndex.allKeys(myElement.getProject());
for (String statement : assignmentStatements) {
final Collection<TheRAssignmentStatement> statements =
TheRAssignmentNameIndex.find(statement, myElement.getProject(), new LibraryScope(myElement.getProject(), library));
for (TheRAssignmentStatement assignmentStatement : statements) {
final PsiDirectory directory = assignmentStatement.getContainingFile().getParent();
assert directory != null;
if (directory.getName().equals("base") || FileUtil.pathsEqual(directory.getVirtualFile().getCanonicalPath(), skeletonsDir)) {
result.add(LookupElementBuilder.create(assignmentStatement));
}
else {
result.add(LookupElementBuilder.create(assignmentStatement, directory.getName() + "::" + assignmentStatement.getName()));
}
}
}
}
}
}
@Override
public boolean isSoft() {
return false;
}
}
| UTF-8 | Java | 7,516 | java | TheRReferenceImpl.java | Java | [] | null | [] | package com.jetbrains.ther.psi.references;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.module.impl.scopes.LibraryScope;
import com.intellij.openapi.roots.ModifiableModelsProvider;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.ther.TheRElementGenerator;
import com.jetbrains.ther.TheRPsiUtils;
import com.jetbrains.ther.interpreter.TheRInterpreterConfigurable;
import com.jetbrains.ther.interpreter.TheRInterpreterService;
import com.jetbrains.ther.interpreter.TheRSkeletonGenerator;
import com.jetbrains.ther.parsing.TheRElementTypes;
import com.jetbrains.ther.psi.api.*;
import com.jetbrains.ther.psi.stubs.TheRAssignmentNameIndex;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class TheRReferenceImpl implements PsiPolyVariantReference {
protected final TheRReferenceExpression myElement;
public TheRReferenceImpl(TheRReferenceExpression element) {
myElement = element;
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
final List<ResolveResult> result = new ArrayList<ResolveResult>();
if (TheRPsiUtils.isNamedArgument(myElement)) {
TheRResolver.resolveNameArgument(myElement, myElement.getName(), result);
return result.toArray(new ResolveResult[result.size()]);
}
final String namespace = myElement.getNamespace();
final String name = myElement.getName();
if (name == null) return ResolveResult.EMPTY_ARRAY;
if (namespace != null) {
TheRResolver.resolveWithNamespace(myElement.getProject(), name, namespace, result);
}
TheRResolver.resolveFunction(myElement, name, result);
if (!result.isEmpty()) {
return result.toArray(new ResolveResult[result.size()]);
}
TheRResolver.resolveWithoutNamespaceInFile(myElement, name, result);
if (!result.isEmpty()) {
return result.toArray(new ResolveResult[result.size()]);
}
TheRResolver.addFromSkeletonsAndRLibrary(myElement, result, name);
return result.toArray(new ResolveResult[result.size()]);
}
@Override
public PsiElement getElement() {
return myElement;
}
@Override
public TextRange getRangeInElement() {
final TextRange range = myElement.getNode().getTextRange();
return range.shiftRight(-myElement.getNode().getStartOffset());
}
@Nullable
@Override
public PsiElement resolve() {
final ResolveResult[] results = multiResolve(false);
return results.length >= 1 ? results[0].getElement() : null;
}
@NotNull
@Override
public String getCanonicalText() {
return getElement().getText();
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
final ASTNode oldNameIdentifier = getElement().getNode().findChildByType(TheRElementTypes.THE_R_IDENTIFIER);
if (oldNameIdentifier != null) {
final PsiFile dummyFile = TheRElementGenerator.createDummyFile(newElementName, false, getElement().getProject());
ASTNode identifier = dummyFile.getNode().getFirstChildNode().findChildByType(TheRElementTypes.THE_R_IDENTIFIER);
if (identifier != null) {
getElement().getNode().replaceChild(oldNameIdentifier, identifier);
}
}
return getElement();
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public boolean isReferenceTo(PsiElement element) {
//TODO: check some conditions
return resolve() == element;
}
@NotNull
@Override
public Object[] getVariants() {
List<LookupElement> result = new ArrayList<LookupElement>();
final String name = myElement.getName();
if (myElement.getParent() instanceof TheRReferenceExpression) return ResolveResult.EMPTY_ARRAY;
if (name == null) return ResolveResult.EMPTY_ARRAY;
TheRBlockExpression rBlock = PsiTreeUtil.getParentOfType(myElement, TheRBlockExpression.class);
while (rBlock != null) {
final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(rBlock, TheRAssignmentStatement.class);
if (statements != null) {
for (TheRAssignmentStatement statement : statements) {
final PsiElement assignee = statement.getAssignee();
if (assignee != null) {
result.add(LookupElementBuilder.create(assignee.getText()));
}
}
}
rBlock = PsiTreeUtil.getParentOfType(rBlock, TheRBlockExpression.class);
}
final TheRFunctionExpression rFunction = PsiTreeUtil.getParentOfType(myElement, TheRFunctionExpression.class);
if (rFunction != null) {
final TheRParameterList list = rFunction.getParameterList();
for (TheRParameter parameter : list.getParameterList()) {
result.add(LookupElementBuilder.create(parameter));
}
}
final PsiFile file = myElement.getContainingFile();
final TheRAssignmentStatement[] statements = PsiTreeUtil.getChildrenOfType(file, TheRAssignmentStatement.class);
if (statements != null) {
for (TheRAssignmentStatement statement : statements) {
final PsiElement assignee = statement.getAssignee();
if (assignee != null) {
result.add(LookupElementBuilder.create(assignee.getText()));
}
}
}
addVariantsFromSkeletons(result);
return result.toArray();
}
private void addVariantsFromSkeletons(@NotNull final List<LookupElement> result) {
final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance();
final LibraryTable.ModifiableModel model = modelsProvider.getLibraryTableModifiableModel(myElement.getProject());
if (model != null) {
final Library library = model.getLibraryByName(TheRInterpreterConfigurable.THE_R_SKELETONS);
final String skeletonsDir = TheRSkeletonGenerator.getSkeletonsPath(TheRInterpreterService.getInstance().getInterpreterPath());
if (library != null) {
final Collection<String> assignmentStatements = TheRAssignmentNameIndex.allKeys(myElement.getProject());
for (String statement : assignmentStatements) {
final Collection<TheRAssignmentStatement> statements =
TheRAssignmentNameIndex.find(statement, myElement.getProject(), new LibraryScope(myElement.getProject(), library));
for (TheRAssignmentStatement assignmentStatement : statements) {
final PsiDirectory directory = assignmentStatement.getContainingFile().getParent();
assert directory != null;
if (directory.getName().equals("base") || FileUtil.pathsEqual(directory.getVirtualFile().getCanonicalPath(), skeletonsDir)) {
result.add(LookupElementBuilder.create(assignmentStatement));
}
else {
result.add(LookupElementBuilder.create(assignmentStatement, directory.getName() + "::" + assignmentStatement.getName()));
}
}
}
}
}
}
@Override
public boolean isSoft() {
return false;
}
}
| 7,516 | 0.736163 | 0.735897 | 188 | 38.978722 | 34.793457 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.579787 | false | false | 15 |
de191a4b0d61b60d1548edba2fbcac5fc35cd6c3 | 39,290,360,849,705 | 6bf9565ddcc68a46a1f6349cb73bdb8b9a2f3089 | /modules/rsl-util/src/main/java/rsl/util/pubsub/PubSubEventLogger.java | 7f2248f42226b80cd01c436285cede7f6a6c452a | [] | no_license | asanctor/rsl-master | https://github.com/asanctor/rsl-master | cefa70c1d77d0ed8b0cfff9ba61378278f1ebb7a | 5151457123d9d55a70d9cebdfce9d638204d674d | refs/heads/main | 2023-05-03T22:35:48.893000 | 2021-05-21T15:51:49 | 2021-05-21T15:51:49 | 369,582,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rsl.util.pubsub;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PubSubEventLogger {
private boolean outputEnabled = true;
@Subscribe
@AllowConcurrentEvents
public void handleEvent(PubSubEvent event)
{
if(outputEnabled){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = sdf.format(new Date(event.getTimestamp()));
String logMessage = getLogMessage(event);
String logOutput = String.format("[%s] %s", time, logMessage);
System.out.println(logOutput);
}
}
public void enableOutput()
{
outputEnabled = true;
}
public void disableOutput()
{
outputEnabled = false;
}
private String getLogMessage(PubSubEvent event)
{
Method handler = getEventHandleMethod(event);
try {
return handler.invoke(this, event).toString();
} catch (Exception e) {
System.out.println("Error while invoking the logging method for event of type " + event.getClass().getSimpleName());
System.out.println("Make sure that the class is defined as public and that your method can take this type as argument!");
e.printStackTrace();
return "";
}
}
// use reflection to find a method to handle this specific type of event
// if it's not found, use the generic method for PubSubEvent events
private Method getEventHandleMethod(PubSubEvent event)
{
String methodName = event.getClass().getSimpleName();
try {
return this.getClass().getDeclaredMethod("handle" + methodName, event.getClass());
} catch (NoSuchMethodException e) {
try {
return this.getClass().getDeclaredMethod("handlePubSubEvent", PubSubEvent.class);
} catch (NoSuchMethodException e1) {
System.out.println("handlePubSubEvent method not found in PubSubEventLogger");
e1.printStackTrace();
return null;
}
}
}
private String handlePubSubEvent(PubSubEvent event)
{
return event.getMessage();
}
private String handleErrorEvent(ErrorEvent event)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
event.getException().printStackTrace(pw);
String stackTrace = sw.toString();
String exceptionType = event.getException().getClass().getSimpleName();
return String.format("ERROR (%s) %s \n %s \n %s", exceptionType, event.getMessage(), event.getException().getMessage(), stackTrace);
}
}
| UTF-8 | Java | 2,877 | java | PubSubEventLogger.java | Java | [] | null | [] | package rsl.util.pubsub;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PubSubEventLogger {
private boolean outputEnabled = true;
@Subscribe
@AllowConcurrentEvents
public void handleEvent(PubSubEvent event)
{
if(outputEnabled){
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = sdf.format(new Date(event.getTimestamp()));
String logMessage = getLogMessage(event);
String logOutput = String.format("[%s] %s", time, logMessage);
System.out.println(logOutput);
}
}
public void enableOutput()
{
outputEnabled = true;
}
public void disableOutput()
{
outputEnabled = false;
}
private String getLogMessage(PubSubEvent event)
{
Method handler = getEventHandleMethod(event);
try {
return handler.invoke(this, event).toString();
} catch (Exception e) {
System.out.println("Error while invoking the logging method for event of type " + event.getClass().getSimpleName());
System.out.println("Make sure that the class is defined as public and that your method can take this type as argument!");
e.printStackTrace();
return "";
}
}
// use reflection to find a method to handle this specific type of event
// if it's not found, use the generic method for PubSubEvent events
private Method getEventHandleMethod(PubSubEvent event)
{
String methodName = event.getClass().getSimpleName();
try {
return this.getClass().getDeclaredMethod("handle" + methodName, event.getClass());
} catch (NoSuchMethodException e) {
try {
return this.getClass().getDeclaredMethod("handlePubSubEvent", PubSubEvent.class);
} catch (NoSuchMethodException e1) {
System.out.println("handlePubSubEvent method not found in PubSubEventLogger");
e1.printStackTrace();
return null;
}
}
}
private String handlePubSubEvent(PubSubEvent event)
{
return event.getMessage();
}
private String handleErrorEvent(ErrorEvent event)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
event.getException().printStackTrace(pw);
String stackTrace = sw.toString();
String exceptionType = event.getException().getClass().getSimpleName();
return String.format("ERROR (%s) %s \n %s \n %s", exceptionType, event.getMessage(), event.getException().getMessage(), stackTrace);
}
}
| 2,877 | 0.641988 | 0.641293 | 88 | 31.693182 | 31.958551 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511364 | false | false | 15 |
3686dd18c209f4e4ab342785050c9d8606971a99 | 37,203,006,753,872 | c30cac1b04639d53347aab7052945e7335a90248 | /Ticket-app-Final/Ticket-app/app/src/main/java/com/example/zhangmingqi/ticket_app/Controller/ViewPager/fragment.java | 3771aeca9863d917d68d331970784b47227ea745 | [] | no_license | WangJunwen1995/Enjoy_film | https://github.com/WangJunwen1995/Enjoy_film | fd563b37da9267c3796ecec3d2b169b38b29fd8b | 05f70f6c5fc06be68ac2a36897d1fdaecda09a86 | refs/heads/master | 2021-01-20T17:39:46.644000 | 2017-06-24T06:19:43 | 2017-06-24T06:19:43 | 90,881,319 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.zhangmingqi.ticket_app.Controller.ViewPager;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.zhangmingqi.ticket_app.Controller.MovieDetail;
import com.example.zhangmingqi.ticket_app.Model.MainViewModel;
import com.example.zhangmingqi.ticket_app.R;
import com.example.zhangmingqi.ticket_app.View.MainFragmentView;
//主页fragment
@SuppressLint("ValidFragment")
public class fragment extends Fragment {
private MainFragmentView fragmentView;
public MainViewModel mainViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment, container, false);
fragmentView = new MainFragmentView(view,getActivity());
mainViewModel = new MainViewModel(getActivity(),fragmentView.imgView);
mainViewModel.setImage();
fragmentView.imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mainViewModel.imageName.equals("尚未请求到电影信息!"))
Toast.makeText(getActivity(),"尚未请求到电影信息,请稍后再试!",Toast.LENGTH_SHORT).show();
else {
String name = mainViewModel.imageName;
Bundle bundle = new Bundle();
bundle.putString("movieName",name);
Intent intent = new Intent(getContext(), MovieDetail.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
return view;
}
}
| UTF-8 | Java | 1,926 | java | fragment.java | Java | [] | null | [] | package com.example.zhangmingqi.ticket_app.Controller.ViewPager;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.zhangmingqi.ticket_app.Controller.MovieDetail;
import com.example.zhangmingqi.ticket_app.Model.MainViewModel;
import com.example.zhangmingqi.ticket_app.R;
import com.example.zhangmingqi.ticket_app.View.MainFragmentView;
//主页fragment
@SuppressLint("ValidFragment")
public class fragment extends Fragment {
private MainFragmentView fragmentView;
public MainViewModel mainViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment, container, false);
fragmentView = new MainFragmentView(view,getActivity());
mainViewModel = new MainViewModel(getActivity(),fragmentView.imgView);
mainViewModel.setImage();
fragmentView.imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mainViewModel.imageName.equals("尚未请求到电影信息!"))
Toast.makeText(getActivity(),"尚未请求到电影信息,请稍后再试!",Toast.LENGTH_SHORT).show();
else {
String name = mainViewModel.imageName;
Bundle bundle = new Bundle();
bundle.putString("movieName",name);
Intent intent = new Intent(getContext(), MovieDetail.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
return view;
}
}
| 1,926 | 0.669338 | 0.668803 | 52 | 35 | 26.149717 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 15 |
88d0f550b51931cb9e335cb50b2ca0e177169799 | 33,852,932,289,626 | 2a58bac44d9a1fbfb4c4528fadc0df7322d2bd7f | /sooltoryteller/src/main/java/com/sooltoryteller/controller/MyBbstController.java | 42a0115a973def2437d7e47e23f0d3f707a7e969 | [] | no_license | Limhyeonsu/sooltoryteller | https://github.com/Limhyeonsu/sooltoryteller | ab71adadb5d790aecdf04b0205be1f4504004dce | f62249834d02792b7f26f07492862f7c4b9e20ec | refs/heads/main | 2023-02-13T14:46:10.340000 | 2021-01-15T15:41:22 | 2021-01-15T15:41:22 | 329,936,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sooltoryteller.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sooltoryteller.domain.BbstCriteria;
import com.sooltoryteller.domain.MyBbstPageDTO;
import com.sooltoryteller.service.BbstService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
@RestController
@Log4j
@AllArgsConstructor
@RequestMapping("/mybbst/")
public class MyBbstController {
private BbstService service;
// 마이페이지
// 내가 쓴 게시글 리스트
@GetMapping(value="/pages/{memberId}/{page}",
produces= {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_UTF8_VALUE
})
public ResponseEntity<MyBbstPageDTO> getMyBbstList(
@PathVariable("page") int page,
@PathVariable("memberId") Long memberId) {
BbstCriteria cri = new BbstCriteria(page, 9);
log.info("========== MEMBERID " + memberId + "'S BBST LIST==========");
log.info("========== " + cri + " ==========");
return new ResponseEntity<>(service.getMyBbstList(cri, memberId), HttpStatus.OK);
}
}
| UTF-8 | Java | 1,363 | java | MyBbstController.java | Java | [] | null | [] | package com.sooltoryteller.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sooltoryteller.domain.BbstCriteria;
import com.sooltoryteller.domain.MyBbstPageDTO;
import com.sooltoryteller.service.BbstService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
@RestController
@Log4j
@AllArgsConstructor
@RequestMapping("/mybbst/")
public class MyBbstController {
private BbstService service;
// 마이페이지
// 내가 쓴 게시글 리스트
@GetMapping(value="/pages/{memberId}/{page}",
produces= {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_UTF8_VALUE
})
public ResponseEntity<MyBbstPageDTO> getMyBbstList(
@PathVariable("page") int page,
@PathVariable("memberId") Long memberId) {
BbstCriteria cri = new BbstCriteria(page, 9);
log.info("========== MEMBERID " + memberId + "'S BBST LIST==========");
log.info("========== " + cri + " ==========");
return new ResponseEntity<>(service.getMyBbstList(cri, memberId), HttpStatus.OK);
}
}
| 1,363 | 0.7603 | 0.756554 | 43 | 30.046511 | 23.101347 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.255814 | false | false | 15 |
92541cb9ae8fb287f372d58fd682a4cd61f761e6 | 34,067,680,637,223 | 786a244e9c921ed8b7bbdb5b006530c157de6867 | /src/com/github/FailVictim/MythicalEarth/Engine/MythicalEarth.java | 2a12e8a0f158ca1199baddda1fe7975e61b59d41 | [] | no_license | FailVictim/MythicalEarth | https://github.com/FailVictim/MythicalEarth | 7fa3905c8489903825227824480974b4267c3208 | 388a11ddd4beff7557a578b5c213aaf19fb85b95 | refs/heads/master | 2020-06-01T09:39:40.566000 | 2014-09-12T21:56:40 | 2014-09-12T21:56:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.FailVictim.MythicalEarth.Engine;
import com.github.FailVictim.MythicalEarth.UI.MenuFrame;
public class MythicalEarth {
public static void main(String args[]) {
MenuFrame menuFrame = new MenuFrame();
@SuppressWarnings("unused")
Data data = new Data(menuFrame);
}
}
| UTF-8 | Java | 317 | java | MythicalEarth.java | Java | [] | null | [] | package com.github.FailVictim.MythicalEarth.Engine;
import com.github.FailVictim.MythicalEarth.UI.MenuFrame;
public class MythicalEarth {
public static void main(String args[]) {
MenuFrame menuFrame = new MenuFrame();
@SuppressWarnings("unused")
Data data = new Data(menuFrame);
}
}
| 317 | 0.706625 | 0.706625 | 15 | 19.133333 | 20.529221 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.133333 | false | false | 15 |
28c864bc3f5c2f6f86d672cb3ba93a964cc0b8d5 | 39,195,871,565,577 | 033a01e35103570f4bbca302768a26ee8f6dbece | /Save the World Again/Solution.java | fd4a6d986db351749ad7a1b074b83215489d0dc0 | [] | no_license | axemaneric/Google-Code-Jam | https://github.com/axemaneric/Google-Code-Jam | c0078b6e40c6a778601bc0162d7ddf37cfe1a4c3 | 0e70e0094770dc96eceda149f6cec92a4e2ebda8 | refs/heads/master | 2020-03-10T03:18:12.731000 | 2018-04-11T22:26:46 | 2018-04-11T22:26:46 | 129,160,337 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int i = 1; i <= t; ++i) {
int d = in.nextInt();
String p = in.next();
int numswap = 0;
while (!outOfSwaps(p) && dead(p, d)) {
for (int j = p.length() - 1; j > 0; j--) {
if (p.charAt(j) == 'S' && p.charAt(j - 1) == 'C') {
char[] c = p.toCharArray();
char temp = c[j];
c[j] = c[j - 1];
c[j - 1] = temp;
p = new String(c);
numswap++;
}
}
}
if (dead(p, d)) {
System.out.println("Case #" + i + ": IMPOSSIBLE");
} else {
System.out.println("Case #" + i + ": " + numswap);
}
}
}
public static boolean outOfSwaps(String p) {
boolean shouldbeend = false;
if (!p.contains("C")) {
return true;
}
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == 'C') {
shouldbeend = true;
} else if (p.charAt(i) == 'S' && shouldbeend) {
return false;
}
}
return true;
}
public static boolean dead(String p, int d) {
int health = d;
int damage = 1;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == 'C') {
damage = damage * 2;
} else {
health = health - damage;
}
}
return health < 0;
}
} | UTF-8 | Java | 1,479 | java | Solution.java | Java | [] | null | [] | import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int i = 1; i <= t; ++i) {
int d = in.nextInt();
String p = in.next();
int numswap = 0;
while (!outOfSwaps(p) && dead(p, d)) {
for (int j = p.length() - 1; j > 0; j--) {
if (p.charAt(j) == 'S' && p.charAt(j - 1) == 'C') {
char[] c = p.toCharArray();
char temp = c[j];
c[j] = c[j - 1];
c[j - 1] = temp;
p = new String(c);
numswap++;
}
}
}
if (dead(p, d)) {
System.out.println("Case #" + i + ": IMPOSSIBLE");
} else {
System.out.println("Case #" + i + ": " + numswap);
}
}
}
public static boolean outOfSwaps(String p) {
boolean shouldbeend = false;
if (!p.contains("C")) {
return true;
}
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == 'C') {
shouldbeend = true;
} else if (p.charAt(i) == 'S' && shouldbeend) {
return false;
}
}
return true;
}
public static boolean dead(String p, int d) {
int health = d;
int damage = 1;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == 'C') {
damage = damage * 2;
} else {
health = health - damage;
}
}
return health < 0;
}
} | 1,479 | 0.499662 | 0.491548 | 62 | 22.854839 | 19.650862 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.967742 | false | false | 15 |
4b5b8698fcee6127155f2435ec1f01f639093b56 | 29,875,792,567,620 | 4331fa86ca7f56c38430277b2e66d727eb27d512 | /Myjavaprograms/src/com/hasarelationship/Bike.java | 3835a38c195cc7e79dc2b29d2fe518adb671b09e | [] | no_license | Karthikmk1996/Myjavaprograms | https://github.com/Karthikmk1996/Myjavaprograms | dbcea5941a2c8243c9c1a9f2d8a4b3e5c90e1240 | 5742f861222de74dffb6d40ce8c44ada3ec19159 | refs/heads/master | 2020-08-31T03:34:16.660000 | 2019-11-24T19:12:15 | 2019-11-24T19:12:15 | 218,575,423 | 0 | 1 | null | false | 2019-10-30T16:46:21 | 2019-10-30T16:41:19 | 2019-10-30T16:41:22 | 2019-10-30T16:46:15 | 0 | 0 | 1 | 0 | null | false | false | package com.hasarelationship;
class Bike {
Engine e=new Engine(100);
double mileage;
String colour;
Bike()
{
}
Bike(double mileage,String colour)
{
this.mileage=mileage;
this.colour=colour;
}
}
| UTF-8 | Java | 227 | java | Bike.java | Java | [] | null | [] | package com.hasarelationship;
class Bike {
Engine e=new Engine(100);
double mileage;
String colour;
Bike()
{
}
Bike(double mileage,String colour)
{
this.mileage=mileage;
this.colour=colour;
}
}
| 227 | 0.643172 | 0.629956 | 16 | 12.1875 | 11.265094 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 15 |
3754bbe13cb8e75450f2bb365206c782ecc7bea5 | 39,384,850,134,908 | c0d517357d9b4069a0d001f11ffdad6b0dfa031d | /src/com/dream/system/SystemDemo.java | 55d50ad8eb544b0de11be1794547830c5f2a5e95 | [] | no_license | Dream1228/threadstudy | https://github.com/Dream1228/threadstudy | a0b9c0f3244e868ac0052faa17905c36db22cbb2 | e3fd5127c4a61ddfd496aa2e9ea7f4ec243faf9d | refs/heads/master | 2021-05-19T04:10:28.241000 | 2020-03-31T06:45:35 | 2020-03-31T06:45:35 | 251,520,714 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dream.system;
import java.util.Properties;
/**
* @author :lixiang
* @version :v1.0
* @program :jvm
* @date :2020/3/31 11:38
* @description :
*/
public class SystemDemo {
public static void main(String[] args) {
System.setProperty("defined", "myValue");
Properties properties = System.getProperties();
properties.forEach((key, value) -> {
System.out.println(key + " ===== " + value);
});
String defined = System.getProperty("defined");
System.out.println("defined = " + defined);
}
}
| UTF-8 | Java | 585 | java | SystemDemo.java | Java | [
{
"context": "m;\n\nimport java.util.Properties;\n\n/**\n * @author :lixiang\n * @version :v1.0\n * @program :jvm\n * @date :2020",
"end": 80,
"score": 0.9965344071388245,
"start": 73,
"tag": "USERNAME",
"value": "lixiang"
}
] | null | [] | package com.dream.system;
import java.util.Properties;
/**
* @author :lixiang
* @version :v1.0
* @program :jvm
* @date :2020/3/31 11:38
* @description :
*/
public class SystemDemo {
public static void main(String[] args) {
System.setProperty("defined", "myValue");
Properties properties = System.getProperties();
properties.forEach((key, value) -> {
System.out.println(key + " ===== " + value);
});
String defined = System.getProperty("defined");
System.out.println("defined = " + defined);
}
}
| 585 | 0.593044 | 0.570435 | 26 | 21.115385 | 20.083149 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 15 |
0470dd31947d0d968f3fd6c1a23c4909b56d1f46 | 37,271,726,222,857 | dd62012819e5fe95ab5cb1b60b97e8f63e9ec7b3 | /esupplier-web/src/main/java/com/yjf/esupplier/web/controller/front/platform/ShoppingCartBaseController.java | 4307ebe71260dc700a43f7d4d707bef94e2648db | [] | no_license | cl510804194/fengjievue | https://github.com/cl510804194/fengjievue | 86a40c7e8c4ef3b432cd8152986b34c53174d6e6 | e1f58f14398a1b5ce0b671f17bfd4c3c88a8ee4e | refs/heads/master | 2020-04-19T09:48:17.742000 | 2019-01-29T08:52:26 | 2019-01-29T08:52:26 | 168,121,303 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yjf.esupplier.web.controller.front.platform;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import rop.thirdparty.com.google.common.collect.Lists;
import com.yjf.common.lang.util.StringUtil;
import com.yjf.esupplier.service.product.DeliveryService;
import com.yjf.esupplier.service.product.ShopCartService;
import com.yjf.esupplier.service.user.info.UserInfo;
import com.yjf.esupplier.web.controller.front.base.FrontAutowiredBaseController;
import com.yjf.esupplier.web.controller.front.platform.bean.Cart;
import com.yjf.esupplier.web.util.WebSessionUtil;
import com.yjf.esupplier.ws.info.CartItemInfo;
import com.yjf.esupplier.ws.product.enums.ShopingCartTypeEnum;
import com.yjf.esupplier.ws.product.info.ProductInfo;
import com.yjf.esupplier.ws.product.info.ShopCartInfo;
import com.yjf.esupplier.ws.product.order.ShopCartItemOrder;
import com.yjf.esupplier.ws.service.query.result.QueryBaseBatchResult;
public class ShoppingCartBaseController extends FrontAutowiredBaseController {
@Autowired
protected DeliveryService deliveryService;
@Autowired
protected ShopCartService shopCartService;
protected void initShopCart(UserInfo userInfo) {
initShopCart(userInfo, ShopingCartTypeEnum.O2O);
}
protected void initShopCart(UserInfo userInfo, ShopingCartTypeEnum shopingCartType) {
QueryBaseBatchResult<ShopCartInfo> batchResult = shopCartService.getShopCartList(
userInfo.getUserId(), shopingCartType.code());
List<CartItemInfo> addNewCardItemList = Lists.newArrayList();
Cart cart = null;
if (ShopingCartTypeEnum.ORDER_MEAL == shopingCartType) {
cart = WebSessionUtil.getStaticCurrentOrderMealCart();
} else {
cart = WebSessionUtil.getStaticCurrentCart();
}
if (cart.getCount() > 0) {
Map<Long, List<CartItemInfo>> cartItemMap = cart.getValue();
Iterator<Entry<Long, List<CartItemInfo>>> iterator = cartItemMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Long, List<CartItemInfo>> entry = iterator.next();
for (CartItemInfo cartItemInfo : entry.getValue()) {
boolean isExist = false;
for (ShopCartInfo shopCartInfo : batchResult.getPageList()) {
if (cartItemInfo.getProductId() == shopCartInfo.getProductId()) {
isExist = true;
ShopCartItemOrder cartItemOrder = new ShopCartItemOrder();
cartItemOrder.setProductId(shopCartInfo.getProductId());
cartItemOrder.setUserId(shopCartInfo.getUserId());
cartItemOrder.setQuantity(cartItemInfo.getQuantity());
cartItemOrder.setPicPath(cartItemInfo.getImage());
cartItemOrder.setProductName(shopCartInfo.getProductName());
cartItemOrder.setPrice(cartItemInfo.getPrice());
cartItemOrder.setTotalPrice(cartItemOrder.getPrice().multiply(
cartItemOrder.getQuantity()));
cartItemOrder.setSupplierId(shopCartInfo.getSupplierId());
cartItemOrder.setSupplierName(shopCartInfo.getSupplierName());
cartItemOrder.setUserName(userInfo.getUserName());
cartItemOrder.setUserNikename(userInfo.getNickname());
cartItemOrder.setProductUnit(shopCartInfo.getProductUnit());
cartItemOrder.setSaleType(cart.getShopingCartType().code());
shopCartService.updateShopCartItem(cartItemOrder);
}
}
if (!isExist) {
addNewCardItemList.add(cartItemInfo);
}
}
}
for (CartItemInfo cartItemInfo : addNewCardItemList) {
ProductInfo productInfo = productService.findProductById(cartItemInfo
.getProductId());
ShopCartItemOrder cartItemOrder = new ShopCartItemOrder();
cartItemOrder.setPicPath(productInfo.getSmallPicPath());
cartItemOrder.setProductId(productInfo.getProductId());
cartItemOrder.setProductName(productInfo.getProductName());
cartItemOrder.setQuantity(cartItemInfo.getQuantity());
cartItemOrder.setPrice(cartItemInfo.getPrice());
cartItemOrder.setTotalPrice(cartItemOrder.getPrice().multiply(
cartItemOrder.getQuantity()));
cartItemOrder.setSupplierId(productInfo.getSupplierId());
cartItemOrder.setSupplierName(productInfo.getSupplierName());
cartItemOrder.setUserId(userInfo.getUserId());
cartItemOrder.setUserName(userInfo.getUserName());
cartItemOrder.setUserNikename(userInfo.getNickname());
cartItemOrder.setProductUnit(productInfo.getProductUnit());
cartItemOrder.setSaleType(cart.getShopingCartType().code());
shopCartService.addShopCartItem(cartItemOrder);
}
}
for (ShopCartInfo shopCartInfo : batchResult.getPageList()) {
if (StringUtil.equals("1", shopCartInfo.getIsDelete()))
continue;
CartItemInfo item = new CartItemInfo(shopCartInfo.getProductId(),
shopCartInfo.getSupplierId(), (int) shopCartInfo.getQuantity());
item.setName(shopCartInfo.getProductName());
item.setPrice(shopCartInfo.getPrice());
item.setImage(shopCartInfo.getPicPath());
item.setSupplierName(shopCartInfo.getSupplierName());
item.setUnit(shopCartInfo.getProductUnit());
ProductInfo productInfo = productService.findProductById(shopCartInfo.getProductId());
if (productInfo.getPostType() != null)
item.setPostType(productInfo.getPostType().getDbValue());
else
item.setPostType(0);
/*邮费单独计算*/
item.setDeliveryInfo(null);
cart.addCartItemInfo(item);
}
}
}
| UTF-8 | Java | 5,393 | java | ShoppingCartBaseController.java | Java | [] | null | [] | package com.yjf.esupplier.web.controller.front.platform;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import rop.thirdparty.com.google.common.collect.Lists;
import com.yjf.common.lang.util.StringUtil;
import com.yjf.esupplier.service.product.DeliveryService;
import com.yjf.esupplier.service.product.ShopCartService;
import com.yjf.esupplier.service.user.info.UserInfo;
import com.yjf.esupplier.web.controller.front.base.FrontAutowiredBaseController;
import com.yjf.esupplier.web.controller.front.platform.bean.Cart;
import com.yjf.esupplier.web.util.WebSessionUtil;
import com.yjf.esupplier.ws.info.CartItemInfo;
import com.yjf.esupplier.ws.product.enums.ShopingCartTypeEnum;
import com.yjf.esupplier.ws.product.info.ProductInfo;
import com.yjf.esupplier.ws.product.info.ShopCartInfo;
import com.yjf.esupplier.ws.product.order.ShopCartItemOrder;
import com.yjf.esupplier.ws.service.query.result.QueryBaseBatchResult;
public class ShoppingCartBaseController extends FrontAutowiredBaseController {
@Autowired
protected DeliveryService deliveryService;
@Autowired
protected ShopCartService shopCartService;
protected void initShopCart(UserInfo userInfo) {
initShopCart(userInfo, ShopingCartTypeEnum.O2O);
}
protected void initShopCart(UserInfo userInfo, ShopingCartTypeEnum shopingCartType) {
QueryBaseBatchResult<ShopCartInfo> batchResult = shopCartService.getShopCartList(
userInfo.getUserId(), shopingCartType.code());
List<CartItemInfo> addNewCardItemList = Lists.newArrayList();
Cart cart = null;
if (ShopingCartTypeEnum.ORDER_MEAL == shopingCartType) {
cart = WebSessionUtil.getStaticCurrentOrderMealCart();
} else {
cart = WebSessionUtil.getStaticCurrentCart();
}
if (cart.getCount() > 0) {
Map<Long, List<CartItemInfo>> cartItemMap = cart.getValue();
Iterator<Entry<Long, List<CartItemInfo>>> iterator = cartItemMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Long, List<CartItemInfo>> entry = iterator.next();
for (CartItemInfo cartItemInfo : entry.getValue()) {
boolean isExist = false;
for (ShopCartInfo shopCartInfo : batchResult.getPageList()) {
if (cartItemInfo.getProductId() == shopCartInfo.getProductId()) {
isExist = true;
ShopCartItemOrder cartItemOrder = new ShopCartItemOrder();
cartItemOrder.setProductId(shopCartInfo.getProductId());
cartItemOrder.setUserId(shopCartInfo.getUserId());
cartItemOrder.setQuantity(cartItemInfo.getQuantity());
cartItemOrder.setPicPath(cartItemInfo.getImage());
cartItemOrder.setProductName(shopCartInfo.getProductName());
cartItemOrder.setPrice(cartItemInfo.getPrice());
cartItemOrder.setTotalPrice(cartItemOrder.getPrice().multiply(
cartItemOrder.getQuantity()));
cartItemOrder.setSupplierId(shopCartInfo.getSupplierId());
cartItemOrder.setSupplierName(shopCartInfo.getSupplierName());
cartItemOrder.setUserName(userInfo.getUserName());
cartItemOrder.setUserNikename(userInfo.getNickname());
cartItemOrder.setProductUnit(shopCartInfo.getProductUnit());
cartItemOrder.setSaleType(cart.getShopingCartType().code());
shopCartService.updateShopCartItem(cartItemOrder);
}
}
if (!isExist) {
addNewCardItemList.add(cartItemInfo);
}
}
}
for (CartItemInfo cartItemInfo : addNewCardItemList) {
ProductInfo productInfo = productService.findProductById(cartItemInfo
.getProductId());
ShopCartItemOrder cartItemOrder = new ShopCartItemOrder();
cartItemOrder.setPicPath(productInfo.getSmallPicPath());
cartItemOrder.setProductId(productInfo.getProductId());
cartItemOrder.setProductName(productInfo.getProductName());
cartItemOrder.setQuantity(cartItemInfo.getQuantity());
cartItemOrder.setPrice(cartItemInfo.getPrice());
cartItemOrder.setTotalPrice(cartItemOrder.getPrice().multiply(
cartItemOrder.getQuantity()));
cartItemOrder.setSupplierId(productInfo.getSupplierId());
cartItemOrder.setSupplierName(productInfo.getSupplierName());
cartItemOrder.setUserId(userInfo.getUserId());
cartItemOrder.setUserName(userInfo.getUserName());
cartItemOrder.setUserNikename(userInfo.getNickname());
cartItemOrder.setProductUnit(productInfo.getProductUnit());
cartItemOrder.setSaleType(cart.getShopingCartType().code());
shopCartService.addShopCartItem(cartItemOrder);
}
}
for (ShopCartInfo shopCartInfo : batchResult.getPageList()) {
if (StringUtil.equals("1", shopCartInfo.getIsDelete()))
continue;
CartItemInfo item = new CartItemInfo(shopCartInfo.getProductId(),
shopCartInfo.getSupplierId(), (int) shopCartInfo.getQuantity());
item.setName(shopCartInfo.getProductName());
item.setPrice(shopCartInfo.getPrice());
item.setImage(shopCartInfo.getPicPath());
item.setSupplierName(shopCartInfo.getSupplierName());
item.setUnit(shopCartInfo.getProductUnit());
ProductInfo productInfo = productService.findProductById(shopCartInfo.getProductId());
if (productInfo.getPostType() != null)
item.setPostType(productInfo.getPostType().getDbValue());
else
item.setPostType(0);
/*邮费单独计算*/
item.setDeliveryInfo(null);
cart.addCartItemInfo(item);
}
}
}
| 5,393 | 0.768259 | 0.767515 | 123 | 42.747967 | 25.129452 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.715447 | false | false | 15 |
7e4169124ea21c9136903e2349ebbde319a344f7 | 34,248,069,271,026 | 058c25584d8cd255e4cb9189c6e115e0ec8586b5 | /JavaPractice/src/org/dimigo/exception/AgeCheckException.java | 5811854d6f926d36956d12806b81096b2490ebeb | [] | no_license | hd132520/JavaPractice | https://github.com/hd132520/JavaPractice | 45717662b323edd6ef78ed329d9c73379378826b | 09bb1b807f346dc0e8ff0c63d171e8f42e5f80fe | refs/heads/master | 2021-01-16T19:33:29.957000 | 2015-11-10T01:54:13 | 2015-11-10T01:54:13 | 32,296,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package org.dimigo.exception;
/**
*<pre>
*
* JavaPractice
* org.dimigo.exception
* |_ AgeCheckException
*
* 1. 개요 :
* 2. 작성일: 2015. 9. 21.
*
*
* </pre>
* @author : 박수환
* @version : 1.0
*/
public class AgeCheckException extends Exception {
public AgeCheckException() {
}
public AgeCheckException(Movie movie) {
super(movie.getTitle()+"은/는"+movie.getLimitAge()+"이상 관람가 입니다.");
}
}
| UTF-8 | Java | 489 | java | AgeCheckException.java | Java | [
{
"context": "일: 2015. 9. 21.\r\n *\r\n *\r\n * </pre>\r\n * @author : 박수환\r\n * @version : 1.0\r\n */\r\npublic class AgeCheckEx",
"end": 213,
"score": 0.9998507499694824,
"start": 210,
"tag": "NAME",
"value": "박수환"
}
] | null | [] | /**
*
*/
package org.dimigo.exception;
/**
*<pre>
*
* JavaPractice
* org.dimigo.exception
* |_ AgeCheckException
*
* 1. 개요 :
* 2. 작성일: 2015. 9. 21.
*
*
* </pre>
* @author : 박수환
* @version : 1.0
*/
public class AgeCheckException extends Exception {
public AgeCheckException() {
}
public AgeCheckException(Movie movie) {
super(movie.getTitle()+"은/는"+movie.getLimitAge()+"이상 관람가 입니다.");
}
}
| 489 | 0.560706 | 0.536424 | 30 | 13.1 | 16.147963 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 15 |
366adff96e71c679a21fa971919a067c8a80e06e | 37,632,503,464,022 | b38aa1da91e1b35a2d6dddd7e197d12bcce58a64 | /src/main/java/com/virtusa/impl/NumberWordConverter.java | 02ae12c24f721be6a80baaec7d8949940e838a3e | [] | no_license | ramkumargs/virtusa_numbertoword | https://github.com/ramkumargs/virtusa_numbertoword | 6e6c250d68543e9bc526da1e9ba814acd7445899 | 0d7db5d29b176b2aa9c89c3dbfdf50879944d9fb | refs/heads/master | 2021-07-09T10:19:06.227000 | 2019-08-17T09:28:54 | 2019-08-17T09:28:54 | 202,860,651 | 0 | 0 | null | false | 2020-10-13T15:23:51 | 2019-08-17T09:23:01 | 2019-08-17T09:29:35 | 2020-10-13T15:23:50 | 4 | 0 | 0 | 1 | Java | false | false | package com.virtusa.impl;
import com.virtusa.Constants;
import com.virtusa.INumberWorderConverter;
import com.virtusa.exception.NumberValidationException;
public class NumberWordConverter implements INumberWorderConverter, Constants {
public String getWordFromNumber(int number) {
if (number <= 0) {
throw new NumberValidationException(NUMBER_SHOULD_BE_GREATER_THAN_ZERO);
}
if (number > 999999999) {
throw new NumberValidationException(NUMBER_SHOULD_NOT_BE_GREATER_THAN_999_999_999);
}
return new NumberWordConverter().converter(number);
}
private String converter(int num) {
if (num < 20) {
return one[num];
}
if (num < 100) {
return ten[num / 10] + ((num % 10 != 0) ? STRING2 : STRING) + one[num % 10];
}
if (num < 1000) {
return one[num / 100] + HUNDRED + ((num % 100 != 0) ? AND : STRING) + converter(num % 100);
}
if (num < 100000) {
return converter(num / 1000) + THOUSAND + ((num % 10000 != 0) ? STRING2 : STRING) + converter(num % 1000);
}
if (num < 10000000) {
return converter(num / 100000) + HUNDRED + ((num % 100000 != 0) ? AND : STRING) + converter(num % 100000);
}
return converter(num / 1000000) + MILLION + ((num % 1000000 != 0) ? STRING2 : STRING) + converter(num % 1000000);
}
}
| UTF-8 | Java | 1,267 | java | NumberWordConverter.java | Java | [] | null | [] | package com.virtusa.impl;
import com.virtusa.Constants;
import com.virtusa.INumberWorderConverter;
import com.virtusa.exception.NumberValidationException;
public class NumberWordConverter implements INumberWorderConverter, Constants {
public String getWordFromNumber(int number) {
if (number <= 0) {
throw new NumberValidationException(NUMBER_SHOULD_BE_GREATER_THAN_ZERO);
}
if (number > 999999999) {
throw new NumberValidationException(NUMBER_SHOULD_NOT_BE_GREATER_THAN_999_999_999);
}
return new NumberWordConverter().converter(number);
}
private String converter(int num) {
if (num < 20) {
return one[num];
}
if (num < 100) {
return ten[num / 10] + ((num % 10 != 0) ? STRING2 : STRING) + one[num % 10];
}
if (num < 1000) {
return one[num / 100] + HUNDRED + ((num % 100 != 0) ? AND : STRING) + converter(num % 100);
}
if (num < 100000) {
return converter(num / 1000) + THOUSAND + ((num % 10000 != 0) ? STRING2 : STRING) + converter(num % 1000);
}
if (num < 10000000) {
return converter(num / 100000) + HUNDRED + ((num % 100000 != 0) ? AND : STRING) + converter(num % 100000);
}
return converter(num / 1000000) + MILLION + ((num % 1000000 != 0) ? STRING2 : STRING) + converter(num % 1000000);
}
}
| 1,267 | 0.660616 | 0.568272 | 44 | 27.795454 | 34.809597 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 15 |
c855319ab86175e84fe3daf24d60ac566e09f7c8 | 39,530,879,030,028 | b8fb03eb7538736bfe68a63950781d2609c092f1 | /src/main/java/com/cli/CliTest.java | b0ec28daa5d558da615c7ec02d3c15530712c45e | [] | no_license | earthxiaoyi/netty | https://github.com/earthxiaoyi/netty | ed1c9a5751abe719c06bf4f52494f43c85d0e014 | a4f6245e86f5e86503245d68751f6964f6bdbfbe | refs/heads/master | 2020-12-24T13:20:18.175000 | 2015-08-11T09:57:31 | 2015-08-11T09:57:31 | 40,393,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cli;
import java.util.Scanner;
public class CliTest {
public static void main(String[] args) {
/*Options options = new Options();
options.addOption("t",false,"display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if(cmd.hasOption("t")){
System.out.println(new Date().toGMTString());
}else{
System.out.println("command is error");
}*/
Scanner s = new Scanner(System.in);
while(true){
System.out.println("请输入:");
String str = s.next();
System.out.println(str);
}
}
}
| UTF-8 | Java | 628 | java | CliTest.java | Java | [] | null | [] | package com.cli;
import java.util.Scanner;
public class CliTest {
public static void main(String[] args) {
/*Options options = new Options();
options.addOption("t",false,"display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if(cmd.hasOption("t")){
System.out.println(new Date().toGMTString());
}else{
System.out.println("command is error");
}*/
Scanner s = new Scanner(System.in);
while(true){
System.out.println("请输入:");
String str = s.next();
System.out.println(str);
}
}
}
| 628 | 0.630645 | 0.630645 | 27 | 20.962963 | 17.980404 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.222222 | false | false | 15 |
14fae76814e856eb2a7c998db34e890f1439854e | 38,431,367,381,594 | 41a0735c5f522f3b273afc74c111591c1d67effe | /src/nilsl/processing/lib/img/filters/OrderByBriFilter.java | 96c7aae42d36e75ca905c8b774074795f1085fd0 | [] | no_license | NilsL/ProcessingJava | https://github.com/NilsL/ProcessingJava | aa6432ae47feb10eb4ebb4ca56cf366e53b235df | e0c25ea159179cdf83deeef93c4d05a32c1a09f6 | refs/heads/master | 2021-01-25T05:34:40.400000 | 2014-09-03T21:42:39 | 2014-09-03T21:42:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nilsl.processing.lib.img.filters;
import java.util.Collections;
import java.util.List;
import nilsl.processing.lib.img.NImage;
import nilsl.processing.lib.img.comparators.BriComparator;
public class OrderByBriFilter implements FilterCommand {
private boolean desc;
public OrderByBriFilter(boolean desc) {
this.desc = desc;
}
@Override
public void apply(List<? super NImage> images) {
((List<NImage>) images).sort(new BriComparator());
if (desc)
Collections.reverse(images);
}
@Override
public boolean removeAfterApply() {
return true;
}
}
| UTF-8 | Java | 576 | java | OrderByBriFilter.java | Java | [] | null | [] | package nilsl.processing.lib.img.filters;
import java.util.Collections;
import java.util.List;
import nilsl.processing.lib.img.NImage;
import nilsl.processing.lib.img.comparators.BriComparator;
public class OrderByBriFilter implements FilterCommand {
private boolean desc;
public OrderByBriFilter(boolean desc) {
this.desc = desc;
}
@Override
public void apply(List<? super NImage> images) {
((List<NImage>) images).sort(new BriComparator());
if (desc)
Collections.reverse(images);
}
@Override
public boolean removeAfterApply() {
return true;
}
}
| 576 | 0.75 | 0.75 | 30 | 18.200001 | 19.516489 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 15 |
af51aebdb486e26377b1054988b93aa3e57f099d | 33,981,781,301,301 | b41f92836be5d84fa24a9e5204eae28345d370bc | /src/main/java/io/github/hbothra/simplebugtracker/controller/BugsController.java | b0a4cde95c3fe0f320e79ae927aa9a8169d1a1d7 | [] | no_license | hbothra15/simple-bug | https://github.com/hbothra15/simple-bug | afc5b57e9f34199b418c60e131d4f5fbded96379 | 248760efd3e22695bce80e5886ff0124071f7315 | refs/heads/master | 2022-10-12T18:44:57.883000 | 2020-06-07T08:15:09 | 2020-06-07T08:15:09 | 263,025,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.hbothra.simplebugtracker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.hbothra.simplebugtracker.ro.BugCommentsRo;
import io.github.hbothra.simplebugtracker.ro.BugRo;
import io.github.hbothra.simplebugtracker.service.BugService;
@RestController
@RequestMapping("/api/bugs")
@PreAuthorize("hasRole('VENDOR') or hasRole('SUPPORT') or hasRole('ADMIN')")
public class BugsController {
@Autowired
private BugService bugService;
@GetMapping
@PreAuthorize("hasRole('ADMIN')")
public List<BugRo> getAllBugs() {
return bugService.findAll();
}
@GetMapping("/user")
@PreAuthorize("hasRole('VENDOR') or hasRole('SUPPORT')")
public List<BugRo> fetchAllBugsBasedOnUserId(@AuthenticationPrincipal(expression = "userId") Long userId) {
return bugService.fetchAllBugsBasedOnUserId(userId);
}
@GetMapping("/{id}/comments")
public List<BugCommentsRo> getBugComments(@PathVariable("id") long id) {
return bugService.getAllComments(id);
}
@PostMapping
public BugRo addBug(@RequestBody BugRo bug, @AuthenticationPrincipal(expression = "userId") Long userId) {
bug.setCreatedById(userId);
bug.setModifiedById(userId);
return bugService.addBug(bug);
}
@PutMapping
public BugRo updateBug(@RequestBody BugRo bug, @AuthenticationPrincipal(expression = "userId") Long userId) {
bug.setModifiedById(userId);
return bugService.updateBug(bug);
}
}
| UTF-8 | Java | 2,022 | java | BugsController.java | Java | [
{
"context": "package io.github.hbothra.simplebugtracker.controller;\n\nimport java.util.Li",
"end": 25,
"score": 0.8539700508117676,
"start": 18,
"tag": "USERNAME",
"value": "hbothra"
},
{
"context": "ind.annotation.RestController;\n\nimport io.github.hbothra.simplebugtracker.ro.Bug... | null | [] | package io.github.hbothra.simplebugtracker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.hbothra.simplebugtracker.ro.BugCommentsRo;
import io.github.hbothra.simplebugtracker.ro.BugRo;
import io.github.hbothra.simplebugtracker.service.BugService;
@RestController
@RequestMapping("/api/bugs")
@PreAuthorize("hasRole('VENDOR') or hasRole('SUPPORT') or hasRole('ADMIN')")
public class BugsController {
@Autowired
private BugService bugService;
@GetMapping
@PreAuthorize("hasRole('ADMIN')")
public List<BugRo> getAllBugs() {
return bugService.findAll();
}
@GetMapping("/user")
@PreAuthorize("hasRole('VENDOR') or hasRole('SUPPORT')")
public List<BugRo> fetchAllBugsBasedOnUserId(@AuthenticationPrincipal(expression = "userId") Long userId) {
return bugService.fetchAllBugsBasedOnUserId(userId);
}
@GetMapping("/{id}/comments")
public List<BugCommentsRo> getBugComments(@PathVariable("id") long id) {
return bugService.getAllComments(id);
}
@PostMapping
public BugRo addBug(@RequestBody BugRo bug, @AuthenticationPrincipal(expression = "userId") Long userId) {
bug.setCreatedById(userId);
bug.setModifiedById(userId);
return bugService.addBug(bug);
}
@PutMapping
public BugRo updateBug(@RequestBody BugRo bug, @AuthenticationPrincipal(expression = "userId") Long userId) {
bug.setModifiedById(userId);
return bugService.updateBug(bug);
}
}
| 2,022 | 0.799703 | 0.799703 | 58 | 33.862068 | 30.01577 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.155172 | false | false | 15 |
3f69b42e422f475cbf5e627d53728bdd0e823346 | 19,928,648,316,510 | 13ad7d75350bc3f40fae0c21ce33ebc579671fd4 | /app/src/main/java/com/example/dulich/Object/BanBe.java | 4a7a72294c4af6c89093d3cd6ac65ffcc0590a56 | [] | no_license | chotchachi/DuLich | https://github.com/chotchachi/DuLich | 02e296818ff3ffd4c5bb8718e908d293d3afe250 | 3d7fa6d6d4dd95a716b5d77f83f5ab941c78b08a | refs/heads/master | 2022-12-10T15:54:04.654000 | 2020-09-08T04:14:30 | 2020-09-08T04:14:30 | 189,409,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.dulich.Object;
public class BanBe {
private String Username;
private String User_Id;
public BanBe(String username, String user_id) {
Username = username;
User_Id = user_id;
}
public BanBe(){
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getUser_Id() {
return User_Id;
}
public void setUser_Id(String user_Id) {
User_Id = user_Id;
}
}
| UTF-8 | Java | 551 | java | BanBe.java | Java | [
{
"context": "ing username, String user_id) {\n Username = username;\n User_Id = user_id;\n }\n\n public Ban",
"end": 194,
"score": 0.9951291084289551,
"start": 186,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.example.dulich.Object;
public class BanBe {
private String Username;
private String User_Id;
public BanBe(String username, String user_id) {
Username = username;
User_Id = user_id;
}
public BanBe(){
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getUser_Id() {
return User_Id;
}
public void setUser_Id(String user_Id) {
User_Id = user_Id;
}
}
| 551 | 0.589837 | 0.589837 | 31 | 16.774193 | 15.708452 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.322581 | false | false | 15 |
5927899f275112abb9c23f9a47bcfe6d2604a523 | 37,099,927,535,253 | 52c821fa7f7edae6af0a7861ab250e4e0170e5a1 | /base/src/it/fabiobiscaro/socket/biagio/ClientSide/SckClt.java | daddac9ef3fcb562a3d614efde1ba4e9f560a97e | [] | no_license | meogrande/einaudi-adventure | https://github.com/meogrande/einaudi-adventure | fd728620ded9e7cee1e0b4b5744a9d455fe94f11 | df02c46d66f73dba16a8dbb4cdf7656673038f98 | refs/heads/master | 2022-05-14T13:04:47.281000 | 2022-05-01T10:17:22 | 2022-05-01T10:17:22 | 49,280,626 | 4 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | /***
* @author BiRG81
* @descrption Classe Client-Side allo scopo di:
* - instaurare una connessione con il server
* - mandare al server, attraverso un socket, messaggi di testo
* - chiudere da remoto il socket nel caso in cui il messaggio inviato sia END
***/
package it.fabiobiscaro.socket.biagio.ClientSide;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class SckClt {
public static void main(String[] args) throws IOException {
// prelievo da linea di comando dei parametri IP, PORT, MSG
final String IP = (args.length > 0) ? args[0] : "localhost";
final int PORT = (args.length > 1) ? Integer.parseInt(args[1]) : 1234;
final String MSG = (args.length > 2) ? args[2] : "VAT 69 - Un wisky maschio senza rischio!";
// Creazione di uno stream per la scrittura sul buffer
PrintWriter out = null;
//instaurazione del socket
Socket s = new Socket(IP, PORT);
out = new PrintWriter(s.getOutputStream(), true);
out.println(MSG); // invio messagio al server
System.out.print(
"Client attivo [" + s.getLocalAddress() + "]\n" +
" - Connesso al Server: " + IP + ":" +PORT + "\n" +
" - invio messaggio: " + MSG + "..\n");
s.close();
System.out.println("Client chiuso...");
}
}
| UTF-8 | Java | 1,265 | java | SckClt.java | Java | [
{
"context": "/***\n * @author BiRG81\n * @descrption Classe Client-Side allo scopo di:\n",
"end": 22,
"score": 0.9997076988220215,
"start": 16,
"tag": "USERNAME",
"value": "BiRG81"
}
] | null | [] | /***
* @author BiRG81
* @descrption Classe Client-Side allo scopo di:
* - instaurare una connessione con il server
* - mandare al server, attraverso un socket, messaggi di testo
* - chiudere da remoto il socket nel caso in cui il messaggio inviato sia END
***/
package it.fabiobiscaro.socket.biagio.ClientSide;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class SckClt {
public static void main(String[] args) throws IOException {
// prelievo da linea di comando dei parametri IP, PORT, MSG
final String IP = (args.length > 0) ? args[0] : "localhost";
final int PORT = (args.length > 1) ? Integer.parseInt(args[1]) : 1234;
final String MSG = (args.length > 2) ? args[2] : "VAT 69 - Un wisky maschio senza rischio!";
// Creazione di uno stream per la scrittura sul buffer
PrintWriter out = null;
//instaurazione del socket
Socket s = new Socket(IP, PORT);
out = new PrintWriter(s.getOutputStream(), true);
out.println(MSG); // invio messagio al server
System.out.print(
"Client attivo [" + s.getLocalAddress() + "]\n" +
" - Connesso al Server: " + IP + ":" +PORT + "\n" +
" - invio messaggio: " + MSG + "..\n");
s.close();
System.out.println("Client chiuso...");
}
}
| 1,265 | 0.671146 | 0.660079 | 44 | 27.75 | 26.553656 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.340909 | false | false | 15 |
635a911e67b2a4c8d2f511340f8fcf5a36ce0c82 | 38,800,734,599,767 | 9dfe781b62083b477d8f85668bd2f2e833d2d8b1 | /app/src/main/java/matheusfroes/ycecoco/adapters/OpcoesAdapter.java | 995a6a5b5a89bfa3fbe721db73d7b27060847c0e | [] | no_license | froesmatheus/yce-coco-app | https://github.com/froesmatheus/yce-coco-app | ea435201a0a0703642332e90a762cc64c33f807f | 605ba92262abaa69871547a3c705ed6b8af4662c | refs/heads/master | 2016-09-13T15:38:35.170000 | 2016-07-07T23:13:50 | 2016-07-07T23:13:50 | 62,584,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package matheusfroes.ycecoco.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import matheusfroes.ycecoco.activities.ListaPedidosActivity;
import matheusfroes.ycecoco.activities.ListaProdutosActivity;
import matheusfroes.ycecoco.activities.novo_pedido.NovoPedidoActivity;
import matheusfroes.ycecoco.R;
import matheusfroes.ycecoco.activities.ListaClientesActivity;
import matheusfroes.ycecoco.models.OpcaoMenu;
/**
* Created by matheus on 23/06/16.
*/
public class OpcoesAdapter extends RecyclerView.Adapter<OpcoesAdapter.ViewHolder> {
private Context contexto;
private List<OpcaoMenu> listaOpcoes;
public OpcoesAdapter(Context contexto, List<OpcaoMenu> listaOpcoes) {
this.contexto = contexto;
this.listaOpcoes = listaOpcoes;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(contexto).inflate(R.layout.opcao_view, null, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final OpcaoMenu opcaoMenu = listaOpcoes.get(position);
TextView opcaoTxt = (TextView) holder.view.findViewById(R.id.txt_opcao);
ImageView opcaoImg = (ImageView) holder.view.findViewById(R.id.img_opcao);
opcaoTxt.setText(opcaoMenu.getOpcao());
opcaoImg.setImageResource(opcaoMenu.getImgOpcao());
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent;
switch (opcaoMenu.getOpcao()) {
case "Novo Pedido":
intent = new Intent(contexto, NovoPedidoActivity.class);
contexto.startActivity(intent);
break;
case "Clientes":
intent = new Intent(contexto, ListaClientesActivity.class);
contexto.startActivity(intent);
break;
case "Produtos":
intent = new Intent(contexto, ListaProdutosActivity.class);
contexto.startActivity(intent);
break;
case "Pedidos":
intent = new Intent(contexto, ListaPedidosActivity.class);
contexto.startActivity(intent);
break;
}
}
});
}
@Override
public int getItemCount() {
return listaOpcoes.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public View view;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
}
}
}
| UTF-8 | Java | 3,054 | java | OpcoesAdapter.java | Java | [
{
"context": "froes.ycecoco.models.OpcaoMenu;\n\n/**\n * Created by matheus on 23/06/16.\n */\npublic class OpcoesAdapter exten",
"end": 692,
"score": 0.99894779920578,
"start": 685,
"tag": "USERNAME",
"value": "matheus"
}
] | null | [] | package matheusfroes.ycecoco.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import matheusfroes.ycecoco.activities.ListaPedidosActivity;
import matheusfroes.ycecoco.activities.ListaProdutosActivity;
import matheusfroes.ycecoco.activities.novo_pedido.NovoPedidoActivity;
import matheusfroes.ycecoco.R;
import matheusfroes.ycecoco.activities.ListaClientesActivity;
import matheusfroes.ycecoco.models.OpcaoMenu;
/**
* Created by matheus on 23/06/16.
*/
public class OpcoesAdapter extends RecyclerView.Adapter<OpcoesAdapter.ViewHolder> {
private Context contexto;
private List<OpcaoMenu> listaOpcoes;
public OpcoesAdapter(Context contexto, List<OpcaoMenu> listaOpcoes) {
this.contexto = contexto;
this.listaOpcoes = listaOpcoes;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(contexto).inflate(R.layout.opcao_view, null, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final OpcaoMenu opcaoMenu = listaOpcoes.get(position);
TextView opcaoTxt = (TextView) holder.view.findViewById(R.id.txt_opcao);
ImageView opcaoImg = (ImageView) holder.view.findViewById(R.id.img_opcao);
opcaoTxt.setText(opcaoMenu.getOpcao());
opcaoImg.setImageResource(opcaoMenu.getImgOpcao());
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent;
switch (opcaoMenu.getOpcao()) {
case "Novo Pedido":
intent = new Intent(contexto, NovoPedidoActivity.class);
contexto.startActivity(intent);
break;
case "Clientes":
intent = new Intent(contexto, ListaClientesActivity.class);
contexto.startActivity(intent);
break;
case "Produtos":
intent = new Intent(contexto, ListaProdutosActivity.class);
contexto.startActivity(intent);
break;
case "Pedidos":
intent = new Intent(contexto, ListaPedidosActivity.class);
contexto.startActivity(intent);
break;
}
}
});
}
@Override
public int getItemCount() {
return listaOpcoes.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public View view;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
}
}
}
| 3,054 | 0.632286 | 0.629993 | 91 | 32.56044 | 26.113535 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.593407 | false | false | 15 |
8fe4a531ef50bb11dd0aefca08f07b044a28a789 | 39,530,878,996,336 | 4d099aff696a3be1a53b4d088a514a369ff70f30 | /bulk_fhir_resource_curator/src/test/java/edu/gatech/curator/factory/RetrofitClientFactoryTest.java | 9b09179c59ea5bcb4760523e3a6e659aad7a4b22 | [] | no_license | chemketoo/CS6440 | https://github.com/chemketoo/CS6440 | 9c787d781fcc5e0b36eaf4fab968ad3a294ff641 | 599937e80857e699bc8d75d68fcaade9b545a20b | refs/heads/master | 2020-07-16T02:31:49.250000 | 2019-06-05T10:28:17 | 2019-06-05T10:28:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.gatech.curator.factory;
import edu.gatech.curator.client.BulkFhirApiClient;
import edu.gatech.curator.entity.SourceSystemEntity;
import edu.gatech.curator.service.CuratorService;
import edu.gatech.curator.service.ServiceTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.MalformedURLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@SpringBootTest
@Import(ServiceTestConfiguration.class)
@RunWith(SpringRunner.class)
public class RetrofitClientFactoryTest {
@MockBean
CuratorService service;
@Autowired
ApplicationContext context;
@Autowired
RetrofitClientFactory subject;
@Mock
private SourceSystemEntity sourceSystem;
@Before
public void setUp() {
when(sourceSystem.getBaseUrl()).thenReturn("http://localhost.test");
}
@Test
public void getAPIClient() throws MalformedURLException {
BulkFhirApiClient client = subject.getAPIClient(sourceSystem);
assertThat(client).isNotNull();
}
} | UTF-8 | Java | 1,491 | java | RetrofitClientFactoryTest.java | Java | [] | null | [] | package edu.gatech.curator.factory;
import edu.gatech.curator.client.BulkFhirApiClient;
import edu.gatech.curator.entity.SourceSystemEntity;
import edu.gatech.curator.service.CuratorService;
import edu.gatech.curator.service.ServiceTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.MalformedURLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@SpringBootTest
@Import(ServiceTestConfiguration.class)
@RunWith(SpringRunner.class)
public class RetrofitClientFactoryTest {
@MockBean
CuratorService service;
@Autowired
ApplicationContext context;
@Autowired
RetrofitClientFactory subject;
@Mock
private SourceSystemEntity sourceSystem;
@Before
public void setUp() {
when(sourceSystem.getBaseUrl()).thenReturn("http://localhost.test");
}
@Test
public void getAPIClient() throws MalformedURLException {
BulkFhirApiClient client = subject.getAPIClient(sourceSystem);
assertThat(client).isNotNull();
}
} | 1,491 | 0.792757 | 0.792086 | 51 | 28.254902 | 23.141375 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false | 15 |
56a4fe8fa2bd464467409d4df21f5aebf4cc358c | 455,266,550,075 | db128eef5de3d21dfb9bb4f159b051ae18c26a53 | /Main.java | 01a27806498ca593a3809988cac40c6f5b988dcf | [] | no_license | joshdemusz/CS1632_D2 | https://github.com/joshdemusz/CS1632_D2 | b814b0c6a0aa501fa935ce102d516a0ded6c8556 | 6627d75bcf7cef3b542210c8ab5a02f695849978 | refs/heads/master | 2021-01-19T12:37:12.967000 | 2017-02-19T22:08:09 | 2017-02-19T22:08:09 | 82,348,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Josh Demusz
CS 1632
Deliverable 2
2/19/17
*/
public class Main
{
public static void main(String[] args)
{
// Create a simulation object
Simulation sim = new Simulation();
Integer seed = sim.checkArgs(args);
// If seed is null, input was invalid
if(seed == null)
{
System.out.println("Please enter the correct arguments.");
System.exit(0);
}
// Run the simulation
sim.run();
}
}
| UTF-8 | Java | 511 | java | Main.java | Java | [
{
"context": "/*\n Josh Demusz\n CS 1632\n Deliverable 2\n 2/19/17\n */\n\npu",
"end": 18,
"score": 0.9997347593307495,
"start": 7,
"tag": "NAME",
"value": "Josh Demusz"
}
] | null | [] | /*
<NAME>
CS 1632
Deliverable 2
2/19/17
*/
public class Main
{
public static void main(String[] args)
{
// Create a simulation object
Simulation sim = new Simulation();
Integer seed = sim.checkArgs(args);
// If seed is null, input was invalid
if(seed == null)
{
System.out.println("Please enter the correct arguments.");
System.exit(0);
}
// Run the simulation
sim.run();
}
}
| 506 | 0.528376 | 0.506849 | 28 | 17.25 | 18.009174 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 15 |
7d4b9c2d0cc9fbfef37030478bc39919db089fde | 28,200,755,315,849 | dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9 | /data_defect4j/preprossed_method_corpus/Math/16/org/apache/commons/math3/util/Decimal64Field_getInstance_44.java | 96a23f667cee868f6de09f990b28e46c23a037c1 | [] | no_license | hvdthong/NetML | https://github.com/hvdthong/NetML | dca6cf4d34c5799b400d718e0a6cd2e0b167297d | 9bb103da21327912e5a29cbf9be9ff4d058731a5 | refs/heads/master | 2021-06-30T15:03:52.618000 | 2020-10-07T01:58:48 | 2020-10-07T01:58:48 | 150,383,588 | 1 | 1 | null | true | 2018-09-26T07:08:45 | 2018-09-26T07:08:44 | 2018-03-01T05:04:19 | 2018-01-15T07:59:20 | 172,367 | 0 | 0 | 0 | null | false | null |
org apach common math3 util
field precis float point number
version
decimal64
decimal64 field decimal64field field decimal64
return uniqu instanc
uniqu instanc
decimal64 field decimal64field instanc getinst
instanc
| UTF-8 | Java | 268 | java | Decimal64Field_getInstance_44.java | Java | [] | null | [] |
org apach common math3 util
field precis float point number
version
decimal64
decimal64 field decimal64field field decimal64
return uniqu instanc
uniqu instanc
decimal64 field decimal64field instanc getinst
instanc
| 268 | 0.697761 | 0.649254 | 29 | 7.103448 | 13.399292 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 15 |
60ad99977a8866da4cdfd9ae6813fbbe131eaec3 | 33,122,787,838,088 | 92dae771e19102dff69b95973287a827619d447b | /MyDemo/src/com/demo/reflect/ReflectSample.java | 498aa0d9ad5ed8451376a7d9f6dd9184da9e6fd1 | [] | no_license | myunlong/exam | https://github.com/myunlong/exam | 200b9222b3ff8d7ed60e0797adc39c0e57815804 | df1ea9533e7bb8a289a40900323f22f298fc238b | refs/heads/master | 2020-07-21T21:04:55.266000 | 2019-09-10T14:24:30 | 2019-09-10T14:24:30 | 206,975,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @ClassName ReflectSample
* @Description TODO
* @Author Yunlong
* @Date 2019/9/3 19:15
* @Version 1.0
*/
public class ReflectSample {
public static void main(String[] args) throws Exception {
Class rc = Class.forName("com.demo.reflect.Robot");
Robot r = (Robot) rc.newInstance();
// 获取类名
System.out.println("Class name is " + rc.getName());
// 获取私有方法
Method getHello = rc.getDeclaredMethod("sayHello", String.class);
getHello.setAccessible(true);
// 执行方法
getHello.invoke(r, "Bob");
// 获取公有方法
Method sayHi = rc.getMethod("sayHi");
// 获取成员变量
Field name = rc.getDeclaredField("name");
name.setAccessible(true);
// 给变量赋值
name.set(r, "Alice");
sayHi.invoke(r);
}
}
| UTF-8 | Java | 970 | java | ReflectSample.java | Java | [
{
"context": "Name ReflectSample\n * @Description TODO\n * @Author Yunlong\n * @Date 2019/9/3 19:15\n * @Version 1.0\n */",
"end": 158,
"score": 0.5299796462059021,
"start": 157,
"tag": "NAME",
"value": "Y"
},
{
"context": "me ReflectSample\n * @Description TODO\n * @Author Yunlong\n... | null | [] | package com.demo.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @ClassName ReflectSample
* @Description TODO
* @Author Yunlong
* @Date 2019/9/3 19:15
* @Version 1.0
*/
public class ReflectSample {
public static void main(String[] args) throws Exception {
Class rc = Class.forName("com.demo.reflect.Robot");
Robot r = (Robot) rc.newInstance();
// 获取类名
System.out.println("Class name is " + rc.getName());
// 获取私有方法
Method getHello = rc.getDeclaredMethod("sayHello", String.class);
getHello.setAccessible(true);
// 执行方法
getHello.invoke(r, "Bob");
// 获取公有方法
Method sayHi = rc.getMethod("sayHi");
// 获取成员变量
Field name = rc.getDeclaredField("name");
name.setAccessible(true);
// 给变量赋值
name.set(r, "Alice");
sayHi.invoke(r);
}
}
| 970 | 0.599119 | 0.585903 | 33 | 26.515152 | 18.630573 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 15 |
878157ec0f86d83289cd2a6a2f967392feaed8b7 | 28,716,151,361,484 | 6aedfbd825f73fc2d523a932231389583e2ee013 | /src/com/fireslug/gameutils/ColorScheme.java | 65beaae216f8b0ec9c0b82b08a3311946eadc5e3 | [] | no_license | fieryslug/Minesweeper | https://github.com/fieryslug/Minesweeper | bd8d7a5ffdf73c99640badee0bc00091d144dbca | 725f51fad00a5ea126a46a85892d48ca4c6e60d6 | refs/heads/master | 2020-03-20T17:26:21.592000 | 2018-06-16T11:34:56 | 2018-06-16T11:34:56 | 137,559,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fireslug.gameutils;
import java.awt.*;
public class ColorScheme {
public Color panelBackground;
public Color buttonBackground;
public Color buttonRestartBackground;
public Color gridBorder;
public Color gridBorderEx;
public Color gridDefault;
public Color gridZero;
public Color gridEx;
public Color gridLost;
public Color gridLostHighlight;
public Color gridWon;
public Color gridWonZero;
public Color textWonMine;
public Color textMine;
public Color textNum;
public Color textGuess;
public static ColorScheme scheme1 = new ColorScheme();
public static ColorScheme scheme2 = new ColorScheme();
static {
initSchemes();
}
public ColorScheme() {
}
public static void initSchemes() {
scheme1.panelBackground = new Color(0, 0, 0);
scheme1.buttonBackground = new Color(192, 91, 135);
scheme1.buttonRestartBackground = new Color(67, 169, 170);
scheme1.gridBorder = new Color(128, 128, 128);
scheme1.gridBorderEx = new Color(128, 128, 128);
scheme1.gridDefault = new Color(192, 192, 192);
scheme1.gridZero = new Color(25, 51, 14);
scheme1.gridEx = new Color(40, 88, 21);
scheme1.gridLost = new Color(95, 24, 70);
scheme1.gridLostHighlight = new Color(255, 0, 0);
scheme1.gridWon = new Color(66, 114, 151);
scheme1.gridWonZero = new Color(48, 69, 96);
scheme1.textWonMine = new Color(98, 187, 175);
scheme1.textMine = new Color(255, 255, 255);
scheme1.textNum = new Color(255, 255, 255);
scheme1.textGuess = new Color(161, 81, 41);
scheme2.panelBackground = new Color(0, 0, 0);
scheme2.buttonBackground = new Color(136, 39, 156);
scheme2.buttonRestartBackground = new Color(58, 39, 172);
scheme2.gridBorder = new Color(168, 106, 46);
scheme2.gridBorderEx = new Color(64, 70, 88);
scheme2.gridDefault = new Color(0, 0, 0);
scheme2.gridZero = new Color(46, 116, 117);
scheme2.gridEx = new Color(51, 129, 130);
scheme2.gridLost = new Color(53, 22, 56);
scheme2.gridLostHighlight = new Color(134, 173, 96);
scheme2.gridWon = new Color(70, 171, 36);
scheme2.gridWonZero = new Color(57, 141, 30);
scheme2.textWonMine = new Color(187, 145, 39);
scheme2.textMine = new Color(0, 0, 0);
scheme2.textNum = new Color(0, 0, 0);
scheme2.textGuess = new Color(214, 27, 243);
}
}
| UTF-8 | Java | 2,619 | java | ColorScheme.java | Java | [] | null | [] | package com.fireslug.gameutils;
import java.awt.*;
public class ColorScheme {
public Color panelBackground;
public Color buttonBackground;
public Color buttonRestartBackground;
public Color gridBorder;
public Color gridBorderEx;
public Color gridDefault;
public Color gridZero;
public Color gridEx;
public Color gridLost;
public Color gridLostHighlight;
public Color gridWon;
public Color gridWonZero;
public Color textWonMine;
public Color textMine;
public Color textNum;
public Color textGuess;
public static ColorScheme scheme1 = new ColorScheme();
public static ColorScheme scheme2 = new ColorScheme();
static {
initSchemes();
}
public ColorScheme() {
}
public static void initSchemes() {
scheme1.panelBackground = new Color(0, 0, 0);
scheme1.buttonBackground = new Color(192, 91, 135);
scheme1.buttonRestartBackground = new Color(67, 169, 170);
scheme1.gridBorder = new Color(128, 128, 128);
scheme1.gridBorderEx = new Color(128, 128, 128);
scheme1.gridDefault = new Color(192, 192, 192);
scheme1.gridZero = new Color(25, 51, 14);
scheme1.gridEx = new Color(40, 88, 21);
scheme1.gridLost = new Color(95, 24, 70);
scheme1.gridLostHighlight = new Color(255, 0, 0);
scheme1.gridWon = new Color(66, 114, 151);
scheme1.gridWonZero = new Color(48, 69, 96);
scheme1.textWonMine = new Color(98, 187, 175);
scheme1.textMine = new Color(255, 255, 255);
scheme1.textNum = new Color(255, 255, 255);
scheme1.textGuess = new Color(161, 81, 41);
scheme2.panelBackground = new Color(0, 0, 0);
scheme2.buttonBackground = new Color(136, 39, 156);
scheme2.buttonRestartBackground = new Color(58, 39, 172);
scheme2.gridBorder = new Color(168, 106, 46);
scheme2.gridBorderEx = new Color(64, 70, 88);
scheme2.gridDefault = new Color(0, 0, 0);
scheme2.gridZero = new Color(46, 116, 117);
scheme2.gridEx = new Color(51, 129, 130);
scheme2.gridLost = new Color(53, 22, 56);
scheme2.gridLostHighlight = new Color(134, 173, 96);
scheme2.gridWon = new Color(70, 171, 36);
scheme2.gridWonZero = new Color(57, 141, 30);
scheme2.textWonMine = new Color(187, 145, 39);
scheme2.textMine = new Color(0, 0, 0);
scheme2.textNum = new Color(0, 0, 0);
scheme2.textGuess = new Color(214, 27, 243);
}
}
| 2,619 | 0.618939 | 0.5231 | 76 | 32.460526 | 21.731277 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.539474 | false | false | 15 |
ab38970b2e68492a02089c422ab7744717b2eacd | 22,943,715,346,703 | 4cc7edd8298c58b463abd680cf7d88c76b904484 | /Code/src/designPatterns/TemplateMethod/HitAndRunMethod.java | 1c21842d6812ea1b6bc56586c06139a51e32cbc1 | [] | no_license | Passion-Logan/Summary | https://github.com/Passion-Logan/Summary | eee0ce88966ba59c88134bf57901993de4c2d3fd | cb63876b2afbc06b70b2c4fb6604269f29228de8 | refs/heads/master | 2021-10-27T07:14:22.337000 | 2021-10-21T09:42:38 | 2021-10-21T09:42:38 | 221,710,018 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package designPatterns.TemplateMethod;
/**
* 具体方法
*
* @author wql
* @desc HitAndRunMethod
* @date 2021/5/31
* @lastUpdateUser wql
* @lastUpdateDesc
* @lastUpdateTime 2021/5/31
*/
public class HitAndRunMethod extends StealingMethod {
@Override
protected String pickTarget() {
return "地精老妇人";
}
@Override
protected void confuseTarget(String target) {
System.out.println(String.format("从后面接近 %s.", target));
}
@Override
protected void stealTheItem(String target) {
System.out.println("拿起手提包,快速逃跑!");
}
}
| UTF-8 | Java | 625 | java | HitAndRunMethod.java | Java | [
{
"context": "atterns.TemplateMethod;\n\n/**\n * 具体方法\n *\n * @author wql\n * @desc HitAndRunMethod\n * @date 2021/5/31\n * @l",
"end": 69,
"score": 0.9996487498283386,
"start": 66,
"tag": "USERNAME",
"value": "wql"
},
{
"context": "AndRunMethod\n * @date 2021/5/31\n * @lastUpdateUse... | null | [] | package designPatterns.TemplateMethod;
/**
* 具体方法
*
* @author wql
* @desc HitAndRunMethod
* @date 2021/5/31
* @lastUpdateUser wql
* @lastUpdateDesc
* @lastUpdateTime 2021/5/31
*/
public class HitAndRunMethod extends StealingMethod {
@Override
protected String pickTarget() {
return "地精老妇人";
}
@Override
protected void confuseTarget(String target) {
System.out.println(String.format("从后面接近 %s.", target));
}
@Override
protected void stealTheItem(String target) {
System.out.println("拿起手提包,快速逃跑!");
}
}
| 625 | 0.655652 | 0.631304 | 30 | 18.166666 | 18.153206 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 15 |
570397ed2a7bcfe434cc5dbe9dcafbc6200fae8a | 1,958,505,138,209 | 83838e16a8aed067eba725af68c2cfd8f8008581 | /dal/src/main/java/com/zxg/zbc/dal/dao/ibatis/ZbcBillingRecordDAOImpl.java | 3157ee1471ae5e9f069dffc2a60248c06a9ca32a | [] | no_license | shenke119/zhaobaocai | https://github.com/shenke119/zhaobaocai | 79fcfef326db5cb52a56adc4e30ebe141ca92c6c | 56263c7fcc46c235086039eeca8326a33776be29 | refs/heads/master | 2017-11-29T23:59:20.604000 | 2017-02-06T07:46:34 | 2017-02-06T07:46:34 | 81,059,900 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zxg.zbc.dal.dao.ibatis;
import java.util.List;
import com.taobao.common.dao.persistence.DBRoute;
import com.taobao.common.dao.persistence.SqlMapBaseDAO;
import com.zxg.zbc.dal.dao.ZbcBillingRecordDAO;
import com.zxg.zbc.dal.dao.exception.DAOException;
import com.zxg.zbc.dal.dataobject.ZbcBillingRecord;
import com.zxg.zbc.dal.dataobject.ZbcBillingRecordExample;
public class ZbcBillingRecordDAOImpl extends SqlMapBaseDAO implements ZbcBillingRecordDAO {
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public ZbcBillingRecordDAOImpl() {
super();
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public Long insert(ZbcBillingRecord record) throws DAOException {
try {
Object newKey = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).insert("zbc_billing_record.abatorgenerated_insert", record);
return (Long) newKey;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByPrimaryKey(ZbcBillingRecord record) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).update("zbc_billing_record.abatorgenerated_updateByPrimaryKey",
record);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByPrimaryKeySelective(ZbcBillingRecord record) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.update("zbc_billing_record.abatorgenerated_updateByPrimaryKeySelective", record);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
@SuppressWarnings("unchecked")
public List<ZbcBillingRecord> selectByExample(ZbcBillingRecordExample example) throws DAOException {
try {
List<ZbcBillingRecord> list = (List<ZbcBillingRecord>) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForList("zbc_billing_record.abatorgenerated_selectByExample", example);
return list;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public ZbcBillingRecord selectByPrimaryKey(Long id) throws DAOException {
try {
ZbcBillingRecord key = new ZbcBillingRecord();
key.setId(id);
ZbcBillingRecord record = (ZbcBillingRecord) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForObject("zbc_billing_record.abatorgenerated_selectByPrimaryKey", key);
return record;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int deleteByExample(ZbcBillingRecordExample example) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).delete("zbc_billing_record.abatorgenerated_deleteByExample",
example);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int deleteByPrimaryKey(Long id) throws DAOException {
try {
ZbcBillingRecord key = new ZbcBillingRecord();
key.setId(id);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).delete("zbc_billing_record.abatorgenerated_deleteByPrimaryKey",
key);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int countByExample(ZbcBillingRecordExample example) throws DAOException {
try {
Integer count = (Integer) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForObject("zbc_billing_record.abatorgenerated_countByExample", example);
return count;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByExampleSelective(ZbcBillingRecord record, ZbcBillingRecordExample example) throws DAOException {
try {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.update("zbc_billing_record.abatorgenerated_updateByExampleSelective", parms);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByExample(ZbcBillingRecord record, ZbcBillingRecordExample example) throws DAOException {
try {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).update("zbc_billing_record.abatorgenerated_updateByExample", parms);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This class was generated by Abator for iBATIS. This class corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
private static class UpdateByExampleParms extends ZbcBillingRecordExample {
private Object record;
public UpdateByExampleParms(Object record, ZbcBillingRecordExample example) {
super(example);
this.record = record;
}
public Object getRecord() {
return record;
}
}
} | UTF-8 | Java | 7,355 | java | ZbcBillingRecordDAOImpl.java | Java | [] | null | [] | package com.zxg.zbc.dal.dao.ibatis;
import java.util.List;
import com.taobao.common.dao.persistence.DBRoute;
import com.taobao.common.dao.persistence.SqlMapBaseDAO;
import com.zxg.zbc.dal.dao.ZbcBillingRecordDAO;
import com.zxg.zbc.dal.dao.exception.DAOException;
import com.zxg.zbc.dal.dataobject.ZbcBillingRecord;
import com.zxg.zbc.dal.dataobject.ZbcBillingRecordExample;
public class ZbcBillingRecordDAOImpl extends SqlMapBaseDAO implements ZbcBillingRecordDAO {
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public ZbcBillingRecordDAOImpl() {
super();
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public Long insert(ZbcBillingRecord record) throws DAOException {
try {
Object newKey = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).insert("zbc_billing_record.abatorgenerated_insert", record);
return (Long) newKey;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByPrimaryKey(ZbcBillingRecord record) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).update("zbc_billing_record.abatorgenerated_updateByPrimaryKey",
record);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByPrimaryKeySelective(ZbcBillingRecord record) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.update("zbc_billing_record.abatorgenerated_updateByPrimaryKeySelective", record);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
@SuppressWarnings("unchecked")
public List<ZbcBillingRecord> selectByExample(ZbcBillingRecordExample example) throws DAOException {
try {
List<ZbcBillingRecord> list = (List<ZbcBillingRecord>) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForList("zbc_billing_record.abatorgenerated_selectByExample", example);
return list;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public ZbcBillingRecord selectByPrimaryKey(Long id) throws DAOException {
try {
ZbcBillingRecord key = new ZbcBillingRecord();
key.setId(id);
ZbcBillingRecord record = (ZbcBillingRecord) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForObject("zbc_billing_record.abatorgenerated_selectByPrimaryKey", key);
return record;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int deleteByExample(ZbcBillingRecordExample example) throws DAOException {
try {
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).delete("zbc_billing_record.abatorgenerated_deleteByExample",
example);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int deleteByPrimaryKey(Long id) throws DAOException {
try {
ZbcBillingRecord key = new ZbcBillingRecord();
key.setId(id);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).delete("zbc_billing_record.abatorgenerated_deleteByPrimaryKey",
key);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int countByExample(ZbcBillingRecordExample example) throws DAOException {
try {
Integer count = (Integer) this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.queryForObject("zbc_billing_record.abatorgenerated_countByExample", example);
return count;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByExampleSelective(ZbcBillingRecord record, ZbcBillingRecordExample example) throws DAOException {
try {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute())
.update("zbc_billing_record.abatorgenerated_updateByExampleSelective", parms);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This method was generated by Abator for iBATIS. This method corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
public int updateByExample(ZbcBillingRecord record, ZbcBillingRecordExample example) throws DAOException {
try {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = this.getSqlDaoBaseSupport().getSqlMapTemplate(DBRoute.getAssistantRoute()).update("zbc_billing_record.abatorgenerated_updateByExample", parms);
return rows;
} catch (Exception e) {
throw new DAOException(e.getMessage(), e);
}
}
/**
* This class was generated by Abator for iBATIS. This class corresponds to
* the database table zbc_billing_record
*
* @abatorgenerated Tue Jan 10 17:29:57 CST 2017
*/
private static class UpdateByExampleParms extends ZbcBillingRecordExample {
private Object record;
public UpdateByExampleParms(Object record, ZbcBillingRecordExample example) {
super(example);
this.record = record;
}
public Object getRecord() {
return record;
}
}
} | 7,355 | 0.709857 | 0.690279 | 207 | 34.536232 | 36.612045 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357488 | false | false | 15 |
76e24adec791bbe19b0f2453cf88420f60d7c422 | 14,740,327,820,438 | abf2d149e231a42ccdaf3b843ebed70385f6e5f6 | /src/main/java/com/luyongmin/task/demotask/node/AbstractMng.java | 3f8240c52d9dca8afa9d1296c382d8b78ab03695 | [] | no_license | luyongmin/tash | https://github.com/luyongmin/tash | e6b4adbf3091198b715ada9fd514acefe05a9fae | 2ed4a5af2c21352064c2320f905f78e1aae5508f | refs/heads/master | 2022-06-22T18:49:25.515000 | 2020-03-08T10:00:54 | 2020-03-08T10:00:54 | 245,418,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.luyongmin.task.demotask.node;
import com.luyongmin.task.demotask.constant.ErrorCode;
import com.luyongmin.task.demotask.domain.Task;
import com.luyongmin.task.demotask.domain.TaskNode;
import com.luyongmin.task.demotask.enums.TaskNodeStatus;
import com.luyongmin.task.demotask.enums.TaskStatus;
import com.luyongmin.task.demotask.excention.BizException;
import com.luyongmin.task.demotask.service.TaskNodeMngInf;
import com.luyongmin.task.demotask.service.TaskNodeService;
import com.luyongmin.task.demotask.service.TaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author: lu.yongmin
* @date: 2020/3/6 18:07
* @description:
*/
public abstract class AbstractMng implements TaskNodeMngInf {
/**
* 查询的每页数量
*/
@Value("#{jj}")
protected String QUERY_SIZE;
@Resource
public TaskService taskService;
@Resource
public TaskNodeService taskNodeService;
/**
* 验证节点是否可以执行
* @param taskNode
* @param settleDate
*/
@Override
public void validateExecute(TaskNode taskNode, String settleDate){
if(!StringUtils.isEmpty(taskNode.getFrontNode())){
List<Task> taskList = taskService.queryBySettleDate(settleDate);
List<String> succTaskList = new ArrayList<String>();
List<String> failTaskList = new ArrayList<String>();
convertTaskList(taskList,succTaskList,failTaskList);
List<String> succNodeList = new ArrayList<String>();
List<String> failNodeList = new ArrayList<String>();
convertNodeList(taskList,succNodeList,failNodeList);
String[] arr = taskNode.getFrontNode().split(",");
if(arr != null && arr.length>0){
for(String val : arr){
if(val.startsWith("TASK_")){
if(succTaskList.contains(val)){
continue;
}
if(failTaskList.contains(val)){
throw new BizException(ErrorCode.FRONT_TASK_FAIL,"前置任务处理失败");
}
}else{
if(succNodeList.contains(val)){
continue;
}
if(failNodeList.contains(val)){
throw new BizException(ErrorCode.FRONT_TASK_FAIL,"前置任务处理失败");
}
}
throw new BizException(ErrorCode.FRONT_TASK_UNCOMPLETE,"存在前置任务处理未完成");
}
}
}
}
private void convertTaskList(List<Task> taskList,List<String> succTaskList,List<String> failTaskList) {
if(taskList != null && taskList.size()>0){
for(Task task : taskList){
TaskStatus taskStatus = TaskStatus.getByCode(task.getStatus());
if(taskStatus == TaskStatus.SUCC){
succTaskList.add(task.getTaskCode());
continue;
}
if(taskStatus == TaskStatus.FAIL){
failTaskList.add(task.getTaskCode());
continue;
}
}
}
}
private void convertNodeList(List<Task> taskList,List<String> succNodeList,List<String> failNodeList) {
if(taskList != null && taskList.size()>0){
for(Task task : taskList){
List<TaskNode> taskNodeList = task.getTaskNodeList();
if(taskNodeList != null && taskNodeList.size()>0){
for(TaskNode taskNode : taskNodeList){
TaskNodeStatus status = TaskNodeStatus.getByCode(taskNode.getStatus());
if(status == TaskNodeStatus.SUCC){
succNodeList.add(taskNode.getNodeCode());
}
if(status == TaskNodeStatus.FAIL){
failNodeList.add(taskNode.getNodeCode());
}
}
}
}
}
}
}
| UTF-8 | Java | 4,332 | java | AbstractMng.java | Java | [
{
"context": "ArrayList;\nimport java.util.List;\n\n/**\n * @author: lu.yongmin\n * @date: 2020/3/6 18:07\n * @description:\n */\npub",
"end": 759,
"score": 0.7944742441177368,
"start": 749,
"tag": "NAME",
"value": "lu.yongmin"
}
] | null | [] | package com.luyongmin.task.demotask.node;
import com.luyongmin.task.demotask.constant.ErrorCode;
import com.luyongmin.task.demotask.domain.Task;
import com.luyongmin.task.demotask.domain.TaskNode;
import com.luyongmin.task.demotask.enums.TaskNodeStatus;
import com.luyongmin.task.demotask.enums.TaskStatus;
import com.luyongmin.task.demotask.excention.BizException;
import com.luyongmin.task.demotask.service.TaskNodeMngInf;
import com.luyongmin.task.demotask.service.TaskNodeService;
import com.luyongmin.task.demotask.service.TaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author: lu.yongmin
* @date: 2020/3/6 18:07
* @description:
*/
public abstract class AbstractMng implements TaskNodeMngInf {
/**
* 查询的每页数量
*/
@Value("#{jj}")
protected String QUERY_SIZE;
@Resource
public TaskService taskService;
@Resource
public TaskNodeService taskNodeService;
/**
* 验证节点是否可以执行
* @param taskNode
* @param settleDate
*/
@Override
public void validateExecute(TaskNode taskNode, String settleDate){
if(!StringUtils.isEmpty(taskNode.getFrontNode())){
List<Task> taskList = taskService.queryBySettleDate(settleDate);
List<String> succTaskList = new ArrayList<String>();
List<String> failTaskList = new ArrayList<String>();
convertTaskList(taskList,succTaskList,failTaskList);
List<String> succNodeList = new ArrayList<String>();
List<String> failNodeList = new ArrayList<String>();
convertNodeList(taskList,succNodeList,failNodeList);
String[] arr = taskNode.getFrontNode().split(",");
if(arr != null && arr.length>0){
for(String val : arr){
if(val.startsWith("TASK_")){
if(succTaskList.contains(val)){
continue;
}
if(failTaskList.contains(val)){
throw new BizException(ErrorCode.FRONT_TASK_FAIL,"前置任务处理失败");
}
}else{
if(succNodeList.contains(val)){
continue;
}
if(failNodeList.contains(val)){
throw new BizException(ErrorCode.FRONT_TASK_FAIL,"前置任务处理失败");
}
}
throw new BizException(ErrorCode.FRONT_TASK_UNCOMPLETE,"存在前置任务处理未完成");
}
}
}
}
private void convertTaskList(List<Task> taskList,List<String> succTaskList,List<String> failTaskList) {
if(taskList != null && taskList.size()>0){
for(Task task : taskList){
TaskStatus taskStatus = TaskStatus.getByCode(task.getStatus());
if(taskStatus == TaskStatus.SUCC){
succTaskList.add(task.getTaskCode());
continue;
}
if(taskStatus == TaskStatus.FAIL){
failTaskList.add(task.getTaskCode());
continue;
}
}
}
}
private void convertNodeList(List<Task> taskList,List<String> succNodeList,List<String> failNodeList) {
if(taskList != null && taskList.size()>0){
for(Task task : taskList){
List<TaskNode> taskNodeList = task.getTaskNodeList();
if(taskNodeList != null && taskNodeList.size()>0){
for(TaskNode taskNode : taskNodeList){
TaskNodeStatus status = TaskNodeStatus.getByCode(taskNode.getStatus());
if(status == TaskNodeStatus.SUCC){
succNodeList.add(taskNode.getNodeCode());
}
if(status == TaskNodeStatus.FAIL){
failNodeList.add(taskNode.getNodeCode());
}
}
}
}
}
}
}
| 4,332 | 0.561734 | 0.558435 | 130 | 31.646154 | 27.789833 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415385 | false | false | 15 |
11f5d704546191b0cf6a7712d61b64a7a3b3d989 | 1,992,864,876,461 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/arc082/B/4884668.java | 07c323a777d210faa2d0f6d1346e5ff60145e256 | [] | no_license | Kawser-nerd/CLCDSA | https://github.com/Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588000 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* @Author Silviase(@silviasetitech)
* For ProCon
*/
import java.util.*;
import java.lang.*;
import java.math.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] num = new int[n+1];
int ans = 0;
int tmp;
num[0] = 10000000;
for (int i = 1; i <= n; i++) {
num[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
if (i == n) {
if (num[i] == i) {
tmp = num[i];
num[i] = num[i-1];
num[i-1] = tmp;
ans++;
}
} else {
if (num[i] == i) {
tmp = num[i];
num[i] = num[i+1];
num[i+1] = tmp;
ans++;
}
}
}
System.out.println(ans);
sc.close();
}
} | UTF-8 | Java | 1,035 | java | 4884668.java | Java | [
{
"context": "/*\r\n* @Author Silviase(@silviasetitech)\r\n* For ProCon\r\n*/\r\n\r\nimport java",
"end": 22,
"score": 0.9998206496238708,
"start": 14,
"tag": "NAME",
"value": "Silviase"
},
{
"context": "/*\r\n* @Author Silviase(@silviasetitech)\r\n* For ProCon\r\n*/\r\n\r\nimport ja... | null | [] | /*
* @Author Silviase(@silviasetitech)
* For ProCon
*/
import java.util.*;
import java.lang.*;
import java.math.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] num = new int[n+1];
int ans = 0;
int tmp;
num[0] = 10000000;
for (int i = 1; i <= n; i++) {
num[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
if (i == n) {
if (num[i] == i) {
tmp = num[i];
num[i] = num[i-1];
num[i-1] = tmp;
ans++;
}
} else {
if (num[i] == i) {
tmp = num[i];
num[i] = num[i+1];
num[i+1] = tmp;
ans++;
}
}
}
System.out.println(ans);
sc.close();
}
} | 1,035 | 0.322705 | 0.30628 | 44 | 21.568182 | 13.422162 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 15 |
5cc84ab5d69c23046e3eab7420cf45ab6c65b475 | 8,220,567,453,411 | 2869004017993877b5d28182c7168c8631350c3d | /src/dataquery/CalendarDAO.java | 0ce7b2756a8f71df00e7592b4f1f3fbc6269f179 | [] | no_license | jw291/StackProject-JSP-Version | https://github.com/jw291/StackProject-JSP-Version | de0402230bff8a3263a7bc7bebd3f360ccef6a91 | a99694fdc07fea9e9b3e042edd4e1af04c32b8e2 | refs/heads/master | 2022-11-26T00:03:06.751000 | 2020-08-08T02:18:07 | 2020-08-08T02:18:07 | 285,955,635 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dataquery;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javabean.CalendarDataBean;
import javabean.FreeBoardDataBean;
public class CalendarDAO {
private CalendarDAO() {
}
private static CalendarDAO instance = new CalendarDAO();
public static CalendarDAO getInstance(){
return instance;
}
// insert
public int insert(Connection conn, CalendarDataBean CD) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "insert into tbl_events values (?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, CD.getId());
pstmt.setString(2, CD.getTitle());
pstmt.setString(3, CD.getStart());
pstmt.setString(4, CD.getEnd());
pstmt.setString(5, CD.getThreadname());
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// edit
public int edit(Connection conn, CalendarDataBean CD) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "UPDATE tbl_events SET title = ?, start=?,end=? where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,CD.getTitle());
pstmt.setString(2, CD.getStart());
pstmt.setString(3, CD.getEnd());
pstmt.setInt(4, CD.getId());
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// delete
public int delete(Connection conn, int id) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "delete from tbl_events where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
public CalendarDataBean createFromResultSet(ResultSet rs) throws SQLException {
int id = rs.getInt("id");
String title = rs.getString("title");
String start = rs.getString("start");
String end = rs.getString("end");
String threadname = rs.getString("threadname");
CalendarDataBean pe = new CalendarDataBean(id, title, start, end,threadname);
return pe;
}
// selectList
public List<CalendarDataBean> selectList(Connection conn,String threadname) throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "select * from tbl_events where threadname='"+threadname+"'";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<CalendarDataBean> pList = new ArrayList<>();
while (rs.next()) {
pList.add(createFromResultSet(rs));
}
return pList;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
}
}
| UTF-8 | Java | 2,787 | java | CalendarDAO.java | Java | [] | null | [] | package dataquery;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javabean.CalendarDataBean;
import javabean.FreeBoardDataBean;
public class CalendarDAO {
private CalendarDAO() {
}
private static CalendarDAO instance = new CalendarDAO();
public static CalendarDAO getInstance(){
return instance;
}
// insert
public int insert(Connection conn, CalendarDataBean CD) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "insert into tbl_events values (?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, CD.getId());
pstmt.setString(2, CD.getTitle());
pstmt.setString(3, CD.getStart());
pstmt.setString(4, CD.getEnd());
pstmt.setString(5, CD.getThreadname());
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// edit
public int edit(Connection conn, CalendarDataBean CD) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "UPDATE tbl_events SET title = ?, start=?,end=? where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,CD.getTitle());
pstmt.setString(2, CD.getStart());
pstmt.setString(3, CD.getEnd());
pstmt.setInt(4, CD.getId());
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// delete
public int delete(Connection conn, int id) throws SQLException {
PreparedStatement pstmt = null;
try {
String sql = "delete from tbl_events where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
return pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
public CalendarDataBean createFromResultSet(ResultSet rs) throws SQLException {
int id = rs.getInt("id");
String title = rs.getString("title");
String start = rs.getString("start");
String end = rs.getString("end");
String threadname = rs.getString("threadname");
CalendarDataBean pe = new CalendarDataBean(id, title, start, end,threadname);
return pe;
}
// selectList
public List<CalendarDataBean> selectList(Connection conn,String threadname) throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "select * from tbl_events where threadname='"+threadname+"'";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<CalendarDataBean> pList = new ArrayList<>();
while (rs.next()) {
pList.add(createFromResultSet(rs));
}
return pList;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
}
}
| 2,787 | 0.672408 | 0.66882 | 109 | 24.568808 | 21.420374 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.752294 | false | false | 15 |
59b6011bcfe6ad30c43ce44e89bbf49e14864df3 | 15,479,062,190,557 | 86936a85e2c3506d31e5fb258b06cd44f51c1331 | /term 1/Combinatory/Combinatorics25.java | b7c71ea99cbe4d860c00a973d71e83e704b2cd10 | [] | no_license | hftmmiterNune09/itmo-dm-labs | https://github.com/hftmmiterNune09/itmo-dm-labs | db93482aeda30c1332d7f3c8a92ed55a3f09c1ab | 09dc19b0629e62934ced656b252d4c67d6f55027 | refs/heads/master | 2023-06-06T02:49:19.458000 | 2020-02-04T02:46:27 | 2020-02-04T02:46:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.itmo.chizhikov;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Combinatorics25 {
static int[] nextCombination(int[] a, int n, int k) {
int b[] = new int[n];
for (int i = 0; i < k; i++) {
b[i] = a[i];
}
if (n != k) {
b[k] = n + 1;
int ind = k - 1;
while (ind >= 0 && b[ind + 1] - b[ind] < 2) {
ind--;
}
if (ind >= 0) {
b[ind]++;
for (int j = ind + 1; j < k; j++) {
b[j] = b[j - 1] + 1;
}
for (int i = 0; i < k; i++) {
a[i] = b[i];
}
return a;
} else return null;
} else return null;
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("nextchoose.in"));
FileWriter fileWriter = new FileWriter(new File("nextchoose.out"));
int n = scanner.nextInt();
int k = scanner.nextInt();
int a[] = new int[k];
for (int i = 0; i < k; i++) a[i] = scanner.nextInt();
int b[] = nextCombination(a, n, k);
if (b != null) {
for (int i = 0; i < k; i++) {
fileWriter.write(b[i] + " ");
}
} else {
fileWriter.write("-1");
}
fileWriter.flush();
}
}
| UTF-8 | Java | 1,489 | java | Combinatorics25.java | Java | [] | null | [] | package ru.itmo.chizhikov;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Combinatorics25 {
static int[] nextCombination(int[] a, int n, int k) {
int b[] = new int[n];
for (int i = 0; i < k; i++) {
b[i] = a[i];
}
if (n != k) {
b[k] = n + 1;
int ind = k - 1;
while (ind >= 0 && b[ind + 1] - b[ind] < 2) {
ind--;
}
if (ind >= 0) {
b[ind]++;
for (int j = ind + 1; j < k; j++) {
b[j] = b[j - 1] + 1;
}
for (int i = 0; i < k; i++) {
a[i] = b[i];
}
return a;
} else return null;
} else return null;
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("nextchoose.in"));
FileWriter fileWriter = new FileWriter(new File("nextchoose.out"));
int n = scanner.nextInt();
int k = scanner.nextInt();
int a[] = new int[k];
for (int i = 0; i < k; i++) a[i] = scanner.nextInt();
int b[] = nextCombination(a, n, k);
if (b != null) {
for (int i = 0; i < k; i++) {
fileWriter.write(b[i] + " ");
}
} else {
fileWriter.write("-1");
}
fileWriter.flush();
}
}
| 1,489 | 0.415715 | 0.40497 | 51 | 28.196079 | 17.800661 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.784314 | false | false | 15 |
8b561d9f103baea14c15a75e7917fb5fe3600b97 | 27,066,883,902,316 | 71975999c9d702a0883ec9038ce3e76325928549 | /src2.4.0/src/main/java/cn/jpush/android/service/TagAliasReceiver.java | 67d55c2fe32153fe3a5c87193cb184316c9c49fe | [] | no_license | XposedRunner/PhysicalFitnessRunner | https://github.com/XposedRunner/PhysicalFitnessRunner | dc64179551ccd219979a6f8b9fe0614c29cd61de | cb037e59416d6c290debbed5ed84c956e705e738 | refs/heads/master | 2020-07-15T18:18:23.001000 | 2019-09-02T04:21:34 | 2019-09-02T04:21:34 | 205,620,387 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.jpush.android.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import cn.jpush.android.d.f;
public class TagAliasReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent == null) {
f.c("TagAliasReceiver", "TagAliasOperator onReceive intent is null");
return;
}
long longExtra = intent.getLongExtra("tagalias_seqid", -1);
int intExtra = intent.getIntExtra("tagalias_errorcode", 0);
if (longExtra != -1) {
f.a().a(context.getApplicationContext(), longExtra, intExtra, intent);
}
}
}
| UTF-8 | Java | 718 | java | TagAliasReceiver.java | Java | [] | null | [] | package cn.jpush.android.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import cn.jpush.android.d.f;
public class TagAliasReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent == null) {
f.c("TagAliasReceiver", "TagAliasOperator onReceive intent is null");
return;
}
long longExtra = intent.getLongExtra("tagalias_seqid", -1);
int intExtra = intent.getIntExtra("tagalias_errorcode", 0);
if (longExtra != -1) {
f.a().a(context.getApplicationContext(), longExtra, intExtra, intent);
}
}
}
| 718 | 0.649025 | 0.644847 | 20 | 33.900002 | 26.185682 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.85 | false | false | 15 |
efcea959fb66b48e54fcefc35a38638739196b92 | 1,099,511,647,558 | 71975999c9d702a0883ec9038ce3e76325928549 | /src2.4.0/src/main/java/com/autonavi/ae/gmap/glanimation/AdglAnimation1V.java | 54dbf1fadd5b11b0108042fbebc8a8e90ade9b3b | [] | no_license | XposedRunner/PhysicalFitnessRunner | https://github.com/XposedRunner/PhysicalFitnessRunner | dc64179551ccd219979a6f8b9fe0614c29cd61de | cb037e59416d6c290debbed5ed84c956e705e738 | refs/heads/master | 2020-07-15T18:18:23.001000 | 2019-09-02T04:21:34 | 2019-09-02T04:21:34 | 205,620,387 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.autonavi.ae.gmap.glanimation;
import android.os.SystemClock;
public class AdglAnimation1V extends AbstractAdglAnimation {
private float curValue;
private AbstractAdglAnimationParam1V v1Param = null;
public AdglAnimation1V(int i) {
reset();
this.duration = i;
this.curValue = 0.0f;
}
public void doAnimation(Object obj) {
if (!this.isOver) {
this.offsetTime = SystemClock.uptimeMillis() - this.startTime;
float f = ((float) this.offsetTime) / ((float) this.duration);
if (f > 1.0f) {
this.isOver = true;
f = 1.0f;
} else if (f < 0.0f) {
this.isOver = true;
return;
}
if (this.v1Param != null) {
this.v1Param.setNormalizedTime(f);
this.curValue = this.v1Param.getCurValue();
}
}
}
public float getCurValue() {
return this.curValue;
}
public float getEndValue() {
return this.v1Param != null ? this.v1Param.getToValue() : 0.0f;
}
public float getStartValue() {
return this.v1Param != null ? this.v1Param.getFromValue() : 0.0f;
}
public void reset() {
this.isOver = false;
this.duration = 0;
if (this.v1Param != null) {
this.v1Param.reset();
}
}
public void setAnimationValue(float f, float f2, int i) {
if (this.v1Param == null) {
this.v1Param = new AbstractAdglAnimationParam1V();
}
this.v1Param.reset();
this.v1Param.setInterpolatorType(i, 1.0f);
this.v1Param.setFromValue(f);
this.v1Param.setToValue(f2);
this.startTime = SystemClock.uptimeMillis();
this.isOver = false;
}
}
| UTF-8 | Java | 1,888 | java | AdglAnimation1V.java | Java | [] | null | [] | package com.autonavi.ae.gmap.glanimation;
import android.os.SystemClock;
public class AdglAnimation1V extends AbstractAdglAnimation {
private float curValue;
private AbstractAdglAnimationParam1V v1Param = null;
public AdglAnimation1V(int i) {
reset();
this.duration = i;
this.curValue = 0.0f;
}
public void doAnimation(Object obj) {
if (!this.isOver) {
this.offsetTime = SystemClock.uptimeMillis() - this.startTime;
float f = ((float) this.offsetTime) / ((float) this.duration);
if (f > 1.0f) {
this.isOver = true;
f = 1.0f;
} else if (f < 0.0f) {
this.isOver = true;
return;
}
if (this.v1Param != null) {
this.v1Param.setNormalizedTime(f);
this.curValue = this.v1Param.getCurValue();
}
}
}
public float getCurValue() {
return this.curValue;
}
public float getEndValue() {
return this.v1Param != null ? this.v1Param.getToValue() : 0.0f;
}
public float getStartValue() {
return this.v1Param != null ? this.v1Param.getFromValue() : 0.0f;
}
public void reset() {
this.isOver = false;
this.duration = 0;
if (this.v1Param != null) {
this.v1Param.reset();
}
}
public void setAnimationValue(float f, float f2, int i) {
if (this.v1Param == null) {
this.v1Param = new AbstractAdglAnimationParam1V();
}
this.v1Param.reset();
this.v1Param.setInterpolatorType(i, 1.0f);
this.v1Param.setFromValue(f);
this.v1Param.setToValue(f2);
this.startTime = SystemClock.uptimeMillis();
this.isOver = false;
}
}
| 1,888 | 0.536017 | 0.516419 | 64 | 27.5 | 21.232346 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484375 | false | false | 15 |
3e512ef0e8a36d451d620cd0eed022f83eb92d01 | 12,506,944,780,562 | 0933cd88d2de6c4a46f6945700f0acd0d7899983 | /src/com/lineadecodigo/java/basico/ObtenerPrimerDigitoDeUnNumero.java | 3bab476fa97db66de3be6348a71f78917fd6bd09 | [] | no_license | victorcuervo/lineadecodigo_java | https://github.com/victorcuervo/lineadecodigo_java | 2f08d57938e5ab59a42d05cf87c7a122f5c15aea | 31f48c8d0a6332b4adf6fc240b70562acfb1bcc3 | refs/heads/master | 2023-06-24T18:10:42.443000 | 2023-06-20T21:44:58 | 2023-06-20T21:44:58 | 35,690,886 | 20 | 21 | null | false | 2022-12-05T23:30:26 | 2015-05-15T18:48:53 | 2022-11-01T04:45:42 | 2022-12-05T23:30:25 | 472 | 13 | 13 | 11 | Java | false | false | package com.lineadecodigo.java.basico;
import java.util.Scanner;
/**
* @file ObtenerPrimerDigitoDeUnNumero.java
* @version 1.0
* @author Víctor Cuervo (http://lineadecodigo.com)
* @date 10/enero/2009
* @url http://lineadecodigo.com/2009/01/12/primer-digito-de-un-numero-con-java/
* @description Solicitar un número por consola y devolver el primer dígito.
*/
public class ObtenerPrimerDigitoDeUnNumero {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int iNumero, iTamanioNumero,iDesplazamiento;
String sNumero;
System.out.println("Introduce un número por pantalla: ");
sNumero = reader.next();
iTamanioNumero = sNumero.length();
iNumero = Integer.parseInt(sNumero);
iDesplazamiento = Double.valueOf(Math.pow(10, iTamanioNumero-1)).intValue();
System.out.println("El primer dígito del número " + iNumero + " es el " + iNumero/iDesplazamiento);
System.out.println(iDesplazamiento);
reader.close();
}
}
| UTF-8 | Java | 998 | java | ObtenerPrimerDigitoDeUnNumero.java | Java | [
{
"context": "erDigitoDeUnNumero.java\n * @version 1.0\n * @author Víctor Cuervo (http://lineadecodigo.com)\n * @date 10/enero/200",
"end": 155,
"score": 0.9998819828033447,
"start": 142,
"tag": "NAME",
"value": "Víctor Cuervo"
}
] | null | [] | package com.lineadecodigo.java.basico;
import java.util.Scanner;
/**
* @file ObtenerPrimerDigitoDeUnNumero.java
* @version 1.0
* @author <NAME> (http://lineadecodigo.com)
* @date 10/enero/2009
* @url http://lineadecodigo.com/2009/01/12/primer-digito-de-un-numero-con-java/
* @description Solicitar un número por consola y devolver el primer dígito.
*/
public class ObtenerPrimerDigitoDeUnNumero {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int iNumero, iTamanioNumero,iDesplazamiento;
String sNumero;
System.out.println("Introduce un número por pantalla: ");
sNumero = reader.next();
iTamanioNumero = sNumero.length();
iNumero = Integer.parseInt(sNumero);
iDesplazamiento = Double.valueOf(Math.pow(10, iTamanioNumero-1)).intValue();
System.out.println("El primer dígito del número " + iNumero + " es el " + iNumero/iDesplazamiento);
System.out.println(iDesplazamiento);
reader.close();
}
}
| 990 | 0.72379 | 0.704637 | 36 | 26.555555 | 27.529221 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.388889 | false | false | 15 |
bb6c013311a963599d1851ff2f189aac40b857f5 | 1,047,972,063,182 | 58a5765bdef44025d054c9db009fdcd0212047a9 | /Community/src/com/community/dao/GoodDao.java | fbcfd3bc9bd3bbb1e6bce5aa02d63fe844c39e7d | [] | no_license | HelloProgrammer/MyGitRepository | https://github.com/HelloProgrammer/MyGitRepository | 3aeb211fee6037aa46d6b5e7361935faaca2cbc1 | ae84d4018d3f094b705a4c220c712ac4bf791573 | refs/heads/master | 2016-09-06T11:12:59.889000 | 2015-06-29T13:05:07 | 2015-06-29T13:08:29 | 35,249,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.community.dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import com.community.model.Good;
import com.community.model.OrderGood;
public interface GoodDao {
public void addGood(Good good);
public List<Good> getAllGood();
public List<Good> getAllGoodBySaleNum();
public Good getOneGood(String goodId);
public void deleteGood(Good good);
public void deleteGood(String id);
public void updateGood(Good good)throws HibernateException, SQLException ;
public List<Good> findGoodById(Good good);
public void modifyGoodNum(OrderGood orderGood);
public List<Good> getGoodsByKindId(String kindId);
public List<Good> showAllGoodDesc();
public List<Good> showAllGoodAsc();
}
| UTF-8 | Java | 743 | java | GoodDao.java | Java | [] | null | [] | package com.community.dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import com.community.model.Good;
import com.community.model.OrderGood;
public interface GoodDao {
public void addGood(Good good);
public List<Good> getAllGood();
public List<Good> getAllGoodBySaleNum();
public Good getOneGood(String goodId);
public void deleteGood(Good good);
public void deleteGood(String id);
public void updateGood(Good good)throws HibernateException, SQLException ;
public List<Good> findGoodById(Good good);
public void modifyGoodNum(OrderGood orderGood);
public List<Good> getGoodsByKindId(String kindId);
public List<Good> showAllGoodDesc();
public List<Good> showAllGoodAsc();
}
| 743 | 0.794078 | 0.794078 | 25 | 28.719999 | 18.756374 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.28 | false | false | 15 |
f8a2fe7caed46b09c1347987d0d1373a13ac99fe | 1,262,720,403,192 | fb5d99cc10f7b1ad11c5c7770ed4109e0f6fb142 | /mySpringMvc2Prac01/src/main/java/com/spring/boardPrac01/dao/BoardDAO.java | 3ca2d37ef9f1bb977424372df278bfc49c6f84b5 | [] | no_license | lhe2010/mySpringMvc2Prac01 | https://github.com/lhe2010/mySpringMvc2Prac01 | c69afa5b132c824d8834f0aa1947e3646376764f | b8c0eab42e1633e013da4fefe15c33cb0c2760fc | refs/heads/master | 2023-03-03T21:52:56.065000 | 2021-02-14T07:05:13 | 2021-02-14T07:05:13 | 333,699,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spring.boardPrac01.dao;
import java.util.List;
import com.spring.boardPrac01.dto.BoardDTO;
public interface BoardDAO {
public List<BoardDTO> getAllBoard() throws Exception;
}
| UTF-8 | Java | 202 | java | BoardDAO.java | Java | [] | null | [] | package com.spring.boardPrac01.dao;
import java.util.List;
import com.spring.boardPrac01.dto.BoardDTO;
public interface BoardDAO {
public List<BoardDTO> getAllBoard() throws Exception;
}
| 202 | 0.752475 | 0.732673 | 10 | 18.200001 | 19.727139 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
25757dff57a0cfd77ad79bf8cbdcdbb71b990cb8 | 20,822,001,461,340 | e74e0001a024e69a0721743925fed54fe66ee420 | /eclipse-workspace_JAVA/Day_0416/src/binary/MemberSearch.java | abfb19a1769f26801441325c614b343f1b7ae205 | [] | no_license | JeongDalim/JAVA | https://github.com/JeongDalim/JAVA | 8612dd45b09956433f8f26cbdb9fb0d470741cca | e23bf419f9df75e3b603c888496d76b4e96666c3 | refs/heads/master | 2021-05-21T04:15:57.738000 | 2020-04-02T18:49:32 | 2020-04-02T18:49:32 | 252,537,830 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package binary;
import java.util.Scanner;
public class MemberSearch {
public static void main(String[] args) {
MemberData md = new MemberData();
md.print();
Scanner scn = new Scanner(System.in);
System.out.print("Member 검색:");
int sNO = scn.nextInt();
String name = scn.next();
int age = scn.nextInt();
Member member = new Member(sNO, name, age);
Member mem = md.binarySearch(member);
if (mem != null) {
System.out.print(md.binarySearch(member).getsNO() + "\t");
System.out.print(md.binarySearch(member).getName() + "\t");
System.out.print(md.binarySearch(member).getAge() + "\t");
scn.close();
} else {
System.out.println("존재하지 않습니다.");
}
}
}
| UHC | Java | 707 | java | MemberSearch.java | Java | [] | null | [] | package binary;
import java.util.Scanner;
public class MemberSearch {
public static void main(String[] args) {
MemberData md = new MemberData();
md.print();
Scanner scn = new Scanner(System.in);
System.out.print("Member 검색:");
int sNO = scn.nextInt();
String name = scn.next();
int age = scn.nextInt();
Member member = new Member(sNO, name, age);
Member mem = md.binarySearch(member);
if (mem != null) {
System.out.print(md.binarySearch(member).getsNO() + "\t");
System.out.print(md.binarySearch(member).getName() + "\t");
System.out.print(md.binarySearch(member).getAge() + "\t");
scn.close();
} else {
System.out.println("존재하지 않습니다.");
}
}
}
| 707 | 0.650655 | 0.650655 | 25 | 26.48 | 18.635708 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.36 | false | false | 15 |
d734d809f2b61902efb4d89b80c7a1328659800a | 30,614,526,893,514 | 395f9248749114b94d4845c38112da7fdb9ef716 | /SensorServer/src/main/java/model/StatusManager.java | 9d136a4ca4280eecde57bef9839b321d56e93f1e | [] | no_license | ancadiana23/SensorWatch | https://github.com/ancadiana23/SensorWatch | 0038a602c9f8c43a77814e1c47df7141dad71b70 | bd3785d3c0c878e3cd16bf553030607040abaf36 | refs/heads/master | 2020-02-13T21:54:01.007000 | 2017-06-05T14:30:59 | 2017-06-05T14:30:59 | 86,235,144 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class StatusManager
{
private static HashMap<String, StatusManager> statusManagers;
protected String sensorName;
protected ArrayList<Status> statuses;
protected int storeOffset = 0;
public StatusManager() {}
public static void init() {
statusManagers = new HashMap<>();
statusManagers.put("battery", BatteryStatusManager.getInstance());
statusManagers.put("wifi", WiFiStatusManager.getInstance());
loadItems();
}
public static ArrayList<Status> get(String sensor) {
return statusManagers.get(sensor).getStatuses();
}
public static StatusManager getManager(String sensor) {
return statusManagers.get(sensor);
}
public static void storeItems()
{
for (StatusManager manager : statusManagers.values())
{
manager.store();
}
}
public static void addItemsFromString (String data, String sensor) {
statusManagers.get(sensor).loadFromString(data);
}
public static void loadItems()
{
for (StatusManager manager : statusManagers.values())
{
manager.load();
}
}
public ArrayList<Status> getStatuses()
{
return statuses;
}
public void loadFromString(String data) {
String[] instances = data.split(";");
for (String line : instances) {
statuses.add(instantiateFromCSV(line));
}
}
public Status instantiateFromCSV(String csv)
{
return null;
}
public void store()
{
FileWriter fw = null;
BufferedWriter bw = null;
String fileName = sensorName + ".csv";
try
{
File file = new File(fileName);
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
for (int i = storeOffset; i < statuses.size(); i++)
{
bw.write(statuses.get(i).toCSV() + "\n");
}
bw.flush();
}
catch(IOException e)
{
System.out.println("Store");
System.out.println(e.toString());
}
finally
{
try
{
if (fw != null) { fw.close(); }
if (bw != null) { bw.close(); }
}
catch (IOException e)
{
System.out.println("Store close");
System.out.println(e.toString());
}
}
}
public void load()
{
FileReader fr = null;
BufferedReader br = null;
String fileName = "store/" + sensorName + ".csv";
try
{
File file = new File(fileName);
fr = new FileReader(file);
br = new BufferedReader(fr);
String line = br.readLine();
while (line != null)
{
System.out.println(line);
statuses.add(instantiateFromCSV(line));
line = br.readLine();
}
storeOffset = statuses.size();
}
catch(Exception e)
{
System.out.println("Load" + e.toString());
}
finally
{
try
{
if (fr != null) { fr.close(); }
if (br != null) { br.close(); }
}
catch (IOException e)
{
System.out.println("Load end");
System.out.println(e.toString());
}
}
}
}
| UTF-8 | Java | 3,790 | java | StatusManager.java | Java | [] | null | [] | package model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class StatusManager
{
private static HashMap<String, StatusManager> statusManagers;
protected String sensorName;
protected ArrayList<Status> statuses;
protected int storeOffset = 0;
public StatusManager() {}
public static void init() {
statusManagers = new HashMap<>();
statusManagers.put("battery", BatteryStatusManager.getInstance());
statusManagers.put("wifi", WiFiStatusManager.getInstance());
loadItems();
}
public static ArrayList<Status> get(String sensor) {
return statusManagers.get(sensor).getStatuses();
}
public static StatusManager getManager(String sensor) {
return statusManagers.get(sensor);
}
public static void storeItems()
{
for (StatusManager manager : statusManagers.values())
{
manager.store();
}
}
public static void addItemsFromString (String data, String sensor) {
statusManagers.get(sensor).loadFromString(data);
}
public static void loadItems()
{
for (StatusManager manager : statusManagers.values())
{
manager.load();
}
}
public ArrayList<Status> getStatuses()
{
return statuses;
}
public void loadFromString(String data) {
String[] instances = data.split(";");
for (String line : instances) {
statuses.add(instantiateFromCSV(line));
}
}
public Status instantiateFromCSV(String csv)
{
return null;
}
public void store()
{
FileWriter fw = null;
BufferedWriter bw = null;
String fileName = sensorName + ".csv";
try
{
File file = new File(fileName);
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
for (int i = storeOffset; i < statuses.size(); i++)
{
bw.write(statuses.get(i).toCSV() + "\n");
}
bw.flush();
}
catch(IOException e)
{
System.out.println("Store");
System.out.println(e.toString());
}
finally
{
try
{
if (fw != null) { fw.close(); }
if (bw != null) { bw.close(); }
}
catch (IOException e)
{
System.out.println("Store close");
System.out.println(e.toString());
}
}
}
public void load()
{
FileReader fr = null;
BufferedReader br = null;
String fileName = "store/" + sensorName + ".csv";
try
{
File file = new File(fileName);
fr = new FileReader(file);
br = new BufferedReader(fr);
String line = br.readLine();
while (line != null)
{
System.out.println(line);
statuses.add(instantiateFromCSV(line));
line = br.readLine();
}
storeOffset = statuses.size();
}
catch(Exception e)
{
System.out.println("Load" + e.toString());
}
finally
{
try
{
if (fr != null) { fr.close(); }
if (br != null) { br.close(); }
}
catch (IOException e)
{
System.out.println("Load end");
System.out.println(e.toString());
}
}
}
}
| 3,790 | 0.514776 | 0.514512 | 158 | 22.987341 | 19.799625 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405063 | false | false | 15 |
db1cb4203d4c8f18b0b0c1d1713012a4aa23901d | 28,166,395,542,424 | 473942c7a2a7c59dd5a905eb6a72fe0396972877 | /JavaLab4Kushnir/src/Main.java | 0de590abe8c07c8eb9d8bae18a7270d14240a798 | [] | no_license | MishanyaKush/Lb4 | https://github.com/MishanyaKush/Lb4 | 4bc50ae822d68279261e2a0d12f7f702271d9011 | 3bd7d5d72853dfa3cbce25d12c318f2a4b35dc55 | refs/heads/main | 2023-06-02T09:53:01.065000 | 2021-06-11T06:08:25 | 2021-06-11T06:08:25 | 375,916,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.lang.model.element.NestingKind;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
public class Main {
static Scanner scanner = new Scanner(System.in);
static String fileName = "file.txt";
static int indexList = 1;
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
abstract static class Shop {
String name;
String address;
abstract void allBuyers();
abstract void minBuyers();
abstract void commentWithWord();
}
public static class Time extends Shop {
int buyers;
String comment;
@Override
public void allBuyers() {
int all = 0;
for(Time tmp : timeInfo)
{
all+= tmp.buyers;
}
System.out.println("Загальна к-сть покупців: " + all);
}
@Override
public void minBuyers() {
Time min = timeInfo.get(0);
for(Time tmp : timeInfo)
{
if(min.buyers > tmp.buyers) min = tmp;
}
System.out.println("Мінімальна к-сть покупців: " + min.buyers);
}
@Override
public void commentWithWord() {
String word;
System.out.println("Введіть слово: ");
word = scanner.nextLine();
for(Time tmp : timeInfo)
{
if(tmp.comment.contains(word)) {
System.out.println("Коментар який містить слово: " + tmp.comment);
}
}
}
public void AddNewData() {
try {
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
System.out.print("Введіть назву: ");
name = scanner.nextLine();
System.out.print("Введіть адрес: ");
address = scanner.nextLine();
System.out.print("Введіть к-сть покупців: ");
buyers = scanner.nextInt();
System.out.print("Введіть коментар: ");
comment = scanner.nextLine();
comment = scanner.nextLine();
dos.writeUTF(name);
dos.writeUTF(address);
dos.write(buyers);
dos.writeUTF(comment);
dos.close();
timeInfo.add(this);
} catch (IOException e) {
System.out.println("Error");
}
}
public void EditData() {
byte lineIndex;
do {
do {
System.out.print("Введіть поле дял редагування\n(1.Назва | 2.Адрес | 3.К-сть покупців | 4.Коментар)\n(5.Назад в меню)\nВведіть індекс:");
lineIndex = scanner.nextByte();
} while (lineIndex < 1 || lineIndex > 6);
switch (lineIndex) {
case 1: {
System.out.print("Введіть прізвище: ");
name = scanner.nextLine();
name = scanner.nextLine();
}
case 2: {
System.out.print("Введіть адрес: ");
address = scanner.nextLine();
address = scanner.nextLine();
}
break;
case 3: {
System.out.print("Введіть к-сть покупців: ");
buyers = scanner.nextByte();
}
break;
case 4: {
System.out.print("Введіть коментар: ");
comment = scanner.nextLine();
comment = scanner.nextLine();
}
break;
}
} while (lineIndex != 5);
try {
FileOutputStream tmpfos = new FileOutputStream(fileName);
DataOutputStream tmpdos = new DataOutputStream(tmpfos);
tmpdos.close();
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
for (Time tmpVisit : timeInfo) {
dos.writeUTF(tmpVisit.name);
dos.writeUTF(tmpVisit.address);
dos.write(tmpVisit.buyers);
dos.writeUTF(tmpVisit.comment);
}
dos.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public void Show() {
System.out.println("Назва: " + name + " | Адрес: " + address + " | К-сть покупців: " + buyers + " |\n Коментар: " + comment);
}
}
static ArrayList<Time> timeInfo = new ArrayList<Time>();
static void LoadFromFile() {
timeInfo.clear();
try {
FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis);
Time temp;
while (dis.available() > 0) {
temp = new Time();
temp.name = dis.readUTF();
temp.address = dis.readUTF();
temp.buyers = dis.read();
temp.comment = dis.readUTF();
timeInfo.add(temp);
}
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String enterkey;
LoadFromFile();
try {
do {
System.out.println("Введіть:\n 'р' - редагувати,\n 'а' - додати,\n 'в' - вивід,\n 'с' - Загальна кількість покупців,\n 'м' - година з найменшою кількістю покупців,\n 'н' - коментарями з певними словами,\n 'д' - вилучення,\n 'е' - вихід");
enterkey = reader.readLine();
Time temp = new Time();
switch (enterkey.charAt(0)) {
case 'р': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
byte index;
do {
System.out.print("Введіть індекс(" + "from 1 to " + timeInfo.size() + "):");
index = scanner.nextByte();
} while (index < 1 || index > timeInfo.size());
timeInfo.get(index - 1).EditData();
}
break;
case 'в': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайте дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
}
break;
case 'а':
temp.AddNewData();
break;
case 'с': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).allBuyers();
}
}
break;
case 'н': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).commentWithWord();
}
}
break;
case 'м': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).minBuyers();
}
}
break;
case 'д': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
byte index;
do {
System.out.print("Введіть індекс (" + "from 1 to " + timeInfo.size() + "):");
index = scanner.nextByte();
} while (index < 1 || index > timeInfo.size());
timeInfo.remove(index - 1);
try {
FileOutputStream tmpfos = new FileOutputStream(fileName);
DataOutputStream tmpdos = new DataOutputStream(tmpfos);
tmpdos.close();
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
for (Time tmpVisit : timeInfo) {
dos.writeUTF(tmpVisit.name);
dos.writeUTF(tmpVisit.address);
dos.write(tmpVisit.buyers);
dos.writeUTF(tmpVisit.comment);
}
dos.close();
} catch (IOException e) {
System.out.println("Error");
}
}
break;
}
}
while (enterkey.charAt(0) != 'е');
} catch (
IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 11,565 | java | Main.java | Java | [] | null | [] | import javax.lang.model.element.NestingKind;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
public class Main {
static Scanner scanner = new Scanner(System.in);
static String fileName = "file.txt";
static int indexList = 1;
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
abstract static class Shop {
String name;
String address;
abstract void allBuyers();
abstract void minBuyers();
abstract void commentWithWord();
}
public static class Time extends Shop {
int buyers;
String comment;
@Override
public void allBuyers() {
int all = 0;
for(Time tmp : timeInfo)
{
all+= tmp.buyers;
}
System.out.println("Загальна к-сть покупців: " + all);
}
@Override
public void minBuyers() {
Time min = timeInfo.get(0);
for(Time tmp : timeInfo)
{
if(min.buyers > tmp.buyers) min = tmp;
}
System.out.println("Мінімальна к-сть покупців: " + min.buyers);
}
@Override
public void commentWithWord() {
String word;
System.out.println("Введіть слово: ");
word = scanner.nextLine();
for(Time tmp : timeInfo)
{
if(tmp.comment.contains(word)) {
System.out.println("Коментар який містить слово: " + tmp.comment);
}
}
}
public void AddNewData() {
try {
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
System.out.print("Введіть назву: ");
name = scanner.nextLine();
System.out.print("Введіть адрес: ");
address = scanner.nextLine();
System.out.print("Введіть к-сть покупців: ");
buyers = scanner.nextInt();
System.out.print("Введіть коментар: ");
comment = scanner.nextLine();
comment = scanner.nextLine();
dos.writeUTF(name);
dos.writeUTF(address);
dos.write(buyers);
dos.writeUTF(comment);
dos.close();
timeInfo.add(this);
} catch (IOException e) {
System.out.println("Error");
}
}
public void EditData() {
byte lineIndex;
do {
do {
System.out.print("Введіть поле дял редагування\n(1.Назва | 2.Адрес | 3.К-сть покупців | 4.Коментар)\n(5.Назад в меню)\nВведіть індекс:");
lineIndex = scanner.nextByte();
} while (lineIndex < 1 || lineIndex > 6);
switch (lineIndex) {
case 1: {
System.out.print("Введіть прізвище: ");
name = scanner.nextLine();
name = scanner.nextLine();
}
case 2: {
System.out.print("Введіть адрес: ");
address = scanner.nextLine();
address = scanner.nextLine();
}
break;
case 3: {
System.out.print("Введіть к-сть покупців: ");
buyers = scanner.nextByte();
}
break;
case 4: {
System.out.print("Введіть коментар: ");
comment = scanner.nextLine();
comment = scanner.nextLine();
}
break;
}
} while (lineIndex != 5);
try {
FileOutputStream tmpfos = new FileOutputStream(fileName);
DataOutputStream tmpdos = new DataOutputStream(tmpfos);
tmpdos.close();
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
for (Time tmpVisit : timeInfo) {
dos.writeUTF(tmpVisit.name);
dos.writeUTF(tmpVisit.address);
dos.write(tmpVisit.buyers);
dos.writeUTF(tmpVisit.comment);
}
dos.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public void Show() {
System.out.println("Назва: " + name + " | Адрес: " + address + " | К-сть покупців: " + buyers + " |\n Коментар: " + comment);
}
}
static ArrayList<Time> timeInfo = new ArrayList<Time>();
static void LoadFromFile() {
timeInfo.clear();
try {
FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis);
Time temp;
while (dis.available() > 0) {
temp = new Time();
temp.name = dis.readUTF();
temp.address = dis.readUTF();
temp.buyers = dis.read();
temp.comment = dis.readUTF();
timeInfo.add(temp);
}
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String enterkey;
LoadFromFile();
try {
do {
System.out.println("Введіть:\n 'р' - редагувати,\n 'а' - додати,\n 'в' - вивід,\n 'с' - Загальна кількість покупців,\n 'м' - година з найменшою кількістю покупців,\n 'н' - коментарями з певними словами,\n 'д' - вилучення,\n 'е' - вихід");
enterkey = reader.readLine();
Time temp = new Time();
switch (enterkey.charAt(0)) {
case 'р': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
byte index;
do {
System.out.print("Введіть індекс(" + "from 1 to " + timeInfo.size() + "):");
index = scanner.nextByte();
} while (index < 1 || index > timeInfo.size());
timeInfo.get(index - 1).EditData();
}
break;
case 'в': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайте дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
}
break;
case 'а':
temp.AddNewData();
break;
case 'с': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).allBuyers();
}
}
break;
case 'н': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).commentWithWord();
}
}
break;
case 'м': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
timeInfo.get(0).minBuyers();
}
}
break;
case 'д': {
if (timeInfo.isEmpty()) {
System.out.println("Список пустий, додайти дані.");
} else {
System.out.println("Список:");
indexList = 1;
for (Time tmpVisit : timeInfo) {
System.out.print(indexList + ": ");
tmpVisit.Show();
indexList++;
}
}
byte index;
do {
System.out.print("Введіть індекс (" + "from 1 to " + timeInfo.size() + "):");
index = scanner.nextByte();
} while (index < 1 || index > timeInfo.size());
timeInfo.remove(index - 1);
try {
FileOutputStream tmpfos = new FileOutputStream(fileName);
DataOutputStream tmpdos = new DataOutputStream(tmpfos);
tmpdos.close();
FileOutputStream fos = new FileOutputStream(fileName, true);
DataOutputStream dos = new DataOutputStream(fos);
for (Time tmpVisit : timeInfo) {
dos.writeUTF(tmpVisit.name);
dos.writeUTF(tmpVisit.address);
dos.write(tmpVisit.buyers);
dos.writeUTF(tmpVisit.comment);
}
dos.close();
} catch (IOException e) {
System.out.println("Error");
}
}
break;
}
}
while (enterkey.charAt(0) != 'е');
} catch (
IOException e) {
e.printStackTrace();
}
}
}
| 11,565 | 0.40481 | 0.402067 | 292 | 36.452053 | 27.138554 | 254 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606164 | false | false | 15 |
4399a2f42763a05465a99c91518d93bbd31b6f6f | 23,974,507,493,287 | fe7d4e669efe7dfc0c15eb3daccce8bc3196a4af | /TP3/RomanNumber.java | cad4a7354f5e0dc97e6bac70716c8f682f3758cd | [] | no_license | Anaelle-Dessaigne/TPGenieLogiciel | https://github.com/Anaelle-Dessaigne/TPGenieLogiciel | cc3943eb773fbd74a6a3259b8bf899958f4bc21d | 466c1f47c6adad036826f0778c9e86b5ba209fec | refs/heads/master | 2020-08-15T10:56:57.126000 | 2019-10-20T22:12:36 | 2019-10-20T22:12:36 | 215,329,317 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package roman;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;
import java.util.Map;
public final class RomanNumber extends Number {
public static final long serialVersionUID = 1L;
// Table des symboles
private static final LinkedHashMap<String, Integer> SYMBOLS = new LinkedHashMap<>();
static {
SYMBOLS.put("M", 1000);
SYMBOLS.put("CM", 900);
SYMBOLS.put("D", 500);
SYMBOLS.put("CD", 400);
SYMBOLS.put("C", 100);
SYMBOLS.put("XC", 90);
SYMBOLS.put("L", 50);
SYMBOLS.put("XL", 40);
SYMBOLS.put("X", 10);
SYMBOLS.put("IX", 9);
SYMBOLS.put("V", 5);
SYMBOLS.put("IV", 4);
SYMBOLS.put("I", 1);
}
// Expression reguliere de validation
private static final Pattern VALIDATION_RE = Pattern.compile(
"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$");
private final int value;
public RomanNumber(String romanValue) {
this.value = fromRoman(romanValue);
}
public RomanNumber(int value) {
this.value = value;
}
//Pour les fonctions suivantes (double, float, int, long, nous n'avons pas compris comment les implémenter et surtout à quoi elles servent, du coup nous n'avons pas réussi à les faire
/**
* @{inheritDoc}
*/
@Override
public double doubleValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public float floatValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public int intValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public long longValue() {
// TODO
return 0;
}
@Override
public String toString() {
return toRoman(this.value);
}
public static RomanNumber valueOf(String roman) {
return new RomanNumber(roman);
}
public static RomanNumber valueOf(int value) {
return new RomanNumber(value);
}
private static int fromRoman(String romanValue) {
int result = 0;
int index = 0;
for(Map.Entry<String, Integer> v : SYMBOLS.entrySet()){
while(romanValue.substring(index, index + v.getKey().length()) == v.getKey()){
result += v.getValue();
index += v.getKey().length();
}
}
return result;
}
private static String toRoman(int value) {
String result = "";
for(Map.Entry<String, Integer> v : SYMBOLS.entrySet()) {
while(value >= v.getValue()) {
result += v.getKey();
value -= v.getValue();
}
}
return result;
}
}
| UTF-8 | Java | 2,363 | java | RomanNumber.java | Java | [] | null | [] | package roman;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;
import java.util.Map;
public final class RomanNumber extends Number {
public static final long serialVersionUID = 1L;
// Table des symboles
private static final LinkedHashMap<String, Integer> SYMBOLS = new LinkedHashMap<>();
static {
SYMBOLS.put("M", 1000);
SYMBOLS.put("CM", 900);
SYMBOLS.put("D", 500);
SYMBOLS.put("CD", 400);
SYMBOLS.put("C", 100);
SYMBOLS.put("XC", 90);
SYMBOLS.put("L", 50);
SYMBOLS.put("XL", 40);
SYMBOLS.put("X", 10);
SYMBOLS.put("IX", 9);
SYMBOLS.put("V", 5);
SYMBOLS.put("IV", 4);
SYMBOLS.put("I", 1);
}
// Expression reguliere de validation
private static final Pattern VALIDATION_RE = Pattern.compile(
"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$");
private final int value;
public RomanNumber(String romanValue) {
this.value = fromRoman(romanValue);
}
public RomanNumber(int value) {
this.value = value;
}
//Pour les fonctions suivantes (double, float, int, long, nous n'avons pas compris comment les implémenter et surtout à quoi elles servent, du coup nous n'avons pas réussi à les faire
/**
* @{inheritDoc}
*/
@Override
public double doubleValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public float floatValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public int intValue() {
// TODO
return 0;
}
/**
* @{inheritDoc}
*/
@Override
public long longValue() {
// TODO
return 0;
}
@Override
public String toString() {
return toRoman(this.value);
}
public static RomanNumber valueOf(String roman) {
return new RomanNumber(roman);
}
public static RomanNumber valueOf(int value) {
return new RomanNumber(value);
}
private static int fromRoman(String romanValue) {
int result = 0;
int index = 0;
for(Map.Entry<String, Integer> v : SYMBOLS.entrySet()){
while(romanValue.substring(index, index + v.getKey().length()) == v.getKey()){
result += v.getValue();
index += v.getKey().length();
}
}
return result;
}
private static String toRoman(int value) {
String result = "";
for(Map.Entry<String, Integer> v : SYMBOLS.entrySet()) {
while(value >= v.getValue()) {
result += v.getKey();
value -= v.getValue();
}
}
return result;
}
}
| 2,363 | 0.643493 | 0.625265 | 120 | 18.658333 | 23.4021 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.908333 | false | false | 15 |
51620ee0b0c7ad78994d3adad84b9b6d5a4233dd | 7,378,753,819,529 | e0f01ff8fc135aa0976e619096adf3b3d6f8ebcd | /src/main/java/cn/javaex/yaoqishan/service/type_field/TypeFieldService.java | a2015c3de94368b2e42ac6da5ef88a25728e85a3 | [
"Apache-2.0"
] | permissive | wsx180808/yaoqishan | https://github.com/wsx180808/yaoqishan | b454fca71c4f4114667798f38042aceb55d1c6fa | 515bed940e12aec37c12aca5d338a60b96bc7bbc | refs/heads/master | 2022-12-23T16:20:20.136000 | 2019-03-03T07:56:28 | 2019-03-03T07:56:28 | 232,039,413 | 0 | 0 | Apache-2.0 | false | 2022-12-16T11:36:15 | 2020-01-06T06:34:49 | 2020-01-06T06:35:26 | 2022-12-16T11:36:13 | 1,542 | 0 | 0 | 7 | Java | false | false | package cn.javaex.yaoqishan.service.type_field;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.javaex.yaoqishan.dao.field_info.IFieldInfoDAO;
import cn.javaex.yaoqishan.dao.media_info.IMediaInfoDAO;
import cn.javaex.yaoqishan.dao.type_field.ITypeFieldDAO;
import cn.javaex.yaoqishan.view.TypeField;
@Service("TypeFieldService")
public class TypeFieldService {
@Autowired
private ITypeFieldDAO iTypeFieldDAO;
@Autowired
private IFieldInfoDAO iFieldInfoDAO;
@Autowired
private IMediaInfoDAO iMediaInfoDAO;
/**
* 根据分类信息主键,查询该分类下的字段配置
* @param typeId 分类信息主键
* @return
*/
public List<TypeField> listByTypeId(String typeId) {
return iTypeFieldDAO.listByTypeId(typeId);
}
/**
* 保存某个分类信息下的字段配置
* @param typeId 分类信息主键
* @param typeFieldList
* @param fieldIdArr 字段主键数组
*/
public void save(String typeId, List<TypeField> typeFieldList, String[] fieldIdArr) {
// 1.0 删除该分类下的所有字段配置
iTypeFieldDAO.deleteByTypeId(typeId);
// 2.0 批量插入分类信息下的字段配置
iTypeFieldDAO.batchInsert(typeFieldList);
// 3.0 生成关联字段
// 3.1 获取字段的变量名集合
List<String> list = iFieldInfoDAO.listVarNameByIdArr(fieldIdArr);
if (list!=null && list.isEmpty()==false) {
int len = list.size();
for (int i=0; i<len; i++) {
String varName = list.get(i);
StringBuffer sql = new StringBuffer();
sql.append(" IF NOT EXISTS ( ");
sql.append(" SELECT ");
sql.append(" * ");
sql.append(" FROM ");
sql.append(" syscolumns ");
sql.append(" WHERE ");
sql.append(" id = object_id('media_info') ");
sql.append(" AND name = '"+varName+"' ");
sql.append(" ) ");
sql.append(" BEGIN ");
sql.append(" ALTER TABLE media_info ADD "+varName+" VARCHAR (100) ");
sql.append(" END ");
iMediaInfoDAO.alter(sql.toString());
}
}
}
/**
* 检索指定字段是否必填
* @param typeId 分类信息主键
* @param varName 字段变量名
* @return
*/
public String selectIsRequired(String typeId, String varName) {
return iTypeFieldDAO.selectIsRequired(typeId, varName);
}
}
| UTF-8 | Java | 2,414 | java | TypeFieldService.java | Java | [] | null | [] | package cn.javaex.yaoqishan.service.type_field;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.javaex.yaoqishan.dao.field_info.IFieldInfoDAO;
import cn.javaex.yaoqishan.dao.media_info.IMediaInfoDAO;
import cn.javaex.yaoqishan.dao.type_field.ITypeFieldDAO;
import cn.javaex.yaoqishan.view.TypeField;
@Service("TypeFieldService")
public class TypeFieldService {
@Autowired
private ITypeFieldDAO iTypeFieldDAO;
@Autowired
private IFieldInfoDAO iFieldInfoDAO;
@Autowired
private IMediaInfoDAO iMediaInfoDAO;
/**
* 根据分类信息主键,查询该分类下的字段配置
* @param typeId 分类信息主键
* @return
*/
public List<TypeField> listByTypeId(String typeId) {
return iTypeFieldDAO.listByTypeId(typeId);
}
/**
* 保存某个分类信息下的字段配置
* @param typeId 分类信息主键
* @param typeFieldList
* @param fieldIdArr 字段主键数组
*/
public void save(String typeId, List<TypeField> typeFieldList, String[] fieldIdArr) {
// 1.0 删除该分类下的所有字段配置
iTypeFieldDAO.deleteByTypeId(typeId);
// 2.0 批量插入分类信息下的字段配置
iTypeFieldDAO.batchInsert(typeFieldList);
// 3.0 生成关联字段
// 3.1 获取字段的变量名集合
List<String> list = iFieldInfoDAO.listVarNameByIdArr(fieldIdArr);
if (list!=null && list.isEmpty()==false) {
int len = list.size();
for (int i=0; i<len; i++) {
String varName = list.get(i);
StringBuffer sql = new StringBuffer();
sql.append(" IF NOT EXISTS ( ");
sql.append(" SELECT ");
sql.append(" * ");
sql.append(" FROM ");
sql.append(" syscolumns ");
sql.append(" WHERE ");
sql.append(" id = object_id('media_info') ");
sql.append(" AND name = '"+varName+"' ");
sql.append(" ) ");
sql.append(" BEGIN ");
sql.append(" ALTER TABLE media_info ADD "+varName+" VARCHAR (100) ");
sql.append(" END ");
iMediaInfoDAO.alter(sql.toString());
}
}
}
/**
* 检索指定字段是否必填
* @param typeId 分类信息主键
* @param varName 字段变量名
* @return
*/
public String selectIsRequired(String typeId, String varName) {
return iTypeFieldDAO.selectIsRequired(typeId, varName);
}
}
| 2,414 | 0.666361 | 0.660862 | 81 | 24.938272 | 20.476633 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.123457 | false | false | 15 |
3555f2363e563bc908eb16b8c9eaa5912cd6d8f4 | 20,916,490,785,940 | aad3500549be3f32a429c7f5cd6e4b249e9f1367 | /app/src/main/java/com/nantia/repartonantia/venta/VentaListaView.java | 194600c159de469eedde01f751928db25b24fb5f | [] | no_license | emiben/NantiaReparto | https://github.com/emiben/NantiaReparto | bd96c5a057910b44ce96d12a9d22c8b8fc01df8c | e3971dc5347e4a645fd8679965a4a689c8a44693 | refs/heads/master | 2020-03-19T07:15:53.155000 | 2018-10-31T01:11:17 | 2018-10-31T01:11:17 | 136,099,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nantia.repartonantia.venta;
import java.util.List;
public interface VentaListaView {
void onSetProgressBarVisibility(int visibility);
void setVentasInfo(List<Venta> ventas);
void addListeners();
}
| UTF-8 | Java | 223 | java | VentaListaView.java | Java | [] | null | [] | package com.nantia.repartonantia.venta;
import java.util.List;
public interface VentaListaView {
void onSetProgressBarVisibility(int visibility);
void setVentasInfo(List<Venta> ventas);
void addListeners();
}
| 223 | 0.7713 | 0.7713 | 9 | 23.777779 | 18.665344 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 15 |
018debd46db4904e2a114c13e50a9176b578340b | 26,551,487,878,560 | 92877af20ddda0905d112765c374ddcd3e2862c6 | /src/main/java/com/vancuongngo/springwebapp/service/security/role/RoleService.java | b16c04ebc5f36904aa668ae27fc837f3e361a32a | [] | no_license | bavuonglong/springbootwebapp | https://github.com/bavuonglong/springbootwebapp | 5efaf33c78f1fd9beed743aa2d1830f2728c7f2c | b222cea1a0e48902363d6321656178a434678a42 | refs/heads/master | 2021-01-01T05:56:41.819000 | 2017-10-09T09:06:34 | 2017-10-09T09:06:34 | 97,314,421 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vancuongngo.springwebapp.service.security.role;
import com.vancuongngo.springwebapp.repository.model.Role;
import com.vancuongngo.springwebapp.service.CRUDService;
public interface RoleService extends CRUDService<Role> {
}
| UTF-8 | Java | 237 | java | RoleService.java | Java | [] | null | [] | package com.vancuongngo.springwebapp.service.security.role;
import com.vancuongngo.springwebapp.repository.model.Role;
import com.vancuongngo.springwebapp.service.CRUDService;
public interface RoleService extends CRUDService<Role> {
}
| 237 | 0.848101 | 0.848101 | 7 | 32.857143 | 28.185247 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 15 |
91b41f83955db83b7679218987d863d98f69843f | 35,338,990,954,063 | 9fb4c77ef51ecfe9bde73d931ae7437be8507a0d | /verticalstepper/src/test/java/com/snowble/android/widget/verticalstepper/VerticalStepperTest.java | 172f09d54af9ccef286987399b8db6b096806e32 | [
"Apache-2.0"
] | permissive | albodelu/vertical-stepper | https://github.com/albodelu/vertical-stepper | 4e7da764d3f3d51adf28cd93f1e8b2f5c5b812db | e6ecfe1f0b8aebbc204a029cb5189dd5e7c1f18d | refs/heads/master | 2021-01-19T11:03:54.893000 | 2017-01-16T20:06:04 | 2017-01-16T22:14:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.snowble.android.widget.verticalstepper;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Parcelable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.AppCompatButton;
import android.text.TextPaint;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.Robolectric;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.*;
import static org.mockito.Mockito.*;
@RunWith(Enclosed.class)
public class VerticalStepperTest {
private static class MockedStep {
View innerView;
VerticalStepper.LayoutParams innerLayoutParams;
VerticalStepper.InternalTouchView touchView;
AppCompatButton continueButton;
VerticalStepper.LayoutParams continueLayoutParams;
Step step;
MockedStep() {
innerView = mock(View.class);
innerLayoutParams = mock(VerticalStepper.LayoutParams.class);
when(innerView.getLayoutParams()).thenReturn(innerLayoutParams);
continueButton = mock(AppCompatButton.class);
continueLayoutParams = mock(VerticalStepper.LayoutParams.class);
when(continueButton.getLayoutParams()).thenReturn(continueLayoutParams);
touchView = mock(VerticalStepper.InternalTouchView.class);
step = mock(Step.class);
when(step.getInnerView()).thenReturn(innerView);
when(step.getTouchView()).thenReturn(touchView);
when(step.getContinueButton()).thenReturn(continueButton);
}
}
public abstract static class GivenAStepper extends GivenAnActivity {
VerticalStepper stepper;
@Before
public void givenAStepper() {
stepper = new VerticalStepper(activity);
}
void mockActiveState(MockedStep step, boolean isActive) {
when(step.step.isActive()).thenReturn(isActive);
int visibility = isActive ? View.VISIBLE : View.GONE;
when(step.innerView.getVisibility()).thenReturn(visibility);
when(step.continueButton.getVisibility()).thenReturn(visibility);
}
}
public static class GivenZeroSteps extends GivenAStepper {
private int getColor(int colorRes) {
return ResourcesCompat.getColor(activity.getResources(), colorRes, activity.getTheme());
}
@SuppressLint("PrivateResource") // https://code.google.com/p/android/issues/detail?id=230985
@Test
public void initPropertiesFromAttrs_NoAttrsSet_ShouldUseDefaults() {
stepper.initPropertiesFromAttrs(null, 0, 0);
assertThat(stepper.iconActiveColor).isEqualTo(getColor(R.color.bg_active_icon));
assertThat(stepper.iconInactiveColor).isEqualTo(getColor(R.color.bg_inactive_icon));
assertThat(stepper.iconCompleteColor).isEqualTo(stepper.iconActiveColor);
assertThat(stepper.continueButtonStyle)
.isEqualTo(android.support.v7.appcompat.R.style.Widget_AppCompat_Button_Colored);
}
@SuppressLint("PrivateResource") // https://code.google.com/p/android/issues/detail?id=230985
@Test
public void initPropertiesFromAttrs_AttrsSet_ShouldUseAttrs() {
Robolectric.AttributeSetBuilder builder = Robolectric.buildAttributeSet();
builder.addAttribute(R.attr.iconColorActive, "@android:color/black");
builder.addAttribute(R.attr.iconColorInactive, "@android:color/darker_gray");
builder.addAttribute(R.attr.iconColorComplete, "@android:color/holo_orange_dark");
builder.addAttribute(R.attr.continueButtonStyle, "@style/Widget.AppCompat.Button.Borderless");
stepper.initPropertiesFromAttrs(builder.build(), 0, 0);
assertThat(stepper.iconActiveColor).isEqualTo(getColor(android.R.color.black));
assertThat(stepper.iconInactiveColor).isEqualTo(getColor(android.R.color.darker_gray));
assertThat(stepper.iconCompleteColor).isEqualTo(getColor(android.R.color.holo_orange_dark));
assertThat(stepper.continueButtonStyle)
.isEqualTo(android.support.v7.appcompat.R.style.Widget_AppCompat_Button_Borderless);
}
@Test
public void initSteps_ShouldHaveEmptyInnerViews() {
stepper.initSteps(null);
assertThat(stepper.steps).isEmpty();
}
@Test
public void calculateWidth_ShouldReturnHorizontalPadding() {
int width = stepper.calculateWidth();
assertThat(width)
.isEqualTo(stepper.calculateHorizontalPadding());
}
@Test
public void doMeasurement_UnspecifiedSpecs_ShouldMeasurePadding() {
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.doMeasurement(ms, ms);
assertThat(stepper.getMeasuredHeight()).isEqualTo(stepper.calculateVerticalPadding());
assertThat(stepper.getMeasuredWidth()).isEqualTo(stepper.calculateHorizontalPadding());
}
@Test
public void doMeasurement_AtMostSpecsRequiresClipping_ShouldMeasureToAtMostValues() {
int width = stepper.calculateHorizontalPadding() / 2;
int height = stepper.calculateVerticalPadding() / 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void doMeasurement_ExactlySpecsRequiresClipping_ShouldMeasureToExactValues() {
int width = stepper.calculateHorizontalPadding() / 2;
int height = stepper.calculateVerticalPadding() / 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void doMeasurement_ExactlySpecsRequiresExpanding_ShouldMeasureToExactValues() {
int width = stepper.calculateHorizontalPadding() * 2;
int height = stepper.calculateVerticalPadding() * 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void calculateHeight_ShouldReturnVerticalPadding() {
int width = stepper.calculateHeight();
assertThat(width)
.isEqualTo(stepper.calculateVerticalPadding());
}
@Test
public void calculateHorizontalPadding_ShouldReturnAllPadding() {
int horizontalPadding = stepper.calculateHorizontalPadding();
assertThat(horizontalPadding)
.isEqualTo((stepper.outerHorizontalPadding * 2) +
stepper.getPaddingLeft() + stepper.getPaddingRight());
}
@Test
public void calculateVerticalPadding_ShouldReturnAllPadding() {
int verticalPadding = stepper.calculateVerticalPadding();
assertThat(verticalPadding)
.isEqualTo((stepper.outerVerticalPadding * 2) +
stepper.getPaddingTop() + stepper.getPaddingBottom());
}
@Test
public void layoutTouchView_WhenNotEnoughSpace_ShouldClip() {
int leftPadding = 20;
int topPadding = 4;
int rightPadding = 10;
int bottomPadding = 2;
stepper.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int adjustedLeft = left + stepper.outerHorizontalPadding + leftPadding;
int adjustedTop = top + stepper.outerVerticalPadding + topPadding;
int adjustedRight = right - stepper.outerHorizontalPadding - rightPadding;
int adjustedBottom = bottom - stepper.outerVerticalPadding - bottomPadding;
VerticalStepper.InternalTouchView touchView = mock(VerticalStepper.InternalTouchView.class);
when(touchView.getMeasuredHeight()).thenReturn(bottom * 2);
stepper.layoutTouchView(new Rect(adjustedLeft, adjustedTop, adjustedRight, adjustedBottom), touchView);
verify(touchView).layout(eq(left + leftPadding), eq(top + topPadding),
eq(right - left - rightPadding), eq(bottom - top - bottomPadding));
}
@Test
public void layoutTouchView_WhenEnoughSpace_ShouldUseFullWidthAndMeasuredHeight() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int adjustedLeft = left + stepper.outerHorizontalPadding;
int adjustedTop = top + stepper.outerVerticalPadding;
int adjustedRight = right - stepper.outerHorizontalPadding;
int adjustedBottom = bottom - stepper.outerVerticalPadding;
VerticalStepper.InternalTouchView touchView = mock(VerticalStepper.InternalTouchView.class);
int touchMeasuredHeight = bottom / 2;
when(touchView.getMeasuredHeight()).thenReturn(touchMeasuredHeight);
stepper.layoutTouchView(new Rect(adjustedLeft, adjustedTop, adjustedRight, adjustedBottom), touchView);
verify(touchView).layout(eq(left), eq(top), eq(right - left), eq(top + touchMeasuredHeight));
}
@Test
public void layoutActiveView_WhenNotEnoughSpace_ShouldClip() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int leftMargin = 5;
int topMargin = 20;
int rightMargin = 10;
int bottomMargin = 15;
View activeView = mock(View.class);
when(activeView.getMeasuredWidth()).thenReturn(right * 2);
when(activeView.getMeasuredHeight()).thenReturn(bottom * 2);
when(activeView.getLayoutParams()).thenReturn(
createTestLayoutParams(leftMargin, topMargin, rightMargin, bottomMargin));
stepper.layoutActiveView(new Rect(left, top, right, bottom), activeView);
verify(activeView).layout(eq(left + leftMargin), eq(top + topMargin),
eq(right - rightMargin), eq(bottom - bottomMargin));
}
@Test
public void layoutActiveView_WhenEnoughSpace_ShouldUseFullWidthAndMeasuredHeight() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
View activeView = mock(View.class);
int measuredWidth = right / 2;
when(activeView.getMeasuredWidth()).thenReturn(measuredWidth);
int measuredHeight = bottom / 2;
when(activeView.getMeasuredHeight()).thenReturn(measuredHeight);
when(activeView.getLayoutParams()).thenReturn(mock(VerticalStepper.LayoutParams.class));
stepper.layoutActiveView(new Rect(left, top, right, bottom), activeView);
verify(activeView).layout(eq(left), eq(top), eq(left + measuredWidth), eq(top + measuredHeight));
}
}
public abstract static class GivenOneStep extends GivenAStepper {
MockedStep mockedStep1;
@Before
public void givenOneStep() {
mockedStep1 = new MockedStep();
stepper.steps.add(mockedStep1.step);
clearInvocations(mockedStep1.innerView);
clearInvocations(mockedStep1.innerLayoutParams);
clearInvocations(mockedStep1.continueButton);
clearInvocations(mockedStep1.continueLayoutParams);
clearInvocations(mockedStep1.touchView);
clearInvocations(mockedStep1.step);
}
void mockStep1Widths(int decoratorWidth, int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
mockStepWidths(mockedStep1, decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
}
void mockStepWidths(MockedStep mockedStep, int decoratorWidth,
int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
when(mockedStep.step.calculateStepDecoratorWidth()).thenReturn(decoratorWidth);
when(mockedStep.step.calculateHorizontalUsedSpace(mockedStep.innerView)).thenReturn(innerUsedSpace);
when(mockedStep.innerView.getMeasuredWidth()).thenReturn(innerWidth);
when(mockedStep.step.calculateHorizontalUsedSpace(mockedStep.continueButton)).thenReturn(continueUsedSpace);
when(mockedStep.continueButton.getMeasuredWidth()).thenReturn(continueWidth);
}
void mockStepHeights(int decoratorHeight, int childrenVisibleHeight, int bottomMarginHeight, Step step) {
when(step.getDecoratorHeight()).thenReturn(decoratorHeight);
when(step.getChildrenVisibleHeight()).thenReturn(childrenVisibleHeight);
when(step.getBottomMarginHeight()).thenReturn(bottomMarginHeight);
}
}
public static class GivenExactlyOneStep extends GivenOneStep {
@Test
public void initInnerView_ShouldInitializeStepViews() {
assertThat(stepper.steps)
.hasSize(1)
.doesNotContainNull();
Step step = stepper.steps.get(0);
assertThat(step.getTouchView())
.isNotNull();
assertThat(step.getContinueButton())
.isNotNull();
}
@Test
public void initTouchView_ShouldSetClickListener() {
stepper.initTouchView(mockedStep1.step);
verify(mockedStep1.touchView).setOnClickListener((View.OnClickListener) notNull());
}
@Test
public void initTouchView_ShouldAttachToStepper() {
stepper.initTouchView(mockedStep1.step);
assertThat(stepper.getChildCount()).isEqualTo(1);
}
@Test
public void initNavButtons_ShouldSetTextToContinue() {
stepper.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setText(R.string.continue_button);
}
@Test
public void initNavButtons_ShouldSetLayoutParamsWithTopMarginAndHeight() {
int height = 80;
int topMargin = 20;
when(mockedStep1.step.getNavButtonHeight()).thenReturn(height);
when(mockedStep1.step.getNavButtonTopMargin()).thenReturn(topMargin);
stepper.initNavButtons(mockedStep1.step);
ArgumentCaptor<VerticalStepper.LayoutParams> lpCaptor =
ArgumentCaptor.forClass(VerticalStepper.LayoutParams.class);
verify(mockedStep1.continueButton).setLayoutParams(lpCaptor.capture());
VerticalStepper.LayoutParams lp = lpCaptor.getValue();
assertThat(lp.topMargin).isEqualTo(topMargin);
assertThat(lp.height).isEqualTo(height);
}
@Test
public void initNavButtons_ShouldSetClickListener() {
stepper.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setOnClickListener((View.OnClickListener) notNull());
}
@Test
public void initNavButtons_ShouldAttachToStepper() {
stepper.initNavButtons(mockedStep1.step);
assertThat(stepper.getChildCount()).isEqualTo(1);
}
@Test
public void measureBottomMarginHeights_ShouldNotMeasureBottomMarginToNextStep() {
stepper.measureStepBottomMarginHeights();
verify(mockedStep1.step, never()).measureBottomMarginToNextStep();
}
@Test
public void calculateWidth_ShouldReturnHorizontalPaddingAndStepWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = decoratorWidth * 4;
int continueUsedSpace = 30;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int width = stepper.calculateWidth();
assertThat(width)
.isEqualTo(stepper.calculateHorizontalPadding()
+ innerWidth + innerUsedSpace);
}
@Test
public void calculateMaxStepWidth_DecoratorsHaveMaxWidth_ShouldReturnDecoratorsWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 10;
int innerWidth = 0;
int continueUsedSpace = 15;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(decoratorWidth);
}
@Test
public void calculateMaxStepWidth_InnerViewHasMaxWidth_ShouldReturnInnerViewWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = decoratorWidth * 4;
int continueUsedSpace = 15;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(innerWidth + innerUsedSpace);
}
@Test
public void calculateMaxStepWidth_NavButtonsHaveMaxWidth_ShouldReturnNavButtonsWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = 0;
int continueUsedSpace = 10;
int continueWidth = decoratorWidth * 4;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(continueWidth + continueUsedSpace);
}
@Test
public void calculateHeight_ShouldReturnVerticalPaddingPlusTotalStepHeight() {
int decoratorHeight = 100;
int childrenVisibleHeight = 400;
int bottomMarginHeight = 48;
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep1.step);
int width = stepper.calculateHeight();
assertThat(width)
.isEqualTo(stepper.calculateVerticalPadding()
+ decoratorHeight + childrenVisibleHeight + bottomMarginHeight);
}
@Test
public void layoutActiveViews_ShouldNotModifyInputRect() {
Rect rect = new Rect(1, 2, 3, 4);
stepper.layoutActiveViews(rect, mockedStep1.step);
assertThat(rect).isEqualTo(new Rect(1, 2, 3, 4));
}
}
public static class GivenOneStepAndAStepValidator extends GivenOneStep {
private StepValidator validator;
@Before
public void givenStepperSpyWithExactlyTwoStepsAndAStepValidator() {
validator = mock(StepValidator.class);
when(validator.validate(mockedStep1.innerView, false))
.thenReturn(ValidationResult.VALID_COMPLETE_RESULT);
stepper.setStepValidator(validator);
}
@Test
public void attemptStepCompletion_HasValidator_ShouldCallListenerWithInnerView() {
stepper.attemptStepCompletion(mockedStep1.step);
verify(validator).validate(mockedStep1.innerView, false);
}
@Test
public void attemptStepCompletion_HasValidator_ShoulClearErrorButNotCompleteIfIncomplete() {
when(validator.validate(mockedStep1.innerView, false))
.thenReturn(ValidationResult.VALID_INCOMPLETE_RESULT);
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step, never()).markComplete();
}
@Test
public void attemptStepCompletion_HasValidator_ShouldCompleteIfStepValidAndComplete() {
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
}
@Test
public void attemptStepCompletion_removeStepValidator_ShouldComplete() {
String error = "error";
ValidationResult result = new ValidationResult(error);
when(validator.validate(mockedStep1.innerView, false)).thenReturn(result);
stepper.removeStepValidator();
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step, never()).setError(error);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
}
}
public static class GivenExactlyOneActiveStep extends GivenOneStep {
@Before
public void givenExactlyOneActiveStep() {
mockActiveState(mockedStep1, true);
}
@Test
public void syncVisibilityWithActiveState_ShouldMakeActiveViewsVisible() {
stepper.syncVisibilityWithActiveState(mockedStep1.step);
verify(mockedStep1.innerView).setVisibility(View.VISIBLE);
verify(mockedStep1.continueButton).setVisibility(View.VISIBLE);
}
@Test
public void measureActiveViews_ShouldHaveActiveViewsHeightsWithActualHeight() {
final int innerViewHeight = 100;
final int buttonHeight = 50;
when(mockedStep1.innerView.getMeasuredHeight()).thenReturn(innerViewHeight);
when(mockedStep1.continueButton.getMeasuredHeight()).thenReturn(buttonHeight);
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.measureActiveViews(ms, ms);
verify(mockedStep1.step).setActiveViewsHeight(innerViewHeight + buttonHeight);
}
}
public static class GivenExactlyOneInactiveStep extends GivenOneStep {
@Before
public void givenExactlyOneInactiveStep() {
mockActiveState(mockedStep1, false);
}
@Test
public void syncVisibilityWithActiveState_ShouldMakeActiveViewsGone() {
stepper.syncVisibilityWithActiveState(mockedStep1.step);
verify(mockedStep1.innerView).setVisibility(View.GONE);
verify(mockedStep1.continueButton).setVisibility(View.GONE);
}
}
public static abstract class GivenTwoSteps extends GivenOneStep {
MockedStep mockedStep2;
@Before
public void givenTwoSteps() {
mockedStep2 = new MockedStep();
stepper.steps.add(mockedStep2.step);
clearInvocations(mockedStep2.innerView);
clearInvocations(mockedStep2.innerLayoutParams);
clearInvocations(mockedStep2.continueButton);
clearInvocations(mockedStep2.continueLayoutParams);
clearInvocations(mockedStep2.touchView);
clearInvocations(mockedStep2.step);
}
void mockStep2Widths(int decoratorWidth, int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
mockStepWidths(mockedStep2, decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
}
}
public static class GivenExactlyTwoSteps extends GivenTwoSteps {
@Test
public void onSaveInstanceState_ShouldSaveStepStates() {
Parcelable state = stepper.onSaveInstanceState();
verify(mockedStep1.step).generateState();
verify(mockedStep2.step).generateState();
assertThat(state).isInstanceOf(VerticalStepper.SavedState.class);
VerticalStepper.SavedState ss = (VerticalStepper.SavedState) state;
assertThat(ss.stepStates).hasSize(2);
}
@Test
public void measureStepDecoratorHeights_ShouldMeasureStepDecoratorHeightTwice() {
stepper.measureStepDecoratorHeights();
verify(mockedStep1.step).measureStepDecoratorHeight();
verify(mockedStep2.step).measureStepDecoratorHeight();
}
@Test
public void measureBottomMarginHeights_ShouldMeasureBottomMarginToNextStepOnce() {
stepper.measureStepBottomMarginHeights();
verify(mockedStep1.step).measureBottomMarginToNextStep();
}
@Test
public void measureActiveViews_ShouldMeasureViews() {
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.measureActiveViews(ms, ms);
verify(mockedStep1.innerView).measure(anyInt(), anyInt());
verify(mockedStep2.innerView).measure(anyInt(), anyInt());
verify(mockedStep1.continueButton).measure(anyInt(), anyInt());
verify(mockedStep1.continueButton).measure(anyInt(), anyInt());
}
@Test
public void calculateMaxStepWidth_ShouldReturnLargerStepWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int continueWidth = 0;
int continueUsedSpace = 10;
int inner1Width = decoratorWidth * 2;
mockStep1Widths(decoratorWidth, innerUsedSpace, inner1Width, continueUsedSpace, continueWidth);
int inner2Width = decoratorWidth * 3;
mockStep2Widths(decoratorWidth, innerUsedSpace, inner2Width, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isNotEqualTo(inner1Width + innerUsedSpace)
.isEqualTo(inner2Width + innerUsedSpace);
}
@Test
public void calculateHeight_ShouldReturnVerticalPaddingPlusTotalStepHeight() {
int decoratorHeight = 100;
int childrenVisibleHeight = 400;
int bottomMarginHeight = 48;
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep1.step);
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep2.step);
int height = stepper.calculateHeight();
assertThat(height)
.isEqualTo(stepper.calculateVerticalPadding()
+ (2 * (decoratorHeight + childrenVisibleHeight + bottomMarginHeight)));
}
@Test
public void measureTouchViews_ShouldMeasureAllWidthsAndHeightsExactly() {
int width = 20;
int height = 80;
when(mockedStep1.step.getTouchViewHeight()).thenReturn(height);
when(mockedStep2.step.getTouchViewHeight()).thenReturn(height);
stepper.measureTouchViews(width);
ArgumentCaptor<Integer> wmsCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> hmsCaptor = ArgumentCaptor.forClass(Integer.class);
verify(mockedStep1.touchView).measure(wmsCaptor.capture(), hmsCaptor.capture());
verify(mockedStep2.touchView).measure(wmsCaptor.capture(), hmsCaptor.capture());
for (int actualWms : wmsCaptor.getAllValues()) {
assertThat(View.MeasureSpec.getMode(actualWms)).isEqualTo(View.MeasureSpec.EXACTLY);
assertThat(View.MeasureSpec.getSize(actualWms)).isEqualTo(width);
}
for (int actualHms : hmsCaptor.getAllValues()) {
assertThat(View.MeasureSpec.getMode(actualHms)).isEqualTo(View.MeasureSpec.EXACTLY);
assertThat(View.MeasureSpec.getSize(actualHms)).isEqualTo(height);
}
}
}
public static abstract class GivenStepperSpy extends GivenAStepper {
VerticalStepper stepperSpy;
@Before
public void givenStepperSpy() {
stepperSpy = spy(stepper);
}
}
public static class GivenEmptyStepperSpy extends GivenStepperSpy {
@Test
public void onAttachedToWindow_ShouldInitSteps() {
doNothing().when(stepperSpy).initSteps(null);
stepperSpy.onAttachedToWindow();
verify(stepperSpy).initSteps(null);
}
@SuppressLint("WrongCall") // Explicitly testing onMeasure
@Test
public void onMeasure_ShouldCallDoMeasurement() {
doNothing().when(stepperSpy).doMeasurement(anyInt(), anyInt());
stepperSpy.onMeasure(0, 0);
verify(stepperSpy).doMeasurement(eq(0), eq(0));
}
@SuppressLint("WrongCall") // Explicitly testing onDraw
@Test
public void onDraw_ShouldCallDoDraw() {
Canvas canvas = mock(Canvas.class);
doNothing().when(stepperSpy).doDraw(same(canvas));
stepperSpy.onDraw(canvas);
verify(stepperSpy).doDraw(canvas);
}
}
public static class GivenStepperSpyWithStubbedInitStepsMethods extends GivenStepperSpy {
@Before
public void givenStepperSpyWithStubbedInitStepsMethods() {
View child1 = mock(View.class);
View child2 = mock(View.class);
VerticalStepper.LayoutParams lp = mock(VerticalStepper.LayoutParams.class);
when(lp.getTitle()).thenReturn("title");
when(child1.getLayoutParams()).thenReturn(lp);
when(child2.getLayoutParams()).thenReturn(lp);
// For some reason, calling addView() doesn't update the children properly with the stepperSpy.
// So explicitly set child count and children
doReturn(2).when(stepperSpy).getChildCount();
doReturn(child1).when(stepperSpy).getChildAt(0);
doReturn(child2).when(stepperSpy).getChildAt(1);
doNothing().when(stepperSpy).initTouchView(any(Step.class));
doNothing().when(stepperSpy).initNavButtons(any(Step.class));
doNothing().when(stepperSpy).syncVisibilityWithActiveState(any(Step.class));
}
@Test
public void initSteps_ShouldInitStepsAndChildViews() {
stepperSpy.initSteps(null);
verify(stepperSpy, times(2)).initTouchView(any(Step.class));
verify(stepperSpy, times(2)).initNavButtons(any(Step.class));
verify(stepperSpy, times(2)).syncVisibilityWithActiveState(any(Step.class));
assertThat(stepperSpy.steps).hasSize(2).doesNotContainNull();
}
@Test
public void initSteps_ShouldSetStatesForSteps() {
String summary = "summary";
String error = "error";
List<Step.State> states = Arrays.asList(new Step.State(false, true, null, summary),
new Step.State(true, false, error, null));
VerticalStepper.SavedState state = new VerticalStepper.SavedState(mock(Parcelable.class), states);
stepperSpy.initSteps(state);
Step step1 = stepperSpy.steps.get(0);
assertThat(step1.isActive()).isFalse();
assertThat(step1.isComplete()).isTrue();
assertThat(step1.hasError()).isFalse();
assertThat(step1.getSubtitle()).isEqualTo(summary);
Step step2 = stepperSpy.steps.get(1);
assertThat(step2.isActive()).isTrue();
assertThat(step2.isComplete()).isFalse();
assertThat(step2.hasError()).isTrue();
assertThat(step2.getSubtitle()).isEqualTo(error);
}
}
public static abstract class GivenStepperSpyWithTwoSteps extends GivenStepperSpy {
MockedStep mockedStep1;
MockedStep mockedStep2;
@Before
public void givenStepperSpyWithTwoSteps() {
mockedStep1 = new MockedStep();
mockedStep2 = new MockedStep();
stepperSpy.steps.add(mockedStep1.step);
stepperSpy.steps.add(mockedStep2.step);
}
}
public static class GivenStepperSpyWithExactlyTwoSteps extends GivenStepperSpyWithTwoSteps {
@Test
public void touchViewOnClickListener_ShouldCallCollapseOtherStepsAndToggle() {
ArgumentCaptor<View.OnClickListener> captor = ArgumentCaptor.forClass(View.OnClickListener.class);
stepperSpy.initTouchView(mockedStep1.step);
verify(mockedStep1.touchView).setOnClickListener(captor.capture());
View.OnClickListener clickListenerSpy = spy(captor.getValue());
doNothing().when(stepperSpy).collapseOtherSteps(mockedStep1.step);
doNothing().when(stepperSpy).toggleStepExpandedState(mockedStep1.step);
clickListenerSpy.onClick(mock(View.class));
verify(stepperSpy).collapseOtherSteps(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void continueButtonOnClickListener_ShouldCallCompleteStep() {
ArgumentCaptor<View.OnClickListener> captor = ArgumentCaptor.forClass(View.OnClickListener.class);
stepperSpy.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setOnClickListener(captor.capture());
View.OnClickListener clickListenerSpy = spy(captor.getValue());
doNothing().when(stepperSpy).attemptStepCompletion(mockedStep1.step);
clickListenerSpy.onClick(mock(View.class));
verify(stepperSpy).attemptStepCompletion(mockedStep1.step);
}
@Test
public void attemptStepCompletion_HasValidator_ShouldSetErrorAndRelayout() {
StepValidator validator = mock(StepValidator.class);
String error = "error";
ValidationResult result = new ValidationResult(error);
when(validator.validate(mockedStep1.innerView, false)).thenReturn(result);
stepperSpy.setStepValidator(validator);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).setError(error);
verify(stepperSpy).requestLayout();
}
@Test
public void attemptStepCompletion_ShouldCollapseCompleteCurrentStep() {
mockActiveState(mockedStep1, true);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
verify(stepperSpy).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void attemptStepCompletion_ShouldExpandNextStep() {
mockActiveState(mockedStep1, true);
mockActiveState(mockedStep2, false);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
}
@Test
public void attemptStepCompletion_LastStep_ShouldOnlyCollapseCurrentStep() {
mockActiveState(mockedStep2, true);
stepperSpy.attemptStepCompletion(mockedStep2.step);
verify(stepperSpy).attemptStepCompletion(mockedStep2.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
verify(stepperSpy).toggleActiveState(mockedStep2.step);
verify(stepperSpy).syncVisibilityWithActiveState(mockedStep2.step);
verifyNoMoreInteractions(stepperSpy);
}
@Test
public void collapseOtherSteps_ShouldCollapseAnyOtherActiveSteps() {
mockActiveState(mockedStep1, true);
mockActiveState(mockedStep2, true);
stepperSpy.collapseOtherSteps(mockedStep1.step);
verify(stepperSpy, never()).toggleStepExpandedState(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
}
@Test
public void collapseOtherSteps_ShouldNotCollapseListenerStep() {
mockActiveState(mockedStep1, true);
stepper.collapseOtherSteps(mockedStep1.step);
verify(stepperSpy, never()).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void toggleStepExpandedState_ShouldToggleActiveStateAndSyncVisibility() {
stepperSpy.toggleStepExpandedState(mockedStep1.step);
verify(stepperSpy).toggleActiveState(mockedStep1.step);
verify(stepperSpy).syncVisibilityWithActiveState(mockedStep1.step);
}
@Test
public void measureActiveView_ShouldMeasureActiveViewAccountingForUsedSpace() {
int currentHeight = 30;
int horizontalPadding = 40;
doReturn(horizontalPadding).when(stepperSpy).calculateHorizontalPadding();
VerticalStepper.LayoutParams innerLp = createTestLayoutParams(5, 10, 5, 10);
innerLp.width = VerticalStepper.LayoutParams.WRAP_CONTENT;
innerLp.height = VerticalStepper.LayoutParams.WRAP_CONTENT;
when(mockedStep1.innerView.getLayoutParams()).thenReturn(innerLp);
int innerHorizontalUsedSpace = 20;
when(mockedStep1.step.calculateHorizontalUsedSpace(mockedStep1.innerView))
.thenReturn(innerHorizontalUsedSpace);
int innerVerticalUsedSpace = 20;
when(mockedStep1.step.calculateVerticalUsedSpace(mockedStep1.innerView))
.thenReturn(innerVerticalUsedSpace);
int maxWidth = 1080;
int maxHeight = 1920;
int wms = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST);
int hms = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST);
int expectedWidthSpec = View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST);
int expectedHeightSpec = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST);
doReturn(expectedWidthSpec).when(stepperSpy).nonStaticGetChildMeasureSpec(eq(wms), anyInt(), anyInt());
doReturn(expectedHeightSpec).when(stepperSpy).nonStaticGetChildMeasureSpec(eq(hms), anyInt(), anyInt());
stepperSpy.measureActiveView(mockedStep1.step, mockedStep1.innerView, wms, hms, currentHeight);
verify(stepperSpy).nonStaticGetChildMeasureSpec(wms, horizontalPadding + innerHorizontalUsedSpace,
VerticalStepper.LayoutParams.WRAP_CONTENT);
verify(stepperSpy).nonStaticGetChildMeasureSpec(hms, currentHeight + innerVerticalUsedSpace,
VerticalStepper.LayoutParams.WRAP_CONTENT);
verify(mockedStep1.innerView).measure(expectedWidthSpec, expectedHeightSpec);
}
}
public static class GivenStepperSpyWithTwoStepsAndInnerViewIds extends GivenStepperSpyWithTwoSteps {
private int innerViewId1;
private int innerViewId2;
@Before
public void givenStepperSpyWithTwoStepsAndInnerViewIds() {
innerViewId1 = 21;
innerViewId2 = 22;
when(mockedStep1.innerView.getId()).thenReturn(innerViewId1);
when(mockedStep2.innerView.getId()).thenReturn(innerViewId2);
doNothing().when(stepperSpy).invalidate();
}
@Test
public void setStepSummary_UnrecognizedViewId_ShouldDoNothing() {
stepperSpy.setStepSummary(-1, "summary");
verify(mockedStep1.step, never()).setSummary(anyString());
verify(stepperSpy, never()).invalidate();
}
@Test
public void setStepSummary_ShouldSetStepSummaryAndInvalidate() {
String summary = "summary";
stepperSpy.setStepSummary(innerViewId1, summary);
verify(mockedStep1.step).setSummary(summary);
verify(stepperSpy).invalidate();
}
}
public static class GivenStepperSpyWithTwoStepsAndStandardActiveDimensions extends GivenStepperSpyWithTwoSteps {
private static final int MAX_WIDTH = 1080;
private static final int MAX_HEIGHT = 1920;
private static final int WMS = View.MeasureSpec.makeMeasureSpec(MAX_WIDTH, View.MeasureSpec.AT_MOST);
private static final int HMS = View.MeasureSpec.makeMeasureSpec(MAX_HEIGHT, View.MeasureSpec.AT_MOST);
private static final int VERTICAL_PADDING = 30;
private static final int DECORATOR_HEIGHT = 30;
private static final int INNER_ACTIVE_HEIGHT = 200;
private static final int CONTINUE_ACTIVE_HEIGHT = 50;
private static final int BOTTOM_MARGIN = 30;
@Before
public void givenStepperSpyWithExactlyTwoStepsAndStandardActiveDimensions() {
doNothing()
.when(stepperSpy).measureActiveView(any(Step.class), any(View.class), anyInt(), anyInt(), anyInt());
doReturn(VERTICAL_PADDING).when(stepperSpy).calculateVerticalPadding();
doReturn(DECORATOR_HEIGHT).when(mockedStep1.step).getDecoratorHeight();
doReturn(DECORATOR_HEIGHT).when(mockedStep2.step).getDecoratorHeight();
doReturn(INNER_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.innerView);
doReturn(INNER_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep2.step, mockedStep2.innerView);
doReturn(CONTINUE_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.continueButton);
doReturn(CONTINUE_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep2.step, mockedStep2.continueButton);
doReturn(BOTTOM_MARGIN).when(mockedStep1.step).getBottomMarginHeight();
doReturn(0).when(mockedStep2.step).getBottomMarginHeight();
}
@Test
public void measureActiveViews_ShouldMeasureActiveViewsAccountingForDecorator() {
doReturn(0).when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.innerView);
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.innerView, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
}
@Test
public void measureActiveViews_ShouldMeasureNavButtonsAccountingForInnerView() {
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT);
}
@Test
public void measureActiveViews_ShouldMeasureActiveViewsAccountingForBottomMargin() {
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.innerView, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep2.step, mockedStep2.innerView, WMS, HMS,
VERTICAL_PADDING + 2 * DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT
+ CONTINUE_ACTIVE_HEIGHT + BOTTOM_MARGIN);
verify(stepperSpy).measureActiveView(mockedStep2.step, mockedStep2.continueButton, WMS, HMS,
VERTICAL_PADDING + 2 * (DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT)
+ CONTINUE_ACTIVE_HEIGHT + BOTTOM_MARGIN);
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawMethods() {
doNothing().when(stepperSpy).drawIcon(same(canvas), any(Step.class), anyInt());
doNothing().when(stepperSpy).drawText(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawConnector(same(canvas), any(Step.class), anyInt());
}
@Test
public void doDraw_ShouldCallDrawIconTwice() {
InOrder order = inOrder(stepperSpy);
stepperSpy.doDraw(canvas);
order.verify(stepperSpy).drawIcon(canvas, mockedStep1.step, 1);
order.verify(stepperSpy).drawIcon(canvas, mockedStep2.step, 2);
}
@Test
public void doDraw_ShouldCallDrawTextTwice() {
InOrder order = inOrder(stepperSpy);
stepperSpy.doDraw(canvas);
order.verify(stepperSpy).drawText(canvas, mockedStep1.step);
order.verify(stepperSpy).drawText(canvas, mockedStep2.step);
}
@Test
public void doDraw_ShouldCallDrawConnectorOnce() {
int distanceToNextStep = 300;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
stepperSpy.doDraw(canvas);
verify(stepperSpy).drawConnector(canvas, mockedStep1.step, distanceToNextStep);
}
@Test
public void doDraw_ShouldTranslateByDistanceToNextStep() {
InOrder order = inOrder(canvas);
int leftPadding = 10;
int topPadding = 20;
int rightPadding = 5;
int bottomPadding = 15;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int distanceToNextStep = 300;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
stepperSpy.doDraw(canvas);
// first translate for the left and top padding
order.verify(canvas).translate(stepperSpy.outerHorizontalPadding + leftPadding,
stepperSpy.outerVerticalPadding + topPadding);
// translate for the first step
order.verify(canvas).translate(0, 0);
// translate for the second step
order.verify(canvas).translate(0, distanceToNextStep);
// finally translate for the right and bottom padding
order.verify(canvas).translate(stepperSpy.outerHorizontalPadding + rightPadding,
stepperSpy.outerVerticalPadding + bottomPadding);
}
@Test
public void doDraw_ShouldSaveAndRestoreForEachChild() {
InOrder order = inOrder(canvas);
stepperSpy.doDraw(canvas);
// for all of doDraw
order.verify(canvas).save();
// first step
order.verify(canvas).save();
order.verify(canvas).restore();
// second step
order.verify(canvas).save();
order.verify(canvas).restore();
// for all of doDraw
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawIconMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawIconMethods() {
doNothing().when(stepperSpy).drawIconBackground(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawIconError(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawIconText(same(canvas), any(Step.class), anyInt());
}
@Test
public void doDraw_HasError_ShouldCallDrawIconError() {
when(mockedStep1.step.hasError()).thenReturn(true);
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
verify(stepperSpy).drawIconError(canvas, mockedStep1.step);
}
@Test
public void drawIcon_ShouldCallDrawIconBackgroundAndDrawIconText() {
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
verify(stepperSpy).drawIconBackground(canvas, mockedStep1.step);
verify(stepperSpy).drawIconText(canvas, mockedStep1.step, 1);
}
@Test
public void drawIcon_ShouldCallSaveAndRestore() {
InOrder order = inOrder(canvas);
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
order.verify(canvas).save();
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawTextMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawTextMethods() {
doNothing().when(stepperSpy).drawTitle(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawSubtitle(same(canvas), any(Step.class));
}
@Test
public void drawText_ShouldCallDrawTitleAndDrawSubtitle() {
stepperSpy.drawText(canvas, mockedStep1.step);
verify(stepperSpy).drawTitle(canvas, mockedStep1.step);
verify(stepperSpy).drawSubtitle(canvas, mockedStep1.step);
}
@Test
public void drawText_ShouldSaveTranslateByIconWidthAndRestoreCanvas() {
InOrder order = inOrder(canvas);
int iconWidth = 40;
when(mockedStep1.step.calculateStepDecoratorIconWidth()).thenReturn(iconWidth);
stepperSpy.drawText(canvas, mockedStep1.step);
order.verify(canvas).save();
order.verify(canvas).translate(iconWidth, 0);
order.verify(canvas).restore();
}
}
public static abstract class GivenStepperSpyWithTwoStepsAndMockCanvas extends GivenStepperSpyWithTwoSteps {
Canvas canvas;
@Before
public void givenStepperSpyWithTwoStepsAndMockCanvas() {
canvas = mock(Canvas.class);
}
}
public static class GivenStepperSpyWithExactlyTwoStepsAndMockCanvas
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Test
public void drawIconError_ShouldDrawErrorBitmap() {
when(mockedStep1.step.hasError()).thenReturn(true);
Bitmap bitmap = mock(Bitmap.class);
when(mockedStep1.step.getIconErrorBitmap()).thenReturn(bitmap);
stepperSpy.drawIconError(canvas, mockedStep1.step);
verify(canvas).drawBitmap(bitmap, 0, 0, null);
}
@Test
public void drawIconBackground_ShouldDrawCircleWithIconColor() {
Paint color = mock(Paint.class);
RectF rect = mock(RectF.class);
when(mockedStep1.step.getIconBackground()).thenReturn(color);
when(mockedStep1.step.getTempRectForIconBackground()).thenReturn(rect);
stepperSpy.drawIconBackground(canvas, mockedStep1.step);
verify(canvas).drawArc(rect, 0f, 360f, true, color);
}
@Test
public void drawIconText_ShouldDrawStepNumber() {
TextPaint paint = mock(TextPaint.class);
Rect rect = mock(Rect.class);
PointF point = mock(PointF.class);
when(mockedStep1.step.getIconTextPaint()).thenReturn(paint);
when(mockedStep1.step.getTempRectForIconTextBounds()).thenReturn(rect);
when(mockedStep1.step.getTempPointForIconTextCenter()).thenReturn(point);
int stepNumber = 4;
stepperSpy.drawIconText(canvas, mockedStep1.step, stepNumber);
String stepNumberString = String.valueOf(stepNumber);
verify(canvas).drawText(eq(stepNumberString), anyFloat(), anyFloat(), same(paint));
}
@Test
public void drawTitle_ShouldDrawTextWithStepTitle() {
TextPaint paint = mock(TextPaint.class);
String title = "vertical stepper";
float titleBaseline = 20f;
when(mockedStep1.step.getTitle()).thenReturn(title);
when(mockedStep1.step.getTitleTextPaint()).thenReturn(paint);
when(mockedStep1.step.getTitleBaselineRelativeToStepTop()).thenReturn(titleBaseline);
stepperSpy.drawTitle(canvas, mockedStep1.step);
verify(canvas).drawText(title, 0, titleBaseline, paint);
}
@Test
public void drawSubtitle_WhenEmpty_ShouldNotDraw() {
TextPaint paint = mock(TextPaint.class);
when(mockedStep1.step.getSubtitleTextPaint()).thenReturn(paint);
when(mockedStep1.step.getSubtitle()).thenReturn("");
stepperSpy.drawSubtitle(canvas, mockedStep1.step);
verify(canvas, never()).drawText(anyString(), anyFloat(), anyFloat(), eq(paint));
}
@Test
public void drawSubtitle_NotEmpty_ShouldTranslateAndDraw() {
InOrder order = inOrder(canvas);
String subtitle = "subtitle";
when(mockedStep1.step.getSubtitle()).thenReturn(subtitle);
float titleBottom = 15f;
when(mockedStep1.step.getTitleBottomRelativeToStepTop()).thenReturn(titleBottom);
float subtitleBaseline = 20f;
when(mockedStep1.step.getSubtitleBaselineRelativeToTitleBottom()).thenReturn(subtitleBaseline);
TextPaint paint = mock(TextPaint.class);
when(mockedStep1.step.getSubtitleTextPaint()).thenReturn(paint);
stepperSpy.drawSubtitle(canvas, mockedStep1.step);
order.verify(canvas).translate(0, titleBottom);
order.verify(canvas).drawText(subtitle, 0, subtitleBaseline, paint);
}
@Test
public void drawConnector_ShouldSaveTranslateDrawAndRestore() {
InOrder order = inOrder(canvas);
Paint paint = mock(Paint.class);
float strokeWidth = 3f;
when(paint.getStrokeWidth()).thenReturn(strokeWidth);
when(mockedStep1.step.getConnectorPaint()).thenReturn(paint);
stepperSpy.drawConnector(canvas, mockedStep1.step, 0);
order.verify(canvas).save();
order.verify(canvas).translate(anyFloat(), anyFloat());
order.verify(canvas).drawLine(anyFloat(), anyFloat(), anyFloat(), anyFloat(), same(paint));
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedLayoutActiveViewMethod
extends GivenStepperSpyWithTwoSteps {
private Rect rect;
@Before
public void givenStepperSpyWithTwoStepsAndStubbedLayoutActiveViewMethod() {
rect = mock(Rect.class);
doNothing().when(stepperSpy).layoutActiveView(same(rect), any(View.class));
}
@Test
public void layoutInnerView_ShouldCallLayoutActiveViewWithInnerView() {
stepperSpy.layoutInnerView(rect, mockedStep1.step);
verify(stepperSpy).layoutActiveView(rect, mockedStep1.innerView);
}
@Test
public void layoutNavButtons_ShouldCallLayoutActiveViewWithContinueButton() {
stepperSpy.layoutNavButtons(rect, mockedStep1.step);
verify(stepperSpy).layoutActiveView(rect, mockedStep1.continueButton);
}
}
public static abstract class GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoSteps {
static class CaptureRectAnswer implements Answer<Void> {
private final Rect rectToCaptureArg;
CaptureRectAnswer(Rect rectToCaptureArg) {
this.rectToCaptureArg = rectToCaptureArg;
}
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Rect rect = invocation.getArgument(0);
rectToCaptureArg.set(rect);
return null;
}
}
@Before
public void givenStepperSpyWithTwoStepsAndStubbedLayoutMethods() {
doNothing().when(stepperSpy).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
doNothing().when(stepperSpy).layoutInnerView(any(Rect.class), any(Step.class));
doNothing().when(stepperSpy).layoutNavButtons(any(Rect.class), any(Step.class));
when(mockedStep1.step.getTempRectForLayout()).thenReturn(new Rect());
}
}
@SuppressLint("WrongCall") // Explicitly testing onLayout
public static class GivenStepperSpyWithTwoInactiveStepsAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods {
@Before
public void givenStepperSpyWithTwoInactiveStepsAndStubbedLayoutMethods() {
when(mockedStep1.step.isActive()).thenReturn(false);
when(mockedStep2.step.isActive()).thenReturn(false);
}
@Test
public void onLayout_ShouldNotCallLayoutInnerViewOrLayoutNavButtons() {
stepperSpy.onLayout(true, 0, 0, 0, 0);
verify(stepperSpy, times(2)).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
verify(stepperSpy, never()).layoutInnerView(any(Rect.class), any(Step.class));
verify(stepperSpy, never()).layoutNavButtons(any(Rect.class), any(Step.class));
}
@Test
public void onLayout_ShouldAdjustTouchForPadding() {
int leftPadding = 8;
int topPadding = 20;
int rightPadding = 4;
int bottomPadding = 10;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int left = 0;
int top = 0;
int right = 400;
int bottom = 200;
stepperSpy.onLayout(true, left, top, right, bottom);
ArgumentCaptor<Rect> rectCaptor = ArgumentCaptor.forClass(Rect.class);
verify(stepperSpy).layoutTouchView(rectCaptor.capture(), same(mockedStep1.touchView));
Rect touchRect = rectCaptor.getValue();
assertThat(touchRect.left).isEqualTo(stepperSpy.outerHorizontalPadding + leftPadding);
assertThat(touchRect.top).isEqualTo(stepperSpy.outerVerticalPadding + topPadding);
assertThat(touchRect.right).isEqualTo(right - stepperSpy.outerHorizontalPadding - rightPadding);
assertThat(touchRect.bottom).isEqualTo(bottom - stepperSpy.outerVerticalPadding - bottomPadding);
}
@Test
public void onLayout_ShouldAdjustNextTopForPreviousStepHeight() {
InOrder order = inOrder(stepperSpy);
int distanceToNextStep = 400;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
final Rect firstRect = new Rect();
final Rect secondRect = new Rect();
doAnswer(new CaptureRectAnswer(firstRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
doAnswer(new CaptureRectAnswer(secondRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep2.touchView));
stepperSpy.onLayout(true, 0, 0, 0, 0);
order.verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
order.verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep2.touchView));
int firstStepTop = firstRect.top;
int secondStepTop = secondRect.top;
assertThat(secondStepTop).isEqualTo(firstStepTop + distanceToNextStep);
}
@Test
public void onLayout_NonZeroLeft_ShouldAdjustForLeftOffset() {
int left = 50;
int right = 300;
final Rect touchRect = new Rect();
doAnswer(new CaptureRectAnswer(touchRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
stepperSpy.onLayout(true, left, 0, right, 0);
verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
assertThat(touchRect.left).isEqualTo(stepperSpy.outerHorizontalPadding);
assertThat(touchRect.right).isEqualTo(right - left - stepperSpy.outerHorizontalPadding);
}
@Test
public void onLayout_NonZeroTop_ShouldAdjustForTopOffset() {
int top = 50;
int bottom = 300;
final Rect touchRect = new Rect();
doAnswer(new CaptureRectAnswer(touchRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
stepperSpy.onLayout(true, 0, top, 0, bottom);
verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
assertThat(touchRect.top).isEqualTo(stepperSpy.outerVerticalPadding);
assertThat(touchRect.bottom).isEqualTo(bottom - top - stepperSpy.outerVerticalPadding);
}
}
@SuppressLint("WrongCall") // Explicitly testing onLayout
public static class GivenStepperSpyWithTwoStepsOneActiveAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods {
@Before
public void givenStepperSpyWithTwoStepsOneActiveAndStubbedLayoutMethods() {
when(mockedStep1.step.isActive()).thenReturn(true);
when(mockedStep2.step.isActive()).thenReturn(false);
}
@Test
public void onLayout_ShouldCallLayoutInnerViewAndLayoutNavButtons() {
stepperSpy.onLayout(true, 0, 0, 0, 0);
verify(stepperSpy, times(2)).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
verify(stepperSpy).layoutInnerView(any(Rect.class), any(Step.class));
verify(stepperSpy).layoutNavButtons(any(Rect.class), any(Step.class));
}
@Test
public void onLayout_ShouldAdjustInnerViewForPaddingAndStepDecorators() {
int distanceToTextBottom = 80;
when(mockedStep1.step.calculateYDistanceToTextBottom()).thenReturn(distanceToTextBottom);
int iconWidth = 40;
when(mockedStep1.step.calculateStepDecoratorIconWidth()).thenReturn(iconWidth);
int leftPadding = 8;
int topPadding = 20;
int rightPadding = 4;
int bottomPadding = 10;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
final Rect innerRect = new Rect();
doAnswer(new CaptureRectAnswer(innerRect))
.when(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
int left = 0;
int top = 0;
int right = 400;
int bottom = 200;
stepperSpy.onLayout(true, left, top, right, bottom);
verify(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
assertThat(innerRect.left)
.isEqualTo(leftPadding + stepperSpy.outerHorizontalPadding + iconWidth);
assertThat(innerRect.top)
.isEqualTo(stepperSpy.outerVerticalPadding + topPadding + distanceToTextBottom);
assertThat(innerRect.right)
.isEqualTo(right - left - stepperSpy.outerHorizontalPadding - rightPadding);
assertThat(innerRect.bottom)
.isEqualTo(bottom - top - stepperSpy.outerVerticalPadding - bottomPadding);
}
@Test
public void onLayout_ShouldAdjustButtonsTopForInnerViewHeight() {
InOrder order = inOrder(stepperSpy);
when(mockedStep1.step.isActive()).thenReturn(true);
int innerHeight = 400;
when(mockedStep1.innerView.getHeight()).thenReturn(innerHeight);
final Rect innerRect = new Rect();
final Rect navRect = new Rect();
doAnswer(new CaptureRectAnswer(innerRect))
.when(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
doAnswer(new CaptureRectAnswer(navRect))
.when(stepperSpy).layoutNavButtons(any(Rect.class), same(mockedStep1.step));
stepperSpy.onLayout(true, 0, 0, 0, 0);
order.verify(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
order.verify(stepperSpy).layoutNavButtons(any(Rect.class), same(mockedStep1.step));
int innerTop = innerRect.top;
int buttonsTop = navRect.top;
assertThat(buttonsTop).isEqualTo(innerTop + innerHeight);
}
}
}
| UTF-8 | Java | 65,772 | java | VerticalStepperTest.java | Java | [] | null | [] | package com.snowble.android.widget.verticalstepper;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Parcelable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.AppCompatButton;
import android.text.TextPaint;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.Robolectric;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.*;
import static org.mockito.Mockito.*;
@RunWith(Enclosed.class)
public class VerticalStepperTest {
private static class MockedStep {
View innerView;
VerticalStepper.LayoutParams innerLayoutParams;
VerticalStepper.InternalTouchView touchView;
AppCompatButton continueButton;
VerticalStepper.LayoutParams continueLayoutParams;
Step step;
MockedStep() {
innerView = mock(View.class);
innerLayoutParams = mock(VerticalStepper.LayoutParams.class);
when(innerView.getLayoutParams()).thenReturn(innerLayoutParams);
continueButton = mock(AppCompatButton.class);
continueLayoutParams = mock(VerticalStepper.LayoutParams.class);
when(continueButton.getLayoutParams()).thenReturn(continueLayoutParams);
touchView = mock(VerticalStepper.InternalTouchView.class);
step = mock(Step.class);
when(step.getInnerView()).thenReturn(innerView);
when(step.getTouchView()).thenReturn(touchView);
when(step.getContinueButton()).thenReturn(continueButton);
}
}
public abstract static class GivenAStepper extends GivenAnActivity {
VerticalStepper stepper;
@Before
public void givenAStepper() {
stepper = new VerticalStepper(activity);
}
void mockActiveState(MockedStep step, boolean isActive) {
when(step.step.isActive()).thenReturn(isActive);
int visibility = isActive ? View.VISIBLE : View.GONE;
when(step.innerView.getVisibility()).thenReturn(visibility);
when(step.continueButton.getVisibility()).thenReturn(visibility);
}
}
public static class GivenZeroSteps extends GivenAStepper {
private int getColor(int colorRes) {
return ResourcesCompat.getColor(activity.getResources(), colorRes, activity.getTheme());
}
@SuppressLint("PrivateResource") // https://code.google.com/p/android/issues/detail?id=230985
@Test
public void initPropertiesFromAttrs_NoAttrsSet_ShouldUseDefaults() {
stepper.initPropertiesFromAttrs(null, 0, 0);
assertThat(stepper.iconActiveColor).isEqualTo(getColor(R.color.bg_active_icon));
assertThat(stepper.iconInactiveColor).isEqualTo(getColor(R.color.bg_inactive_icon));
assertThat(stepper.iconCompleteColor).isEqualTo(stepper.iconActiveColor);
assertThat(stepper.continueButtonStyle)
.isEqualTo(android.support.v7.appcompat.R.style.Widget_AppCompat_Button_Colored);
}
@SuppressLint("PrivateResource") // https://code.google.com/p/android/issues/detail?id=230985
@Test
public void initPropertiesFromAttrs_AttrsSet_ShouldUseAttrs() {
Robolectric.AttributeSetBuilder builder = Robolectric.buildAttributeSet();
builder.addAttribute(R.attr.iconColorActive, "@android:color/black");
builder.addAttribute(R.attr.iconColorInactive, "@android:color/darker_gray");
builder.addAttribute(R.attr.iconColorComplete, "@android:color/holo_orange_dark");
builder.addAttribute(R.attr.continueButtonStyle, "@style/Widget.AppCompat.Button.Borderless");
stepper.initPropertiesFromAttrs(builder.build(), 0, 0);
assertThat(stepper.iconActiveColor).isEqualTo(getColor(android.R.color.black));
assertThat(stepper.iconInactiveColor).isEqualTo(getColor(android.R.color.darker_gray));
assertThat(stepper.iconCompleteColor).isEqualTo(getColor(android.R.color.holo_orange_dark));
assertThat(stepper.continueButtonStyle)
.isEqualTo(android.support.v7.appcompat.R.style.Widget_AppCompat_Button_Borderless);
}
@Test
public void initSteps_ShouldHaveEmptyInnerViews() {
stepper.initSteps(null);
assertThat(stepper.steps).isEmpty();
}
@Test
public void calculateWidth_ShouldReturnHorizontalPadding() {
int width = stepper.calculateWidth();
assertThat(width)
.isEqualTo(stepper.calculateHorizontalPadding());
}
@Test
public void doMeasurement_UnspecifiedSpecs_ShouldMeasurePadding() {
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.doMeasurement(ms, ms);
assertThat(stepper.getMeasuredHeight()).isEqualTo(stepper.calculateVerticalPadding());
assertThat(stepper.getMeasuredWidth()).isEqualTo(stepper.calculateHorizontalPadding());
}
@Test
public void doMeasurement_AtMostSpecsRequiresClipping_ShouldMeasureToAtMostValues() {
int width = stepper.calculateHorizontalPadding() / 2;
int height = stepper.calculateVerticalPadding() / 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void doMeasurement_ExactlySpecsRequiresClipping_ShouldMeasureToExactValues() {
int width = stepper.calculateHorizontalPadding() / 2;
int height = stepper.calculateVerticalPadding() / 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void doMeasurement_ExactlySpecsRequiresExpanding_ShouldMeasureToExactValues() {
int width = stepper.calculateHorizontalPadding() * 2;
int height = stepper.calculateVerticalPadding() * 2;
int wms = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int hms = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
stepper.doMeasurement(wms, hms);
assertThat(stepper.getMeasuredWidth()).isEqualTo(width);
assertThat(stepper.getMeasuredHeight()).isEqualTo(height);
}
@Test
public void calculateHeight_ShouldReturnVerticalPadding() {
int width = stepper.calculateHeight();
assertThat(width)
.isEqualTo(stepper.calculateVerticalPadding());
}
@Test
public void calculateHorizontalPadding_ShouldReturnAllPadding() {
int horizontalPadding = stepper.calculateHorizontalPadding();
assertThat(horizontalPadding)
.isEqualTo((stepper.outerHorizontalPadding * 2) +
stepper.getPaddingLeft() + stepper.getPaddingRight());
}
@Test
public void calculateVerticalPadding_ShouldReturnAllPadding() {
int verticalPadding = stepper.calculateVerticalPadding();
assertThat(verticalPadding)
.isEqualTo((stepper.outerVerticalPadding * 2) +
stepper.getPaddingTop() + stepper.getPaddingBottom());
}
@Test
public void layoutTouchView_WhenNotEnoughSpace_ShouldClip() {
int leftPadding = 20;
int topPadding = 4;
int rightPadding = 10;
int bottomPadding = 2;
stepper.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int adjustedLeft = left + stepper.outerHorizontalPadding + leftPadding;
int adjustedTop = top + stepper.outerVerticalPadding + topPadding;
int adjustedRight = right - stepper.outerHorizontalPadding - rightPadding;
int adjustedBottom = bottom - stepper.outerVerticalPadding - bottomPadding;
VerticalStepper.InternalTouchView touchView = mock(VerticalStepper.InternalTouchView.class);
when(touchView.getMeasuredHeight()).thenReturn(bottom * 2);
stepper.layoutTouchView(new Rect(adjustedLeft, adjustedTop, adjustedRight, adjustedBottom), touchView);
verify(touchView).layout(eq(left + leftPadding), eq(top + topPadding),
eq(right - left - rightPadding), eq(bottom - top - bottomPadding));
}
@Test
public void layoutTouchView_WhenEnoughSpace_ShouldUseFullWidthAndMeasuredHeight() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int adjustedLeft = left + stepper.outerHorizontalPadding;
int adjustedTop = top + stepper.outerVerticalPadding;
int adjustedRight = right - stepper.outerHorizontalPadding;
int adjustedBottom = bottom - stepper.outerVerticalPadding;
VerticalStepper.InternalTouchView touchView = mock(VerticalStepper.InternalTouchView.class);
int touchMeasuredHeight = bottom / 2;
when(touchView.getMeasuredHeight()).thenReturn(touchMeasuredHeight);
stepper.layoutTouchView(new Rect(adjustedLeft, adjustedTop, adjustedRight, adjustedBottom), touchView);
verify(touchView).layout(eq(left), eq(top), eq(right - left), eq(top + touchMeasuredHeight));
}
@Test
public void layoutActiveView_WhenNotEnoughSpace_ShouldClip() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
int leftMargin = 5;
int topMargin = 20;
int rightMargin = 10;
int bottomMargin = 15;
View activeView = mock(View.class);
when(activeView.getMeasuredWidth()).thenReturn(right * 2);
when(activeView.getMeasuredHeight()).thenReturn(bottom * 2);
when(activeView.getLayoutParams()).thenReturn(
createTestLayoutParams(leftMargin, topMargin, rightMargin, bottomMargin));
stepper.layoutActiveView(new Rect(left, top, right, bottom), activeView);
verify(activeView).layout(eq(left + leftMargin), eq(top + topMargin),
eq(right - rightMargin), eq(bottom - bottomMargin));
}
@Test
public void layoutActiveView_WhenEnoughSpace_ShouldUseFullWidthAndMeasuredHeight() {
int left = 0;
int top = 0;
int right = 300;
int bottom = 500;
View activeView = mock(View.class);
int measuredWidth = right / 2;
when(activeView.getMeasuredWidth()).thenReturn(measuredWidth);
int measuredHeight = bottom / 2;
when(activeView.getMeasuredHeight()).thenReturn(measuredHeight);
when(activeView.getLayoutParams()).thenReturn(mock(VerticalStepper.LayoutParams.class));
stepper.layoutActiveView(new Rect(left, top, right, bottom), activeView);
verify(activeView).layout(eq(left), eq(top), eq(left + measuredWidth), eq(top + measuredHeight));
}
}
public abstract static class GivenOneStep extends GivenAStepper {
MockedStep mockedStep1;
@Before
public void givenOneStep() {
mockedStep1 = new MockedStep();
stepper.steps.add(mockedStep1.step);
clearInvocations(mockedStep1.innerView);
clearInvocations(mockedStep1.innerLayoutParams);
clearInvocations(mockedStep1.continueButton);
clearInvocations(mockedStep1.continueLayoutParams);
clearInvocations(mockedStep1.touchView);
clearInvocations(mockedStep1.step);
}
void mockStep1Widths(int decoratorWidth, int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
mockStepWidths(mockedStep1, decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
}
void mockStepWidths(MockedStep mockedStep, int decoratorWidth,
int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
when(mockedStep.step.calculateStepDecoratorWidth()).thenReturn(decoratorWidth);
when(mockedStep.step.calculateHorizontalUsedSpace(mockedStep.innerView)).thenReturn(innerUsedSpace);
when(mockedStep.innerView.getMeasuredWidth()).thenReturn(innerWidth);
when(mockedStep.step.calculateHorizontalUsedSpace(mockedStep.continueButton)).thenReturn(continueUsedSpace);
when(mockedStep.continueButton.getMeasuredWidth()).thenReturn(continueWidth);
}
void mockStepHeights(int decoratorHeight, int childrenVisibleHeight, int bottomMarginHeight, Step step) {
when(step.getDecoratorHeight()).thenReturn(decoratorHeight);
when(step.getChildrenVisibleHeight()).thenReturn(childrenVisibleHeight);
when(step.getBottomMarginHeight()).thenReturn(bottomMarginHeight);
}
}
public static class GivenExactlyOneStep extends GivenOneStep {
@Test
public void initInnerView_ShouldInitializeStepViews() {
assertThat(stepper.steps)
.hasSize(1)
.doesNotContainNull();
Step step = stepper.steps.get(0);
assertThat(step.getTouchView())
.isNotNull();
assertThat(step.getContinueButton())
.isNotNull();
}
@Test
public void initTouchView_ShouldSetClickListener() {
stepper.initTouchView(mockedStep1.step);
verify(mockedStep1.touchView).setOnClickListener((View.OnClickListener) notNull());
}
@Test
public void initTouchView_ShouldAttachToStepper() {
stepper.initTouchView(mockedStep1.step);
assertThat(stepper.getChildCount()).isEqualTo(1);
}
@Test
public void initNavButtons_ShouldSetTextToContinue() {
stepper.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setText(R.string.continue_button);
}
@Test
public void initNavButtons_ShouldSetLayoutParamsWithTopMarginAndHeight() {
int height = 80;
int topMargin = 20;
when(mockedStep1.step.getNavButtonHeight()).thenReturn(height);
when(mockedStep1.step.getNavButtonTopMargin()).thenReturn(topMargin);
stepper.initNavButtons(mockedStep1.step);
ArgumentCaptor<VerticalStepper.LayoutParams> lpCaptor =
ArgumentCaptor.forClass(VerticalStepper.LayoutParams.class);
verify(mockedStep1.continueButton).setLayoutParams(lpCaptor.capture());
VerticalStepper.LayoutParams lp = lpCaptor.getValue();
assertThat(lp.topMargin).isEqualTo(topMargin);
assertThat(lp.height).isEqualTo(height);
}
@Test
public void initNavButtons_ShouldSetClickListener() {
stepper.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setOnClickListener((View.OnClickListener) notNull());
}
@Test
public void initNavButtons_ShouldAttachToStepper() {
stepper.initNavButtons(mockedStep1.step);
assertThat(stepper.getChildCount()).isEqualTo(1);
}
@Test
public void measureBottomMarginHeights_ShouldNotMeasureBottomMarginToNextStep() {
stepper.measureStepBottomMarginHeights();
verify(mockedStep1.step, never()).measureBottomMarginToNextStep();
}
@Test
public void calculateWidth_ShouldReturnHorizontalPaddingAndStepWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = decoratorWidth * 4;
int continueUsedSpace = 30;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int width = stepper.calculateWidth();
assertThat(width)
.isEqualTo(stepper.calculateHorizontalPadding()
+ innerWidth + innerUsedSpace);
}
@Test
public void calculateMaxStepWidth_DecoratorsHaveMaxWidth_ShouldReturnDecoratorsWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 10;
int innerWidth = 0;
int continueUsedSpace = 15;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(decoratorWidth);
}
@Test
public void calculateMaxStepWidth_InnerViewHasMaxWidth_ShouldReturnInnerViewWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = decoratorWidth * 4;
int continueUsedSpace = 15;
int continueWidth = 0;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(innerWidth + innerUsedSpace);
}
@Test
public void calculateMaxStepWidth_NavButtonsHaveMaxWidth_ShouldReturnNavButtonsWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int innerWidth = 0;
int continueUsedSpace = 10;
int continueWidth = decoratorWidth * 4;
mockStep1Widths(decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isEqualTo(continueWidth + continueUsedSpace);
}
@Test
public void calculateHeight_ShouldReturnVerticalPaddingPlusTotalStepHeight() {
int decoratorHeight = 100;
int childrenVisibleHeight = 400;
int bottomMarginHeight = 48;
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep1.step);
int width = stepper.calculateHeight();
assertThat(width)
.isEqualTo(stepper.calculateVerticalPadding()
+ decoratorHeight + childrenVisibleHeight + bottomMarginHeight);
}
@Test
public void layoutActiveViews_ShouldNotModifyInputRect() {
Rect rect = new Rect(1, 2, 3, 4);
stepper.layoutActiveViews(rect, mockedStep1.step);
assertThat(rect).isEqualTo(new Rect(1, 2, 3, 4));
}
}
public static class GivenOneStepAndAStepValidator extends GivenOneStep {
private StepValidator validator;
@Before
public void givenStepperSpyWithExactlyTwoStepsAndAStepValidator() {
validator = mock(StepValidator.class);
when(validator.validate(mockedStep1.innerView, false))
.thenReturn(ValidationResult.VALID_COMPLETE_RESULT);
stepper.setStepValidator(validator);
}
@Test
public void attemptStepCompletion_HasValidator_ShouldCallListenerWithInnerView() {
stepper.attemptStepCompletion(mockedStep1.step);
verify(validator).validate(mockedStep1.innerView, false);
}
@Test
public void attemptStepCompletion_HasValidator_ShoulClearErrorButNotCompleteIfIncomplete() {
when(validator.validate(mockedStep1.innerView, false))
.thenReturn(ValidationResult.VALID_INCOMPLETE_RESULT);
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step, never()).markComplete();
}
@Test
public void attemptStepCompletion_HasValidator_ShouldCompleteIfStepValidAndComplete() {
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
}
@Test
public void attemptStepCompletion_removeStepValidator_ShouldComplete() {
String error = "error";
ValidationResult result = new ValidationResult(error);
when(validator.validate(mockedStep1.innerView, false)).thenReturn(result);
stepper.removeStepValidator();
stepper.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step, never()).setError(error);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
}
}
public static class GivenExactlyOneActiveStep extends GivenOneStep {
@Before
public void givenExactlyOneActiveStep() {
mockActiveState(mockedStep1, true);
}
@Test
public void syncVisibilityWithActiveState_ShouldMakeActiveViewsVisible() {
stepper.syncVisibilityWithActiveState(mockedStep1.step);
verify(mockedStep1.innerView).setVisibility(View.VISIBLE);
verify(mockedStep1.continueButton).setVisibility(View.VISIBLE);
}
@Test
public void measureActiveViews_ShouldHaveActiveViewsHeightsWithActualHeight() {
final int innerViewHeight = 100;
final int buttonHeight = 50;
when(mockedStep1.innerView.getMeasuredHeight()).thenReturn(innerViewHeight);
when(mockedStep1.continueButton.getMeasuredHeight()).thenReturn(buttonHeight);
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.measureActiveViews(ms, ms);
verify(mockedStep1.step).setActiveViewsHeight(innerViewHeight + buttonHeight);
}
}
public static class GivenExactlyOneInactiveStep extends GivenOneStep {
@Before
public void givenExactlyOneInactiveStep() {
mockActiveState(mockedStep1, false);
}
@Test
public void syncVisibilityWithActiveState_ShouldMakeActiveViewsGone() {
stepper.syncVisibilityWithActiveState(mockedStep1.step);
verify(mockedStep1.innerView).setVisibility(View.GONE);
verify(mockedStep1.continueButton).setVisibility(View.GONE);
}
}
public static abstract class GivenTwoSteps extends GivenOneStep {
MockedStep mockedStep2;
@Before
public void givenTwoSteps() {
mockedStep2 = new MockedStep();
stepper.steps.add(mockedStep2.step);
clearInvocations(mockedStep2.innerView);
clearInvocations(mockedStep2.innerLayoutParams);
clearInvocations(mockedStep2.continueButton);
clearInvocations(mockedStep2.continueLayoutParams);
clearInvocations(mockedStep2.touchView);
clearInvocations(mockedStep2.step);
}
void mockStep2Widths(int decoratorWidth, int innerUsedSpace, int innerWidth,
int continueUsedSpace, int continueWidth) {
mockStepWidths(mockedStep2, decoratorWidth, innerUsedSpace, innerWidth, continueUsedSpace, continueWidth);
}
}
public static class GivenExactlyTwoSteps extends GivenTwoSteps {
@Test
public void onSaveInstanceState_ShouldSaveStepStates() {
Parcelable state = stepper.onSaveInstanceState();
verify(mockedStep1.step).generateState();
verify(mockedStep2.step).generateState();
assertThat(state).isInstanceOf(VerticalStepper.SavedState.class);
VerticalStepper.SavedState ss = (VerticalStepper.SavedState) state;
assertThat(ss.stepStates).hasSize(2);
}
@Test
public void measureStepDecoratorHeights_ShouldMeasureStepDecoratorHeightTwice() {
stepper.measureStepDecoratorHeights();
verify(mockedStep1.step).measureStepDecoratorHeight();
verify(mockedStep2.step).measureStepDecoratorHeight();
}
@Test
public void measureBottomMarginHeights_ShouldMeasureBottomMarginToNextStepOnce() {
stepper.measureStepBottomMarginHeights();
verify(mockedStep1.step).measureBottomMarginToNextStep();
}
@Test
public void measureActiveViews_ShouldMeasureViews() {
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
stepper.measureActiveViews(ms, ms);
verify(mockedStep1.innerView).measure(anyInt(), anyInt());
verify(mockedStep2.innerView).measure(anyInt(), anyInt());
verify(mockedStep1.continueButton).measure(anyInt(), anyInt());
verify(mockedStep1.continueButton).measure(anyInt(), anyInt());
}
@Test
public void calculateMaxStepWidth_ShouldReturnLargerStepWidth() {
int decoratorWidth = 20;
int innerUsedSpace = 20;
int continueWidth = 0;
int continueUsedSpace = 10;
int inner1Width = decoratorWidth * 2;
mockStep1Widths(decoratorWidth, innerUsedSpace, inner1Width, continueUsedSpace, continueWidth);
int inner2Width = decoratorWidth * 3;
mockStep2Widths(decoratorWidth, innerUsedSpace, inner2Width, continueUsedSpace, continueWidth);
int maxWidth = stepper.calculateMaxStepWidth();
assertThat(maxWidth)
.isNotEqualTo(inner1Width + innerUsedSpace)
.isEqualTo(inner2Width + innerUsedSpace);
}
@Test
public void calculateHeight_ShouldReturnVerticalPaddingPlusTotalStepHeight() {
int decoratorHeight = 100;
int childrenVisibleHeight = 400;
int bottomMarginHeight = 48;
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep1.step);
mockStepHeights(decoratorHeight, childrenVisibleHeight, bottomMarginHeight, mockedStep2.step);
int height = stepper.calculateHeight();
assertThat(height)
.isEqualTo(stepper.calculateVerticalPadding()
+ (2 * (decoratorHeight + childrenVisibleHeight + bottomMarginHeight)));
}
@Test
public void measureTouchViews_ShouldMeasureAllWidthsAndHeightsExactly() {
int width = 20;
int height = 80;
when(mockedStep1.step.getTouchViewHeight()).thenReturn(height);
when(mockedStep2.step.getTouchViewHeight()).thenReturn(height);
stepper.measureTouchViews(width);
ArgumentCaptor<Integer> wmsCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> hmsCaptor = ArgumentCaptor.forClass(Integer.class);
verify(mockedStep1.touchView).measure(wmsCaptor.capture(), hmsCaptor.capture());
verify(mockedStep2.touchView).measure(wmsCaptor.capture(), hmsCaptor.capture());
for (int actualWms : wmsCaptor.getAllValues()) {
assertThat(View.MeasureSpec.getMode(actualWms)).isEqualTo(View.MeasureSpec.EXACTLY);
assertThat(View.MeasureSpec.getSize(actualWms)).isEqualTo(width);
}
for (int actualHms : hmsCaptor.getAllValues()) {
assertThat(View.MeasureSpec.getMode(actualHms)).isEqualTo(View.MeasureSpec.EXACTLY);
assertThat(View.MeasureSpec.getSize(actualHms)).isEqualTo(height);
}
}
}
public static abstract class GivenStepperSpy extends GivenAStepper {
VerticalStepper stepperSpy;
@Before
public void givenStepperSpy() {
stepperSpy = spy(stepper);
}
}
public static class GivenEmptyStepperSpy extends GivenStepperSpy {
@Test
public void onAttachedToWindow_ShouldInitSteps() {
doNothing().when(stepperSpy).initSteps(null);
stepperSpy.onAttachedToWindow();
verify(stepperSpy).initSteps(null);
}
@SuppressLint("WrongCall") // Explicitly testing onMeasure
@Test
public void onMeasure_ShouldCallDoMeasurement() {
doNothing().when(stepperSpy).doMeasurement(anyInt(), anyInt());
stepperSpy.onMeasure(0, 0);
verify(stepperSpy).doMeasurement(eq(0), eq(0));
}
@SuppressLint("WrongCall") // Explicitly testing onDraw
@Test
public void onDraw_ShouldCallDoDraw() {
Canvas canvas = mock(Canvas.class);
doNothing().when(stepperSpy).doDraw(same(canvas));
stepperSpy.onDraw(canvas);
verify(stepperSpy).doDraw(canvas);
}
}
public static class GivenStepperSpyWithStubbedInitStepsMethods extends GivenStepperSpy {
@Before
public void givenStepperSpyWithStubbedInitStepsMethods() {
View child1 = mock(View.class);
View child2 = mock(View.class);
VerticalStepper.LayoutParams lp = mock(VerticalStepper.LayoutParams.class);
when(lp.getTitle()).thenReturn("title");
when(child1.getLayoutParams()).thenReturn(lp);
when(child2.getLayoutParams()).thenReturn(lp);
// For some reason, calling addView() doesn't update the children properly with the stepperSpy.
// So explicitly set child count and children
doReturn(2).when(stepperSpy).getChildCount();
doReturn(child1).when(stepperSpy).getChildAt(0);
doReturn(child2).when(stepperSpy).getChildAt(1);
doNothing().when(stepperSpy).initTouchView(any(Step.class));
doNothing().when(stepperSpy).initNavButtons(any(Step.class));
doNothing().when(stepperSpy).syncVisibilityWithActiveState(any(Step.class));
}
@Test
public void initSteps_ShouldInitStepsAndChildViews() {
stepperSpy.initSteps(null);
verify(stepperSpy, times(2)).initTouchView(any(Step.class));
verify(stepperSpy, times(2)).initNavButtons(any(Step.class));
verify(stepperSpy, times(2)).syncVisibilityWithActiveState(any(Step.class));
assertThat(stepperSpy.steps).hasSize(2).doesNotContainNull();
}
@Test
public void initSteps_ShouldSetStatesForSteps() {
String summary = "summary";
String error = "error";
List<Step.State> states = Arrays.asList(new Step.State(false, true, null, summary),
new Step.State(true, false, error, null));
VerticalStepper.SavedState state = new VerticalStepper.SavedState(mock(Parcelable.class), states);
stepperSpy.initSteps(state);
Step step1 = stepperSpy.steps.get(0);
assertThat(step1.isActive()).isFalse();
assertThat(step1.isComplete()).isTrue();
assertThat(step1.hasError()).isFalse();
assertThat(step1.getSubtitle()).isEqualTo(summary);
Step step2 = stepperSpy.steps.get(1);
assertThat(step2.isActive()).isTrue();
assertThat(step2.isComplete()).isFalse();
assertThat(step2.hasError()).isTrue();
assertThat(step2.getSubtitle()).isEqualTo(error);
}
}
public static abstract class GivenStepperSpyWithTwoSteps extends GivenStepperSpy {
MockedStep mockedStep1;
MockedStep mockedStep2;
@Before
public void givenStepperSpyWithTwoSteps() {
mockedStep1 = new MockedStep();
mockedStep2 = new MockedStep();
stepperSpy.steps.add(mockedStep1.step);
stepperSpy.steps.add(mockedStep2.step);
}
}
public static class GivenStepperSpyWithExactlyTwoSteps extends GivenStepperSpyWithTwoSteps {
@Test
public void touchViewOnClickListener_ShouldCallCollapseOtherStepsAndToggle() {
ArgumentCaptor<View.OnClickListener> captor = ArgumentCaptor.forClass(View.OnClickListener.class);
stepperSpy.initTouchView(mockedStep1.step);
verify(mockedStep1.touchView).setOnClickListener(captor.capture());
View.OnClickListener clickListenerSpy = spy(captor.getValue());
doNothing().when(stepperSpy).collapseOtherSteps(mockedStep1.step);
doNothing().when(stepperSpy).toggleStepExpandedState(mockedStep1.step);
clickListenerSpy.onClick(mock(View.class));
verify(stepperSpy).collapseOtherSteps(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void continueButtonOnClickListener_ShouldCallCompleteStep() {
ArgumentCaptor<View.OnClickListener> captor = ArgumentCaptor.forClass(View.OnClickListener.class);
stepperSpy.initNavButtons(mockedStep1.step);
verify(mockedStep1.continueButton).setOnClickListener(captor.capture());
View.OnClickListener clickListenerSpy = spy(captor.getValue());
doNothing().when(stepperSpy).attemptStepCompletion(mockedStep1.step);
clickListenerSpy.onClick(mock(View.class));
verify(stepperSpy).attemptStepCompletion(mockedStep1.step);
}
@Test
public void attemptStepCompletion_HasValidator_ShouldSetErrorAndRelayout() {
StepValidator validator = mock(StepValidator.class);
String error = "error";
ValidationResult result = new ValidationResult(error);
when(validator.validate(mockedStep1.innerView, false)).thenReturn(result);
stepperSpy.setStepValidator(validator);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).setError(error);
verify(stepperSpy).requestLayout();
}
@Test
public void attemptStepCompletion_ShouldCollapseCompleteCurrentStep() {
mockActiveState(mockedStep1, true);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(mockedStep1.step).clearError();
verify(mockedStep1.step).markComplete();
verify(stepperSpy).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void attemptStepCompletion_ShouldExpandNextStep() {
mockActiveState(mockedStep1, true);
mockActiveState(mockedStep2, false);
stepperSpy.attemptStepCompletion(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
}
@Test
public void attemptStepCompletion_LastStep_ShouldOnlyCollapseCurrentStep() {
mockActiveState(mockedStep2, true);
stepperSpy.attemptStepCompletion(mockedStep2.step);
verify(stepperSpy).attemptStepCompletion(mockedStep2.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
verify(stepperSpy).toggleActiveState(mockedStep2.step);
verify(stepperSpy).syncVisibilityWithActiveState(mockedStep2.step);
verifyNoMoreInteractions(stepperSpy);
}
@Test
public void collapseOtherSteps_ShouldCollapseAnyOtherActiveSteps() {
mockActiveState(mockedStep1, true);
mockActiveState(mockedStep2, true);
stepperSpy.collapseOtherSteps(mockedStep1.step);
verify(stepperSpy, never()).toggleStepExpandedState(mockedStep1.step);
verify(stepperSpy).toggleStepExpandedState(mockedStep2.step);
}
@Test
public void collapseOtherSteps_ShouldNotCollapseListenerStep() {
mockActiveState(mockedStep1, true);
stepper.collapseOtherSteps(mockedStep1.step);
verify(stepperSpy, never()).toggleStepExpandedState(mockedStep1.step);
}
@Test
public void toggleStepExpandedState_ShouldToggleActiveStateAndSyncVisibility() {
stepperSpy.toggleStepExpandedState(mockedStep1.step);
verify(stepperSpy).toggleActiveState(mockedStep1.step);
verify(stepperSpy).syncVisibilityWithActiveState(mockedStep1.step);
}
@Test
public void measureActiveView_ShouldMeasureActiveViewAccountingForUsedSpace() {
int currentHeight = 30;
int horizontalPadding = 40;
doReturn(horizontalPadding).when(stepperSpy).calculateHorizontalPadding();
VerticalStepper.LayoutParams innerLp = createTestLayoutParams(5, 10, 5, 10);
innerLp.width = VerticalStepper.LayoutParams.WRAP_CONTENT;
innerLp.height = VerticalStepper.LayoutParams.WRAP_CONTENT;
when(mockedStep1.innerView.getLayoutParams()).thenReturn(innerLp);
int innerHorizontalUsedSpace = 20;
when(mockedStep1.step.calculateHorizontalUsedSpace(mockedStep1.innerView))
.thenReturn(innerHorizontalUsedSpace);
int innerVerticalUsedSpace = 20;
when(mockedStep1.step.calculateVerticalUsedSpace(mockedStep1.innerView))
.thenReturn(innerVerticalUsedSpace);
int maxWidth = 1080;
int maxHeight = 1920;
int wms = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST);
int hms = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST);
int expectedWidthSpec = View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST);
int expectedHeightSpec = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST);
doReturn(expectedWidthSpec).when(stepperSpy).nonStaticGetChildMeasureSpec(eq(wms), anyInt(), anyInt());
doReturn(expectedHeightSpec).when(stepperSpy).nonStaticGetChildMeasureSpec(eq(hms), anyInt(), anyInt());
stepperSpy.measureActiveView(mockedStep1.step, mockedStep1.innerView, wms, hms, currentHeight);
verify(stepperSpy).nonStaticGetChildMeasureSpec(wms, horizontalPadding + innerHorizontalUsedSpace,
VerticalStepper.LayoutParams.WRAP_CONTENT);
verify(stepperSpy).nonStaticGetChildMeasureSpec(hms, currentHeight + innerVerticalUsedSpace,
VerticalStepper.LayoutParams.WRAP_CONTENT);
verify(mockedStep1.innerView).measure(expectedWidthSpec, expectedHeightSpec);
}
}
public static class GivenStepperSpyWithTwoStepsAndInnerViewIds extends GivenStepperSpyWithTwoSteps {
private int innerViewId1;
private int innerViewId2;
@Before
public void givenStepperSpyWithTwoStepsAndInnerViewIds() {
innerViewId1 = 21;
innerViewId2 = 22;
when(mockedStep1.innerView.getId()).thenReturn(innerViewId1);
when(mockedStep2.innerView.getId()).thenReturn(innerViewId2);
doNothing().when(stepperSpy).invalidate();
}
@Test
public void setStepSummary_UnrecognizedViewId_ShouldDoNothing() {
stepperSpy.setStepSummary(-1, "summary");
verify(mockedStep1.step, never()).setSummary(anyString());
verify(stepperSpy, never()).invalidate();
}
@Test
public void setStepSummary_ShouldSetStepSummaryAndInvalidate() {
String summary = "summary";
stepperSpy.setStepSummary(innerViewId1, summary);
verify(mockedStep1.step).setSummary(summary);
verify(stepperSpy).invalidate();
}
}
public static class GivenStepperSpyWithTwoStepsAndStandardActiveDimensions extends GivenStepperSpyWithTwoSteps {
private static final int MAX_WIDTH = 1080;
private static final int MAX_HEIGHT = 1920;
private static final int WMS = View.MeasureSpec.makeMeasureSpec(MAX_WIDTH, View.MeasureSpec.AT_MOST);
private static final int HMS = View.MeasureSpec.makeMeasureSpec(MAX_HEIGHT, View.MeasureSpec.AT_MOST);
private static final int VERTICAL_PADDING = 30;
private static final int DECORATOR_HEIGHT = 30;
private static final int INNER_ACTIVE_HEIGHT = 200;
private static final int CONTINUE_ACTIVE_HEIGHT = 50;
private static final int BOTTOM_MARGIN = 30;
@Before
public void givenStepperSpyWithExactlyTwoStepsAndStandardActiveDimensions() {
doNothing()
.when(stepperSpy).measureActiveView(any(Step.class), any(View.class), anyInt(), anyInt(), anyInt());
doReturn(VERTICAL_PADDING).when(stepperSpy).calculateVerticalPadding();
doReturn(DECORATOR_HEIGHT).when(mockedStep1.step).getDecoratorHeight();
doReturn(DECORATOR_HEIGHT).when(mockedStep2.step).getDecoratorHeight();
doReturn(INNER_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.innerView);
doReturn(INNER_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep2.step, mockedStep2.innerView);
doReturn(CONTINUE_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.continueButton);
doReturn(CONTINUE_ACTIVE_HEIGHT)
.when(stepperSpy).calculateActiveHeight(mockedStep2.step, mockedStep2.continueButton);
doReturn(BOTTOM_MARGIN).when(mockedStep1.step).getBottomMarginHeight();
doReturn(0).when(mockedStep2.step).getBottomMarginHeight();
}
@Test
public void measureActiveViews_ShouldMeasureActiveViewsAccountingForDecorator() {
doReturn(0).when(stepperSpy).calculateActiveHeight(mockedStep1.step, mockedStep1.innerView);
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.innerView, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
}
@Test
public void measureActiveViews_ShouldMeasureNavButtonsAccountingForInnerView() {
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT);
}
@Test
public void measureActiveViews_ShouldMeasureActiveViewsAccountingForBottomMargin() {
stepperSpy.measureActiveViews(WMS, HMS);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.innerView, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep1.step, mockedStep1.continueButton, WMS, HMS,
VERTICAL_PADDING + DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT);
verify(stepperSpy).measureActiveView(mockedStep2.step, mockedStep2.innerView, WMS, HMS,
VERTICAL_PADDING + 2 * DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT
+ CONTINUE_ACTIVE_HEIGHT + BOTTOM_MARGIN);
verify(stepperSpy).measureActiveView(mockedStep2.step, mockedStep2.continueButton, WMS, HMS,
VERTICAL_PADDING + 2 * (DECORATOR_HEIGHT + INNER_ACTIVE_HEIGHT)
+ CONTINUE_ACTIVE_HEIGHT + BOTTOM_MARGIN);
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawMethods() {
doNothing().when(stepperSpy).drawIcon(same(canvas), any(Step.class), anyInt());
doNothing().when(stepperSpy).drawText(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawConnector(same(canvas), any(Step.class), anyInt());
}
@Test
public void doDraw_ShouldCallDrawIconTwice() {
InOrder order = inOrder(stepperSpy);
stepperSpy.doDraw(canvas);
order.verify(stepperSpy).drawIcon(canvas, mockedStep1.step, 1);
order.verify(stepperSpy).drawIcon(canvas, mockedStep2.step, 2);
}
@Test
public void doDraw_ShouldCallDrawTextTwice() {
InOrder order = inOrder(stepperSpy);
stepperSpy.doDraw(canvas);
order.verify(stepperSpy).drawText(canvas, mockedStep1.step);
order.verify(stepperSpy).drawText(canvas, mockedStep2.step);
}
@Test
public void doDraw_ShouldCallDrawConnectorOnce() {
int distanceToNextStep = 300;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
stepperSpy.doDraw(canvas);
verify(stepperSpy).drawConnector(canvas, mockedStep1.step, distanceToNextStep);
}
@Test
public void doDraw_ShouldTranslateByDistanceToNextStep() {
InOrder order = inOrder(canvas);
int leftPadding = 10;
int topPadding = 20;
int rightPadding = 5;
int bottomPadding = 15;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int distanceToNextStep = 300;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
stepperSpy.doDraw(canvas);
// first translate for the left and top padding
order.verify(canvas).translate(stepperSpy.outerHorizontalPadding + leftPadding,
stepperSpy.outerVerticalPadding + topPadding);
// translate for the first step
order.verify(canvas).translate(0, 0);
// translate for the second step
order.verify(canvas).translate(0, distanceToNextStep);
// finally translate for the right and bottom padding
order.verify(canvas).translate(stepperSpy.outerHorizontalPadding + rightPadding,
stepperSpy.outerVerticalPadding + bottomPadding);
}
@Test
public void doDraw_ShouldSaveAndRestoreForEachChild() {
InOrder order = inOrder(canvas);
stepperSpy.doDraw(canvas);
// for all of doDraw
order.verify(canvas).save();
// first step
order.verify(canvas).save();
order.verify(canvas).restore();
// second step
order.verify(canvas).save();
order.verify(canvas).restore();
// for all of doDraw
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawIconMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawIconMethods() {
doNothing().when(stepperSpy).drawIconBackground(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawIconError(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawIconText(same(canvas), any(Step.class), anyInt());
}
@Test
public void doDraw_HasError_ShouldCallDrawIconError() {
when(mockedStep1.step.hasError()).thenReturn(true);
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
verify(stepperSpy).drawIconError(canvas, mockedStep1.step);
}
@Test
public void drawIcon_ShouldCallDrawIconBackgroundAndDrawIconText() {
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
verify(stepperSpy).drawIconBackground(canvas, mockedStep1.step);
verify(stepperSpy).drawIconText(canvas, mockedStep1.step, 1);
}
@Test
public void drawIcon_ShouldCallSaveAndRestore() {
InOrder order = inOrder(canvas);
stepperSpy.drawIcon(canvas, mockedStep1.step, 1);
order.verify(canvas).save();
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedDrawTextMethods
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Before
public void givenStepperSpyWithTwoStepsAndStubbedDrawTextMethods() {
doNothing().when(stepperSpy).drawTitle(same(canvas), any(Step.class));
doNothing().when(stepperSpy).drawSubtitle(same(canvas), any(Step.class));
}
@Test
public void drawText_ShouldCallDrawTitleAndDrawSubtitle() {
stepperSpy.drawText(canvas, mockedStep1.step);
verify(stepperSpy).drawTitle(canvas, mockedStep1.step);
verify(stepperSpy).drawSubtitle(canvas, mockedStep1.step);
}
@Test
public void drawText_ShouldSaveTranslateByIconWidthAndRestoreCanvas() {
InOrder order = inOrder(canvas);
int iconWidth = 40;
when(mockedStep1.step.calculateStepDecoratorIconWidth()).thenReturn(iconWidth);
stepperSpy.drawText(canvas, mockedStep1.step);
order.verify(canvas).save();
order.verify(canvas).translate(iconWidth, 0);
order.verify(canvas).restore();
}
}
public static abstract class GivenStepperSpyWithTwoStepsAndMockCanvas extends GivenStepperSpyWithTwoSteps {
Canvas canvas;
@Before
public void givenStepperSpyWithTwoStepsAndMockCanvas() {
canvas = mock(Canvas.class);
}
}
public static class GivenStepperSpyWithExactlyTwoStepsAndMockCanvas
extends GivenStepperSpyWithTwoStepsAndMockCanvas {
@Test
public void drawIconError_ShouldDrawErrorBitmap() {
when(mockedStep1.step.hasError()).thenReturn(true);
Bitmap bitmap = mock(Bitmap.class);
when(mockedStep1.step.getIconErrorBitmap()).thenReturn(bitmap);
stepperSpy.drawIconError(canvas, mockedStep1.step);
verify(canvas).drawBitmap(bitmap, 0, 0, null);
}
@Test
public void drawIconBackground_ShouldDrawCircleWithIconColor() {
Paint color = mock(Paint.class);
RectF rect = mock(RectF.class);
when(mockedStep1.step.getIconBackground()).thenReturn(color);
when(mockedStep1.step.getTempRectForIconBackground()).thenReturn(rect);
stepperSpy.drawIconBackground(canvas, mockedStep1.step);
verify(canvas).drawArc(rect, 0f, 360f, true, color);
}
@Test
public void drawIconText_ShouldDrawStepNumber() {
TextPaint paint = mock(TextPaint.class);
Rect rect = mock(Rect.class);
PointF point = mock(PointF.class);
when(mockedStep1.step.getIconTextPaint()).thenReturn(paint);
when(mockedStep1.step.getTempRectForIconTextBounds()).thenReturn(rect);
when(mockedStep1.step.getTempPointForIconTextCenter()).thenReturn(point);
int stepNumber = 4;
stepperSpy.drawIconText(canvas, mockedStep1.step, stepNumber);
String stepNumberString = String.valueOf(stepNumber);
verify(canvas).drawText(eq(stepNumberString), anyFloat(), anyFloat(), same(paint));
}
@Test
public void drawTitle_ShouldDrawTextWithStepTitle() {
TextPaint paint = mock(TextPaint.class);
String title = "vertical stepper";
float titleBaseline = 20f;
when(mockedStep1.step.getTitle()).thenReturn(title);
when(mockedStep1.step.getTitleTextPaint()).thenReturn(paint);
when(mockedStep1.step.getTitleBaselineRelativeToStepTop()).thenReturn(titleBaseline);
stepperSpy.drawTitle(canvas, mockedStep1.step);
verify(canvas).drawText(title, 0, titleBaseline, paint);
}
@Test
public void drawSubtitle_WhenEmpty_ShouldNotDraw() {
TextPaint paint = mock(TextPaint.class);
when(mockedStep1.step.getSubtitleTextPaint()).thenReturn(paint);
when(mockedStep1.step.getSubtitle()).thenReturn("");
stepperSpy.drawSubtitle(canvas, mockedStep1.step);
verify(canvas, never()).drawText(anyString(), anyFloat(), anyFloat(), eq(paint));
}
@Test
public void drawSubtitle_NotEmpty_ShouldTranslateAndDraw() {
InOrder order = inOrder(canvas);
String subtitle = "subtitle";
when(mockedStep1.step.getSubtitle()).thenReturn(subtitle);
float titleBottom = 15f;
when(mockedStep1.step.getTitleBottomRelativeToStepTop()).thenReturn(titleBottom);
float subtitleBaseline = 20f;
when(mockedStep1.step.getSubtitleBaselineRelativeToTitleBottom()).thenReturn(subtitleBaseline);
TextPaint paint = mock(TextPaint.class);
when(mockedStep1.step.getSubtitleTextPaint()).thenReturn(paint);
stepperSpy.drawSubtitle(canvas, mockedStep1.step);
order.verify(canvas).translate(0, titleBottom);
order.verify(canvas).drawText(subtitle, 0, subtitleBaseline, paint);
}
@Test
public void drawConnector_ShouldSaveTranslateDrawAndRestore() {
InOrder order = inOrder(canvas);
Paint paint = mock(Paint.class);
float strokeWidth = 3f;
when(paint.getStrokeWidth()).thenReturn(strokeWidth);
when(mockedStep1.step.getConnectorPaint()).thenReturn(paint);
stepperSpy.drawConnector(canvas, mockedStep1.step, 0);
order.verify(canvas).save();
order.verify(canvas).translate(anyFloat(), anyFloat());
order.verify(canvas).drawLine(anyFloat(), anyFloat(), anyFloat(), anyFloat(), same(paint));
order.verify(canvas).restore();
}
}
public static class GivenStepperSpyWithTwoStepsAndStubbedLayoutActiveViewMethod
extends GivenStepperSpyWithTwoSteps {
private Rect rect;
@Before
public void givenStepperSpyWithTwoStepsAndStubbedLayoutActiveViewMethod() {
rect = mock(Rect.class);
doNothing().when(stepperSpy).layoutActiveView(same(rect), any(View.class));
}
@Test
public void layoutInnerView_ShouldCallLayoutActiveViewWithInnerView() {
stepperSpy.layoutInnerView(rect, mockedStep1.step);
verify(stepperSpy).layoutActiveView(rect, mockedStep1.innerView);
}
@Test
public void layoutNavButtons_ShouldCallLayoutActiveViewWithContinueButton() {
stepperSpy.layoutNavButtons(rect, mockedStep1.step);
verify(stepperSpy).layoutActiveView(rect, mockedStep1.continueButton);
}
}
public static abstract class GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoSteps {
static class CaptureRectAnswer implements Answer<Void> {
private final Rect rectToCaptureArg;
CaptureRectAnswer(Rect rectToCaptureArg) {
this.rectToCaptureArg = rectToCaptureArg;
}
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Rect rect = invocation.getArgument(0);
rectToCaptureArg.set(rect);
return null;
}
}
@Before
public void givenStepperSpyWithTwoStepsAndStubbedLayoutMethods() {
doNothing().when(stepperSpy).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
doNothing().when(stepperSpy).layoutInnerView(any(Rect.class), any(Step.class));
doNothing().when(stepperSpy).layoutNavButtons(any(Rect.class), any(Step.class));
when(mockedStep1.step.getTempRectForLayout()).thenReturn(new Rect());
}
}
@SuppressLint("WrongCall") // Explicitly testing onLayout
public static class GivenStepperSpyWithTwoInactiveStepsAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods {
@Before
public void givenStepperSpyWithTwoInactiveStepsAndStubbedLayoutMethods() {
when(mockedStep1.step.isActive()).thenReturn(false);
when(mockedStep2.step.isActive()).thenReturn(false);
}
@Test
public void onLayout_ShouldNotCallLayoutInnerViewOrLayoutNavButtons() {
stepperSpy.onLayout(true, 0, 0, 0, 0);
verify(stepperSpy, times(2)).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
verify(stepperSpy, never()).layoutInnerView(any(Rect.class), any(Step.class));
verify(stepperSpy, never()).layoutNavButtons(any(Rect.class), any(Step.class));
}
@Test
public void onLayout_ShouldAdjustTouchForPadding() {
int leftPadding = 8;
int topPadding = 20;
int rightPadding = 4;
int bottomPadding = 10;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
int left = 0;
int top = 0;
int right = 400;
int bottom = 200;
stepperSpy.onLayout(true, left, top, right, bottom);
ArgumentCaptor<Rect> rectCaptor = ArgumentCaptor.forClass(Rect.class);
verify(stepperSpy).layoutTouchView(rectCaptor.capture(), same(mockedStep1.touchView));
Rect touchRect = rectCaptor.getValue();
assertThat(touchRect.left).isEqualTo(stepperSpy.outerHorizontalPadding + leftPadding);
assertThat(touchRect.top).isEqualTo(stepperSpy.outerVerticalPadding + topPadding);
assertThat(touchRect.right).isEqualTo(right - stepperSpy.outerHorizontalPadding - rightPadding);
assertThat(touchRect.bottom).isEqualTo(bottom - stepperSpy.outerVerticalPadding - bottomPadding);
}
@Test
public void onLayout_ShouldAdjustNextTopForPreviousStepHeight() {
InOrder order = inOrder(stepperSpy);
int distanceToNextStep = 400;
when(mockedStep1.step.calculateYDistanceToNextStep()).thenReturn(distanceToNextStep);
final Rect firstRect = new Rect();
final Rect secondRect = new Rect();
doAnswer(new CaptureRectAnswer(firstRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
doAnswer(new CaptureRectAnswer(secondRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep2.touchView));
stepperSpy.onLayout(true, 0, 0, 0, 0);
order.verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
order.verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep2.touchView));
int firstStepTop = firstRect.top;
int secondStepTop = secondRect.top;
assertThat(secondStepTop).isEqualTo(firstStepTop + distanceToNextStep);
}
@Test
public void onLayout_NonZeroLeft_ShouldAdjustForLeftOffset() {
int left = 50;
int right = 300;
final Rect touchRect = new Rect();
doAnswer(new CaptureRectAnswer(touchRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
stepperSpy.onLayout(true, left, 0, right, 0);
verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
assertThat(touchRect.left).isEqualTo(stepperSpy.outerHorizontalPadding);
assertThat(touchRect.right).isEqualTo(right - left - stepperSpy.outerHorizontalPadding);
}
@Test
public void onLayout_NonZeroTop_ShouldAdjustForTopOffset() {
int top = 50;
int bottom = 300;
final Rect touchRect = new Rect();
doAnswer(new CaptureRectAnswer(touchRect))
.when(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
stepperSpy.onLayout(true, 0, top, 0, bottom);
verify(stepperSpy).layoutTouchView(any(Rect.class), same(mockedStep1.touchView));
assertThat(touchRect.top).isEqualTo(stepperSpy.outerVerticalPadding);
assertThat(touchRect.bottom).isEqualTo(bottom - top - stepperSpy.outerVerticalPadding);
}
}
@SuppressLint("WrongCall") // Explicitly testing onLayout
public static class GivenStepperSpyWithTwoStepsOneActiveAndStubbedLayoutMethods
extends GivenStepperSpyWithTwoStepsAndStubbedLayoutMethods {
@Before
public void givenStepperSpyWithTwoStepsOneActiveAndStubbedLayoutMethods() {
when(mockedStep1.step.isActive()).thenReturn(true);
when(mockedStep2.step.isActive()).thenReturn(false);
}
@Test
public void onLayout_ShouldCallLayoutInnerViewAndLayoutNavButtons() {
stepperSpy.onLayout(true, 0, 0, 0, 0);
verify(stepperSpy, times(2)).layoutTouchView(any(Rect.class), any(VerticalStepper.InternalTouchView.class));
verify(stepperSpy).layoutInnerView(any(Rect.class), any(Step.class));
verify(stepperSpy).layoutNavButtons(any(Rect.class), any(Step.class));
}
@Test
public void onLayout_ShouldAdjustInnerViewForPaddingAndStepDecorators() {
int distanceToTextBottom = 80;
when(mockedStep1.step.calculateYDistanceToTextBottom()).thenReturn(distanceToTextBottom);
int iconWidth = 40;
when(mockedStep1.step.calculateStepDecoratorIconWidth()).thenReturn(iconWidth);
int leftPadding = 8;
int topPadding = 20;
int rightPadding = 4;
int bottomPadding = 10;
stepperSpy.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
final Rect innerRect = new Rect();
doAnswer(new CaptureRectAnswer(innerRect))
.when(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
int left = 0;
int top = 0;
int right = 400;
int bottom = 200;
stepperSpy.onLayout(true, left, top, right, bottom);
verify(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
assertThat(innerRect.left)
.isEqualTo(leftPadding + stepperSpy.outerHorizontalPadding + iconWidth);
assertThat(innerRect.top)
.isEqualTo(stepperSpy.outerVerticalPadding + topPadding + distanceToTextBottom);
assertThat(innerRect.right)
.isEqualTo(right - left - stepperSpy.outerHorizontalPadding - rightPadding);
assertThat(innerRect.bottom)
.isEqualTo(bottom - top - stepperSpy.outerVerticalPadding - bottomPadding);
}
@Test
public void onLayout_ShouldAdjustButtonsTopForInnerViewHeight() {
InOrder order = inOrder(stepperSpy);
when(mockedStep1.step.isActive()).thenReturn(true);
int innerHeight = 400;
when(mockedStep1.innerView.getHeight()).thenReturn(innerHeight);
final Rect innerRect = new Rect();
final Rect navRect = new Rect();
doAnswer(new CaptureRectAnswer(innerRect))
.when(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
doAnswer(new CaptureRectAnswer(navRect))
.when(stepperSpy).layoutNavButtons(any(Rect.class), same(mockedStep1.step));
stepperSpy.onLayout(true, 0, 0, 0, 0);
order.verify(stepperSpy).layoutInnerView(any(Rect.class), same(mockedStep1.step));
order.verify(stepperSpy).layoutNavButtons(any(Rect.class), same(mockedStep1.step));
int innerTop = innerRect.top;
int buttonsTop = navRect.top;
assertThat(buttonsTop).isEqualTo(innerTop + innerHeight);
}
}
}
| 65,772 | 0.653089 | 0.643663 | 1,574 | 40.78653 | 34.018162 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704574 | false | false | 15 |
2cb4b2106daa9e9d4dad44d40cc5c0cfb4a96809 | 38,594,576,135,791 | 46305138d3fbb38da7708395d1abd4d03a00ea7f | /Foody Resful Service/web-service-myfoody-master/src/model/UserModel.java | 3dd817f85c2d3bcc2b01445a7f8dba20b09108d6 | [] | no_license | hoanglvbd/ML-and-Deep-learning | https://github.com/hoanglvbd/ML-and-Deep-learning | c9c7fd2732dcba055b3b7fde30a0c5e3f78e6a12 | 8c4fdd7f82e2c4ea1b9a5a354d6bec85763a962f | refs/heads/master | 2020-04-12T05:58:23.202000 | 2018-12-19T20:07:07 | 2018-12-19T20:07:07 | 162,338,017 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import application.AppConfig;
import bean.LoginCredential;
import bean.UserBean;
import dao.UserDAO;
public class UserModel {
private UserDAO userDAO;
private String avatarPath=AppConfig.IMAGE_PATH_USER_AVATAR_LOCAL;
private String coverPath=AppConfig.IMAGE_PATH_USER_COVER_LOCAL;
public UserModel(){
userDAO=UserDAO.getInstance();
}
public UserBean checkLogin(LoginCredential loginCredential){
UserBean user=null;
try {
ResultSet rs=userDAO.checkLogin(loginCredential);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public UserBean getUserByID(String userid){
UserBean user=null;
try {
ResultSet rs=userDAO.getUserByID(userid);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public UserBean getUserByID(String userid,String token){
UserBean user=null;
try {
ResultSet rs=userDAO.getUserByID(userid,token);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public String getimage(String userid,String image,String token){
String out="";
try{
ResultSet rs=userDAO.getimage(userid, image, token);
if(rs!=null){
if(rs.next()){
out=rs.getString(1);
}
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
}
public int register(UserBean user,String password) throws SQLException{
return userDAO.register(user, password);
}
public int update(UserBean user) throws SQLException{
return userDAO.update(user);
}
public int changePass(String userid,String currentpass,String newpass) throws SQLException{
return userDAO.changePass(userid,currentpass,newpass);
}
public int changeavatar(String userid,String avatar,String token) throws SQLException{
return userDAO.changeavatar(userid, avatar, token);
}
public int changecover(String userid,String cover,String token) throws SQLException{
return userDAO.changecover(userid, cover, token);
}
}
| UTF-8 | Java | 4,360 | java | UserModel.java | Java | [] | null | [] | package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import application.AppConfig;
import bean.LoginCredential;
import bean.UserBean;
import dao.UserDAO;
public class UserModel {
private UserDAO userDAO;
private String avatarPath=AppConfig.IMAGE_PATH_USER_AVATAR_LOCAL;
private String coverPath=AppConfig.IMAGE_PATH_USER_COVER_LOCAL;
public UserModel(){
userDAO=UserDAO.getInstance();
}
public UserBean checkLogin(LoginCredential loginCredential){
UserBean user=null;
try {
ResultSet rs=userDAO.checkLogin(loginCredential);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public UserBean getUserByID(String userid){
UserBean user=null;
try {
ResultSet rs=userDAO.getUserByID(userid);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public UserBean getUserByID(String userid,String token){
UserBean user=null;
try {
ResultSet rs=userDAO.getUserByID(userid,token);
if(rs!=null){
if(rs.next()){
String user_id=rs.getString(1);
String name=rs.getString(3);
String phone=rs.getString(4);
String address=rs.getString(5);
String age=rs.getString(6);
String sex=rs.getString(8);
String marry=rs.getString(9);
String avatar=rs.getString(7)!=null?avatarPath+rs.getString(7):"";
String cover=rs.getString(10)!=null?coverPath+rs.getString(10):"";
String datejoin=rs.getString(11);
String firstname=rs.getString(12);
String secretcode=rs.getString(13);
user=new UserBean(user_id,name,phone,address,age,avatar,sex,marry,cover,firstname);
user.setDatejoin(datejoin);
user.setSecretcode(secretcode);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public String getimage(String userid,String image,String token){
String out="";
try{
ResultSet rs=userDAO.getimage(userid, image, token);
if(rs!=null){
if(rs.next()){
out=rs.getString(1);
}
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
}
public int register(UserBean user,String password) throws SQLException{
return userDAO.register(user, password);
}
public int update(UserBean user) throws SQLException{
return userDAO.update(user);
}
public int changePass(String userid,String currentpass,String newpass) throws SQLException{
return userDAO.changePass(userid,currentpass,newpass);
}
public int changeavatar(String userid,String avatar,String token) throws SQLException{
return userDAO.changeavatar(userid, avatar, token);
}
public int changecover(String userid,String cover,String token) throws SQLException{
return userDAO.changecover(userid, cover, token);
}
}
| 4,360 | 0.692202 | 0.678899 | 153 | 27.496733 | 22.905924 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.816993 | false | false | 15 |
dbb70c1a83b15346cfb560b6a9dfe550518ffd36 | 37,263,136,284,179 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /weather-widget-source/src/com/gau/go/a/e/f.java | 96faaf99a1ba96911e8db29eb9b78c3af53b7a99 | [] | no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.gau.go.a.e;
import android.app.PendingIntent;
import android.content.Context;
public abstract class f
{
private long a;
private long b;
private String c;
private boolean d;
private PendingIntent e;
public f()
{
a = 0L;
b = 0L;
d = false;
}
public abstract void a();
public void a(long l)
{
a = l;
}
public void a(PendingIntent pendingintent)
{
e = pendingintent;
}
public void a(Context context, String s)
{
c = (new StringBuilder()).append(context.getPackageName()).append(s).toString();
}
public void a(boolean flag)
{
d = flag;
}
public long b()
{
return a;
}
public void b(long l)
{
b = l;
}
public long c()
{
return b;
}
public String d()
{
return c;
}
public boolean e()
{
return d;
}
public PendingIntent f()
{
return e;
}
public void g()
{
e = null;
}
}
| UTF-8 | Java | 1,245 | java | f.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996800422668457,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.gau.go.a.e;
import android.app.PendingIntent;
import android.content.Context;
public abstract class f
{
private long a;
private long b;
private String c;
private boolean d;
private PendingIntent e;
public f()
{
a = 0L;
b = 0L;
d = false;
}
public abstract void a();
public void a(long l)
{
a = l;
}
public void a(PendingIntent pendingintent)
{
e = pendingintent;
}
public void a(Context context, String s)
{
c = (new StringBuilder()).append(context.getPackageName()).append(s).toString();
}
public void a(boolean flag)
{
d = flag;
}
public long b()
{
return a;
}
public void b(long l)
{
b = l;
}
public long c()
{
return b;
}
public String d()
{
return c;
}
public boolean e()
{
return d;
}
public PendingIntent f()
{
return e;
}
public void g()
{
e = null;
}
}
| 1,235 | 0.531727 | 0.524498 | 82 | 14.182927 | 16.05792 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.292683 | false | false | 15 |
4bb9c9fcd8475e0159a9ebf67b2374effa1ad401 | 16,192,026,755,633 | 255abe8a8b29d236ecd829447967059cc7bcff45 | /刷题日记/vs_leetcode/78.子集.java | e3d78041337b64a4bba7473b56b7033396c48efb | [] | no_license | zhuxiang555111/Blog | https://github.com/zhuxiang555111/Blog | ab3156a08d3b27aefe9cb56297a92f8174dcc40b | 366b0d89140c21bcd7e3be1daad48a353ee0dd4c | refs/heads/master | 2023-02-03T19:07:36.584000 | 2020-12-25T01:34:35 | 2020-12-25T01:34:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
/*
* @lc app=leetcode.cn id=78 lang=java
*
* [78] 子集
*/
// @lc code=start
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int len = nums.length;
int count = (int) Math.pow(2, len);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < count; i++) {
int x = i;
int index = 0;
ArrayList<Integer> item = new ArrayList<>();
while (x != 0) {
if (x % 2 == 1) {
item.add(nums[index]);
}
index++;
x /= 2;
}
res.add(item);
}
System.out.println(res.toString());
return res;
}
}
// @lc code=end
| UTF-8 | Java | 771 | java | 78.子集.java | Java | [] | null | [] | import java.util.ArrayList;
/*
* @lc app=leetcode.cn id=78 lang=java
*
* [78] 子集
*/
// @lc code=start
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int len = nums.length;
int count = (int) Math.pow(2, len);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < count; i++) {
int x = i;
int index = 0;
ArrayList<Integer> item = new ArrayList<>();
while (x != 0) {
if (x % 2 == 1) {
item.add(nums[index]);
}
index++;
x /= 2;
}
res.add(item);
}
System.out.println(res.toString());
return res;
}
}
// @lc code=end
| 771 | 0.432855 | 0.418514 | 32 | 22.96875 | 16.302769 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
4e03a4a8260cb744cd21b52f6a0683797b9c4a55 | 35,605,278,924,153 | d421588d6dbd7b11494a97a2088c4104c0568156 | /Framework/src/io/greatbone/web/WebActivity.java | e8fb796e3065a3642658523340275c53e02241ef | [
"Apache-2.0"
] | permissive | xartopaikths/grid | https://github.com/xartopaikths/grid | 628d28d1c6c7666512702be3ebba493ca01a60be | 5292b361a227b8b83df9f76451ed73f3c178df1a | refs/heads/master | 2020-05-21T19:01:15.902000 | 2016-05-30T09:30:30 | 2016-05-30T09:30:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.greatbone.web;
import io.greatbone.util.Roll;
import io.netty.handler.codec.http.HttpMethod;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* A set of actions working on request/response eachanges to carry out management tasks on a collection of resources.
*/
public abstract class WebActivity {
// the root handler
protected final WebHost vhost;
// the parent of this work instance, if any
protected final WebActivity parent;
// the key by which this control is added to a parent
String key;
final Roll<String, Action> actions = new Roll<>(32);
// access checker
Authorizer authorizer;
// execution of background tasks
Thread cycler;
protected WebActivity(WebHost vhost, WebActivity parent) {
this.vhost = (vhost != null) ? vhost : (WebHost) this;
this.parent = parent;
// initialize web methods
for (Method m : getClass().getMethods()) {
int mod = m.getModifiers();
// public non-static void
if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
Class<?>[] pts = m.getParameterTypes();
// with the two parameters
if (pts.length == 1 && WebContext.class == pts[0]) {
String key = m.getName().toLowerCase();
if ("$".equals(key)) {
key = "";
}
actions.put(key, new Action(this, m));
}
}
}
// initialize the cycler thread if any
if (this instanceof Runnable) {
cycler = new Thread((Runnable) this);
cycler.start();
}
}
public String key() {
return key;
}
/**
* To handle a request/response exchange by this or by an appropriate sub controller.
*
* @param base the relative URI that this controller is based
* @param exch the request.response exchange
*/
protected void perform(String base, WebContext exch) throws Exception {
int slash = base.indexOf('/');
if (slash == -1) { // without a slash then handle by this controller instance
exch.control = this;
HttpMethod method = exch.method();
if (method == HttpMethod.GET) default_(exch);
// } else if (subordinates != null) { // resolve the sub structure
// WebControl control = subordinates.locateSub(base.substring(0, slash), exch);
// if (control != null) {
// control.perform(base.substring(slash + 1), exch);
// } else {
// exch.sendNotFound();
// }
} else {
exch.sendNotFound();
}
}
public void default_(WebContext wc) throws Exception {
}
}
| UTF-8 | Java | 2,830 | java | WebActivity.java | Java | [] | null | [] | package io.greatbone.web;
import io.greatbone.util.Roll;
import io.netty.handler.codec.http.HttpMethod;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* A set of actions working on request/response eachanges to carry out management tasks on a collection of resources.
*/
public abstract class WebActivity {
// the root handler
protected final WebHost vhost;
// the parent of this work instance, if any
protected final WebActivity parent;
// the key by which this control is added to a parent
String key;
final Roll<String, Action> actions = new Roll<>(32);
// access checker
Authorizer authorizer;
// execution of background tasks
Thread cycler;
protected WebActivity(WebHost vhost, WebActivity parent) {
this.vhost = (vhost != null) ? vhost : (WebHost) this;
this.parent = parent;
// initialize web methods
for (Method m : getClass().getMethods()) {
int mod = m.getModifiers();
// public non-static void
if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
Class<?>[] pts = m.getParameterTypes();
// with the two parameters
if (pts.length == 1 && WebContext.class == pts[0]) {
String key = m.getName().toLowerCase();
if ("$".equals(key)) {
key = "";
}
actions.put(key, new Action(this, m));
}
}
}
// initialize the cycler thread if any
if (this instanceof Runnable) {
cycler = new Thread((Runnable) this);
cycler.start();
}
}
public String key() {
return key;
}
/**
* To handle a request/response exchange by this or by an appropriate sub controller.
*
* @param base the relative URI that this controller is based
* @param exch the request.response exchange
*/
protected void perform(String base, WebContext exch) throws Exception {
int slash = base.indexOf('/');
if (slash == -1) { // without a slash then handle by this controller instance
exch.control = this;
HttpMethod method = exch.method();
if (method == HttpMethod.GET) default_(exch);
// } else if (subordinates != null) { // resolve the sub structure
// WebControl control = subordinates.locateSub(base.substring(0, slash), exch);
// if (control != null) {
// control.perform(base.substring(slash + 1), exch);
// } else {
// exch.sendNotFound();
// }
} else {
exch.sendNotFound();
}
}
public void default_(WebContext wc) throws Exception {
}
}
| 2,830 | 0.568551 | 0.566078 | 90 | 30.444445 | 26.058529 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422222 | false | false | 15 |
29bcadef6afe49e01fa6f139c4a97b4714b75d3c | 37,907,381,373,881 | 4d725385355306878afdfaa25f8285bd3f32bd3f | /taipan/src/main/java/com/taipan/Ship.java | 0565dc58f6dd6d102a82437a056cff0dbad25416 | [] | no_license | drokita/taipan | https://github.com/drokita/taipan | 2db8ddd3ac9f5d2e723ec65d94e8f5f4f5f73feb | 030ce4113d43b09f9ecdc3efb95e5b54bb4fb876 | refs/heads/master | 2020-12-25T06:14:45.534000 | 2016-06-06T20:00:12 | 2016-06-06T20:00:12 | 60,556,731 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taipan;
/**
* Taipan - An Interpretation of the Classic Apple IIe Game
*
* Class Description of Ship
* @author David M. Rokita
* @version 0.9 June 01, 2016
*
* This class produces a Ship object. The Ship object is instatiated with
* cargo_hold and hp_total where cargo_hold is the total value of cargo that
* the ship can hold. The Ship also has a field of hp_total. This is the
* total number of damage points that the Ship can take. Finally, hp_current
* is the current number of hit points that the Ship has after taking damage
*/
public class Ship {
/** cargo_hold is the total volume of the cargo_hold */
private int cargo_hold;
/** hp_total is the total number of hit point when health is 100% */
private int hp_total;
/** hp_current is the number of hit_points total minus an damage taken */
private int hp_current;
/** Ship Constructor
* @param cargo_hold
* @param hp_total */
Ship(int cargo_hold, int hp_total ) {
this.cargo_hold = cargo_hold;
this.hp_total = hp_total;
this.hp_current = hp_total;
}
/** getCargoHold()
* @return cargo_hold */
public int getCargoHold() {
return cargo_hold;
}
/** getHpCurrent()
* @return hp_current */
public int getHpCurrent() { return hp_current; }
/** getHpTotal()
* @return hp_total */
public int getHpTotal() { return hp_total; }
/** commitDamage
* @param damage Number of dmage hit points
* @return hp_current */
public int commitDamage(int damage) {
if ( hp_current - damage > 0 ) {
hp_current = hp_current - damage;
} else {
hp_current = 0;
}
return hp_current;
}
/** repairDamage
* @return hp_current */
public int repairDamage() {
hp_current = hp_total;
return hp_current;
}
}
| UTF-8 | Java | 1,897 | java | Ship.java | Java | [
{
"context": "Ie Game\n *\n * Class Description of Ship\n * @author David M. Rokita\n * @version 0.9 June 01, 2016\n *\n * This class pr",
"end": 143,
"score": 0.9998877048492432,
"start": 128,
"tag": "NAME",
"value": "David M. Rokita"
}
] | null | [] | package com.taipan;
/**
* Taipan - An Interpretation of the Classic Apple IIe Game
*
* Class Description of Ship
* @author <NAME>
* @version 0.9 June 01, 2016
*
* This class produces a Ship object. The Ship object is instatiated with
* cargo_hold and hp_total where cargo_hold is the total value of cargo that
* the ship can hold. The Ship also has a field of hp_total. This is the
* total number of damage points that the Ship can take. Finally, hp_current
* is the current number of hit points that the Ship has after taking damage
*/
public class Ship {
/** cargo_hold is the total volume of the cargo_hold */
private int cargo_hold;
/** hp_total is the total number of hit point when health is 100% */
private int hp_total;
/** hp_current is the number of hit_points total minus an damage taken */
private int hp_current;
/** Ship Constructor
* @param cargo_hold
* @param hp_total */
Ship(int cargo_hold, int hp_total ) {
this.cargo_hold = cargo_hold;
this.hp_total = hp_total;
this.hp_current = hp_total;
}
/** getCargoHold()
* @return cargo_hold */
public int getCargoHold() {
return cargo_hold;
}
/** getHpCurrent()
* @return hp_current */
public int getHpCurrent() { return hp_current; }
/** getHpTotal()
* @return hp_total */
public int getHpTotal() { return hp_total; }
/** commitDamage
* @param damage Number of dmage hit points
* @return hp_current */
public int commitDamage(int damage) {
if ( hp_current - damage > 0 ) {
hp_current = hp_current - damage;
} else {
hp_current = 0;
}
return hp_current;
}
/** repairDamage
* @return hp_current */
public int repairDamage() {
hp_current = hp_total;
return hp_current;
}
}
| 1,888 | 0.615709 | 0.608856 | 66 | 27.742424 | 22.192211 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 15 |
510d0dd14c0a733390459161fd29dc49164859fe | 21,655,225,169,678 | 570bc576ccbe2ebf9968b9da6d4d9748eb291f0b | /src/main/java/fvarrui/games/turtlegame/controller/PS4GamepadCodes.java | 99b5ddc3dfe9e64dbb2cb6a194ae769aba3f997b | [] | no_license | fvarrui/TurtleGame | https://github.com/fvarrui/TurtleGame | 6965ea0a843b1dde1c0bb6d3e58b0570736ed6c4 | 54054d951cb5b39e7de02ffceb863f0242585fbe | refs/heads/master | 2022-02-19T12:58:56.544000 | 2022-02-09T17:20:12 | 2022-02-09T17:20:12 | 178,076,629 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fvarrui.games.turtlegame.controller;
public class PS4GamepadCodes {
public static final int AXIS_LEFT_X = 3;
public static final int AXIS_LEFT_Y = 2;
public static final int AXIS_LEFT_BUTTON = 10;
public static final int AXIS_RIGHT_X = 1;
public static final int AXIS_RIGHT_Y = 0;
public static final int AXIS_RIGHT_BUTTON = 11;
public static final int BUTTON_SQUARE = 0;
public static final int BUTTON_CROSS = 1;
public static final int BUTTON_CIRCLE = 2;
public static final int BUTTON_TRIANGLE = 3;
public static final int BUTTON_L1 = 4;
public static final int BUTTON_R1 = 5;
public static final int BUTTON_L2 = 6;
public static final int BUTTON_R2 = 7;
public static final int BUTTON_SHARE = 8;
public static final int BUTTON_OPTIONS = 9;
public static final int BUTTON_PS = 12;
public static final int POV = 0;
}
| UTF-8 | Java | 898 | java | PS4GamepadCodes.java | Java | [] | null | [] | package fvarrui.games.turtlegame.controller;
public class PS4GamepadCodes {
public static final int AXIS_LEFT_X = 3;
public static final int AXIS_LEFT_Y = 2;
public static final int AXIS_LEFT_BUTTON = 10;
public static final int AXIS_RIGHT_X = 1;
public static final int AXIS_RIGHT_Y = 0;
public static final int AXIS_RIGHT_BUTTON = 11;
public static final int BUTTON_SQUARE = 0;
public static final int BUTTON_CROSS = 1;
public static final int BUTTON_CIRCLE = 2;
public static final int BUTTON_TRIANGLE = 3;
public static final int BUTTON_L1 = 4;
public static final int BUTTON_R1 = 5;
public static final int BUTTON_L2 = 6;
public static final int BUTTON_R2 = 7;
public static final int BUTTON_SHARE = 8;
public static final int BUTTON_OPTIONS = 9;
public static final int BUTTON_PS = 12;
public static final int POV = 0;
}
| 898 | 0.700445 | 0.671492 | 30 | 28.933332 | 20.286175 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.766667 | false | false | 15 |
ba09a26ed749877e707ed1c5165fdc8a09a69d5f | 19,396,072,355,733 | 3e1c15464e5b769f92e1af219dca802ae8236c3e | /app/src/main/java/com/npupt/npubits/utils/ColorUtils.java | 1be0b7d53be21baa4508b0e9034365c16e7eef9b | [] | no_license | banixc/NPUBits | https://github.com/banixc/NPUBits | 831467643c762f6974ac5990a4b1d67112023e80 | 8753f04d55b5f25d669afb35e155e8deb3005b8f | refs/heads/master | 2016-09-13T17:10:10.425000 | 2016-05-30T06:55:09 | 2016-05-30T06:55:09 | 59,341,156 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.npupt.npubits.utils;
import java.util.List;
/**
* Java Code to get a color name from rgb/hex value/awt color
* <p/>
* The part of looking up a color name from the rgb values is edited from
* https://gist.github.com/nightlark/6482130#file-gistfile1-java (that has some errors) by Ryan Mast (nightlark)
*
* @author Xiaoxiao Li
*/
public class ColorUtils {
/**
* Initialize the color list that we have.
*/
public static int getHexFromColorName(int color) {
return getHexFromColorName(get_hl_color(color), true);
}
public static int getHexFromColorName(String colorname) {
return getHexFromColorName(colorname, ColorName.TRANSPARENCY);
}
// public int colorToHex(Color c) {
// return Integer.decode("0x"
// + Integer.toHexString(c.getRGB()).substring(2));
// }
//
// public String getColorNameFromColor(Color color) {
// return getColorNameFromRgb(color.getRed(), color.getGreen(),
// color.getBlue());
// }
public static int getHexFromColorName(String colorname, boolean full) {
return full ? getHexFromColorName(colorname, ColorName.ALPHA_MASK) : getHexFromColorName(colorname, ColorName.TRANSPARENCY);
}
public static int getHexFromColorName(String colorname, int transparency) {
List<ColorName> colorList = ColorName.colorList;
for (ColorName c : colorList) {
if (c.name.equalsIgnoreCase(colorname))
return c.getRGB(transparency);
}
return 0;
}
public static String get_hl_color(int color) {
switch (color) {
case 1:
return "Black";
case 2:
return "Sienna";
case 3:
return "DarkOliveGreen";
case 4:
return "DarkGreen";
case 5:
return "DarkSlateBlue";
case 6:
return "Navy";
case 7:
return "Indigo";
case 8:
return "DarkSlateGray";
case 9:
return "DarkRed";
case 10:
return "DarkOrange";
case 11:
return "Olive";
case 12:
return "Green";
case 13:
return "Teal";
case 14:
return "Blue";
case 15:
return "SlateGray";
case 16:
return "DimGray";
case 17:
return "Red";
case 18:
return "SandyBrown";
case 19:
return "YellowGreen";
case 20:
return "SeaGreen";
case 21:
return "MediumTurquoise";
case 22:
return "RoyalBlue";
case 23:
return "Purple";
case 24:
return "Gray";
case 25:
return "Magenta";
case 26:
return "Orange";
case 27:
return "Yellow";
case 28:
return "Lime";
case 29:
return "Cyan";
case 30:
return "DeepSkyBlue";
case 31:
return "DarkOrchid";
case 32:
return "Silver";
case 33:
return "Pink";
case 34:
return "Wheat";
case 35:
return "LemonChiffon";
case 36:
return "PaleGreen";
case 37:
return "PaleTurquoise";
case 38:
return "LightBlue";
case 39:
return "Plum";
case 40:
return "White";
default:
return "Black";
}
}
/**
* Get the closest color name from our list
*
* @param r
* @param g
* @param b
* @return
*/
public String getColorNameFromRgb(int r, int g, int b) {
List<ColorName> colorList = ColorName.colorList;
ColorName closestMatch = null;
int minMSE = Integer.MAX_VALUE;
int mse;
for (ColorName c : colorList) {
mse = c.computeMSE(r, g, b);
if (mse < minMSE) {
minMSE = mse;
closestMatch = c;
}
}
if (closestMatch != null) {
return closestMatch.getName();
} else {
return "No matched color name.";
}
}
/**
* Convert hexColor to rgb, then call getColorNameFromRgb(r, g, b)
*
* @param hexColor
* @return
*/
public String getColorNameFromHex(int hexColor) {
int r = (hexColor & 0xFF0000) >> 16;
int g = (hexColor & 0xFF00) >> 8;
int b = (hexColor & 0xFF);
return getColorNameFromRgb(r, g, b);
}
} | UTF-8 | Java | 4,989 | java | ColorUtils.java | Java | [
{
"context": " values is edited from\n * https://gist.github.com/nightlark/6482130#file-gistfile1-java (that has some errors",
"end": 242,
"score": 0.999210774898529,
"start": 233,
"tag": "USERNAME",
"value": "nightlark"
},
{
"context": "2130#file-gistfile1-java (that has some errors... | null | [] | package com.npupt.npubits.utils;
import java.util.List;
/**
* Java Code to get a color name from rgb/hex value/awt color
* <p/>
* The part of looking up a color name from the rgb values is edited from
* https://gist.github.com/nightlark/6482130#file-gistfile1-java (that has some errors) by <NAME> (nightlark)
*
* @author <NAME>
*/
public class ColorUtils {
/**
* Initialize the color list that we have.
*/
public static int getHexFromColorName(int color) {
return getHexFromColorName(get_hl_color(color), true);
}
public static int getHexFromColorName(String colorname) {
return getHexFromColorName(colorname, ColorName.TRANSPARENCY);
}
// public int colorToHex(Color c) {
// return Integer.decode("0x"
// + Integer.toHexString(c.getRGB()).substring(2));
// }
//
// public String getColorNameFromColor(Color color) {
// return getColorNameFromRgb(color.getRed(), color.getGreen(),
// color.getBlue());
// }
public static int getHexFromColorName(String colorname, boolean full) {
return full ? getHexFromColorName(colorname, ColorName.ALPHA_MASK) : getHexFromColorName(colorname, ColorName.TRANSPARENCY);
}
public static int getHexFromColorName(String colorname, int transparency) {
List<ColorName> colorList = ColorName.colorList;
for (ColorName c : colorList) {
if (c.name.equalsIgnoreCase(colorname))
return c.getRGB(transparency);
}
return 0;
}
public static String get_hl_color(int color) {
switch (color) {
case 1:
return "Black";
case 2:
return "Sienna";
case 3:
return "DarkOliveGreen";
case 4:
return "DarkGreen";
case 5:
return "DarkSlateBlue";
case 6:
return "Navy";
case 7:
return "Indigo";
case 8:
return "DarkSlateGray";
case 9:
return "DarkRed";
case 10:
return "DarkOrange";
case 11:
return "Olive";
case 12:
return "Green";
case 13:
return "Teal";
case 14:
return "Blue";
case 15:
return "SlateGray";
case 16:
return "DimGray";
case 17:
return "Red";
case 18:
return "SandyBrown";
case 19:
return "YellowGreen";
case 20:
return "SeaGreen";
case 21:
return "MediumTurquoise";
case 22:
return "RoyalBlue";
case 23:
return "Purple";
case 24:
return "Gray";
case 25:
return "Magenta";
case 26:
return "Orange";
case 27:
return "Yellow";
case 28:
return "Lime";
case 29:
return "Cyan";
case 30:
return "DeepSkyBlue";
case 31:
return "DarkOrchid";
case 32:
return "Silver";
case 33:
return "Pink";
case 34:
return "Wheat";
case 35:
return "LemonChiffon";
case 36:
return "PaleGreen";
case 37:
return "PaleTurquoise";
case 38:
return "LightBlue";
case 39:
return "Plum";
case 40:
return "White";
default:
return "Black";
}
}
/**
* Get the closest color name from our list
*
* @param r
* @param g
* @param b
* @return
*/
public String getColorNameFromRgb(int r, int g, int b) {
List<ColorName> colorList = ColorName.colorList;
ColorName closestMatch = null;
int minMSE = Integer.MAX_VALUE;
int mse;
for (ColorName c : colorList) {
mse = c.computeMSE(r, g, b);
if (mse < minMSE) {
minMSE = mse;
closestMatch = c;
}
}
if (closestMatch != null) {
return closestMatch.getName();
} else {
return "No matched color name.";
}
}
/**
* Convert hexColor to rgb, then call getColorNameFromRgb(r, g, b)
*
* @param hexColor
* @return
*/
public String getColorNameFromHex(int hexColor) {
int r = (hexColor & 0xFF0000) >> 16;
int g = (hexColor & 0xFF00) >> 8;
int b = (hexColor & 0xFF);
return getColorNameFromRgb(r, g, b);
}
} | 4,981 | 0.482261 | 0.46342 | 180 | 26.722221 | 20.352192 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 15 |
22b0593a9a5a843955e930b540e4d004cf9901fd | 19,396,072,352,998 | 1ae9303df4b1f7f57682e19fc5b67e1611e04dc9 | /2014.08.27 - histogram-fill-with-water/src/MyKata/InterviewTest.java | d87d331532efa6175599f49df7590fa7e5ae223a | [] | no_license | aaronfi/playground | https://github.com/aaronfi/playground | 9efd86adaedf0ea58016d369e89ecd259d94e4c2 | 1492457fd38b8183eaa87fd877fef616b2f8490d | refs/heads/master | 2020-06-08T19:14:26.408000 | 2014-09-09T05:13:09 | 2014-09-09T05:13:09 | 1,643,124 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package MyKata;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class InterviewTest {
@Test
public void TestMalformedHistogram() {
int count = Interview.FillHistogramWithWater(new int[]{2});
assertTrue("Expected 0 but found: " + count, 0 == count);
}
// 3:
// 2: x x
// 1: x x
// 0: x x
@Test
public void TestFlat() {
int count = Interview.FillHistogramWithWater(new int[]{2, 2});
assertTrue("Expected 0 but found: " + count, 0 == count);
assertEquals(0, Interview.FillHistogramWithWater( new int[] { 2, 2 } ));
}
// 3:
// 2: x - x
// 1: x x x
// 0: x x x
@Test
public void TestSimple() {
int count = Interview.FillHistogramWithWater(new int[]{ 2, 1, 2 });
assertTrue("Expected 1 but found: " + count, 1 == count);
}
// 3: x
// 2: x x x
// 1: x x x x x
// 0: x x x x x
@Test
public void TestPyramid() {
int count = Interview.FillHistogramWithWater(new int[]{1, 2, 3, 2, 1 });
assertTrue("Expected 0 but found: " + count, 0 == count);
}
// 3: x
// 2: x - - - - - x
// 1: x - - x - - x
// 0: x x x x x x x
@Test
public void TestLongAndShallow() {
int count = Interview.FillHistogramWithWater(new int[]{2, 0, 0, 1, 0, 0, 3 });
assertTrue("Expected 9 but found: " + count, 9 == count);
}
// 3: x
// 2: x - - x x
// 1: x - - x x x
// 0: x x x x x x x
@Test
public void TestTwoPools() {
int count = Interview.FillHistogramWithWater(new int[] { 2, 0, 0, 3, 2, 1, 0 });
assertTrue("Expected 4 but found: " + count, 4 == count);
}
} | UTF-8 | Java | 1,792 | java | InterviewTest.java | Java | [] | null | [] | package MyKata;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class InterviewTest {
@Test
public void TestMalformedHistogram() {
int count = Interview.FillHistogramWithWater(new int[]{2});
assertTrue("Expected 0 but found: " + count, 0 == count);
}
// 3:
// 2: x x
// 1: x x
// 0: x x
@Test
public void TestFlat() {
int count = Interview.FillHistogramWithWater(new int[]{2, 2});
assertTrue("Expected 0 but found: " + count, 0 == count);
assertEquals(0, Interview.FillHistogramWithWater( new int[] { 2, 2 } ));
}
// 3:
// 2: x - x
// 1: x x x
// 0: x x x
@Test
public void TestSimple() {
int count = Interview.FillHistogramWithWater(new int[]{ 2, 1, 2 });
assertTrue("Expected 1 but found: " + count, 1 == count);
}
// 3: x
// 2: x x x
// 1: x x x x x
// 0: x x x x x
@Test
public void TestPyramid() {
int count = Interview.FillHistogramWithWater(new int[]{1, 2, 3, 2, 1 });
assertTrue("Expected 0 but found: " + count, 0 == count);
}
// 3: x
// 2: x - - - - - x
// 1: x - - x - - x
// 0: x x x x x x x
@Test
public void TestLongAndShallow() {
int count = Interview.FillHistogramWithWater(new int[]{2, 0, 0, 1, 0, 0, 3 });
assertTrue("Expected 9 but found: " + count, 9 == count);
}
// 3: x
// 2: x - - x x
// 1: x - - x x x
// 0: x x x x x x x
@Test
public void TestTwoPools() {
int count = Interview.FillHistogramWithWater(new int[] { 2, 0, 0, 3, 2, 1, 0 });
assertTrue("Expected 4 but found: " + count, 4 == count);
}
} | 1,792 | 0.521763 | 0.488281 | 67 | 25.761194 | 25.291784 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.656716 | false | false | 15 |
16c340b19e359a1392e7c06e78d254a4e9964d66 | 7,249,904,804,517 | d9315252df430d5666880787efa77e69e1dc5472 | /src/dueactivityv2/namespace/Second.java | 5b2e4090b9a119c42318d034df7d4e575fc44538 | [] | no_license | jacopotatarelli/DueActivityV2 | https://github.com/jacopotatarelli/DueActivityV2 | 0f8a99da9daa6471b31f92a8cd2bad1d36eac5dd | 24f91da928543605f444f37e6b6edd6a25300064 | refs/heads/master | 2021-01-01T05:48:04.389000 | 2012-01-19T18:52:42 | 2012-01-19T18:52:42 | 3,219,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dueactivityv2.namespace;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView label = (TextView) findViewById(R.id.editText1);
String iltestoricevuto = getIntent().getExtras().getString("IlTestoNelBox");
label.setText(iltestoricevuto);
}
@Override
public void onStart()
{
super.onStart();
Log.d("Log","onStart");
}
@Override
public void onRestart()
{
super.onRestart();
Log.d("Log","onRestart");
}
@Override
public void onResume()
{
super.onResume();
Log.d("Log", "onResume");
}
@Override
public void onPause()
{
super.onPause();
Log.d("Log", "onPause");
}
@Override
public void onStop()
{
super.onStop();
Log.d("Log", "onStop");
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.d("Log", "onDestroy");
}
}
| UTF-8 | Java | 1,046 | java | Second.java | Java | [] | null | [] | package dueactivityv2.namespace;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView label = (TextView) findViewById(R.id.editText1);
String iltestoricevuto = getIntent().getExtras().getString("IlTestoNelBox");
label.setText(iltestoricevuto);
}
@Override
public void onStart()
{
super.onStart();
Log.d("Log","onStart");
}
@Override
public void onRestart()
{
super.onRestart();
Log.d("Log","onRestart");
}
@Override
public void onResume()
{
super.onResume();
Log.d("Log", "onResume");
}
@Override
public void onPause()
{
super.onPause();
Log.d("Log", "onPause");
}
@Override
public void onStop()
{
super.onStop();
Log.d("Log", "onStop");
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.d("Log", "onDestroy");
}
}
| 1,046 | 0.671128 | 0.669216 | 52 | 19.096153 | 17.08042 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 15 |
9cac6e9da563a3055e40562b0e8f17277738f893 | 13,743,895,393,988 | e5c7367187660490413a5aeae18c4f2cd785414e | /Hisab/src/main/java/com/ANP/util/ANPConstants.java | 8735eb8f3fff7fc68239e788e4e89d2269322e70 | [] | no_license | riteshjoshi11/APN | https://github.com/riteshjoshi11/APN | b0a25776a95370916db31859659943ca4875a2e4 | e181e40ab6c9c19a0a2a5196b5619b4ef02a8cfd | refs/heads/development | 2023-04-06T16:37:06.236000 | 2022-02-20T15:01:15 | 2022-02-20T15:01:15 | 228,081,136 | 0 | 0 | null | false | 2023-03-27T22:19:26 | 2019-12-14T19:59:46 | 2022-02-20T15:00:49 | 2023-03-27T22:19:24 | 62,397 | 0 | 0 | 3 | Java | false | false | package com.ANP.util;
public interface ANPConstants {
// public static final int EMPLOYEE_TYPE_SUPER_ADMIN=1;
// public static final int EMPLOYEE_TYPE_VIRTUAL=6;
//public static final int EMPLOYEE_TYPE_DEFAULT=7;
public static final String LOGIN_TYPE_EMPLOYEE="EMPLOYEE";
public static final String LOGIN_TYPE_CUSTOMER="CUSTOMER";
public static final String SEARCH_FIELDTYPE_STRING="String" ;
public static final String SEARCH_FIELDTYPE_DATE="Date" ;
public static final String OPERATION_TYPE_ADD="ADD" ;
public static final String OPERATION_TYPE_SUBTRACT="SUBTRACT";
public static final String DB_TBL_customerinvoice = "customerinvoice";
public static final String DB_TBL_purchasefromvendor = "purchasefromvendor";
public static final String DB_TBL_delivery = "delivery";
public static final String DB_TBL_generalexpense = "generalexpense";
public static final String DB_TBL_internaltransfer = "internaltransfer";
public static final String DB_TBL_paymentreceived = "paymentreceived";
public static final String DB_TBL_paytovendor = "paytovendor";
public static final String DB_TBL_retailsale = "retailsale";
public static final String DB_TBL_GST_REPORT = "p_gst_reports";
public static final String DB_TBL_TXN_REPORT = "p_txn_reports";
public static final String DB_TBL_UI_OBJ_COMAPANYTYPE = "companytype" ;
public static final String DB_TBL_UI_OBJ_BUSINESS_NATURE="businessnature" ;
public static final String DB_TBL_UI_OBJ_NOOFEMPLOYEES="noofemployee";
public static final String DB_TBL_UI_OBJ_EMPLOYEE_TYPE="employeetype";
public static final String TRANSACTION_NAME_SALE = "SALE";
public static final String TRANSACTION_NAME_PURCHASE = "PURCHASE";
public static final String TRANSACTION_NAME_PAYMENT_RECEIVED = "PAYMENT_RECEIVED";
public static final String TRANSACTION_NAME_PAY_TO_VENDOR = "PAY_TO_VENDOR";
public static final String TRANSACTION_NAME_EXPENSE = "EXPENSE";
public static final String TRANSACTION_NAME_INTERNAL_TRANSFER = "INTERNAL_TRANSFER";
public static final String TRANSACTION_NAME_RETAIL_SALE = "RETAIL_SALE";
public static final String SYSTEM_AUDIT_CUSTOMER = "CUSTOMER";
public static final String SYSTEM_AUDIT_EMPLOYEE = "EMPLOYEE";
public static final String GST_REPORT_CURRENT_MONTH="current";
public static final String GST_REPORT_PREVIOUS_MONTH="previous";
public static final String EMPLOYEE_SALARY_AUDIT_TYPE_PAY="Salary_Pay";
public static final String EMPLOYEE_SALARY_AUDIT_TYPE_DUE="Salary_Due";
}
| UTF-8 | Java | 2,669 | java | ANPConstants.java | Java | [] | null | [] | package com.ANP.util;
public interface ANPConstants {
// public static final int EMPLOYEE_TYPE_SUPER_ADMIN=1;
// public static final int EMPLOYEE_TYPE_VIRTUAL=6;
//public static final int EMPLOYEE_TYPE_DEFAULT=7;
public static final String LOGIN_TYPE_EMPLOYEE="EMPLOYEE";
public static final String LOGIN_TYPE_CUSTOMER="CUSTOMER";
public static final String SEARCH_FIELDTYPE_STRING="String" ;
public static final String SEARCH_FIELDTYPE_DATE="Date" ;
public static final String OPERATION_TYPE_ADD="ADD" ;
public static final String OPERATION_TYPE_SUBTRACT="SUBTRACT";
public static final String DB_TBL_customerinvoice = "customerinvoice";
public static final String DB_TBL_purchasefromvendor = "purchasefromvendor";
public static final String DB_TBL_delivery = "delivery";
public static final String DB_TBL_generalexpense = "generalexpense";
public static final String DB_TBL_internaltransfer = "internaltransfer";
public static final String DB_TBL_paymentreceived = "paymentreceived";
public static final String DB_TBL_paytovendor = "paytovendor";
public static final String DB_TBL_retailsale = "retailsale";
public static final String DB_TBL_GST_REPORT = "p_gst_reports";
public static final String DB_TBL_TXN_REPORT = "p_txn_reports";
public static final String DB_TBL_UI_OBJ_COMAPANYTYPE = "companytype" ;
public static final String DB_TBL_UI_OBJ_BUSINESS_NATURE="businessnature" ;
public static final String DB_TBL_UI_OBJ_NOOFEMPLOYEES="noofemployee";
public static final String DB_TBL_UI_OBJ_EMPLOYEE_TYPE="employeetype";
public static final String TRANSACTION_NAME_SALE = "SALE";
public static final String TRANSACTION_NAME_PURCHASE = "PURCHASE";
public static final String TRANSACTION_NAME_PAYMENT_RECEIVED = "PAYMENT_RECEIVED";
public static final String TRANSACTION_NAME_PAY_TO_VENDOR = "PAY_TO_VENDOR";
public static final String TRANSACTION_NAME_EXPENSE = "EXPENSE";
public static final String TRANSACTION_NAME_INTERNAL_TRANSFER = "INTERNAL_TRANSFER";
public static final String TRANSACTION_NAME_RETAIL_SALE = "RETAIL_SALE";
public static final String SYSTEM_AUDIT_CUSTOMER = "CUSTOMER";
public static final String SYSTEM_AUDIT_EMPLOYEE = "EMPLOYEE";
public static final String GST_REPORT_CURRENT_MONTH="current";
public static final String GST_REPORT_PREVIOUS_MONTH="previous";
public static final String EMPLOYEE_SALARY_AUDIT_TYPE_PAY="Salary_Pay";
public static final String EMPLOYEE_SALARY_AUDIT_TYPE_DUE="Salary_Due";
}
| 2,669 | 0.729487 | 0.728363 | 53 | 49.35849 | 32.840435 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.698113 | false | false | 15 |
6f4660b09c3d1723845260198ddffe3f07265b85 | 31,379,031,133,696 | d14627e0326e887007496c029b76d016eff8c9b8 | /pet-clinic-data/src/main/java/pb/spring/mypetclinic/repositories/VetRepository.java | 22920ccb20a7a6559e82b83685f39989e5524c38 | [] | no_license | PiotrBosak2/myPetClinic | https://github.com/PiotrBosak2/myPetClinic | 7332df59aa8e705d8d0d521ad43e090d6003207c | d003c352e9f5b67cf81e23f4ab315fc3569add6a | refs/heads/master | 2022-04-07T02:50:13.946000 | 2020-03-10T18:40:36 | 2020-03-10T18:40:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pb.spring.mypetclinic.repositories;
import org.springframework.data.repository.CrudRepository;
import pb.spring.mypetclinic.model.Vet;
public interface VetRepository extends CrudRepository<Vet,Long> {
}
| UTF-8 | Java | 214 | java | VetRepository.java | Java | [] | null | [] | package pb.spring.mypetclinic.repositories;
import org.springframework.data.repository.CrudRepository;
import pb.spring.mypetclinic.model.Vet;
public interface VetRepository extends CrudRepository<Vet,Long> {
}
| 214 | 0.836449 | 0.836449 | 8 | 25.75 | 26.588297 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
c06714b6e2f4c659d83712656fd63ab6214ed729 | 10,574,209,552,550 | ece7ef713c48f94fccc44c0367e499a3109eaef1 | /ClinicManagement/src/com/bridgelabz/clinicmanagement/model/Patients.java | c65e49fd1276adcf9d5880052a5ab11e62a2c7b4 | [] | no_license | shivani5853/OOPs | https://github.com/shivani5853/OOPs | c43d415525f8312b82ba86858d7980159a9162e7 | 42f4074f262f653361e831933ce827ed317fbae2 | refs/heads/master | 2020-09-16T22:31:30.165000 | 2019-11-25T09:09:30 | 2019-11-25T09:09:30 | 223,905,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /******************************************************************************
* Purpose: This programme is used to manage a list of Doctors associated with the Clinique. This also manages the list of patients who use the clinique. It manages Doctors by Name, Id, Specialization and Availability (AM, PM or both). It manages Patients by Name, ID, Mobile Number and Age. The Program allows users to search Doctor by name, id, Specialization or Availability. Also the programs
allows users to search patient by name, mobile number or id.
*
* @author Shivani Kumari
* @version 1.0
* @since 20-11-2019
*
******************************************************************************/
/*
* PACKAGE NAME
*/
package com.bridgelabz.clinicmanagement.model;
public class Patients {
/*
* PRIVATE INSTANCE VARIABLE
*/
private String patientName;
private String id;
private long mobile;
private int age;
/*
* SETTERS AND GETTERS
*/
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* TO STRING METHOD
*/
@Override
public String toString() {
return "Patients [patientName=" + patientName + ", id=" + id + ", mobile=" + mobile + ", age=" + age + "]";
}
} | UTF-8 | Java | 1,661 | java | Patients.java | Java | [
{
"context": "nt by name, mobile number or id.\r\n *\r\n * @author Shivani Kumari\r\n * @version 1.0\r\n * @since 20-11-2019\r\n *\r\n ",
"end": 578,
"score": 0.9997718930244446,
"start": 564,
"tag": "NAME",
"value": "Shivani Kumari"
}
] | null | [] | /******************************************************************************
* Purpose: This programme is used to manage a list of Doctors associated with the Clinique. This also manages the list of patients who use the clinique. It manages Doctors by Name, Id, Specialization and Availability (AM, PM or both). It manages Patients by Name, ID, Mobile Number and Age. The Program allows users to search Doctor by name, id, Specialization or Availability. Also the programs
allows users to search patient by name, mobile number or id.
*
* @author <NAME>
* @version 1.0
* @since 20-11-2019
*
******************************************************************************/
/*
* PACKAGE NAME
*/
package com.bridgelabz.clinicmanagement.model;
public class Patients {
/*
* PRIVATE INSTANCE VARIABLE
*/
private String patientName;
private String id;
private long mobile;
private int age;
/*
* SETTERS AND GETTERS
*/
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* TO STRING METHOD
*/
@Override
public String toString() {
return "Patients [patientName=" + patientName + ", id=" + id + ", mobile=" + mobile + ", age=" + age + "]";
}
} | 1,653 | 0.590608 | 0.584588 | 70 | 21.757143 | 49.792839 | 397 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.114286 | false | false | 9 |
c3299fa8d437cf37d0b7a84d5bedefdc27bb0056 | 8,839,042,760,327 | f46d6620acff261a3cf88c3586cd349c47bef652 | /Java-Advanced/Advanced/StacksAndQueues/SimpleTextEdintor.java | d23035f15111ac02388f8ec42c9013f5f9bc2877 | [] | no_license | Vasetoo0/SoftUni-Homeworks | https://github.com/Vasetoo0/SoftUni-Homeworks | 2af571cebb8183411e39c07922f0bb56814ccf99 | d96224011d7a1c668364eaccef69f80d181c87d2 | refs/heads/master | 2020-05-03T14:16:36.761000 | 2020-03-19T09:29:53 | 2020-03-19T09:29:53 | 178,673,149 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Advanced.StacksAndQueues;
import java.util.ArrayDeque;
import java.util.Scanner;
public class SimpleTextEdintor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = Integer.parseInt(scanner.nextLine());
String currText = "";
ArrayDeque<String> undoes = new ArrayDeque<>();
for (int i = 0; i < count; i++) {
String[] data = scanner.nextLine().split("\\s+");
String command = data[0];
switch (command) {
case "1":
undoes.push(currText);
String elements = data[1];
currText += elements;
break;
case "2":
undoes.push(currText);
int elementsToErase = Integer.parseInt(data[1]);
for (int j = 0; j < elementsToErase; j++) {
currText = currText.substring(0, currText.length() - 1);
}
break;
case "3":
int indexToShow = Integer.parseInt(data[1]);
try {
System.out.println(currText.charAt(indexToShow - 1));
} catch (Exception e) {
}
break;
case "4":
currText = undoes.pop();
break;
}
}
}
}
| UTF-8 | Java | 1,486 | java | SimpleTextEdintor.java | Java | [] | null | [] | package Advanced.StacksAndQueues;
import java.util.ArrayDeque;
import java.util.Scanner;
public class SimpleTextEdintor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = Integer.parseInt(scanner.nextLine());
String currText = "";
ArrayDeque<String> undoes = new ArrayDeque<>();
for (int i = 0; i < count; i++) {
String[] data = scanner.nextLine().split("\\s+");
String command = data[0];
switch (command) {
case "1":
undoes.push(currText);
String elements = data[1];
currText += elements;
break;
case "2":
undoes.push(currText);
int elementsToErase = Integer.parseInt(data[1]);
for (int j = 0; j < elementsToErase; j++) {
currText = currText.substring(0, currText.length() - 1);
}
break;
case "3":
int indexToShow = Integer.parseInt(data[1]);
try {
System.out.println(currText.charAt(indexToShow - 1));
} catch (Exception e) {
}
break;
case "4":
currText = undoes.pop();
break;
}
}
}
}
| 1,486 | 0.440781 | 0.432032 | 56 | 25.535715 | 22.85198 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482143 | false | false | 9 |
c23b8cc08ab0da30057e5e71e256e55cb9a4fd2b | 29,643,864,285,147 | 7ba46bde7622a787efced5a8e473422a6640b327 | /gate_three/gate_three-web/src/test/java/com/econstruction/gate_three/test/zul/util/filler/budget/BudgetLineDocumentFiller.java | 9be12f019733e8d0fdbb40340bbf87be66ccf0cb | [] | no_license | szhou2015/gatethree_trunk_test | https://github.com/szhou2015/gatethree_trunk_test | d736ef3683f3be3b09ae1def37bfc85a11738a83 | f802393c2a5ee79777ab76a3f5f28612c42e2304 | refs/heads/master | 2016-09-16T09:45:54.009000 | 2015-04-09T19:25:56 | 2015-04-09T19:25:56 | 33,679,651 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* EllisDon,
* Copyright 2008, EllisDon., and individual contributors as indicated
* by the @authors tag.
*
* This program is copyright protected and belongs to EllisDon. All rights are
* reserved.
*
* This software 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.
*/
package com.econstruction.gate_three.test.zul.util.filler.budget;
import com.econstruction.gate_three.test.zul.util.filler.DocumentFiller;
import com.econstruction.gate_three.testmanager.G3FETestBase;
/**
*
* @author LGS/tveilleux
* @version 1.0 2013-07-30
*/
public class BudgetLineDocumentFiller extends DocumentFiller {
/**
* Constructor of DocumentFillerBudgetLine
*
* @param test
*/
public BudgetLineDocumentFiller(G3FETestBase test) {
super(test);
// TODO Auto-generated constructor stub
}
/**
* TabPanel : <code>budget\tabpanels\tp_budgetLineTransactions.zul</code><br/>
* <p>
* This method will fill the following form panels :
* </p>
* <ol>
* <li><code>fp_costaccounttransactions</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillTransactions() {
selectSection("tabBudgetLineTransactions");
}
/**
* TabPanel : <code>budget\tabpanels\tp_costAccountAssignment.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_costAccountAssignment</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillCostAccountAssignment() {
selectSection("tabBudgetLineCostAssignment");
clickButton("btnAssignCostAccount");//Label=Assign Cost Accounts
checkRowInG3View("assignCostAccountBudgetLineView",0);
clickButton("btnAddCostAccounts");//Label=Add Cost Accounts
clickButton("btnAssign");//Label=Assign Cost Accounts
clickActionLinkInG3View("g3viewAssignment","Allocate Available",0);//ActionId = 5
typeInG3View("g3viewAssignment", "allocatedToThisBudgetLine",0, "25000.00");
clickActionLinkInG3View("g3viewAssignment","Apply",0);//ActionId = 4
}
/**
* TabPanel : <code>budget\tabpanels\tp_summaryBudgetLine.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_summaryBudgetLine</code></li>
* <li><code>fp_financialSummary</code></li>
* <li><code>fp_budgetLineComments</code></li>
* <li><code>fp_budgetLineAttachments</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillSummary(String budgetLine, String budgetlinenumber) {
selectSection("tabBudgetLineBudgetLine");
setTextValue("budgetlinenumber",budgetlinenumber);
setTextValue("budgetlinename", budgetLine+"-"+budgetlinenumber); // Stored value = zatsBudgetLine-20130821033016
setTextValue("draftBudget","10000");
setTextValue("richTextEditor","<p>comment</p>");
clickUpload("btnAddAttachments");
//Use uploadReport(btnAddAttachments, "<INSERT YOUR KINDOFDOCUMENTNAME HERE>");
// to upload the "Main" jrxml file in the ~/conf/reports/ folder.
}
/**
* TabPanel : <code>budget\tabpanels\tp_originalBudgetAdjustments.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_originalBudgetAdjustment</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillOriginalBudgetAdjustments() {
//TODO TEST FE (where it is?)
}
}
| UTF-8 | Java | 3,556 | java | BudgetLineDocumentFiller.java | Java | [
{
"context": " * </ol>\r\n\t * \r\n\t * @param test \n \t * @author LGS/tveilleux\r\n\t */\r\n\tpublic void fillSummary(String budgetLin",
"end": 2605,
"score": 0.7932106852531433,
"start": 2596,
"tag": "USERNAME",
"value": "tveilleux"
},
{
"context": " * </ol>\r\n\t * \r\n\t * @par... | null | [] | /**
* EllisDon,
* Copyright 2008, EllisDon., and individual contributors as indicated
* by the @authors tag.
*
* This program is copyright protected and belongs to EllisDon. All rights are
* reserved.
*
* This software 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.
*/
package com.econstruction.gate_three.test.zul.util.filler.budget;
import com.econstruction.gate_three.test.zul.util.filler.DocumentFiller;
import com.econstruction.gate_three.testmanager.G3FETestBase;
/**
*
* @author LGS/tveilleux
* @version 1.0 2013-07-30
*/
public class BudgetLineDocumentFiller extends DocumentFiller {
/**
* Constructor of DocumentFillerBudgetLine
*
* @param test
*/
public BudgetLineDocumentFiller(G3FETestBase test) {
super(test);
// TODO Auto-generated constructor stub
}
/**
* TabPanel : <code>budget\tabpanels\tp_budgetLineTransactions.zul</code><br/>
* <p>
* This method will fill the following form panels :
* </p>
* <ol>
* <li><code>fp_costaccounttransactions</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillTransactions() {
selectSection("tabBudgetLineTransactions");
}
/**
* TabPanel : <code>budget\tabpanels\tp_costAccountAssignment.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_costAccountAssignment</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillCostAccountAssignment() {
selectSection("tabBudgetLineCostAssignment");
clickButton("btnAssignCostAccount");//Label=Assign Cost Accounts
checkRowInG3View("assignCostAccountBudgetLineView",0);
clickButton("btnAddCostAccounts");//Label=Add Cost Accounts
clickButton("btnAssign");//Label=Assign Cost Accounts
clickActionLinkInG3View("g3viewAssignment","Allocate Available",0);//ActionId = 5
typeInG3View("g3viewAssignment", "allocatedToThisBudgetLine",0, "25000.00");
clickActionLinkInG3View("g3viewAssignment","Apply",0);//ActionId = 4
}
/**
* TabPanel : <code>budget\tabpanels\tp_summaryBudgetLine.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_summaryBudgetLine</code></li>
* <li><code>fp_financialSummary</code></li>
* <li><code>fp_budgetLineComments</code></li>
* <li><code>fp_budgetLineAttachments</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillSummary(String budgetLine, String budgetlinenumber) {
selectSection("tabBudgetLineBudgetLine");
setTextValue("budgetlinenumber",budgetlinenumber);
setTextValue("budgetlinename", budgetLine+"-"+budgetlinenumber); // Stored value = zatsBudgetLine-20130821033016
setTextValue("draftBudget","10000");
setTextValue("richTextEditor","<p>comment</p>");
clickUpload("btnAddAttachments");
//Use uploadReport(btnAddAttachments, "<INSERT YOUR KINDOFDOCUMENTNAME HERE>");
// to upload the "Main" jrxml file in the ~/conf/reports/ folder.
}
/**
* TabPanel : <code>budget\tabpanels\tp_originalBudgetAdjustments.zul</code><br/>
* <p>This method will fill the following form panels :</p>
* <ol>
* <li><code>fp_originalBudgetAdjustment</code></li>
* </ol>
*
* @param test
* @author LGS/tveilleux
*/
public void fillOriginalBudgetAdjustments() {
//TODO TEST FE (where it is?)
}
}
| 3,556 | 0.693195 | 0.677728 | 112 | 29.8125 | 28.076914 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.116071 | false | false | 9 |
4a0a7442d19d3a9553527976a662650debcd4d05 | 12,635,793,847,116 | edc806cde9b9fea8f55c1c06f6e4c3db8137c03c | /app/src/main/java/my/maslianah/com/pickfeastfyp/DatabaseHelper.java | 2e9972ea378a789f710259aeaf4e78653e7351c6 | [] | no_license | Maslianah/Pick-Feast | https://github.com/Maslianah/Pick-Feast | 262541563ee1bfa452ce791fc6b0753f1ff8c7db | d27c3ed6976ec161bcc44bb68f866b60205af4a5 | refs/heads/master | 2020-03-18T13:32:34.245000 | 2018-05-25T03:22:12 | 2018-05-25T03:22:12 | 134,790,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package my.maslianah.com.pickfeastfyp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "STORAGE";
public static final String TABLE_STORAGE = "storage";
public static final String col1 = "pack_id";
public static final String col2 = "charity_id";
public static final String col3 = "status";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(" CREATE TABLE " + TABLE_STORAGE + " (pack_id TEXT, charity_id TEXT, status INTEGER);");
Log.e("msg", "table created");
}
catch (Exception e)
{
Log.e("msg", "hey something wrong here");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STORAGE);
// Create tables again
onCreate(db);
}
public boolean insertData()
{
SQLiteDatabase db = this.getWritableDatabase();
try {
ContentValues cv = new ContentValues();
cv.put(col1, "P001");
cv.put(col2, "");
cv.put(col3, 0);
long result = db.insert(TABLE_STORAGE, null, cv);
}
catch (Exception e)
{
Log.e("msg", "cannot insertData");
}
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * from "+TABLE_STORAGE, null);
return res;
}
public boolean updatePackID(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col1, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
public boolean updateCharityID(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col2, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
public boolean updateTheme(int id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col3, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
}
| UTF-8 | Java | 3,510 | java | DatabaseHelper.java | Java | [] | null | [] | package my.maslianah.com.pickfeastfyp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "STORAGE";
public static final String TABLE_STORAGE = "storage";
public static final String col1 = "pack_id";
public static final String col2 = "charity_id";
public static final String col3 = "status";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(" CREATE TABLE " + TABLE_STORAGE + " (pack_id TEXT, charity_id TEXT, status INTEGER);");
Log.e("msg", "table created");
}
catch (Exception e)
{
Log.e("msg", "hey something wrong here");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STORAGE);
// Create tables again
onCreate(db);
}
public boolean insertData()
{
SQLiteDatabase db = this.getWritableDatabase();
try {
ContentValues cv = new ContentValues();
cv.put(col1, "P001");
cv.put(col2, "");
cv.put(col3, 0);
long result = db.insert(TABLE_STORAGE, null, cv);
}
catch (Exception e)
{
Log.e("msg", "cannot insertData");
}
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * from "+TABLE_STORAGE, null);
return res;
}
public boolean updatePackID(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col1, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
public boolean updateCharityID(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col2, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
public boolean updateTheme(int id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(col3, id);
db.update(TABLE_STORAGE, cv, null, null);
return true;
}
}
| 3,510 | 0.57151 | 0.567521 | 105 | 32.323811 | 26.184509 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.780952 | false | false | 9 |
adb6c3e98d9397da887a5adb9342f1f41c4b1e26 | 24,627,342,525,551 | 5fefc5276dcade3479b33bea3e0b20a7aafd005a | /BoredApp/src/main/java/com/boredapp/repository/ReviewRepository.java | 3e934329ff54204f75bbc14d4fa4c3429b7de13b | [] | no_license | jpkravcik/BoredProject | https://github.com/jpkravcik/BoredProject | 8301c16923e822dfb3c47f9d2988d3329cd700d1 | a90e1772f3d830ee50ee93b8e56989df52b8366b | refs/heads/main | 2023-09-03T13:53:43.393000 | 2021-11-16T18:00:32 | 2021-11-16T18:00:32 | 408,630,512 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.boredapp.repository;
import org.springframework.data.repository.CrudRepository;
import com.boredapp.model.Review;
public interface ReviewRepository extends CrudRepository<Review, Integer> {
}
| UTF-8 | Java | 209 | java | ReviewRepository.java | Java | [] | null | [] | package com.boredapp.repository;
import org.springframework.data.repository.CrudRepository;
import com.boredapp.model.Review;
public interface ReviewRepository extends CrudRepository<Review, Integer> {
}
| 209 | 0.827751 | 0.827751 | 10 | 19.9 | 26.726204 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
e7c3d77e15df83baeb978e7523ab53a1874037ee | 26,439,818,725,788 | b0808c30c5c0d711a42955190b057f3b8a959585 | /src/multithreading/Synchronized_Keyword.java | 698133d50f11dae5c3ea599f749e1a57c6595985 | [] | no_license | MohanDarure/FullStackJava15Feb | https://github.com/MohanDarure/FullStackJava15Feb | 813adfe29c741ee00818aaeddb83695124e15e44 | 850157879f0f287d08d5b953cdfbc9abba081c12 | refs/heads/master | 2023-03-27T04:40:29.196000 | 2021-03-25T22:30:48 | 2021-03-25T22:30:48 | 342,234,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package multithreading;
public class Synchronized_Keyword {
int num;
public void set(){
num++;
}
public static void main(String[] args) {
Synchronized_Keyword synk =new Synchronized_Keyword();
Thread thread =new Thread(new Runnable() {
@Override
public void run() {
for(int i=1; i<=1000;i++){
synk.set();
}
}
});
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
for(int i=1; i<=1000;i++)
synk.set();
}
});
thread.start();
thread1.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(synk.num);
}
}
| UTF-8 | Java | 1,010 | java | Synchronized_Keyword.java | Java | [] | null | [] | package multithreading;
public class Synchronized_Keyword {
int num;
public void set(){
num++;
}
public static void main(String[] args) {
Synchronized_Keyword synk =new Synchronized_Keyword();
Thread thread =new Thread(new Runnable() {
@Override
public void run() {
for(int i=1; i<=1000;i++){
synk.set();
}
}
});
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
for(int i=1; i<=1000;i++)
synk.set();
}
});
thread.start();
thread1.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(synk.num);
}
}
| 1,010 | 0.449505 | 0.436634 | 43 | 22.488373 | 15.776597 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44186 | false | false | 9 |
f2642f430bbec751d92e94b88f989e2eb1924db5 | 10,617,159,212,297 | ee0ec80ddfb72670fda4f9d6b7f26cf36ef81a87 | /src/riemann/Application.java | d608168378ec567493a5b92eaff3ad2d13f6ad2e | [
"Unlicense"
] | permissive | admiralorbiter/riemann-was-on-to-sum-thing | https://github.com/admiralorbiter/riemann-was-on-to-sum-thing | 3d51f72bf89b8170924b81b1649ac5783ffddd91 | 64c081e30fd63a5dda97c9e1ccd593a62e931732 | refs/heads/master | 2021-06-05T10:59:26.151000 | 2021-04-15T17:33:18 | 2021-04-15T17:33:18 | 135,071,551 | 0 | 0 | null | false | 2021-04-15T17:00:10 | 2018-05-27T18:29:17 | 2019-05-27T00:49:24 | 2021-04-15T17:00:10 | 26 | 0 | 0 | 0 | Java | false | false | package riemann;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class Application extends JFrame{
private enum State {
INPUT,
DISPLAY;
}
private InputFrame inputframe = new InputFrame();
private SolidFrame solidframe=null;
private State state = State.INPUT;
public Application() {
setSize(1400, 800);
setTitle("Welcome to the Circus of Values");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
inputframe.setVisible(true);
add(inputframe);
}
public static void main(String[] args) {
Application app = new Application();
app.setVisible(true);
while(true)
app.run();
}
public void run() {
if(state==State.INPUT) {
System.out.println(inputframe.showSolid());
if(inputframe.showSolid() && solidframe==null) {
remove(inputframe);
setTitle("Riemann was on to Sum Thing");
solidframe = new SolidFrame(inputframe.getLowerBound(), inputframe.getUpperBound(), (int) inputframe.getN());
solidframe.setVisible(true);
add(solidframe);
revalidate();
repaint();
state=State.DISPLAY;
}
}
if(state==State.DISPLAY)
solidframe.run();
/*
System.out.println(inputframe.showSolid());
if(inputframe.showSolid() && solidframe==null) {
remove(inputframe);
setTitle("Riemann was on to Sum Thing");
solidframe = new SolidFrame(inputframe.getLowerBound(), inputframe.getUpperBound(), (int) inputframe.getN());
solidframe.setVisible(true);
add(solidframe);
revalidate();
repaint();
}else if(solidframe!=null) {
solidframe.run();
}*/
}
}
| UTF-8 | Java | 1,723 | java | Application.java | Java | [
{
"context": "==null) {\r\n\t\t\t\tremove(inputframe);\r\n\t\t\t\tsetTitle(\"Riemann was on to Sum Thing\");\r\n\t\t\t\tsolidframe = new Soli",
"end": 952,
"score": 0.846976101398468,
"start": 945,
"tag": "NAME",
"value": "Riemann"
},
{
"context": "me==null) {\r\n\t\t\tremove(inputfr... | null | [] | package riemann;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class Application extends JFrame{
private enum State {
INPUT,
DISPLAY;
}
private InputFrame inputframe = new InputFrame();
private SolidFrame solidframe=null;
private State state = State.INPUT;
public Application() {
setSize(1400, 800);
setTitle("Welcome to the Circus of Values");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
inputframe.setVisible(true);
add(inputframe);
}
public static void main(String[] args) {
Application app = new Application();
app.setVisible(true);
while(true)
app.run();
}
public void run() {
if(state==State.INPUT) {
System.out.println(inputframe.showSolid());
if(inputframe.showSolid() && solidframe==null) {
remove(inputframe);
setTitle("Riemann was on to Sum Thing");
solidframe = new SolidFrame(inputframe.getLowerBound(), inputframe.getUpperBound(), (int) inputframe.getN());
solidframe.setVisible(true);
add(solidframe);
revalidate();
repaint();
state=State.DISPLAY;
}
}
if(state==State.DISPLAY)
solidframe.run();
/*
System.out.println(inputframe.showSolid());
if(inputframe.showSolid() && solidframe==null) {
remove(inputframe);
setTitle("Riemann was on to Sum Thing");
solidframe = new SolidFrame(inputframe.getLowerBound(), inputframe.getUpperBound(), (int) inputframe.getN());
solidframe.setVisible(true);
add(solidframe);
revalidate();
repaint();
}else if(solidframe!=null) {
solidframe.run();
}*/
}
}
| 1,723 | 0.661637 | 0.657574 | 73 | 21.602739 | 22.011044 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.452055 | false | false | 9 |
a97499f289bbdfb341a006f52adff825b35d47c2 | 9,388,798,554,826 | a251b9f43cf6ad992ee31f76ab38cae61a6e31ee | /twill-core/src/test/java/org/apache/twill/internal/DebugOptionsTest.java | df9697334ff5e85040aeb85f5f7ee5c56e582ed4 | [
"Apache-2.0",
"LicenseRef-scancode-unknown"
] | permissive | apache/twill | https://github.com/apache/twill | 3c4d8696941207ce62e4cad447d18685b20f94b8 | 29bea3409ced14a269d07cf1d91d60aae872d49e | refs/heads/master | 2023-07-02T20:16:21.405000 | 2020-03-15T22:07:16 | 2020-03-16T01:37:47 | 64,458,355 | 70 | 139 | Apache-2.0 | false | 2020-03-16T01:37:58 | 2016-07-29T07:00:06 | 2020-01-21T21:54:37 | 2020-03-16T01:37:57 | 13,154 | 60 | 59 | 3 | Java | false | false | /*
* 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.twill.internal;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.util.Set;
/**
* Unit test for {@link org.apache.twill.internal.JvmOptions.DebugOptions} class.
*/
public class DebugOptionsTest {
@Test
public void testNoDebug() {
JvmOptions.DebugOptions noDebug = new JvmOptions.DebugOptions(false, false, null);
Assert.assertEquals(JvmOptions.DebugOptions.NO_DEBUG, noDebug);
}
@Test
public void testWithNull() {
JvmOptions.DebugOptions noDebug = new JvmOptions.DebugOptions(false, false, null);
Assert.assertNotEquals(noDebug, null);
}
@Test
public void testDoDebug() {
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, false, null);
Assert.assertNotEquals(JvmOptions.DebugOptions.NO_DEBUG, option1);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, false, null);
Assert.assertEquals(option1, option2);
}
@Test
public void testDoSuspend() {
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, true, null);
Assert.assertNotEquals(JvmOptions.DebugOptions.NO_DEBUG, option1);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, true, null);
Assert.assertEquals(option1, option2);
}
@Test
public void testSameRunnables() {
Set<String> runnables = Sets.newHashSet();
runnables.add("runnable1");
runnables.add("runnable2");
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(false, false, runnables);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(false, false, runnables);
Assert.assertEquals(option1, option2);
}
@Test
public void testDifferentRunnables() {
Set<String> runnables1 = Sets.newHashSet();
runnables1.add("runnable1");
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, false, runnables1);
Assert.assertNotEquals(option1, JvmOptions.DebugOptions.NO_DEBUG);
Set<String> runnables2 = Sets.newHashSet();
runnables2.add("runnable2-1");
runnables2.add("runnable2-2");
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, false, runnables2);
Assert.assertNotEquals(option1, option2);
}
}
| UTF-8 | Java | 3,066 | java | DebugOptionsTest.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.twill.internal;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.util.Set;
/**
* Unit test for {@link org.apache.twill.internal.JvmOptions.DebugOptions} class.
*/
public class DebugOptionsTest {
@Test
public void testNoDebug() {
JvmOptions.DebugOptions noDebug = new JvmOptions.DebugOptions(false, false, null);
Assert.assertEquals(JvmOptions.DebugOptions.NO_DEBUG, noDebug);
}
@Test
public void testWithNull() {
JvmOptions.DebugOptions noDebug = new JvmOptions.DebugOptions(false, false, null);
Assert.assertNotEquals(noDebug, null);
}
@Test
public void testDoDebug() {
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, false, null);
Assert.assertNotEquals(JvmOptions.DebugOptions.NO_DEBUG, option1);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, false, null);
Assert.assertEquals(option1, option2);
}
@Test
public void testDoSuspend() {
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, true, null);
Assert.assertNotEquals(JvmOptions.DebugOptions.NO_DEBUG, option1);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, true, null);
Assert.assertEquals(option1, option2);
}
@Test
public void testSameRunnables() {
Set<String> runnables = Sets.newHashSet();
runnables.add("runnable1");
runnables.add("runnable2");
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(false, false, runnables);
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(false, false, runnables);
Assert.assertEquals(option1, option2);
}
@Test
public void testDifferentRunnables() {
Set<String> runnables1 = Sets.newHashSet();
runnables1.add("runnable1");
JvmOptions.DebugOptions option1 = new JvmOptions.DebugOptions(true, false, runnables1);
Assert.assertNotEquals(option1, JvmOptions.DebugOptions.NO_DEBUG);
Set<String> runnables2 = Sets.newHashSet();
runnables2.add("runnable2-1");
runnables2.add("runnable2-2");
JvmOptions.DebugOptions option2 = new JvmOptions.DebugOptions(true, false, runnables2);
Assert.assertNotEquals(option1, option2);
}
}
| 3,066 | 0.741683 | 0.729615 | 99 | 29.969696 | 30.8517 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
4565f63da0e7829660464bd3577aa729ae44661d | 11,793,980,233,835 | 05d4ef36bb3e491f41c930d90b92642a6a52841c | /dealingapp/src/main/java/com/example/dealingapp/mvc/inner/tab/tab1/Tab1.java | d2fd6979d780d0d87d811022f2e8f6a32d21fb2b | [] | no_license | jonnychu/dealing | https://github.com/jonnychu/dealing | 69c7efedde49069c9e4c0edc43d2290b4fbb78a8 | 84b08345bd2e748517f90a067210389d48566a0d | refs/heads/master | 2021-01-10T09:58:37.390000 | 2015-12-03T07:53:00 | 2015-12-03T07:53:00 | 46,970,833 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.dealingapp.mvc.inner.tab.tab1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import com.example.dealingapp.mvc.Context;
import com.example.dealingapp.mvc.inner.AbstractInnerFrame;
import com.example.dealingapp.mvc.plugin.price.PricePanel;
import com.example.dealingapp.util.ComponentFactory;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.factories.Paddings;
@SuppressWarnings("serial")
public class Tab1 extends AbstractInnerFrame {
private JTabbedPane tabbedPane;
private JButton btnStart;
public Tab1(Context context) {
super(context);
}
@Override
protected FormBuilder getLayoutBuilder() {
return FormBuilder.create().debug(context.isDebug()).columns("$lcgap,fill:pref:grow,$lcgap")
.rows("$lcgap,fill:pref,$lcgap").padding(Paddings.EMPTY);
}
@Override
protected void initGUI(FormBuilder builder) {
//
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
//
List<PricePanel> allPrice = new LinkedList<>();
int col = 5;
int row = 6;
FormBuilder price = FormBuilder.create().columns(col+"*(pref:grow(0.2))").rows(row+"*(pref:grow(0.1))");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
PricePanel pp = new PricePanel();
allPrice.add(pp);
price.add(pp).xy(i+1, j+1);
}
}
btnStart = ComponentFactory.XJButton.create("Start", "start", new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CountDownLatch cdl = new CountDownLatch(col*row);
for (PricePanel pricePanel : allPrice) {
pricePanel.getPrice1().subcribe(cdl);
cdl.countDown();
pricePanel.getPrice2().subcribe(cdl);
cdl.countDown();
}
}
});
JPanel tabbedPanel = FormBuilder.create()
.columns("fill:pref:grow,60dlu")
.rows("20dlu,20dlu,fill:pref:grow")
.add(price.build()).xywh(1, 1, 1, 3).add(btnStart).xy(2, 1).build();
tabbedPane.addTab("price", tabbedPanel);
tabbedPane.addTab("trade", new JLabel("A"));
builder.add(tabbedPane).xy(2, 2).build();
}
@Override
protected void binder() {
}
}
| UTF-8 | Java | 2,400 | java | Tab1.java | Java | [] | null | [] | package com.example.dealingapp.mvc.inner.tab.tab1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import com.example.dealingapp.mvc.Context;
import com.example.dealingapp.mvc.inner.AbstractInnerFrame;
import com.example.dealingapp.mvc.plugin.price.PricePanel;
import com.example.dealingapp.util.ComponentFactory;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.factories.Paddings;
@SuppressWarnings("serial")
public class Tab1 extends AbstractInnerFrame {
private JTabbedPane tabbedPane;
private JButton btnStart;
public Tab1(Context context) {
super(context);
}
@Override
protected FormBuilder getLayoutBuilder() {
return FormBuilder.create().debug(context.isDebug()).columns("$lcgap,fill:pref:grow,$lcgap")
.rows("$lcgap,fill:pref,$lcgap").padding(Paddings.EMPTY);
}
@Override
protected void initGUI(FormBuilder builder) {
//
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
//
List<PricePanel> allPrice = new LinkedList<>();
int col = 5;
int row = 6;
FormBuilder price = FormBuilder.create().columns(col+"*(pref:grow(0.2))").rows(row+"*(pref:grow(0.1))");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
PricePanel pp = new PricePanel();
allPrice.add(pp);
price.add(pp).xy(i+1, j+1);
}
}
btnStart = ComponentFactory.XJButton.create("Start", "start", new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CountDownLatch cdl = new CountDownLatch(col*row);
for (PricePanel pricePanel : allPrice) {
pricePanel.getPrice1().subcribe(cdl);
cdl.countDown();
pricePanel.getPrice2().subcribe(cdl);
cdl.countDown();
}
}
});
JPanel tabbedPanel = FormBuilder.create()
.columns("fill:pref:grow,60dlu")
.rows("20dlu,20dlu,fill:pref:grow")
.add(price.build()).xywh(1, 1, 1, 3).add(btnStart).xy(2, 1).build();
tabbedPane.addTab("price", tabbedPanel);
tabbedPane.addTab("trade", new JLabel("A"));
builder.add(tabbedPane).xy(2, 2).build();
}
@Override
protected void binder() {
}
}
| 2,400 | 0.682083 | 0.67 | 84 | 26.571428 | 23.558582 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.309524 | false | false | 9 |
4bf49fba05e6ecc0fa73f859f7630a0853771993 | 22,617,297,824,512 | 83e9bb810559331c0a205b76cf517d6ebf46dc4c | /src/main/java/com/muspelheim/httpbucket/soap/SoapBucket.java | 01e0b2020a550f6c13a5466ee9f924b411dae7bc | [] | no_license | skrymer/http-bucket | https://github.com/skrymer/http-bucket | fae7ec5fa112ff56529c263ce03f124dabbf591e | 68bd0bd1304fb2d40b6f9b4add713bbe288f4ef7 | refs/heads/master | 2020-06-08T04:55:42.900000 | 2014-02-11T01:52:30 | 2014-02-11T01:52:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.muspelheim.httpbucket.soap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.MessageEndpoint;
import org.springframework.ws.soap.SoapMessage;
import com.muspelheim.httpbucket.handler.RequestHandler;
public class SoapBucket implements MessageEndpoint {
private static final Logger LOG = Logger.getLogger(SoapBucket.class);
@Autowired
public void setSoapRequestHandler(RequestHandler<SoapMessage, SoapMessage> requestHandler){
this.requestHandler = requestHandler;
}
private RequestHandler<SoapMessage, SoapMessage> requestHandler;
public void invoke(MessageContext messageContext) throws Exception {
LOG.trace("HttpBucketEndpoint was invoked");
SoapMessage request = (SoapMessage)messageContext.getRequest();
SoapMessage response = requestHandler.handleRequest(request);
messageContext.setResponse(response);
}
}
| UTF-8 | Java | 1,010 | java | SoapBucket.java | Java | [] | null | [] | package com.muspelheim.httpbucket.soap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.MessageEndpoint;
import org.springframework.ws.soap.SoapMessage;
import com.muspelheim.httpbucket.handler.RequestHandler;
public class SoapBucket implements MessageEndpoint {
private static final Logger LOG = Logger.getLogger(SoapBucket.class);
@Autowired
public void setSoapRequestHandler(RequestHandler<SoapMessage, SoapMessage> requestHandler){
this.requestHandler = requestHandler;
}
private RequestHandler<SoapMessage, SoapMessage> requestHandler;
public void invoke(MessageContext messageContext) throws Exception {
LOG.trace("HttpBucketEndpoint was invoked");
SoapMessage request = (SoapMessage)messageContext.getRequest();
SoapMessage response = requestHandler.handleRequest(request);
messageContext.setResponse(response);
}
}
| 1,010 | 0.815842 | 0.814851 | 29 | 33.827587 | 29.276411 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 9 |
54f9d671b920b0c306cece2e6b64844d94ea8f21 | 27,324,581,976,587 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /java/java-tests/testData/inspection/dataFlow/fixture/TrueOrEqualsSomething.java | e5542846f1cba18c5fc7856f7c6f8cd345d66464 | [
"Apache-2.0"
] | permissive | JetBrains/intellij-community | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | class Contracts {
void test(boolean b, boolean c) {
boolean x = false;
<warning descr="Condition 'x' at the left side of assignment expression is always 'false'. Can be simplified">x</warning> |= b && c;
System.out.println(x);
}
private boolean method(boolean a) {
boolean b = true;
<warning descr="Condition 'b' at the left side of assignment expression is always 'true'. Can be simplified"><caret>b</warning> |= a;
return b;
}
} | UTF-8 | Java | 471 | java | TrueOrEqualsSomething.java | Java | [] | null | [] | class Contracts {
void test(boolean b, boolean c) {
boolean x = false;
<warning descr="Condition 'x' at the left side of assignment expression is always 'false'. Can be simplified">x</warning> |= b && c;
System.out.println(x);
}
private boolean method(boolean a) {
boolean b = true;
<warning descr="Condition 'b' at the left side of assignment expression is always 'true'. Can be simplified"><caret>b</warning> |= a;
return b;
}
} | 471 | 0.653928 | 0.653928 | 15 | 30.466667 | 43.749081 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
e8f36e6f30c2e942c5545f639f48e4298f4de612 | 1,906,965,483,689 | 6cb4e7e2be7ac9928dfa1daf8da03ea8835f6b5a | /src/com/matt/repository/impl/SaItemRepositoryImpl.java | 35ac75c59f02dbfcc8289e499a7b70ffe515005f | [] | no_license | matteoyangaugust/shoppingAgent | https://github.com/matteoyangaugust/shoppingAgent | a5a69af0be597c6a0378e2c42d52d0567d5878b5 | 791214b06bfd1513d5b0d72765a373d8cd70c1b3 | refs/heads/master | 2020-04-27T11:33:02.115000 | 2019-03-07T21:06:05 | 2019-03-07T21:06:05 | 174,299,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.matt.repository.impl;
import com.matt.mapper.SaItemMapper;
import com.matt.model.Sa_item;
import com.matt.repository.BaseRepository;
import com.matt.repository.SaItemRepository;
import com.matt.util.XMLReader;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class SaItemRepositoryImpl extends BaseRepository implements SaItemRepository {
private static final XMLReader reader = XMLReader.getInstance(SaItemRepositoryImpl.class);
@Override
public List<Sa_item> findItems() {
String sql = reader.getString("select_sa_items");
try{
return systemDao.getJdbcTemplate().query(sql, new SaItemMapper());
}catch (EmptyResultDataAccessException e){
log.error("No Items");
return new ArrayList<>();
}
}
@Override
public Integer update(Sa_item itemToUpdate) {
return super.updateModelProcess("sa_item", itemToUpdate, "sn");
}
@Override
public Integer insert(Sa_item newItem) {
return super.insertModelProcess("sa_item", newItem, "sn");
}
}
| UTF-8 | Java | 1,206 | java | SaItemRepositoryImpl.java | Java | [] | null | [] | package com.matt.repository.impl;
import com.matt.mapper.SaItemMapper;
import com.matt.model.Sa_item;
import com.matt.repository.BaseRepository;
import com.matt.repository.SaItemRepository;
import com.matt.util.XMLReader;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class SaItemRepositoryImpl extends BaseRepository implements SaItemRepository {
private static final XMLReader reader = XMLReader.getInstance(SaItemRepositoryImpl.class);
@Override
public List<Sa_item> findItems() {
String sql = reader.getString("select_sa_items");
try{
return systemDao.getJdbcTemplate().query(sql, new SaItemMapper());
}catch (EmptyResultDataAccessException e){
log.error("No Items");
return new ArrayList<>();
}
}
@Override
public Integer update(Sa_item itemToUpdate) {
return super.updateModelProcess("sa_item", itemToUpdate, "sn");
}
@Override
public Integer insert(Sa_item newItem) {
return super.insertModelProcess("sa_item", newItem, "sn");
}
}
| 1,206 | 0.718076 | 0.718076 | 39 | 29.923077 | 26.399673 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564103 | false | false | 9 |
5318ae2001ddb2bdda48775af9aa73ef23da68bb | 1,906,965,480,932 | 2e4b2b71e0bc193913543b2dde33ecce6938baef | /src/com/infragistics/samples/chart/ChartCategoryRangeSeriesSample.java | 536f2babb4c5b4e49abb4c888440292a58344fa0 | [] | no_license | zouweihao/test | https://github.com/zouweihao/test | e13ee5d50940f9489d9b5f61c7e6035acad95f5f | 54c8778dd29743d6d7d5c3138db10eeacaba6669 | refs/heads/master | 2020-04-06T06:59:36.568000 | 2016-09-01T03:07:08 | 2016-09-01T03:07:08 | 62,291,297 | 1 | 0 | null | false | 2016-09-01T03:07:09 | 2016-06-30T07:52:45 | 2016-09-01T02:29:07 | 2016-09-01T03:07:08 | 25,730 | 1 | 0 | 0 | Java | null | null | package com.infragistics.samples.chart;
import java.util.List;
import com.infragistics.controls.*;
import com.infragistics.data.CategoryDataSample;
import com.infragistics.graphics.SolidColorBrush;
import com.infragistics.samplesbrowser.SampleInfo;
import android.app.Activity;
import android.graphics.Color;
import android.util.TypedValue;
public class ChartCategoryRangeSeriesSample extends SampleChart {
private int _defaultTransitionInDuration = 1000;
public ChartCategoryRangeSeriesSample(Activity activity, SampleInfo info, boolean useLegend, boolean smallData) {
super(activity, info, useLegend);
List<?> testData = CategoryDataSample.GetTemperatureData();
chart.setTitle("Temperatures Over Time");
chart.setSubtitle("Miami vs New York ");
CategoryXAxis xAxis = new CategoryXAxis();
NumericYAxis yAxis1 = new NumericYAxis();
NumericYAxis yAxis2 = new NumericYAxis();
xAxis.setTitle("Months");
yAxis1.setTitle("Temperature (C)");
yAxis2.setTitle("Temperature (F)");
xAxis.setDataSource(testData);
xAxis.setLabel("label");
xAxis.setLabelAngle(90);
xAxis.setInterval(1);
yAxis1.setMinimumValue(-10);
yAxis1.setMaximumValue(30);
yAxis2.setMinimumValue(14);
yAxis2.setMaximumValue(86);
yAxis2.setInterval(9);
yAxis1.setOnFormatLabelListener(new OnAxisNumericLabelListener());
yAxis2.setOnFormatLabelListener(new OnAxisNumericLabelListener());
SolidColorBrush transparentBrush = new SolidColorBrush();
transparentBrush.setColor(Color.parseColor("#00494949"));
yAxis1.setTitleAngle(-90);
yAxis2.setTitleAngle(90);
yAxis2.setMajorStroke(transparentBrush);
yAxis2.setTitlePosition(AxisTitlePosition.RIGHT);
yAxis2.setLabelLocation(AxisLabelsLocation.OUTSIDE_RIGHT);
chart.addAxis(xAxis);
chart.addAxis(yAxis1);
chart.addAxis(yAxis2);
HorizontalRangeCategorySeries series;
try {
series = (HorizontalRangeCategorySeries)info.seriesClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
return;
}
series.setXAxis(xAxis);
series.setYAxis(yAxis1);
series.setLowMemberPath("lowValue");
series.setHighMemberPath("highValue");
series.setDataSource(testData);
series.setTitle("NA");
series.setIsTransitionInEnabled(true);
series.setTransitionInDuration(_defaultTransitionInDuration);
series.setThickness(TypedValue.COMPLEX_UNIT_DIP, 2);
series.setAreaFillOpacity(.7);
chart.addSeries(series);
}
@Override
protected String getDescription() {
return "This sample shows the Horizontal Range Category Series.";
}
}
| UTF-8 | Java | 2,654 | java | ChartCategoryRangeSeriesSample.java | Java | [] | null | [] | package com.infragistics.samples.chart;
import java.util.List;
import com.infragistics.controls.*;
import com.infragistics.data.CategoryDataSample;
import com.infragistics.graphics.SolidColorBrush;
import com.infragistics.samplesbrowser.SampleInfo;
import android.app.Activity;
import android.graphics.Color;
import android.util.TypedValue;
public class ChartCategoryRangeSeriesSample extends SampleChart {
private int _defaultTransitionInDuration = 1000;
public ChartCategoryRangeSeriesSample(Activity activity, SampleInfo info, boolean useLegend, boolean smallData) {
super(activity, info, useLegend);
List<?> testData = CategoryDataSample.GetTemperatureData();
chart.setTitle("Temperatures Over Time");
chart.setSubtitle("Miami vs New York ");
CategoryXAxis xAxis = new CategoryXAxis();
NumericYAxis yAxis1 = new NumericYAxis();
NumericYAxis yAxis2 = new NumericYAxis();
xAxis.setTitle("Months");
yAxis1.setTitle("Temperature (C)");
yAxis2.setTitle("Temperature (F)");
xAxis.setDataSource(testData);
xAxis.setLabel("label");
xAxis.setLabelAngle(90);
xAxis.setInterval(1);
yAxis1.setMinimumValue(-10);
yAxis1.setMaximumValue(30);
yAxis2.setMinimumValue(14);
yAxis2.setMaximumValue(86);
yAxis2.setInterval(9);
yAxis1.setOnFormatLabelListener(new OnAxisNumericLabelListener());
yAxis2.setOnFormatLabelListener(new OnAxisNumericLabelListener());
SolidColorBrush transparentBrush = new SolidColorBrush();
transparentBrush.setColor(Color.parseColor("#00494949"));
yAxis1.setTitleAngle(-90);
yAxis2.setTitleAngle(90);
yAxis2.setMajorStroke(transparentBrush);
yAxis2.setTitlePosition(AxisTitlePosition.RIGHT);
yAxis2.setLabelLocation(AxisLabelsLocation.OUTSIDE_RIGHT);
chart.addAxis(xAxis);
chart.addAxis(yAxis1);
chart.addAxis(yAxis2);
HorizontalRangeCategorySeries series;
try {
series = (HorizontalRangeCategorySeries)info.seriesClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
return;
}
series.setXAxis(xAxis);
series.setYAxis(yAxis1);
series.setLowMemberPath("lowValue");
series.setHighMemberPath("highValue");
series.setDataSource(testData);
series.setTitle("NA");
series.setIsTransitionInEnabled(true);
series.setTransitionInDuration(_defaultTransitionInDuration);
series.setThickness(TypedValue.COMPLEX_UNIT_DIP, 2);
series.setAreaFillOpacity(.7);
chart.addSeries(series);
}
@Override
protected String getDescription() {
return "This sample shows the Horizontal Range Category Series.";
}
}
| 2,654 | 0.768274 | 0.749812 | 91 | 28.164835 | 22.434404 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.285714 | false | false | 9 |
9cd16f376bcb1d239e1060558f0cc936bcc282e2 | 2,370,821,992,790 | 5a04b02d379df66c9696985b17176c858808b9b5 | /app/src/main/java/com/careager/BE/DealerLoginBE.java | 7098014a374c2dde315951e3cc55f117134e0dc0 | [] | no_license | androidPranav/CarEager | https://github.com/androidPranav/CarEager | c5f9ba28a0a089cbe60f5c14b8741661e7281ef8 | bc8fd48abf0f36e26662129e59d7fc6cc11a9f50 | refs/heads/master | 2021-01-10T13:46:54.310000 | 2016-03-29T03:18:25 | 2016-03-29T03:18:25 | 49,450,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.careager.BE;
/**
* Created by Pranav Mittal on 11/5/2015.
*/
public class DealerLoginBE {
private String email;
private String password;
private String gcmID;
private String deviceID;
public String getGcmID() {
return gcmID;
}
public void setGcmID(String gcmID) {
this.gcmID = gcmID;
}
public String getDeviceID() {
return deviceID;
}
public void setDeviceID(String deviceID) {
this.deviceID = deviceID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| UTF-8 | Java | 798 | java | DealerLoginBE.java | Java | [
{
"context": "package com.careager.BE;\n\n/**\n * Created by Pranav Mittal on 11/5/2015.\n */\npublic class DealerLoginBE {\n\n ",
"end": 57,
"score": 0.9998655319213867,
"start": 44,
"tag": "NAME",
"value": "Pranav Mittal"
},
{
"context": "assword(String password) {\n this.pa... | null | [] | package com.careager.BE;
/**
* Created by <NAME> on 11/5/2015.
*/
public class DealerLoginBE {
private String email;
private String password;
private String gcmID;
private String deviceID;
public String getGcmID() {
return gcmID;
}
public void setGcmID(String gcmID) {
this.gcmID = gcmID;
}
public String getDeviceID() {
return deviceID;
}
public void setDeviceID(String deviceID) {
this.deviceID = deviceID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
| 793 | 0.606516 | 0.597744 | 44 | 17.136364 | 15.253302 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false | 9 |
f619eca30239f8711a2bfb297ecaec6d1e023775 | 6,571,300,010,036 | c4d3c5492d138a360ad25fde006fa15cb576686c | /src/bytedance/Medium147.java | d6bb7de33b95c7943696a00c3572acc9a6b07676 | [] | no_license | sollunna/leetcode-practice | https://github.com/sollunna/leetcode-practice | 605a7757fa2870440350203642390df0d073e097 | 8bbc322d9014cc2728a8a8fe20f0b5542fc37a6a | refs/heads/master | 2022-04-15T07:41:00.038000 | 2020-03-24T14:04:08 | 2020-03-24T14:04:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bytedance;
import org.junit.Test;
/**
* 对链表进行插入排序。
* <p>
* 思路:插入排序算法:
*
* 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
* 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
* 重复直到所有输入数据插入完为止。
*
* 思路:网友牛逼!!
* 虚拟头结点,游标pre,head
* head每次固定,pre从第一个元素开始遍历找到第一个大于head的元素,将head插到pre前面。
*/
public class Medium147 {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);
/*这里为什么没有将dummy.next=head
* 因为他的插入不是原地插入,而是相当于dummy另起一队,可以认为与head是平行的两个队列。
* dummy每次从head上取一个下来,dummy加一个,head就减少一个,每次取过来以后,排序
* 这样head取完了,dummy也就排好序了
* 所以一上来在第一次循环中,就会将head的第一个元素取下来挂在dummy后面,从第二个元素开始再来就排序了*/
ListNode pre = dummy;
while (head != null) {
ListNode temp = head.next;//保存head的后继
/*按理说pre每次都应该从dummy出发,但是插入排序特点就是每次我都认为前面的排好序了
* 所以pre在上一轮停留位置上的元素如果小于当前这轮要比较的元素,那证明pre之前的也小于它,
* 他就排在pre后面就好了,节省了pre从dummy遍历的时间*/
if (pre.val >= head.val) pre = dummy;
while (pre.next != null && pre.next.val < head.val) {
//如果pre.next<head证明head不应该插在它前面,pre继续往后找
pre = pre.next;
}
/*此处pre.next>head了,head就应该插在pre.next前面*/
head.next = pre.next;//head.next已经保存在temp那了,所以先操作他
pre.next = head;
head = temp;//head向后移动一步
}
return dummy.next;
}
//**********************************************************************
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
//*********************************************************************
@Test
public void test1() {
}
}
| UTF-8 | Java | 2,641 | java | Medium147.java | Java | [] | null | [] | package bytedance;
import org.junit.Test;
/**
* 对链表进行插入排序。
* <p>
* 思路:插入排序算法:
*
* 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
* 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
* 重复直到所有输入数据插入完为止。
*
* 思路:网友牛逼!!
* 虚拟头结点,游标pre,head
* head每次固定,pre从第一个元素开始遍历找到第一个大于head的元素,将head插到pre前面。
*/
public class Medium147 {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);
/*这里为什么没有将dummy.next=head
* 因为他的插入不是原地插入,而是相当于dummy另起一队,可以认为与head是平行的两个队列。
* dummy每次从head上取一个下来,dummy加一个,head就减少一个,每次取过来以后,排序
* 这样head取完了,dummy也就排好序了
* 所以一上来在第一次循环中,就会将head的第一个元素取下来挂在dummy后面,从第二个元素开始再来就排序了*/
ListNode pre = dummy;
while (head != null) {
ListNode temp = head.next;//保存head的后继
/*按理说pre每次都应该从dummy出发,但是插入排序特点就是每次我都认为前面的排好序了
* 所以pre在上一轮停留位置上的元素如果小于当前这轮要比较的元素,那证明pre之前的也小于它,
* 他就排在pre后面就好了,节省了pre从dummy遍历的时间*/
if (pre.val >= head.val) pre = dummy;
while (pre.next != null && pre.next.val < head.val) {
//如果pre.next<head证明head不应该插在它前面,pre继续往后找
pre = pre.next;
}
/*此处pre.next>head了,head就应该插在pre.next前面*/
head.next = pre.next;//head.next已经保存在temp那了,所以先操作他
pre.next = head;
head = temp;//head向后移动一步
}
return dummy.next;
}
//**********************************************************************
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
//*********************************************************************
@Test
public void test1() {
}
}
| 2,641 | 0.542841 | 0.539966 | 62 | 27.048388 | 22.150824 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241935 | false | false | 9 |
b8415ab4e720c13d1dce884f5aefc0ce30017abb | 29,678,224,065,967 | be5ba08ba3adc3e598f21158be694962fbabde04 | /src/main/java/com/omnivista/object/Device.java | 0c3cc1f2b88ad32384f214a0853e07a155c142d2 | [] | no_license | nghia0220/Exercise1-SpringMVC-Mongodb | https://github.com/nghia0220/Exercise1-SpringMVC-Mongodb | fc4d2dcd6b969e4312c95d8b5e918a4c5180332a | 84162c46c594e684c6753eaccb3999aed8b9ded6 | refs/heads/master | 2021-01-26T00:03:56.674000 | 2020-02-26T10:26:32 | 2020-02-26T10:26:32 | 243,235,055 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.omnivista.object;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Device")
public class Device {
@Id
private String id;
private String name;
private Status status;
enum Status {
UP,
DOWN,
WARNING,
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Device(String _id, String _name, Status _status) {
name = _name;
id = _id;
status = _status;
}
public Device(String _id, String _name) {
name = _name;
id = _id;
}
}
| UTF-8 | Java | 818 | java | Device.java | Java | [] | null | [] | package com.omnivista.object;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Device")
public class Device {
@Id
private String id;
private String name;
private Status status;
enum Status {
UP,
DOWN,
WARNING,
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Device(String _id, String _name, Status _status) {
name = _name;
id = _id;
status = _status;
}
public Device(String _id, String _name) {
name = _name;
id = _id;
}
}
| 818 | 0.669927 | 0.669927 | 49 | 15.693877 | 15.379823 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false | 9 |
249a5df9dc4b49109136cd4d46cb079c7fa27953 | 31,233,002,191,297 | cecc84f39cfcd106d40333bfddd4f03afd9f41c7 | /creditGateway-service-api/src/main/java/com/zdmoney/credit/api/lufax/service/Lufax100009Service.java | af6916431127447b69876d4ef6ba893b1973aae4 | [] | no_license | happyjianguo/gateway | https://github.com/happyjianguo/gateway | e8b6e15f487a72abe6c0f441414ff47eab33a25e | a9936ad58dc40e3697e8c7bf747e17a5347adb41 | refs/heads/master | 2020-07-30T08:09:51.322000 | 2018-11-17T13:58:15 | 2018-11-17T13:58:15 | 210,148,823 | 0 | 1 | null | true | 2019-09-22T13:05:53 | 2019-09-22T13:05:53 | 2018-11-17T13:59:33 | 2018-11-17T13:59:29 | 997 | 0 | 0 | 0 | null | false | false | package com.zdmoney.credit.api.lufax.service;
import java.util.Arrays;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zdmoney.credit.common.annotate.FuncIdAnnotate;
import com.zdmoney.credit.common.exception.PlatformException;
import com.zdmoney.credit.common.util.DesUtil;
import com.zdmoney.credit.common.vo.FuncResult;
import com.zdmoney.credit.config.LufaxProperties;
import com.zdmoney.credit.framework.vo.lufax.input.Lufax100009Vo;
import com.zdmoney.credit.framework.vo.lufax.input.Lufax100013Vo;
/**
* @ClassName: Lufax100001Service.java
* @Description:
* @author 柳云华
* @version V1.0
* @Since JDK 1.7
* @Date 2017年4月19日 下午2:04:44
*/
@Service
public class Lufax100009Service extends LufaxBusinessService {
private static final Log LOGGER = LogFactory.getLog(LufaxBusinessService.class);
@Autowired
private LufaxProperties lufaxProperties;
private static final String PRODUCT_TYPE = "1000500010";
private static final String INTERFACE_ID_10 = "800010";
private static final String INTERFACE_ID_70 = "200100";
@FuncIdAnnotate(value = "lufax100009", desc = "证大发起一般还款/提前还款指令/逾期回购指令", voCls = Lufax100009Vo.class)
public FuncResult execute(Lufax100009Vo vo) {
try {
String jsonStr = JSON.toJSONString(vo);
LOGGER.info("证大发起一般还款/提前还款指令/逾期回购指令:" + jsonStr);
String encryptStr = DesUtil.encrypt(jsonStr, "utf-8", lufaxProperties.getKeyStorePassword(), lufaxProperties.getKeyStoreFileName());
JSONObject wrapper = new JSONObject();
String interface_reqser = DateTime.now().toString("yyyyMMddHHmmssSS") + vo.getInterface_id() + RandomStringUtils.randomNumeric(6);
wrapper.put("interface_reqser", interface_reqser); //请求流水
wrapper.put("interface_id", INTERFACE_ID_10);//接口编号
wrapper.put("channel_code", CHANNEL_CODE);
wrapper.put("service_company_code", SERVICE_COMPANY_CODE);
wrapper.put("info_content", encryptStr);
String wrapperStr = wrapper.toJSONString();
String fileName = "ZDJR_TO_LUFAX" + DateTime.now().toString("yyyyMMddHHmmssSSS") + ".txt";
JSONObject json = upload(fileName, wrapperStr);
if(HttpStatus.SC_OK == Integer.parseInt(json.getString("HttpStatus"))){
Lufax100013Vo vo13 = new Lufax100013Vo();
vo13.setInterfaceId(INTERFACE_ID_70);
vo13.setFile_name(Arrays.asList(json.getString("fileKey")));
vo13.setProduct_type(PRODUCT_TYPE);
return super.execute(vo13);
} else{
throw new PlatformException("上传陆金所IOBS文件失败-->状态:" + json.getString("HttpStatus") + ", 失败原因:" + json.getString("httpContent"));
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return FuncResult.fail(e.getMessage());
}
}
}
| UTF-8 | Java | 3,473 | java | Lufax100009Service.java | Java | [
{
"context": "ervice.java\n * @Description: \n * @author 柳云华\n * @version V1.0 \n * @Since JDK ",
"end": 947,
"score": 0.999788761138916,
"start": 944,
"tag": "NAME",
"value": "柳云华"
}
] | null | [] | package com.zdmoney.credit.api.lufax.service;
import java.util.Arrays;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zdmoney.credit.common.annotate.FuncIdAnnotate;
import com.zdmoney.credit.common.exception.PlatformException;
import com.zdmoney.credit.common.util.DesUtil;
import com.zdmoney.credit.common.vo.FuncResult;
import com.zdmoney.credit.config.LufaxProperties;
import com.zdmoney.credit.framework.vo.lufax.input.Lufax100009Vo;
import com.zdmoney.credit.framework.vo.lufax.input.Lufax100013Vo;
/**
* @ClassName: Lufax100001Service.java
* @Description:
* @author 柳云华
* @version V1.0
* @Since JDK 1.7
* @Date 2017年4月19日 下午2:04:44
*/
@Service
public class Lufax100009Service extends LufaxBusinessService {
private static final Log LOGGER = LogFactory.getLog(LufaxBusinessService.class);
@Autowired
private LufaxProperties lufaxProperties;
private static final String PRODUCT_TYPE = "1000500010";
private static final String INTERFACE_ID_10 = "800010";
private static final String INTERFACE_ID_70 = "200100";
@FuncIdAnnotate(value = "lufax100009", desc = "证大发起一般还款/提前还款指令/逾期回购指令", voCls = Lufax100009Vo.class)
public FuncResult execute(Lufax100009Vo vo) {
try {
String jsonStr = JSON.toJSONString(vo);
LOGGER.info("证大发起一般还款/提前还款指令/逾期回购指令:" + jsonStr);
String encryptStr = DesUtil.encrypt(jsonStr, "utf-8", lufaxProperties.getKeyStorePassword(), lufaxProperties.getKeyStoreFileName());
JSONObject wrapper = new JSONObject();
String interface_reqser = DateTime.now().toString("yyyyMMddHHmmssSS") + vo.getInterface_id() + RandomStringUtils.randomNumeric(6);
wrapper.put("interface_reqser", interface_reqser); //请求流水
wrapper.put("interface_id", INTERFACE_ID_10);//接口编号
wrapper.put("channel_code", CHANNEL_CODE);
wrapper.put("service_company_code", SERVICE_COMPANY_CODE);
wrapper.put("info_content", encryptStr);
String wrapperStr = wrapper.toJSONString();
String fileName = "ZDJR_TO_LUFAX" + DateTime.now().toString("yyyyMMddHHmmssSSS") + ".txt";
JSONObject json = upload(fileName, wrapperStr);
if(HttpStatus.SC_OK == Integer.parseInt(json.getString("HttpStatus"))){
Lufax100013Vo vo13 = new Lufax100013Vo();
vo13.setInterfaceId(INTERFACE_ID_70);
vo13.setFile_name(Arrays.asList(json.getString("fileKey")));
vo13.setProduct_type(PRODUCT_TYPE);
return super.execute(vo13);
} else{
throw new PlatformException("上传陆金所IOBS文件失败-->状态:" + json.getString("HttpStatus") + ", 失败原因:" + json.getString("httpContent"));
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return FuncResult.fail(e.getMessage());
}
}
}
| 3,473 | 0.679398 | 0.645414 | 76 | 42.75 | 32.533031 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 9 |
5ccd601243ac63197536c9d9a74547193727d622 | 1,640,677,508,860 | 31728192b3e36147736b024dacbd4b8386779104 | /web/src/main/java/com/xiaowei/web/controller/ec/EcController.java | 05b98be0b4b6677254cca4550f578521a4eefbc5 | [] | no_license | kanshunfu123/sys | https://github.com/kanshunfu123/sys | 915f1e3e889f2ac9265ce33669e6eb36b50b1f36 | 0996ebf50abace389fd3ccc8a38caf5e06d64589 | refs/heads/master | 2020-05-16T15:09:00.935000 | 2019-04-24T01:44:56 | 2019-04-24T01:44:56 | 183,123,815 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaowei.web.controller.ec;
import com.github.pagehelper.PageInfo;
import com.xiaowei.common.common.JSONResult;
import com.xiaowei.common.error.BaseReq;
import com.xiaowei.common.req.cw.CwPushReq;
import com.xiaowei.common.req.ec.EcAddReq;
import com.xiaowei.common.req.ec.EcEditReq;
import com.xiaowei.common.req.ec.EcPageList;
import com.xiaowei.common.req.ec.EcUuidReq;
import com.xiaowei.common.req.rw.RwPageList;
import com.xiaowei.service.ec.EcService;
import com.xiaowei.service.rw.RwService;
import com.xiaowei.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
/**
* Created by MOMO on 2019/1/10.
*/
@RestController
@Slf4j
@RequestMapping("/platform")
public class EcController extends BaseController {
@Autowired
private EcService ecService;
@Autowired
private RwService rwService;
@PostMapping("/ec/add/v1")
public JSONResult add(@Validated(EcAddReq.Add.class) @RequestBody EcAddReq ecAddReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.interEc(ecAddReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},新增电梯失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("新增电梯失败");
}
}
@PostMapping("/ec/uuid/v1")
public JSONResult uuid(@Validated(EcUuidReq.Add.class) @RequestBody EcUuidReq ecUuidReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.uuidEc(ecUuidReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},查询电梯失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("查询电梯失败");
}
}
@PostMapping("/ec/edit/v1")
public JSONResult edit(@Validated(EcEditReq.Add.class) @RequestBody EcEditReq ecEditReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.editEc(ecEditReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},编辑电梯设备失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("编辑电梯设备失败");
}
}
@PostMapping("/ec/pageList/v1")
public JSONResult parentId(@Validated(RwPageList.Add.class) @RequestBody RwPageList rwPageList,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
PageInfo pageInfo = rwService.pageList(rwPageList, this.redisUser(userInfo));
return JSONResult.ok(pageInfo);
} catch (UnsupportedEncodingException e) {
log.error("电梯分页失败:{},电梯分页失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("电梯分页失败");
}
}
@PostMapping("/ec/selEc/v1")
public JSONResult selEc(
@RequestHeader(value = "userHeader", required = false) String userInfo) {
JSONResult jsonResult = ecService.selEc();
return jsonResult;
}
@PostMapping("/ec/push/v1")
public JSONResult editPush(@Validated(CwPushReq.Add.class) @RequestBody CwPushReq cwPushReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.editPush(cwPushReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},编辑饮用水推送失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("编辑饮用水推送失败");
}
}
}
| UTF-8 | Java | 4,088 | java | EcController.java | Java | [
{
"context": "o.UnsupportedEncodingException;\n\n/**\n * Created by MOMO on 2019/1/10.\n */\n@RestController\n@Slf4j\n@Request",
"end": 838,
"score": 0.9964737892150879,
"start": 834,
"tag": "USERNAME",
"value": "MOMO"
}
] | null | [] | package com.xiaowei.web.controller.ec;
import com.github.pagehelper.PageInfo;
import com.xiaowei.common.common.JSONResult;
import com.xiaowei.common.error.BaseReq;
import com.xiaowei.common.req.cw.CwPushReq;
import com.xiaowei.common.req.ec.EcAddReq;
import com.xiaowei.common.req.ec.EcEditReq;
import com.xiaowei.common.req.ec.EcPageList;
import com.xiaowei.common.req.ec.EcUuidReq;
import com.xiaowei.common.req.rw.RwPageList;
import com.xiaowei.service.ec.EcService;
import com.xiaowei.service.rw.RwService;
import com.xiaowei.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
/**
* Created by MOMO on 2019/1/10.
*/
@RestController
@Slf4j
@RequestMapping("/platform")
public class EcController extends BaseController {
@Autowired
private EcService ecService;
@Autowired
private RwService rwService;
@PostMapping("/ec/add/v1")
public JSONResult add(@Validated(EcAddReq.Add.class) @RequestBody EcAddReq ecAddReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.interEc(ecAddReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},新增电梯失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("新增电梯失败");
}
}
@PostMapping("/ec/uuid/v1")
public JSONResult uuid(@Validated(EcUuidReq.Add.class) @RequestBody EcUuidReq ecUuidReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.uuidEc(ecUuidReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},查询电梯失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("查询电梯失败");
}
}
@PostMapping("/ec/edit/v1")
public JSONResult edit(@Validated(EcEditReq.Add.class) @RequestBody EcEditReq ecEditReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.editEc(ecEditReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},编辑电梯设备失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("编辑电梯设备失败");
}
}
@PostMapping("/ec/pageList/v1")
public JSONResult parentId(@Validated(RwPageList.Add.class) @RequestBody RwPageList rwPageList,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
PageInfo pageInfo = rwService.pageList(rwPageList, this.redisUser(userInfo));
return JSONResult.ok(pageInfo);
} catch (UnsupportedEncodingException e) {
log.error("电梯分页失败:{},电梯分页失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("电梯分页失败");
}
}
@PostMapping("/ec/selEc/v1")
public JSONResult selEc(
@RequestHeader(value = "userHeader", required = false) String userInfo) {
JSONResult jsonResult = ecService.selEc();
return jsonResult;
}
@PostMapping("/ec/push/v1")
public JSONResult editPush(@Validated(CwPushReq.Add.class) @RequestBody CwPushReq cwPushReq,
@RequestHeader(value = "userHeader", required = false) String userInfo) {
try {
return ecService.editPush(cwPushReq, redisUser(userInfo));
} catch (UnsupportedEncodingException e) {
log.error("token解析错误:{},编辑饮用水推送失败:{}", userInfo, e.getMessage());
return JSONResult.errorMap("编辑饮用水推送失败");
}
}
}
| 4,088 | 0.665126 | 0.661017 | 98 | 38.734695 | 30.461937 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653061 | false | false | 9 |
98d1aada63ea1485f7c0a81e95e07913250eb046 | 7,267,084,686,587 | 380584904f33624335e9ce7e72c70354a937e7c1 | /src/main/java/com/project/consumer/event/InnCloseEvent.java | 0185fe23ff2bbadd874d519b783a790261d76900 | [
"Apache-2.0"
] | permissive | fred1573/fqms | https://github.com/fred1573/fqms | afdce6c7f40efdd79da34b38df39b4910db53462 | ccac6c2074b16f49287ed11569ed6f9bb5c7c88b | refs/heads/master | 2020-04-01T18:39:22.047000 | 2016-06-30T10:12:02 | 2016-06-30T10:12:05 | 62,300,165 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.project.consumer.event;
import org.springframework.context.ApplicationEvent;
/**
* 处理分销商关房结果的事件
* Created by sam on 2016/4/11.
*/
public class InnCloseEvent extends ApplicationEvent {
public InnCloseEvent(Object source) {
super(source);
}
}
| UTF-8 | Java | 299 | java | InnCloseEvent.java | Java | [
{
"context": "plicationEvent;\n\n/**\n * 处理分销商关房结果的事件\n * Created by sam on 2016/4/11.\n */\npublic class InnCloseEvent exte",
"end": 128,
"score": 0.9770813584327698,
"start": 125,
"tag": "USERNAME",
"value": "sam"
}
] | null | [] | package com.project.consumer.event;
import org.springframework.context.ApplicationEvent;
/**
* 处理分销商关房结果的事件
* Created by sam on 2016/4/11.
*/
public class InnCloseEvent extends ApplicationEvent {
public InnCloseEvent(Object source) {
super(source);
}
}
| 299 | 0.723636 | 0.698182 | 14 | 18.642857 | 19.396639 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 9 |
15ab9fbfd13b5dbaf1b2830b481a39e2068e7942 | 15,075,335,228,429 | 95891c4991521ca35ea3ae9ee6d186862b3040c8 | /src/com/genersoft/fs/settlement/accountmanagement/customaccount/cmd/CustomCommand.java | 52cdbdb609dae9a5751fe5d85ce929c0b1608bcc | [] | no_license | regapple/nfs0.1 | https://github.com/regapple/nfs0.1 | 11984ba92f0ad3b862677086e979853a1d8868a4 | b8a3573d8e41f1734c41df86ec3990b5f5325549 | refs/heads/master | 2016-04-18T23:14:45.347000 | 2016-04-14T06:56:09 | 2016-04-14T06:56:10 | 43,864,526 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.genersoft.fs.settlement.accountmanagement.customaccount.cmd;
import com.genersoft.cfs.base.jszhzd.dao.JszhzdDomain;
import com.genersoft.fs.settlement.accountmanagement.customaccount.dao.ICustomDomain;
import org.loushang.next.web.cmd.BaseAjaxCommand;
import org.loushang.sca.ScaComponentFactory;
import java.math.BigDecimal;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: zhangjing
* Date: 14-1-21
* Time: 上午10:59
* To change this template use File | Settings | File Templates.
*/
public class CustomCommand extends BaseAjaxCommand {
private ICustomDomain customDomain = ScaComponentFactory.
getService(ICustomDomain.class, "fs.settlement.accountmanagement.customaccount.dao.ICustomDomain/CustomDomain");
private JszhzdDomain jszhzdDomain = ScaComponentFactory.getService(JszhzdDomain.class, "cfs.base.jszhzd.dao.JszhzdDomain/JszhzdDomain");
public void doCustomAccSave() {
HashMap hm = customDomain.doCustomAccSave(this.getParameterSet());
String zhid = (String) hm.get("zhid");
String zhbh = (String) hm.get("zhbh");
this.setReturn("newId", zhid);
this.setReturn("newBh", zhbh);
}
/**
* 通过表主键 删除(作废)
*/
public void doRemoveById() {
String[] keysArray = (String[]) getParameter("keysArray");
int updateCount = customDomain.doRemoveById(keysArray);
this.setReturn("updateCount", updateCount);
}
/*
获取执行利率
*/
public void getZxlv() {
String fdfs = (String) getParameterSet().getParameter("fdfs");
Float fdblsz = new Float(0);
if("2".equals(fdfs)){//不浮动
}else{
fdblsz = new Float(getParameterSet().getParameter("fdblsz").toString());
}
String llbh = (String) getParameterSet().getParameter("llbh");
BigDecimal zxlv = jszhzdDomain.excuteRate(fdfs, fdblsz, llbh);
this.setReturn("zxlv", zxlv);
}
}
| UTF-8 | Java | 1,997 | java | CustomCommand.java | Java | [
{
"context": "hMap;\n\n/**\n * Created with IntelliJ IDEA.\n * User: zhangjing\n * Date: 14-1-21\n * Time: 上午10:59\n * To change th",
"end": 421,
"score": 0.999012291431427,
"start": 412,
"tag": "USERNAME",
"value": "zhangjing"
}
] | null | [] | package com.genersoft.fs.settlement.accountmanagement.customaccount.cmd;
import com.genersoft.cfs.base.jszhzd.dao.JszhzdDomain;
import com.genersoft.fs.settlement.accountmanagement.customaccount.dao.ICustomDomain;
import org.loushang.next.web.cmd.BaseAjaxCommand;
import org.loushang.sca.ScaComponentFactory;
import java.math.BigDecimal;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: zhangjing
* Date: 14-1-21
* Time: 上午10:59
* To change this template use File | Settings | File Templates.
*/
public class CustomCommand extends BaseAjaxCommand {
private ICustomDomain customDomain = ScaComponentFactory.
getService(ICustomDomain.class, "fs.settlement.accountmanagement.customaccount.dao.ICustomDomain/CustomDomain");
private JszhzdDomain jszhzdDomain = ScaComponentFactory.getService(JszhzdDomain.class, "cfs.base.jszhzd.dao.JszhzdDomain/JszhzdDomain");
public void doCustomAccSave() {
HashMap hm = customDomain.doCustomAccSave(this.getParameterSet());
String zhid = (String) hm.get("zhid");
String zhbh = (String) hm.get("zhbh");
this.setReturn("newId", zhid);
this.setReturn("newBh", zhbh);
}
/**
* 通过表主键 删除(作废)
*/
public void doRemoveById() {
String[] keysArray = (String[]) getParameter("keysArray");
int updateCount = customDomain.doRemoveById(keysArray);
this.setReturn("updateCount", updateCount);
}
/*
获取执行利率
*/
public void getZxlv() {
String fdfs = (String) getParameterSet().getParameter("fdfs");
Float fdblsz = new Float(0);
if("2".equals(fdfs)){//不浮动
}else{
fdblsz = new Float(getParameterSet().getParameter("fdblsz").toString());
}
String llbh = (String) getParameterSet().getParameter("llbh");
BigDecimal zxlv = jszhzdDomain.excuteRate(fdfs, fdblsz, llbh);
this.setReturn("zxlv", zxlv);
}
}
| 1,997 | 0.685612 | 0.67998 | 57 | 33.263157 | 31.989323 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 9 |
2cd188fb9aa700daa4d3c0f3ee999c7964e28aae | 13,082,470,407,874 | 8fcba9e0d39e5fa3e4983fe2e997e6da9c39bbef | /src/test/java/com/xuguruogu/auth/test/TestBase.java | a290b06567c1c68aefc994508101d5208a265dbe | [] | no_license | maxushuang/auth | https://github.com/maxushuang/auth | 640377a4418eb92e681d945012dcc5f526499a4f | 8c0e2248e05cfd75257e0b883612ea8538d55513 | refs/heads/master | 2021-01-12T13:54:32.176000 | 2016-03-29T06:30:19 | 2016-03-29T06:30:19 | 54,951,662 | 1 | 0 | null | true | 2016-03-29T06:32:08 | 2016-03-29T06:32:07 | 2016-03-29T06:31:55 | 2016-03-29T06:30:29 | 1,262 | 0 | 0 | 0 | null | null | null | package com.xuguruogu.auth.test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Junit测试基类
*
* @author benli.lbl
* @version $Id: TestBase.java, v 0.1 Jul 28, 2015 8:04:27 PM benli.lbl Exp $
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public abstract class TestBase {
@Autowired
protected JdbcTemplate jdbcTemplate;
}
| UTF-8 | Java | 648 | java | TestBase.java | Java | [
{
"context": "JUnit4ClassRunner;\n\n/**\n * Junit测试基类\n *\n * @author benli.lbl\n * @version $Id: TestBase.java, v 0.1 Jul 28, 201",
"end": 356,
"score": 0.9962594509124756,
"start": 347,
"tag": "USERNAME",
"value": "benli.lbl"
},
{
"context": " $Id: TestBase.java, v 0.1 Jul 28, 2015... | null | [] | package com.xuguruogu.auth.test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Junit测试基类
*
* @author benli.lbl
* @version $Id: TestBase.java, v 0.1 Jul 28, 2015 8:04:27 PM benli.lbl Exp $
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public abstract class TestBase {
@Autowired
protected JdbcTemplate jdbcTemplate;
}
| 648 | 0.795313 | 0.770312 | 22 | 28.09091 | 26.674654 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
c0f15ffe22d6e060139fdc504bad719506c92c64 | 16,655,883,196,183 | 6b5f4096fa0f6f8f0a81c36e6856fb49b971fe2f | /Stemmer/src/main/java/com/khozzy/stemmer/Main.java | 58c04a3644047ccc6dd9f4d67bc31e109aa8a0cf | [] | no_license | Libardo1/GodStemIt | https://github.com/Libardo1/GodStemIt | 9ed5b88d390c67753a5a97f9ad7c066c8dcaccc6 | 1e7009fc1d2c312c64ef0b8f487f59df9169d9c3 | refs/heads/master | 2021-01-22T21:17:12.211000 | 2015-03-20T06:10:56 | 2015-03-20T06:10:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.khozzy.stemmer;
import com.khozzy.stemmer.database.DAO;
import com.khozzy.stemmer.database.mysql.MysqlDAO;
import com.khozzy.stemmer.domain.Sentence;
import com.khozzy.stemmer.stemming.PolishStemming;
import org.apache.log4j.Logger;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws ExecutionException, InterruptedException {
final DAO dao = new MysqlDAO();
long start, time;
Set<Sentence> sentences = dao.getNotProcessedStatements();
final int total = sentences.size();
logger.info(String.format("Ilość zdań do przetworzenia: %d", total));
logger.info(String.format("Liczba dostępnych procesorów: %d", Runtime.getRuntime().availableProcessors()));
start = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(total);
ExecutorService executor = Executors.newFixedThreadPool(16);
sentences.forEach(s -> executor.submit(new PolishStemming(dao, latch, s)));
executor.shutdown();
latch.await();
time = System.currentTimeMillis() - start;
logger.info(String.format("Zakończono. Całkowity czas: %.3f s", (double) time/1000));
}
}
| UTF-8 | Java | 1,519 | java | Main.java | Java | [] | null | [] | package com.khozzy.stemmer;
import com.khozzy.stemmer.database.DAO;
import com.khozzy.stemmer.database.mysql.MysqlDAO;
import com.khozzy.stemmer.domain.Sentence;
import com.khozzy.stemmer.stemming.PolishStemming;
import org.apache.log4j.Logger;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws ExecutionException, InterruptedException {
final DAO dao = new MysqlDAO();
long start, time;
Set<Sentence> sentences = dao.getNotProcessedStatements();
final int total = sentences.size();
logger.info(String.format("Ilość zdań do przetworzenia: %d", total));
logger.info(String.format("Liczba dostępnych procesorów: %d", Runtime.getRuntime().availableProcessors()));
start = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(total);
ExecutorService executor = Executors.newFixedThreadPool(16);
sentences.forEach(s -> executor.submit(new PolishStemming(dao, latch, s)));
executor.shutdown();
latch.await();
time = System.currentTimeMillis() - start;
logger.info(String.format("Zakończono. Całkowity czas: %.3f s", (double) time/1000));
}
}
| 1,519 | 0.70172 | 0.696429 | 42 | 34 | 30.70055 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 9 |
e5f86db223a3ec98acce04f1b4f870a9034594e6 | 11,699,490,947,206 | a5d5e5496d00e6174d9e462e8d4979a8ef3d2baa | /com/google/android/gms/maps/internal/C0170c.java | 6b42adb4c681d9152c195def7a6ad1639d228838 | [] | no_license | niketpatel2525/Bulls-and-Cows | https://github.com/niketpatel2525/Bulls-and-Cows | 9dc9ce7e7d8a5bcdd59c476397f4a9103f844b3a | 4bde931f0c7c03b7eb30011445e95d1abce8c193 | refs/heads/master | 2021-01-21T08:08:41.600000 | 2017-02-27T17:57:33 | 2017-02-27T17:57:33 | 83,336,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.maps.internal;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import com.google.android.gms.dynamic.C0070b;
import com.google.android.gms.dynamic.C0070b.C0357a;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.internal.ICameraUpdateFactoryDelegate.C0484a;
import com.google.android.gms.maps.internal.IMapFragmentDelegate.C0490a;
import com.google.android.gms.maps.internal.IMapViewDelegate.C0492a;
import com.google.android.gms.maps.model.internal.C0195a;
import com.google.android.gms.maps.model.internal.C0195a.C0529a;
/* renamed from: com.google.android.gms.maps.internal.c */
public interface C0170c extends IInterface {
/* renamed from: com.google.android.gms.maps.internal.c.a */
public static abstract class C0500a extends Binder implements C0170c {
/* renamed from: com.google.android.gms.maps.internal.c.a.a */
private static class C0499a implements C0170c {
private IBinder dG;
C0499a(IBinder iBinder) {
this.dG = iBinder;
}
public IMapViewDelegate m1547a(C0070b c0070b, GoogleMapOptions googleMapOptions) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
if (googleMapOptions != null) {
obtain.writeInt(1);
googleMapOptions.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.dG.transact(3, obtain, obtain2, 0);
obtain2.readException();
IMapViewDelegate O = C0492a.m1544O(obtain2.readStrongBinder());
return O;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public void m1548a(C0070b c0070b, int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
obtain.writeInt(i);
this.dG.transact(6, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public IBinder asBinder() {
return this.dG;
}
public ICameraUpdateFactoryDelegate cG() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
this.dG.transact(4, obtain, obtain2, 0);
obtain2.readException();
ICameraUpdateFactoryDelegate H = C0484a.m1540H(obtain2.readStrongBinder());
return H;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public C0195a cH() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
this.dG.transact(5, obtain, obtain2, 0);
obtain2.readException();
C0195a ac = C0529a.ac(obtain2.readStrongBinder());
return ac;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public void m1549e(C0070b c0070b) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
this.dG.transact(1, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public IMapFragmentDelegate m1550f(C0070b c0070b) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
this.dG.transact(2, obtain, obtain2, 0);
obtain2.readException();
IMapFragmentDelegate N = C0490a.m1543N(obtain2.readStrongBinder());
return N;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
public static C0170c m1551J(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.maps.internal.ICreator");
return (queryLocalInterface == null || !(queryLocalInterface instanceof C0170c)) ? new C0499a(iBinder) : (C0170c) queryLocalInterface;
}
public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
IBinder iBinder = null;
switch (code) {
case DetectedActivity.ON_BICYCLE /*1*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
m714e(C0357a.m1114z(data.readStrongBinder()));
reply.writeNoException();
return true;
case DetectedActivity.ON_FOOT /*2*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
IMapFragmentDelegate f = m715f(C0357a.m1114z(data.readStrongBinder()));
reply.writeNoException();
if (f != null) {
iBinder = f.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.STILL /*3*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
IMapViewDelegate a = m712a(C0357a.m1114z(data.readStrongBinder()), data.readInt() != 0 ? GoogleMapOptions.CREATOR.createFromParcel(data) : null);
reply.writeNoException();
if (a != null) {
iBinder = a.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.UNKNOWN /*4*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
ICameraUpdateFactoryDelegate cG = cG();
reply.writeNoException();
if (cG != null) {
iBinder = cG.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.TILTING /*5*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
C0195a cH = cH();
reply.writeNoException();
if (cH != null) {
iBinder = cH.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case GamesClient.STATUS_NETWORK_ERROR_OPERATION_FAILED /*6*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
m713a(C0357a.m1114z(data.readStrongBinder()), data.readInt());
reply.writeNoException();
return true;
case 1598968902:
reply.writeString("com.google.android.gms.maps.internal.ICreator");
return true;
default:
return super.onTransact(code, data, reply, flags);
}
}
}
IMapViewDelegate m712a(C0070b c0070b, GoogleMapOptions googleMapOptions) throws RemoteException;
void m713a(C0070b c0070b, int i) throws RemoteException;
ICameraUpdateFactoryDelegate cG() throws RemoteException;
C0195a cH() throws RemoteException;
void m714e(C0070b c0070b) throws RemoteException;
IMapFragmentDelegate m715f(C0070b c0070b) throws RemoteException;
}
| UTF-8 | Java | 9,546 | java | C0170c.java | Java | [
{
"context": "{\n obtain.writeInterfaceToken(\"com.google.android.gms.maps.internal.ICreator\");\n obta",
"end": 4636,
"score": 0.8788964152336121,
"start": 4613,
"tag": "KEY",
"value": "com.google.android.gms."
},
{
"context": "n.writeInterfaceT... | null | [] | package com.google.android.gms.maps.internal;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import com.google.android.gms.dynamic.C0070b;
import com.google.android.gms.dynamic.C0070b.C0357a;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.internal.ICameraUpdateFactoryDelegate.C0484a;
import com.google.android.gms.maps.internal.IMapFragmentDelegate.C0490a;
import com.google.android.gms.maps.internal.IMapViewDelegate.C0492a;
import com.google.android.gms.maps.model.internal.C0195a;
import com.google.android.gms.maps.model.internal.C0195a.C0529a;
/* renamed from: com.google.android.gms.maps.internal.c */
public interface C0170c extends IInterface {
/* renamed from: com.google.android.gms.maps.internal.c.a */
public static abstract class C0500a extends Binder implements C0170c {
/* renamed from: com.google.android.gms.maps.internal.c.a.a */
private static class C0499a implements C0170c {
private IBinder dG;
C0499a(IBinder iBinder) {
this.dG = iBinder;
}
public IMapViewDelegate m1547a(C0070b c0070b, GoogleMapOptions googleMapOptions) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
if (googleMapOptions != null) {
obtain.writeInt(1);
googleMapOptions.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.dG.transact(3, obtain, obtain2, 0);
obtain2.readException();
IMapViewDelegate O = C0492a.m1544O(obtain2.readStrongBinder());
return O;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public void m1548a(C0070b c0070b, int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
obtain.writeInt(i);
this.dG.transact(6, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public IBinder asBinder() {
return this.dG;
}
public ICameraUpdateFactoryDelegate cG() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
this.dG.transact(4, obtain, obtain2, 0);
obtain2.readException();
ICameraUpdateFactoryDelegate H = C0484a.m1540H(obtain2.readStrongBinder());
return H;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public C0195a cH() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
this.dG.transact(5, obtain, obtain2, 0);
obtain2.readException();
C0195a ac = C0529a.ac(obtain2.readStrongBinder());
return ac;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public void m1549e(C0070b c0070b) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
this.dG.transact(1, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public IMapFragmentDelegate m1550f(C0070b c0070b) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.maps.internal.ICreator");
obtain.writeStrongBinder(c0070b != null ? c0070b.asBinder() : null);
this.dG.transact(2, obtain, obtain2, 0);
obtain2.readException();
IMapFragmentDelegate N = C0490a.m1543N(obtain2.readStrongBinder());
return N;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
public static C0170c m1551J(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.maps.internal.ICreator");
return (queryLocalInterface == null || !(queryLocalInterface instanceof C0170c)) ? new C0499a(iBinder) : (C0170c) queryLocalInterface;
}
public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
IBinder iBinder = null;
switch (code) {
case DetectedActivity.ON_BICYCLE /*1*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
m714e(C0357a.m1114z(data.readStrongBinder()));
reply.writeNoException();
return true;
case DetectedActivity.ON_FOOT /*2*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
IMapFragmentDelegate f = m715f(C0357a.m1114z(data.readStrongBinder()));
reply.writeNoException();
if (f != null) {
iBinder = f.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.STILL /*3*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
IMapViewDelegate a = m712a(C0357a.m1114z(data.readStrongBinder()), data.readInt() != 0 ? GoogleMapOptions.CREATOR.createFromParcel(data) : null);
reply.writeNoException();
if (a != null) {
iBinder = a.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.UNKNOWN /*4*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
ICameraUpdateFactoryDelegate cG = cG();
reply.writeNoException();
if (cG != null) {
iBinder = cG.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case DetectedActivity.TILTING /*5*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
C0195a cH = cH();
reply.writeNoException();
if (cH != null) {
iBinder = cH.asBinder();
}
reply.writeStrongBinder(iBinder);
return true;
case GamesClient.STATUS_NETWORK_ERROR_OPERATION_FAILED /*6*/:
data.enforceInterface("com.google.android.gms.maps.internal.ICreator");
m713a(C0357a.m1114z(data.readStrongBinder()), data.readInt());
reply.writeNoException();
return true;
case 1598968902:
reply.writeString("com.google.android.gms.maps.internal.ICreator");
return true;
default:
return super.onTransact(code, data, reply, flags);
}
}
}
IMapViewDelegate m712a(C0070b c0070b, GoogleMapOptions googleMapOptions) throws RemoteException;
void m713a(C0070b c0070b, int i) throws RemoteException;
ICameraUpdateFactoryDelegate cG() throws RemoteException;
C0195a cH() throws RemoteException;
void m714e(C0070b c0070b) throws RemoteException;
IMapFragmentDelegate m715f(C0070b c0070b) throws RemoteException;
}
| 9,546 | 0.540645 | 0.503771 | 212 | 44.028301 | 29.432673 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731132 | false | false | 9 |
c0ca35361cdd5127b3a5c7d8f7a29d3392b0d14e | 30,322,469,136,958 | 7abcd4759acc5cf41025bee6815d9a1e3e912f72 | /tong_wong_java_ass/exam/Person.java | f81f875fc04e8c5af6bb7def08278de552822158 | [] | no_license | tengr/Algorithms | https://github.com/tengr/Algorithms | 10534637b327c9beda3de3db7b9a7e55534f24fb | 4e90a51e3da207526a31016682bfb603ecb30947 | refs/heads/master | 2021-03-16T05:21:09.931000 | 2017-06-17T09:16:42 | 2017-06-17T09:16:42 | 33,525,284 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Person {
private String name;
public Person(){
//what should I type here? I should return something here but I don't know what I should return.
}
public Person(String theName){
this.name = theName;
}
public Person (Person theObject){
this(theObject.name); // why? what does this mean?
}
public String getName(){
return name;
}
public void setName(String theName){
this.name = theName;
}
public String toString(){
return name;
}
//public boolean equals(Object other){
// what does this mean in the Person Class?
// what's the function of this method?
// To test the methods? or?
//}
}
| UTF-8 | Java | 686 | java | Person.java | Java | [] | null | [] |
public class Person {
private String name;
public Person(){
//what should I type here? I should return something here but I don't know what I should return.
}
public Person(String theName){
this.name = theName;
}
public Person (Person theObject){
this(theObject.name); // why? what does this mean?
}
public String getName(){
return name;
}
public void setName(String theName){
this.name = theName;
}
public String toString(){
return name;
}
//public boolean equals(Object other){
// what does this mean in the Person Class?
// what's the function of this method?
// To test the methods? or?
//}
}
| 686 | 0.634111 | 0.634111 | 35 | 17.542856 | 20.66791 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 9 |
9153f6b96f3dc9c943428d21780ab1f4747cce55 | 31,370,441,151,572 | b214f96566446763ce5679dd2121ea3d277a9406 | /modules/base/language-api/src/main/java/consulo/language/psi/stub/StubTree.java | a647a894d55158211abff50e4e605fef2dad8d3b | [
"Apache-2.0",
"LicenseRef-scancode-jgraph"
] | permissive | consulo/consulo | https://github.com/consulo/consulo | aa340d719d05ac6cbadd3f7d1226cdb678e6c84f | d784f1ef5824b944c1ee3a24a8714edfc5e2b400 | refs/heads/master | 2023-09-06T06:55:04.987000 | 2023-09-01T06:42:16 | 2023-09-01T06:42:16 | 10,116,915 | 680 | 54 | Apache-2.0 | false | 2023-06-05T18:28:51 | 2013-05-17T05:48:18 | 2023-05-27T20:14:55 | 2023-06-05T18:28:50 | 978,666 | 673 | 48 | 69 | Java | false | false | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package consulo.language.psi.stub;
import consulo.language.psi.stub.internal.StubSpine;
import consulo.util.collection.ContainerUtil;
import jakarta.annotation.Nonnull;
import java.util.List;
public class StubTree extends ObjectStubTree<StubElement<?>> {
private final StubSpine mySpine = new StubSpine(this);
public StubTree(@Nonnull final PsiFileStub root) {
this(root, true);
}
public StubTree(@Nonnull final PsiFileStub root, final boolean withBackReference) {
super((ObjectStubBase)root, withBackReference);
}
@Nonnull
@Override
protected List<StubElement<?>> enumerateStubs(@Nonnull Stub root) {
return ((StubBase)root).myStubList.finalizeLoadingStage().toPlainList();
}
@Nonnull
@Override
final List<StubElement<?>> getPlainListFromAllRoots() {
PsiFileStub[] roots = ((PsiFileStubImpl<?>)getRoot()).getStubRoots();
if (roots.length == 1) return super.getPlainListFromAllRoots();
return ContainerUtil.concat(roots, stub -> ((PsiFileStubImpl)stub).myStubList.toPlainList());
}
@Nonnull
@Override
public PsiFileStub getRoot() {
return (PsiFileStub)myRoot;
}
@Nonnull
public StubbedSpine getSpine() {
return mySpine;
}
}
| UTF-8 | Java | 1,830 | java | StubTree.java | Java | [
{
"context": " limitations under the License.\n */\n\n/*\n * @author max\n */\npackage consulo.language.psi.stub;\n\nimport co",
"end": 619,
"score": 0.7102665901184082,
"start": 616,
"tag": "NAME",
"value": "max"
}
] | null | [] | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package consulo.language.psi.stub;
import consulo.language.psi.stub.internal.StubSpine;
import consulo.util.collection.ContainerUtil;
import jakarta.annotation.Nonnull;
import java.util.List;
public class StubTree extends ObjectStubTree<StubElement<?>> {
private final StubSpine mySpine = new StubSpine(this);
public StubTree(@Nonnull final PsiFileStub root) {
this(root, true);
}
public StubTree(@Nonnull final PsiFileStub root, final boolean withBackReference) {
super((ObjectStubBase)root, withBackReference);
}
@Nonnull
@Override
protected List<StubElement<?>> enumerateStubs(@Nonnull Stub root) {
return ((StubBase)root).myStubList.finalizeLoadingStage().toPlainList();
}
@Nonnull
@Override
final List<StubElement<?>> getPlainListFromAllRoots() {
PsiFileStub[] roots = ((PsiFileStubImpl<?>)getRoot()).getStubRoots();
if (roots.length == 1) return super.getPlainListFromAllRoots();
return ContainerUtil.concat(roots, stub -> ((PsiFileStubImpl)stub).myStubList.toPlainList());
}
@Nonnull
@Override
public PsiFileStub getRoot() {
return (PsiFileStub)myRoot;
}
@Nonnull
public StubbedSpine getSpine() {
return mySpine;
}
}
| 1,830 | 0.732787 | 0.725683 | 64 | 27.59375 | 28.396038 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359375 | false | false | 9 |
d142ea1f85bc538dd6d28e70532301138772d5f2 | 31,988,916,443,328 | af846ab7ffc148cd3207f3e65cfb2dde6d92c767 | /sparrow-web/sparrow-manager/src/main/java/com/sparrow/app/test/CommandInitialize.java | 2e47e3f4794300c2ee28e2c42de7b27675e8b221 | [
"Apache-2.0"
] | permissive | aniu2002/myself-toolkit | https://github.com/aniu2002/myself-toolkit | aaf5f71948bb45d331b206d806de85c84bafadcc | aea640b4339ea24d7bfd32311f093560573635d3 | refs/heads/master | 2022-12-24T20:25:43.702000 | 2019-03-11T14:42:14 | 2019-03-11T14:42:14 | 99,811,298 | 1 | 0 | Apache-2.0 | false | 2022-12-12T21:42:45 | 2017-08-09T13:26:46 | 2020-09-20T11:34:23 | 2022-12-12T21:42:42 | 24,397 | 1 | 0 | 26 | Java | false | false | package com.sparrow.app.test;
import com.sparrow.http.command.Command;
import com.sparrow.server.config.BeanContext;
import com.sparrow.server.config.ParameterWatcher;
/**
* Created by Administrator on 2015/6/2 0002.
*/
public class CommandInitialize {
public static void main(String args[]) {
ParameterWatcher watcher = new ParameterWatcher<Command>() {
@Override
public void watch(String parameter, Command bean) {
System.out.println(" path : " + parameter + " , " + bean.getClass().getName());
}
@Override
public Class<Command> accept() {
return Command.class;
}
};
BeanContext beanContext = new BeanContext("classpath:eggs/beanConfig.xml", watcher);
}
}
| UTF-8 | Java | 800 | java | CommandInitialize.java | Java | [] | null | [] | package com.sparrow.app.test;
import com.sparrow.http.command.Command;
import com.sparrow.server.config.BeanContext;
import com.sparrow.server.config.ParameterWatcher;
/**
* Created by Administrator on 2015/6/2 0002.
*/
public class CommandInitialize {
public static void main(String args[]) {
ParameterWatcher watcher = new ParameterWatcher<Command>() {
@Override
public void watch(String parameter, Command bean) {
System.out.println(" path : " + parameter + " , " + bean.getClass().getName());
}
@Override
public Class<Command> accept() {
return Command.class;
}
};
BeanContext beanContext = new BeanContext("classpath:eggs/beanConfig.xml", watcher);
}
}
| 800 | 0.6225 | 0.61 | 26 | 29.76923 | 27.498682 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 9 |
44a73576afdf4fc258b4dd33ddf5c5fa38d73f9b | 1,546,188,251,547 | 985902de02e6951e1d606453536901f62da4ebc3 | /src/games/glutenfree/MonsterMaze.java | 442c9d30c54dbce566b9534af9d6eb061574d985 | [] | no_license | AlgoRythm-Dylan/Monster-Maze | https://github.com/AlgoRythm-Dylan/Monster-Maze | 211eeeeea305cd1a2b8e0e3167157076737c81cf | fd2e90234eedaa38ed788d51dc9c6bf498bfdd49 | refs/heads/master | 2023-07-17T04:08:53.252000 | 2021-08-23T21:18:46 | 2021-08-23T21:18:46 | 399,245,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package games.glutenfree;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import games.glutenfree.commands.*;
import games.glutenfree.listeners.*;
import games.glutenfree.maze.*;
import net.minecraft.network.protocol.game.PacketPlayOutEntityMetadata;
import net.minecraft.network.syncher.DataWatcher;
import net.minecraft.network.syncher.DataWatcherObject;
import net.minecraft.network.syncher.DataWatcherRegistry;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer;
import org.bukkit.entity.*;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import org.bukkit.util.Vector;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class MonsterMaze extends JavaPlugin {
private Location spawnRoomLocation, mazeStart;
private Template cage, indicator;
private final int CHECK_DELAY = 1;
private final int SLOW_GAME_TICK = 20;
private final double VERTICAL_HIT_DISTANCE = 0.2d;
private final double HORIZONTAL_HIT_DISTANCE = 0.4d;
private final double VERTICAL_BOOP_FORCE = 1.05;
private final double HORIZONTAL_BOOP_FORCE = 0.75;
private final double REPULSE_RANGE = 5d;
private final int HEALTH_PER_HIT = 4;
private final int MAX_RUNNERS = 3000;
private final int NEW_RUNNERS_PER_ROUND = 12;
private final int REPULSE_COST = 10;
private final int ONE_UP_COST = 5;
private final int SPEED_BOOST_COST = 8;
private Cooldown boopCooldown;
private Random random;
private NamespacedKey mazeItemKey;
private int gameTickTask = -1;
private int oncePerSecondTask = -1;
private int releasePlayersTask = -1;
private FixedMetadataValue specialEntity;
private ArrayList<Player> playersInGame, deadPlayers, spectators;
private ArrayList<MazeRunner> runners;
private ArrayList<MazeBlock> placesToSpawn;
private boolean running;
private Maze maze;
private MazePlatformSpawner platformSpawner;
private boolean isClassicMode = false;
private boolean isSingleplayerMode = false;
private MazePlatform startPlatform, currentPlatform, lastPlatform;
private ArrayList<MazePlatform> platforms;
private long lastUpdateTime;
private int currentRound, currentCountdown;
private boolean playersAreReleased = false;
private BossBar timeLeftBossbar;
String classicModeString;
PlayerDataManager dataManager;
private Scoreboard gameScoreboard;
private Team gameTeam;
private PotionEffect noJump;
private ProtocolManager pm;
private final boolean DEV_MODE = false;
@Override
public void onEnable(){
mazeItemKey = new NamespacedKey(this, "mm-powerup");
spawnRoomLocation = new Location(getServer().getWorlds().get(0), 85, 12.5, 9, 90, 0);
mazeStart = new Location(getServer().getWorlds().get(0), -42, 10, -42);
cage = new Template(new Location(getServer().getWorlds().get(0), -130, 8, 11), 15, 3, 15);
indicator = new Template(new Location(getServer().getWorlds().get(0), -130, 5, -4), 5, 8, 5);
playersInGame = new ArrayList<>();
deadPlayers = new ArrayList<>();
runners = new ArrayList<>();
platforms = new ArrayList<>();
placesToSpawn = new ArrayList<>();
spectators = new ArrayList<>();
boopCooldown = new Cooldown(500);
random = new Random();
dataManager = new PlayerDataManager();
specialEntity = new FixedMetadataValue(this, "special-entity");
classicModeString = String.format("%s - %sClassic Mode", ChatColor.RESET, ChatColor.YELLOW);
running = false;
maze = new Maze(100, 100);
maze.setStartLocation(mazeStart);
noJump = new PotionEffect(PotionEffectType.JUMP, 999999, 128, false, false);
pm = ProtocolLibrary.getProtocolManager();
timeLeftBossbar = getServer().createBossBar("Time Left", BarColor.GREEN, BarStyle.SOLID);
/*pm.addPacketListener(
new PacketAdapter(this, ListenerPriority.NORMAL,
PacketType.Play.Server.ENTITY_METADATA) {
@Override
public void onPacketSending(PacketEvent event) {
// Item packets (id: 0x29)
if (event.getPacketType() ==
PacketType.Play.Server.ENTITY_METADATA) {
//event.setCancelled(true);
PacketPlayOutEntityMetadata rawPacket = (PacketPlayOutEntityMetadata) event.getPacket().getHandle();
PacketContainer packet = event.getPacket();
int entityID = packet.getIntegers().read(0);
Player playerInGame = entityIsInGame(entityID);
if(entityIsInGame(entityID) != null) {
//getLogger().info(String.format("Sent packet for entity ID %d... %s", entityID, list.get(0).b()));
DataWatcherObject watcherObject = (DataWatcherObject) packet.getWatchableCollectionModifier().getValues().get(0).get(0).getWatcherObject().getHandle();
getLogger().info(String.format("Entity ID: %d... bitmask: %s",
packet.getIntegers().read(0), ));
}
}
}
});*/
if(DEV_MODE){
getCommand("resetgame").setExecutor(new ResetGameCommand(this));
getCommand("addmetogame").setExecutor(new AddMeToGameCommand(this));
getCommand("startgame").setExecutor(new StartGameCommand(this));
getCommand("placeindicator").setExecutor(new PlaceIndicatorCommand(this));
getServer().getPluginManager().registerEvents(new BlockListener(this), this);
Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
getServer().broadcastMessage(String.format("%s%s== SERVER RUNNING IN DEV MODE ==", ChatColor.RED, ChatColor.BOLD));
}, 5);
}
// GAMERULES
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_INSOMNIA, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_MOB_LOOT, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_MOB_SPAWNING, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.MOB_GRIEFING, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.NATURAL_REGENERATION, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.KEEP_INVENTORY, true);
spawnRoomLocation.getWorld().setGameRule(GameRule.SPECTATORS_GENERATE_CHUNKS, false);
resetGame();
getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerInteractListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerLeaveListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerInventoryListener(this), this);
getServer().getPluginManager().registerEvents(new DamageListener(this), this);
gameScoreboard = getServer().getScoreboardManager().getNewScoreboard();
gameTeam = gameScoreboard.registerNewTeam("game-team");
gameTeam.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER);
gameTeam.setCanSeeFriendlyInvisibles(true);
gameTeam.setAllowFriendlyFire(false);
oncePerSecondTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
for(Player player : getServer().getOnlinePlayers()){
player.setFoodLevel(20);
}
if(running){
if(playersAreReleased){
currentCountdown--;
handleCountdownTime(currentCountdown);
}
}
}, SLOW_GAME_TICK, SLOW_GAME_TICK);
getLogger().info("MonsterMaze game Started!");
}
@Override
public void onDisable(){
resetGame();
HandlerList.unregisterAll(this);
if(gameTickTask != -1) Bukkit.getScheduler().cancelTask(gameTickTask);
if(oncePerSecondTask != -1) Bukkit.getScheduler().cancelTask(oncePerSecondTask);
removeAllEntities();
if(pm != null)
pm.removePacketListeners(this);
if(gameTeam != null)
gameTeam.unregister();
getLogger().info("MonsterMaze game Disabled!");
}
public void parseMaze(){
maze.parse();
platformSpawner = new MazePlatformSpawner(maze.getPlatformAreas());
placesToSpawn = maze.getBlocksOfType(MazeBlockType.SPAWNER);
}
/*
GAME FLOW
*/
public void teleportPlayerToSpawnRoom(Player player){
player.teleport(spawnRoomLocation);
}
public boolean playerIsInGame(Player player){
return playersInGame.contains(player);
}
public Player entityIsInGame(int entityID){
for(Player player : playersInGame){
if(player.getEntityId() == entityID) return player;
}
return null;
}
public boolean addPlayer(Player player){
if(playerIsInGame(player) || running) return false;
playersInGame.add(player);
gameTeam.addEntry(player.getDisplayName());
player.setScoreboard(gameScoreboard);
return true;
}
public int getCountdownTime(int round){
if(round < 15)
return 60 - (round * 2);
else
return 30;
}
public int getCountdownTime(){
return getCountdownTime(currentRound);
}
public void startGame(){
if(isRunning()){
Bukkit.broadcastMessage(ChatColor.RED + "Game already started!");
return;
}
if(playersInGame.size() == 0){
Bukkit.broadcastMessage(ChatColor.RED + "Game needs at least one player to start");
return;
}
running = true;
playersAreReleased = false;
currentRound = 1;
currentCountdown = getCountdownTime();
dataManager.reset();
parseMaze();
int spawns = maze.getBlocksOfType(MazeBlockType.MAZE).size() / 20;
for(Location location : maze.getInitialSpawnPositions(spawns)){
if(canSummonEntity()) // IDK we might hit the limit initially...?
summonEntity(location);
}
startPlatform = maze.createPlatform(
Math.round(((float)maze.getWidth() / 2f) - 7.5f),
Math.round(((float)maze.getHeight() / 2f) - 7.5f), 15, 15);
startPlatform.setIndicator(cage);
startPlatform.setLifeSpan(35000);
startPlatform.setPlatformHeightOffset(1);
startPlatform.placePlatform();
startPlatform.placeIndicator();
platforms.add(startPlatform);
removeEntitiesOnPlatforms();
// Set up all players
for(Player player : playersInGame) {
setupPlayer(player);
}
// Make all non-players specs
for(Player player : Bukkit.getOnlinePlayers()){
if(!playerIsInGame(player))
makePlayerSpectator(player);
}
lastUpdateTime = System.currentTimeMillis();
startGameTick();
spawnNextPlatform();
releasePlayersTask = Bukkit.getScheduler().scheduleSyncDelayedTask(this, this::releasePlayers, 150);
displayGameTitle(String.format("%s%sMonster Maze", ChatColor.GREEN, ChatColor.BOLD), "Get to the safe pad!");
Bukkit.broadcastMessage("\n");
Bukkit.broadcastMessage(String.format(" %s%sMonster Maze", ChatColor.GREEN, ChatColor.BOLD));
if(playersInGame.size() == 1){
isSingleplayerMode = true;
Bukkit.broadcastMessage(String.format(" Singleplayer mode%s", isClassicMode ? classicModeString : ""));
}
else{
isSingleplayerMode = false;
Bukkit.broadcastMessage(String.format(" Game of %s%d%s players%s",
ChatColor.GOLD, playersInGame.size(), ChatColor.RESET,
isClassicMode ? classicModeString : ""));
}
Bukkit.broadcastMessage(String.format("\n %sGet to the safe pad before", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %sthe timer expires! Watch out", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %sfor snowmen. Click items in your", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %shotbar to use powerups!\n\n", ChatColor.GRAY));
// Finally, make players semi-visible to one another
/*if(!isSingleplayerMode){
for(Player player : playersInGame) {
for(Player otherPlayer : playersInGame){
if(player != otherPlayer){
makeInvisibleTo(player, otherPlayer);
}
}
}
}*/
}
public void releasePlayers(){
for(Player player : playersInGame){
timeLeftBossbar.addPlayer(player);
}
playersAreReleased = true;
startPlatform.removeIndicator();
releasePlayersTask = -1;
}
public void resetTitle(){
displayGameTitle(null, null);
}
public void displayGameTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut){
for(Player player : playersInGame){
player.sendTitle(title, subtitle, fadeIn, stay, fadeOut);
}
}
public void displayGameTitle(String title, String subtitle){
displayGameTitle(title, subtitle, 20, 110, 20);
}
public void displayGameTitle(String title){
displayGameTitle(title, null);
}
public void sendToPlayers(String message){
for(Player player : playersInGame){
player.sendMessage(message);
}
}
public void spawnNextPlatform(){
MazeBlock randomPosition = platformSpawner.next();
if(lastPlatform != null){
lastPlatform.removeIndicator(); // Just in case
lastPlatform.restoreOriginal();
platforms.remove(lastPlatform);
}
if(currentPlatform != null){
lastPlatform = currentPlatform;
lastPlatform.setLifeSpan(8000);
lastPlatform.enableAging();
lastPlatform.removeIndicator();
}
currentPlatform = maze.createPlatform(randomPosition.getBlockX() - 2, randomPosition.getBlockY() - 2, 5, 5);
currentPlatform.placePlatform();
currentPlatform.disableAging();
currentPlatform.setIndicator(indicator);
currentPlatform.placeIndicator();
platforms.add(currentPlatform);
removeEntitiesOnPlatforms();
}
public void removeEntitiesOnPlatforms(){
for(MazePlatform platform : platforms){
for(int i = 0; i < runners.size(); i++){
MazeRunner runner = runners.get(i);
if(platform.entityIsOnPlatform(runner.getEntity())){
runner.getEntity().remove();
runners.remove(i);
i--;
}
}
}
}
public void killPlayersNotOnPlatform(){
for(int i = 0; i < playersInGame.size(); i++){
Player player = playersInGame.get(i);
if(!currentPlatform.entityIsOnPlatform(player)){
killPlayer(player, "You weren't on the safe pad!");
i--;
}
}
}
public void setPlayerTokens(Player player, int amt){
player.getInventory().setItem(8, MazePowerup.tokens(mazeItemKey, amt));
}
public void setupPlayer(Player player){
player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue());
player.addPotionEffect(noJump);
Location startLocation = maze.centerOfMaze();
startLocation.setY(startLocation.getY() + 0.5);
player.teleport(startLocation);
player.setCollidable(false);
player.setGameMode(GameMode.ADVENTURE); // Just in case
player.getInventory().clear();
player.getInventory().setItem(0, MazePowerup.repulse(mazeItemKey));
PlayerData data = dataManager.createDataFor(player);
if(!isClassicMode){
player.getInventory().setItem(1, MazePowerup.oneUp(mazeItemKey));
player.getInventory().setItem(2, MazePowerup.speedBoost(mazeItemKey));
setPlayerTokens(player, 0);
data.setTokens(0);
}
else{
setPlayerTokens(player, 30);
data.setTokens(30);
}
}
// Skip ahead but only if its truly "ahead"
public void skipAheadTime(int to){
if(to <= currentCountdown){
currentCountdown = to;
}
}
public void handleCountdownTime(int countdownTime){
timeLeftBossbar.setProgress((double) currentCountdown / (double) getCountdownTime());
timeLeftBossbar.setTitle(String.format("%s%sRound %d - %d Seconds Left", ChatColor.GREEN, ChatColor.BOLD, currentRound, countdownTime));
if(countdownTime <= 0){
killPlayersNotOnPlatform();
if(playersInGame.size() > 0){
currentCountdown = getCountdownTime(++currentRound);
spawnNextPlatform();
for(int i = 0; i < NEW_RUNNERS_PER_ROUND && canSummonEntity(); i++){
MazeBlock block = placesToSpawn.get(random.nextInt(placesToSpawn.size() - 1));
summonEntity(new Location(maze.getStartLocation().getWorld(),
(double) block.getBlockX() + maze.getStartLocation().getBlockX() + 0.5,
maze.getStartLocation().getY() + 1,
(double) block.getBlockY() + maze.getStartLocation().getBlockZ() + 0.5));
}
displayGameTitle(String.format("%s%sSafe!", ChatColor.GREEN, ChatColor.BOLD), "Get to the next safe pad", 0, 40, 10);
for(Player player : playersInGame){
dataManager.get(player).recordRoundSurvived();
}
if(currentRound % 5 == 0) {
Bukkit.broadcastMessage(String.format("\n %s%sRound %d%s\n",
ChatColor.GREEN, ChatColor.BOLD, currentRound,
isSingleplayerMode ? "" : String.format("\n %s%d%s players remaining!",
ChatColor.GOLD, playersInGame.size(), ChatColor.GRAY)));
}
}
}
else if(countdownTime == 10){
displayGameTitle(String.format("%s%s%d", ChatColor.GREEN, ChatColor.BOLD, countdownTime), null, 0, 40, 20);
}
else if(countdownTime <= 3){
// Display countdown time as title
displayGameTitle(String.format("%s%s%d", ChatColor.RED, ChatColor.BOLD, countdownTime), null, 0, 15, 5);
}
}
public void healPlayer(Player player, double amount){
double health = player.getHealth();
if(health + amount > 20) player.setHealth(20);
else player.setHealth(health + amount);
}
public void makePlayerSpectator(Player player){
player.setGameMode(GameMode.SPECTATOR);
spectators.add(player);
player.sendTitle(String.format("%s%sSpectating", ChatColor.GREEN, ChatColor.BOLD),
"You are spectating the game", 20, 60, 20);
Location specLoc = maze.centerOfMaze();
specLoc.setY(specLoc.getY() + 10);
player.teleport(specLoc);
}
public void killPlayer(Player player, String reason){
playersInGame.remove(player);
deadPlayers.add(player);
makePlayerSpectator(player);
timeLeftBossbar.removePlayer(player);
player.sendTitle(String.format("%s%sYou Died!", ChatColor.RED, ChatColor.BOLD), reason, 20, 60, 20);
// Send summary
PlayerData data = dataManager.get(player);
player.sendMessage(String.format("\n %s%s== SUMMARY ==%s\n - Rounds Survived: %s%d%s\n" +
" - Safe Pad Firsts: %s%d%s\n - Total Score: %s%d%s\n - Death: %s\n",
ChatColor.GREEN, ChatColor.BOLD, ChatColor.RESET,
ChatColor.GOLD, data.getRoundsSurvived(), ChatColor.RESET,
ChatColor.GOLD, data.getSafePadsFirst(), ChatColor.RESET,
ChatColor.GOLD, data.getScore(), ChatColor.RESET,
reason == null ? "Health loss" : reason));
if((isSingleplayerMode && playersInGame.size() == 0) ||
(!isSingleplayerMode && playersInGame.size() <= 1)){
finishGame();
}
else{
Bukkit.broadcastMessage(String.format("%s%s died! %d players remain",
ChatColor.YELLOW, player.getDisplayName(), playersInGame.size()));
}
resetPlayer(player);
}
public void killPlayer(Player player){
killPlayer(player, null);
}
public void finishGame(){
running = false;
Bukkit.broadcastMessage(String.format("\n%s Game over!%s\n%s Rounds survived: %s%d\n",
ChatColor.RED, ChatColor.RESET, ChatColor.GRAY, ChatColor.GOLD, currentRound - 1));
resetGame();
}
public void handlePlayerLeave(Player player){
if(playerIsInGame(player)){
resetPlayer(player);
playersInGame.remove(player);
if(playersInGame.size() <= 1){
finishGame();
}
}
if(spectators.contains(player)){
spectators.remove(player);
}
}
public void resetPlayer(Player player){
getLogger().info(String.format("Restting player %s...", player.getDisplayName()));
teleportPlayerToSpawnRoom(player);
player.setVelocity(new Vector().setX(0).setY(0).setZ(0));
player.removePotionEffect(PotionEffectType.JUMP);
player.removePotionEffect(PotionEffectType.INVISIBILITY);
player.removePotionEffect(PotionEffectType.SPEED);
player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue());
player.setCollidable(false);
player.setGameMode(GameMode.ADVENTURE);
timeLeftBossbar.removePlayer(player);
player.getInventory().clear();
// Remove invisible effect entirely
/*for(Player otherPlayer : Bukkit.getOnlinePlayers()){
if(otherPlayer != player){
undoInvisibleEffect(otherPlayer, player);
undoInvisibleEffect(player, otherPlayer);
}
}*/
}
public void resetGame(){
for(Player player : getServer().getOnlinePlayers()){
resetPlayer(player);
}
for(MazePlatform platform : platforms){
platform.restoreOriginal();
platform.removeIndicator();
}
if(releasePlayersTask != -1)
Bukkit.getScheduler().cancelTask(releasePlayersTask);
if(gameTickTask != -1)
Bukkit.getScheduler().cancelTask(gameTickTask);
platforms.clear();
lastPlatform = null;
currentPlatform = null;
running = false;
playersAreReleased = false;
playersInGame.clear();
dataManager.reset();
spectators.clear();
removeAllEntities();
}
public boolean canSummonEntity(){
return runners.size() < MAX_RUNNERS;
}
public Entity summonEntity(Location location){
Snowman snowman = (Snowman) location.getWorld().spawnEntity(location, EntityType.SNOWMAN);
snowman.setMetadata("special-entity", specialEntity);
snowman.setAI(false);
snowman.setCollidable(false);
snowman.setInvulnerable(true);
snowman.setGravity(false);
MazeRunner runner = new MazeRunner(snowman);
runner.setMaze(maze);
runners.add(runner);
return snowman;
}
public void removeAllEntities(){
for(MazeRunner runner : runners){
runner.getEntity().remove();
}
runners.clear();
}
public long deltaTime(){
long newTime = System.currentTimeMillis();
long delta = newTime - lastUpdateTime;
lastUpdateTime = newTime;
return delta;
}
public void startGameTick(){
gameTickTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
long dt = deltaTime();
for(MazeRunner runner : runners){
runner.update(dt);
}
for(int i = 0; i < platforms.size(); i++){
MazePlatform platform = platforms.get(i);
platform.update(dt);
if(platform.isExpired()){
platform.restoreOriginal();
platform.removeIndicator();
platforms.remove(platform);
}
}
for(int i = 0; i < playersInGame.size(); i++){
Player player = playersInGame.get(i);
PlayerData data = dataManager.get(player);
if(playersAreReleased && currentPlatform.entityIsOnPlatform(player)){
if(currentPlatform.isUntouched()){
if(!isSingleplayerMode)
Bukkit.broadcastMessage(String.format("%s%s%s made it to the safe pad first!",
ChatColor.GREEN, player.getDisplayName(), ChatColor.RESET));
skipAheadTime(11);
currentPlatform.setUntouched(false);
healPlayer(player, 2);
data.addTokens(2);
data.recordSafePadFirst();
data.addScore(2);
setPlayerTokens(player, data.getTokens());
}
if (!currentPlatform.playerHasVisited(player)) {
player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 1);
player.sendMessage(String.format("%sYou made it to the safe pad!", ChatColor.GREEN));
healPlayer(player, 2);
data.addTokens(1);
data.addScore(1);
setPlayerTokens(player, data.getTokens());
currentPlatform.recordPlayerVisit(player);
if(currentPlatform.visitCount() >= playersInGame.size()){
skipAheadTime(4);
}
}
}
List<Entity> nearby = player.getWorld().getNearbyEntities(
player.getLocation(),
HORIZONTAL_HIT_DISTANCE, VERTICAL_HIT_DISTANCE, HORIZONTAL_HIT_DISTANCE,
(Entity) -> Entity.hasMetadata("special-entity"))
.stream().toList();
if(nearby.size() > 0){
if(boopCooldown.testEntity(player))
if(boopPlayer(player, nearby.get(0))){
i--; // Player died from the boop :(
continue;
}
}
if(player.getLocation().getY() < maze.getStartLocation().getY() - 0.9){
killPlayer(player, "You fell off the maze!");
i--;
}
}
}, CHECK_DELAY, CHECK_DELAY);
}
// Returns whether or not the player was killed by this boop
public boolean boopPlayer(Player player, Entity entity){
Vector velocity = new Vector();
velocity.setY(VERTICAL_BOOP_FORCE);
double angleBetween = Math.atan2(entity.getLocation().getX() - player.getLocation().getX(),
entity.getLocation().getZ() - player.getLocation().getZ());
velocity.setZ(-Math.cos(angleBetween) * HORIZONTAL_BOOP_FORCE);
velocity.setX(-Math.sin(angleBetween) * HORIZONTAL_BOOP_FORCE);
player.setVelocity(velocity);
if(player.getHealth() <= HEALTH_PER_HIT){
killPlayer(player);
return true;
}
else{
player.damage(HEALTH_PER_HIT);
return false;
}
}
public boolean isRunning(){
return running;
}
public void repulse(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("repulse")) return;
if(data.getTokens() >= REPULSE_COST){
data.setTokens(data.getTokens() - REPULSE_COST);
doRepulseAt(player.getLocation());
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + REPULSE_COST);
}
}
public void doRepulseAt(Location location){
List<Entity> nearby = location.getWorld().getNearbyEntities(
location,
REPULSE_RANGE, REPULSE_RANGE, REPULSE_RANGE,
(Entity) -> Entity.hasMetadata("special-entity"))
.stream().toList();
for(Entity entity : nearby){
runners.remove(entity);
entity.remove();
Firework firework = entity.getWorld().spawn(new Location(
entity.getLocation().getWorld(),
entity.getLocation().getX(),
entity.getLocation().getY() + 1,
entity.getLocation().getZ()
), Firework.class);
FireworkMeta meta = firework.getFireworkMeta();
meta.setPower(2);
FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL).withColor(Color.BLACK).build();
meta.addEffect(effect);
firework.setFireworkMeta(meta);
firework.detonate();
}
}
public void oneUp(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("one-up")) return;
if(data.getTokens() >= ONE_UP_COST){
data.setTokens(data.getTokens() - ONE_UP_COST);
healPlayer(player, 6);
player.sendMessage(ChatColor.GREEN + "You have been healed!");
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + ONE_UP_COST);
}
}
public void speedBoost(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("speed-boost")) return;
if(data.getTokens() >= SPEED_BOOST_COST){
data.setTokens(data.getTokens() - SPEED_BOOST_COST);
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 200, 1, false, false));
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + SPEED_BOOST_COST);
}
}
/*public void makeInvisibleTo(Player viewer, Player invisiblePlayer){
getLogger().info(String.format("Making %s invisible to %s", invisiblePlayer.getDisplayName(), viewer.getDisplayName()));
//PacketContainer packet = pm.createPacket(PacketType.Play.Server.ENTITY_EFFECT);
DataWatcher watcher = ((CraftPlayer) invisiblePlayer).getHandle().getDataWatcher();
watcher.set(new DataWatcherObject<>(0, DataWatcherRegistry.a), (byte)0x20);
PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(invisiblePlayer.getEntityId(),
watcher, false);
/*PacketContainer packet = PacketContainer.fromPacket(
new PacketPlayOutEntityEffect(viewer.getEntityId(),
new MobEffect(MobEffectList.fromId(14), 99999, 1)));*//*
//packet.getIntegers().write(0, invisiblePlayer.getEntityId());
//packet.getBytes().write(0, (byte)(14 & 255));
//packet.getSpecificModifier(MobEffect.class).write(0, new MobEffect(MobEffectList.fromId(14)));
//packet.getIntegers().write(1, 1);
try {
pm.sendServerPacket(viewer, PacketContainer.fromPacket(packet));
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}*/
/*public void undoInvisibleEffect(Player viewer, Player invisiblePlayer){
getLogger().info(String.format("Making %s visible to %s", invisiblePlayer.getDisplayName(), viewer.getDisplayName()));
//PacketContainer packet = pm.createPacket(PacketType.Play.Server.REMOVE_ENTITY_EFFECT);
//packet.getIntegers().write(0, invisiblePlayer.getEntityId());
//packet.getBytes().write(0, (byte) 14);
//packet.getSpecificModifier(MobEffectList.class).write(0, MobEffectList.fromId(14));
DataWatcher watcher = ((CraftPlayer) invisiblePlayer).getHandle().getDataWatcher();
watcher.set(new DataWatcherObject<>(0, DataWatcherRegistry.a), (byte)0);
PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(invisiblePlayer.getEntityId(),
watcher, false);
try {
pm.sendServerPacket(viewer, PacketContainer.fromPacket(packet));
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}*/
public Maze getMaze() {
return maze;
}
public boolean isClassicMode() {
return isClassicMode;
}
public void setClassicMode(boolean classicMode) {
isClassicMode = classicMode;
}
public Template getIndicatorTemplate(){
return indicator;
}
public NamespacedKey getMazeItemKey() {
return mazeItemKey;
}
}
| UTF-8 | Java | 34,916 | java | MonsterMaze.java | Java | [
{
"context": "{\n\n mazeItemKey = new NamespacedKey(this, \"mm-powerup\");\n\n spawnRoomLocation = new Location(getS",
"end": 3479,
"score": 0.9943053722381592,
"start": 3469,
"tag": "KEY",
"value": "mm-powerup"
}
] | null | [] | package games.glutenfree;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import games.glutenfree.commands.*;
import games.glutenfree.listeners.*;
import games.glutenfree.maze.*;
import net.minecraft.network.protocol.game.PacketPlayOutEntityMetadata;
import net.minecraft.network.syncher.DataWatcher;
import net.minecraft.network.syncher.DataWatcherObject;
import net.minecraft.network.syncher.DataWatcherRegistry;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer;
import org.bukkit.entity.*;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import org.bukkit.util.Vector;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class MonsterMaze extends JavaPlugin {
private Location spawnRoomLocation, mazeStart;
private Template cage, indicator;
private final int CHECK_DELAY = 1;
private final int SLOW_GAME_TICK = 20;
private final double VERTICAL_HIT_DISTANCE = 0.2d;
private final double HORIZONTAL_HIT_DISTANCE = 0.4d;
private final double VERTICAL_BOOP_FORCE = 1.05;
private final double HORIZONTAL_BOOP_FORCE = 0.75;
private final double REPULSE_RANGE = 5d;
private final int HEALTH_PER_HIT = 4;
private final int MAX_RUNNERS = 3000;
private final int NEW_RUNNERS_PER_ROUND = 12;
private final int REPULSE_COST = 10;
private final int ONE_UP_COST = 5;
private final int SPEED_BOOST_COST = 8;
private Cooldown boopCooldown;
private Random random;
private NamespacedKey mazeItemKey;
private int gameTickTask = -1;
private int oncePerSecondTask = -1;
private int releasePlayersTask = -1;
private FixedMetadataValue specialEntity;
private ArrayList<Player> playersInGame, deadPlayers, spectators;
private ArrayList<MazeRunner> runners;
private ArrayList<MazeBlock> placesToSpawn;
private boolean running;
private Maze maze;
private MazePlatformSpawner platformSpawner;
private boolean isClassicMode = false;
private boolean isSingleplayerMode = false;
private MazePlatform startPlatform, currentPlatform, lastPlatform;
private ArrayList<MazePlatform> platforms;
private long lastUpdateTime;
private int currentRound, currentCountdown;
private boolean playersAreReleased = false;
private BossBar timeLeftBossbar;
String classicModeString;
PlayerDataManager dataManager;
private Scoreboard gameScoreboard;
private Team gameTeam;
private PotionEffect noJump;
private ProtocolManager pm;
private final boolean DEV_MODE = false;
@Override
public void onEnable(){
mazeItemKey = new NamespacedKey(this, "mm-powerup");
spawnRoomLocation = new Location(getServer().getWorlds().get(0), 85, 12.5, 9, 90, 0);
mazeStart = new Location(getServer().getWorlds().get(0), -42, 10, -42);
cage = new Template(new Location(getServer().getWorlds().get(0), -130, 8, 11), 15, 3, 15);
indicator = new Template(new Location(getServer().getWorlds().get(0), -130, 5, -4), 5, 8, 5);
playersInGame = new ArrayList<>();
deadPlayers = new ArrayList<>();
runners = new ArrayList<>();
platforms = new ArrayList<>();
placesToSpawn = new ArrayList<>();
spectators = new ArrayList<>();
boopCooldown = new Cooldown(500);
random = new Random();
dataManager = new PlayerDataManager();
specialEntity = new FixedMetadataValue(this, "special-entity");
classicModeString = String.format("%s - %sClassic Mode", ChatColor.RESET, ChatColor.YELLOW);
running = false;
maze = new Maze(100, 100);
maze.setStartLocation(mazeStart);
noJump = new PotionEffect(PotionEffectType.JUMP, 999999, 128, false, false);
pm = ProtocolLibrary.getProtocolManager();
timeLeftBossbar = getServer().createBossBar("Time Left", BarColor.GREEN, BarStyle.SOLID);
/*pm.addPacketListener(
new PacketAdapter(this, ListenerPriority.NORMAL,
PacketType.Play.Server.ENTITY_METADATA) {
@Override
public void onPacketSending(PacketEvent event) {
// Item packets (id: 0x29)
if (event.getPacketType() ==
PacketType.Play.Server.ENTITY_METADATA) {
//event.setCancelled(true);
PacketPlayOutEntityMetadata rawPacket = (PacketPlayOutEntityMetadata) event.getPacket().getHandle();
PacketContainer packet = event.getPacket();
int entityID = packet.getIntegers().read(0);
Player playerInGame = entityIsInGame(entityID);
if(entityIsInGame(entityID) != null) {
//getLogger().info(String.format("Sent packet for entity ID %d... %s", entityID, list.get(0).b()));
DataWatcherObject watcherObject = (DataWatcherObject) packet.getWatchableCollectionModifier().getValues().get(0).get(0).getWatcherObject().getHandle();
getLogger().info(String.format("Entity ID: %d... bitmask: %s",
packet.getIntegers().read(0), ));
}
}
}
});*/
if(DEV_MODE){
getCommand("resetgame").setExecutor(new ResetGameCommand(this));
getCommand("addmetogame").setExecutor(new AddMeToGameCommand(this));
getCommand("startgame").setExecutor(new StartGameCommand(this));
getCommand("placeindicator").setExecutor(new PlaceIndicatorCommand(this));
getServer().getPluginManager().registerEvents(new BlockListener(this), this);
Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
getServer().broadcastMessage(String.format("%s%s== SERVER RUNNING IN DEV MODE ==", ChatColor.RED, ChatColor.BOLD));
}, 5);
}
// GAMERULES
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_INSOMNIA, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_MOB_LOOT, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.DO_MOB_SPAWNING, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.MOB_GRIEFING, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.NATURAL_REGENERATION, false);
spawnRoomLocation.getWorld().setGameRule(GameRule.KEEP_INVENTORY, true);
spawnRoomLocation.getWorld().setGameRule(GameRule.SPECTATORS_GENERATE_CHUNKS, false);
resetGame();
getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerInteractListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerLeaveListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerInventoryListener(this), this);
getServer().getPluginManager().registerEvents(new DamageListener(this), this);
gameScoreboard = getServer().getScoreboardManager().getNewScoreboard();
gameTeam = gameScoreboard.registerNewTeam("game-team");
gameTeam.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER);
gameTeam.setCanSeeFriendlyInvisibles(true);
gameTeam.setAllowFriendlyFire(false);
oncePerSecondTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
for(Player player : getServer().getOnlinePlayers()){
player.setFoodLevel(20);
}
if(running){
if(playersAreReleased){
currentCountdown--;
handleCountdownTime(currentCountdown);
}
}
}, SLOW_GAME_TICK, SLOW_GAME_TICK);
getLogger().info("MonsterMaze game Started!");
}
@Override
public void onDisable(){
resetGame();
HandlerList.unregisterAll(this);
if(gameTickTask != -1) Bukkit.getScheduler().cancelTask(gameTickTask);
if(oncePerSecondTask != -1) Bukkit.getScheduler().cancelTask(oncePerSecondTask);
removeAllEntities();
if(pm != null)
pm.removePacketListeners(this);
if(gameTeam != null)
gameTeam.unregister();
getLogger().info("MonsterMaze game Disabled!");
}
public void parseMaze(){
maze.parse();
platformSpawner = new MazePlatformSpawner(maze.getPlatformAreas());
placesToSpawn = maze.getBlocksOfType(MazeBlockType.SPAWNER);
}
/*
GAME FLOW
*/
public void teleportPlayerToSpawnRoom(Player player){
player.teleport(spawnRoomLocation);
}
public boolean playerIsInGame(Player player){
return playersInGame.contains(player);
}
public Player entityIsInGame(int entityID){
for(Player player : playersInGame){
if(player.getEntityId() == entityID) return player;
}
return null;
}
public boolean addPlayer(Player player){
if(playerIsInGame(player) || running) return false;
playersInGame.add(player);
gameTeam.addEntry(player.getDisplayName());
player.setScoreboard(gameScoreboard);
return true;
}
public int getCountdownTime(int round){
if(round < 15)
return 60 - (round * 2);
else
return 30;
}
public int getCountdownTime(){
return getCountdownTime(currentRound);
}
public void startGame(){
if(isRunning()){
Bukkit.broadcastMessage(ChatColor.RED + "Game already started!");
return;
}
if(playersInGame.size() == 0){
Bukkit.broadcastMessage(ChatColor.RED + "Game needs at least one player to start");
return;
}
running = true;
playersAreReleased = false;
currentRound = 1;
currentCountdown = getCountdownTime();
dataManager.reset();
parseMaze();
int spawns = maze.getBlocksOfType(MazeBlockType.MAZE).size() / 20;
for(Location location : maze.getInitialSpawnPositions(spawns)){
if(canSummonEntity()) // IDK we might hit the limit initially...?
summonEntity(location);
}
startPlatform = maze.createPlatform(
Math.round(((float)maze.getWidth() / 2f) - 7.5f),
Math.round(((float)maze.getHeight() / 2f) - 7.5f), 15, 15);
startPlatform.setIndicator(cage);
startPlatform.setLifeSpan(35000);
startPlatform.setPlatformHeightOffset(1);
startPlatform.placePlatform();
startPlatform.placeIndicator();
platforms.add(startPlatform);
removeEntitiesOnPlatforms();
// Set up all players
for(Player player : playersInGame) {
setupPlayer(player);
}
// Make all non-players specs
for(Player player : Bukkit.getOnlinePlayers()){
if(!playerIsInGame(player))
makePlayerSpectator(player);
}
lastUpdateTime = System.currentTimeMillis();
startGameTick();
spawnNextPlatform();
releasePlayersTask = Bukkit.getScheduler().scheduleSyncDelayedTask(this, this::releasePlayers, 150);
displayGameTitle(String.format("%s%sMonster Maze", ChatColor.GREEN, ChatColor.BOLD), "Get to the safe pad!");
Bukkit.broadcastMessage("\n");
Bukkit.broadcastMessage(String.format(" %s%sMonster Maze", ChatColor.GREEN, ChatColor.BOLD));
if(playersInGame.size() == 1){
isSingleplayerMode = true;
Bukkit.broadcastMessage(String.format(" Singleplayer mode%s", isClassicMode ? classicModeString : ""));
}
else{
isSingleplayerMode = false;
Bukkit.broadcastMessage(String.format(" Game of %s%d%s players%s",
ChatColor.GOLD, playersInGame.size(), ChatColor.RESET,
isClassicMode ? classicModeString : ""));
}
Bukkit.broadcastMessage(String.format("\n %sGet to the safe pad before", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %sthe timer expires! Watch out", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %sfor snowmen. Click items in your", ChatColor.GRAY));
Bukkit.broadcastMessage(String.format(" %shotbar to use powerups!\n\n", ChatColor.GRAY));
// Finally, make players semi-visible to one another
/*if(!isSingleplayerMode){
for(Player player : playersInGame) {
for(Player otherPlayer : playersInGame){
if(player != otherPlayer){
makeInvisibleTo(player, otherPlayer);
}
}
}
}*/
}
public void releasePlayers(){
for(Player player : playersInGame){
timeLeftBossbar.addPlayer(player);
}
playersAreReleased = true;
startPlatform.removeIndicator();
releasePlayersTask = -1;
}
public void resetTitle(){
displayGameTitle(null, null);
}
public void displayGameTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut){
for(Player player : playersInGame){
player.sendTitle(title, subtitle, fadeIn, stay, fadeOut);
}
}
public void displayGameTitle(String title, String subtitle){
displayGameTitle(title, subtitle, 20, 110, 20);
}
public void displayGameTitle(String title){
displayGameTitle(title, null);
}
public void sendToPlayers(String message){
for(Player player : playersInGame){
player.sendMessage(message);
}
}
public void spawnNextPlatform(){
MazeBlock randomPosition = platformSpawner.next();
if(lastPlatform != null){
lastPlatform.removeIndicator(); // Just in case
lastPlatform.restoreOriginal();
platforms.remove(lastPlatform);
}
if(currentPlatform != null){
lastPlatform = currentPlatform;
lastPlatform.setLifeSpan(8000);
lastPlatform.enableAging();
lastPlatform.removeIndicator();
}
currentPlatform = maze.createPlatform(randomPosition.getBlockX() - 2, randomPosition.getBlockY() - 2, 5, 5);
currentPlatform.placePlatform();
currentPlatform.disableAging();
currentPlatform.setIndicator(indicator);
currentPlatform.placeIndicator();
platforms.add(currentPlatform);
removeEntitiesOnPlatforms();
}
public void removeEntitiesOnPlatforms(){
for(MazePlatform platform : platforms){
for(int i = 0; i < runners.size(); i++){
MazeRunner runner = runners.get(i);
if(platform.entityIsOnPlatform(runner.getEntity())){
runner.getEntity().remove();
runners.remove(i);
i--;
}
}
}
}
public void killPlayersNotOnPlatform(){
for(int i = 0; i < playersInGame.size(); i++){
Player player = playersInGame.get(i);
if(!currentPlatform.entityIsOnPlatform(player)){
killPlayer(player, "You weren't on the safe pad!");
i--;
}
}
}
public void setPlayerTokens(Player player, int amt){
player.getInventory().setItem(8, MazePowerup.tokens(mazeItemKey, amt));
}
public void setupPlayer(Player player){
player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue());
player.addPotionEffect(noJump);
Location startLocation = maze.centerOfMaze();
startLocation.setY(startLocation.getY() + 0.5);
player.teleport(startLocation);
player.setCollidable(false);
player.setGameMode(GameMode.ADVENTURE); // Just in case
player.getInventory().clear();
player.getInventory().setItem(0, MazePowerup.repulse(mazeItemKey));
PlayerData data = dataManager.createDataFor(player);
if(!isClassicMode){
player.getInventory().setItem(1, MazePowerup.oneUp(mazeItemKey));
player.getInventory().setItem(2, MazePowerup.speedBoost(mazeItemKey));
setPlayerTokens(player, 0);
data.setTokens(0);
}
else{
setPlayerTokens(player, 30);
data.setTokens(30);
}
}
// Skip ahead but only if its truly "ahead"
public void skipAheadTime(int to){
if(to <= currentCountdown){
currentCountdown = to;
}
}
public void handleCountdownTime(int countdownTime){
timeLeftBossbar.setProgress((double) currentCountdown / (double) getCountdownTime());
timeLeftBossbar.setTitle(String.format("%s%sRound %d - %d Seconds Left", ChatColor.GREEN, ChatColor.BOLD, currentRound, countdownTime));
if(countdownTime <= 0){
killPlayersNotOnPlatform();
if(playersInGame.size() > 0){
currentCountdown = getCountdownTime(++currentRound);
spawnNextPlatform();
for(int i = 0; i < NEW_RUNNERS_PER_ROUND && canSummonEntity(); i++){
MazeBlock block = placesToSpawn.get(random.nextInt(placesToSpawn.size() - 1));
summonEntity(new Location(maze.getStartLocation().getWorld(),
(double) block.getBlockX() + maze.getStartLocation().getBlockX() + 0.5,
maze.getStartLocation().getY() + 1,
(double) block.getBlockY() + maze.getStartLocation().getBlockZ() + 0.5));
}
displayGameTitle(String.format("%s%sSafe!", ChatColor.GREEN, ChatColor.BOLD), "Get to the next safe pad", 0, 40, 10);
for(Player player : playersInGame){
dataManager.get(player).recordRoundSurvived();
}
if(currentRound % 5 == 0) {
Bukkit.broadcastMessage(String.format("\n %s%sRound %d%s\n",
ChatColor.GREEN, ChatColor.BOLD, currentRound,
isSingleplayerMode ? "" : String.format("\n %s%d%s players remaining!",
ChatColor.GOLD, playersInGame.size(), ChatColor.GRAY)));
}
}
}
else if(countdownTime == 10){
displayGameTitle(String.format("%s%s%d", ChatColor.GREEN, ChatColor.BOLD, countdownTime), null, 0, 40, 20);
}
else if(countdownTime <= 3){
// Display countdown time as title
displayGameTitle(String.format("%s%s%d", ChatColor.RED, ChatColor.BOLD, countdownTime), null, 0, 15, 5);
}
}
public void healPlayer(Player player, double amount){
double health = player.getHealth();
if(health + amount > 20) player.setHealth(20);
else player.setHealth(health + amount);
}
public void makePlayerSpectator(Player player){
player.setGameMode(GameMode.SPECTATOR);
spectators.add(player);
player.sendTitle(String.format("%s%sSpectating", ChatColor.GREEN, ChatColor.BOLD),
"You are spectating the game", 20, 60, 20);
Location specLoc = maze.centerOfMaze();
specLoc.setY(specLoc.getY() + 10);
player.teleport(specLoc);
}
public void killPlayer(Player player, String reason){
playersInGame.remove(player);
deadPlayers.add(player);
makePlayerSpectator(player);
timeLeftBossbar.removePlayer(player);
player.sendTitle(String.format("%s%sYou Died!", ChatColor.RED, ChatColor.BOLD), reason, 20, 60, 20);
// Send summary
PlayerData data = dataManager.get(player);
player.sendMessage(String.format("\n %s%s== SUMMARY ==%s\n - Rounds Survived: %s%d%s\n" +
" - Safe Pad Firsts: %s%d%s\n - Total Score: %s%d%s\n - Death: %s\n",
ChatColor.GREEN, ChatColor.BOLD, ChatColor.RESET,
ChatColor.GOLD, data.getRoundsSurvived(), ChatColor.RESET,
ChatColor.GOLD, data.getSafePadsFirst(), ChatColor.RESET,
ChatColor.GOLD, data.getScore(), ChatColor.RESET,
reason == null ? "Health loss" : reason));
if((isSingleplayerMode && playersInGame.size() == 0) ||
(!isSingleplayerMode && playersInGame.size() <= 1)){
finishGame();
}
else{
Bukkit.broadcastMessage(String.format("%s%s died! %d players remain",
ChatColor.YELLOW, player.getDisplayName(), playersInGame.size()));
}
resetPlayer(player);
}
public void killPlayer(Player player){
killPlayer(player, null);
}
public void finishGame(){
running = false;
Bukkit.broadcastMessage(String.format("\n%s Game over!%s\n%s Rounds survived: %s%d\n",
ChatColor.RED, ChatColor.RESET, ChatColor.GRAY, ChatColor.GOLD, currentRound - 1));
resetGame();
}
public void handlePlayerLeave(Player player){
if(playerIsInGame(player)){
resetPlayer(player);
playersInGame.remove(player);
if(playersInGame.size() <= 1){
finishGame();
}
}
if(spectators.contains(player)){
spectators.remove(player);
}
}
public void resetPlayer(Player player){
getLogger().info(String.format("Restting player %s...", player.getDisplayName()));
teleportPlayerToSpawnRoom(player);
player.setVelocity(new Vector().setX(0).setY(0).setZ(0));
player.removePotionEffect(PotionEffectType.JUMP);
player.removePotionEffect(PotionEffectType.INVISIBILITY);
player.removePotionEffect(PotionEffectType.SPEED);
player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue());
player.setCollidable(false);
player.setGameMode(GameMode.ADVENTURE);
timeLeftBossbar.removePlayer(player);
player.getInventory().clear();
// Remove invisible effect entirely
/*for(Player otherPlayer : Bukkit.getOnlinePlayers()){
if(otherPlayer != player){
undoInvisibleEffect(otherPlayer, player);
undoInvisibleEffect(player, otherPlayer);
}
}*/
}
public void resetGame(){
for(Player player : getServer().getOnlinePlayers()){
resetPlayer(player);
}
for(MazePlatform platform : platforms){
platform.restoreOriginal();
platform.removeIndicator();
}
if(releasePlayersTask != -1)
Bukkit.getScheduler().cancelTask(releasePlayersTask);
if(gameTickTask != -1)
Bukkit.getScheduler().cancelTask(gameTickTask);
platforms.clear();
lastPlatform = null;
currentPlatform = null;
running = false;
playersAreReleased = false;
playersInGame.clear();
dataManager.reset();
spectators.clear();
removeAllEntities();
}
public boolean canSummonEntity(){
return runners.size() < MAX_RUNNERS;
}
public Entity summonEntity(Location location){
Snowman snowman = (Snowman) location.getWorld().spawnEntity(location, EntityType.SNOWMAN);
snowman.setMetadata("special-entity", specialEntity);
snowman.setAI(false);
snowman.setCollidable(false);
snowman.setInvulnerable(true);
snowman.setGravity(false);
MazeRunner runner = new MazeRunner(snowman);
runner.setMaze(maze);
runners.add(runner);
return snowman;
}
public void removeAllEntities(){
for(MazeRunner runner : runners){
runner.getEntity().remove();
}
runners.clear();
}
public long deltaTime(){
long newTime = System.currentTimeMillis();
long delta = newTime - lastUpdateTime;
lastUpdateTime = newTime;
return delta;
}
public void startGameTick(){
gameTickTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
long dt = deltaTime();
for(MazeRunner runner : runners){
runner.update(dt);
}
for(int i = 0; i < platforms.size(); i++){
MazePlatform platform = platforms.get(i);
platform.update(dt);
if(platform.isExpired()){
platform.restoreOriginal();
platform.removeIndicator();
platforms.remove(platform);
}
}
for(int i = 0; i < playersInGame.size(); i++){
Player player = playersInGame.get(i);
PlayerData data = dataManager.get(player);
if(playersAreReleased && currentPlatform.entityIsOnPlatform(player)){
if(currentPlatform.isUntouched()){
if(!isSingleplayerMode)
Bukkit.broadcastMessage(String.format("%s%s%s made it to the safe pad first!",
ChatColor.GREEN, player.getDisplayName(), ChatColor.RESET));
skipAheadTime(11);
currentPlatform.setUntouched(false);
healPlayer(player, 2);
data.addTokens(2);
data.recordSafePadFirst();
data.addScore(2);
setPlayerTokens(player, data.getTokens());
}
if (!currentPlatform.playerHasVisited(player)) {
player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 1);
player.sendMessage(String.format("%sYou made it to the safe pad!", ChatColor.GREEN));
healPlayer(player, 2);
data.addTokens(1);
data.addScore(1);
setPlayerTokens(player, data.getTokens());
currentPlatform.recordPlayerVisit(player);
if(currentPlatform.visitCount() >= playersInGame.size()){
skipAheadTime(4);
}
}
}
List<Entity> nearby = player.getWorld().getNearbyEntities(
player.getLocation(),
HORIZONTAL_HIT_DISTANCE, VERTICAL_HIT_DISTANCE, HORIZONTAL_HIT_DISTANCE,
(Entity) -> Entity.hasMetadata("special-entity"))
.stream().toList();
if(nearby.size() > 0){
if(boopCooldown.testEntity(player))
if(boopPlayer(player, nearby.get(0))){
i--; // Player died from the boop :(
continue;
}
}
if(player.getLocation().getY() < maze.getStartLocation().getY() - 0.9){
killPlayer(player, "You fell off the maze!");
i--;
}
}
}, CHECK_DELAY, CHECK_DELAY);
}
// Returns whether or not the player was killed by this boop
public boolean boopPlayer(Player player, Entity entity){
Vector velocity = new Vector();
velocity.setY(VERTICAL_BOOP_FORCE);
double angleBetween = Math.atan2(entity.getLocation().getX() - player.getLocation().getX(),
entity.getLocation().getZ() - player.getLocation().getZ());
velocity.setZ(-Math.cos(angleBetween) * HORIZONTAL_BOOP_FORCE);
velocity.setX(-Math.sin(angleBetween) * HORIZONTAL_BOOP_FORCE);
player.setVelocity(velocity);
if(player.getHealth() <= HEALTH_PER_HIT){
killPlayer(player);
return true;
}
else{
player.damage(HEALTH_PER_HIT);
return false;
}
}
public boolean isRunning(){
return running;
}
public void repulse(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("repulse")) return;
if(data.getTokens() >= REPULSE_COST){
data.setTokens(data.getTokens() - REPULSE_COST);
doRepulseAt(player.getLocation());
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + REPULSE_COST);
}
}
public void doRepulseAt(Location location){
List<Entity> nearby = location.getWorld().getNearbyEntities(
location,
REPULSE_RANGE, REPULSE_RANGE, REPULSE_RANGE,
(Entity) -> Entity.hasMetadata("special-entity"))
.stream().toList();
for(Entity entity : nearby){
runners.remove(entity);
entity.remove();
Firework firework = entity.getWorld().spawn(new Location(
entity.getLocation().getWorld(),
entity.getLocation().getX(),
entity.getLocation().getY() + 1,
entity.getLocation().getZ()
), Firework.class);
FireworkMeta meta = firework.getFireworkMeta();
meta.setPower(2);
FireworkEffect effect = FireworkEffect.builder().with(FireworkEffect.Type.BALL).withColor(Color.BLACK).build();
meta.addEffect(effect);
firework.setFireworkMeta(meta);
firework.detonate();
}
}
public void oneUp(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("one-up")) return;
if(data.getTokens() >= ONE_UP_COST){
data.setTokens(data.getTokens() - ONE_UP_COST);
healPlayer(player, 6);
player.sendMessage(ChatColor.GREEN + "You have been healed!");
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + ONE_UP_COST);
}
}
public void speedBoost(Player player){
if(!playerIsInGame(player) || !playersAreReleased) return;
PlayerData data = dataManager.get(player);
if(!data.testPowerupCooldown("speed-boost")) return;
if(data.getTokens() >= SPEED_BOOST_COST){
data.setTokens(data.getTokens() - SPEED_BOOST_COST);
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 200, 1, false, false));
setPlayerTokens(player, data.getTokens());
}
else{
player.sendMessage(ChatColor.RED + "Not enough tokens! Costs " + SPEED_BOOST_COST);
}
}
/*public void makeInvisibleTo(Player viewer, Player invisiblePlayer){
getLogger().info(String.format("Making %s invisible to %s", invisiblePlayer.getDisplayName(), viewer.getDisplayName()));
//PacketContainer packet = pm.createPacket(PacketType.Play.Server.ENTITY_EFFECT);
DataWatcher watcher = ((CraftPlayer) invisiblePlayer).getHandle().getDataWatcher();
watcher.set(new DataWatcherObject<>(0, DataWatcherRegistry.a), (byte)0x20);
PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(invisiblePlayer.getEntityId(),
watcher, false);
/*PacketContainer packet = PacketContainer.fromPacket(
new PacketPlayOutEntityEffect(viewer.getEntityId(),
new MobEffect(MobEffectList.fromId(14), 99999, 1)));*//*
//packet.getIntegers().write(0, invisiblePlayer.getEntityId());
//packet.getBytes().write(0, (byte)(14 & 255));
//packet.getSpecificModifier(MobEffect.class).write(0, new MobEffect(MobEffectList.fromId(14)));
//packet.getIntegers().write(1, 1);
try {
pm.sendServerPacket(viewer, PacketContainer.fromPacket(packet));
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}*/
/*public void undoInvisibleEffect(Player viewer, Player invisiblePlayer){
getLogger().info(String.format("Making %s visible to %s", invisiblePlayer.getDisplayName(), viewer.getDisplayName()));
//PacketContainer packet = pm.createPacket(PacketType.Play.Server.REMOVE_ENTITY_EFFECT);
//packet.getIntegers().write(0, invisiblePlayer.getEntityId());
//packet.getBytes().write(0, (byte) 14);
//packet.getSpecificModifier(MobEffectList.class).write(0, MobEffectList.fromId(14));
DataWatcher watcher = ((CraftPlayer) invisiblePlayer).getHandle().getDataWatcher();
watcher.set(new DataWatcherObject<>(0, DataWatcherRegistry.a), (byte)0);
PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(invisiblePlayer.getEntityId(),
watcher, false);
try {
pm.sendServerPacket(viewer, PacketContainer.fromPacket(packet));
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}*/
public Maze getMaze() {
return maze;
}
public boolean isClassicMode() {
return isClassicMode;
}
public void setClassicMode(boolean classicMode) {
isClassicMode = classicMode;
}
public Template getIndicatorTemplate(){
return indicator;
}
public NamespacedKey getMazeItemKey() {
return mazeItemKey;
}
}
| 34,916 | 0.608002 | 0.600126 | 842 | 40.467934 | 29.758881 | 183 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.839667 | false | false | 9 |
8c27d3600b1db5a19ad9b7dbfef23553de8da646 | 19,275,813,245,700 | 683c2019cdab7cdda488caa15b58a1357ee6ae54 | /BasicBake/src/com/example/basicbake/ButterCakeActivity.java | 18f2c76872e36c862f216fa6af81f94d4f0df865 | [] | no_license | munishchouhan/GoodAndroidApps | https://github.com/munishchouhan/GoodAndroidApps | a65020f92793a35cf90376de011158ee7e8ca782 | 4baa35c58d4aa16e002a3ccc49ed4544ae0752f4 | refs/heads/master | 2023-07-06T19:09:38.198000 | 2016-12-28T12:01:22 | 2016-12-28T12:01:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.basicbake;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.TextView;
public class ButterCakeActivity extends Activity {
TextView mTextView;
WebView webView;
String Name;
ImageButton play, pause, stop;
boolean stopoption = false;
final MediaPlayer mp = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_butter_cake);
play = (ImageButton) findViewById(R.id.playbtn);
pause = (ImageButton) findViewById(R.id.pausebtn);
stop = (ImageButton) findViewById(R.id.stopbtn);
Bundle bundle = getIntent().getExtras();
Name= bundle.getString("name");
mTextView = (TextView) findViewById(R.id.recipestitle);
mTextView.setText(Name);
webView = (WebView) findViewById(R.id.recipesDetails);
Name = Name.toLowerCase();
Name=Name.replace(" ", "");
webView.loadUrl("file:///android_asset/"+Name+".html");
playaudio();
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(stopoption)
{
playaudio();
stopoption = false;
}
else
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
stopoption = true;
}
});
}
public void playaudio() {
mp.stop();
mp.reset();
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("audio/" + Name + ".wav");
mp.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.stop();
mp.reset();
}
} | UTF-8 | Java | 2,182 | java | ButterCakeActivity.java | Java | [] | null | [] | package com.example.basicbake;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.TextView;
public class ButterCakeActivity extends Activity {
TextView mTextView;
WebView webView;
String Name;
ImageButton play, pause, stop;
boolean stopoption = false;
final MediaPlayer mp = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_butter_cake);
play = (ImageButton) findViewById(R.id.playbtn);
pause = (ImageButton) findViewById(R.id.pausebtn);
stop = (ImageButton) findViewById(R.id.stopbtn);
Bundle bundle = getIntent().getExtras();
Name= bundle.getString("name");
mTextView = (TextView) findViewById(R.id.recipestitle);
mTextView.setText(Name);
webView = (WebView) findViewById(R.id.recipesDetails);
Name = Name.toLowerCase();
Name=Name.replace(" ", "");
webView.loadUrl("file:///android_asset/"+Name+".html");
playaudio();
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(stopoption)
{
playaudio();
stopoption = false;
}
else
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
stopoption = true;
}
});
}
public void playaudio() {
mp.stop();
mp.reset();
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("audio/" + Name + ".wav");
mp.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.stop();
mp.reset();
}
} | 2,182 | 0.691567 | 0.691567 | 92 | 22.72826 | 17.547516 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.456522 | false | false | 9 |
5eb0cad6b9eaefea6b28073dc10b0c11786fab4e | 23,338,852,311,605 | 80b112eeee88915873ad6f784a9ae995d91c2305 | /src/main/java/com/designpattern/factoryClass/Windows.java | d7ac5fe17330cc8c3464f83fa157076dbdd06861 | [] | no_license | sharmaashish54/DesignPatterns | https://github.com/sharmaashish54/DesignPatterns | 02e914fb8235f2e48f530b786f560d8bad14ccb9 | 082d052e4e417ad393466f340427084e1b220659 | refs/heads/master | 2023-06-14T09:59:50.722000 | 2021-07-18T16:27:58 | 2021-07-18T16:27:58 | 387,220,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.designpattern.factoryClass;
public class Windows implements OS {
public void specs() {
System.out.println("Good OS for windows");
}
}
| UTF-8 | Java | 156 | java | Windows.java | Java | [] | null | [] | package com.designpattern.factoryClass;
public class Windows implements OS {
public void specs() {
System.out.println("Good OS for windows");
}
}
| 156 | 0.717949 | 0.717949 | 10 | 14.6 | 17.647663 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 9 |
301ba938abf871cf9fd15b95fe0620366488634a | 1,872,605,765,728 | b0c1f8765ffa7ee9a42f8edee5bd8ed377e8d4ed | /SlideShowDemo/src/slideshowdemo/SlideShow.java | 5e649c1c9fcf9594b2c3983a1d1ba753cfe269a4 | [] | no_license | sunjid-git/Java-Swing-Core-Concepts | https://github.com/sunjid-git/Java-Swing-Core-Concepts | 14167abd40670d91c74caa8551d35e6293db6497 | d5c4fcfebd7c970ba950be107369b666ef9ea34f | refs/heads/master | 2020-09-11T21:23:49.592000 | 2020-02-05T15:08:42 | 2020-02-05T15:08:42 | 222,194,467 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package slideshowdemo;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SlideShow extends JFrame implements ActionListener{
private Container c;
private JPanel panel;
private JButton prevButton, nextButton;
private ImageIcon icon;
private JLabel label;
private CardLayout card;
SlideShow()
{
initComponents();
showImage();
}
public void showImage()
{
String[] imageNames = {"1 (1).jpg","1 (2).jpg","1 (3).jpg","1 (4).jpg","1 (5).jpg","1 (6).jpg","1 (7).jpg","1 (8).jpg","1 (9).jpg","1 (10).jpg","1 (11).jpg","1 (12).jpg","1 (13).jpg","1 (14).jpg","1 (15).jpg","1 (16).jpg","1 (17).jpg","1 (18).jpg","1 (19).jpg","1 (20).jpg","1 (21).jpg","1 (22).jpg","1 (23).jpg","1 (24).jpg","1 (25).jpg","1 (26).jpg","1 (27).jpg","1 (28).jpg","1 (29).jpg","1 (30).jpg","1 (31).jpg","1 (32).jpg","1 (33).jpg","1 (34).jpg","1 (35).jpg","1 (36).jpg","1 (37).jpg","1 (38).jpg","1 (39).jpg","1 (40).jpg"};
for(String n : imageNames)
{
icon = new ImageIcon("src/Arabicography/"+n);
//resizing image
Image img = icon.getImage();
Image newImage = img.getScaledInstance(panel.getWidth(),panel.getHeight(),Image.SCALE_SMOOTH );
icon = new ImageIcon(newImage);
label = new JLabel(icon);
panel.add(label);
}
}
public void initComponents()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,600,500);
this.setTitle("Slide Show");
c = this.getContentPane();
c.setLayout(null);
c.setBackground(Color.LIGHT_GRAY);
card = new CardLayout();
panel = new JPanel(card);
panel.setBounds(10,10,560,380);
c.add(panel);
prevButton = new JButton("Previous");
prevButton.setBounds(10,400,100,50);
c.add(prevButton);
nextButton = new JButton("Next");
nextButton.setBounds(470,400,100,50);
c.add(nextButton);
prevButton.addActionListener(this);
nextButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==prevButton)
{
card.previous(panel);
}
if(e.getSource()==nextButton)
{
card.next(panel);
}
}
public static void main(String[] args) {
SlideShow frame = new SlideShow();
frame.setVisible(true);
}
}
| UTF-8 | Java | 3,048 | java | SlideShow.java | Java | [] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package slideshowdemo;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SlideShow extends JFrame implements ActionListener{
private Container c;
private JPanel panel;
private JButton prevButton, nextButton;
private ImageIcon icon;
private JLabel label;
private CardLayout card;
SlideShow()
{
initComponents();
showImage();
}
public void showImage()
{
String[] imageNames = {"1 (1).jpg","1 (2).jpg","1 (3).jpg","1 (4).jpg","1 (5).jpg","1 (6).jpg","1 (7).jpg","1 (8).jpg","1 (9).jpg","1 (10).jpg","1 (11).jpg","1 (12).jpg","1 (13).jpg","1 (14).jpg","1 (15).jpg","1 (16).jpg","1 (17).jpg","1 (18).jpg","1 (19).jpg","1 (20).jpg","1 (21).jpg","1 (22).jpg","1 (23).jpg","1 (24).jpg","1 (25).jpg","1 (26).jpg","1 (27).jpg","1 (28).jpg","1 (29).jpg","1 (30).jpg","1 (31).jpg","1 (32).jpg","1 (33).jpg","1 (34).jpg","1 (35).jpg","1 (36).jpg","1 (37).jpg","1 (38).jpg","1 (39).jpg","1 (40).jpg"};
for(String n : imageNames)
{
icon = new ImageIcon("src/Arabicography/"+n);
//resizing image
Image img = icon.getImage();
Image newImage = img.getScaledInstance(panel.getWidth(),panel.getHeight(),Image.SCALE_SMOOTH );
icon = new ImageIcon(newImage);
label = new JLabel(icon);
panel.add(label);
}
}
public void initComponents()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100,100,600,500);
this.setTitle("Slide Show");
c = this.getContentPane();
c.setLayout(null);
c.setBackground(Color.LIGHT_GRAY);
card = new CardLayout();
panel = new JPanel(card);
panel.setBounds(10,10,560,380);
c.add(panel);
prevButton = new JButton("Previous");
prevButton.setBounds(10,400,100,50);
c.add(prevButton);
nextButton = new JButton("Next");
nextButton.setBounds(470,400,100,50);
c.add(nextButton);
prevButton.addActionListener(this);
nextButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==prevButton)
{
card.previous(panel);
}
if(e.getSource()==nextButton)
{
card.next(panel);
}
}
public static void main(String[] args) {
SlideShow frame = new SlideShow();
frame.setVisible(true);
}
}
| 3,048 | 0.574803 | 0.524278 | 101 | 28.178217 | 54.670097 | 543 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.049505 | false | false | 9 |
b4df8d3e221de347c39c0a6b65919385602b1482 | 30,837,865,212,573 | 2c2ba5363e5e980a7bdaae95d267657f9d9ccd50 | /src/main/java/TwoDRotateMatrix.java | 982b4f016fceb757d5c18ccf6ebf43c21092213e | [] | no_license | rohangaur21/leetcode | https://github.com/rohangaur21/leetcode | e19e95882fdec7c405ba92652b33e4df955f56d5 | c82742d255594e054204f8c43fc6b06ff3094937 | refs/heads/master | 2022-01-08T00:38:12.733000 | 2021-12-29T16:01:51 | 2021-12-29T16:01:51 | 162,465,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
// i => 0 to middle
// j => i to n-i-j
// swap => i$j, j$n-1-j, n-1-i$n-1-j, n-1-j$i
*/public class TwoDRotateMatrix {
public void rotate(int[][] matrix) {
if (matrix.length <= 1) {
return;
}
int n = matrix.length;
int middle = n / 2;
for (int idx = 0; idx < middle; idx++) {
for (int j = idx; j < (n - 1 - idx); j++) {
int _1 = matrix[idx][j];
int _2 = matrix[j][n - 1 - idx];
int _3 = matrix[n - 1 - idx][n - 1 - j];
int _4 = matrix[n - 1 - j][idx];
matrix[j][n - 1 - idx] = _1;
matrix[n - 1 - idx][n - 1 - j] = _2;
matrix[n - 1 - j][idx] = _3;
matrix[idx][j] = _4;
}
}
}
}
| UTF-8 | Java | 1,463 | java | TwoDRotateMatrix.java | Java | [] | null | [] | /*
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
// i => 0 to middle
// j => i to n-i-j
// swap => i$j, j$n-1-j, n-1-i$n-1-j, n-1-j$i
*/public class TwoDRotateMatrix {
public void rotate(int[][] matrix) {
if (matrix.length <= 1) {
return;
}
int n = matrix.length;
int middle = n / 2;
for (int idx = 0; idx < middle; idx++) {
for (int j = idx; j < (n - 1 - idx); j++) {
int _1 = matrix[idx][j];
int _2 = matrix[j][n - 1 - idx];
int _3 = matrix[n - 1 - idx][n - 1 - j];
int _4 = matrix[n - 1 - j][idx];
matrix[j][n - 1 - idx] = _1;
matrix[n - 1 - idx][n - 1 - j] = _2;
matrix[n - 1 - j][idx] = _3;
matrix[idx][j] = _4;
}
}
}
}
| 1,463 | 0.475735 | 0.410116 | 70 | 19.9 | 24.399151 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.957143 | false | false | 9 |
64547876240b0566ebe3a95407f8bed3f3774d22 | 21,251,498,201,419 | e1e5bd6b116e71a60040ec1e1642289217d527b0 | /Interlude/L2jFrozen_15/L2jFrozen_15_Revision_1596/L2jFrozen_15/head-src/com/l2jfrozen/gameserver/model/actor/stat/SummonStat.java | cd1345f58d2d03da8f4884f16fd87d3777d1e53c | [] | no_license | serk123/L2jOpenSource | https://github.com/serk123/L2jOpenSource | 6d6e1988a421763a9467bba0e4ac1fe3796b34b3 | 603e784e5f58f7fd07b01f6282218e8492f7090b | refs/heads/master | 2023-03-18T01:51:23.867000 | 2020-04-23T10:44:41 | 2020-04-23T10:44:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.l2jfrozen.gameserver.model.actor.stat;
import com.l2jfrozen.gameserver.model.L2Summon;
public class SummonStat extends PlayableStat
{
public SummonStat(final L2Summon activeChar)
{
super(activeChar);
}
@Override
public L2Summon getActiveChar()
{
return (L2Summon) super.getActiveChar();
}
}
| UTF-8 | Java | 318 | java | SummonStat.java | Java | [] | null | [] | package com.l2jfrozen.gameserver.model.actor.stat;
import com.l2jfrozen.gameserver.model.L2Summon;
public class SummonStat extends PlayableStat
{
public SummonStat(final L2Summon activeChar)
{
super(activeChar);
}
@Override
public L2Summon getActiveChar()
{
return (L2Summon) super.getActiveChar();
}
}
| 318 | 0.77044 | 0.751572 | 17 | 17.705883 | 19.774508 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false | 9 |
5c8785d8beb62eea9054848aa5a772a14023c19a | 8,280,696,976,511 | 174e416c9ff6405b4dd8d658e1dc0addcb4ece4d | /android/SmartSignCapture/app/src/main/java/at/fhs/smartsigncapture/data/scheme/SSCSharedPreferncesHandler.java | 93c18d821e64055ee84cff902485b614c00edb85 | [
"MIT"
] | permissive | SmartSignCapture/SmartSignCapture | https://github.com/SmartSignCapture/SmartSignCapture | 6ec513b9fcd8a65c05be50fe45cb8936d1e2abb7 | 611949eb097b7b6f109710f2e498dab1dbb0d256 | refs/heads/master | 2021-01-10T15:42:03.545000 | 2016-02-22T07:20:32 | 2016-02-22T07:20:32 | 50,570,047 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package at.fhs.smartsigncapture.data.scheme;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
/**
* Created by MartinTiefengrabner on 15/07/15.
*/
public class SSCSharedPreferncesHandler {
public static final String PREFS_NAME = "at.fhs.smartsigncapture";
public static void cleanSharedPreferences(Context context){
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear().commit();
}
public static void storeValueForKey(Context context, String key, String value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value).commit();
}
public static void storeValueForKey(Context context, String key, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value).commit();
}
public static void storeValueForKey(Context context, String key, float value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, value).commit();
}
public static void storeValueForKey(Context context, String key, int value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value).commit();
}
public static void storeValueForKey(Context context, String key, long value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(key, value).commit();
}
public static void storeValueForKey(Context context, String key, Set<String> value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putStringSet(key, value).commit();
}
public static String restoreValue(Context context, String key, String defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getString(key, defaultValue);
}
public static float restoreValue(Context context, String key, float defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getFloat(key, defaultValue);
}
public static int restoreValue(Context context, String key, int defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getInt(key, defaultValue);
}
public static long restoreValue(Context context, String key, long defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getLong(key, defaultValue);
}
public static Set<String> restoreValue(Context context, String key, Set<String> defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getStringSet(key, defaultValue);
}
}
| UTF-8 | Java | 3,401 | java | SSCSharedPreferncesHandler.java | Java | [
{
"context": "erences;\n\nimport java.util.Set;\n\n/**\n * Created by MartinTiefengrabner on 15/07/15.\n */\npublic class SSCSharedPrefernces",
"end": 181,
"score": 0.9938244223594666,
"start": 162,
"tag": "NAME",
"value": "MartinTiefengrabner"
}
] | null | [] | package at.fhs.smartsigncapture.data.scheme;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
/**
* Created by MartinTiefengrabner on 15/07/15.
*/
public class SSCSharedPreferncesHandler {
public static final String PREFS_NAME = "at.fhs.smartsigncapture";
public static void cleanSharedPreferences(Context context){
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear().commit();
}
public static void storeValueForKey(Context context, String key, String value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value).commit();
}
public static void storeValueForKey(Context context, String key, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value).commit();
}
public static void storeValueForKey(Context context, String key, float value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, value).commit();
}
public static void storeValueForKey(Context context, String key, int value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value).commit();
}
public static void storeValueForKey(Context context, String key, long value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(key, value).commit();
}
public static void storeValueForKey(Context context, String key, Set<String> value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putStringSet(key, value).commit();
}
public static String restoreValue(Context context, String key, String defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getString(key, defaultValue);
}
public static float restoreValue(Context context, String key, float defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getFloat(key, defaultValue);
}
public static int restoreValue(Context context, String key, int defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getInt(key, defaultValue);
}
public static long restoreValue(Context context, String key, long defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getLong(key, defaultValue);
}
public static Set<String> restoreValue(Context context, String key, Set<String> defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
return settings.getStringSet(key, defaultValue);
}
}
| 3,401 | 0.719494 | 0.714202 | 84 | 39.488094 | 34.224918 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.964286 | false | false | 9 |
eab304b0790ab7c3d838415a5089e57ad333063e | 2,138,893,741,309 | af1ab3b6ed945a53742891afb85871f0df4bc0d1 | /09.ObjectCommunicationAndEvents/ObjectCommunicationAndEventsHomework/src/p05_kingGambit/models/BasePerson.java | c906d07cf924bb97987d40e5f7b62824e5ba844c | [] | no_license | vasilgramov/java-oop-advanced | https://github.com/vasilgramov/java-oop-advanced | 94f5321e89c0d9e446a80e1bff38947c22c5364d | 909ef2abfdd225db09f29e5fec578a1edd493006 | refs/heads/master | 2021-06-13T22:37:19.852000 | 2017-04-21T16:19:58 | 2017-04-21T16:19:58 | 84,982,046 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p05_kingGambit.models;
import p05_kingGambit.models.interfaces.Attackable;
import p05_kingGambit.models.interfaces.Hurtable;
import p05_kingGambit.models.interfaces.Nameable;
/**
* Created by vladix on 4/12/17.
*/
public abstract class BasePerson implements Nameable, Attackable, Hurtable {
private String name;
private int livePoints;
protected BasePerson(String name, int livePoints) {
this.name = name;
this.livePoints = livePoints;
}
@Override
public String getName() {
return this.name;
}
protected int getLivePoints() {
return this.livePoints;
}
protected void setLivePoints(int livePoints) {
this.livePoints = livePoints;
}
}
| UTF-8 | Java | 735 | java | BasePerson.java | Java | [
{
"context": "bit.models.interfaces.Nameable;\n\n/**\n * Created by vladix on 4/12/17.\n */\npublic abstract class BasePerson ",
"end": 209,
"score": 0.9996671676635742,
"start": 203,
"tag": "USERNAME",
"value": "vladix"
}
] | null | [] | package p05_kingGambit.models;
import p05_kingGambit.models.interfaces.Attackable;
import p05_kingGambit.models.interfaces.Hurtable;
import p05_kingGambit.models.interfaces.Nameable;
/**
* Created by vladix on 4/12/17.
*/
public abstract class BasePerson implements Nameable, Attackable, Hurtable {
private String name;
private int livePoints;
protected BasePerson(String name, int livePoints) {
this.name = name;
this.livePoints = livePoints;
}
@Override
public String getName() {
return this.name;
}
protected int getLivePoints() {
return this.livePoints;
}
protected void setLivePoints(int livePoints) {
this.livePoints = livePoints;
}
}
| 735 | 0.691156 | 0.673469 | 33 | 21.272728 | 20.818512 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false | 9 |
405e7b258c712dbc0c09c9d599681c266f912425 | 31,001,073,995,394 | 7c66fe6909a2f1d59881c79f95b436bd6dec644e | /algorithm/implementation/bon_apetite.java | 78fc3e1379a32f4324c9213e7df26590e3fbf7dd | [] | no_license | mynamerahulkumar/HackerRank | https://github.com/mynamerahulkumar/HackerRank | 5bcd6a4032886aae2ad6c934c53626df2159902c | 89cefed3e6bedb78268c874007852a8e3c849bfb | refs/heads/master | 2021-01-20T09:54:37.136000 | 2018-04-24T22:28:27 | 2018-04-24T22:28:27 | 90,299,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n;
int k;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
k=sc.nextInt();
int[]arr=new int[n];
int res;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int b;
b=sc.nextInt();
int sum=0;
for(int i=0;i<n;i++){
if(i!=k){
sum+=arr[i];
}
}
sum=sum/2;
if(sum<b){
res=b-sum;
System.out.println(res);
}
else{
System.out.println("Bon Appetit");
}
}
}
| UTF-8 | Java | 917 | java | bon_apetite.java | Java | [] | null | [] | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n;
int k;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
k=sc.nextInt();
int[]arr=new int[n];
int res;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int b;
b=sc.nextInt();
int sum=0;
for(int i=0;i<n;i++){
if(i!=k){
sum+=arr[i];
}
}
sum=sum/2;
if(sum<b){
res=b-sum;
System.out.println(res);
}
else{
System.out.println("Bon Appetit");
}
}
}
| 917 | 0.453653 | 0.449291 | 41 | 21.365854 | 18.910257 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609756 | false | false | 9 |
c1c30003d661e9399b2b2e29dfcf46fec51b6899 | 566,935,743,290 | 96e10137acd9c8ffb45c366ac94aace52b80e5a0 | /src/main/java/org/eason/common/utils/NumberUtils.java | 7275426a721517c59857e4af940bd3dd5d6f0d86 | [] | no_license | easonz/commons | https://github.com/easonz/commons | 6ef4c0f19f9afd54e5faa524873da980cbe166cd | ad34214778e30fef6b751d88fd5ca3dfd741e01a | refs/heads/master | 2021-01-21T16:34:46.355000 | 2013-10-08T09:39:34 | 2013-10-08T09:39:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.eason.common.utils;
public class NumberUtils {
public static byte[] shortToBytes(short n) {
byte[] b = new byte[2];
b[1] = (byte) (n & 0xff);
b[0] = (byte) ((n >> 8) & 0xff);
return b;
}
public static short bytesToShort(byte[] b) {
return (short) (b[1] & 0xff | (b[0] & 0xff) << 8);
}
/**
* int类型转换成byte[]
*
* @param num
* int数
* @return byte[]
*/
public static byte[] intToBytes(int num) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (num >>> (24 - i * 8));
}
return b;
}
public static int bytes2int(byte[] b) {
// byte[] b=new byte[]{1,2,3,4};
int mask = 0xff;
int temp = 0;
int res = 0;
for (int i = 0; i < 4; i++) {
res <<= 8;
temp = b[i] & mask;
res |= temp;
}
return res;
}
public static byte[] longToBytes(long num) {
byte[] b = new byte[8];
for (int i = 0; i < 8; i++) {
b[i] = (byte) (num >>> (56 - i * 8));
}
return b;
}
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString();
}
public static String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static byte[] hexStringToBytes(String hexString) {
String chars = "0123456789ABCDEF";
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (chars.indexOf(hexChars[pos]) << 4 | chars
.indexOf(hexChars[pos + 1]));
}
return d;
}
}
| UTF-8 | Java | 2,170 | java | NumberUtils.java | Java | [] | null | [] | package org.eason.common.utils;
public class NumberUtils {
public static byte[] shortToBytes(short n) {
byte[] b = new byte[2];
b[1] = (byte) (n & 0xff);
b[0] = (byte) ((n >> 8) & 0xff);
return b;
}
public static short bytesToShort(byte[] b) {
return (short) (b[1] & 0xff | (b[0] & 0xff) << 8);
}
/**
* int类型转换成byte[]
*
* @param num
* int数
* @return byte[]
*/
public static byte[] intToBytes(int num) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (num >>> (24 - i * 8));
}
return b;
}
public static int bytes2int(byte[] b) {
// byte[] b=new byte[]{1,2,3,4};
int mask = 0xff;
int temp = 0;
int res = 0;
for (int i = 0; i < 4; i++) {
res <<= 8;
temp = b[i] & mask;
res |= temp;
}
return res;
}
public static byte[] longToBytes(long num) {
byte[] b = new byte[8];
for (int i = 0; i < 8; i++) {
b[i] = (byte) (num >>> (56 - i * 8));
}
return b;
}
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString();
}
public static String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static byte[] hexStringToBytes(String hexString) {
String chars = "0123456789ABCDEF";
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (chars.indexOf(hexChars[pos]) << 4 | chars
.indexOf(hexChars[pos + 1]));
}
return d;
}
}
| 2,170 | 0.563485 | 0.530584 | 95 | 21.71579 | 17.217289 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.410526 | false | false | 9 |
f9afef319f26f7e6d1653906ab8c88ffc49c840c | 32,195,074,907,154 | 2e8b1f9d35b89483f81f9850e830a84b98c4be02 | /src/main/java/org/mcphackers/mcp/tasks/TaskCleanup.java | 26755b2863ac39906ed850e1a13efe75e078f0c6 | [] | no_license | OldSchoolMinecraft/RetroMCP-Java | https://github.com/OldSchoolMinecraft/RetroMCP-Java | d586d57c63a4d4765ac9d75db8584b02da422b81 | 9b90b0963d06bb197b13d5b45191be7f6a022598 | refs/heads/main | 2022-08-26T20:03:44.861000 | 2022-06-02T12:12:06 | 2022-06-02T12:12:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.mcphackers.mcp.tasks;
import java.nio.file.Files;
import java.nio.file.Path;
import org.mcphackers.mcp.MCP;
import org.mcphackers.mcp.MCPPaths;
import org.mcphackers.mcp.tasks.mode.TaskParameter;
import org.mcphackers.mcp.tools.FileUtil;
import org.mcphackers.mcp.tools.Util;
public class TaskCleanup extends Task {
public TaskCleanup(MCP instance) {
super(Side.ANY, instance);
}
@Override
public void doTask() throws Exception {
cleanup(mcp.getOptions().getBooleanParameter(TaskParameter.SRC_CLEANUP));
}
public void cleanup(boolean srcCleanup) throws Exception {
long startTime = System.currentTimeMillis();
int foldersDeleted = 0;
Path[] pathsToDelete = new Path[] {
MCPPaths.get(mcp, MCPPaths.CONF),
MCPPaths.get(mcp, MCPPaths.JARS),
MCPPaths.get(mcp, MCPPaths.LIB),
MCPPaths.get(mcp, MCPPaths.TEMP),
MCPPaths.get(mcp, MCPPaths.SRC),
MCPPaths.get(mcp, MCPPaths.BIN),
MCPPaths.get(mcp, MCPPaths.REOBF),
MCPPaths.get(mcp, MCPPaths.BUILD),
MCPPaths.get(mcp, "workspace")
};
if (srcCleanup) pathsToDelete = new Path[] {
MCPPaths.get(mcp, MCPPaths.SRC),
MCPPaths.get(mcp, MCPPaths.BIN),
MCPPaths.get(mcp, MCPPaths.REOBF),
MCPPaths.get(mcp, MCPPaths.BUILD)
};
for (Path path : pathsToDelete) {
if (Files.exists(path)) {
foldersDeleted++;
log("Deleting " + path.getFileName() + "...");
FileUtil.deleteDirectory(path);
}
}
if(!srcCleanup) mcp.setCurrentVersion(null);
if(foldersDeleted > 0) {
log("Done in " + Util.time(System.currentTimeMillis() - startTime));
}
else {
log("Nothing to clear!");
}
}
}
| UTF-8 | Java | 1,634 | java | TaskCleanup.java | Java | [] | null | [] | package org.mcphackers.mcp.tasks;
import java.nio.file.Files;
import java.nio.file.Path;
import org.mcphackers.mcp.MCP;
import org.mcphackers.mcp.MCPPaths;
import org.mcphackers.mcp.tasks.mode.TaskParameter;
import org.mcphackers.mcp.tools.FileUtil;
import org.mcphackers.mcp.tools.Util;
public class TaskCleanup extends Task {
public TaskCleanup(MCP instance) {
super(Side.ANY, instance);
}
@Override
public void doTask() throws Exception {
cleanup(mcp.getOptions().getBooleanParameter(TaskParameter.SRC_CLEANUP));
}
public void cleanup(boolean srcCleanup) throws Exception {
long startTime = System.currentTimeMillis();
int foldersDeleted = 0;
Path[] pathsToDelete = new Path[] {
MCPPaths.get(mcp, MCPPaths.CONF),
MCPPaths.get(mcp, MCPPaths.JARS),
MCPPaths.get(mcp, MCPPaths.LIB),
MCPPaths.get(mcp, MCPPaths.TEMP),
MCPPaths.get(mcp, MCPPaths.SRC),
MCPPaths.get(mcp, MCPPaths.BIN),
MCPPaths.get(mcp, MCPPaths.REOBF),
MCPPaths.get(mcp, MCPPaths.BUILD),
MCPPaths.get(mcp, "workspace")
};
if (srcCleanup) pathsToDelete = new Path[] {
MCPPaths.get(mcp, MCPPaths.SRC),
MCPPaths.get(mcp, MCPPaths.BIN),
MCPPaths.get(mcp, MCPPaths.REOBF),
MCPPaths.get(mcp, MCPPaths.BUILD)
};
for (Path path : pathsToDelete) {
if (Files.exists(path)) {
foldersDeleted++;
log("Deleting " + path.getFileName() + "...");
FileUtil.deleteDirectory(path);
}
}
if(!srcCleanup) mcp.setCurrentVersion(null);
if(foldersDeleted > 0) {
log("Done in " + Util.time(System.currentTimeMillis() - startTime));
}
else {
log("Nothing to clear!");
}
}
}
| 1,634 | 0.698898 | 0.697674 | 59 | 26.694916 | 18.953337 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.728814 | false | false | 9 |
52dda21bf879d0ef0b7bdde00bb3b792df5ee7d9 | 29,910,152,312,378 | d7890c3b0b485159eefb1c003651740b346a0be8 | /Go2DrinkLibrary/src/com/g2d/domain/ToppingEnum.java | cf12367c18ee5ca7664a9425f1455801bf64ffe6 | [] | no_license | s930415/Go2Drink | https://github.com/s930415/Go2Drink | 341c0880d2693a9abd0bfa6f972d1917854676ff | 77ff022bec64aa431deb8cc75d07d18d4dc21fb5 | refs/heads/master | 2021-01-17T12:36:24.928000 | 2018-03-08T15:57:16 | 2018-03-09T08:45:18 | 58,420,528 | 4 | 2 | null | false | 2016-05-10T08:46:31 | 2016-05-10T01:39:14 | 2016-05-10T04:11:20 | 2016-05-10T08:46:30 | 51 | 2 | 1 | 0 | Java | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.g2d.domain;
/**
*
* @author Administrator
*/
public enum ToppingEnum {
BUBBLE,BASILSEED,LITTLETAROBALLS,KONJACJELLY,LYCHEEJELLY,HERBJELLY,AIYUJELLY,REDBEAN,ALOE,COCONUTJELLY,CARAMEL,MILKCANDY,FLAN
}
| UTF-8 | Java | 410 | java | ToppingEnum.java | Java | [
{
"context": "or.\n */\npackage com.g2d.domain;\n\n/**\n *\n * @author Administrator\n */\npublic enum ToppingEnum {\n \n BUBBLE,BAS",
"end": 241,
"score": 0.6504960060119629,
"start": 228,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.g2d.domain;
/**
*
* @author Administrator
*/
public enum ToppingEnum {
BUBBLE,BASILSEED,LITTLETAROBALLS,KONJACJELLY,LYCHEEJELLY,HERBJELLY,AIYUJELLY,REDBEAN,ALOE,COCONUTJELLY,CARAMEL,MILKCANDY,FLAN
}
| 410 | 0.753659 | 0.75122 | 16 | 24.625 | 35.117435 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
a6896913227bdd25196fc3e0e92173936e51e207 | 8,933,532,035,729 | bbbd81caabfe5914bb515c43158f01cea9cf1b86 | /src/com/matigakis/flightbot/aircraft/sensors/TemperatureSensor.java | e897d6d582029f1740cb2d896e0d28a7b914cd11 | [] | no_license | pmatigakis/flightbot | https://github.com/pmatigakis/flightbot | e0a2bc941261da248381bfa5bd8cd0289ba56ee4 | 7fc0ff4f3aa67a0adb7425a9dcc87f42a005bdef | refs/heads/master | 2020-04-23T07:56:28.211000 | 2015-01-22T19:57:03 | 2015-01-22T19:57:03 | 20,157,960 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.matigakis.flightbot.aircraft.sensors;
import com.matigakis.fgcontrol.fdm.FDMData;;
/**
* The TemperatureSensor measures the air temperature.
*/
public class TemperatureSensor implements Sensor{
protected double temperature;
/**
* Reset the temperature sensor,
*/
@Override
public void reset() {
setTemperature(0.0);
}
/**
* Update the temperature sensor using data from the sensors.
*/
@Override
public void updateFromFDMData(FDMData fdmData) {
setTemperature(fdmData.getAtmosphere().getTemperature());
}
/**
* Set the temperature
*
* @param temperature
*/
public void setTemperature(double temperature){
this.temperature = temperature;
}
/**
* Get the temperature
*
* @return temperature
*/
public double getTemperature(){
return temperature;
}
}
| UTF-8 | Java | 820 | java | TemperatureSensor.java | Java | [] | null | [] | package com.matigakis.flightbot.aircraft.sensors;
import com.matigakis.fgcontrol.fdm.FDMData;;
/**
* The TemperatureSensor measures the air temperature.
*/
public class TemperatureSensor implements Sensor{
protected double temperature;
/**
* Reset the temperature sensor,
*/
@Override
public void reset() {
setTemperature(0.0);
}
/**
* Update the temperature sensor using data from the sensors.
*/
@Override
public void updateFromFDMData(FDMData fdmData) {
setTemperature(fdmData.getAtmosphere().getTemperature());
}
/**
* Set the temperature
*
* @param temperature
*/
public void setTemperature(double temperature){
this.temperature = temperature;
}
/**
* Get the temperature
*
* @return temperature
*/
public double getTemperature(){
return temperature;
}
}
| 820 | 0.709756 | 0.707317 | 44 | 17.636364 | 19.095562 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.045455 | false | false | 9 |
8817a9d6eafc51909bebf795c7d36ea3ac051340 | 4,363,686,826,903 | 6d6833327ea9e9b85fdc151b22a5cc05577ef186 | /src/clases/DetallePedido.java | 64b0a891d6badf63d12e36d8759e857f6e9b2bfb | [] | no_license | jeremysch98/yelizSistemaLavanderia | https://github.com/jeremysch98/yelizSistemaLavanderia | 5b0dfa8ea61fd320d14747d99c1f88855f8af5a6 | 70459c1c425b1bc54113c177f8621a3d0eee0545 | refs/heads/main | 2023-07-07T05:19:49.655000 | 2021-08-16T04:48:26 | 2021-08-16T04:48:26 | 396,621,288 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clases;
public class DetallePedido {
private int coda;
private String descripcion;
private int cantidad;
private double precio;
private String codped;
private double subtotal;
public DetallePedido() {
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public String getCodped() {
return codped;
}
public void setCodped(String codped) {
this.codped = codped;
}
public int getCoda() {
return coda;
}
public void setCoda(int coda) {
this.coda = coda;
}
public double getSubtotal() {
return subtotal;
}
public void setSubtotal(double subtotal) {
this.subtotal = subtotal;
}
}
| UTF-8 | Java | 1,135 | java | DetallePedido.java | Java | [] | null | [] | package clases;
public class DetallePedido {
private int coda;
private String descripcion;
private int cantidad;
private double precio;
private String codped;
private double subtotal;
public DetallePedido() {
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public String getCodped() {
return codped;
}
public void setCodped(String codped) {
this.codped = codped;
}
public int getCoda() {
return coda;
}
public void setCoda(int coda) {
this.coda = coda;
}
public double getSubtotal() {
return subtotal;
}
public void setSubtotal(double subtotal) {
this.subtotal = subtotal;
}
}
| 1,135 | 0.6 | 0.6 | 62 | 17.306452 | 15.207796 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306452 | false | false | 9 |
4d06ca30bf665edc02745f5da54736ab5b34642c | 16,750,372,517,369 | 34c60fa9dba17a5a23a5806dac3c12ab935cb42e | /src/com/singularity/clover/activity/entity/TaskViewActivity.java | 2c0788e588bf144e3d5d303ef03a88c40bccffe1 | [] | no_license | johnnyeric/singularity-clover | https://github.com/johnnyeric/singularity-clover | 54749a0aa93908e0ec0a39e8efd305a07e1075ea | 9b91b9455a1a7325d17aaad7eb2069eac168824f | refs/heads/master | 2020-12-25T08:16:14.856000 | 2012-06-20T02:47:35 | 2012-06-20T02:47:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.singularity.clover.activity.entity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.singularity.clover.Global;
import com.singularity.clover.R;
import com.singularity.clover.SingularityApplication;
import com.singularity.clover.activity.entity.TaskViewActivityHelper.ViewHolder;
import com.singularity.clover.activity.record.NoteActivity;
import com.singularity.clover.activity.record.RecordOverViewActivity;
import com.singularity.clover.activity.record.WhiteboardActivity;
import com.singularity.clover.entity.EntityPool;
import com.singularity.clover.entity.EntityViewModel;
import com.singularity.clover.entity.Persisable;
import com.singularity.clover.entity.record.PictureRecord;
import com.singularity.clover.entity.record.Record;
import com.singularity.clover.entity.record.TextRecord;
import com.singularity.clover.entity.task.Task;
import com.singularity.clover.util.drag.DragController;
import com.singularity.clover.util.drag.DragDeleteZone;
import com.singularity.clover.util.drag.DragLayer;
import com.singularity.clover.util.drag.DragScrollView;
import com.singularity.clover.util.drag.DragSource;
import com.singularity.clover.util.drag.DragVerticalScrollView;
import com.singularity.clover.util.drag.MyAbsoluteLayout.LayoutParams;
public class TaskViewActivity extends Activity
implements DragController.DragListener{
public static final String TASK_NEW = "singularity.activity.entity.task.new";
public static final String TASK_EDIT = "singularity.activity.entity.task.edit";
public static final String TASK_SHOW_NOTIFICATION =
"singularity.activity.entity.task.notification.show";
public static final String IN_TASK_ID =
"com.singularity.activity.entity.TaskViewActivity.task.id";
public static final String IN_SCENARIO_ID =
"com.singularity.activity.entity.TaskViewActivity.scenario.id";
public static final String RESULT_RECORD_ID =
"com.singularity.activity.entity.TaskViewActivity.result.record.id";
public static final int OUT_NOTE_NEW = 0;
public static final int OUT_NOTE_EDIT = 1;
public static final int OUT_RECORD_PICK = 2;
public static final int OUT_RECORD_EDIT = 3;
public static final int OUT_PICTURE_EDIT = 4;
protected DragController mDragController;
protected DragLayer mDragLayer;
private DragDeleteZone mDeleteZ;
private View mMenu;
protected View mDropIndicator;
protected View mLayout;
private AlertDialog mOBJDialog = null;
private ViewGroup mOBJLayout;
private ViewGroup mOBJGroup;
private float mTouchX,mTouchY;
private DragScrollView mHorizontalScrollView;
private DragVerticalScrollView mVerticalScrollView;
private EntityViewModel mEditViewModel;
private View mEditView;
private TaskViewActivityHelper mHelper;
protected Task mTask;
private GestureCallback mGestureCallback;
protected OnRecordClick mRecordClickListner = new OnRecordClick();
protected OnNoteClick mNoteClickListner = new OnNoteClick();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_view_layout);
mHelper = new TaskViewActivityHelper(this);
parse(getIntent());
mLayout = findViewById(R.id.task_view_layout);
mDragController = new DragController(this);
mDragLayer = (DragLayer) findViewById(R.id.task_view_drag_layer);
mDeleteZ = (DragDeleteZone) findViewById(R.id.task_view_drag_delete_zone);
mMenu = findViewById(R.id.task_view_menu);
mDropIndicator = findViewById(R.id.task_view_drop_indicator);
mDragLayer.setDragController(mDragController);
mDragController.addDropTarget (mDragLayer);
mDragController.addDropTarget(mDeleteZ);
mDragController.setDragListener(mDeleteZ);
mDragController.setDragListener(this);
mHorizontalScrollView = (DragScrollView) findViewById(
R.id.task_view_framelayout);
mVerticalScrollView = (DragVerticalScrollView) findViewById(
R.id.task_view_framelayout_vertical);
mGestureCallback = new GestureCallback();
mHorizontalScrollView.setGestrueCallback(mGestureCallback);
mVerticalScrollView.setGestrueCallback(mGestureCallback);
mHelper.setupTask(mTask,mDragLayer);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
parse(intent);
mHelper.setupBasicInfo(mTask,mDragLayer);
}
private void parse(Intent intent){
String action = intent.getAction();
if(action.equals(TASK_NEW)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();}
}else if(action.equals(TASK_EDIT)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();}
}else if(action.equals(TASK_SHOW_NOTIFICATION)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
SingularityApplication.instance().getNotifierBinder().bindNotifer();
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();
}
}
}
public class OnDragViewLongClick implements OnLongClickListener{
@Override
public boolean onLongClick(View v) {
if (!v.isInTouchMode())
return false;
Object dragInfo = v;
mDragController.startDrag (v, mDragLayer,
dragInfo, DragController.DRAG_ACTION_MOVE);
return true;
}
}
private void setupOBJDialog(){
AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.
getSystemService(LAYOUT_INFLATER_SERVICE);
View root = (ViewGroup) inflater.inflate(
R.layout.task_view_objective_layout,null);
mOBJLayout = (ViewGroup) root.findViewById(
R.id.task_view_objectives_layout);
mOBJGroup = (ViewGroup) root.findViewById(
R.id.task_view_objectives_group);
builder = new AlertDialog.Builder(mContext);
builder.setView(root);
mOBJDialog = builder.create();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
public void onBackPressed() {
View view = getCurrentFocus();
if(view != null){
view.clearFocus();}
if(mMenu.getVisibility() == View.VISIBLE){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
return;
}else{
String action = getIntent().getAction();
if(action.equals(TASK_EDIT)){
super.onBackPressed();
}else if(action.equals(TASK_NEW)){
Intent intent = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.setAction(TaskOverViewActivity.TASK_OVERVIEW_ADD_TASK_DONE);
intent.putExtra(TaskOverViewActivity.IN_ADD_TASK_ID, mTask.getId());
startActivity(intent);
}else if(action.equals(TASK_SHOW_NOTIFICATION)){
Intent intent = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//intent.setAction(TaskOverViewActivity.TASK_OVERVIEWBY_SCENARIO);
//intent.putExtra(TaskOverViewActivity.IN_SCENAIRO_ID, mTask.getScenarioId());
startActivity(intent);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void onAddRecord(View v){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
Intent intent = new Intent(this, RecordOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setAction(RecordOverViewActivity.RECORD_PICK);
startActivityForResult(intent, OUT_RECORD_PICK);
}
public void onAddOBJ(View v){
if(mOBJDialog == null)
setupOBJDialog();
mOBJDialog.show();
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
public void onAddTextRecord(View v){
newNote();
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
public void onCheckable(View v){
View layout = mHelper.mCheckableModel.initView();
mHelper.mCheckableModel.changeModel(CheckableViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onOBJRemove(View v){
mOBJGroup.removeView((View) v.getParent());
}
public void onNumeric(View v){
View layout = mHelper.mNumericModel.initView();
mHelper.mNumericModel.changeModel(NumericViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onDurable(View v){
View layout = mHelper.mDurableModel.initView();
mHelper.mDurableModel.changeModel(DurableViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onOBJConfirm(View v){
mOBJDialog.dismiss();
mHelper.groupStoreHelper(mDragLayer,mOBJGroup,(int)mTouchX,(int)mTouchY);
}
public void onOBJCancel(View v){
mOBJDialog.dismiss();
}
public Task getTask(){
return mTask;
}
@Override
public void onDragStart(DragSource source, Object info, int dragAction) {
mDeleteZ.setVisibility(View.VISIBLE);
mHorizontalScrollView.setDragging(true);
mVerticalScrollView.setDragging(true);
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
@Override
public void onDragEnd() {
mDeleteZ.setVisibility(View.GONE);
mHorizontalScrollView.setDragging(false);
mVerticalScrollView.setDragging(false);
}
private void newNote(){
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_NEW);
startActivityForResult(intent, OUT_NOTE_NEW);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case OUT_NOTE_NEW:
if(resultCode == RESULT_OK){
long id = data.getLongExtra(
RESULT_RECORD_ID, Global.INVALIDATE_ID);
if(id != Global.INVALIDATE_ID){
View layout = mHelper.mTextModel.addToLayout(
mDragLayer,(int)mTouchX, (int)mTouchY,id);
layout.setOnClickListener(mNoteClickListner);}
}else{}
break;
case OUT_RECORD_PICK:
if(resultCode == RESULT_OK){
long id = data.getLongExtra(
RESULT_RECORD_ID, Global.INVALIDATE_ID);
if(id != Global.INVALIDATE_ID){
Record record = (Record) EntityPool.instance().forId(id, Record.TAG);
if(record.getTAG() == TextRecord.TAG){
View layout = mHelper.mTextModel.addToLayout(
mDragLayer,(int)mTouchX, (int)mTouchY,id);
layout.setOnClickListener(mNoteClickListner);
}else if(record.getTAG() == PictureRecord.TAG){
View layout = mHelper.mRecordModel.addToLayout(mDragLayer,
(int)mTouchX, (int)mTouchY, id);
layout.setOnClickListener(mRecordClickListner);
}
}
}else{}
break;
case OUT_NOTE_EDIT:
if(resultCode == RESULT_OK){
if(mEditView == null){ /*因为挂机添加判断,原因不明*/
break;}
ViewHolder holder = (ViewHolder) mEditView.getTag();
Persisable e = EntityPool.instance().forId(holder.id, holder.tag);
mEditViewModel.entityToView(e, mEditView);
}else{}
break;
case OUT_PICTURE_EDIT:
if(resultCode == RESULT_OK){
if(mEditView == null){ /*因为挂机添加判断,原因不明*/
break;}
ViewHolder holder = (ViewHolder) mEditView.getTag();
Persisable e = EntityPool.instance().forId(holder.id, holder.tag);
mEditViewModel.entityToView(e, mEditView);
}else{
Toast toast = Toast.makeText(this,
getText(R.string.memory_low), Toast.LENGTH_SHORT);
toast.show();
}
break;
default:
break;
}
}
private class OnNoteClick implements OnClickListener{
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_EDIT);
intent.putExtra(NoteActivity.NOTE_EDIT_ID, holder.id);
startActivityForResult(intent, OUT_NOTE_EDIT);
}
}
private class OnRecordClick implements OnClickListener{
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
Record record= (Record) EntityPool.instance().forId(holder.id, holder.tag);
if(record.getTAG() == TextRecord.TAG){
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_EDIT);
intent.putExtra(NoteActivity.NOTE_EDIT_ID, holder.id);
mEditViewModel = mHelper.mTextModel;
mEditView = v;
startActivityForResult(intent, OUT_NOTE_EDIT);
}else if(record.getTAG() == PictureRecord.TAG){
Intent intent = new Intent(TaskViewActivity.this,
WhiteboardActivity.class);
intent.setAction(WhiteboardActivity.WHITEBOARD_EDIT);
intent.putExtra(WhiteboardActivity.WHITEBOARD_URI, record.getContent());
intent.putExtra(WhiteboardActivity.RECORD_ID, holder.id);
mEditViewModel = mHelper.mRecordModel;
mEditView = v;
startActivityForResult(intent, OUT_PICTURE_EDIT);
}
}
}
private class GestureCallback implements DragScrollView.GestureCallback {
@Override
public void onLongPress(MotionEvent e) {
mTouchX = e.getX();
mTouchY = e.getY();
mMenu.setVisibility(View.VISIBLE);
LayoutParams lp = (LayoutParams) mDropIndicator.getLayoutParams();
lp.x = (int) mTouchX;
lp.y = (int) mTouchY;
mDragLayer.updateViewLayout(mDropIndicator, lp);
mDropIndicator.setVisibility(View.VISIBLE);
}
@Override
public void onSingleTapUp(MotionEvent e) {
View focus = TaskViewActivity.this.getCurrentFocus();
if(focus != null && focus != mDragLayer){
focus.clearFocus();
InputMethodManager inputManager = (InputMethodManager)
TaskViewActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
focus.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
if(mMenu.getVisibility() == View.VISIBLE){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}else{
Toast.makeText(TaskViewActivity.this, getString(R.string.click_task_view_hint),
Toast.LENGTH_SHORT).show();
}
}
}
}
| GB18030 | Java | 15,470 | java | TaskViewActivity.java | Java | [] | null | [] | package com.singularity.clover.activity.entity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.singularity.clover.Global;
import com.singularity.clover.R;
import com.singularity.clover.SingularityApplication;
import com.singularity.clover.activity.entity.TaskViewActivityHelper.ViewHolder;
import com.singularity.clover.activity.record.NoteActivity;
import com.singularity.clover.activity.record.RecordOverViewActivity;
import com.singularity.clover.activity.record.WhiteboardActivity;
import com.singularity.clover.entity.EntityPool;
import com.singularity.clover.entity.EntityViewModel;
import com.singularity.clover.entity.Persisable;
import com.singularity.clover.entity.record.PictureRecord;
import com.singularity.clover.entity.record.Record;
import com.singularity.clover.entity.record.TextRecord;
import com.singularity.clover.entity.task.Task;
import com.singularity.clover.util.drag.DragController;
import com.singularity.clover.util.drag.DragDeleteZone;
import com.singularity.clover.util.drag.DragLayer;
import com.singularity.clover.util.drag.DragScrollView;
import com.singularity.clover.util.drag.DragSource;
import com.singularity.clover.util.drag.DragVerticalScrollView;
import com.singularity.clover.util.drag.MyAbsoluteLayout.LayoutParams;
public class TaskViewActivity extends Activity
implements DragController.DragListener{
public static final String TASK_NEW = "singularity.activity.entity.task.new";
public static final String TASK_EDIT = "singularity.activity.entity.task.edit";
public static final String TASK_SHOW_NOTIFICATION =
"singularity.activity.entity.task.notification.show";
public static final String IN_TASK_ID =
"com.singularity.activity.entity.TaskViewActivity.task.id";
public static final String IN_SCENARIO_ID =
"com.singularity.activity.entity.TaskViewActivity.scenario.id";
public static final String RESULT_RECORD_ID =
"com.singularity.activity.entity.TaskViewActivity.result.record.id";
public static final int OUT_NOTE_NEW = 0;
public static final int OUT_NOTE_EDIT = 1;
public static final int OUT_RECORD_PICK = 2;
public static final int OUT_RECORD_EDIT = 3;
public static final int OUT_PICTURE_EDIT = 4;
protected DragController mDragController;
protected DragLayer mDragLayer;
private DragDeleteZone mDeleteZ;
private View mMenu;
protected View mDropIndicator;
protected View mLayout;
private AlertDialog mOBJDialog = null;
private ViewGroup mOBJLayout;
private ViewGroup mOBJGroup;
private float mTouchX,mTouchY;
private DragScrollView mHorizontalScrollView;
private DragVerticalScrollView mVerticalScrollView;
private EntityViewModel mEditViewModel;
private View mEditView;
private TaskViewActivityHelper mHelper;
protected Task mTask;
private GestureCallback mGestureCallback;
protected OnRecordClick mRecordClickListner = new OnRecordClick();
protected OnNoteClick mNoteClickListner = new OnNoteClick();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_view_layout);
mHelper = new TaskViewActivityHelper(this);
parse(getIntent());
mLayout = findViewById(R.id.task_view_layout);
mDragController = new DragController(this);
mDragLayer = (DragLayer) findViewById(R.id.task_view_drag_layer);
mDeleteZ = (DragDeleteZone) findViewById(R.id.task_view_drag_delete_zone);
mMenu = findViewById(R.id.task_view_menu);
mDropIndicator = findViewById(R.id.task_view_drop_indicator);
mDragLayer.setDragController(mDragController);
mDragController.addDropTarget (mDragLayer);
mDragController.addDropTarget(mDeleteZ);
mDragController.setDragListener(mDeleteZ);
mDragController.setDragListener(this);
mHorizontalScrollView = (DragScrollView) findViewById(
R.id.task_view_framelayout);
mVerticalScrollView = (DragVerticalScrollView) findViewById(
R.id.task_view_framelayout_vertical);
mGestureCallback = new GestureCallback();
mHorizontalScrollView.setGestrueCallback(mGestureCallback);
mVerticalScrollView.setGestrueCallback(mGestureCallback);
mHelper.setupTask(mTask,mDragLayer);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
parse(intent);
mHelper.setupBasicInfo(mTask,mDragLayer);
}
private void parse(Intent intent){
String action = intent.getAction();
if(action.equals(TASK_NEW)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();}
}else if(action.equals(TASK_EDIT)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();}
}else if(action.equals(TASK_SHOW_NOTIFICATION)){
long id = intent.getLongExtra(IN_TASK_ID, Global.INVALIDATE_ID);
mTask = (Task) EntityPool.instance().forId(id, Task.TAG);
SingularityApplication.instance().getNotifierBinder().bindNotifer();
if(mTask == null){
Intent error = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(error);
finish();
}
}
}
public class OnDragViewLongClick implements OnLongClickListener{
@Override
public boolean onLongClick(View v) {
if (!v.isInTouchMode())
return false;
Object dragInfo = v;
mDragController.startDrag (v, mDragLayer,
dragInfo, DragController.DRAG_ACTION_MOVE);
return true;
}
}
private void setupOBJDialog(){
AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.
getSystemService(LAYOUT_INFLATER_SERVICE);
View root = (ViewGroup) inflater.inflate(
R.layout.task_view_objective_layout,null);
mOBJLayout = (ViewGroup) root.findViewById(
R.id.task_view_objectives_layout);
mOBJGroup = (ViewGroup) root.findViewById(
R.id.task_view_objectives_group);
builder = new AlertDialog.Builder(mContext);
builder.setView(root);
mOBJDialog = builder.create();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
public void onBackPressed() {
View view = getCurrentFocus();
if(view != null){
view.clearFocus();}
if(mMenu.getVisibility() == View.VISIBLE){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
return;
}else{
String action = getIntent().getAction();
if(action.equals(TASK_EDIT)){
super.onBackPressed();
}else if(action.equals(TASK_NEW)){
Intent intent = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.setAction(TaskOverViewActivity.TASK_OVERVIEW_ADD_TASK_DONE);
intent.putExtra(TaskOverViewActivity.IN_ADD_TASK_ID, mTask.getId());
startActivity(intent);
}else if(action.equals(TASK_SHOW_NOTIFICATION)){
Intent intent = new Intent(
TaskViewActivity.this,TaskOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//intent.setAction(TaskOverViewActivity.TASK_OVERVIEWBY_SCENARIO);
//intent.putExtra(TaskOverViewActivity.IN_SCENAIRO_ID, mTask.getScenarioId());
startActivity(intent);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void onAddRecord(View v){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
Intent intent = new Intent(this, RecordOverViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setAction(RecordOverViewActivity.RECORD_PICK);
startActivityForResult(intent, OUT_RECORD_PICK);
}
public void onAddOBJ(View v){
if(mOBJDialog == null)
setupOBJDialog();
mOBJDialog.show();
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
public void onAddTextRecord(View v){
newNote();
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
public void onCheckable(View v){
View layout = mHelper.mCheckableModel.initView();
mHelper.mCheckableModel.changeModel(CheckableViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onOBJRemove(View v){
mOBJGroup.removeView((View) v.getParent());
}
public void onNumeric(View v){
View layout = mHelper.mNumericModel.initView();
mHelper.mNumericModel.changeModel(NumericViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onDurable(View v){
View layout = mHelper.mDurableModel.initView();
mHelper.mDurableModel.changeModel(DurableViewModel.MODEL_EDIT, layout);
mOBJGroup.addView(layout);
}
public void onOBJConfirm(View v){
mOBJDialog.dismiss();
mHelper.groupStoreHelper(mDragLayer,mOBJGroup,(int)mTouchX,(int)mTouchY);
}
public void onOBJCancel(View v){
mOBJDialog.dismiss();
}
public Task getTask(){
return mTask;
}
@Override
public void onDragStart(DragSource source, Object info, int dragAction) {
mDeleteZ.setVisibility(View.VISIBLE);
mHorizontalScrollView.setDragging(true);
mVerticalScrollView.setDragging(true);
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}
@Override
public void onDragEnd() {
mDeleteZ.setVisibility(View.GONE);
mHorizontalScrollView.setDragging(false);
mVerticalScrollView.setDragging(false);
}
private void newNote(){
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_NEW);
startActivityForResult(intent, OUT_NOTE_NEW);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case OUT_NOTE_NEW:
if(resultCode == RESULT_OK){
long id = data.getLongExtra(
RESULT_RECORD_ID, Global.INVALIDATE_ID);
if(id != Global.INVALIDATE_ID){
View layout = mHelper.mTextModel.addToLayout(
mDragLayer,(int)mTouchX, (int)mTouchY,id);
layout.setOnClickListener(mNoteClickListner);}
}else{}
break;
case OUT_RECORD_PICK:
if(resultCode == RESULT_OK){
long id = data.getLongExtra(
RESULT_RECORD_ID, Global.INVALIDATE_ID);
if(id != Global.INVALIDATE_ID){
Record record = (Record) EntityPool.instance().forId(id, Record.TAG);
if(record.getTAG() == TextRecord.TAG){
View layout = mHelper.mTextModel.addToLayout(
mDragLayer,(int)mTouchX, (int)mTouchY,id);
layout.setOnClickListener(mNoteClickListner);
}else if(record.getTAG() == PictureRecord.TAG){
View layout = mHelper.mRecordModel.addToLayout(mDragLayer,
(int)mTouchX, (int)mTouchY, id);
layout.setOnClickListener(mRecordClickListner);
}
}
}else{}
break;
case OUT_NOTE_EDIT:
if(resultCode == RESULT_OK){
if(mEditView == null){ /*因为挂机添加判断,原因不明*/
break;}
ViewHolder holder = (ViewHolder) mEditView.getTag();
Persisable e = EntityPool.instance().forId(holder.id, holder.tag);
mEditViewModel.entityToView(e, mEditView);
}else{}
break;
case OUT_PICTURE_EDIT:
if(resultCode == RESULT_OK){
if(mEditView == null){ /*因为挂机添加判断,原因不明*/
break;}
ViewHolder holder = (ViewHolder) mEditView.getTag();
Persisable e = EntityPool.instance().forId(holder.id, holder.tag);
mEditViewModel.entityToView(e, mEditView);
}else{
Toast toast = Toast.makeText(this,
getText(R.string.memory_low), Toast.LENGTH_SHORT);
toast.show();
}
break;
default:
break;
}
}
private class OnNoteClick implements OnClickListener{
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_EDIT);
intent.putExtra(NoteActivity.NOTE_EDIT_ID, holder.id);
startActivityForResult(intent, OUT_NOTE_EDIT);
}
}
private class OnRecordClick implements OnClickListener{
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
Record record= (Record) EntityPool.instance().forId(holder.id, holder.tag);
if(record.getTAG() == TextRecord.TAG){
Intent intent = new Intent(TaskViewActivity.this, NoteActivity.class);
intent.setAction(NoteActivity.NOTE_EDIT);
intent.putExtra(NoteActivity.NOTE_EDIT_ID, holder.id);
mEditViewModel = mHelper.mTextModel;
mEditView = v;
startActivityForResult(intent, OUT_NOTE_EDIT);
}else if(record.getTAG() == PictureRecord.TAG){
Intent intent = new Intent(TaskViewActivity.this,
WhiteboardActivity.class);
intent.setAction(WhiteboardActivity.WHITEBOARD_EDIT);
intent.putExtra(WhiteboardActivity.WHITEBOARD_URI, record.getContent());
intent.putExtra(WhiteboardActivity.RECORD_ID, holder.id);
mEditViewModel = mHelper.mRecordModel;
mEditView = v;
startActivityForResult(intent, OUT_PICTURE_EDIT);
}
}
}
private class GestureCallback implements DragScrollView.GestureCallback {
@Override
public void onLongPress(MotionEvent e) {
mTouchX = e.getX();
mTouchY = e.getY();
mMenu.setVisibility(View.VISIBLE);
LayoutParams lp = (LayoutParams) mDropIndicator.getLayoutParams();
lp.x = (int) mTouchX;
lp.y = (int) mTouchY;
mDragLayer.updateViewLayout(mDropIndicator, lp);
mDropIndicator.setVisibility(View.VISIBLE);
}
@Override
public void onSingleTapUp(MotionEvent e) {
View focus = TaskViewActivity.this.getCurrentFocus();
if(focus != null && focus != mDragLayer){
focus.clearFocus();
InputMethodManager inputManager = (InputMethodManager)
TaskViewActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
focus.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
if(mMenu.getVisibility() == View.VISIBLE){
mMenu.setVisibility(View.GONE);
mDropIndicator.setVisibility(View.GONE);
}else{
Toast.makeText(TaskViewActivity.this, getString(R.string.click_task_view_hint),
Toast.LENGTH_SHORT).show();
}
}
}
}
| 15,470 | 0.722143 | 0.721819 | 454 | 31.960352 | 22.813131 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.839207 | false | false | 9 |
0e28eba02b0a0f7ee396254169f97d198d3756db | 27,101,243,637,834 | 22ac03d62bf20b51bebf6d996650c3ae353b3a11 | /src/main/java/cassandra/metadata/MetadataService.java | 7520bc6b3dfe87468c3ba111aa5cd4965ab7708a | [
"Apache-2.0"
] | permissive | pakudayo/cassandra-connector-java | https://github.com/pakudayo/cassandra-connector-java | 9038b045e9fecb94e44175d5d742bcccb1156061 | a9a89489853d988295a1556d2833c95afc1640f6 | refs/heads/master | 2016-08-08T01:27:34.418000 | 2014-05-01T05:08:30 | 2014-05-01T05:08:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cassandra.metadata;
import cassandra.CassandraCluster;
import cassandra.cql.*;
import cassandra.routing.RoutingPolicy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
public class MetadataService extends Metadata implements CassandraCluster.EventListener {
private static final Logger logger = LoggerFactory.getLogger(MetadataService.class);
private static final ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
private final CassandraCluster cluster;
private RoutingPolicy routingPolicy;
public MetadataService(CassandraCluster cluster) {
this.cluster = cluster;
routingPolicy = new LocalRoutingPolicy();
}
@JsonIgnore
public boolean isInitialized() {
return super.getClusterName() != null;
}
public boolean initialize() {
if (!updateLocal()) {
return false;
}
updateKeyspaces();
updateTables();
updateColumns();
return true;
}
public List<InetAddress> selectPeers() {
List<InetAddress> peers = null;
for (Row row : executeLocal("SELECT peer FROM system.peers")) {
if (peers == null) {
peers = new ArrayList<InetAddress>();
}
peers.add(row.getInet("peer"));
}
if (peers == null) {
return Collections.emptyList();
}
return peers;
}
@Override
public void setLocal(InetAddress local) {
super.setLocal(local);
if (!isInitialized()) {
initialize();
}
}
@Override
public String getClusterName() {
String clusterName = super.getClusterName();
if (clusterName == null) {
clusterName = "unknown";
}
return clusterName;
}
@Override
public void onJoinCluster(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).updatePeer(endpoint);
if (!isInitialized() && cluster.seeds().contains(endpoint)) {
initialize();
}
}
@Override
public void onLeaveCluster(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).removePeer(endpoint);
}
@Override
public void onMove(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).updatePeers();
}
@Override
public void onUp(CassandraCluster cluster, InetAddress endpoint) {
if (validate(cluster).hasPeer(endpoint)) {
setPeerAsUp(endpoint);
} else {
updatePeer(endpoint);
}
}
@Override
public void onDown(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).setPeerAsDown(endpoint);
}
@Override
public void onCreateKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).updateKeyspace(keyspace);
}
@Override
public void onUpdateKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).updateKeyspace(keyspace);
}
@Override
public void onDropKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).removeKeyspace(keyspace);
}
@Override
public void onCreateTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).updateTable(keyspace, table);
updateColumns(keyspace, table);
}
@Override
public void onUpdateTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).updateTable(keyspace, table);
updateColumns(keyspace, table);
}
@Override
public void onDropTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).removeTable(keyspace, table);
}
public boolean updateLocal() {
ResultSet rs = executeLocal("SELECT cluster_name,data_center,host_id,partitioner,rack,release_version,schema_version,tokens FROM system.local WHERE key='local'");
if (!rs.hasNext()) {
return false;
}
Row row = rs.next();
setClusterName(row.getString("cluster_name"));
setPartitioner(row.getString("partitioner"));
PeerMetadata newPeer = PeerMetadata.newBuilder()
.setMetadata(this)
.setAddress(getLocal())
.setDatacenter(row.getString("data_center"))
.setRack(row.getString("rack"))
.setHostId(row.getUUID("host_id"))
.setSchemaVersion(row.getUUID("schema_version"))
.setReleaseVersion(row.getString("release_version"))
.setTokens(row.getSet("tokens", String.class))
.build();
addPeer(newPeer);
return true;
}
public void updatePeers() {
ResultSet rs = executeLocal("SELECT * FROM system.peers");
for (Row row : rs) {
boolean down = false;
PeerMetadata oldPeer = getPeer(row.getInet("peer"));
if (oldPeer != null) {
down = oldPeer.isDown();
}
addPeer(PeerMetadata.newBuilder().mergeFrom(this, row).setDown(down).build());
}
}
public boolean updatePeer(InetAddress endpoint) {
ResultSet rs = executeLocal("SELECT * FROM system.peers WHERE peer=?", endpoint);
if (!rs.hasNext()) {
return false;
}
addPeer(PeerMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateKeyspaces() {
for (Row row : executeLocal("SELECT * FROM system.schema_keyspaces")) {
addKeyspace(KeyspaceMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public boolean updateKeyspace(String keyspace) {
ResultSet rs = executeLocal("SELECT * FROM system.schema_keyspaces WHERE keyspace_name=?", keyspace);
if (!rs.hasNext()) {
return false;
}
addKeyspace(KeyspaceMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateTables() {
for (Row row : executeLocal("SELECT * FROM system.schema_columnfamilies")) {
addTable(TableMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public boolean updateTable(String keyspace, String table) {
ResultSet rs = executeLocal("SELECT * FROM system.schema_columnfamilies WHERE keyspace_name=? AND columnfamily_name=?", keyspace, table);
if (!rs.hasNext()) {
return false;
}
addTable(TableMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateColumns() {
for (Row row : executeLocal("SELECT * FROM system.schema_columns")) {
addColumn(ColumnMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public void updateColumns(String keyspace, String table) {
for (Row row : executeLocal("SELECT * FROM system.schema_columns WHERE keyspace_name=? AND columnfamily_name=?", keyspace, table)) {
addColumn(ColumnMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public void clear() {
super.clear();
}
private ResultSet executeLocal(String query) {
return cluster.session().statement(query).setConsistency(Consistency.ONE).setRoutingPolicy(routingPolicy).execute();
}
private ResultSet executeLocal(String query, Object... values) {
return cluster.session().statement(query, values).setConsistency(Consistency.ONE).setRoutingPolicy(routingPolicy).execute();
}
private MetadataService validate(CassandraCluster cluster) {
if (!this.cluster.equals(cluster)) {
throw new IllegalStateException();
}
return this;
}
static JsonNode valueToJsonNode(Object value) {
return mapper.valueToTree(value);
}
static String valueToJsonString(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
return null;
}
}
static <E> List<E> convertAsList(String json, Class<E> elementClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, elementClass));
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return Collections.emptyList();
}
}
static <K, V> Map<K, V> convertAsMap(String json, Class<K> keyClass, Class<V> valueClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, keyClass, valueClass));
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return Collections.emptyMap();
}
}
private class LocalRoutingPolicy implements RoutingPolicy {
@Override
public boolean isLocal(InetAddress endpoint) {
return true;
}
@Override
public Iterator<InetAddress> activeEndpoints(AbstractStatement<?> statement) {
InetAddress local = getLocal();
if (local == null) {
return cluster.options().getRoutingPolicy().activeEndpoints(statement);
}
return Collections.singletonList(local).iterator();
}
@Override
public void addEndpoint(InetAddress endpoint) {
throw new UnsupportedOperationException();
}
@Override
public void removeEndpoint(InetAddress endpoint) {
throw new UnsupportedOperationException();
}
}
}
| UTF-8 | Java | 10,110 | java | MetadataService.java | Java | [] | null | [] | package cassandra.metadata;
import cassandra.CassandraCluster;
import cassandra.cql.*;
import cassandra.routing.RoutingPolicy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
public class MetadataService extends Metadata implements CassandraCluster.EventListener {
private static final Logger logger = LoggerFactory.getLogger(MetadataService.class);
private static final ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
private final CassandraCluster cluster;
private RoutingPolicy routingPolicy;
public MetadataService(CassandraCluster cluster) {
this.cluster = cluster;
routingPolicy = new LocalRoutingPolicy();
}
@JsonIgnore
public boolean isInitialized() {
return super.getClusterName() != null;
}
public boolean initialize() {
if (!updateLocal()) {
return false;
}
updateKeyspaces();
updateTables();
updateColumns();
return true;
}
public List<InetAddress> selectPeers() {
List<InetAddress> peers = null;
for (Row row : executeLocal("SELECT peer FROM system.peers")) {
if (peers == null) {
peers = new ArrayList<InetAddress>();
}
peers.add(row.getInet("peer"));
}
if (peers == null) {
return Collections.emptyList();
}
return peers;
}
@Override
public void setLocal(InetAddress local) {
super.setLocal(local);
if (!isInitialized()) {
initialize();
}
}
@Override
public String getClusterName() {
String clusterName = super.getClusterName();
if (clusterName == null) {
clusterName = "unknown";
}
return clusterName;
}
@Override
public void onJoinCluster(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).updatePeer(endpoint);
if (!isInitialized() && cluster.seeds().contains(endpoint)) {
initialize();
}
}
@Override
public void onLeaveCluster(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).removePeer(endpoint);
}
@Override
public void onMove(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).updatePeers();
}
@Override
public void onUp(CassandraCluster cluster, InetAddress endpoint) {
if (validate(cluster).hasPeer(endpoint)) {
setPeerAsUp(endpoint);
} else {
updatePeer(endpoint);
}
}
@Override
public void onDown(CassandraCluster cluster, InetAddress endpoint) {
validate(cluster).setPeerAsDown(endpoint);
}
@Override
public void onCreateKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).updateKeyspace(keyspace);
}
@Override
public void onUpdateKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).updateKeyspace(keyspace);
}
@Override
public void onDropKeyspace(CassandraCluster cluster, String keyspace) {
validate(cluster).removeKeyspace(keyspace);
}
@Override
public void onCreateTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).updateTable(keyspace, table);
updateColumns(keyspace, table);
}
@Override
public void onUpdateTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).updateTable(keyspace, table);
updateColumns(keyspace, table);
}
@Override
public void onDropTable(CassandraCluster cluster, String keyspace, String table) {
validate(cluster).removeTable(keyspace, table);
}
public boolean updateLocal() {
ResultSet rs = executeLocal("SELECT cluster_name,data_center,host_id,partitioner,rack,release_version,schema_version,tokens FROM system.local WHERE key='local'");
if (!rs.hasNext()) {
return false;
}
Row row = rs.next();
setClusterName(row.getString("cluster_name"));
setPartitioner(row.getString("partitioner"));
PeerMetadata newPeer = PeerMetadata.newBuilder()
.setMetadata(this)
.setAddress(getLocal())
.setDatacenter(row.getString("data_center"))
.setRack(row.getString("rack"))
.setHostId(row.getUUID("host_id"))
.setSchemaVersion(row.getUUID("schema_version"))
.setReleaseVersion(row.getString("release_version"))
.setTokens(row.getSet("tokens", String.class))
.build();
addPeer(newPeer);
return true;
}
public void updatePeers() {
ResultSet rs = executeLocal("SELECT * FROM system.peers");
for (Row row : rs) {
boolean down = false;
PeerMetadata oldPeer = getPeer(row.getInet("peer"));
if (oldPeer != null) {
down = oldPeer.isDown();
}
addPeer(PeerMetadata.newBuilder().mergeFrom(this, row).setDown(down).build());
}
}
public boolean updatePeer(InetAddress endpoint) {
ResultSet rs = executeLocal("SELECT * FROM system.peers WHERE peer=?", endpoint);
if (!rs.hasNext()) {
return false;
}
addPeer(PeerMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateKeyspaces() {
for (Row row : executeLocal("SELECT * FROM system.schema_keyspaces")) {
addKeyspace(KeyspaceMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public boolean updateKeyspace(String keyspace) {
ResultSet rs = executeLocal("SELECT * FROM system.schema_keyspaces WHERE keyspace_name=?", keyspace);
if (!rs.hasNext()) {
return false;
}
addKeyspace(KeyspaceMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateTables() {
for (Row row : executeLocal("SELECT * FROM system.schema_columnfamilies")) {
addTable(TableMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public boolean updateTable(String keyspace, String table) {
ResultSet rs = executeLocal("SELECT * FROM system.schema_columnfamilies WHERE keyspace_name=? AND columnfamily_name=?", keyspace, table);
if (!rs.hasNext()) {
return false;
}
addTable(TableMetadata.newBuilder().mergeFrom(this, rs.next()).build());
return true;
}
public void updateColumns() {
for (Row row : executeLocal("SELECT * FROM system.schema_columns")) {
addColumn(ColumnMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public void updateColumns(String keyspace, String table) {
for (Row row : executeLocal("SELECT * FROM system.schema_columns WHERE keyspace_name=? AND columnfamily_name=?", keyspace, table)) {
addColumn(ColumnMetadata.newBuilder().mergeFrom(this, row).build());
}
}
public void clear() {
super.clear();
}
private ResultSet executeLocal(String query) {
return cluster.session().statement(query).setConsistency(Consistency.ONE).setRoutingPolicy(routingPolicy).execute();
}
private ResultSet executeLocal(String query, Object... values) {
return cluster.session().statement(query, values).setConsistency(Consistency.ONE).setRoutingPolicy(routingPolicy).execute();
}
private MetadataService validate(CassandraCluster cluster) {
if (!this.cluster.equals(cluster)) {
throw new IllegalStateException();
}
return this;
}
static JsonNode valueToJsonNode(Object value) {
return mapper.valueToTree(value);
}
static String valueToJsonString(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
return null;
}
}
static <E> List<E> convertAsList(String json, Class<E> elementClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, elementClass));
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return Collections.emptyList();
}
}
static <K, V> Map<K, V> convertAsMap(String json, Class<K> keyClass, Class<V> valueClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, keyClass, valueClass));
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return Collections.emptyMap();
}
}
private class LocalRoutingPolicy implements RoutingPolicy {
@Override
public boolean isLocal(InetAddress endpoint) {
return true;
}
@Override
public Iterator<InetAddress> activeEndpoints(AbstractStatement<?> statement) {
InetAddress local = getLocal();
if (local == null) {
return cluster.options().getRoutingPolicy().activeEndpoints(statement);
}
return Collections.singletonList(local).iterator();
}
@Override
public void addEndpoint(InetAddress endpoint) {
throw new UnsupportedOperationException();
}
@Override
public void removeEndpoint(InetAddress endpoint) {
throw new UnsupportedOperationException();
}
}
}
| 10,110 | 0.63274 | 0.632542 | 308 | 31.824675 | 30.815567 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516234 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.