text
stringlengths
10
2.72M
package com.g7s.ics.testcase.ReportDayFinance; import com.g7s.ics.api.ReportDayFinanceApi; import io.qameta.allure.Description; import io.qameta.allure.Epic; import io.qameta.allure.Feature; import io.restassured.response.Response; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.ResourceBundle; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @Author: zhangwenping * @Description: 获取财务日报信息 * @Date: Create in 11:51 2020-08-04 */ @Epic("财务日报-测试用例") @Feature("日报查询") public class ReportDayFinanceTest { ResourceBundle bundle =ResourceBundle.getBundle("Interface/ListInterface"); String FinanceDayReportPath = bundle.getString("FinanceDayReportPath"); @Test @Description("调用接口:/inward/v1/report/day/finance,查询固定值,2020-08-01 的财务日报") @DisplayName("查询固定值,2020-08-01 的财务日报,验证接口返回数据正常") public void getFinanceDayReport(){ HashMap<String,Object> Date = new HashMap<String, Object>(); Date.put("id",0); Date.put("pageSize",100); //0 全部,1 正常 2 灰 3 黑 Date.put("reportDate","2020-08-01"); Response response = ReportDayFinanceApi.getDayReport(Date,FinanceDayReportPath); assertAll( //()->assertEquals(pageDate.get("type"),response.path("data.records.type[0]")), ()->assertEquals("0",response.path("code").toString()), ()->assertEquals("成功",response.path("sub_msg")) );} }
package lab5_jorgevega; /** Jorge Vega */ public class Clase_Estudiante { private String GENE; private String APELLI; private String NAME; private String CARRE; private int EDAD; private int COUNT; public Clase_Estudiante() { } public Clase_Estudiante(String NOMBRE, String APELLIDO, int NUM_CUENTA, String SEXO, int EDAD, String COURS) { this.NAME = NOMBRE; this.APELLI = APELLIDO; this.COUNT = NUM_CUENTA; this.GENE = SEXO; this.EDAD = EDAD; this.CARRE = COURS; } public String getNAME() { return NAME; } public void setNAME(String NAME) { this.NAME = NAME; } public String getAPELLI() { return APELLI; } public void setAPELLI(String APELLI) { this.APELLI = APELLI; } public int getCOUNT() { return COUNT; } public void setCOUNT(int COUNT) { this.COUNT = COUNT; } public String getGENE() { return GENE; } public void setGENE(String GENE) { this.GENE = GENE; } public int getEDAD() { return EDAD; } public void setEDAD(int EDAD) { this.EDAD = EDAD; } public String getCARRE() { return CARRE; } public void setCARRE(String CARRE) { this.CARRE = CARRE; } @Override public String toString() { return "NOMBRE:" + NAME + " APELLIDO: " + APELLI + ", GENERO: " + GENE + ", EDAD: " + EDAD + ", CARRERA: " + CARRE; } }
package com.rhysnguyen.casestudyjavaweb.service; import com.rhysnguyen.casestudyjavaweb.entity.Employee; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface EmployeeService { Page<Employee> findAll(Pageable pageable); Employee findById(Long id); void save(Employee employee); void delete(Long id); }
package com.yinghai.a24divine_user.module.divine.book.pay; import com.yinghai.a24divine_user.base.MyBasePresenter; import com.yinghai.a24divine_user.bean.AliPayBean; import com.yinghai.a24divine_user.bean.WechatPayBean; /** * @author Created by:fanson * Created Time: 2017/11/16 17:09 * Describe: */ public class PayPresenter extends MyBasePresenter<WeChatPayModel,ContractPay.IPayView> implements ContractPay.IPayPresenter, ContractPay.IPayModel.IPayCallback, ContractPay.IPayModel.IAliPayCallback { @Override protected WeChatPayModel createModel() { return new WeChatPayModel(); } public PayPresenter(ContractPay.IPayView view){ attachView(view); } @Override public void wechatCreateOrder(String orderNo, int orderType, String spbillCreateIp) { mBaseModel.wechatPay(orderNo,orderType,spbillCreateIp,this); } @Override public void aliPay(String orderNo, int orderType) { mBaseModel.aliPay(orderNo,orderType,this); } @Override public void handlerResultCode(int code) { handleResultCode(code); } @Override public void paySuccess(WechatPayBean bean) { if (isViewAttached()){ getBaseView().wechatCreateSuccess(bean); } } @Override public void payFailure(String errorMsg) { if (isViewAttached()){ getBaseView().wechatCreateFailure(errorMsg); } } @Override public void onPaySuccess(AliPayBean bean) { if (isViewAttached()){ getBaseView().showAliPaySuccess(bean); } } @Override public void onPayFailure(String errorMsg) { if (isViewAttached()){ getBaseView().wechatCreateFailure(errorMsg); } } }
package me.themgrf.skooblock.utils; import org.bukkit.ChatColor; import org.bukkit.inventory.ItemStack; import java.util.List; /** * A simple string modification class to colour or reformat text */ public class Text { /** * Format a string to contain Bukkit colour codes * * @param msg The message to format * @return The formatted colour coded string */ public static String colour(String msg) { return ChatColor.translateAlternateColorCodes('&', msg); } /** * Format an array to contain Bukkit colour codes * * @param lore The array to format * @return The formatted colour coded array */ public static List<String> colourArray(List<String> lore) { for (int x = 0; x < lore.size(); x++) { lore.set(x, colour(lore.get(x))); } return lore; } /** * Shortened method for grabbing an items name from Paper's API if you dont know what i18n is. * @param itemStack The item to get the name of * @return The name of the specified item */ public static String getItemName(ItemStack itemStack) { return itemStack.getI18NDisplayName(); } /** * Convert a bukkit string value to a readable string * * @param old The old string value to convert * @return The readable string value */ public static String convertUnformattedString(String old) { String convert = old.toLowerCase().replaceAll("_", " "); StringBuilder newValue = new StringBuilder(); boolean space = true; for (int i = 0; i < convert.length(); i++) { if (space) { newValue.append(Character.toUpperCase(convert.charAt(i))); } else { newValue.append(convert.charAt(i)); } space = convert.charAt(i) == ' '; } return newValue.toString(); } }
package math; public class Matrix { public static int[][] plus(int[][] a, int[][] b) { int rows = a.length; int cols = a[0].length; int[][] c = new int[rows][]; for (int i = 0; i < rows; i++) c[i] = new int[cols]; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { c[row][col] = a[row][col] + b[row][col]; } } return c; } }
package com.lbins.FruitsBusiness.data; /** * Created by Administrator on 2015/8/12. * "id": "9", "url": "http://www.baidu.com/", "dateline": "1446422704", "imgurl": "/Uploads/2015-11-02/5636a8b031af8.png" */ public class AdSlide { private String id; private String url; private String dateline; private String imgurl; public AdSlide(String id, String url, String dateline, String imgurl) { this.id = id; this.url = url; this.dateline = dateline; this.imgurl = imgurl; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDateline() { return dateline; } public void setDateline(String dateline) { this.dateline = dateline; } public String getImgurl() { return imgurl; } public void setImgurl(String imgurl) { this.imgurl = imgurl; } }
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class WordCount { public static void main(String[] args){ ArrayList<String> list = new ArrayList<String>(); ArrayList<String> listScanner = new ArrayList<String>(); try( BufferedReader in = new BufferedReader( new FileReader("input.txt")); PrintWriter out = new PrintWriter( new FileWriter("output.txt")); Scanner scan = new Scanner(System.in) ){ String l; while( (l = in.readLine() ) != null ){ list.add(l); } listScanner = scan.stream().map(s -> s.split("\\s+")).collect(Collectors.toList()); // while( (scan.hasNext()) ){ // l = scan.next("\\s+"); // listScanner.add(l); // } }catch(FileNotFoundException e){ System.out.println(e); }catch(IOException e){ System.out.println(e); }catch(IllegalArgumentException e){ System.out.println(e); }catch(InputMismatchException e){ System.out.println(e); } System.out.println("Word Count in Buffered Reader: " + list.size()); System.out.println("Word Count in Scanner Input: " + listScanner.size()); } }
package com.smxknife.annotation.processor; import javax.annotation.processing.Filer; import javax.lang.model.util.Elements; /** * @author smxknife * 2019-03-28 */ public interface DataPointGenerator { void generate(Elements elements, Filer filer); }
/* * 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.test.BikeRentalApp.exceptions; /** * * @author Keagan Nigel Gonsalves <kg19aaj@herts.ac.uk> */ public class ApplicationException extends RuntimeException{ public ApplicationException(String message){ super(message); } }
package org.codeshifts.spring.core.contextconfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertNotNull; /** * Just check that xml configuration itself behaves as expected */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/spring/core/contextconfiguration/beanC.xml") public class ContextXmlTest { private static final Logger LOG = LoggerFactory.getLogger(ContextMixedConfigurationTest.class); @Autowired private TestBeanC beanC; @Test public void verifyBeans() { LOG.info("Checks if beanC is autowired from xml configuration!"); assertNotNull(beanC); } }
package com.android.testapplication.dataModels; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * TestApplication * Created by Alex on 18.05.2017. * contact on luck.alex13@gmail.com * © Alexander Novikov 2017 */ public class TempGallery extends RealmObject { @SerializedName("format") @Expose private String format; @SerializedName("width") @Expose private int width; @SerializedName("height") @Expose private int height; @SerializedName("filename") @Expose private String filename; @PrimaryKey @SerializedName("id") @Expose private int id; @SerializedName("author") @Expose private String author; @SerializedName("author_url") @Expose private String authorUrl; @SerializedName("post_url") @Expose private String postUrl; /** * No args constructor for use in serialization * */ public TempGallery() { } /** * * @param id * @param author * @param height * @param postUrl * @param width * @param authorUrl * @param filename * @param format */ public TempGallery(int id, String filename, String format, int width, int height, String author, String authorUrl, String postUrl) { super(); this.format = format; this.width = width; this.height = height; this.filename = filename; this.id = id; this.author = author; this.authorUrl = authorUrl; this.postUrl = postUrl; } public static TempGallery copyFrom(GalleryModel galleryModel){ return new TempGallery(galleryModel.getId(),galleryModel.getFilename(),galleryModel.getFormat(),galleryModel.getWidth(),galleryModel.getHeight(),galleryModel.getAuthor(),galleryModel.getAuthorUrl(),galleryModel.getPostUrl()); } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getAuthorUrl() { return authorUrl; } public void setAuthorUrl(String authorUrl) { this.authorUrl = authorUrl; } public String getPostUrl() { return postUrl; } public void setPostUrl(String postUrl) { this.postUrl = postUrl; } }
package characters; /** * Created by Stark on 2017/12/14. * 新的整数字面表达式 * -"0b" 二进制前缀 * -"_" 连接符 */ public class Character_3 { public static void main(String[] args) { //下面的值相同 byte b1 = 0b00100001; //二进制表示 byte b2 = 040;//八进制表示 byte b3 = 0x21;//16进制 byte b4 = 32; //十进制 /** * 用下划线链接整数提高其可读性 * 约束: * 不能在数的开头和结尾 * 不能在浮点型数组的小数点左右 * 不能在F或L下标的前面 * 字符串数字不行 */ //float f1 = 3._14f; float f2 = 3.1_4f; long l = 11_11_11_11_11_11L; //int a1 =_52; //int a2 =52_; int a3 = 5__________2; int a4 = 0________40; } }
package com.bastiaanjansen.jwt; import com.bastiaanjansen.jwt.algorithms.Algorithm; import com.bastiaanjansen.jwt.exceptions.JWTCreationException; import com.bastiaanjansen.jwt.exceptions.JWTDecodeException; import com.bastiaanjansen.jwt.exceptions.JWTExpiredException; import com.bastiaanjansen.jwt.exceptions.JWTValidationException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Date; import static org.junit.jupiter.api.Assertions.*; class DefaultJWTValidatorTest { private Algorithm algorithm; @BeforeEach void setUp() { this.algorithm = Algorithm.HMAC384("secret"); } @AfterEach void tearDown() { this.algorithm = null; } @Test void validate_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).build(); JWTValidator validator = new DefaultJWTValidator(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidSignature_throwsJWTValidationException() throws JWTCreationException, JWTDecodeException { String jwtString = "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJhdWQiOiJhdWRpZW5jZSIsImlhdCI6MTYxNDY3NjkyNjE3MiwianRpIjoiaWQifQ.ibsMduBXhE8Y1TkDAazH-J7BaAtcJTcwmHfzvQg9EWS6uKZFsA_7z4LYtSa-nnR"; JWT jwt = JWT.fromRawJWT(algorithm, jwtString); JWTValidator validator = new DefaultJWTValidator(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithExpirationTimeInPast_throwsJWTExpiredException() throws JWTCreationException { Date past = new Date(100); JWT jwt = new JWT.Builder(algorithm).withExpirationTime(past).build(); JWTValidator validator = new DefaultJWTValidator(); assertThrows(JWTExpiredException.class, () -> validator.validate(jwt)); } @Test void validateWithExpirationTimeInFuture_doesNotThrow() throws JWTCreationException { Date future = Date.from(Instant.now().plusSeconds(1000)); JWT jwt = new JWT.Builder(algorithm).withExpirationTime(future).build(); JWTValidator validator = new DefaultJWTValidator(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithValidType_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withType("JWT").build(); JWTValidator validator = new DefaultJWTValidator(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidType_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withType("type").build(); JWTValidator validator = new DefaultJWTValidator(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithInvalidContentType_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withContentType("invalid").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withContentType("content-type").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidContentType_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withContentType("content-type").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withContentType("content-type").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidAlgorithm_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withAlgorithm("invalid").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidAlgorithm_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withAlgorithm("HS384").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidIssuer_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withIssuer("issuer").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withIssuer("invalid").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidIssuer_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withIssuer("issuer").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withIssuer("issuer").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidSubject_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withSubject("subject").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withSubject("invalid").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidSubject_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withSubject("issuer").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withSubject("issuer").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidAudience_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withAudience("aud1", "aud2").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withOneOfAudience("invalid").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidAudience_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withAudience("aud1", "aud2").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withOneOfAudience("aud1").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithValidAllAudience_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withAudience("aud1", "aud2", "aud3").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withAllOfAudience("aud1", "aud2").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithValidAllAudience_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withAudience("aud1", "aud3").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withAllOfAudience("aud1", "aud2").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithInvalidExpirationDate_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withExpirationTime(100).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withExpirationTime(200).build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidExpirationDate_doesNotThrow() throws JWTCreationException { Date date = Date.from(Instant.now().plusSeconds(100)); JWT jwt = new JWT.Builder(algorithm).withExpirationTime(date).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withExpirationTime(date).build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidNotBefore_throwsJWTValidationException() throws JWTCreationException { Date date = Date.from(Instant.now().plusSeconds(100)); JWT jwt = new JWT.Builder(algorithm).withNotBefore(date).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withNotBefore(100).build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidNotBefore_doesNotThrow() throws JWTCreationException { Date date = Date.from(Instant.now().minusSeconds(100)); JWT jwt = new JWT.Builder(algorithm).withNotBefore(date).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withNotBefore(date).build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidIssuedAt_throwsJWTValidationException() throws JWTCreationException { Date date = new Date(100); JWT jwt = new JWT.Builder(algorithm).withIssuedAt(date).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withIssuedAt(200).build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidIssuedAt_doesNotThrow() throws JWTCreationException { Date date = new Date(100); JWT jwt = new JWT.Builder(algorithm).withNotBefore(date).build(); JWTValidator validator = new DefaultJWTValidator.Builder().withNotBefore(date).build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithInvalidID_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withID("id").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withID("invalid").build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithValidID_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withID("id").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withID("id").build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithHeader_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withHeader("test", "value").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withHeader("test", "value"::equals).build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithHeader_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withHeader("test", "value").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withHeader("test", "invalid"::equals).build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithClaim_doesNotThrow() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withClaim("test", "value").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withClaim("test", "value"::equals).build(); assertDoesNotThrow(() -> validator.validate(jwt)); } @Test void validateWithClaim_throwsJWTValidationException() throws JWTCreationException { JWT jwt = new JWT.Builder(algorithm).withClaim("test", "value").build(); JWTValidator validator = new DefaultJWTValidator.Builder().withClaim("test", "invalid"::equals).build(); assertThrows(JWTValidationException.class, () -> validator.validate(jwt)); } @Test void validateWithHeaderNameIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withHeader(null, "value").build()); } @Test void validateWithHeaderValueIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withHeader("name", null).build()); } @Test void validateWithCustomHeaderNameIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withHeader(null, value -> false).build()); } @Test void validateWithCustomHeaderValidatorIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withHeader("name", null).build()); } @Test void validateWithClaimNameIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withClaim(null, "value").build()); } @Test void validateWithClaimValueIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withClaim("name", null).build()); } @Test void validateWithCustomClaimNameIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withClaim(null, value -> false).build()); } @Test void validateWithCustomClaimValidatorIsNull_throwsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> new DefaultJWTValidator.Builder().withClaim("name", null).build()); } }
package nelsys.modelo; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Funcionario { @Id private String idpessoafuncionario; public void setIdpessoafuncionario(String idpessoafuncionario) { this.idpessoafuncionario = idpessoafuncionario; } public String getIdpessoafuncionario() { return idpessoafuncionario; } }
/* * YNAB API Endpoints * Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ynab.client.api; import ynab.client.invoker.ApiCallback; import ynab.client.invoker.ApiClient; import ynab.client.invoker.ApiException; import ynab.client.invoker.ApiResponse; import ynab.client.invoker.Configuration; import ynab.client.invoker.Pair; import ynab.client.invoker.ProgressRequestBody; import ynab.client.invoker.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ynab.client.model.ErrorResponse; import org.threeten.bp.LocalDate; import ynab.client.model.MonthDetailResponse; import ynab.client.model.MonthSummariesResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MonthsApi { private ApiClient apiClient; public MonthsApi() { this(Configuration.getDefaultApiClient()); } public MonthsApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for getBudgetMonth * @param budgetId The ID of the Budget. (required) * @param month The Budget Month. \&quot;current\&quot; can also be used to specify the current calendar month (UTC). (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call getBudgetMonthCall(String budgetId, LocalDate month, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/budgets/{budget_id}/months/{month}" .replaceAll("\\{" + "budget_id" + "\\}", apiClient.escapeString(budgetId)) .replaceAll("\\{" + "month" + "\\}", apiClient.escapeString(month.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "bearer" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getBudgetMonthValidateBeforeCall(String budgetId, LocalDate month, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'budgetId' is set if (budgetId == null) { throw new ApiException("Missing the required parameter 'budgetId' when calling getBudgetMonth(Async)"); } // verify the required parameter 'month' is set if (month == null) { throw new ApiException("Missing the required parameter 'month' when calling getBudgetMonth(Async)"); } com.squareup.okhttp.Call call = getBudgetMonthCall(budgetId, month, progressListener, progressRequestListener); return call; } /** * Single budget month * Returns a single budget month * @param budgetId The ID of the Budget. (required) * @param month The Budget Month. \&quot;current\&quot; can also be used to specify the current calendar month (UTC). (required) * @return MonthDetailResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public MonthDetailResponse getBudgetMonth(String budgetId, LocalDate month) throws ApiException { ApiResponse<MonthDetailResponse> resp = getBudgetMonthWithHttpInfo(budgetId, month); return resp.getData(); } /** * Single budget month * Returns a single budget month * @param budgetId The ID of the Budget. (required) * @param month The Budget Month. \&quot;current\&quot; can also be used to specify the current calendar month (UTC). (required) * @return ApiResponse&lt;MonthDetailResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<MonthDetailResponse> getBudgetMonthWithHttpInfo(String budgetId, LocalDate month) throws ApiException { com.squareup.okhttp.Call call = getBudgetMonthValidateBeforeCall(budgetId, month, null, null); Type localVarReturnType = new TypeToken<MonthDetailResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Single budget month (asynchronously) * Returns a single budget month * @param budgetId The ID of the Budget. (required) * @param month The Budget Month. \&quot;current\&quot; can also be used to specify the current calendar month (UTC). (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getBudgetMonthAsync(String budgetId, LocalDate month, final ApiCallback<MonthDetailResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getBudgetMonthValidateBeforeCall(budgetId, month, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<MonthDetailResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for getBudgetMonths * @param budgetId The ID of the Budget. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call getBudgetMonthsCall(String budgetId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/budgets/{budget_id}/months" .replaceAll("\\{" + "budget_id" + "\\}", apiClient.escapeString(budgetId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "bearer" }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call getBudgetMonthsValidateBeforeCall(String budgetId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'budgetId' is set if (budgetId == null) { throw new ApiException("Missing the required parameter 'budgetId' when calling getBudgetMonths(Async)"); } com.squareup.okhttp.Call call = getBudgetMonthsCall(budgetId, progressListener, progressRequestListener); return call; } /** * List budget months * Returns all budget months * @param budgetId The ID of the Budget. (required) * @return MonthSummariesResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public MonthSummariesResponse getBudgetMonths(String budgetId) throws ApiException { ApiResponse<MonthSummariesResponse> resp = getBudgetMonthsWithHttpInfo(budgetId); return resp.getData(); } /** * List budget months * Returns all budget months * @param budgetId The ID of the Budget. (required) * @return ApiResponse&lt;MonthSummariesResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<MonthSummariesResponse> getBudgetMonthsWithHttpInfo(String budgetId) throws ApiException { com.squareup.okhttp.Call call = getBudgetMonthsValidateBeforeCall(budgetId, null, null); Type localVarReturnType = new TypeToken<MonthSummariesResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * List budget months (asynchronously) * Returns all budget months * @param budgetId The ID of the Budget. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getBudgetMonthsAsync(String budgetId, final ApiCallback<MonthSummariesResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getBudgetMonthsValidateBeforeCall(budgetId, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<MonthSummariesResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
package synchronized_test; public class Synchronized { //1,同步方法 2,加入static关键字 public void method1(){ System.out.println("method1 start!"); try { synchronized(this){ System.out.println("method1 excute"); Thread.sleep(3000);} } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("method1 end!"); } //1,同步方法 2,加入static关键字 3,同步代码块 public void method2(){ System.out.println("method2 start!"); try { synchronized(this){ System.out.println("method2 excute"); Thread.sleep(1000);} } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("method2 end"); } public static void main(String[] args) { Synchronized sync = new Synchronized(); //Synchronized sync1 = new Synchronized(); new Thread(new Runnable(){ @Override public void run(){ sync.method1(); } }).start(); new Thread(new Runnable(){ @Override public void run() { sync.method2(); } }).start(); } }
package com.tencent.mm.plugin.remittance.model; import android.net.wifi.WifiInfo; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.g.a.fo; import com.tencent.mm.kernel.g; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.plugin.soter.c.c; import com.tencent.mm.plugin.wallet_core.model.o; import com.tencent.mm.protocal.c.jh; import com.tencent.mm.protocal.c.ji; import com.tencent.mm.protocal.c.xb; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.c.d; import java.net.URLDecoder; public final class i extends l implements k, d { private e diJ; public b eAN; public ji mxj; public String mxk; public fo mxl = null; public i(String str, String str2, int i, String str3, String str4, int i2, int i3, String str5, String str6, int i4, int i5, String str7, xb xbVar, String str8, int i6, String str9, String str10, String str11, String str12) { a aVar = new a(); aVar.dIG = new jh(); aVar.dIH = new ji(); aVar.dIF = 1633; aVar.uri = "/cgi-bin/mmpay-bin/busif2fplaceorder"; aVar.dII = 0; aVar.dIJ = 0; c bFh = com.tencent.mm.plugin.soter.c.b.bFh(); String str13 = bFh.onE; String str14 = bFh.onF; this.mxk = str9; this.eAN = aVar.KT(); jh jhVar = (jh) this.eAN.dID.dIL; jhVar.myl = str; jhVar.rkC = URLDecoder.decode(str2); jhVar.scene = i; jhVar.rkD = str3; jhVar.myf = str4; jhVar.rcI = i2; jhVar.bVU = i3; jhVar.myg = str5; jhVar.mym = str6; jhVar.myk = i4; jhVar.rcH = str7; if (xbVar != null) { jhVar.rcG = xbVar; } jhVar.rkw = str8; jhVar.mwQ = i6; if (i5 == 1) { WifiInfo wifiInfo = ao.getWifiInfo(ad.getContext()); if (wifiInfo != null) { jhVar.rkE = wifiInfo.getBSSID(); } else { x.w("MicroMsg.NetSceneBusiF2fPlaceOrder", "wifi info is null"); } jhVar.rkF = 0; } jhVar.onE = str13; jhVar.onF = str14; jhVar.rkH = o.bOW().bPu(); g.l(com.tencent.mm.pluginsdk.k.class); jhVar.rkG = false; jhVar.rkI = str9; jhVar.myi = str10; jhVar.nickname = str11; jhVar.mxM = str12; x.i("MicroMsg.NetSceneBusiF2fPlaceOrder", "dycodeurl: %s", new Object[]{str9}); x.i("MicroMsg.NetSceneBusiF2fPlaceOrder", "NetSceneBusiF2fPlaceOrder, scene: %s, channel: %s, total: %s, qrcode: %s, getPayWifi: %s favor_compose_info %s dynamicCodeUrl %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i3), Integer.valueOf(i2), str2, Integer.valueOf(i5), a.a(xbVar), str9}); } public final int getType() { return 1633; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.eAN, this); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.i("MicroMsg.NetSceneBusiF2fPlaceOrder", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str}); this.mxj = (ji) ((b) qVar).dIE.dIL; StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(String.format("trans_id: %s,", new Object[]{this.mxj.rcE})); stringBuffer.append(String.format("zero_pay_flag: %s,", new Object[]{Integer.valueOf(this.mxj.rkP)})); stringBuffer.append(String.format("can_use_fingerprint: %s,", new Object[]{Integer.valueOf(this.mxj.rkV)})); stringBuffer.append(String.format("payer_need_auth_flag: %s,", new Object[]{Integer.valueOf(this.mxj.rkQ)})); x.i("MicroMsg.NetSceneBusiF2fPlaceOrder", "ret_code: %s, ret_msg: %s trans_id: %s f2f_id: %s re_getfavor: %s payok_checksign: %s reqKey %s ret:%s", new Object[]{Integer.valueOf(this.mxj.hwV), this.mxj.hwW, this.mxj.rcE, this.mxj.rcD, Integer.valueOf(this.mxj.rkO), this.mxj.rcF, this.mxj.bQa, stringBuffer.toString()}); if (this.diJ != null) { this.diJ.a(i2, i3, str, this); } } }
package jetris.model; import org.apache.commons.lang3.RandomUtils; import jetris.model.Tetromino.Shape; class RandomTetrominoFactory implements TetrominoFactory { @Override public Tetromino create() { Shape shape = Shape.values()[RandomUtils.nextInt(0, Shape.values().length)]; return new Tetromino(shape); } }
package tests_dominio; import dominio.Asesino; import dominio.Elfo; import dominio.Guerrero; import dominio.Humano; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; public class TestGuerrero { @Test public void testDobleGolpe() { HashMap <String,Integer> mapa = new HashMap<String,Integer>(); Humano h = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); Elfo e = new Elfo("Nico", 100, 100, 25, 20, 30, new Asesino(0.2, 0.3, 1.5), 0, 3, 1); Assert.assertEquals(e.getSalud() , 100); if (h.habilidadCasta1(e)) { Assert.assertTrue(e.getSalud() < 100); } Humano h2 = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); Elfo e2 = new Elfo("Nico", 100, 100, 25, 20, 30, new Asesino(0.2, 0.3, 1.5), 0, 3, 1); mapa.put("energia", 5); h2.actualizar(mapa); if (!h2.habilidadCasta1(e2)) { Assert.assertEquals(e2.getSalud() , 100); } } @Test public void testAutoDefensa() { HashMap <String,Integer> mapa = new HashMap<String,Integer>(); Humano h = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); Assert.assertEquals(h.getDefensa() , 20); h.habilidadCasta2(null); Assert.assertEquals(h.getDefensa() , 65); Humano h2 = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); mapa.put("energia", 1); h2.actualizar(mapa); h2.habilidadCasta2(null); Assert.assertNotEquals(h2.getDefensa() , 65); } @Test public void testIgnoraDefensa() { HashMap <String,Integer> mapa = new HashMap<String,Integer>(); Humano h = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); Elfo e = new Elfo("Nico", 100, 100, 25, 20, 30, new Asesino(0.2, 0.3, 1.5), 0, 3, 1); Assert.assertTrue(e.getSalud() == 100); if (h.habilidadCasta3(e)) { Assert.assertTrue(e.getSalud() < 100); }else Assert.assertTrue(e.getSalud() == 100); Humano h2 = new Humano("Nico", 100, 100, 25, 20, 30, new Guerrero(0.2, 0.3, 1.5), 0, 1, 1); Elfo e2 = new Elfo("Nico", 100, 100, 25, 20, 30, new Asesino(0.2, 0.3, 1.5), 0, 3, 1); mapa.put("energia", 5); h2.actualizar(mapa); if (!h2.habilidadCasta3(e2)) { Assert.assertTrue(e2.getSalud() == 100); } } }
package PhotosView; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import app.Persistance; import app.Photo; import app.User; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * UI controller which manages the slideshow function of our photos app. * @author Eshan Wadhwa and Vishal Patel. * */ public class SlideshowController implements Initializable { /** * ImageView to display the image */ @FXML private ImageView images; /** * Button to exit the program */ @FXML private Button exit; /** * Button to view the previous image */ @FXML private Button previous; /** * Button to view the next image */ @FXML private Button next; /** * Array of the photos to be displayed in the slideshow */ private static Photo[] slideshow; /** * Integer that gets the index of the photo to display */ private static int currentPhoto = 0; /** * Method to exit the program. * @param event Event triggered by user pressing exit button. */ @FXML void exitButton(ActionEvent event) { try { Stage stage = new Stage(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/PhotosView/PhotoAlbum.fxml")); AnchorPane rootLayout = (AnchorPane) loader.load(); Scene scene = new Scene(rootLayout); stage.setScene(scene); ((Node)event.getSource()).getScene().getWindow().hide(); stage.show(); } catch (IOException m) { m.printStackTrace(); } } /** * Method to display the next photo. * @param event Event triggered by user pressing next button. */ @FXML void nextButton(ActionEvent event) { Photo photo; if (currentPhoto == slideshow.length - 1) { currentPhoto = 0; } else { currentPhoto ++; } photo = slideshow[currentPhoto]; Image display = new Image(photo.getLocation()); images.setImage(display); } /** * Method to display the previous photo. * @param event Event triggered by user pressing previous button. */ @FXML void previousButton(ActionEvent event) { Photo photo; if (currentPhoto <= 0) { currentPhoto = slideshow.length - 1; } else { currentPhoto --; } photo = slideshow[currentPhoto]; Image display = new Image(photo.getLocation()); images.setImage(display); } /** * Method that is automatically called when the user gets to this stage. */ @Override public void initialize(URL arg0, ResourceBundle arg1) { Photo photo; currentPhoto = 0; User currentUser = Persistance.getUser(LoginController.getUserIndex()); Iterator<Photo> photoIter = currentUser.getAlbum(UserController.getOpenAlbumIndex()).photoIterator(); List<Photo> photoList = new ArrayList<>(); while(photoIter.hasNext()) { photoList.add(photoIter.next()); } slideshow = photoList.toArray(new Photo[0]); photo = slideshow[currentPhoto]; Image display = new Image(photo.getLocation()); images.setImage(display); } }
package com.hladkevych.menu.utils.mlp; import java.io.IOException; import org.apache.log4j.Logger; import org.datavec.api.records.reader.RecordReader; import org.datavec.api.records.reader.impl.csv.CSVRecordReader; import org.datavec.api.split.FileSplit; import org.datavec.api.util.ClassPathResource; import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; import org.nd4j.linalg.activations.Activation; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.SplitTestAndTrain; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.lossfunctions.LossFunctions; /** * Created by ggladko97 on 23.01.18. */ public class MlpConfiguration { private static final Logger logger = Logger.getLogger(MlpConfiguration.class); private DataSet allData; private DataSet trainData; private DataSet testData; private int numInputs = 51; private int outputNum = 13; private int iterations = 1000; private int seed = 8; public MlpConfiguration(int numInputs, int outputNum, int iterations, int seed) { this.numInputs = numInputs; this.outputNum = outputNum; this.iterations = iterations; this.seed = seed; try { allData = readDataFromCsv("prod_beta_numeric.csv"); allData.shuffle(); SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.85); trainData = testAndTrain.getTrain(); testData = testAndTrain.getTest(); logger.info("Train: " + trainData); logger.info("Test: " + testData); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } private MultiLayerConfiguration createNetwork() { MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .seed(seed) .iterations(iterations) .activation(Activation.TANH) .weightInit(WeightInit.XAVIER) .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .learningRate(0.1) .regularization(true).l2(1e-4) .list() .layer(0, new DenseLayer.Builder().nIn(numInputs).nOut(outputNum).build()) .layer(1, new DenseLayer.Builder().nIn(outputNum).nOut(outputNum).build()) .layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .activation(Activation.SOFTMAX) .nIn(outputNum).nOut(outputNum) .build()).backprop(true) .pretrain(false) .build(); return conf; } private MultiLayerNetwork trainNetwork() { MultiLayerNetwork model = new MultiLayerNetwork(createNetwork()); model.init(); model.fit(trainData); return model; } public INDArray validateNetwork() { MultiLayerNetwork multiLayerNetwork = trainNetwork(); return multiLayerNetwork.output(testData.getFeatureMatrix()); } public INDArray classifyRow(DataSet row) { MultiLayerNetwork multiLayerNetwork = trainNetwork(); return multiLayerNetwork.output(row.getFeatureMatrix()); } public DataSet readDataFromCsv(String path) throws IOException, InterruptedException { RecordReader recordReader = new CSVRecordReader(0, ','); DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 70, 0, 13); recordReader.initialize(new FileSplit(new ClassPathResource(path).getFile())); return iterator.next(); } }
package com.example.michael.e_; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; /* 有别于后台服务 不会被回收 优先级高 */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 打印主线程的id Log.d("MainActivity", "Thread id is " + Thread.currentThread(). getId()); Intent intentService = new Intent(MainActivity.this, MyService.class); startService(intentService); } }); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GLUEHENPlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGN3; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class ProgrammzeileType_BEHGN3_Builder { public static String marshal(BEHGN3 bEHGN3) throws JAXBException { JAXBElement<BEHGN3> jaxbElement = new JAXBElement<>(new QName("TESTING"), BEHGN3.class , bEHGN3); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private GLUEHENPlanungType gLUEHEN; public ProgrammzeileType_BEHGN3_Builder setGLUEHEN(GLUEHENPlanungType value) { this.gLUEHEN = value; return this; } public BEHGN3 build() { BEHGN3 result = new BEHGN3(); result.setGLUEHEN(gLUEHEN); return result; } }
/** * KITE */ package com.kite.modules.att.dao; import javax.websocket.server.PathParam; import org.apache.ibatis.annotations.Param; import com.kite.common.persistence.CrudDao; import com.kite.common.persistence.annotation.MyBatisDao; import com.kite.modules.att.entity.SysBaseCoach; /** * 教练员DAO接口 * @author lyb * @version 2019-11-13 */ @MyBatisDao public interface SysBaseCoachDao extends CrudDao<SysBaseCoach> { /** * 查找已存在的教练数量 * @return */ public int findSysBaseCoachCount(); /** * 根据 * @param code * @return */ public String findSysBaseCoachIdByCode(@Param("code")String code); }
package com.cibertec.controller; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.cibertec.entidad.Mascota; import com.cibertec.servicio.MascotaService; @Controller public class MascotaController { @Autowired private MascotaService service; @RequestMapping("/registraMascota") @ResponseBody public Map<String, Object> registra(Mascota obj){ Map<String, Object> salida = new HashMap<>(); Mascota objSalida = service.insertaMascota(obj); if (objSalida == null) { salida.put("MENSAJE", "Registro erróneo"); }else { salida.put("MENSAJE", "Registro exitoso"); } return salida; } }
package com.example.hbase; import com.example.hbase.utils.RedisClusterUtil; import com.example.hbase.utils.RedisParam; import com.example.hbase.utils.RedisUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.test.context.junit4.SpringRunner; import redis.clients.jedis.Jedis; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Created by DuJunchen on 2017/6/1. */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { private static final String redisPrefix_video_property_sort = RedisParam.R_VIDEO_PROPERTY_SORT; private static final String redisPrefix_doc_property_sort = RedisParam.R_DOC_PROPERTY_SORT; private static final String redisPrefix_case_property_sort = RedisParam.R_CASE_PROPERTY_SORT; private static final String redisPrefix_property_resource_sort = RedisParam.R_PROPERTY_RESOURCE_SORT; private static final String redisPrefix_video_dao = RedisParam.R_VIDEO_BASEINFO; private static final String redisPrefix_doc_dao = RedisParam.R_DOC_BASEINFO; private static final String redisPrefix_case_dao = RedisParam.R_CASE_BASEINFO; private static final String redisPrefix_all = RedisParam.R_CUSTOMER_RECOMMEND_RESOURCE_ALL; private static final String redisPrefix_customer_browse = RedisParam.R_CUSTOMER_BROWSE_RECENT; private RedisUtil util = new RedisUtil(); //redis集群配置 @Autowired RedisClusterUtil clusterUtil; @Autowired RedisTemplate<String,String> redisTemplate; @Test public void clusterTest(){ ZSetOperations<String, String> op = redisTemplate.opsForZSet(); //Double score = zSetOperations.score("recommend:customer:score:profile:1397586886349", "1418139699975"); Set<ZSetOperations.TypedTuple<String>> typedTuples = op.rangeWithScores("recommend:customer:score:profile:1397586886349", 0, -1); List<String> scoredIdList = new ArrayList<>(); for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) { scoredIdList.add(typedTuple.getValue()); } } @Test public void test1(){ Jedis resource = util.getPool().getResource(); resource.zadd("recommendTestKey",0.0,"a"); Double zscore = resource.zscore("recommendTestKey", "a"); System.out.println(zscore); } }
package simplePageRank; import java.io.IOException; import java.util.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; public class simplePageRank_reduce extends Reducer<Text, Text, Text, Text>{ public static float randomJump = 0.85f; public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException{ float oldPageRank = 0.0f; float newPageRank = 0.0f; float sumOfPageRank = 0.0f; float residualError = 0.0f; String outgoingLinks = ""; Iterator<Text> iter = values.iterator(); while(iter.hasNext()){ //Recover graph structure String[] valueArray = iter.next().toString().trim().split("\\s+"); if(valueArray[0].equals("is_node")){ oldPageRank = Float.parseFloat(valueArray[1]); outgoingLinks = valueArray.length==3? valueArray[2]:""; } //Sum incoming PageRank contributions else{ sumOfPageRank += Float.parseFloat(valueArray[0]); } } //Update the PageRank value of current node newPageRank = simplePageRank_reduce.randomJump*sumOfPageRank+(1-simplePageRank_reduce.randomJump)/simplePageRank.numOfwebGraphNodes; //Compute the residual_error for the current node residualError = Math.abs(newPageRank-oldPageRank) / newPageRank; //Accumulate error over the whole graph context.getCounter(accumulator.counter.RESIDUALERRORS).increment((long)(residualError*100000000)); //Emit node as input of the map context.write(key, new Text(newPageRank+" "+outgoingLinks.split(",").length+" "+outgoingLinks)); } }
package com.tencent.mm.ui.base; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.w.a.g; import com.tencent.mm.w.a.k; import com.tencent.mm.w.a.m; public class MMFormVerifyCodeInputView extends LinearLayout { private TextView eCm; private Button eVi; private al eeo; private OnFocusChangeListener jzz; private int layout; private Context mContext; private EditText meN; private int qyt; private int tuA; private int tuB; private OnClickListener tuC; private int tuo; private int[] tup; private TextView tuy; private int tuz; static /* synthetic */ void c(MMFormVerifyCodeInputView mMFormVerifyCodeInputView) { if (mMFormVerifyCodeInputView.tup != null) { mMFormVerifyCodeInputView.setPadding(mMFormVerifyCodeInputView.tup[0], mMFormVerifyCodeInputView.tup[1], mMFormVerifyCodeInputView.tup[2], mMFormVerifyCodeInputView.tup[3]); } } @TargetApi(11) public MMFormVerifyCodeInputView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet); this.mContext = null; this.qyt = -1; this.tuo = -1; this.tuz = -1; this.layout = -1; this.tuA = 60; this.tuB = this.tuA; this.jzz = null; this.tuC = null; TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, m.FormItemView, i, 0); this.tuo = obtainStyledAttributes.getResourceId(m.FormItemView_form_hint, -1); this.qyt = obtainStyledAttributes.getResourceId(m.FormItemView_form_title, -1); this.tuz = obtainStyledAttributes.getResourceId(m.FormItemView_form_btn_title, -1); this.layout = obtainStyledAttributes.getResourceId(m.FormItemView_form_layout, this.layout); obtainStyledAttributes.recycle(); inflate(context, this.layout, this); this.mContext = context; } public MMFormVerifyCodeInputView(Context context, AttributeSet attributeSet) { this(context, attributeSet, -1); } public void onFinishInflate() { super.onFinishInflate(); this.eCm = (TextView) findViewById(g.title); this.meN = (EditText) findViewById(g.edittext); this.tuy = (TextView) findViewById(g.timer); this.eVi = (Button) findViewById(g.send_verify_code_btn); if (this.eCm == null || this.meN == null || this.tuy == null || this.eVi == null) { x.w("MicroMsg.MMFormVerifyCodeInputView", "titleTV : %s, contentET : %s, timerTv: %s, sendSmsBtn: %s", new Object[]{this.eCm, this.meN, this.tuy, this.eVi}); } else { if (this.qyt != -1) { this.eCm.setText(this.qyt); } if (this.tuo != -1) { this.meN.setHint(this.tuo); } if (this.tuz != -1) { this.eVi.setText(this.tuz); } } if (this.meN != null) { this.meN.setOnFocusChangeListener(new 1(this)); } if (this.eVi != null) { this.eVi.setOnClickListener(new 2(this)); } } public void setFocusListener(OnFocusChangeListener onFocusChangeListener) { this.jzz = onFocusChangeListener; } public void setSendSmsBtnClickListener(OnClickListener onClickListener) { this.tuC = onClickListener; } public void setTitle(String str) { if (this.eCm != null) { this.eCm.setText(str); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "titleTV is null!"); } } public void setHint(String str) { if (this.meN != null) { this.meN.setHint(str); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); } } public void setTitle(int i) { if (this.eCm != null) { this.eCm.setText(i); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "titleTV is null!"); } } public void setHint(int i) { if (this.meN != null) { this.meN.setHint(i); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); } } public void setText(String str) { if (this.meN != null) { this.meN.setText(str); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); } } public void setImeOption(int i) { if (this.meN != null) { this.meN.setImeOptions(i); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); } } public void setSmsBtnText(int i) { if (this.eVi != null) { this.eVi.setText(i); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "sendSmsBtn is null!"); } } public void setSmsBtnText(String str) { if (this.eVi != null) { this.eVi.setText(str); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "sendSmsBtn is null!"); } } public final void cru() { this.eVi.setVisibility(8); this.tuy.setVisibility(0); this.tuy.setText(getContext().getString(k.mobile_input_send_sms_timer_title, new Object[]{Integer.valueOf(this.tuA)})); if (this.eeo != null) { this.eeo.SO(); this.eeo.J(1000, 1000); } else if (getContext() != null) { this.eeo = new al(getContext().getMainLooper(), new 3(this), true); this.eeo.J(1000, 1000); } else if (this.eeo != null) { this.eeo.SO(); } } public final void reset() { if (this.eeo != null) { this.eeo.SO(); } this.meN.setText(""); this.tuy.setVisibility(8); this.tuB = this.tuA; this.eVi.setVisibility(0); } public void setInputType(int i) { if (this.meN != null) { this.meN.setInputType(i); } else { x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); } } public final void addTextChangedListener(TextWatcher textWatcher) { if (this.meN != null) { this.meN.addTextChangedListener(textWatcher); return; } x.w("MicroMsg.MMFormVerifyCodeInputView", "watcher : %s, contentET : %s", new Object[]{textWatcher, this.meN}); } public Editable getText() { if (this.meN != null) { return this.meN.getText(); } x.e("MicroMsg.MMFormVerifyCodeInputView", "contentET is null!"); return null; } public EditText getContentEditText() { return this.meN; } public TextView getTitleTextView() { return this.eCm; } }
package joshelser.hashtable; import java.util.Collection; import java.util.Map.Entry; import java.util.Set; public interface HashTable<K,V> { public V get(K key); public boolean put(K key, V value); public V remove(K key); public int size(); public Set<K> keySet(); public Collection<V> values(); public String objdump(); }
package com.java.michael.chesstutor; public class Cell { Boolean hasPiece; int row; int column; Cell(int row, int column, Boolean hasPiece){ this.row = row; this.column = column; this.hasPiece = hasPiece; } Cell(int row, int column){ this.row = row; this.column = column; this.hasPiece = false; } }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class DaysBetweenTwoDays { //Write a program to calculate the difference between two dates in number of days. //The dates are entered at two consecutive lines in format day-month-year. //Days are in range [1…31]. Months are in range [1…12]. Years are in range [1900…2100]. public static void main(String[] args) throws ParseException { //Read the input from the console as a string Scanner reader = new Scanner(System.in); System.out.println("Enter a starting date in format dd-MM-yyyy: "); String inputStart= reader.nextLine(); System.out.println("Enter an end date in format dd-MM-yyyy: "); String inputEnd = reader.nextLine(); //Specify the format of the date using the build-in java class 'SimpleDateFormat' SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); //Initialize two date objects which we're going to format Date start = null; Date end = null; String dateStart = inputStart; String dateStop = inputEnd; start = format.parse(dateStart); end = format.parse(dateStop); // calculate the difference in milliseconds with the build-in method 'getTime' long difference = end.getTime() - start.getTime(); //calculate the result in days long days = difference / (24 * 60 * 60 * 1000); System.out.println(days); } }
package cn.org.cerambycidae.mapper; import cn.org.cerambycidae.pojo.StudentJSFInfo; import cn.org.cerambycidae.pojo.StudentJSFInfoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface StudentJSFInfoMapper { long countByExample(StudentJSFInfoExample example); int deleteByExample(StudentJSFInfoExample example); int deleteByPrimaryKey(Integer stuNum); int insert(StudentJSFInfo record); int insertSelective(StudentJSFInfo record); List<StudentJSFInfo> selectByExample(StudentJSFInfoExample example); StudentJSFInfo selectByPrimaryKey(Integer stuNum); int updateByExampleSelective(@Param("record") StudentJSFInfo record, @Param("example") StudentJSFInfoExample example); int updateByExample(@Param("record") StudentJSFInfo record, @Param("example") StudentJSFInfoExample example); int updateByPrimaryKeySelective(StudentJSFInfo record); int updateByPrimaryKey(StudentJSFInfo record); }
package com.tecapro.ldap.cache; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.unboundid.ldap.sdk.LDAPConnectionPool; import org.springframework.util.Assert; import java.util.HashMap; import java.util.Map; /** * Created by chai65 on 12/21/2016. */ public class CacheFactory { private LDAPConnectionPool pool; private HazelcastInstance hazelcastInstance; private Map<String, AttributeToDnCache> a2dCaches = new HashMap<>(); /** * @return */ public CacheFactory(HazelcastInstance instance, LDAPConnectionPool pool) { this.pool = pool; this.hazelcastInstance = instance; } public CrashA2DCache createA2D() { return new CrashA2DCache(hazelcastInstance, pool, this); } public static class CrashA2DCache { private AttributeToDnCache instance; private CacheFactory cacheFactory; private HazelcastInstance hazelcastInstance; public CrashA2DCache(HazelcastInstance hazelcastInstance, LDAPConnectionPool pool, CacheFactory cacheFactory) { this.cacheFactory = cacheFactory; this.hazelcastInstance = hazelcastInstance; this.instance = new AttributeToDnCache(pool); } public CrashA2DCache baseDn(String baseDn) { instance.setBaseDn(baseDn == null ? "" : baseDn); return this; } public CrashA2DCache attr(String attr) { Assert.notNull(attr); instance.setAttributeName(attr); return this; } public CrashA2DCache objClass(String obj) { Assert.notNull(obj); instance.setObjectClass(obj); return this; } public AttributeToDnCache get() { IMap<String, String> map = this.hazelcastInstance.getMap(instance.toString()); instance.init(map); cacheFactory.getA2dCaches().put(instance.toString(),instance); return instance; } } public Map<String, AttributeToDnCache> getA2dCaches() { return a2dCaches; } public AttributeToDnCache a2d(String objectClass, String attributeName, String baseDn){ return a2dCaches.get(AttributeToDnCache.a2dName(objectClass,attributeName, baseDn)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.insat.gl5.crm_pfa.web.controller; import java.io.Serializable; import javax.enterprise.context.Conversation; import javax.inject.Inject; import org.jboss.solder.logging.Logger; /** * * @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com -- */ public class ConversationController implements Serializable { @Inject private Conversation conversation; @Inject private Logger log; /** * Init conversation */ public void beginConversation() { if (conversation.isTransient()) { getConversation().begin(); } } /* * Fermer la conversation */ public void endConversation() { if (!conversation.isTransient()) { getConversation().end(); } } /** * Close conversation * @param redirect * @return */ public void cancel() { endConversation(); } /** * Fermer la conversation et redirection vers la page redirect * @param redirect la page de destination * @return la page de destination */ public String cancel(String redirect) { endConversation(); return redirect; } /** * @return the conversation */ public Conversation getConversation() { return conversation; } /** * @param conversation the conversation to set */ public void setConversation(Conversation conversation) { this.conversation = conversation; } }
package com.tradeshift.todo.webentity; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.codehaus.jackson.map.annotate.JsonRootName; @XmlAccessorType(XmlAccessType.FIELD ) @XmlRootElement(name = "item") @JsonRootName(value = "item") public class TaskItem{ @XmlElement(name = "id", required = true) private Long id; @XmlElement(name = "todoTask", required = true) private String todoTask; @XmlElement(name = "assigneeId", required = true) private String assigneeId; @XmlElement(name = "isComplete", required = false) private Long isComplete; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTodoTask() { return todoTask; } public void setTodoTask(String todoTask) { this.todoTask = todoTask; } public String getAssigneeId() { return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } /** * @return the isComplete */ public Long getIsComplete() { return isComplete; } /** * @param isComplete the isComplete to set */ public void setIsComplete(Long isComplete) { this.isComplete = isComplete; } }
/* Даны координаты двух различных полей шахматной доски x1, y1, x2, y2 (целые числа, лежащие в диапазоне 1–8). Проверить истинность высказывания: «Данные поля имеют одинаковый цвет». */ public class Ex_20_func { public static boolean cond(int x1, int y1, int x2, int y2){ boolean cond = false; if (x1 < 1 || x1 > 8) { System.err.println("x1(first digit) doesn't satisfy condition."); cond = true; } if (x2 < 1 || x2 > 8) { System.err.println("x2(third digit) doesn't satisfy condition."); cond = true; } if (y1 < 1 || y1 > 8) { System.err.println("y1(second digit) doesn't satisfy condition."); cond = true; } if (y2 < 1 || y2 > 8) { System.err.println("y2(fourth digit) doesn't satisfy condition."); cond = true; } if(cond) System.err.println("Check, that all arguments are in array from 1 to 8."); return cond; } public static boolean generalCond(String[] args, int conditionLength){ boolean cond = false; if (args.length < conditionLength) { System.err.println("You haven't entered arguments! The task requires entering four arguments."); cond = true; } if (args.length > conditionLength) System.out.println("You entered more arguments, than programm needs. \nIt will use only first two."); return cond; } public static void squares(int x1, int y1, int x2, int y2) { int fig1 = (x1 + y1)%2; int fig2 = (x2 + y2)%2; if (fig1 == fig2){ if (fig1 == 1) { System.out.println("This are the same colored white squares."); } else System.out.println("This are the same colored black squares."); } else System.out.println("This are the different colored squares."); } public static void main(String[] args){ if(generalCond(args,4)) return; Integer x1 = Integer.parseInt(args[0]); Integer y1 = Integer.parseInt(args[1]); Integer x2 = Integer.parseInt(args[2]); Integer y2 = Integer.parseInt(args[3]); if(cond(x1,y1,x2,y2)) return; squares(x1,y1,x2,y2); } }
package com.goodhealth.web.Timer; import com.goodhealth.comm.util.DateUtils; import org.springframework.stereotype.Component; import java.util.Date; /** * @Description * @Author WDH * @Date 2019/9/28 10:51 **/ @Component public class TimeWork { public void task(){ System.out.println("现在是北京时间:"+ DateUtils.formatDateTime(new Date(), DateUtils.YYYY_MM_DD_HH_MI_SS)); } }
package com.example.zhifou.entity; import lombok.Data; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.Entity; import javax.persistence.Id; @Data @Entity @DynamicUpdate public class CommentInfo { @Id private int commentId; }
package com.getlosthere.apps.peep.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import com.getlosthere.apps.peep.applications.TwitterApplication; import com.getlosthere.apps.peep.helpers.NetworkHelper; import com.getlosthere.apps.peep.models.Tweet; import com.getlosthere.apps.peep.rest_clients.TwitterClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; /** * Created by violetaria on 8/10/16. */ public class MentionsTimelineFragment extends TweetsListFragment { private TwitterClient client; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); client = TwitterApplication.getRestClient(); // pb.setVisibility(ProgressBar.VISIBLE); populateTimeline(1); // pb.setVisibility(ProgressBar.INVISIBLE); } public void populateTimeline(long maxId) { if (NetworkHelper.isOnline() && NetworkHelper.isNetworkAvailable(getActivity())) { client.getMentions(maxId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { ArrayList<Tweet> newTweets = Tweet.fromJSONArray(response); addAll(newTweets); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode)); Log.d("DEBUG", responseString); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode)); Log.d("DEBUG", errorResponse.toString()); } @Override public void onUserException(Throwable error) { Log.d("DEBUG", error.toString()); } }); } else { // TODO Fix this somehow to be the user mentions query for tweets ArrayList<Tweet> dbTweets = Tweet.getAll(); addAll(dbTweets); Toast.makeText(getActivity(), "You're offline, using DB. Check your network connection",Toast.LENGTH_LONG).show(); } } }
package com.lch.testscripts; import java.net.ConnectException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import com.jayway.restassured.response.Response; import com.lch.testbase.TestBase; import com.lch.utills.ExcelReader; import com.lch.utills.ExcelWriter; import com.lch.webservices.methods.Webservices; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; @Guice public class TestScripts extends TestBase { static Logger LOG = Logger.getLogger(TestScripts.class.getName()); int dataCount = 1; String newJson; JSONParser jsonParser; Object jsonParseObject; String inputJson; Response response = null; String testcaseID; //Response response1 =null; @BeforeClass public void beforeSuite(){ SetUp(); LOG.info("Execution Started"); CreateResultExcel(); } @Test(dataProvider="testData", dataProviderClass = ExcelReader.class) public void testMethod(Map<Object, Object> datamap) throws ConnectException, ParseException{ String apiURL = (String) datamap.get("APIURL"); String apiType = (String) datamap.get("Type"); testcaseID = (String) datamap.get("TCID"); String expectedResponseCode = (String) datamap.get("ExpResponseCode"); String validations="None"; HashMap<String,String> headersMap=new HashMap<String,String>(); Map<String,String> validationDataMap=new HashMap<String,String>(); //reads the headers and attach to request headersMap = getHeadersInfo(datamap); switch((String) datamap.get("Type")){ case "GET": response = Webservices.Get(headersMap,apiURL); break; case "POST": jsonRequest = jsonRequest(datamap); response = Webservices.Post(headersMap,apiURL,jsonRequest); break; case "PUT": jsonRequest = jsonRequest(datamap); response = Webservices.Put(headersMap,apiURL,jsonRequest); break; case "DELETE": response = Webservices.Delete(headersMap,apiURL); break; } TestBase.responseCode = String.valueOf(response.getStatusCode()); TestBase.jsonResponse= response.asString(); //TestBase.jsonResponse= ""; TestBase.jsonRequest = ""; if (expectedResponseCode.equals(TestBase.responseCode)) { testcaseStatus = "PASS"; } else{ testcaseStatus = "FAIL"; } validationDataMap = ValidateResponse(datamap); String apiResults=null; if (!validationDataMap.isEmpty()) { apiResults = this.verifyValidations(TestBase.jsonResponse,validationDataMap); System.out.println(apiResults); validations=apiResults; validationDataMap.clear(); } if (testcaseStatus.equals("FAIL")) { TestBase.overallRunStatus = "FAIL"; } testResultsData.put(String.valueOf(dataCount++), new Object[] {testcaseID, testcaseStatus, apiURL, apiType,expectedResponseCode,TestBase.responseCode,validations,TestBase.jsonRequest,TestBase.jsonResponse.length()}); SoftAssert softAssertion = new SoftAssert(); softAssertion.assertEquals(TestBase.responseCode, expectedResponseCode); softAssertion.assertAll(); } /*@AfterMethod public void afterMethod(){ if(testcaseID=="GetResponseJSON"){ response1 = response; System.out.println(response1); } }*/ @AfterSuite public void afterClass() { if ((TestBase.getProperty("report_format").equalsIgnoreCase("EXCEL")) || (TestBase.getProperty("report_format").equalsIgnoreCase(""))) { //writes the results in excel file. ExcelWriter writeInExcel = new ExcelWriter(); writeInExcel.writeResultsInExcel(workbook, sheet, testResultsData); } } }
package com.tinyurl.service; import java.util.Optional; import org.springframework.cache.annotation.Cacheable; import com.tinyurl.model.TinyUrl; public interface TinyUrlService { public TinyUrl createTinyUrl(String longUrl) throws Exception; @Cacheable(value = "retrieveTinyUrlCache", key = "#shortUrl") public Optional<TinyUrl> retrieveTinyUrl(String shortUrl); }
package com.xujiangjun.archetype.service.component; import com.alibaba.fastjson.JSONArray; import com.xujiangjun.archetype.support.RpcResult; import com.xujiangjun.archetype.enums.ResponseEnum; import com.xujiangjun.archetype.exception.BusinessException; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Component; import java.lang.reflect.Method; /** * Dubbo异常拦截器 * * @author xujiangjun * @since 2018.05.20 */ @Slf4j @Component public class DubboExceptionHandler implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { try { return invocation.proceed(); } catch (BusinessException e) { log.error("【Dubbo服务】抛出自定义异常", e); return processException(invocation, e); } catch (DataAccessException e) { log.error("【Dubbo服务】抛出数据访问异常", e); return processException(invocation, e); } catch (Exception e) { log.error("【Dubbo服务】抛出未知异常", e); return processException(invocation, e); } } /** * 捕获异常后处理 * * @return 封装异常返回结果 */ private Object processException(MethodInvocation invocation, Exception e) { Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); String methodName = method.getDeclaringClass().getName() + "." + method.getName(); log.error("Dubbo服务异常[method = " + methodName + ", params = " + JSONArray.toJSONString(args) + "]", e); Class<?> clazz = method.getReturnType(); if (clazz.equals(RpcResult.class)) { if (e instanceof BusinessException) { BusinessException ex = (BusinessException) e; return RpcResult.wrapFailureResult(ex.getCode(), ex.getMessage()); } return RpcResult.wrapFailureResult(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage()); } return null; } }
package com.gtfs.dao.impl; import java.io.Serializable; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import com.gtfs.bean.BranchMst; import com.gtfs.bean.LicCmsMst; import com.gtfs.bean.LicHubMst; import com.gtfs.bean.LicOblApplicationMst; import com.gtfs.bean.LicPisMst; import com.gtfs.dao.interfaces.LicPisMstDao; @Repository public class LicPisMstDaoImpl implements LicPisMstDao,Serializable{ private Logger log = Logger.getLogger(LicPisMstDaoImpl.class); @Autowired private SessionFactory sessionFactory; public List<Object> findApplicationforPis(BranchMst branchMst){ List<Object> list = null; Session session = null; try { session = sessionFactory.openSession(); Query query = session.createQuery("SELECT " + "loam.oblApplNo," + "loam.businessDate," + "coalesce((SELECT sum(lpd1.amount) FROM LicPaymentDtls as lpd1 WHERE lpd1.payMode = 'C' and lpd1.shortPremFlag is null and lpd1.licPaymentMst = lpm),0.0) as cash," + "coalesce((SELECT sum(lpd2.amount) FROM LicPaymentDtls as lpd2 WHERE (lpd2.payMode = 'Q' or lpd2.payMode = 'D') and lpd2.licPaymentMst = lpm and lpd2.payeeName = 'LIFE INSURANCE CORPORATION OF INDIA (LICI)'),0.0) as ins," + "coalesce((SELECT sum(lpd3.amount) FROM LicPaymentDtls as lpd3 WHERE (lpd3.payMode = 'Q' or lpd3.payMode = 'D') and lpd3.licPaymentMst = lpm and lpd3.payeeName = 'SARADA INSURANCE CONSULTANCY LTD'),0.0) as tie," + "loam.id " + "FROM " + "LicOblApplicationMst as loam inner join " + "loam.licBusinessTxn as lbt inner join " + "lbt.licPaymentMst as lpm " + "WHERE " + "loam.branchMst = :branchMst " + "and loam.deleteFlag = 'N' " + "and loam.migrationFlag = 'N' " + "and loam.secondaryEntryFlag = 'Y' " + "and loam.licPisMst IS NULL "); query.setParameter("branchMst", branchMst); list = query.list(); } catch (Exception e) { log.info("LicPaymentDtlsDaoImpl findApplicationforPis Error", e); } finally { session.close(); } return list; } public List<Object> findPolicyDtlsforPis(BranchMst branchMst){ List<Object> list =null; Session session = null; try { session = sessionFactory.openSession(); Query query =session.createQuery("SELECT " + "lpm.policyNo, " + "lpd.payDate, " + "coalesce((select sum(lpd1.amount) from LicRnlPaymentDtls as lpd1 where lpd1.payMode = 'C' and lpd1.shortPremFlag is null and lpd1.licRnlPaymentMst = lrpm),0.0) as cash," + "coalesce((select sum(lpd2.amount) from LicRnlPaymentDtls as lpd2 where (lpd2.payMode = 'Q' or lpd2.payMode = 'D') and lpd2.licRnlPaymentMst = lrpm and lpd2.payeeName = 'LIFE INSURANCE CORPORATION OF INDIA (LICI)'),0.0) as ins," + "coalesce((select sum(lpd3.amount) from LicRnlPaymentDtls as lpd3 where (lpd3.payMode = 'Q' or lpd3.payMode = 'D') and lpd3.licRnlPaymentMst = lrpm and lpd3.payeeName = 'SARADA INSURANCE CONSULTANCY LTD'),0.0) as tie," + "lpd.id, " + "lrpm.id " + "FROM " + "LicPolicyDtls as lpd inner join " + "lpd.licPolicyMst as lpm inner join " + "lpd.licPolicyPaymentMappings as lppm inner join " + "lppm.licRnlPaymentMst as lrpm " + "WHERE " + "lpd.branchMst = :branchMst " + "and lpd.deleteFlag = 'N' " + "and lpd.licPisMst is null " + "order by lrpm.id"); query.setParameter("branchMst", branchMst); list = query.list(); } catch (Exception e) { log.info("LicPaymentDtlsDaoImpl findPolicyDtlsforPis Error", e); } finally { session.close(); } return list; } public List<Object> findApplicationforPisForRequirement(BranchMst branchMst){ List<Object> list = null; Session session = null; try { session = sessionFactory.openSession(); Query query =session.createQuery("select " + "loam.oblApplNo," + "loam.businessDate," + "coalesce((select lpd1.amount from LicPaymentDtls as lpd1 where lpd1.payMode = 'C' and shortPremFlag = 'Y' and lpd1.licRequirementDtls.id = lrd.id and lpd1.licPaymentMst = lpm),0.0 ) as cash," //+ "coalesce((select lpd2.amount from LicPaymentDtls as lpd2 where (lpd2.payMode = 'Q' or lpd2.payMode = 'D') and lpd2.licPaymentMst = lpm and lpd2.payeeName = 'LIFE INSURANCE CORPORATION OF INDIA (LICI)'),0.0) as ins," //+ "coalesce((select lpd3.amount from LicPaymentDtls as lpd3 where (lpd3.payMode = 'Q' or lpd3.payMode = 'D') and lpd3.licPaymentMst = lpm and lpd3.payeeName = 'SARADA INSURANCE CONSULTANCY LTD'),0.0) as tie," + "loam.id," + "lrd.id " + "FROM " + "LicRequirementDtls as lrd inner join " + "lrd.licOblApplicationMst as loam inner join " + "loam.licBusinessTxn as lbt inner join " + "lbt.licPaymentMst as lpm " + "WHERE " + "loam.branchMst = :branchMst " + "and loam.deleteFlag = 'N' " + "and loam.migrationFlag = 'N' " + "and lrd.deleteFlag = 'N' " + "and lrd.licPisMst is null " + "and lrd.reqType ='S' " + "and lrd.branchRcvFlag = 'Y'"); query.setParameter("branchMst", branchMst); list = query.list(); } catch (Exception e) { log.info("LicPaymentDtlsDaoImpl findApplicationforPisForRequirement Error", e); } finally { session.close(); } return list; } public Boolean save(LicPisMst licPisMst){ Boolean status = false; Session session = null; Transaction tx = null; try { session = sessionFactory.openSession(); tx= session.beginTransaction(); session.save(licPisMst); tx.commit(); status = true; }catch (Exception e) { if(tx!=null)tx.rollback(); status = false; log.info("LicPaymentDtlsDaoImpl save Error", e); } finally { session.close(); } return status; } @Override public List<LicOblApplicationMst> findPisGeneratedReport(Date businessFromDate, Date businessToDate, String pisCms, String applNo, List<LicHubMst> licHubMsts) { Session session = null; List<LicOblApplicationMst> list = null; try{ session = sessionFactory.openSession(); Criteria criteria= session.createCriteria(LicOblApplicationMst.class,"loam"); criteria.createAlias("loam.licProductValueMst", "lpvm"); criteria.createAlias("loam.licProposerDtls", "lpd"); criteria.createAlias("loam.licInsuredDtls", "lid"); criteria.createAlias("loam.oblHubMst", "ohm"); criteria.createAlias("loam.branchMst", "bm"); criteria.createAlias("loam.licBusinessTxn", "lbt"); criteria.createAlias("lpvm.licProductMst", "lpm"); criteria.createAlias("lbt.licPaymentMst", "lpaym"); if(pisCms.equals("Y")){ criteria.add(Restrictions.isNotNull("loam.licPisMst")); }else if(pisCms.equals("N")){ criteria.add(Restrictions.isNull("loam.licPisMst")); } if(applNo != null){ criteria.add(Restrictions.eq("loam.oblApplNo", applNo)); }else{ criteria.add(Restrictions.ge("loam.businessDate", businessFromDate)); criteria.add(Restrictions.le("loam.businessDate", businessToDate)); } criteria.add(Restrictions.in("loam.oblHubMst", licHubMsts)); //criteria.add(Restrictions.eq("loam.branchMst", branchMst)); criteria.add(Restrictions.eq("lpvm.deleteFlag", "N")); criteria.add(Restrictions.eq("lpd.deleteFlag", "N")); criteria.add(Restrictions.eq("lid.deleteFlag", "N")); criteria.add(Restrictions.eq("lpm.deleteFlag", "N")); criteria.add(Restrictions.eq("loam.deleteFlag", "N")); criteria.add(Restrictions.eq("loam.migrationFlag", "N")); list = criteria.list(); }catch(Exception e){ log.info("LicPaymentDtlsDaoImpl findPisGeneratedReport Error", e); }finally{ session.close(); } return list; } @Override public List<LicPisMst> findPisListForPisReport(Long pisId,Date busineeFormDate, Date businessToDate) { Session session = null; List<LicPisMst> list = null; try{ session = sessionFactory.openSession(); Criteria criteria= session.createCriteria(LicPisMst.class,"lpm"); criteria.createAlias("lpm.licOblApplicationMsts", "loam"); if(pisId!=null){ criteria.add(Restrictions.eq("lpm.id", pisId)); } if(busineeFormDate!=null){ criteria.add(Restrictions.ge("loam.businessDate", busineeFormDate)); } if(businessToDate!=null){ criteria.add(Restrictions.le("loam.businessDate", businessToDate)); } criteria.addOrder(Order.desc("lpm.id")); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); list = criteria.list(); }catch(Exception e){ log.info("LicPaymentDtlsDaoImpl findPisGeneratedReport Error", e); }finally{ session.close(); } return list; } @Override public List<Object> findApplicationByPis(Long pisId) { List<Object> list = null; Session session = null; try { session = sessionFactory.openSession(); Query query = session.createQuery("SELECT " + "loam.oblApplNo," + "loam.businessDate," + "coalesce((SELECT sum(lpd1.amount) FROM LicPaymentDtls as lpd1 WHERE lpd1.payMode = 'C' and lpd1.shortPremFlag is null and lpd1.licPaymentMst = lpm),0.0) as cash," + "coalesce((SELECT sum(lpd2.amount) FROM LicPaymentDtls as lpd2 WHERE (lpd2.payMode = 'Q' or lpd2.payMode = 'D') and lpd2.licPaymentMst = lpm and lpd2.payeeName = 'LIFE INSURANCE CORPORATION OF INDIA (LICI)'),0.0) as ins," + "coalesce((SELECT sum(lpd3.amount) FROM LicPaymentDtls as lpd3 WHERE (lpd3.payMode = 'Q' or lpd3.payMode = 'D') and lpd3.licPaymentMst = lpm and lpd3.payeeName = 'SARADA INSURANCE CONSULTANCY LTD'),0.0) as tie," + "loam.id " + "FROM " + "LicOblApplicationMst as loam inner join " + "loam.licBusinessTxn as lbt inner join " + "lbt.licPaymentMst as lpm inner join " + "loam.licPisMst as lpms " + "WHERE " + "loam.deleteFlag = 'N' " + "and loam.migrationFlag = 'N' " + "and loam.secondaryEntryFlag = 'Y' " + "and lpms.id= :pisId "); query.setParameter("pisId", pisId); list = query.list(); } catch (Exception e) { log.info("LicPaymentDtlsDaoImpl findApplicationforPis Error", e); } finally { session.close(); } return list; } @Override public List<LicCmsMst> findCmsByPisId(Long id) { Session session = null; List<LicCmsMst> list = null; try{ session = sessionFactory.openSession(); Criteria criteria= session.createCriteria(LicCmsMst.class,"lcm"); criteria.add(Restrictions.eq("lcm.licPisMst.id", id)); criteria.add(Restrictions.eq("lcm.deleteFlag", "N")); list = criteria.list(); }catch(Exception e){ log.info("LicPaymentDtlsDaoImpl findPisGeneratedReport Error", e); }finally{ session.close(); } return list; } }
package com.espendwise.manta.web.tags; import com.espendwise.manta.util.alert.AppLocale; import com.espendwise.manta.auth.Auth; import com.espendwise.manta.i18n.I18nUtil; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.JspException; import java.io.IOException; public class DayMonthPromptTag extends TagSupport { @Override public int doEndTag() throws JspException { try { AppLocale locale = new AppLocale(Auth.getAppUser().getLocale()); pageContext.getOut().write(I18nUtil.getDayWithMonthPatternPrompt(locale)); } catch (IOException e) { //ignore } return TagSupport.EVAL_PAGE; } }
package com.test; import java.lang.reflect.Field; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Properties; import com.interf.test.Constant; import examples.Config; //import model.nn_composition.DocSimplifiedLSTM123Main; public class RMIServer { public static void main(String[] args) throws Exception { Config cfObject = new Config("config.json"); RemoteImpl impl = new RemoteImpl(); int rmiport = Integer.parseInt(cfObject.getAtribute("rmi-port")); Registry registry = LocateRegistry.createRegistry(rmiport); registry.bind(cfObject.getAtribute("rmi-id"), impl); System.out.println("start is started"); } }
package com.johacks; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class AppTest extends TestCase { private static final Logger logger = LogManager.getLogger("TestLogger"); /** * Rigourous Test :-) * @throws NoSuchAlgorithmException * @throws SignatureException * @throws InvalidKeySpecException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void testApp() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, InvalidKeySpecException, SignatureException { logger.info("Started testing"); final Wallet utilityWallet = new Wallet("Utility Wallet"); final KeyPair genesysKey = utilityWallet.generateKeyPair("genesysKeyPair"); final KeyPair minerKey = utilityWallet.generateKeyPair("minerKeyPair"); final Wallet fromWallet = new Wallet("My Source Wallet"); final KeyPair fromKey = fromWallet.generateKeyPair("myFromKeyPair"); final Wallet toWallet = new Wallet("My Destination Wallet"); final KeyPair toKey0 = toWallet.generateKeyPair("myToKeyPair 0"); final KeyPair toKey1 = toWallet.generateKeyPair("myToKeyPair 1"); logger.info("Keys created"); final Transaction genesysTransaction = new Transaction(); //todo supply proof final TransactionOutput genesysOutput = new TransactionOutput(0,1000,genesysKey.getPublicKey(),""); genesysTransaction.addOutput(genesysOutput); final Miner miner = new Miner(genesysTransaction,minerKey); logger.info("miner intialised with genesys transaction"); final Transaction firstTransaction = new Transaction(); final TransactionInput input0= new TransactionInput(0,genesysTransaction.getOutput(0)); firstTransaction.addInput(input0); //todo supply proof final TransactionOutput output0 = new TransactionOutput(0,50,toKey0.getPublicKey(),""); final TransactionOutput output1 = new TransactionOutput(1,50,toKey1.getPublicKey(),""); firstTransaction.addOutput(output0); firstTransaction.addOutput(output0); logger.info("first transaction created"); miner.addTransaction(firstTransaction); miner.confirmWipTransactions(); logger.info("completed first set of mining"); moveMoney(genesysTransaction,toKey0,toKey1,miner); moveMoney(genesysTransaction,toKey0,toKey1,miner); moveMoney(firstTransaction,toKey0,toKey1,miner); miner.confirmWipTransactions(); logger.info("completed second set of mining"); } private void moveMoney(Transaction genesysTransaction,KeyPair toKey0,KeyPair toKey1,Miner miner) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException { final Transaction myTransaction = new Transaction(); final TransactionInput input0= new TransactionInput(0,genesysTransaction.getOutput(0)); myTransaction.addInput(input0); //todo supply proof final TransactionOutput output0 = new TransactionOutput(0,10,toKey0.getPublicKey(),""); final TransactionOutput output1 = new TransactionOutput(1,10,toKey1.getPublicKey(),""); myTransaction.addOutput(output0); myTransaction.addOutput(output0); miner.addTransaction(myTransaction); logger.info("moneyMoved"); } /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } }
package com.tt.miniapp.impl; import com.tt.option.v.b; public class HostOptionSceneDependImpl implements b { public String getScene(String paramString) { return ""; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\impl\HostOptionSceneDependImpl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example.demo; public class MethodOverride { public static void main(String[] args){ Animal animal = new Animal(); animal.makeNoise(); Cat cat = new Cat(); cat.makeNoise(); } } class Animal{ void makeNoise(){ System.out.println("Animal makes noise."); } void animalEat(){ System.out.println("Animal eats!"); } } class Dog extends Animal{ @Override void makeNoise() { System.out.println("Dog makes noise."); } } class Cat extends Animal{ void makeNoise(){ System.out.println("Cat makes noise."); } }
package com.yuyang.wirelesstransmission; import android.app.AlertDialog; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.support.v4.provider.DocumentFile; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.NotificationCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.yuyang.wirelesstransmission.adapter.FileInfoAdapter; import com.yuyang.wirelesstransmission.adapter.SyncAdapter; import com.yuyang.wirelesstransmission.adapter.TransAdapter; import com.yuyang.wirelesstransmission.transmission.ClientConnection; import com.yuyang.wirelesstransmission.transmission.Client_t; import com.yuyang.wirelesstransmission.transmission.FileAccess; import com.yuyang.wirelesstransmission.transmission.FileInfo; import com.yuyang.wirelesstransmission.transmission.FileInfo_rec; import com.yuyang.wirelesstransmission.transmission.FileInfo_send; import com.yuyang.wirelesstransmission.transmission.Server_t; import com.yuyang.wirelesstransmission.transmission.TransInfo; import com.yuyang.wirelesstransmission.transmission.TransManage; import com.yuyang.wirelesstransmission.transmission.tranSignal; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ClientActivity extends AppCompatActivity implements TransAdapter.OnTransItemCancelListener,FileInfoAdapter.onItemRequestListener,Client_t.onSignalDeliverListener,FileInfoAdapter.onItemClickListener,ClientConnection.ConnectionCompact { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Explorer"); setContentView(R.layout.activity_client); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED); int ori=getIntent().getIntExtra("ori",0); if(ori==0){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }else{ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } pager=(ViewPager)findViewById(R.id.client_pages); LayoutInflater inflater=getLayoutInflater(); page_file=inflater.inflate(R.layout.file_page,null); page_trans=inflater.inflate(R.layout.trans_page,null); page_his=inflater.inflate(R.layout.his_page,null); view_file=(RecyclerView)page_file.findViewById(R.id.file_view); view_trans=(RecyclerView)page_trans.findViewById(R.id.trans_view); view_his=(RecyclerView)page_his.findViewById(R.id.his_view); file_dir=(TextView)page_file.findViewById(R.id.file_dir); trans_stop=(TextView)page_trans.findViewById(R.id.trans_stop_txt); editText=null; qrIP=null; qrPort=null; file_upload=page_file.findViewById(R.id.file_upload); file_trans=page_file.findViewById(R.id.file_proc); trans_pause=page_trans.findViewById(R.id.trans_stop); trans_cancel=page_trans.findViewById(R.id.trans_cancel); trans_cancel.setEnabled(false); his_clean=page_his.findViewById(R.id.his_clean); his_trans=page_his.findViewById(R.id.his_trans); his_clean.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish_list.clear(); historyAdapter.notifyDataSetChanged(); } }); his_trans.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(1); } }); dir_bar=(ProgressBar) page_file.findViewById(R.id.dir_bar); trans_bar1=(CircleProgress) page_file.findViewById(R.id.file_bar); trans_bar2=(CircleProgress) page_trans.findViewById(R.id.trans_bar); trans_bar3=(CircleProgress) page_his.findViewById(R.id.his_bar); trans_bar1.setStrokeWidth(15); trans_bar2.setStrokeWidth(15); trans_bar3.setStrokeWidth(15); pagetitle=new String[]{"文件浏览","传输列表","历史记录"}; ViewList=new View[]{page_file,page_trans,page_his}; file_trans.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(1); } }); trans_pause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { connection.switchPause(); } }); trans_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { connection.cancelAllTask(); trans_cancel.setEnabled(false); } }); file_upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FileAccess.getFileActivity(ClientActivity.this); } }); connection = new ClientConnection(this); view_file.setLayoutManager(new LinearLayoutManager(this)); view_trans.setLayoutManager(new LinearLayoutManager(this)); view_his.setLayoutManager(new LinearLayoutManager(this)); download=null; //client=null; handler=new Handler(); file_list=new ArrayList<>(); finish_list=new ArrayList<>(); fileInfoAdapter=new FileInfoAdapter(file_list,this); historyAdapter=new FileInfoAdapter(finish_list,this,true); manage=new TransManage(); connection.bindTransManage(manage); transAdapter=new TransAdapter(manage,this); view_file.setAdapter(fileInfoAdapter); view_his.setAdapter(historyAdapter); view_trans.setAdapter(transAdapter); path_stack=new Stack<>(); path_stack.push("/"); request_pos=null; notificationProc=-1; notBuilder=null; notManager=null; working =false; pager.setAdapter(getPageAdapter()); helper=DataHelper.getHelper(this); settings=SettingStores.getSetingStores(this); total_bar_update(); start_helper(); } private PagerAdapter getPageAdapter(){ return new PagerAdapter() { @Override public int getCount() { return ViewList.length; } @Override public boolean isViewFromObject(View view, Object object) { return view==ViewList[Integer.parseInt(object.toString())]; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(ViewList[position]); } @Override public Object instantiateItem(ViewGroup container, int position){ container.addView(ViewList[position]); return position; } @Override public CharSequence getPageTitle(int position){ return pagetitle[position]; } }; } private void total_bar_update(){ handler.post(new Runnable() { @Override public void run() { if(manage.isEmptyTask()){ trans_bar1.setMax(100); trans_bar1.setProgress(0); trans_bar2.setMax(100); trans_bar2.setProgress(0); trans_bar3.setMax(100); trans_bar3.setProgress(0); }else{ trans_bar1.setMax(manage.getTask(0).getSize()); trans_bar1.setProgress(manage.getTask(0).getFinished()); trans_bar2.setMax(manage.getTask(0).getSize()); trans_bar2.setProgress(manage.getTask(0).getFinished()); trans_bar3.setMax(manage.getTask(0).getSize()); trans_bar3.setProgress(manage.getTask(0).getFinished()); } } }); } private void repeat_file_dialog(final FileInfo_rec rec, final DocumentFile df){ AlertDialog.Builder builder= new AlertDialog.Builder(ClientActivity.this); builder.setTitle("文件已存在"); builder.setMessage(String.format("文件\"%s\"已经存在, 是否覆盖?",rec.getName())); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); builder.setPositiveButton("覆盖", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { connection.send(tranSignal.Get_File,rec.getPath()); remove_repeat(df); connection.add_task(rec); connection.start_task(); dialog.dismiss(); } }); builder.show(); } private void remove_repeat(DocumentFile df){ for (int i = 0;i<finish_list.size();i++){ if(finish_list.get(i).getDocumentFile().getUri().equals(df.getUri())) { finish_list.remove(i); final int x = i; handler.post(new Runnable() { @Override public void run() { historyAdapter.notifyItemRemoved(x); } }); return ; } } } private void repeat_task_dialog(final FileInfo_rec rec,final int idx){ AlertDialog.Builder builder= new AlertDialog.Builder(ClientActivity.this); builder.setTitle("任务冲突"); builder.setMessage(String.format("文件\"%s\"已经在传输列队中?",rec.getName())); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); builder.setPositiveButton("查看", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { pager.setCurrentItem(1); view_trans.smoothScrollToPosition(idx); //total_bar_update(); dialog.dismiss(); } }); builder.show(); } public static boolean isIP(String str){ String ip = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))"; Pattern pattern = Pattern.compile(ip); Matcher matcher = pattern.matcher(str); return matcher.matches(); } public static boolean isPort_accept(int port){ return port>1024&&port<60000; } private void start_helper(){ AlertDialog.Builder helper= new AlertDialog.Builder(ClientActivity.this); final View view = LayoutInflater.from(ClientActivity.this).inflate(R.layout.layout_catch_helper,null); helper.setTitle("建立连接"); helper.setView(view); helper.setCancelable(false); final EditText path=(EditText)view.findViewById(R.id.catch_to_dir); final EditText port=(EditText)view.findViewById(R.id.catch_port); final EditText addr=(EditText)view.findViewById(R.id.catch_ip); final TextView sele=(TextView)view.findViewById(R.id.catch_sele_dir); final ProgressBar link=(ProgressBar)view.findViewById(R.id.link__process); final ImageButton qr = (ImageButton) view.findViewById(R.id.qr_scan); qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new IntentIntegrator(ClientActivity.this) .setOrientationLocked(false) .setCaptureActivity(QRScanActivity.class) .initiateScan(); } }); addr.requestFocus(); final EditText group[]={path,port,addr}; editText=path; qrPort=port; qrIP=addr; download=FileAccess.getDir_Doc(this); if(download!=null) path.setText(FileAccess.getPathUri(this,download.getUri())); port.setText(settings.getPortSignalDefault()); sele.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FileAccess.getDirActivity(ClientActivity.this); } }); helper.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ClientActivity.this.finish(); editText=null; qrIP=null; qrPort=null; } }); helper.setPositiveButton("应用", null); final AlertDialog dialog= helper.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { for(EditText E:group){ if(E.getText().length()==0){ E.setError("输入错误"); E.requestFocus(); return; } } if(download==null||download.isFile()){ path.setError("无法使用该路径"); path.requestFocus(); return; } String address=addr.getText().toString(); if(!isIP(address)){ addr.setError("无效地址"); addr.requestFocus(); return; } if(false&&getIP().equals("0.0.0.0")){ Toast.makeText(ClientActivity.this, "请检查连接", Toast.LENGTH_SHORT).show(); return; } int port_; try{ port_ =Integer.parseInt(port.getText().toString()); if(!isPort_accept(port_)) throw new Exception("无效端口"); }catch (NumberFormatException e){ port.setError("端口号只允许数字"); port.requestFocus(); return; }catch (Exception e){ port.setError("无效端口"); port.requestFocus(); return; } //client=Client_t.getClient_t(address,port_,settings.getTime_Out(),ClientActivity.this); //connection.setClient(client); connection.buildClient(address,port_,settings.getTime_Out(),ClientActivity.this); connection.setDownload(download); link.setIndeterminate(true); new Thread(){ public void run(){ final int e=connection.openClient(); handler.post(new Runnable() { @Override public void run() { if(e==0) { editText = null; qrIP=null; qrPort=null; dialog.dismiss(); }else{ link.setIndeterminate(false); if(e==-4) Toast.makeText(ClientActivity.this, "链接被拒绝,请重启服务端", Toast.LENGTH_SHORT).show(); else Toast.makeText(ClientActivity.this, "连接超时,请重试"+e, Toast.LENGTH_SHORT).show(); connection.closeClient(); } } }); } }.start(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event){ switch (keyCode){ case KeyEvent.KEYCODE_BACK: if(pager.getCurrentItem()==0){ if(path_stack.size()==1) { Toast.makeText(this, "当前已在根目录", Toast.LENGTH_SHORT).show(); }else{ if(!connection.isDir_sw()) { path_stack.pop(); connection.switch_dir(path_stack.peek()); } else { if(request_pos!=null) return true; path_stack.pop(); request_pos=new FileInfo_rec("par",-1,path_stack.peek()); connection.send(tranSignal.Target_Found); Log.d("target_found","calcel"); } } }else{ pager.setCurrentItem(0); } return true; default: return super.onKeyDown(keyCode,event); } } @Override public void OnSignalDeliver() { handler.post(new Runnable() { @Override public void run() { connection.signalHandel(); } }); } public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if(requestCode==FileAccess.READ_REQUEST_CODE){ if(resultCode == RESULT_OK){ Uri uri = resultData.getData(); if(editText!=null) { download=DocumentFile.fromTreeUri(this,uri); editText.setText(FileAccess.getPathUri(this,download.getUri())); } } }else if(requestCode==FileAccess.FILE_REQUEST_CODE){ if(resultCode == RESULT_OK){ Uri uri = resultData.getData(); DocumentFile documentFile=DocumentFile.fromSingleUri(this,uri); FileInfo_send send=new FileInfo_send(documentFile); connection.add_task(send); connection.send(tranSignal.Send_File,String.format("%s:::%d:::%s",send.getName(),send.getSize(),path_stack.peek())); connection.start_task(); } }else if(requestCode==IntentIntegrator.REQUEST_CODE){ IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,resultData); if(intentResult!=null){ if(intentResult.getContents() == null) { Toast.makeText(this,"无效二维码",Toast.LENGTH_LONG).show(); }else{ String ScanResult = intentResult.getContents(); String datas[] = ScanResult.split(":::"); if(qrPort==null||qrIP==null) return; qrIP.setText(datas[1]); qrPort.setText(datas[2]); Toast.makeText(this, "服务器所在网络:"+datas[0], Toast.LENGTH_SHORT).show(); } } } } //// ///// @Override public InputStream onRequireInStream(DocumentFile src) throws FileNotFoundException { return ClientActivity.this.getContentResolver().openInputStream(src.getUri()); } @Override public OutputStream onRequireOutStream(DocumentFile tar) throws FileNotFoundException { return ClientActivity.this.getContentResolver().openOutputStream(tar.getUri()); } @Override public void onTaskStart() { setOnWorking(true); } @Override public void onProgressUpdate() { handler.post(new Runnable() { @Override public void run() { transAdapter.notifyItemChanged(0); } }); notificationUpdate(); total_bar_update(); } @Override public void onTaskFinished() { handler.post(new Runnable() { @Override public void run() { transAdapter.notifyItemRemoved(0); } }); total_bar_update(); } @Override public void onAllTaskFinished() { total_bar_update(); cancelNotification(); TransFinishService.notify_new(ClientActivity.this,"文件传输已完成"); setOnWorking(false); } @Override public void onMakeNotification() { makeNotification(); } @Override public void onNotificationUpdate() { notificationUpdate(); } @Override public void onAddFinishedTask(final FileInfo finishInfo) { finish_list.add((FileInfo_rec) finishInfo); handler.post(new Runnable() { @Override public void run() { historyAdapter.notifyItemInserted(finish_list.size()); } }); helper.insert_history(null,(FileInfo_rec)finishInfo); } @Override public void onNotificationIndeterminate(boolean state) { notificationIndeterminate(state); } @Override public void onNotificationInit() { notificationUpdate(); notificationProc=-1; } @Override public void onTaskStop() { trans_stop.setText("继续"); } @Override public void onTaskContinue() { trans_stop.setText("暂停"); } @Override public void onTaskCancelALL() { handler.post(new Runnable() { @Override public void run() { transAdapter.notifyDataSetChanged(); } }); total_bar_update(); } @Override public void onTaskAdd(final int pos) { total_bar_update(); notificationUpdateRealTime(); handler.post(new Runnable() { @Override public void run() { transAdapter.notifyItemInserted(pos); } }); } @Override public void onTaskCancelAt(int index) { transAdapter.notifyItemRemoved(index); } @Override public void onPauseSwitch(boolean state) { trans_stop.setText(state?"继续":"暂停"); } @Override public void onAddFileInfo(FileInfo_rec file) { file_list.add(file); fileInfoAdapter.notifyItemInserted(file_list.size()); //connection.send(tranSignal.INFO_D); } @Override public void OnLinkLost() { connection.setLinklost(true); handler.post(new Runnable() { @Override public void run() { Toast.makeText(ClientActivity.this, "连接丢失,请检查网络设置", Toast.LENGTH_SHORT).show(); } }); connection.closeClient(); finish(); } @Override public void onSwitchDir() { file_list.clear(); fileInfoAdapter.notifyDataSetChanged(); file_dir.setText(path_stack.peek()); } @Override public void onTaskRepeat(final FileInfo_rec rec,final int idx) { repeat_task_dialog(rec,idx); } @Override public void onFileRepeat(final FileInfo_rec rec, final DocumentFile df) { repeat_file_dialog(rec,df); } @Override public void onRecordPath(String path) { path_stack.push(path); } @Override public void onSwitchDirStart() { dir_bar.setVisibility(View.VISIBLE); } @Override public void onDirSwitched() { dir_bar.setVisibility(View.INVISIBLE); if(request_pos!=null){ connection.requestItem(request_pos); request_pos=null; } } @Override public void onSyncStart(final boolean success){ handler.post(new Runnable() { @Override public void run() { if(success) crateSyncDialog(); else Toast.makeText(ClientActivity.this, "请等待当前任务完成", Toast.LENGTH_SHORT).show(); } }); } @Override public void onSyncFinish(){ handler.post(new Runnable() { @Override public void run() { finishSync(); } }); } @Override public void onSyncAdd(final ClientConnection.FileInfo_Sync sync){ if(syncAdapter ==null) { Log.d("SYNCTEST-ADP", "syncAdapter missing"); return; } handler.post(new Runnable() { @Override public void run() { connection.getSyncList().add(sync); syncAdapter.notifyItemInserted(connection.getSyncList().size()); } }); } @Override public void onSyncProcessMaxSet(final int p){ if(syncBar==null) return; handler.post(new Runnable() { @Override public void run() { syncBar.setIndeterminate(false); syncBar.setMax(p); syncBar.setProgress(0); syncBar.setSecondaryProgress(0); } }); } @Override public void onSyncProcessUpdata(int p){ if(syncBar==null) return; syncBar.setProgress(p); } @Override public void onSyncApplying(final boolean apply) { if(apply == true && !working) return; handler.post(new Runnable() { @Override public void run() { trans_cancel.setEnabled(!apply); } }); } public void onSecondarySyncProcessUpdate(int p){ if(syncBar==null) return; syncBar.setSecondaryProgress(p); } @Override public void OnTransItemCanceled(int pos) { connection.cancelItem(pos); } @Override public void OnItemRequest(int pos) { if(request_pos!=null||connection.isCanceling()||connection.isSync_apply()) return; FileInfo_rec info=file_list.get(pos); if(connection.isDir_sw()){ request_pos=info; connection.send(tranSignal.Target_Found); Log.d("target_found","push"); return; } connection.requestItem(info); } private Intent getIntentOut(FileInfo info) { Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d("uricheck",info.getDocumentFile().getUri().toString()); File file=new File(FileAccess.getPathUri(ClientActivity.this,info.getDocumentFile().getUri())); if(file==null||!file.exists()){ Toast.makeText(this,"文件不存在", Toast.LENGTH_SHORT).show(); return null; } Uri uri=Uri.fromFile(file); intent.setDataAndType(uri, info.getMimeType()); return intent; } private void openBySys(Intent intent) { try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "无法找到合适的应用打开该文件", Toast.LENGTH_SHORT); } } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.c_his: Intent intent = new Intent(ClientActivity.this,HistoryActivity.class); startActivity(intent); return true; case R.id.c_close: showCloseDialog(); return true; case R.id.c_sync: connection.syncStart(); return true; case R.id.c_ref: if(!connection.isDir_sw()) { connection.switch_dir(path_stack.peek()); } else { if(request_pos!=null) return true; request_pos=new FileInfo_rec("par",-1,path_stack.peek()); connection.send(tranSignal.Target_Found); Log.d("target_found","calcel"); } return true; default: return false; } } private void showCloseDialog(){ AlertDialog.Builder dialog =new AlertDialog.Builder(this); dialog.setTitle("关闭连接?"); dialog.setMessage("是否关闭连接?"); dialog.setPositiveButton("是", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { connection.closeClient(); ClientActivity.this.finish(); } }); dialog.setNegativeButton("否",null); dialog.create().show(); } private void bindSyncDialog(View dialogView){ syncBar = (ProgressBar) dialogView.findViewById(R.id.sync_bar); seleRemote = (Button) dialogView.findViewById(R.id.sync_select_remote); seleLocal = (Button) dialogView.findViewById(R.id.sync_select_local); seleClear = (Button) dialogView.findViewById(R.id.sync_select_clear); //syncTitle = dialogView.findViewById(R.id.sync_title); syncView = (RecyclerView) dialogView.findViewById(R.id.syncRecyclerView); syncView.setLayoutManager(new LinearLayoutManager(this)); syncAdapter = new SyncAdapter(connection.getSyncList(),ClientActivity.this); syncBar.setIndeterminate(true); seleRemote.setEnabled(false); seleLocal.setEnabled(false); seleClear.setEnabled(false); syncView.setAdapter(syncAdapter); } private void unbindSyncDialog(){ syncBar = null; seleRemote = null; seleLocal = null; seleClear=null; //syncTitle = null; syncView = null; syncAdapter = null; syncDia=null; } private void finishSync(){ if(syncDia==null) return; seleLocal.setEnabled(true); seleRemote.setEnabled(true); seleClear.setEnabled(true); seleLocal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(ClientConnection.FileInfo_Sync x:connection.getSyncList()){ x.setMode(ClientConnection.FileInfo_Sync.syncMode.upload); } syncAdapter.notifyDataSetChanged(); } }); seleRemote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(ClientConnection.FileInfo_Sync x:connection.getSyncList()){ x.setMode(ClientConnection.FileInfo_Sync.syncMode.download); } syncAdapter.notifyDataSetChanged(); } }); seleClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(ClientConnection.FileInfo_Sync x:connection.getSyncList()){ x.setMode(ClientConnection.FileInfo_Sync.syncMode.skip); } syncAdapter.notifyDataSetChanged(); } }); syncDia.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); syncDia.getButton(AlertDialog.BUTTON_NEGATIVE).setText("取消"); syncDia.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(true); } private void crateSyncDialog(){ final AlertDialog.Builder syncDialog = new AlertDialog.Builder(ClientActivity.this); final View dialogView = LayoutInflater.from(ClientActivity.this).inflate(R.layout.sync_dialog_view,null); syncDialog.setTitle("同步目录"); syncDialog.setCancelable(false); syncDialog.setView(dialogView); bindSyncDialog(dialogView); syncDialog.setPositiveButton("应用",null); syncDialog.setNegativeButton("停止",null); syncDia=syncDialog.show(); Window window = syncDia.getWindow(); window.getDecorView().setPadding(0,0,0,0); WindowManager.LayoutParams lp = window.getAttributes(); lp.width=WindowManager.LayoutParams.MATCH_PARENT; lp.height=WindowManager.LayoutParams.MATCH_PARENT; window.setAttributes(lp); syncDia.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); syncDia.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connection.applySyncList(); //connection.clearSyncList(); syncDia.dismiss(); unbindSyncDialog(); } }); syncDia.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(syncDia.getButton(AlertDialog.BUTTON_NEGATIVE).getText().toString().equals("停止")){ connection.syncStop(); syncDia.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false); }else{ connection.clearSyncList(); syncDia.dismiss(); unbindSyncDialog(); } } }); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.client_menu, menu); return true; } @Override public void OnClickListener(int pos) { openBySys(getIntentOut(finish_list.get(pos))); } private String getIP(){ WifiManager m=(WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!m.isWifiEnabled()) { m.setWifiEnabled(true); } WifiInfo wifiInfo = m.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); return Server_t.intToIp(ipAddress); } @Override public void OnLongClickListerer(int pos) { delete_file_dialog(pos); } private void delete_file_dialog(final int pos){ AlertDialog.Builder builder= new AlertDialog.Builder(ClientActivity.this); final FileInfo_rec rec = finish_list.get(pos); builder.setTitle("删除记录"); builder.setMessage(String.format("删除记录\"%s\"?",rec.getName())); builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); builder.setPositiveButton("删除记录", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { helper.delete(null,rec.getPath()); finish_list.remove(pos); historyAdapter.notifyItemRemoved(pos); } }); builder.setNegativeButton("删除文件", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { helper.delete(null,rec.getPath()); finish_list.get(pos).getDocumentFile().delete(); finish_list.remove(pos); historyAdapter.notifyItemRemoved(pos); } }); builder.show(); } private void makeNotification(){ if(notBuilder!=null) return; notBuilder=new NotificationCompat.Builder(ClientActivity.this); Intent myIntent = new Intent(this, ClientActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0); notBuilder.setOngoing(true); notBuilder.setContentIntent(pendingIntent); notBuilder.setSmallIcon(R.drawable.icon_main); notBuilder.setContentTitle("Transmission"); notBuilder.setContentText(String.format("剩余任务:%d",manage.getTaskSize())); notBuilder.setProgress(0,0,true); notManager=((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)); notManager.notify(notificationNum,notBuilder.build()); } private void notificationUpdate(){ Log.d("NotificationServe","1"); if(notBuilder==null||manage.isEmptyTask()) return; TransInfo info=manage.getTask(0); notBuilder.setContentTitle(String.format("正在%s - %s",info.isSend()?"上传":"下载",info.getName())); notBuilder.setContentText(String.format("剩余任务:%d",manage.getTaskSize())); if(info.getSize()==0){ notBuilder.setProgress(0,0 ,true); notManager.notify(notificationNum, notBuilder.build()); return; } int pro=(int)((100*info.getFinished()/info.getSize())); if(pro==100||pro>notificationProc+3) { notificationProc = pro; notBuilder.setProgress(100,notificationProc , false); notManager.notify(notificationNum, notBuilder.build()); } } private void notificationUpdateRealTime(){ if(notBuilder==null||manage.isEmptyTask()) return; TransInfo info=manage.getTask(0); notBuilder.setContentTitle(String.format("正在%s-%s",info.isSend()?"分享":"接收",info.getName())); notBuilder.setContentText(String.format("剩余任务:%d",manage.getTaskSize())); notManager.notify(notificationNum, notBuilder.build()); } private void notificationIndeterminate(boolean indeterminate){// task_wait||cancel_pause||pause_all if(indeterminate) { notBuilder.setProgress(0, 0, true); notManager.notify(notificationNum, notBuilder.build()); } } private void cancelNotification(){ if(notManager==null) return; notManager.cancel(notificationNum); notBuilder=null; notManager=null; } @Override public void onConfigurationChanged(Configuration newConfig){ finish(); } @Override public void finish(){ connection.closeClient(); cancelNotification(); super.finish(); } @Override public void onDestroy(){ connection.closeClient(); super.onDestroy(); } private void setOnWorking(final boolean on){ working = on; handler.post(new Runnable() { @Override public void run() { pager.setKeepScreenOn(on); trans_cancel.setEnabled(on&&!connection.isSync_apply()); } }); } private ViewPager pager; private View page_file,page_trans,page_his,ViewList[]; private RecyclerView view_file,view_trans,view_his; private TextView file_dir,trans_stop; private EditText editText,qrIP,qrPort; private View file_upload,file_trans,trans_pause,trans_cancel,his_clean,his_trans; private ProgressBar dir_bar; private CircleProgress trans_bar1,trans_bar2,trans_bar3; private Handler handler; private Stack<String> path_stack; private String pagetitle[]; private DocumentFile download; private AlertDialog syncDia; private ProgressBar syncBar; private Button seleRemote; private Button seleLocal; private Button seleClear; private RecyclerView syncView; private SyncAdapter syncAdapter; private ArrayList<FileInfo_rec> file_list; private ArrayList<FileInfo_rec> finish_list; private FileInfo_rec request_pos; private FileInfoAdapter fileInfoAdapter,historyAdapter; private TransAdapter transAdapter; private TransManage manage; private DataHelper helper; private SettingStores settings; private NotificationCompat.Builder notBuilder; private NotificationManager notManager; private final static int notificationNum=0x514; private int notificationProc; private ClientConnection connection; private boolean working; }
package seveida.firetvforreddit.response.objects; import com.squareup.moshi.Json; public class Gildings { @Json(name = "gid_1") public int gid1; @Json(name = "gid_2") public int gid2; @Json(name = "gid_3") public int gid3; /** * No args constructor for use in serialization * */ public Gildings() { } /** * * @param gid1 * @param gid3 * @param gid2 */ public Gildings(int gid1, int gid2, int gid3) { super(); this.gid1 = gid1; this.gid2 = gid2; this.gid3 = gid3; } }
package fss; import shared.*; import shared.Error; import java.lang.*; public class ShowTestSetPerf{ /* ShowTestSetPerf ENUM */ public final static byte showNever = 0; public final static byte showFinalOnly = 1; public final static byte showBestOnly = 2; public final static byte showAlways = 3; /* END ENUM */ private byte value; public ShowTestSetPerf(){ value = 0;} public ShowTestSetPerf(byte i_value){ value = i_value;} public byte get_value(){return value;} public void set_value(byte i_value){value = i_value;} public String toString(){ switch (value){ case 0 : return "showNever"; case 1 : return "showFinalOnly"; case 2 : return "showBestOnly"; case 3 : return "showAlways"; default : return "ShowTestSetPerf.toString:: The stored value ("+value+")is not a specified value."; } } }
package com.example.gayashan.limbcare; import android.Manifest; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class UpdateGallery extends AppCompatActivity { final int REQUEST_CODE_GALLERY = 999; ImageView imageUpdatega; DatabaseHelper mHelper; public String IDgalary,uptopic,updescription; Cursor cursorgala; EditText insert_idGallery,updatetopicGallery,txtDescriptionGallery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_gallery); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mHelper = new DatabaseHelper(this); Button btnimage,get_details,btn_update,btncancel; btncancel = findViewById(R.id.btn_cancel); btnimage= findViewById(R.id.btnimage); get_details= findViewById(R.id.get_details); btn_update= findViewById(R.id.btn_update); insert_idGallery= findViewById(R.id.insert_id); updatetopicGallery= findViewById(R.id.updatetopic); txtDescriptionGallery= findViewById(R.id.txtDescription); imageUpdatega= findViewById(R.id.imageUpdate); btnimage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat.requestPermissions( UpdateGallery.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_GALLERY ); } }); get_details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText updatetopicgallry,txtDescriptiongallery; IDgalary=insert_idGallery.getText().toString(); updatetopicgallry= findViewById(R.id.updatetopic); txtDescriptiongallery= (EditText)findViewById(R.id.txtDescription); Cursor cursor = retrieveAllData(); if (cursor.moveToNext()) { uptopic=cursor.getString(1); updescription= cursor.getString(2); byte[] foodImage = cursor.getBlob(3); Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length); imageUpdatega.setImageBitmap(bitmap); updatetopicgallry.setText(uptopic); txtDescriptiongallery.setText(updescription); } else { Toast.makeText(UpdateGallery.this, " Not valid ID!!!", Toast.LENGTH_SHORT).show(); } cursor.close(); } }); btn_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String ID,Topic,Description; byte[] img; insert_idGallery= findViewById(R.id.insert_id); updatetopicGallery= findViewById(R.id.updatetopic); txtDescriptionGallery= findViewById(R.id.txtDescription); imageUpdatega= findViewById(R.id.imageUpdate); ID=insert_idGallery.getText().toString(); Topic=updatetopicGallery.getText().toString(); Description=txtDescriptionGallery.getText().toString(); img=imageViewToByte(imageUpdatega); ContentValues values = new ContentValues(); ContentValues value = new ContentValues(); value.put("topic", Topic); value.put("description", Description); value.put("photo", img); SQLiteDatabase db = mHelper.getReadableDatabase(); String selection = "id = ?"; int newRowId = db.update( "GALLERY", value, selection, new String[]{ID}); if (newRowId == 0) { Toast.makeText(getApplicationContext(), "Gallery Not Update Successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Gallery Update Successfully", Toast.LENGTH_SHORT).show(); finish(); } } }); btncancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private Cursor retrieveAllData() { SQLiteDatabase db = mHelper.getReadableDatabase(); String SQLW="select * from GALLERY where id='" + IDgalary + "'"; cursorgala = db.rawQuery(SQLW,null); return cursorgala; } public static byte[] imageViewToByte(ImageView image) { Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); return byteArray; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode == REQUEST_CODE_GALLERY){ if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, REQUEST_CODE_GALLERY); } else { Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show(); } return; } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){ Uri uri = data.getData(); try { InputStream inputStream = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); imageUpdatega.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } }
package utils; import java.util.Scanner; public class SendGmailUtil { public static void sendGmail(String gmail,String sub,String msg) { final String user = "nsklap2611@gmail.com"; final String pass="maiyeu97"; SendMail.send(gmail, sub, msg, user, pass); } }
package com.gsonkeno.elasticsearch; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.SearchHit; import java.util.ArrayList; import java.util.List; import java.util.Map; /** es滑动查询结果容器 * Created by gaosong on 2017-04-09. */ public class ScrollRespContainer { private Client client; private SearchResponse scrollResp; private int pageSize; public ScrollRespContainer(Client client, SearchResponse scrollResp, int pageSize){ this.client = client; this.scrollResp = scrollResp; this.pageSize = pageSize; } public List<Map<String,Object>> next(){ List<Map<String,Object>> results = new ArrayList<Map<String, Object>>(); if (scrollResp.getHits().getHits().length != 0){ for (SearchHit hit : scrollResp.getHits().getHits()) { Map<String, Object> source = hit.getSourceAsMap(); results.add(source); } } scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet(); return results; } }
package ar.edu.design.examples.clientesTarjetaCredito.domain; public interface CondicionComercial { public void comprar(int monto, Cliente cliente); }
package com.tencent.mm.plugin.recharge.ui; public interface MallEditText$b { void bqa(); void fE(boolean z); }
package com.encore.spring.model.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.encore.spring.domain.MyProduct; import com.encore.spring.model.MyProductDAO; import com.encore.spring.model.MyProductService; @Service @Transactional public class MyProductServiceImpl implements MyProductService{ @Autowired private MyProductDAO myProductDAO; @Transactional @Override public void addProduct(MyProduct product) throws Exception { myProductDAO.addProduct(product); } @Override public List<MyProduct> getProductsByName(String name) throws Exception { return myProductDAO.getProductsByName(name); } @Override public List<MyProduct> getProductsByMaker(String maker) throws Exception { return myProductDAO.getProductsByMaker(maker); } @Override public List<MyProduct> getProductList() throws Exception { return myProductDAO.getProductList(); } @Override public MyProduct getProduct(int id) throws Exception { return myProductDAO.getProduct(id); } @Override public List<MyProduct> searchProduct(Map map) throws Exception { return myProductDAO.searchProduct(map); } @Override public void updateProduct(MyProduct product) throws Exception { myProductDAO.updateProduct(product); } @Override public void deleteProduct(int id) throws Exception { myProductDAO.deleteProduct(id); } }
package com.paytechnologies.DTO; public class NavDrawerItems { private int id; private int category; private String itemName; private int icon; private int selectedIcon; private int pressesIcon; private boolean isSelected = false; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public int getSelectedIcon() { return selectedIcon; } public void setSelectedIcon(int selectedIcon) { this.selectedIcon = selectedIcon; } public int getPressesIcon() { return pressesIcon; } public void setPressesIcon(int pressesIcon) { this.pressesIcon = pressesIcon; } public boolean isSelected() { return isSelected; } public void setSelected(boolean isselected) { this.isSelected = isselected; } }
package owner; public class OwnerImpl implements Owner { private String name; public OwnerImpl(String name) { this.name = name; } @Override public String getName() { return name; } }
package queue; import java.util.LinkedList; import java.util.Queue; public class Programmars_2 { public static void main(String[] args){ Programmars_2 s = new Programmars_2(); int[] priorities = {2, 1, 3, 2}; System.out.println(s.solution(priorities, 2)); priorities = new int[]{1, 1, 9, 1, 1, 1}; System.out.println(s.solution(priorities, 0)); } public int solution(int[] priorities, int location){ int answer = 1; Queue<Paper> q1 = new LinkedList<>(); for(int i=0; i < priorities.length; i++){ Paper p = new Paper(i, priorities[i]); q1.offer(p); } while(!q1.isEmpty()){ Paper current = q1.poll(); boolean flag = false; for(int i=0; i < q1.size(); i++){ if(((LinkedList<Paper>) q1).get(i).priority > current.priority){ q1.offer(current); flag = true; break; } } if(flag) continue; if(current.index == location){ break; } else { answer++; } } return answer; } private class Paper{ int index; int priority; public Paper(int index, int priority){ this.index = index; this.priority = priority; } } }
package cn.com.custom.widgetproject.callback; /** * 请求事件 * Created by custom on 2016/6/14. */ public class ReuqstEvent { public String mMsg;//传递的信息 public int cateGoryCode;//分类号 public ReuqstEvent(String Message,int cate) { mMsg = Message; this.cateGoryCode =cate; } }
public class LisasKlasse { }
/* * Copyright (C) 2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.services.fees.calculation.crypto.queries; import com.hedera.mirror.web3.evm.store.Store; import com.hedera.services.fees.calculation.QueryResourceUsageEstimator; import com.hedera.services.hapi.utils.fees.CryptoFeeBuilder; import com.hederahashgraph.api.proto.java.FeeData; import com.hederahashgraph.api.proto.java.Query; import com.hederahashgraph.api.proto.java.ResponseType; import com.hederahashgraph.api.proto.java.TransactionRecord; import java.util.Map; import org.jetbrains.annotations.Nullable; /** * Copied Logic type from hedera-services. Differences with the original: * 1. Removed child record logic * 2. Removed retching TransactionRecord from AnswerFunctions, since we do not save records in TxnIdRecentHistory */ public class GetTxnRecordResourceUsage implements QueryResourceUsageEstimator { static final TransactionRecord MISSING_RECORD_STANDIN = TransactionRecord.getDefaultInstance(); private final CryptoFeeBuilder usageEstimator; public GetTxnRecordResourceUsage(CryptoFeeBuilder usageEstimator) { this.usageEstimator = usageEstimator; } @Override public boolean applicableTo(final Query query) { return query.hasTransactionGetRecord(); } @Override public FeeData usageGiven(Query query, Store store, @Nullable Map<String, Object> queryCtx) { return usageFor(query.getTransactionGetRecord().getHeader().getResponseType()); } // removed child records logic private FeeData usageFor(final ResponseType stateProofType) { return usageEstimator.getTransactionRecordQueryFeeMatrices(MISSING_RECORD_STANDIN, stateProofType); } }
package com.wx.service; import org.springframework.web.client.RestOperations; /** * Created by Shawn on 2014/4/30. */ public class RestService { private RestOperations restTemplate; public RestOperations getRestTemplate() { return restTemplate; } public void setRestTemplate(RestOperations restTemplate) { this.restTemplate = restTemplate; } }
package com.milos.client; import com.milos.domain.Answer; import com.milos.domain.logger.PrimitiveLogger; import com.milos.domain.Message; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.BlockingQueue; import static com.milos.domain.Answer.Type.ACKNOWLEDGED; import static com.milos.domain.Answer.Type.REJECTED; public class Sync implements Runnable, Receiver.AnswerReceived, Sender.Actions { private String name; private Sender sender; private Receiver receiver; private PrimitiveLogger logger; private BlockingQueue<Message> queueToSync; private LifeCycle callback; private long sentCount = 0; private long receivedCount = 0; private Thread senderThread; private Thread receiveThread; public interface LifeCycle { void finished(); } public Sync(final String name, final OutputStream outputStream, final InputStream inputStream, final BlockingQueue<Message> queueToSync, final LifeCycle callback, final PrimitiveLogger logger ) throws IOException { if (outputStream == null) { throw new IllegalArgumentException("outputStream mast not be null"); } if (inputStream == null) { throw new IllegalArgumentException("inputStream mast not be null"); } if (queueToSync == null) { throw new IllegalArgumentException("queueToSync mast not be null"); } if (logger == null) { throw new IllegalArgumentException("logger mast not be null"); } if (callback == null) { throw new IllegalArgumentException("callback mast not be null"); } this.name = name; this.queueToSync = queueToSync; this.sender = new Sender(outputStream, queueToSync, this); this.receiver = new Receiver(inputStream, this, logger); this.logger = logger; this.callback = callback; } @Override public void run() { receiveThread = new Thread(receiver); receiveThread.setName(name + "-ReceiverThread"); receiveThread.start(); senderThread = new Thread(sender); senderThread.setName(name + "-SenderThread"); senderThread.start(); } private boolean awaitsAnswers() { return sentCount > receivedCount; } @Override public void answerReceived(Answer answer) { receivedCount++; if (answer.messageWas(ACKNOWLEDGED)) { //TODO evaluate steps for acknowledged messages, maybe do nothing } else if (answer.messageWas(REJECTED)) { //TODO save rejected messages to some persistent store or notify other parts of the system } else { logger.error("Unknown answer type: " + answer.getType()); } } @Override public void messageSent(Message message) { sentCount++; } @Override public void idle() { //TODO implement logic to await delayed answers from server or mark them as expired logger.info(name + " is idle; " + sentCount + "/" + receivedCount); if (awaitsAnswers()) { return; } receiveThread.interrupt(); senderThread.interrupt(); callback.finished(); } }
package com.test.taskSix; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { /** * Имеется набор вещей, которые необходимо поместить в рюкзак. * Рюкзак обладает заданной грузоподъемностью. Вещи в свою * очередь обладают двумя параметрами — весом и стоимостью. Цель * задачи заполнить рюкзак не превысив его грузоподъемность и * максимизировать суммарную ценность груза. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); Backpack backpack = new Backpack(in); List<Thing> thingsForBackpack = new ArrayList<>(); do { thingsForBackpack.add(backpack.createThing(in)); } while (thingsForBackpack.size() != backpack.getQuantity()); backpack.makeCombinations(thingsForBackpack); System.out.println(Arrays.toString(backpack.getBestCombination().toArray())); } }
abstract class Player{ abstract void Play(String song, String jack, int Vol); } class MP3Player extends Player{ @Override void Play(String song, String jack, int vol) { System.out.println("Song to be played = "+ song); System.out.println("Selected Mode = "+ jack); System.out.println("Selected Volume Level = "+ vol); } void loud(){ System.out.println("MP3 Player is ON"); } } class MP4Player extends Player{ @Override void Play(String song, String jack, int vol) { System.out.println("Song to be played = "+ song); System.out.println("Selected Mode = "+ jack); System.out.println("Selected Volume Level = "+ vol); } void loud(){ System.out.println("MP4 Player is ON"); } } public class AbstractPlayer { public static void main(String[] args) { MP3Player a = new MP3Player(); MP4Player b = new MP4Player(); a.Play("Song in MP3", "Audio", 15); a.loud(); System.out.println("-------------------"); b.Play("Song in MP4", "Video", 40); b.loud(); } }
package com.tencent.mm.plugin.talkroom.model; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import android.os.Looper; import com.tencent.mm.plugin.talkroom.component.a.a; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; class g$1 implements ServiceConnection { final /* synthetic */ g oxj; g$1(g gVar) { this.oxj = gVar; } public final void onServiceConnected(ComponentName componentName, IBinder iBinder) { x.i("MicroMsg.TalkRoomServer", "onServiceConnected "); if (iBinder == null) { g.a(this.oxj).i("enterTalkRoom bindServie or protocalInit failed", 3, -1); return; } g.a(this.oxj, a.U(iBinder)); if (g.b(this.oxj) >= 2) { new ag(Looper.getMainLooper()).post(new 1(this)); } } public final void onServiceDisconnected(ComponentName componentName) { x.i("MicroMsg.TalkRoomServer", "onServiceDisconnected "); } }
package com.tencent.mm.plugin.account.friend.a; import com.tencent.mm.aa.j; import com.tencent.mm.aa.q; import com.tencent.mm.protocal.c.arf; import com.tencent.mm.protocal.c.arh; import com.tencent.mm.sdk.platformtools.ah.a; import com.tencent.mm.sdk.platformtools.x; import java.util.Iterator; class ag$1 implements a { final /* synthetic */ arh eLh; final /* synthetic */ ag eLi; ag$1(ag agVar, arh arh) { this.eLi = agVar; this.eLh = arh; } public final boolean Ks() { return false; } public final boolean Kr() { if (this.eLh != null && this.eLh.rTD.size() > 0) { Iterator it = this.eLh.rTD.iterator(); while (it.hasNext()) { arf arf = (arf) it.next(); if (arf.hcd == 1) { j jVar = new j(); jVar.username = arf.hbL; jVar.dHR = arf.rqZ; jVar.dHQ = arf.rra; jVar.bWA = -1; x.d("MicroMsg.NetSceneListMFriend", "getmlist %s b[%s] s[%s]", new Object[]{jVar.getUsername(), jVar.Kx(), jVar.Ky()}); jVar.csA = 3; jVar.by(true); q.KH().a(jVar); } } } return true; } public final String toString() { return super.toString() + "|onGYNetEnd"; } }
package com.insat.gl5.crm_pfa.model; import com.insat.gl5.crm_pfa.enumeration.Salutation; import java.util.LinkedList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; /** * * @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com -- */ @Entity public class Contact extends CrmUser { private String imageURL; @OneToMany(cascade = CascadeType.ALL) private List<PhoneNumber> lstPhoneNumbers = new LinkedList<PhoneNumber>(); @OneToMany(cascade = CascadeType.ALL) private List<Address> lstAddresses = new LinkedList<Address>(); @Enumerated(EnumType.STRING) private Salutation salutation; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "accountId") private Account account; public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } /** * @return the salutation */ public Salutation getSalutation() { return salutation; } /** * @param salutation the salutation to set */ public void setSalutation(Salutation salutation) { this.salutation = salutation; } /** * @return the lstPhoneNumbers */ public List<PhoneNumber> getLstPhoneNumbers() { return lstPhoneNumbers; } /** * @param lstPhoneNumbers the lstPhoneNumbers to set */ public void setLstPhoneNumbers(List<PhoneNumber> lstPhoneNumbers) { this.lstPhoneNumbers = lstPhoneNumbers; } /** * @return the lstAddresses */ public List<Address> getLstAddresses() { return lstAddresses; } /** * @param lstAddresses the lstAddresses to set */ public void setLstAddresses(List<Address> lstAddresses) { this.lstAddresses = lstAddresses; } /** * @return the imageURL */ public String getImageURL() { return imageURL; } /** * @param imageURL the imageURL to set */ public void setImageURL(String imageURL) { this.imageURL = imageURL; } @Override public String toString() { return salutation + ". " + getFirstName() + " " + getLastName(); } }
package com.tencent.liteav.network; public interface TXIStreamDownloader$a { void onRestartDownloader(); }
package com.ht.springboot_power.mapper; import com.ht.springboot_power.entity.UserEntity; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; /** * @company 宏图 * @User Kodak * @create 2019-06-03 -20:36 * @Email:2270301642@qq.com */ public interface UserMapper { @Select(" SELECT * FROM user_info where userName=#{userName} and password=#{password}") public UserEntity login(UserEntity userEntity); @Insert("insert user_info values (null,#{userName},#{password})") public int insertUser(UserEntity userEntity); }
package br.com.physics.app; import br.com.physics.control.Control; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub new Control(); } }
package com.dreamcatcher.member.action; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import com.dreamcatcher.action.Action; import com.dreamcatcher.member.model.service.MemberServiceImpl; import com.dreamcatcher.util.CharacterConstant; import com.dreamcatcher.util.StringCheck; public class MemberContactAction implements Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String id = StringCheck.nullToBlank(request.getParameter("id")); String name = StringCheck.nullToBlank(request.getParameter("name")); String subject = StringCheck.nullToBlank(request.getParameter("subject")); String message = StringCheck.nullToBlank(request.getParameter("message")); System.out.println(message); JSONObject jSONObject = new JSONObject(); Map<String,String> mailMap = new HashMap<String, String>(); mailMap.put("id", id); mailMap.put("name", name); mailMap.put("subject", subject); mailMap.put("message", message); int cnt = MemberServiceImpl.getInstance().sendContactMail(mailMap); if( cnt == 1 ){ jSONObject.put("result", "sendContactMailSuccess"); }else{ jSONObject.put("result", "sendContactMailFailed"); } String jSONStr = jSONObject.toJSONString(); response.setContentType("text/plain; charset="+CharacterConstant.DEFAULT_CHAR); response.getWriter().write(jSONStr); return null; } }
package buildcraftAdditions.entities; import buildcraft.core.inventory.SimpleInventory; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; /** * Copyright (c) 2014, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class TileBasicCoil extends TileCoilBase implements IInventory { public int increment; private final SimpleInventory inventory = new SimpleInventory(1, "BasicCoil", 64); public TileBasicCoil(){ } @Override public void updateEntity(){ if (shouldHeat && increment < 16) increment++; if (!shouldHeat && increment > 0) increment--; } @Override public int getIncrement() { return increment; } @Override public int getSizeInventory() { return inventory.getSizeInventory(); } @Override public ItemStack getStackInSlot(int slot) { return inventory.getStackInSlot(slot); } @Override public ItemStack decrStackSize(int slot, int amount) { return inventory.decrStackSize(slot, amount); } @Override public ItemStack getStackInSlotOnClosing(int slot) { return inventory.getStackInSlotOnClosing(slot); } @Override public void setInventorySlotContents(int slot, ItemStack stack) { inventory.setInventorySlotContents(slot, stack); } @Override public String getInventoryName() { return inventory.getInventoryName(); } @Override public boolean hasCustomInventoryName() { return inventory.hasCustomInventoryName(); } @Override public int getInventoryStackLimit() { return inventory.getInventoryStackLimit(); } @Override public boolean isUseableByPlayer(EntityPlayer player) { return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this && player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64.0D; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { return GameRegistry.getFuelValue(stack) != 0; } }
package modul4.chapter4; public class Lotto { public Lotto(int[] randomLottoNumbers) { this.randomLottoNumbers = randomLottoNumbers; } private int[] randomLottoNumbers; public int calcResult(int[] inputNumbers) { int counter = 0; for (int lottoNumber : randomLottoNumbers) { for (int inputNumber : inputNumbers) { if (lottoNumber == inputNumber) { counter++; } } } return counter; } private static int[] sortInts(int[] myInts) { for (int i = 1; i < myInts.length; i++) { for (int j = myInts.length - 1; j >= i; j--) { if (myInts[j] < myInts[j - 1]) { int temp = myInts[j]; myInts[j] = myInts[j - 1]; myInts[j - 1] = temp; } } } return myInts; } }
package com.tiandi.logistics.entity.front; import lombok.Data; import java.math.BigDecimal; /** * @author kotori * @version 1.0 * @date 2020/12/7 09:50 * @description */ @Data public class PutOrder { /** * 物品编号 */ private String idGoods; /** * 订单编号 */ private String idOrder; /** * 用户 */ private String username; /** * 物品名称 */ private String nameGoods; /** * 物品数量 */ private String countGoods; /** * 货物类别编号 */ private Integer idSortGoods; /** * 寄件人地址 */ private String senderAddress; /** * 寄件人姓名 */ private String senderName; /** * 寄件人电话 */ private String senderPhone; /** * 收件人姓名 */ private String receiverName; /** * 收件人电话 */ private String receiverPhone; /** * 收件人地址 */ private String receiverAddress; /** * 支付方式 */ private String paymentMethod; /** * 配送价格 */ private BigDecimal deliveryPrice; /** * 订单状态 */ private Integer stateOrder = 0; /** * 备注 */ private String marks; }
package com.hly.o2o.dao; import com.hly.o2o.entity.Award; import org.apache.ibatis.annotations.Param; import java.util.List; public interface AwardDao { /** * 根据传入的条件查询奖品列表 * * @param awardCondition * @param rowIndex * @param pageSize * @return */ List<Award> queryAwardList(@Param("awardCondition") Award awardCondition, @Param("rowIndex") int rowIndex, @Param("pageSize") int pageSize); /** * 配合queryAwardList相同条件下查询奖品的数量 * @param awardCondition * @return */ int queryAwardCount(@Param("awardCondition") Award awardCondition); /** * 根据awardId查询对应的奖品 * @param awardId * @return */ Award queryAwardByAwardId(long awardId); /** * 添加奖品 * @param award * @return */ int insertAward(@Param("award") Award award); /** * 更新奖品 * @param award * @return */ int updateAward(Award award); /** * 删除奖品(根据奖品ID和其对应所在的店铺,因为不能删除其他店铺下的奖品) * @param awardId * @param shopId * @return */ int deleteAward(@Param("awardId") long awardId,@Param("shopId") long shopId); }
package grid.model; /** * Creates the Hipster object. * @author jmen1495 * @version 1.4 11/20/13 Added getters/setters, overloaded constructor for additional hipsters, documentation comments. */ public class Hipster { /** * The name of the Hipster */ private String name; /** * The type of the Hipster */ private String hipsterType; /** * The Hipster catch-phrase */ private String hipsterPhrase; /** * The collection of the Hipster books. */ private String [] hipsterBooks; /** * Creates a default Hipster object with values based on me. */ public Hipster() { hipsterBooks = new String[5]; name = "Jay"; hipsterType = "Student Hipster"; hipsterPhrase = "Dece"; fillTheBooks(); } /** * Creates a Hipster Object with the specified parameters to fill in the component data members. * @param name * @param hipsterType * @param hipsterPhrase * @param hipsterBooks */ public Hipster(String name, String hipsterType, String hipsterPhrase, String [] hipsterBooks) { this.name = name; this.hipsterBooks = hipsterBooks; this.hipsterPhrase = hipsterPhrase; this.hipsterType = hipsterType; } /** * Getter method to get the name. * @return The name of the Hipster. */ public String getName() { return name; } /** * Getter Method for the type of Hipster * @return The Hipster type. */ public String getHipsterType() { return hipsterType; } /** * Getter method for the Hipster phrase. * @return The Hipster phrase */ public String getHipsterPhrase() { return hipsterPhrase; } /** * Getter method for the arrary of Hipster books. * @return The arrary of Hipster books. */ public String[] getHipsterBooks() { return hipsterBooks; } /** * Setter method to change the name of the Hipster. * @param name The new name value for the Hipster. */ public void setName(String name) { this.name = name; } /** * Setter method to change the type of the Hipster. * @param hipsterType The new type of Hipster. */ public void setHipsterType(String hipsterType) { this.hipsterType = hipsterType; } /** * Setter method to change the phrase of the Hipster. * @param hipsterPhrase The new phrase for the Hipster. */ public void setHipsterPhrase(String hipsterPhrase) { this.hipsterPhrase = hipsterPhrase; } /** * Setter method for the array of books for the Hipster. * @param hipsterBooks The new array of books for the Hipster. */ public void setHipsterBooks(String[] hipsterBooks) { this.hipsterBooks = hipsterBooks; } /** * Helper method to fill the book array for the Hipster. */ private void fillTheBooks() { hipsterBooks[0] = "A Game of Thrones"; hipsterBooks[1] = "Name of the Wind"; hipsterBooks[2] = "Watchmen"; hipsterBooks[3] = "V for Vendetta"; hipsterBooks[4] = "Harry Potter"; } }
package com.wangyi.wangyi_yanxuan.service; import com.wangyi.wangyi_yanxuan.domain.Perssion; import com.wangyi.wangyi_yanxuan.vo.R; import java.util.List; public interface PerssionService { List<String> queryByUid(Integer uid); /** * 根据id删除Perssion对象 * * @param id * @return */ public R deletePerssionById(Integer fid); /** * 展示所有资源 * * @return */ public List<Perssion> findAllPerssion(); /** * 增加一个资源 * * @param perssion * @return */ public R addPerssion(Perssion perssion); }
package com.miaoshaproject.service; import com.miaoshaproject.error.BusinessException; import com.miaoshaproject.service.model.UserModel; public interface UserService { /** * 通过用户id获取用户对象的方法 * @param id */ UserModel getUserById(Integer id); void register(UserModel userModel) throws BusinessException; /** * 用户登录 * @param telphone 用户注册手机 * @param encryptPassword 用户加密后的密码 * @throws BusinessException */ UserModel validateLogin(String telphone, String encryptPassword) throws BusinessException; }
package mygroup; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class ForbidLock { // 自定义不可重入锁 private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while (isLocked) { wait(); } isLocked = true; } public synchronized void unlock() { isLocked = false; notify(); } } class ReentrantFobbidLock { // 自定义可重入锁 private boolean isLocked = false; private Thread lockedBy = null; int lockCount = 0; public synchronized void lock() throws InterruptedException { Thread cur = Thread.currentThread(); while (isLocked && lockedBy != cur) { wait(); } isLocked = true; lockedBy = cur; ++lockCount; } public synchronized void unlock() { if (Thread.currentThread() == lockedBy) { --lockCount; } if (lockCount == 0) { isLocked = false; lockedBy = null; notify(); } } } class ReentrantSpinLock { // 自定义自旋锁,不使用同步语义synchronize private AtomicReference<Thread> owner = new AtomicReference<>(); public void lock() { Thread thread = Thread.currentThread(); while (!owner.compareAndSet(null, thread)) { // 等待获得锁 } } public void unlock() { Thread thread = Thread.currentThread(); if (owner.compareAndSet(thread, null)) { // 等待释放锁 return; } throw new IllegalMonitorStateException("unlock异常"); } } public class TestLockReentrance { // 同步代码块是可重入的 private int Recursive(int i) { synchronized(this) { if (i <= 0) { return 0; } else { return i + Recursive(i - 1); } } } public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); Lock r = lock.readLock(); for (int i = 0; i < 3; ++i) { r.lock(); System.out.println("进入锁"); } r.unlock(); TestLockReentrance t = new TestLockReentrance(); System.out.println(t.Recursive(3)); } }
execute(registers, memory) { String st0 = registers.get("ST0"); Double result = Double.parseDouble(st0); Converter converter = new Converter(st0); st0 = converter.toDoublePrecisionHex(); // examine st0 String first = st0.charAt(0) + ""; converter = new Converter(first); first = converter.toBinaryString(); registers.x87().status().set("C1", first.charAt(0)); String top = registers.x87().status().getTop() + ""; if ( registers.x87().tag().getTag(top).equals("11") ) { // empty registers.x87().status().set("C3", '1'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '1'); } else if ( result.isNaN() ) { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '1'); } else if ( result.isInfinite() ) { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '1'); registers.x87().status().set("C0", '1'); } else if ( result.compareTo(new Double(0.0d)) == 0 ) { registers.x87().status().set("C3", '1'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '0'); } else { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '1'); registers.x87().status().set("C0", '0'); } }
package map; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import map.MapReduce; import ordo.Job; import formats.Format; import formats.FormatReader; import formats.FormatWriter; import formats.KV; //celui donné par le sujet public class MapReduceImpl implements MapReduce { private static final long serialVersionUID = 1L; // MapReduce program that computes word counts public void map(FormatReader reader, FormatWriter writer) { System.out.println("Je suis dans le map"); try{ Thread.sleep(5*1000); }catch (Exception e) { e.printStackTrace(); } System.out.println("J'ai fini le map"); } public void reduce(FormatReader reader, FormatWriter writer) { System.out.println("Je suis dans le reduce"); try{ Thread.sleep(5*1000); }catch (Exception e) { e.printStackTrace(); } System.out.println("J'ai fini le reduce"); } public static void main(String args[]) { System.out.println(" MapReduce1"); Job j = new Job(); System.out.println(" MapReduce2"); j.setInputFormat(Format.Type.LINE); System.out.println(args[0]); j.setInputFname(args[0]); System.out.println(" MapReduce3"); long t1 = System.currentTimeMillis(); System.out.println(" MapReduce4"); j.startJob(new MapReduceImpl()); System.out.println(" MapReduce5"); long t2 = System.currentTimeMillis(); System.out.println("time in ms ="+(t2-t1)); System.exit(0); } }
package com.tangdi.production.mpnotice.constants; /** * 支付宝 参数 配置 类 * * @author limiao * */ public class AliPayConfig { }
package org.sbbs.app.gen.service.impl; import org.sbbs.app.gen.dao.GenEntityDao; import org.sbbs.app.gen.model.GenEntity; import org.sbbs.app.gen.service.GenEntityManager; import org.sbbs.base.service.impl.BaseManagerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("genEntityManager") public class GenEntityManagerImpl extends BaseManagerImpl<GenEntity, Long> implements GenEntityManager { private GenEntityDao genEntityDao; @Autowired public GenEntityManagerImpl(GenEntityDao genEntityDao) { super(genEntityDao); this.genEntityDao = genEntityDao; } }
package org.tc.service; import org.tc.bean.UserInfo; public interface SysUserService { public UserInfo findUserByName(String userName); public String getValueByKey(String key); }
package com.javasongkb.changgou.mapper; import com.javasongkb.changgou.model.Spu; public interface SpuMapper { int deleteByPrimaryKey(Long id); int insert(Spu record); int insertSelective(Spu record); Spu selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Spu record); int updateByPrimaryKeyWithBLOBs(Spu record); int updateByPrimaryKey(Spu record); }
package com.wellness.eva; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.format.DateFormat; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import android.support.v7.widget.Toolbar; import com.wellness.eva.messaging.BroadcastEmergency; import com.wellness.eva.messaging.BroadcastReceiver; import com.wellness.eva.procedures.MedicalEmergency; import com.wellness.eva.procedures.MedicalProcedures; import com.wellness.eva.validation.SettingsSecurity; import com.wellness.eva.validation.UserPreferences; import java.util.Date; public class MainActivity extends AppCompatActivity { public static final int SECURITY_CODE = 1; private MedicalEmergency medicalEmergency; private ImageButton redCrossImageButton; private ImageButton sosImageButton; private Toolbar toolbar; private boolean call911Flag; private boolean broadcastFlag; private boolean receiveBroadcastFlag; private Button btnLocation; private boolean EnglishFlag; private boolean SpanishFlag; private Button btnEmergencyLocation; private Button btnBroadcasting; private ImageView imgAlert; private Animation pulse; private String alertDate = ""; private boolean securityShow; private UserPreferences mypreferences = new UserPreferences(); private SharedPreferences internalPref; public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InitiateControls(); InitiateLogic(); } private void InitiateControls() { // Attaching the layout to the toolbar object toolbar = (Toolbar) findViewById(R.id.toolbar); //Initiate alert icon imgAlert = (ImageView)findViewById(R.id.imgAlert); // Setting toolbar as the ActionBar with setSupportActionBar() call setSupportActionBar(toolbar); // Setting redCrossImageButton OnClick listener redCrossImageButton = (ImageButton) findViewById(R.id.imageButton); redCrossImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentVar = new Intent(MainActivity.this, MedicalProcedures.class); startActivity(intentVar); } }); sosImageButton = (ImageButton) findViewById(R.id.imageButton2); sosImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialContactPhone("123"); } }); //Setting emergency location button OnClick listener btnEmergencyLocation = (Button)findViewById(R.id.btnEmergencyLocation); btnEmergencyLocation.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { //Follow location callActivity(BroadcastReceiver.class); } }); //Setting emergency broadcasting button btnBroadcasting = (Button)findViewById(R.id.btnBroadcasting); pulse = AnimationUtils.loadAnimation(this, R.anim.pulse); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); broadcastFlag = settings.getBoolean("broadcastingMode", true); mypreferences.setSendBroadcast(broadcastFlag); internalPref = getSharedPreferences(getString(R.string.preference_internal_file_key), Context.MODE_PRIVATE); setBroadcastingState(broadcastFlag); receiveBroadcastFlag = settings.getBoolean("receiveBroadcastingMode", true); mypreferences.setReceiveBroadcast(receiveBroadcastFlag); imgAlert.setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this, SettingsSecurity.class); intent.putExtra("key",alertDate); startActivityForResult(intent, SECURITY_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == SECURITY_CODE) { boolean ignoreSecurity = data.getBooleanExtra("MESSAGE", false); AlertSettingChanged(!ignoreSecurity); } } private void InitiateLogic() { //Acquire last changed setting date GetLastSettingDate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.settings_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); LanguageHelper myLanguage = new LanguageHelper(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Toast.makeText(getApplicationContext(),"Displaying Settings",Toast.LENGTH_SHORT).show(); } if (id == R.id.menu_allowBroadcast) { Toast.makeText(getApplicationContext(),"Enable Broadcasting",Toast.LENGTH_SHORT).show(); broadcastFlag =true; mypreferences.setSendBroadcast(broadcastFlag); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("broadcastingMode",broadcastFlag).commit(); setBroadcastingState(true); } if (id == R.id.menu_disableBroadcast) { Toast.makeText(getApplicationContext(), "Disable Broadcasting", Toast.LENGTH_SHORT).show(); broadcastFlag = false; mypreferences.setSendBroadcast(broadcastFlag); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("broadcastingMode",broadcastFlag).commit(); setBroadcastingState(false); } if (id == R.id.menu_receiveBroadcast) { Toast.makeText(getApplicationContext(),"Enable Receiving Broadcast",Toast.LENGTH_SHORT).show(); receiveBroadcastFlag = true; mypreferences.setReceiveBroadcast(receiveBroadcastFlag); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("receiveBroadcastingMode",receiveBroadcastFlag).commit(); } if (id == R.id.menu_disable_receiveBroadcast) { Toast.makeText(getApplicationContext(),"Disabled Receiving Broadcast",Toast.LENGTH_SHORT).show(); receiveBroadcastFlag = false; mypreferences.setReceiveBroadcast(receiveBroadcastFlag); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("receiveBroadcastingMode",receiveBroadcastFlag).commit(); } //Inform user of change setting AlertSettingChanged(true); return super.onOptionsItemSelected(item); } private void setBroadcastingState(boolean show) { if(show) { //Share current location BroadcastEmergency shareLocationActivity = new BroadcastEmergency(this, mypreferences); shareLocationActivity.startSharingLocation(); Toast.makeText(getApplicationContext(), "Attention: Broadcast Location is Enable. Your location is been shared!", Toast.LENGTH_LONG).show(); btnBroadcasting.setBackground(getDrawable(R.drawable.ic_signal_wifi_4_bar_white_18dp)); btnBroadcasting.setVisibility(View.VISIBLE); } else { Toast.makeText(getApplicationContext(), "Attention: Broadcast Location is Disabled. Change Settings to Broadcast Location", Toast.LENGTH_LONG).show(); btnBroadcasting.setBackground(getDrawable(R.drawable.ic_signal_wifi_off_white_18dp)); btnBroadcasting.setVisibility(View.INVISIBLE); } } private void AlertSettingChanged(boolean show) { Date d = new Date(); alertDate = DateFormat.format("EEEE, MMMM d, yyyy ", d.getTime()).toString(); SaveLastSettingDate(show); ShowAlert(show); } private void SaveLastSettingDate(boolean show) { SharedPreferences.Editor editor = internalPref.edit(); editor.putBoolean("settings_show", show); editor.putString("settings_date", alertDate); editor.commit(); } private void GetLastSettingDate() { alertDate = internalPref.getString("settings_date", ""); securityShow = internalPref.getBoolean("settings_show", false); ShowAlert(securityShow); } private void ShowAlert(boolean securityShow) { if(securityShow) { imgAlert.startAnimation(pulse); imgAlert.setVisibility(View.VISIBLE); imgAlert.setAnimation(pulse); } else { imgAlert.clearAnimation(); imgAlert.setVisibility(View.INVISIBLE); imgAlert.invalidate(); imgAlert.requestLayout(); } } public void dialContactPhone(final String phoneNumber) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)); startActivity(intent); } private void callActivity(Class<?> cls) { Intent intent = new Intent(this, cls); startActivity(intent); } }
/** * 在该类中包含遗传算法本身的操作所需的方法和变量 * 这个类包括处理交叉、变异、适应度评估和终止条件检查的逻辑 * @author jpgong * */ public class GeneticAlgorithm { private int populationSize; //种群规模 private double mutationRate; //变异率 private double crossoverRate; //交叉率 private double elitismCount; //精英成员数 public GeneticAlgorithm(int populationSize, double mutationRate, double crossoverRate, double elitismCount) { this.populationSize = populationSize; this.mutationRate = mutationRate; this.crossoverRate = crossoverRate; this.elitismCount = elitismCount; } public Population initPopulation(int chromosomeLength) { Population population = new Population(this.populationSize, chromosomeLength); return population; } /* * 对种群中的每个个体计算其适应度值,并存储以便将来使用 * 遗传算法通过选择来引导进化过程,得到更好的个体,正是适应度函数使这种选择成为可能 * 每个特定的优化问题,都需要一个特别开发的适应度函数。在该问题中,只需要计算染色体中1的个数 * 方法:计算染色体中1的个数,然后除以染色体的长度,使输出规格化,在0和1之间 */ public double calcFitness(Individual individual) { //正确染色体的跟踪数量 int corretGenes = 0; //循环染色体中的基因 for (int geneIndex = 0; geneIndex < individual.getChromesomeLength(); geneIndex++) { if (individual.getGene(geneIndex) == 1) { corretGenes += 1; } } double fitness = (double)corretGenes/individual.getChromesomeLength(); individual.setFitness(fitness); return fitness; } /* * 遍历种群中的每个个体并评估它们(即对每个个体调用calcFitness) */ public void evalPopulation(Population population) { double populationFitness = 0; for (Individual individual : population.getIndividuals()) { populationFitness += calcFitness(individual); } population.setPopulationFitness(populationFitness); } /* * 检查终止条件是否已发生 * 方法:如果种群中任何个体的适应度为1,就返回ture */ public boolean isTerminationConditionMet(Population population) { for (Individual individual : population.getIndividuals()) { if (individual.getFitness() == 1) { return true; } } return false; } /* * 从种群中选择个体的方法:轮盘赌选择 * 方法:个体的适应度越高,在轮盘中占据的空间就越多 */ public Individual selectParent(Population population) { //获得种群中的所有个体 Individual individuals[] = population.getIndividuals(); double populationFitness = population.getPopulationFitness(); //规定一个轮盘赌随机位置,选择一个介于0和种群总适应度的随机数 double rouletteWheelPosition = Math.random()*populationFitness; //寻找个体 double spinWheel = 0; //逐个检查每个个体,同时累加他们的适应度值,直到起始选择的随机位置 for (Individual individual : individuals) { spinWheel +=individual.getFitness(); if (spinWheel >= rouletteWheelPosition) { return individual; } } return individuals[population.size()-1]; } /* * 创建种群交叉方法 * 这里实现的交叉方法是均匀交叉,这样后代中的每个基因都有50%的机会来自第一个亲代和第二个亲代 * 该方法是针对种群的每个个体完成交叉过程后,交叉方法返回下一代的种群 */ public Population crossoverPopulation(Population population) { //为下一代创建一个新的空种群 Population newPopulation = new Population(population.size()); //遍历种群,利用交叉率来考虑每个个体的交叉 //如果个体不经过交叉,它就直接加入下一个种群,否则就创建一个新的个体 //后代染色体的填充方法是遍历亲代染色体,随机从每个亲代选择基因,加入后代的染色体 for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) { Individual parent1 = population.getFittest(populationIndex); //是否和这个个体进行交叉? //仅当交叉条件满足且个体条件不是精英,才进行交叉 //种群中的个体已经按照他们的适应度排序,因此最强大的个体索引值最小 //因此,如果需要3个精英个体,应该跳过索引0~2,这将保留最强大的个体,直接传递到下一代 if (this.crossoverRate > Math.random() && populationIndex > this.elitismCount) { Individual offsping = new Individual(parent1.getChromesomeLength()); //寻找第二个个体 Individual parent2 = selectParent(population); for (int geneIndex = 0; geneIndex < parent1.getChromesomeLength(); geneIndex++) { //使用个体1的一半基因和个体2的一半基因 if (Math.random() < 0.5) { offsping.setGene(geneIndex, parent1.getGene(geneIndex)); }else { offsping.setGene(geneIndex, parent2.getGene(geneIndex)); } } //添加这个新的个体到种群中 newPopulation.setIndividual(populationIndex, offsping); }else { //不进行交叉添加个体到新的种群中 newPopulation.setIndividual(populationIndex, parent1); } } return newPopulation; } /* * 种群变异算法 * 方法:“位翻转”变异 */ public Population mutatePopulation(Population population) { //为变异的个体创建一个新的空种群 Population newPopulation = new Population(this.populationSize); //遍历整个种群 for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) { Individual individual = population.getFittest(populationIndex); //遍历每个个体的染色体 for (int geneIndex = 0; geneIndex < individual.getChromesomeLength(); geneIndex++) { //如果是一个精英个体则跳过变异 if (populationIndex >= this.elitismCount) { //判断这个基因是否需要变异 //基于变异率,考虑每个基因是否进行位翻转变异 if (this.mutationRate > Math.random()) { //生成一个新的基因 int newGene = 1; if (individual.getGene(geneIndex) == 1) { newGene = 0; } //变异基因 individual.setGene(geneIndex, newGene); } } } //添加一个新的个体到种群中 newPopulation.setIndividual(populationIndex, individual); } //返回一个变异的种群 return newPopulation; } }
package NivelDeAcceso.Usuario; public abstract class Employee { public String name; private int hireRent; protected String country; public int getHireRent() { return hireRent; } public void setHireRent(int hireRent) { this.hireRent = hireRent; } protected abstract double monthlyPay(); protected abstract double annualPay(); }
package kr.ds.store; import java.util.ArrayList; import java.util.Hashtable; import java.util.Map; import kr.ds.custom.StaticValue; import kr.ds.mylotto.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; /* * 종료 시 팝업 관련 * 티스토어 및 마켓 구분 onclick 리스너 수정 */ public class MainStoreTypeDialog extends DialogFragment implements OnClickListener { private Button mButton1, mButton2, mButton3, mButton4, mButton5; //private CheckBox mCheckBox; @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); //mResultListner = (ResultListner) activity;//리스너등록 } public MainStoreTypeDialog() { // TODO Auto-generated constructor stub } private DialogResultListner mDialogResultListner; public interface DialogResultListner { public void finish(); } public MainStoreTypeDialog callback (DialogResultListner dialogresultlistner){ this.mDialogResultListner = dialogresultlistner; return this; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity()); LayoutInflater mLayoutInflater = getActivity().getLayoutInflater(); View view = mLayoutInflater.inflate(R.layout.dialog, null); (mButton5 = (Button)view.findViewById(R.id.button5)).setOnClickListener(this); (mButton1 = (Button)view.findViewById(R.id.button1)).setOnClickListener(this); (mButton2 = (Button)view.findViewById(R.id.button2)).setOnClickListener(this); (mButton3 = (Button)view.findViewById(R.id.button3)).setOnClickListener(this); // (mButton4 = (Button)view.findViewById(R.id.button4)).setOnClickListener(this); //(mCheckBox = (CheckBox)view.findViewById(R.id.checkBox1)).setOnClickListener(this); mBuilder.setView(view); //mBuilder.setTitle(title); return mBuilder.create(); } private void MarketLink(int type){ switch (type) { case 1: try { startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id="+ StaticValue.APP_DOWN_URL_MARKET))); } catch (Exception e) { // TODO: handle exception Toast.makeText(getActivity(), R.string.popupview_null,Toast.LENGTH_SHORT).show(); } break; case 2: String strSubject = StaticValue.APP_DOWN_TITLE; String strMessage = "안녕하세요. "+StaticValue.APP_DOWN_TITLE+" 입니다. 다운 해주시면 알찬 정보가 기다리고 있습니다. 최선을 다해 업데이트 처리하겠습니다.^^"; String strURL = "market://details?id="+StaticValue.APP_DOWN_URL_MARKET; try { KaKaoAppData(strURL, strSubject, strMessage); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } private void TstoreLink(int type){ switch (type) { case 1: try { String tstorePID = StaticValue.APP_DOWN_URL_TSTORE; Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setClassName("com.skt.skaf.A000Z00040", "com.skt.skaf.A000Z00040.A000Z00040"); intent.setAction("COLLAB_ACTION"); intent.putExtra("com.skt.skaf.COL.URI", ("PRODUCT_VIEW/" + tstorePID + "/0").getBytes()); intent.putExtra("com.skt.skaf.COL.REQUESTER", "A000Z00040"); startActivity(intent); } catch (Exception e) { // TODO: handle exception Toast.makeText(getActivity(), R.string.popupview_null,Toast.LENGTH_SHORT).show(); } break; case 2: String strSubject = StaticValue.APP_DOWN_TITLE; String strMessage = "안녕하세요. "+StaticValue.APP_DOWN_TITLE+" 입니다. 다운 해주시면 알찬 정보가 기다리고 있습니다. 최선을 다해 업데이트 처리하겠습니다.^^"; String strURL = "tstore://PRODUCT_VIEW/"+StaticValue.APP_DOWN_URL_TSTORE+"/0"; try { KaKaoAppData(strURL, strSubject, strMessage); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } private void KaKaoAppData(String url, String subject, String memo) throws NameNotFoundException { String encoding = "UTF-8"; ArrayList<Map<String, String>> metaInfoArray = new ArrayList<Map<String, String>>(); Map<String, String> metaInfoAndroid = new Hashtable<String, String>(1); metaInfoAndroid.put("os", "android"); metaInfoAndroid.put("devicetype", "phone"); metaInfoAndroid.put("installurl", url); metaInfoAndroid.put("executeurl", "kakaoLinkTest://starActivity"); metaInfoArray.add(metaInfoAndroid); KakaoLink kakaoLink = KakaoLink.getLink(getActivity()); if (!kakaoLink.isAvailableIntent()) { return; } kakaoLink.openKakaoAppLink(getActivity(), "http://pctu1213.cafe24.com", memo, getActivity() .getPackageName(), getActivity().getPackageManager() .getPackageInfo(getActivity().getPackageName(), 0).versionName, subject, encoding, metaInfoArray); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: //리뷰 달기 if(StaticValue.TYPE == StaticValue.STORE_MARKET){ MarketLink(1); }else if(StaticValue.TYPE == StaticValue.STORE_TSOTRE){ TstoreLink(1); } break; case R.id.button2: dismiss(); break; case R.id.button3: // if(this.mDialogResultListner != null){ // this.mDialogResultListner.finish(); // } getActivity().finish(); break; // case R.id.button4: //친구 어플소개(카카오스토리) // if(StaticValue.TYPE == StaticValue.STORE_MARKET){ // MarketLink(2); // }else if(StaticValue.TYPE == StaticValue.STORE_TSOTRE){ // TstoreLink(2); // } // break; case R.id.button5: new kr.ds.popupView.PopupView(getActivity(), "N").init(); break; // case R.id.checkBox1: // if(mCheckBox.isChecked()){ // SharedPreference.putSharedPreference(getActivity(), "ch_dialog", true); // }else{ // SharedPreference.putSharedPreference(getActivity(), "ch_dialog", false); // } // break; default: break; } } }
package poc.ignite.controller; import java.util.Set; import java.util.TreeMap; import javax.annotation.PostConstruct; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.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 poc.ignite.domain.Person; import poc.ignite.repos.PersonRepository; @RequestMapping("/persons") @RestController public class PersonRestController { @Autowired private Ignite ignite; @Autowired private PersonRepository ps; private IgniteCache<Integer, Person> personCache; @PostConstruct private void postConstruct() { personCache = ignite.cache("person-cache"); } @GetMapping("/count") public Long count() { return ps.count(); } @GetMapping public Iterable<Person> findAll() { return ps.findAll(); } @GetMapping("/{id}") public Person findById(@PathVariable Integer id) { // Does not work. Not supported yet // return ps.findById(id).orElse(new Person(-1, "UNKNOWN")); return personCache.get(id); } @PostMapping public Person save(@RequestBody Person person) { return ps.save(person.getId(), person); } // Batch insert @PostMapping("/batch") public Iterable<Person> savePersons(@RequestBody TreeMap<Integer, Person> entities) { // personCache.putAll(entities); return ps.save(entities); } @DeleteMapping public String deleteAllById(@RequestBody Set<Integer> ids) { ps.deleteAll(ids); // personCache.removeAll(ids); return "Done"; } @DeleteMapping("/{id}") public boolean deleteById(@PathVariable Integer id) { return personCache.remove(id); } @PutMapping public Person updateAPerson(@RequestBody Person person) { return ps.save(person.getId(), person); } }
package com.team.vo; import java.util.List; import lombok.Data; @Data public class TaskList { private int listNo; private int projectNo; private String listName; private boolean deleted; private List<Task> tasks; }
package sort; public class RadixSort { public static void radixSort(int[] arr){ if(arr == null || arr.length < 2){ return; } } }
/* 1: */ package com.kaldin.setting.forgotpassword.hibernate; /* 2: */ /* 3: */ import com.kaldin.common.util.HibernateUtil; /* 4: */ import com.kaldin.setting.forgotpassword.dto.forgotPasswordDTO; /* 5: */ import com.kaldin.user.register.dto.CandidateDTO; /* 6: */ import com.kaldin.user.register.hibernate.CandidateHibernate; /* 7: */ import org.hibernate.HibernateException; /* 8: */ import org.hibernate.Session; /* 9: */ import org.hibernate.Transaction; /* 10: */ /* 11: */ public class ForgotPassHibernate /* 12: */ { /* 13: */ public String forgotUserPassword(forgotPasswordDTO forgotpassObj) /* 14: */ { /* 15:24 */ Transaction trObj = null; /* 16:25 */ Session sesObj = null; /* 17:26 */ CandidateHibernate canhiber = new CandidateHibernate(); /* 18:27 */ CandidateDTO dtoObj = new CandidateDTO(); /* 19:28 */ String password = null; /* 20:29 */ dtoObj.setUserId(forgotpassObj.getUserId()); /* 21: */ try /* 22: */ { /* 23:31 */ sesObj = HibernateUtil.getSession(); /* 24:32 */ trObj = HibernateUtil.getTrascation(sesObj); /* 25: */ /* 26: */ /* 27:35 */ password = canhiber.returnUserPassword(forgotpassObj.getUserId()); /* 28:36 */ trObj.commit(); /* 29: */ } /* 30: */ catch (HibernateException e) /* 31: */ { /* 32:39 */ trObj.rollback(); /* 33:40 */ e.printStackTrace(); /* 34: */ } /* 35: */ finally /* 36: */ { /* 37:42 */ sesObj.close(); /* 38: */ } /* 39:44 */ return password; /* 40: */ } /* 41: */ /* 42: */ public int getUserId(String email) /* 43: */ { /* 44:50 */ CandidateHibernate canhiber = new CandidateHibernate(); /* 45:51 */ int userid = canhiber.getForgotPasswordUserId(email); /* 46:52 */ return userid; /* 47: */ } /* 48: */ /* 49: */ public int getCompanyId(String email) /* 50: */ { /* 51:57 */ CandidateHibernate canhiber = new CandidateHibernate(); /* 52:58 */ int userid = canhiber.getForgotPasswordCompanyId(email); /* 53:59 */ return userid; /* 54: */ } /* 55: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.setting.forgotpassword.hibernate.ForgotPassHibernate * JD-Core Version: 0.7.0.1 */
package com.rockwellcollins.atc.limp.translate.basicblocks.lustre; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Type; import jkind.lustre.VarDecl; import com.rockwellcollins.atc.limp.translate.lustre.limp2lustre.LocalProcedureToLustre; /** * LustreBlocksToNodes accepts the first LustreBasicBlock in a linked-list of BasicBlocks and * translates them to a Lustre Node. * * Consider a LustreBasicBlock as shown below: * * LustreBasicBlock B1: * Equations: * x = a; * y = b; * * ConditionalExits: * if (x > 0) then B2 * if (y < 0) then B3 * * UnconditionalExit: * B4 * * This will get translated into the following Lustre node (where a and b are inputs) * * node basicBlock_B1(a : int, b : int) returns (x : int, y : int) * let * x = a; * y = b; * tel; * * The ConditionalExits are handled at on the main node which is described in LocalProcedureToMainNode.java * */ public class LustreBlocksToNodes { private static final String propSuffix = "_prop"; public static List<Node> generateNodes(LocalProcedureToLustre p2l) { LustreBlocksToNodes blocksToNodes = new LustreBlocksToNodes(p2l); blocksToNodes.translate(p2l.firstBlock); return new ArrayList<>(blocksToNodes.map.values()); } private Map<LustreBasicBlock,Node> map = new LinkedHashMap<>(); private LocalProcedureToLustre procToLustre; public LustreBlocksToNodes(LocalProcedureToLustre p2l) { this.procToLustre=p2l; } private void translate(LustreBasicBlock block) { if(map.containsKey(block)) { return; } List<VarDecl> inputs = new ArrayList<>(); List<VarDecl> locals = new ArrayList<>(); List<VarDecl> outputs = new ArrayList<>(); List<String> properties = new ArrayList<>(); List<Expr> assertions = new ArrayList<>(); List<Equation> equations = new ArrayList<>(); //these are used to collect the equation Ids of pre and post conditions; List<String> preIds = new ArrayList<>(); List<String> postIds = new ArrayList<>(); inputs.add(new VarDecl(block.triggerId, NamedType.BOOL)); if(!procToLustre.state.isEmpty()) { inputs.add(new VarDecl(block.stateInputId, new NamedType(procToLustre.getStateRecordType().id))); outputs.add(new VarDecl(block.stateOutputId, new NamedType(procToLustre.getStateRecordType().id))); } if(!procToLustre.limpToLustre.globals.isEmpty()) { inputs.add(new VarDecl(block.globalInputId, new NamedType(procToLustre.getGlobalRecordType().id))); outputs.add(new VarDecl(block.globalOutputId, new NamedType(procToLustre.getGlobalRecordType().id))); } Map<String,Type> generatedLocals = block.generatedLocals; for(String key : generatedLocals.keySet()) { locals.add(new VarDecl(key,generatedLocals.get(key))); } outputs.add(new VarDecl(block.preconditionId, NamedType.BOOL)); outputs.add(new VarDecl(block.postconditionId, NamedType.BOOL)); //our equations are right from the block on the previous SSA pass for(ExtendedEquation eeq : block.equations) { for(LustrePrecondition lpre : eeq.preconditions) { locals.add(new VarDecl(lpre.name, NamedType.BOOL)); equations.add(lpre.toEquation()); String propertyId = block.getUniqueID(lpre.name + propSuffix); Equation eq = new Equation(new IdExpr(propertyId), generatePreconditionExpr(block.triggerId,lpre.name)); equations.add(eq); preIds.add(propertyId); locals.add(new VarDecl(propertyId, NamedType.BOOL)); properties.add(propertyId); } equations.addAll(eeq.globalReferences); equations.add(eeq.equation); equations.addAll(eeq.globalAssignments); for(LustrePostcondition lpost : eeq.postconditions) { locals.add(new VarDecl(lpost.name, NamedType.BOOL)); equations.add(lpost.toEquation()); postIds.add(lpost.name); } } equations.add(new Equation(new IdExpr(block.preconditionId), generateAccumulatedExpr(preIds.iterator()))); equations.add(new Equation(new IdExpr(block.postconditionId), generateAccumulatedExpr(postIds.iterator()))); Node n = new Node(block.nodeName,inputs,outputs,locals,equations,properties,assertions); map.put(block, n); for(LustreBlockEdge lbe : block.conditionalExits) { this.translate(lbe.getDestination()); } if(block.unconditionalExit != null) { this.translate(block.unconditionalExit.getDestination()); } } private Expr generatePreconditionExpr(String triggerId, String name) { return new BinaryExpr(new IdExpr(triggerId), BinaryOp.IMPLIES, new IdExpr(name)); } private Expr generateAccumulatedExpr(Iterator<String> it) { if(it.hasNext()) { String next = it.next(); return new BinaryExpr(new IdExpr(next), BinaryOp.AND, generateAccumulatedExpr(it)); } else { return new BoolExpr(true); } } }
package org.hpe.dnslog; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.common.serialization.Serializer; public class DNSLogDESER implements Serializer<DNSLogEntry>, Deserializer<DNSLogEntry> { @Override public void configure(Map<String, ?> configs, boolean isKey) { // TODO Auto-generated method stub } @Override public DNSLogEntry deserialize(String topic, byte[] data) { ObjectMapper mapper = new ObjectMapper(); DNSLogEntry dnsLogEntry = null; try { dnsLogEntry = mapper.readValue(data, DNSLogEntry.class); } catch (Exception e) { e.printStackTrace(); } return dnsLogEntry; } @Override public byte[] serialize(String topic, DNSLogEntry data) { byte[] result = null; ObjectMapper objectMapper = new ObjectMapper(); try { result = objectMapper.writeValueAsString(data).getBytes(); } catch (Exception e) { e.printStackTrace(); } return result; } @Override public void close() { // TODO Auto-generated method stub } }
/** * */ package game.ui.handler; import game.commands.AbstractCommand; import game.commands.RemoveArrowCommand; import game.commands.RemoveGrayedCommand; import game.commands.RemoveStarCommand; import game.commands.SetArrowDownCommand; import game.commands.SetArrowDownLeft; import game.commands.SetArrowDownRightCommand; import game.commands.SetArrowLeftCommand; import game.commands.SetArrowRightCommand; import game.commands.SetArrowUpCommand; import game.commands.SetArrowUpLeftCommand; import game.commands.SetArrowUpRightCommand; import game.commands.SetGrayedCommand; import game.commands.SetStarCommand; import game.core.GamePreferences.HelpMode; import game.core.GamePreferences.LinealMode; import game.model.Field; import game.model.Field.AllowedContent; import game.model.Starfield; import game.ui.EditToolbar; import game.ui.MainWindow; import game.ui.PlayToolbar; import game.ui.StatusBar; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashSet; import java.util.Set; import javax.swing.JToolBar; import javax.swing.border.LineBorder; /** * Der StarfieldViewHandler reagiert auf UserEvents auf dem Starfield. <br> * Bei einem Mausklick auf dem Spielfeld werden hier die entsprechenden Commands * ausgelöst. * * @author Jan * */ public class StarfieldViewHandler implements MouseListener { // Border für MouseEntered LineBorder blackBorder = new LineBorder(Color.BLACK, 1); LineBorder linealBorder = new LineBorder(Color.BLUE, 1); LineBorder helpBorder = new LineBorder(Color.GREEN, 1); LineBorder redLightBorder = new LineBorder(new Color(200, 95, 95), 1); // Border für MouseExited LineBorder whiteBorder = new LineBorder(Color.WHITE, 1); LineBorder redBorder = new LineBorder(Color.RED, 1); @Override public void mouseClicked(MouseEvent pE) { } @Override public void mouseEntered(MouseEvent pE) { Object o = pE.getSource(); if (o instanceof Field) { Field selField = (Field) o; Starfield starfield = MainWindow.getInstance() .getCurrentStarfield(); if (starfield == null) return; JToolBar toolbar = MainWindow.getInstance().getActiveToolBar(); Set<Field> shownErrorFields = null; if (toolbar instanceof EditToolbar) shownErrorFields = ((EditToolbar) toolbar).getErrorFields(); // Gibts keine Fehlerfelder wird einfach ein leeres erstellt if (shownErrorFields == null) shownErrorFields = new HashSet<Field>(); if (MainWindow.getInstance().getGamePrefs().getLinealMode() != LinealMode.NO) { // Selektiertes Feld mit schwarzem Hintergrund setzen if (shownErrorFields.contains(selField)) selField.setBorder(new LineBorder(new Color(240, 75, 75), 1)); else selField.setBorder(blackBorder); // Alle Felder nach oben grau umranden Field nextField = selField; while ((nextField = starfield.getField_U(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach unten umranden nextField = selField; while ((nextField = starfield.getField_D(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach links umranden nextField = selField; while ((nextField = starfield.getField_L(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach rechts umranden nextField = selField; while ((nextField = starfield.getField_R(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // Zusätzlich wenn STAR ausgewählt if (MainWindow.getInstance().getGamePrefs().getLinealMode() == LinealMode.STAR) { // ALle Felder nach links oben umranden nextField = selField; while ((nextField = starfield.getField_UL(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach links unten umranden nextField = selField; while ((nextField = starfield.getField_DL(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach rechts oben umranden nextField = selField; while ((nextField = starfield.getField_UR(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } // ALle Felder nach rechts unten umranden nextField = selField; while ((nextField = starfield.getField_DR(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redLightBorder); else nextField.setBorder(linealBorder); } } } if (MainWindow.getInstance().getGamePrefs().getHelpMode() == HelpMode.ON) { switch (selField.getUserContent()) { case CONTENT_STAR: // Im Falle eines Sterns müssen alle Felder auf Pfeile // durchsucht werden, die in Richtung des Sterns zeigen highlightArrows(selField, starfield); break; case CONTENT_EMPTY: case CONTENT_GRAYED: // Diese Felder brauchen nicht gesondert beachtet werden break; default: // Die Übrigbleibenden Felder sind Felder mit Pfeilen drin, // hier werden die Felder gehighlightet auf die der Pfeil // zeigt. highlightLane(selField, starfield); break; } } } } private void highlightArrows(Field selField, Starfield starfield) { // Felder nach oben durchsuchen Field nextField = selField; while ((nextField = starfield.getField_U(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_D) { nextField.setBorder(helpBorder); } } // Felder nach oben-rechts durchsuchen nextField = selField; while ((nextField = starfield.getField_UR(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_DL) { nextField.setBorder(helpBorder); } } // Felder nach rechts durchsuchen nextField = selField; while ((nextField = starfield.getField_R(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_L) { nextField.setBorder(helpBorder); } } // Felder nach unten-rechts durchsuchen nextField = selField; while ((nextField = starfield.getField_DR(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_UL) { nextField.setBorder(helpBorder); } } // Felder nach unten durchsuchen nextField = selField; while ((nextField = starfield.getField_D(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_U) { nextField.setBorder(helpBorder); } } // Felder nach unten-links durchsuchen nextField = selField; while ((nextField = starfield.getField_DL(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_UR) { nextField.setBorder(helpBorder); } } // Felder nach links durchsuchen nextField = selField; while ((nextField = starfield.getField_L(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_R) { nextField.setBorder(helpBorder); } } // Felder nach oben-links durchsuchen nextField = selField; while ((nextField = starfield.getField_UL(nextField)) != null) { if (nextField.getUserContent() == AllowedContent.CONTENT_ARROW_DR) { nextField.setBorder(helpBorder); } } } private void highlightLane(Field selField, Starfield starfield) { // Nach der Art des Pfeils werden alle Zellen in der Richtung // gekennzeichnet Field nextField; switch (selField.getUserContent()) { case CONTENT_ARROW_U: nextField = selField; while ((nextField = starfield.getField_U(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_UR: nextField = selField; while ((nextField = starfield.getField_UR(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_R: nextField = selField; while ((nextField = starfield.getField_R(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_DR: nextField = selField; while ((nextField = starfield.getField_DR(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_D: nextField = selField; while ((nextField = starfield.getField_D(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_DL: nextField = selField; while ((nextField = starfield.getField_DL(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_L: nextField = selField; while ((nextField = starfield.getField_L(nextField)) != null) { nextField.setBorder(helpBorder); } break; case CONTENT_ARROW_UL: nextField = selField; while ((nextField = starfield.getField_UL(nextField)) != null) { nextField.setBorder(helpBorder); } break; default: return; } } @Override public void mouseExited(MouseEvent pE) { Object o = pE.getSource(); if (o instanceof Field) { Field selField = (Field) o; Starfield starfield = MainWindow.getInstance() .getCurrentStarfield(); if (starfield == null) return; JToolBar toolbar = MainWindow.getInstance().getActiveToolBar(); Set<Field> shownErrorFields = null; if (toolbar instanceof EditToolbar) shownErrorFields = ((EditToolbar) toolbar).getErrorFields(); // Gibts keine Fehlerfelder wird einfach ein leeres erstellt if (shownErrorFields == null) shownErrorFields = new HashSet<Field>(); if (MainWindow.getInstance().getGamePrefs().getLinealMode() != LinealMode.NO) { // Selektiertes Feld Umrandung löschen if (shownErrorFields.contains(selField)) selField.setBorder(redBorder); else selField.setBorder(whiteBorder); // Alle Felder nach oben Umrandung wegmachen Field nextField = selField; while ((nextField = starfield.getField_U(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // Alle Felder nach unten Umrandung wegmachen nextField = selField; while ((nextField = starfield.getField_D(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // Alle Felder nach links Umrandung wegmachen nextField = selField; while ((nextField = starfield.getField_L(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // Alle Felder nach rechts Umrandung wegmachen nextField = selField; while ((nextField = starfield.getField_R(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // Zusätzlich wenn STAR ausgewählt if (MainWindow.getInstance().getGamePrefs().getLinealMode() == LinealMode.STAR) { // ALle Felder nach links oben umranden nextField = selField; while ((nextField = starfield.getField_UL(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // ALle Felder nach links unten umranden nextField = selField; while ((nextField = starfield.getField_DL(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // ALle Felder nach rechts oben umranden nextField = selField; while ((nextField = starfield.getField_UR(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } // ALle Felder nach rechts unten umranden nextField = selField; while ((nextField = starfield.getField_DR(nextField)) != null) { if (shownErrorFields.contains(nextField)) nextField.setBorder(redBorder); else nextField.setBorder(whiteBorder); } } } if (MainWindow.getInstance().getGamePrefs().getHelpMode() == HelpMode.ON) { // Alle Felder werden durchlaufen, hat ein Feld einen Rand vom // HelpModus so wird der alte Rand wieder gesetzt for (int x = 0; x < starfield.getSize().width; x++) { for (int y = 0; y < starfield.getSize().height; y++) { final Field f = starfield.getField(x, y); if (f.getBorder() == helpBorder) { if (shownErrorFields.contains(f)) f.setBorder(redBorder); else f.setBorder(whiteBorder); } } } } } } @Override public void mousePressed(MouseEvent pE) { Object o = pE.getSource(); // Zur Sicherheit wird überprüft ob das aufrufende Element ein Field von // unserem Modell ist if (o instanceof game.model.Field) { // Es wird ein leeres Command erstellt, das im folgenden mit dem // passenden Command gefüllt wird. AbstractCommand command = null; // Abhängig von der AppMode wird das passende Command festgelegt switch (MainWindow.getInstance().getGamePrefs().getAppMode()) { case GAME_MODE: case LOAD_GAME_MODE: command = handlePlayEvent((Field) o, pE); break; case EDIT_MODE: case LOAD_EDIT_MODE: command = handleEditEvent((Field) o, pE); break; default: break; } // Ist das passende Command zur gewünschten Aktion ermittelt worden, // kann es ausgeführt werden. if (command != null) { command.execute(); // Gibt es eine Statusbar, werden die SpielerAktionen // aktualisiert o = MainWindow.getInstance().getStatusBar(); if (o instanceof StatusBar) ((StatusBar) o).increaseMove(); // Im Spielmodus wird überprüft ob das Spiel gewonnen ist o = MainWindow.getInstance().getActiveToolBar(); if (o instanceof PlayToolbar) { ((PlayToolbar) o).get_playHandler().checkInput(); } // Im Editmodus wird überprüft, ob das Spielfeld lösbar ist if (o instanceof EditToolbar) ((EditToolbar) o).setPlayable(MainWindow.getInstance() .getCurrentStarfield().checkPlayable().size() == 0, true); MainWindow.getInstance().getCommandStack().setStackChange(true); } } } /** * Bestimmt welches Command im GameMode ausgeführt werden muss * * @return */ private AbstractCommand handlePlayEvent(Field field, MouseEvent pE) { if (pE.getButton() == MouseEvent.BUTTON1) { if (field.getUserContent() == AllowedContent.CONTENT_EMPTY) return new SetStarCommand(MainWindow.getInstance() .getCommandStack(), pE); else if (field.getUserContent() == AllowedContent.CONTENT_STAR) return new RemoveStarCommand(MainWindow.getInstance() .getCommandStack(), pE); } if (pE.getButton() == MouseEvent.BUTTON3) { if (field.getUserContent() == AllowedContent.CONTENT_EMPTY) return new SetGrayedCommand(MainWindow.getInstance() .getCommandStack(), pE); else if (field.getUserContent() == AllowedContent.CONTENT_GRAYED) return new RemoveGrayedCommand(MainWindow.getInstance() .getCommandStack(), pE); } return null; } /** * Bestimmt welches Command im EditMode ausgeführt werden soll * * @param field * @param pE * @return */ private AbstractCommand handleEditEvent(Field field, MouseEvent pE) { Object o = MainWindow.getInstance().getActiveToolBar(); if (o instanceof EditToolbar) { EditToolbar toolbar = (EditToolbar) o; // Linke Maustaste if (pE.getButton() == MouseEvent.BUTTON1) { if (field.getUserContent() == AllowedContent.CONTENT_EMPTY) { return new SetStarCommand(MainWindow.getInstance() .getCommandStack(), pE); } else if (field.getUserContent() == AllowedContent.CONTENT_STAR) { return new RemoveStarCommand(MainWindow.getInstance() .getCommandStack(), pE); } } // Rechte Maustaste if (pE.getButton() == MouseEvent.BUTTON3) { // Überprüfen ob das Leerfeld ausgewählt ist if (toolbar.getSelectedArrow() == AllowedContent.CONTENT_EMPTY) { if (field.getUserContent().toString() .startsWith("CONTENT_ARROW")) { return new RemoveArrowCommand(MainWindow.getInstance() .getCommandStack(), pE); } } // Überprüfen ob im field ein anderer Pfeil ist, als ausgewählt // wurde if (field.getUserContent() != toolbar.getSelectedArrow() && field.getUserContent() != AllowedContent.CONTENT_STAR) { switch (toolbar.getSelectedArrow()) { case CONTENT_ARROW_UL: return new SetArrowUpLeftCommand(MainWindow .getInstance().getCommandStack(), pE); case CONTENT_ARROW_U: return new SetArrowUpCommand(MainWindow.getInstance() .getCommandStack(), pE); case CONTENT_ARROW_UR: return new SetArrowUpRightCommand(MainWindow .getInstance().getCommandStack(), pE); case CONTENT_ARROW_L: return new SetArrowLeftCommand(MainWindow.getInstance() .getCommandStack(), pE); case CONTENT_ARROW_R: return new SetArrowRightCommand(MainWindow .getInstance().getCommandStack(), pE); case CONTENT_ARROW_DL: return new SetArrowDownLeft(MainWindow.getInstance() .getCommandStack(), pE); case CONTENT_ARROW_D: return new SetArrowDownCommand(MainWindow.getInstance() .getCommandStack(), pE); case CONTENT_ARROW_DR: return new SetArrowDownRightCommand(MainWindow .getInstance().getCommandStack(), pE); default: break; } } else if (field.getUserContent() != AllowedContent.CONTENT_STAR) return new RemoveArrowCommand(MainWindow.getInstance() .getCommandStack(), pE); } } return null; } @Override public void mouseReleased(MouseEvent pE) { } }