text stringlengths 10 2.72M |
|---|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.client.config.interceptors;
import de.hybris.platform.servicelayer.interceptor.InitDefaultsInterceptor;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import java.util.Date;
import org.apache.log4j.Logger;
import com.cnk.travelogix.client.config.core.model.MLMDistributionModel;
/**
* To set effective date as current date by default.
*/
public class MLMDistributionInitDefaultInterceptor implements InitDefaultsInterceptor<MLMDistributionModel>
{
private static final Logger LOG = Logger.getLogger(MLMDistributionInitDefaultInterceptor.class.getName());
@Override
public void onInitDefaults(final MLMDistributionModel mlmDistributionModel, final InterceptorContext ctx)
throws InterceptorException
{
LOG.debug("Entering onInitDefaults() of MLMDistributionInitDefaultInterceptor");
mlmDistributionModel.setEffectiveFrom(new Date());
LOG.debug("Exit onInitDefaults() of MLMDistributionInitDefaultInterceptor");
}
}
|
package mg.egg.eggc.compiler.libegg.base;
public class BLOC {
private TDS_ACTION locales;
public TDS_ACTION getLocs() {
return locales;
}
private BLOC frere;
public BLOC getFrere() {
return frere;
}
public void setFrere(BLOC f) {
frere = f;
}
public BLOC(TDS_ACTION t) {
locales = new TDS_ACTION(t);
frere = null;
}
}
|
package com.ybg.base.jdbc;
import java.util.LinkedHashMap;
/** 改进的LinkedHashMap <br>
* put 元素取消 value为null的集合 **/
public class BaseMap<K, V> extends LinkedHashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
/** 当value 为空时,不加入集合中 **/
@SuppressWarnings("unchecked")
@Override
public V put(K key, V value) {
key = (K) key.toString().toLowerCase();
if (key != null && value != null) {
super.put(key, value);
}
return null;
}
}
|
package com.example.bratwurst.service;
import com.amazonaws.services.sns.AmazonSNS;
import com.example.bratwurst.model.FriendsViewModel;
import com.example.bratwurst.model.User;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface UserService {
boolean validateAuthCode(int inputCode);
void publishMessage(String email) throws JSONException;
void subscribeToTopic(String email) throws JSONException;
void setPolicyFilter(String email) throws JSONException;
User getLogin(String username, String password);
List<FriendsViewModel> getUsers(int id);
User addUser(User user, String confirm_password);
boolean passwordStrong(String password);
User getUserById(int id);
void friendRequest(int userId, int receiverId);
List<User> notifications(int id);
void acceptRequest(int receiverId, int userId);
boolean isAdmin(User user);
void deleteById(int id);
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.sync;
import org.chromium.base.ThreadUtils;
/**
* Starts up the sync backend and notifies the caller once the backend finishes
* initializing or if the backend fails to start up.
*/
public class SyncStartupHelper implements ProfileSyncService.SyncStateChangedListener {
private static final String TAG = "SyncStartupHelper";
private final ProfileSyncService mProfileSyncService;
private final Delegate mDelegate;
private boolean mDestroyed;
/**
* Callback interface for SyncStartupHelper.
*/
public interface Delegate {
// Invoked once the sync backend has successfully started up.
public void startupComplete();
// Invoked if the sync backend failed to start up.
public void startupFailed();
}
public SyncStartupHelper(ProfileSyncService profileSyncService, Delegate delegate) {
ThreadUtils.assertOnUiThread();
mProfileSyncService = profileSyncService;
mDelegate = delegate;
assert mDelegate != null;
}
public void startSync() {
ThreadUtils.assertOnUiThread();
assert !mDestroyed;
if (mProfileSyncService.isSyncInitialized()) {
// Sync is already initialized - notify the delegate.
mDelegate.startupComplete();
} else {
// Tell the sync engine to start up.
mProfileSyncService.syncSignIn();
mProfileSyncService.addSyncStateChangedListener(SyncStartupHelper.this);
syncStateChanged();
}
}
public void destroy() {
ThreadUtils.assertOnUiThread();
mProfileSyncService.removeSyncStateChangedListener(this);
mDestroyed = true;
}
@Override
public void syncStateChanged() {
if (mProfileSyncService.isSyncInitialized()) {
mDelegate.startupComplete();
} else if ((mProfileSyncService.getAuthError() != GoogleServiceAuthError.State.NONE)
|| mProfileSyncService.hasUnrecoverableError()) {
mDelegate.startupFailed();
}
}
}
|
import java.util.Scanner;
public class RectangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sideA = scanner.nextInt();
int sideB = scanner.nextInt();
System.out.println(calculateArea(sideA,sideB));
}
private static int calculateArea(int a, int b) {
return a * b;
}
}
|
package com.funlib.http.download;
/**
* 下载进度,状态,监听
*
* @author taojianli
*
*/
public interface DownloadListener {
/**
* 下载状态改变
* @param tag TODO
* @param index 下载任务的索引
* @param status
* @param filePath
* 文件保存路径
*/
public void onDownloadStatusChanged(Object tag , int index, int status , int percent, String filePath);
}
|
package com.smxknife.java2.thread.semaphore.demo07;
/**
* @author smxknife
* 2018-12-22
*/
public class ThreadP extends AbsThread {
public ThreadP(RepastService service) {
super(service);
}
@Override
public void exe() {
service.set();
}
}
|
package com.muryang.sureforprice.vo;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* This class is POJO representing tbl_category table.
* @author Ethan Cha
* @date Apr 10, 2014
*
*/
public class Category {
private String id ;
private String parentId ;
private Integer depth ;
private String name ;
private Integer dispOrder ;
private Date lastUpdatedDate ;
private String lastUpdateUser ;
private Long lastUpdateTx ;
private Date expiryDate ;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Integer getDispOrder() {
return dispOrder;
}
public void setDispOrder(Integer dispOrder) {
this.dispOrder = dispOrder;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdateUser() {
return lastUpdateUser;
}
public void setLastUpdateUser(String lastUpdateUser) {
this.lastUpdateUser = lastUpdateUser;
}
public Long getLastUpdateTx() {
return lastUpdateTx;
}
public void setLastUpdateTx(Long lastUpdateTx) {
this.lastUpdateTx = lastUpdateTx;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
}
|
int main() {
int[] a;
a = new int[0];
printInt(a.length);
return 0;
} |
package com.meridal.example.mastodon.mvc;
import com.meridal.example.mastodon.domain.UserProfile;
import com.meridal.example.mastodon.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Users", description = "The Twitter User Profile API")
@RestController
@RequestMapping("/api/user")
public class UserController {
private final UserService service;
public UserController(@Autowired final UserService service) {
this.service = service;
}
@Operation(summary = "Get a user profile by user name")
@GetMapping("/{username}")
public UserProfile getUserProfile(@PathVariable final String username) {
return this.service.getUserProfile(username);
}
@Operation(summary = "Get a user profile in CSV format by user name")
@GetMapping("/{username}/csv")
public String getUserProfileAsCSV(@PathVariable final String username) {
return this.service.getUserProfileAsCSV(username);
}
}
|
package algo_basic.day5;
import java.util.Arrays;
public class P233_Nqueen {
private static int size =15;
private static int[][] map = new int[size][size];
public static void dfsBacktracking(int row) {
if(row==size) {
//끝까지 도달 --> 상태 확인
for(int[] line: map) {
System.out.println(Arrays.toString(line));
}
System.out.println();
System.out.println("배치 가능하다!");
System.exit(0);
return;
}else {
for (int c = 0; c < size; c++) {
map[row][c] = 1;
if(isPromisingBacktracking(row, c)) {
dfsBacktracking(row+1);
}
map[row][c] = 0;
}
}
}
// 맨 마지막 까지 돌을 놧으니 이제 이 행동이 적합한지 확인하는 메소드
public static boolean isPromisingBacktracking(int row, int col) {
// 위로 쭉 가면서 수직위와 대각선으로 체크
for (int k = 1; k <= row; k++) {
if(map[row-k][col]==1) {
return false;
}
if(col-k >=0 && map[row-k][col-k]==1) { // 범위 안에 있으면서 대각선이 1인경우
return false;
}
if(col+k <size && map[row-k][col+k]==1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
dfsBacktracking(0);
}
}
|
package com.cse308.sbuify.test;
import com.cse308.sbuify.album.Album;
import com.cse308.sbuify.test.helper.AuthenticatedTest;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class AlbumControllerTest extends AuthenticatedTest {
private final static int NUM_NEW_RELEASES = 30; // todo: make configurable with @ConfigurationProperties
/**
* Test: getting new releases.
*/
@Test
public void getNewReleases() {
Map<String, String> params = new HashMap<>();
params.put("page", "0");
ResponseEntity<ArrayList<Album>> response = restTemplate.exchange("/api/albums/new-releases?page={page}",
HttpMethod.GET, null, new ParameterizedTypeReference<ArrayList<Album>>() {}, params);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(NUM_NEW_RELEASES, response.getBody().size());
}
@Override
public String getEmail() {
return "sbuify+b@gmail.com";
}
@Override
public String getPassword() {
return "b";
}
} |
package com.tingke.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tingke.admin.entity.FrBook;
import com.tingke.admin.exection.CastDiyException;
import com.tingke.admin.mapper.FrBookMapper;
import com.tingke.admin.model.CommonCode;
import com.tingke.admin.model.QueryResponseResultList;
import com.tingke.admin.model.R;
import com.tingke.admin.service.FrBookService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 服务实现类
* </p>
*
* @author zhx
* @since 2020-05-30
*/
@Service
public class FrBookServiceImpl extends ServiceImpl<FrBookMapper, FrBook> implements FrBookService {
//推荐书籍显示
@Override
public R selectBookById(String id) {
if(StringUtils.isEmpty(id)){
CastDiyException.cast(CommonCode.INVALID_PARAM);
}
FrBook frBook = this.getById(id);
if (frBook == null){
CastDiyException.cast(CommonCode.FAIL);
}
return new R(CommonCode.SUCCESS,frBook);
}
//推荐书籍添加
@Override
@Transactional
public R addBook(FrBook frBook) {
if (frBook == null){
CastDiyException.cast(CommonCode.INVALID_PARAM);
}
boolean save = this.save(frBook);
if (!save){
CastDiyException.cast(CommonCode.FAIL);
}
return new R(CommonCode.SUCCESS,frBook);
}
//推荐书籍修改
@Override
@Transactional
public R editBook(FrBook frBook) {
if (frBook == null || StringUtils.isEmpty(frBook.getId())){
CastDiyException.cast(CommonCode.INVALID_PARAM);
}
boolean success = this.updateById(frBook);
if (!success){
CastDiyException.cast(CommonCode.FAIL);
}
return new R(CommonCode.SUCCESS, (QueryResponseResultList) null);
}
//推荐书籍删除
@Override
@Transactional
public R deleteBook(String id) {
if(StringUtils.isEmpty(id)){
CastDiyException.cast(CommonCode.INVALID_PARAM);
}
boolean success = this.removeById(id);
if (!success){
CastDiyException.cast(CommonCode.FAIL);
}
return new R(CommonCode.SUCCESS, (QueryResponseResultList) null);
}
@Override
public R selectPageBook(Long page, Long limit, String condition) {
if (StringUtils.isEmpty(page.toString()) || StringUtils.isEmpty(limit.toString())){
CastDiyException.cast(CommonCode.INVALID_PARAM);
}
//构建分页
Page<FrBook> spage = new Page<>(page, limit);
QueryWrapper<FrBook> wrapper = new QueryWrapper<>();
if (StringUtils.isNoneBlank(condition)){
wrapper.like("title",condition);
}
Page<FrBook> ipage = this.page(spage,wrapper);
if (ipage == null){
CastDiyException.cast(CommonCode.FAIL);
}
QueryResponseResultList queryResponseResultList = new QueryResponseResultList();
queryResponseResultList.setTotal((int) spage.getTotal());
queryResponseResultList.setList(spage.getRecords());
return new R(CommonCode.SUCCESS,queryResponseResultList);
}
}
|
package eiti.sag.facebookcrawler.visitor;
import eiti.sag.facebookcrawler.model.FacebookUser;
public interface FacebookUserVisitor {
boolean shouldVisit(String username);
void visit(FacebookUser user);
void onFetchUserFailed(String username, Exception e);
}
|
package example.api.v1;
public class HealthStatusUtils {
static public boolean isUp(HealthStatus healthStatus) {
if ( healthStatus.getStatus() != null && healthStatus.getStatus().compareToIgnoreCase("UP") == 0) {
return true;
}
return false;
}
}
|
/**
*
*/
package restaurante;
import java.io.Serializable;
import java.util.Comparator;
/**
* @author Gabriel Alves
* @author Joao Carlos
* @author Melissa Diniz
* @author Thais Nicoly
*/
public class OrdenaPorNome implements Comparator<Object>,Serializable{
private static final long serialVersionUID = 1L;
/**
* Compara refeicoes pelo nome
*/
@Override
public int compare(Object refeicao1, Object refeicao2) {
return ((TiposDeRefeicoes) refeicao1).getNome().compareTo(((TiposDeRefeicoes) refeicao2).getNome());
}
}
|
package planit_poc.helpers;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class PageObject {
// The default framework timeout is 60 seconds.
public int defaultTimeout = 60;
protected WebDriver driver;
public PageObject(WebDriver driver) {
this.driver = driver;
}
public boolean waitForEnabled(WebElement element) {
return this.waitForEnabled(element, defaultTimeout);
}
public boolean waitForEnabled(WebElement element, int timeout)
{
//String message = "Wait for element selected " + by.toString() + " to be enabled.";
try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.elementToBeClickable(element));
return true;
} catch (Throwable t) {
String error = "waitForClickable: Element selected by " + element.toString() + " is not enabled after "
+ Integer.toString(timeout) + " second(s).";
}
return false;
}
public boolean waitForVisible(By by, int timeout) throws Exception
{
String message = "[waitForVisible] Wait for element selected " + by.toString() + " to be visible.";
try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOfElementLocated(by));
return true;
} catch (Throwable t) {
String error = "waitForVisible: Element selected by " + by.toString() + " is not visible after "
+ Integer.toString(timeout) + " second(s).";
throw new Exception(message);
//return false;
}
}
public boolean checkVisible(WebElement element) {
return this.checkVisible(element, defaultTimeout);
}
public boolean checkVisible(WebElement element, int timeout) {
try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOf(element));
return true;
} catch (Throwable t) {
return false;
}
}
public void assertExists(String element) {
this.assertExists(element, defaultTimeout);
}
public void assertExists(String element, int timeout) {
String message = "[assertExists] Assert that the element selected by '" + element.toString() + "' exists on screen";
try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.presenceOfElementLocated(By.xpath(element)));
} catch (TimeoutException t) {
String error = "assertExists: Element selected by " + element.toString() + " could not be found on screen.";
throw new RuntimeException(error);
}
}
//TODO check
public String replaceWithValue(String actual,String... parameters) {
for(String parameter : parameters) {
actual=actual.replaceFirst("\\?", parameter);
}
return actual;
}
}
|
package interfaceTest;
public class Phone implements Phoneinterface {
@Override
public void contract(int con) {
System.out.println("약정을 했다");
}
@Override
public void Performance(String per) {
System.out.println("성능이 좋다");
}
@Override
public void Kinds(String kin) {
System.out.println("아이폰13을 샀다");
}
}
|
package nl.funda.uitests;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.LogStatus;
import nl.funda.uitests.base.BaseTest;
import nl.funda.uitests.base.CsvDataProvider;
import nl.funda.uitests.pages.ResultsPage;
import nl.funda.uitests.pages.SearchPage;
public class SearchAmsterdam extends BaseTest {
@Test(dataProvider = "CsvDataProvider", dataProviderClass = CsvDataProvider.class)
public void searchAmsterdam(Map<String, String> testData) {
// Inject details from scr/test/resources/test_data/SearchData.csv
String testNumber = testData.get("no");
String description = testData.get("description");
String filterLocation = testData.get("filterLocation");
String filterDistance = testData.get("filterDistance");
String fromPrice = testData.get("fromPrice");
String toPrice = testData.get("toPrice");
String resultsText = "resultaten";
String fiterCountNumber = "6";
SearchPage searchPage = new SearchPage(driver);
ResultsPage resultsPage = new ResultsPage(driver);
logger.log(LogStatus.INFO, "Started Test No #" + testNumber + " for " + description);
// Starting the script
searchPage.clickForRentButton();
searchPage.addSearchDetails(filterLocation, filterDistance, fromPrice, toPrice);
searchPage.clickSearchButton();
resultsPage.waitForResultsPageToLoad();
// Check if the search returned any results
String checkResults = resultsPage.getResultsText();
Assert.assertTrue(checkResults.contains(resultsText), "This page did not returned any results: " + resultsText + "\nActual: " + "" + checkResults + ".");
captureScreenshot(driver, "005-ForRentSearchResults");
resultsPage.tickNoRentalFeeRadioButton();
resultsPage.tickIndefiniteRadioButtonRadioButton();
resultsPage.tickAvailableImmediatelyRadioButton();
resultsPage.tickApartmentRadioButton();
resultsPage.tickTwoRoomsRadioButton();
resultsPage.tickFloorArea50sqm_RadioButton();
resultsPage.tickNewConstructionRadioButton();
resultsPage.tickAvailableRadioButton();
resultsPage.scrollIntoViewLocationTextbox();
// Check if the expected filters are actually applied on the resultsPage
String checkFilterCount = resultsPage.getFiterCountNumber();
Assert.assertTrue(checkFilterCount.contains(fiterCountNumber),
"Expected number of filters to be applied : " + fiterCountNumber + "\nActual: " + "" + checkFilterCount + ".");
captureScreenshot(driver, "006-ForRentSearchResults-Filtered");
resultsPage.clickFundaLogo();
}
}
|
package com.itractor.thread;
import android.os.Environment;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
/**
* Questa classe gestisce la scrittura su file esterno
* @autor Mark Tex
* @since 2014
*/
public class WriteInfo
{
FileWriter txOut, rxOut, fOut;
// costruttore di default definisce gli attributi sopra
public void writeInLog(boolean append, String line) throws IOException
{
try
{
fOut = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/Log.txt", append);
fOut.write(line);
fOut.flush();
fOut.close();
}
catch (IOException e)
{
throw new IOException("Scrittura RESET non eseguita");
}
}
public void writeInTx(boolean append, String line) throws IOException
{
try
{
txOut = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/tx_time.txt", append);
txOut.write(line);
txOut.flush();
txOut.close();
}
catch(IOException e)
{
throw new IOException("errore nella scrittura su TX");
}
}
public void writeInRx(boolean append, String line) throws IOException
{
try
{
rxOut = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/rx_time.txt", append);
rxOut.write(line);
rxOut.flush();
rxOut.close();
}
catch(IOException e)
{
throw new IOException("errore nella scrittura su RX");
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.pagescontentslots.impl;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.cms2.model.contents.contentslot.ContentSlotModel;
import de.hybris.platform.cms2.model.pages.AbstractPageModel;
import de.hybris.platform.cms2.model.relations.CMSRelationModel;
import de.hybris.platform.cms2.model.relations.ContentSlotForPageModel;
import de.hybris.platform.cms2.model.relations.ContentSlotForTemplateModel;
import de.hybris.platform.cms2.servicelayer.data.ContentSlotData;
import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminContentSlotService;
import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminPageService;
import de.hybris.platform.cmsfacades.data.PageContentSlotData;
import de.hybris.platform.cmsfacades.pagescontentslots.converter.ContentSlotDataConverter;
import de.hybris.platform.cmsfacades.pagescontentslots.service.PageContentSlotConverterRegistry;
import de.hybris.platform.cmsfacades.pagescontentslots.service.PageContentSlotConverterType;
import de.hybris.platform.cmsfacades.pagescontentslots.service.impl.DefaultPageContentSlotConverterType;
import de.hybris.platform.converters.impl.AbstractPopulatingConverter;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultPageContentSlotFacadeTest
{
private static final String INVALID = "invalid";
private static final String SLOT_ID = "header-slot";
private static final String PAGE_ID = "content-page";
@Mock
private CMSAdminContentSlotService adminContentSlotService;
@Mock
private CMSAdminPageService adminPageService;
@Mock
private PageContentSlotConverterRegistry pageContentSlotConverterRegistry;
@Mock
private ContentSlotModel headerSlot;
@Mock
private AbstractPageModel page;
@Mock
private ContentSlotData headerSlotData;
@Mock
private ContentSlotData footerSlotData;
@Mock
private PageContentSlotData pageContentSlotData;
@Mock
private AbstractPopulatingConverter<CMSRelationModel, PageContentSlotData> converter;
@Mock
private ContentSlotDataConverter contentSlotDataConverter;
@InjectMocks
private DefaultPageContentSlotFacade pageContentSlotFacade;
private final PageContentSlotConverterType converterType = new DefaultPageContentSlotConverterType();
@Before
public void setUp()
{
when(adminPageService.getPageForIdFromActiveCatalogVersion(INVALID))
.thenThrow(new UnknownIdentifierException("invalid page id"));
when(adminPageService.getPageForIdFromActiveCatalogVersion(PAGE_ID)).thenReturn(page);
when(adminContentSlotService.getContentSlotForId(INVALID)).thenThrow(new UnknownIdentifierException("invalid slot id"));
when(adminContentSlotService.getContentSlotForId(SLOT_ID)).thenReturn(headerSlot);
when(pageContentSlotConverterRegistry.getPageContentSlotConverterType(ContentSlotForPageModel.class))
.thenReturn(Optional.of(converterType));
when(pageContentSlotConverterRegistry.getPageContentSlotConverterType(ContentSlotForTemplateModel.class))
.thenReturn(Optional.of(converterType));
when(pageContentSlotConverterRegistry.getPageContentSlotConverterType(CustomRelationModel.class))
.thenReturn(Optional.of(converterType));
converterType.setConverter(converter);
}
@Test
public void shouldFindContentSlotsForPage() throws CMSItemNotFoundException, ConversionException
{
when(adminContentSlotService.getContentSlotsForPage(page)).thenReturn(Arrays.asList(headerSlotData, footerSlotData));
when(contentSlotDataConverter.convert(headerSlotData)).thenReturn(pageContentSlotData);
when(contentSlotDataConverter.convert(footerSlotData)).thenReturn(pageContentSlotData);
final List<PageContentSlotData> contentSlots = pageContentSlotFacade.getContentSlotsByPage(PAGE_ID);
assertThat(contentSlots.size(), is(2));
assertThat(contentSlots, hasItem(pageContentSlotData));
}
@Test
public void shouldFindNoContentSlotForPage() throws CMSItemNotFoundException, ConversionException
{
when(adminContentSlotService.getContentSlotsForPage(page)).thenReturn(Collections.emptyList());
final List<PageContentSlotData> contentSlots = pageContentSlotFacade.getContentSlotsByPage(PAGE_ID);
assertThat(contentSlots, empty());
}
@Test(expected = CMSItemNotFoundException.class)
public void shouldNotFindPageId() throws CMSItemNotFoundException, ConversionException
{
pageContentSlotFacade.getContentSlotsByPage(INVALID);
}
@Test(expected = ConversionException.class)
public void shouldFailConversion() throws CMSItemNotFoundException, ConversionException
{
when(adminContentSlotService.getContentSlotsForPage(page)).thenReturn(Arrays.asList(headerSlotData, footerSlotData));
when(contentSlotDataConverter.convert(headerSlotData)).thenThrow(new ConversionException("conversion failure"));
pageContentSlotFacade.getContentSlotsByPage(PAGE_ID);
}
class CustomRelationModel extends ContentSlotForPageModel
{
public CustomRelationModel()
{
super();
}
}
}
|
package com.codependent.mutualauth;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
/**
* Created by e076103 on 21-08-2018.
*/
public class CertificateUtil {
public static void main(String[] args) {
CertificateDetails certDetails = getCertificateDetails();
System.out.println(certDetails.getPrivateKey());
System.out.println(certDetails.getX509Certificate());
addCertificate();
}
public static CertificateDetails getCertificateDetails() {
CertificateDetails certDetails = null;
try {
boolean isAliasWithCertificate = false;
KeyStore keyStore = KeyStore.getInstance("JKS");
// Provide location of Java Keystore and password for access
keyStore.load(new FileInputStream("C:\\Project\\mutual_ssl\\server-truststore.jks"), "secret".toCharArray());
//keyStore.load(new FileInputStream("C:\\Project\\mutual_ssl\\server-keystore.jks"), "secret".toCharArray());
// iterate over all aliases
Enumeration<String> es = keyStore.aliases();
String alias = "";
while (es.hasMoreElements()) {
alias = (String) es.nextElement();
// if alias refers to a private key break at that point
// as we want to use that certificate
if (isAliasWithCertificate = keyStore.isCertificateEntry(alias)) {
break;
}
}
if (isAliasWithCertificate) {
Certificate certificate = keyStore.getCertificate(alias);
certDetails = new CertificateDetails();
//certDetails.setPrivateKey("nothing");
certDetails.setX509Certificate((X509Certificate) certificate);
/*KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
new KeyStore.PasswordProtection(jksPassword.toCharArray()));
PrivateKey myPrivateKey = pkEntry.getPrivateKey();
// Load certificate chain
Certificate[] chain = keyStore.getCertificateChain(alias);
certDetails = new CertificateDetails();
certDetails.setPrivateKey(myPrivateKey);
certDetails.setX509Certificate((X509Certificate) chain[0]);*/
}
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return certDetails;
}
public static void addCertificate() {
CertificateDetails certDetails = null;
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
String certfile = "C:\\Project\\mutual_ssl\\add\\client-public.cer";
InputStream certstream = fullStream (certfile);
Certificate certs = cf.generateCertificate(certstream);
// Provide location of Java Keystore and password for access
keyStore.load(new FileInputStream("C:\\Project\\mutual_ssl\\server-truststore.jks"),
"secret".toCharArray());
keyStore.setCertificateEntry("test", certs);
System.out.println("keyStore.size()");
System.out.println(keyStore.size());
System.out.println("*************CHECK ENtries*****************");
certDetails = getCertificateDetails();
System.out.println(certDetails.getPrivateKey());
System.out.println(certDetails.getX509Certificate());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
private static InputStream fullStream ( String fname ) throws IOException {
FileInputStream fis = new FileInputStream(fname);
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
return bais;
}
}
|
package com.clubrada.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
public class Authentiication extends JFrame {
private JLabel lbl_Login, lbl_Motps,lbl_lock,lbl_time;
private JTextField txt_Login;
private JPasswordField txt_Motps;
private JPanel panel;
private JButton bt_con;
public Authentiication(){
panel = new JPanel();
panel.setBackground(Color.orange);
panel.setSize(800, 600);
panel.setLayout(null);
setBounds(100, 100, 600,300);
setTitle("Authentiication");
setLocationRelativeTo(null);
setResizable(false);
this.setAlwaysOnTop(true);
setDefaultCloseOperation(Authentiication.DISPOSE_ON_CLOSE);
setVisible(true);
lbl_Login = new JLabel("Login :");
lbl_Login.setBounds(40,50,200,60);
lbl_Login.setFont(new Font ("Crystal", Font.PLAIN, 40));
txt_Login = new JTextField();
txt_Login.setBounds(270,65,300,40);
txt_Login.setFont(new Font ("Crystal", Font.PLAIN, 30));
lbl_Motps = new JLabel("PassWord :");
lbl_Motps.setBounds(40,120,300,60);
lbl_Motps.setFont(new Font ("Crystal", Font.PLAIN, 40));
txt_Motps = new JPasswordField();
txt_Motps.setBounds(270,130,300,40);
txt_Motps.setFont(new Font ("Crystal", Font.PLAIN, 30));
bt_con = new JButton();
bt_con.setBounds(320,200,200,41);
bt_con.setIcon(new ImageIcon(Authentiication.class.getResource("/com/clubreda/images/con.png")));
lbl_lock = new JLabel();
lbl_lock.setBounds(40,165,120,120);
lbl_lock.setIcon(new ImageIcon(Authentiication.class.getResource("/com/clubreda/images/lock.png")));
this. add(panel);
panel.add(lbl_Login);
panel.add(txt_Login);
panel.add(lbl_Motps);
panel.add(txt_Motps);
panel. add(bt_con);
panel. add(lbl_lock);
}
}
|
/*
* 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 modle;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
/**
*
* @author suhada
*/
public class Interest implements DAO<pojo.Interest>{
@Override
public boolean save(pojo.Interest t) {
Session session = conn.NewHibernateUtil.getSessionFactory().openSession();
Transaction bt = session.beginTransaction();
try {
session.save(t);
bt.commit();
if (t.getIdInterest() > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
if (bt != null) {
bt.rollback();
}
e.printStackTrace();
return false;
} finally {
session.close();
}
}
@Override
public boolean save(List<pojo.Interest> list) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean update(pojo.Interest t) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean update(List<pojo.Interest> list) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean saveOrUpdate(pojo.Interest t) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean saveOrUpdate(List<pojo.Interest> list) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean delete(pojo.Interest t) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<pojo.Interest> getList() {
Session session = conn.NewHibernateUtil.getSessionFactory().openSession();
try {
return session.createCriteria(pojo.User.class).list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}
/**
*
* @param name VAT,NBT,Stamp
* @return
*/
public pojo.Interest getByName(String name){
Session session = conn.NewHibernateUtil.getSessionFactory().openSession();
try {
return (pojo.Interest) session.createCriteria(pojo.Interest.class)
.add(Restrictions.eq("name", name))
.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}
}
|
package com.foosbot.service.handlers.payloads;
import com.foosbot.service.handlers.Validates;
import lombok.Data;
@Data
public class BatchMatchCreatePayload implements Validates {
@Override
public boolean isValid() {
return false;
}
}
|
package com.FCI.SWE.ServicesModels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import javax.ws.rs.FormParam;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.cloud.sql.jdbc.PreparedStatement;
public class PostEntity
{
protected String postContent ;
Privacy privacy ;
protected boolean isShare; // shared post or not
protected String postType;
protected String postOwner;
public void setPrivacy(Privacy privacy)
{
this.privacy = privacy ;
}
public void setOwner(String postOwner)
{
this.postOwner = postOwner ;
}
public void setContent(String content)
{
this.postContent = content ;
}
public void setPostType(String postType)
{
this.postType = postType ;
}
public void setIsShare(Boolean isShare)
{
this.isShare = isShare ;
}
public boolean sharePost(String postID, String currentEmail)
{
isShare = true ;
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query gaQuery = new Query("posts");
PreparedQuery pq = datastore.prepare(gaQuery);
for(Entity e : pq.asIterable())
{
if(e.getKey().getId() == Long.parseLong(postID))
{
postType = e.getProperty("postType").toString();
if(e.getProperty("isShare").toString().equals("true"))//share a shared Post
{
postID = e.getProperty("sharedPostID").toString();
}
break ;
}
}
Entity sharedPost = new Entity ("posts");
sharedPost.setProperty("owner" ,currentEmail );//who added the post or shared it
sharedPost.setProperty("sharedPostID", postID);
sharedPost.setProperty("likes", 0);
sharedPost.setProperty("likers", "");//who liked the post
sharedPost.setProperty("isShare", isShare);//here it's a shared post
sharedPost.setProperty("postType", postType);
if(datastore.put(sharedPost).isComplete())
{
return true;
}
else
return false ;
}
public boolean likePost(String postID ,String currentEmail) //we send the liker email so as not to like twice
{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query gaeQuery = new Query("posts");
PreparedQuery pq = datastore.prepare(gaeQuery);
String postOwnerEmail = "" ;
for(Entity e : pq.asIterable())
{
if(Long.toString(e.getKey().getId()).equals(postID))
{
if(e.getProperty("likers").toString().contains(currentEmail))
{
return false;
}
if(e.getProperty("postType").toString().equals("page"))
{
DatastoreService datastore2 = DatastoreServiceFactory.getDatastoreService();
Query gaeQuery2 = new Query("pages");
PreparedQuery pq2 = datastore.prepare(gaeQuery2);
for(Entity page : pq.asIterable())
{
if(page.getProperty("pageName").toString().equals(e.getProperty("owner").toString()))
{
postOwnerEmail = page.getProperty("createdEmail").toString();
break ;
}
}
}
else
{
postOwnerEmail = e.getProperty("owner").toString();
}
int likes =Integer.parseInt(e.getProperty("likes").toString());
String likers = (String)e.getProperty("likers");
e.setProperty("likes", likes + 1);
e.setProperty("likers", likers + "," + currentEmail);
datastore.put(e);
break ;
}
}
UserEntity ue = new UserEntity();
String actionPerformerName = ue.getUserNameByEmail(currentEmail);
Entity notification = new Entity ("notifications") ;
notification.setProperty("RecEmail" , postOwnerEmail);
notification.setProperty("actionPerformer" , actionPerformerName); // who did the like
notification.setProperty("notiClass" , "DiscardPostLikeCommand" );
notification.setProperty("notifID" , postID );
datastore.put(notification);
return true ;
}
} |
package ru.aahzbrut.reciperestapi.domain.entities;
class IngredientTest extends BaseTestEntity {
} |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class startCommuncation
{
public static Connection databaseConn() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connect= DriverManager.getConnection(
"jdbc:mysql://localhost:3306/students", "root", "CSCE741!");
Statement stat = connect.createStatement();
return connect;
}
public static void main(String[] args)
{
try
{
databaseConn();
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
} |
package org.caonima.network;
public class Method {
public static final int GET = 0;
public static final int POST = 1;
}
|
package ru.krasview.tv;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.example.kvlib.R;
import ru.krasview.kvlib.adapter.CombineSimpleAdapter;
import ru.krasview.kvlib.indep.AuthAccount;
import ru.krasview.kvlib.indep.HTTPClient;
import ru.krasview.kvlib.indep.HeaderAccount;
import ru.krasview.kvlib.interfaces.OnLoadCompleteListener;
import ru.krasview.kvlib.widget.lists.PackageList;
import ru.krasview.secret.ApiConst;
import ru.krasview.secret.Billing;
import ru.krasview.tv.billing.util.IabHelper;
import ru.krasview.tv.billing.util.IabHelper.QueryInventoryFinishedListener;
import ru.krasview.tv.billing.util.IabResult;
import ru.krasview.tv.billing.util.Inventory;
import ru.krasview.tv.billing.util.Purchase;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.Toast;
public class BillingActivity extends Activity implements OnLoadCompleteListener, OnItemClickListener {
IabHelper mHelper;
PackageList mList;
private void setResultAndFinish(){
HeaderAccount.hideHeader = true;
Toast.makeText(this, "Пакет подключен", Toast.LENGTH_LONG).show();
setResult(RESULT_OK);
this.onBackPressed();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar_background));
setContentView(R.layout.activity_billing);
FrameLayout layout = (FrameLayout)findViewById(R.id.layout);
mList = new PackageList(this, null);
mList.init();
mList.setOnLoadCompleteListener(this);
mList.setOnItemClickListener(this);
layout.addView(mList);
String base64EncodedPublicKey = Billing.base64EncodedPublicKey;
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.i("Debug", "Problem setting up In-app Billing: " + result);
}
mList.refresh();
Log.i("Debug", "Hooray, IAB is fully set up!");
}
});
}
QueryInventoryFinishedListener
mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// Обработка ошибки
Log.i("Debug", "Произошла ошибка");
return;
}
go(inventory);
}
};
@SuppressWarnings("unchecked")
private void go(Inventory inventory) {
CombineSimpleAdapter adapter = mList.getAdapter();
for(int i = 0; i < adapter.getCount(); i++) {
Map<String,Object> map = (Map<String, Object>)adapter.getItem(i);
String id = (String)map.get("sku");
if(inventory.hasDetails(id)){
String productType = inventory.getSkuDetails(id).getType();
if(productType.equals("subs")) {
productType = "подписка на месяц";
}else if(productType.equals("inapp")) {
productType = "на месяц";
}else{
productType = "";
}
map.put("inMarket", true);
map.put("productType", productType);
map.put("price", inventory.getSkuDetails(id).getPrice());
adapter.notifyDataSetChanged();
} else {
String productType = (String)map.get("product");
if(productType == null){
} else {
if(productType.equals("subscription")) {
productType = "подписка на месяц";
} else if(productType.equals("portion")) {
productType = "на месяц";
} else {
productType = "";
}
map.put("productType", productType);
}
map.put("inMarket", false);
map.put("price", "Недоступно");
adapter.notifyDataSetChanged();
}
}
}
class PurchaseFinishedListener implements IabHelper.OnIabPurchaseFinishedListener {
Map<String, Object> m;
PurchaseFinishedListener(Map<String, Object> m) {
this.m = m;
}
@SuppressWarnings("unchecked")
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
//обрабатываем прошедшую выплату
Log.i("Debug", " purchasing: " + result);
if (result.isFailure()) {
//если ошибка
Log.i("Debug", "Error purchasing: " + result);
return;
}
new SendOnServerTask().execute(m);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@SuppressWarnings("unchecked")
@Override
public void loadComplete(String result) {
List<String> additionalSkuList = new ArrayList<String>();
CombineSimpleAdapter adapter = mList.getAdapter();
for(int i = 0; i < adapter.getCount(); i++){
Map<String,Object> map = (Map<String, Object>)adapter.getItem(i);
//потестить
additionalSkuList.add((String)map.get("sku"));
}
mHelper.queryInventoryAsync(true, additionalSkuList,
mQueryFinishedListener);
}
@Override
public void loadComplete(String address, String result) {
}
@SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CombineSimpleAdapter adapter = (CombineSimpleAdapter) parent.getAdapter();
Map<String, Object> m = (Map<String, Object>)adapter.getItem(position);
if (m.get("inMarket") == null || !(Boolean)m.get("inMarket")){
return;
} else {
//Запуск процесса покупки
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new PurchaseFinishedListener(m) ;
mHelper.launchPurchaseFlow(BillingActivity.this, (String)m.get("sku"), 10001,
mPurchaseFinishedListener, Billing.LAUNCH_PUNCHASE_FLOW_EXTRA);
}
}
private class SendOnServerTask extends AsyncTask<Map<String, Object>,Void,String> {
@Override
protected String doInBackground(Map<String, Object>... maps) {
String packet = (String)maps[0].get("id");
String hash = AuthAccount.getInstance().getTvHash();
String address = ApiConst.SUBSCRIBE;
String secret = Billing.getSecret(hash, packet);
String params = "packet=" + packet + "&" + "secret=" + secret;
String result = HTTPClient.getXML(address, params, AuthAccount.AUTH_TYPE_KRASVIEW);
return result;
}
@Override
protected void onPostExecute(String result) {
if (result.equals("ok")) {
setResultAndFinish();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass on the activity result to the helper for handling
// NOTE: handleActivityResult() will update the state of the helper,
// allowing you to make further calls without having it exception on you
if (mHelper.handleActivityResult(requestCode, resultCode, data)) {
Log.d("Debug", "onActivityResult handled by IABUtil.");
//handlePurchaseResult(requestCode, resultCode, data);
return;
}
}
}
|
package com.szcinda.express.params;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class QueryProfileParams extends PageParams {
private String name;
}
|
package com.sneaker.mall.api.model;
import com.google.common.collect.Lists;
import com.sneaker.mall.api.annotation.NODBFeild;
import java.util.Date;
import java.util.List;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
public class Goods extends BaseModel<Long> {
/**
* 商品基础资料ID
*/
private long gid;
/**
* 条型码
*/
private String barcode;
/**
* 商品名称
*/
private String gname;
/**
* 规格
*/
private int spec;
/**
* 包装规格
*/
private String pkgspec;
/**
* 瓶
*/
private String unit;
/**
* 品牌ID
*/
private long bid;
/**
* 品牌名称
*/
private String bname;
/**
* 分类ID
*/
private long tid;
/**
* 分类名称
*/
private String tname;
/**
* 产地
*/
private String place;
/**
* 厂家
*/
private String factory;
/**
* 创建时间
*/
private Date create_time;
/**
* 更新时间
*/
private Date update_time;
/**
* 商品编码
*/
private String gcode;
/**
* 商品图片
*/
private String gphoto;
/**
* 商品索引
*/
private int gphoto_index;
/**
* 分类ID
*/
private long cateid;
/**
* 公司ID
*/
private long company_id;
/**
* 公司名称
*/
private String company_name;
/**
* 价格
*/
private float price;
/**
* 封面
*/
private String cover;
/**
* 副标题
*/
private String sale_name;
/**
* 描述
*/
private String content;
/**
* 绑定商品,目前主要用于解决市场营销活动
*/
private int isbind;
/**
* 是否为赠品
*/
private int giveaway;
/**
* 个数
*/
private int num;
/**
* 商城设定的价格
*/
private float cprice;
/**
* 主商品
*/
private List<Goods> mainGoods = Lists.newArrayList();
/**
* 赠品
*/
private List<Goods> giveGoods = Lists.newArrayList();
/**
* 是否发布 0表示下线,1表示发布
*/
private int publish;
/**
* 仓库ID,多个以逗号分开
*/
private String sids;
/**
* 客户类型,多个以逗号分开
*/
private String cctype;
/**
* 够买限制数
*/
private int restrict;
/**
* 是否置顶
*/
private int istop;
/**
* 销量
*/
private int salesNum;
/**
* 置顶时间
*/
private int top;
/**
* 是否显示 0表示显示,1表示不显示
*/
private int flagdel;
/**
* 赠品修改的号码
*/
private String title;
/**
* 是否大小包装
*/
private int pkgSize;
/**
* 商品价格
*/
private int shop_price;
/**
* 排序字段
*/
private int order;
/**
* 营销活动ID
*/
private String marketid;
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public String getMarketid() {
return marketid;
}
public void setMarketid(String marketid) {
this.marketid = marketid;
}
public int getPkgSize() {
return pkgSize;
}
public void setPkgSize(int pkgSize) {
this.pkgSize = pkgSize;
}
public int getShop_price() {
return shop_price;
}
public void setShop_price(int shop_price) {
this.shop_price = shop_price;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getFlagdel() {
return flagdel;
}
public void setFlagdel(int flagdel) {
this.flagdel = flagdel;
}
public int getIstop() {
return istop;
}
public void setIstop(int istop) {
this.istop = istop;
}
public int getSalesNum() {
return salesNum;
}
public void setSalesNum(int salesNum) {
this.salesNum = salesNum;
}
public int getRestrict() {
return restrict;
}
public void setRestrict(int restrict) {
this.restrict = restrict;
}
/**
* 营销相关信息文字
*/
@NODBFeild
private String marketText;
public String getSids() {
return sids;
}
public void setSids(String sids) {
this.sids = sids;
}
public String getCctype() {
return cctype;
}
public void setCctype(String cctype) {
this.cctype = cctype;
}
public int getPublish() {
return publish;
}
public void setPublish(int publish) {
this.publish = publish;
}
public float getCprice() {
return cprice;
}
public void setCprice(float cprice) {
this.cprice = cprice;
}
public List<Goods> getMainGoods() {
return mainGoods;
}
public void setMainGoods(List<Goods> mainGoods) {
this.mainGoods = mainGoods;
}
public List<Goods> getGiveGoods() {
return giveGoods;
}
public void setGiveGoods(List<Goods> giveGoods) {
this.giveGoods = giveGoods;
}
public String getMarketText() {
return marketText;
}
public void setMarketText(String marketText) {
this.marketText = marketText;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getGiveaway() {
return giveaway;
}
public void setGiveaway(int giveaway) {
this.giveaway = giveaway;
}
public int getIsbind() {
return isbind;
}
public void setIsbind(int isbind) {
this.isbind = isbind;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSale_name() {
return sale_name;
}
public void setSale_name(String sale_name) {
this.sale_name = sale_name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public long getGid() {
return gid;
}
public void setGid(long gid) {
this.gid = gid;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public int getSpec() {
return spec;
}
public void setSpec(int spec) {
this.spec = spec;
}
public String getPkgspec() {
return pkgspec;
}
public void setPkgspec(String pkgspec) {
this.pkgspec = pkgspec;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public long getBid() {
return bid;
}
public void setBid(long bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public long getTid() {
return tid;
}
public void setTid(long tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
public String getGcode() {
return gcode;
}
public void setGcode(String gcode) {
this.gcode = gcode;
}
public String getGphoto() {
return gphoto;
}
public void setGphoto(String gphoto) {
this.gphoto = gphoto;
}
public int getGphoto_index() {
return gphoto_index;
}
public void setGphoto_index(int gphoto_index) {
this.gphoto_index = gphoto_index;
}
public long getCateid() {
return cateid;
}
public void setCateid(long cateid) {
this.cateid = cateid;
}
public long getCompany_id() {
return company_id;
}
public void setCompany_id(long company_id) {
this.company_id = company_id;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
}
|
package com.example.pingreception;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class makePing extends AppCompatActivity {
private Button goBack;
private TextView pingAnswer;
private String getInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_ping);
goBack = findViewById(R.id.goBack);
pingAnswer = findViewById(R.id.pingAnswer);
getInput = getIntent().getStringExtra("input");
Log.e("inputPass",getInput);
new Thread(
() ->{
try {
InetAddress inetAddress = InetAddress.getByName(getInput);
runOnUiThread(
() ->{
pingAnswer.setText("");
}
);
/////// falta la variable para sumar
for (int i=0; i<4;i++){
boolean reach =inetAddress.isReachable(1000);
Log.e("Status",getInput);
runOnUiThread(
() ->{
if(reach){
pingAnswer.append("Sé conecto" + " " + getInput+"\n");
} else {
pingAnswer.append("No sé conecto"+"\n");
}
}
);
Thread.sleep(2000);
}
} catch (UnknownHostException e) {
//por si encuentre el HOST
e.printStackTrace();
} catch (IOException e) {
//por si no es alcanzable
e.printStackTrace();
//para el sleep
} catch (InterruptedException e) {
e.printStackTrace();
}
}
).start();
goBack.setOnClickListener(
(view) -> {
finish();
}
);
}
} |
// Shrey Shah
// ID: 112693183
// Shrey.Shah@stonybrook.edu
// Homework #7
// CSE214
// R.04 James Finn
import java.util.*;
public class IndexComparator implements Comparator<WebPage>{
public int compare(WebPage page1, WebPage page2) {
return Integer.compare(page1.getIndex(), page2.getIndex());
}
}
|
package com.bozhong.lhdataaccess.infrastructure.dao;
import com.bozhong.lhdataaccess.domain.DoctorOrderDO;
import com.bozhong.lhdataaccess.domain.DoctorPrescriptionDO;
import com.bozhong.lhdataaccess.domain.OrganizStructureDO;
import java.util.List;
/**
* User: 李志坚
* Date: 2018/11/5
* 处方数据的DAO
*/
public interface DoctorPrescriptionDAO {
void updateOrInsertDoctorPrescription(DoctorPrescriptionDO doctorPrescriptionDO);
List<DoctorPrescriptionDO> selectDpDataByDoctorPrescriptionDO(DoctorPrescriptionDO doctorPrescriptionDO);
}
|
package com.lec.loop;
import java.util.Scanner;
// 사용자로부터 원하는 구구단수를 입력받아 해당 구구단을 출력해 보자
public class Q3_for {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("몇단 원해");
int dansu = scanner.nextInt();
for (int i=1; i<10; i++) {
System.out.printf("%d*%d= %2d\n", dansu,i,dansu*i);
System.out.println(dansu + "*" + i +"="+(dansu*i));
}
scanner.close();
}
}
|
package rugal.westion.jiefanglu.core.dao;
import rugal.common.hibernate.Updater;
import rugal.common.page.Pagination;
import rugal.westion.jiefanglu.core.entity.Account;
import rugal.westion.jiefanglu.core.entity.QQThirdPart;
import rugal.westion.jiefanglu.core.entity.Route;
import rugal.westion.jiefanglu.core.entity.WBThirdPart;
import rugal.westion.jiefanglu.core.entity.WXThirdPart;
/**
*
* @author Westion
*/
public interface WXThirdPartDao {
WXThirdPart deleteById(Integer id);
WXThirdPart findById(Integer id);
Pagination getPage(int pageNo, int pageSize);
WXThirdPart save(WXThirdPart bean);
WXThirdPart updateByUpdater(Updater<WXThirdPart> updater);
WXThirdPart findByOpenid(String openid);
}
|
package binary.search;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
IPAddress[] ipAddresses = new IPAddress[10000];
int[] octets = new int[4];
long longIP;
@SuppressWarnings("resource")
Scanner readinput = new Scanner(System.in);
writeToArray("C:\\Users\\MirzA\\Documents\\IP-COUNTRY-REGION-CITY-SORTED.csv", ipAddresses);
System.out.println("Enter an IP address whose data you want to retrieve: ");
String inputIP = readinput.nextLine();
LongToIP(inputIP, octets);
longIP = IPToLong(octets);
searchResult(ipAddresses, longIP);
}
public static long IPToLong(int[] arr) {
long longIP = 16777216 * arr[0] + 65536 * arr[1] + 256 * arr[2] + arr[3];
return longIP;
}
public static void writeToArray(String path, IPAddress[] arr) throws IOException {
Scanner scanner = new Scanner(new File(path));
int i = 0;
while(i < arr.length) {
String[] ipAddressStrings = scanner.nextLine().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
for (int j = 0; j < ipAddressStrings.length; j++) {
ipAddressStrings[j] = ipAddressStrings[j].replace("\"", "");
}
long ipFrom = Long.parseLong(ipAddressStrings[0]);
long ipTo = Long.parseLong(ipAddressStrings[1]);
String countryCode = ipAddressStrings[2];
String countryName = ipAddressStrings[3];
String regionName = ipAddressStrings[4];
String cityName = ipAddressStrings[5];
arr[i] = new IPAddress(ipFrom, ipTo, countryCode, countryName, regionName, cityName);
i++;
}
scanner.close();
}
public static void LongToIP(String s, int[] arr) {
String[] parts = s.split("\\.");
for (int k = 0; k < 4; k++) {
arr[k] = Integer.parseInt(parts[k]);
}
}
public static void searchResult(IPAddress[] arr, long key) {
int res = BinarySearch.search(arr, key);
if(res != -1) {
System.out.println("Country code: " + arr[res].countryCode + "\nCountry name: " + arr[res].countryName + "\nRegion: " + arr[res].regionName + "\nCity: " + arr[res].cityName);
} else {
System.out.println("IP address not found");
}
}
}
|
package hirondelle.web4j.security;
import java.util.*;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import hirondelle.web4j.BuildImpl;
import hirondelle.web4j.action.Action;
import hirondelle.web4j.model.BadRequestException;
import hirondelle.web4j.readconfig.ConfigReader;
import hirondelle.web4j.readconfig.InitParam;
import hirondelle.web4j.request.RequestParameter;
import hirondelle.web4j.request.RequestParser;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.action.Operation;
import hirondelle.web4j.model.Id;
import static hirondelle.web4j.util.Consts.FAILS;
/**
Default implementation of {@link ApplicationFirewall}.
<P>Upon startup, this class will inspect all {@link Action}s in the application.
All <tt>public static final</tt> {@link hirondelle.web4j.request.RequestParameter} fields accessible
to each {@link Action} will be collected, and treated here as the set of acceptable
{@link RequestParameter}s for each {@link Action} class. Thus, when this class is used to implement
{@link ApplicationFirewall}, <span class="highlight">each {@link Action} must declare all expected request
parameters as a <tt>public static final</tt> {@link RequestParameter} field, in order to pass hard validation.</span>
<h3>File Upload Forms</h3>
If a POSTed request includes one or more file upload controls, then the underlying HTTP request has
a completely different structure from a regular request having no file upload controls.
Unfortunately, the Servlet API has very poor support for forms that include a file upload control: only the raw underlying request is available, <em>in an unparsed form</em>.
For such forms, POSTed data is not available in the usual way, and by default <tt>request.getParameter(String)</tt> will return <tt>null</tt> -
<em>not only for the file upload control, but for all controls in the form</em>.
<P>An elegant way around this problem involves <em>wrapping</em> the request,
using {@link javax.servlet.http.HttpServletRequestWrapper}, such that POSTed data is parsed and made
available through the usual <tt>request</tt> methods.
If such a wrapper is used, then file upload forms can be handled in much the same way as any other form.
<P>To indicate to this class if such a wrapper is being used for file upload requests, use the <tt>FullyValidateFileUploads</tt> setting
in <tt>web.xml</tt>.
<P>Settings in <tt>web.xml</tt> affecting this class :
<ul>
<li><tt>MaxHttpRequestSize</tt>
<li><tt>MaxFileUploadRequestSize</tt>
<li><tt>MaxRequestParamValueSize</tt> (used by {@link hirondelle.web4j.request.RequestParameter})
<li><tt>SpamDetectionInFirewall</tt>
<li><tt>FullyValidateFileUploads</tt>
</ul>
<P>The above settings control the validations performed by this class :
<table border="1" cellpadding="3" cellspacing="0">
<tr>
<th>Check</th>
<th>Regular</th>
<th>File Upload (Wrapped)</th>
<th>File Upload</th>
</tr>
<tr>
<td>Overall request size <= <tt>MaxHttpRequestSize</tt> </td>
<td>Y</td>
<td>N</td>
<td>N</td>
</tr>
<tr>
<td>Overall request size <= <tt>MaxFileUploadRequestSize</tt> </td>
<td>N</td>
<td>Y</td>
<td>Y</td>
</tr>
<tr>
<td>Every param <em>name</em> is among the {@link hirondelle.web4j.request.RequestParameter}s for that {@link Action}</td>
<td>Y</td>
<td>Y*</td>
<td>N</td>
</tr>
<tr>
<td>Every param <em>value</em> satifies {@link hirondelle.web4j.request.RequestParameter#isValidParamValue(String)}</td>
<td>Y</td>
<td>Y**</td>
<td>N</td>
</tr>
<tr>
<td>If created with {@link hirondelle.web4j.request.RequestParameter#withLengthCheck(String)}, then param value size <= <tt>MaxRequestParamValueSize</tt></td>
<td>Y</td>
<td>Y**</td>
<td>N</td>
</tr>
<tr>
<td>If <tt>SpamDetectionInFirewall</tt> is on, then each param value is checked using the configured {@link hirondelle.web4j.security.SpamDetector}</td>
<td>Y</td>
<td>Y**</td>
<td>N</td>
</tr>
<tr>
<td>If a request param named <tt>Operation</tt> exists and it returns <tt>true</tt> for {@link Operation#hasSideEffects()}, then the underlying request must be a <tt>POST</tt></td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
<tr>
<td><a href='#CSRF'>CSRF Defenses</a></td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
</table>
* For file upload controls, the param name is checked only if the return value of <tt>getParameterNames()</tt> (for the wrapper) includes it.
<br>**Except for file upload controls. For file upload <em>controls</em>, no checks on the param <em>value</em> are made by this class.<br>
<a name='CSRF'></a>
<h3>Defending Against CSRF Attacks</h3>
If the usual WEB4J defenses against CSRF attacks are active (see package-level comments),
then <i>for every <tt>POST</tt> request executed within a session</i> the following will also be performed as a defense against CSRF attacks :
<ul>
<li>validate that a request parameter named
{@link hirondelle.web4j.security.CsrfFilter#FORM_SOURCE_ID_KEY} is present. (This
request parameter is deemed to be a special 'internal' parameter, and does not need to be explicitly declared in
your <tt>Action</tt> like other request parameters.)
<li>validate that its value matches items stored in session scope. First check versus an item stored
under the key {@link hirondelle.web4j.security.CsrfFilter#FORM_SOURCE_ID_KEY}; if that check fails, then
check versus an item stored under the key
{@link hirondelle.web4j.security.CsrfFilter#PREVIOUS_FORM_SOURCE_ID_KEY}
</ul>
See {@link hirondelle.web4j.security.CsrfFilter} for more information.
*/
public class ApplicationFirewallImpl implements ApplicationFirewall {
/**
Called by {@link hirondelle.web4j.request.RequestParser} to initialize this class upon startup.
<P>Inspects all {@link Action} classes to find the {@link RequestParameter}s expected by each one.
<P>Extracts these settings from <tt>web.xml</tt> :
<table border="1" cellpadding="3" cellspacing="0">
<tr><th>Name</th><th>Default Value</th></tr>
<tr><td>MaxHttpRequestSize</td><td>51200</td></tr>
<tr><td>MaxFileUploadRequestSize</td><td>51200</td></tr>
<tr><td>SpamDetectionInFirewall</td><td>OFF</td></tr>
<tr><td>FullyValidateFileUploads</td><td>OFF</td></tr>
</table>
*/
public static void init(ServletConfig aConfig){
fMaxRequestSize = getMaxSize(fMAX_REQUEST_SIZE, aConfig);
fMaxFileUploadRequestSize = getMaxSize(fMAX_FILE_UPLOAD_REQUEST_SIZE, aConfig);
fFullyValidateFileUploads = getBooleanSetting(fFULLY_VALIDATE_FILE_UPLOADS, aConfig);
fIsSpamDetectionOn = getBooleanSetting(fIS_SPAM_DETECTION_ON, aConfig);
mapActionsToExpectedParams();
}
/**
Perform checks on the incoming request.
<P>See class description for more information.
<P>Subclasses may extend this implementation, following the form :
<PRE>
public void doHardValidation(Action aAction, RequestParser aRequestParser) throws BadRequestException {
super(aAction, aRequestParser);
//place additional validations here
//for example, one might check that a Content-Length header is present,
//or that all header values are within some size range
}
</PRE>
*/
public void doHardValidation(Action aAction, RequestParser aRequestParser) throws BadRequestException {
if( aRequestParser.isFileUploadRequest() ){
fLogger.fine("Validating a file upload request.");
}
checkForExtremeSize(aRequestParser);
if ( aRequestParser.isFileUploadRequest() && ! fFullyValidateFileUploads ) {
fLogger.fine("Unable to parse request in the usual way: file upload request is not wrapped. Cannot read parameter names and values. See FullyValidateFileUploads setting in web.xml.");
}
else {
checkParamNamesAndValues(aAction, aRequestParser);
checkSideEffectOperations(aAction, aRequestParser);
defendAgainstCSRFAttacks(aRequestParser);
}
}
// PRIVATE //
/**
Maps {@link Action} classes to a List of expected {@link hirondelle.web4j.request.RequestParameter} objects.
If the incoming request contains a request parameter whose name or value is not consistent with this
list, then a {@link hirondelle.web4j.model.BadRequestException} is thrown.
<P>Key - class object
<br>Value - Set of RequestParameter objects; may be empty, but not null.
<P>This is a mutable object field, but is not modified after startup, so this class is thread-safe.
*/
private static Map<Class<Action>, Set<RequestParameter>> fExpectedParams = new LinkedHashMap<Class<Action>, Set<RequestParameter>>();
/** Max size of a valid HTTP request, in bytes. Pulled in from web.xml. */
private static int fMaxRequestSize;
private static final InitParam fMAX_REQUEST_SIZE = new InitParam("MaxHttpRequestSize", "51200");
/** Max size in bytes of an HTTP request containing a file upload. Pulled in from web.xml. */
private static int fMaxFileUploadRequestSize;
private static final InitParam fMAX_FILE_UPLOAD_REQUEST_SIZE = new InitParam("MaxFileUploadRequestSize", "51200");
/** Indicate if file upload request can be validated in detail. Pulled in from web.xml. */
private static boolean fFullyValidateFileUploads;
private static final InitParam fFULLY_VALIDATE_FILE_UPLOADS = new InitParam("FullyValidateFileUploads", "OFF");
/** Toggle for attempting detection of spam. Pulled in from web.xml. */
private static boolean fIsSpamDetectionOn;
private static final InitParam fIS_SPAM_DETECTION_ON = new InitParam("SpamDetectionInFirewall", "OFF");
private static final String CURRENT_TOKEN_CSRF = CsrfFilter.FORM_SOURCE_ID_KEY;
private static final String PREVIOUS_TOKEN_CSRF = CsrfFilter.PREVIOUS_FORM_SOURCE_ID_KEY;
/**
Special, 'internal' request parameter, used by the framework to defend against CSRF attacks.
*/
private static final RequestParameter fCSRF_REQ_PARAM = RequestParameter.withLengthCheck(CsrfFilter.FORM_SOURCE_ID_KEY);
private static final Logger fLogger = Util.getLogger(ApplicationFirewallImpl.class);
private static int getMaxSize(InitParam aInitParam, ServletConfig aConfig){
int result = Integer.parseInt(
aInitParam.fetch(aConfig).getValue()
);
if ( result < 1000 ) {
throw new IllegalArgumentException(
"Configured value of " + result + " in web.xml for " +
aInitParam.getName() +
" is too low. Please see web.xml for more information."
);
}
return result;
}
private static boolean getBooleanSetting(InitParam aInitParam, ServletConfig aConfig){
boolean result = false;
String value = aInitParam.fetch(aConfig).getValue().trim();
if( "ON".equalsIgnoreCase(value) ) {
result = true;
}
else if ("OFF".equalsIgnoreCase(value)){
//default
}
else {
throw new IllegalArgumentException(
"Configured value of " + Util.quote(value) + " in web.xml for " +
aInitParam.getName() +
" is not among the expected values. Please see web.xml for more information."
);
}
return result;
}
private static void mapActionsToExpectedParams(){
fExpectedParams = ConfigReader.fetchPublicStaticFinalFields(Action.class, RequestParameter.class);
fLogger.config("Expected Request Parameters per Web Action." + Util.logOnePerLine(fExpectedParams));
}
/**
Some denial-of-service attacks place large amounts of data in the request
params, in an attempt to overload the server. This method will check for
such requests. This check must be performed first, before any further
processing is attempted.
*/
private void checkForExtremeSize(RequestParser aRequest) throws BadRequestException {
fLogger.fine("Checking for extreme size.");
if ( isRequestExcessivelyLarge(aRequest) ) {
throw new BadRequestException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
}
}
private boolean isRequestExcessivelyLarge(RequestParser aRequestParser){
boolean result = false;
if ( aRequestParser.isFileUploadRequest() ) {
result = aRequestParser.getRequest().getContentLength() > fMaxFileUploadRequestSize;
}
else {
result = aRequestParser.getRequest().getContentLength() > fMaxRequestSize;
}
return result;
}
void checkParamNamesAndValues(Action aAction, RequestParser aRequestParser) throws BadRequestException {
if ( fExpectedParams.containsKey(aAction.getClass()) ){
Set<RequestParameter> expectedParams = fExpectedParams.get(aAction.getClass());
//this method may return file upload controls - depends on interpretation, whether to include file upload controls in this method
Enumeration paramNames = aRequestParser.getRequest().getParameterNames();
while ( paramNames.hasMoreElements() ){
String incomingParamName = (String)paramNames.nextElement();
fLogger.fine("Checking parameter named " + Util.quote(incomingParamName));
RequestParameter knownParam = matchToKnownParam(incomingParamName, expectedParams);
if( knownParam == null ){
fLogger.severe("*** Unknown Parameter *** : " + Util.quote(incomingParamName) + ". Please add public static final RequestParameter field for this item to your Action.");
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
if ( knownParam.isFileUploadParameter() ) {
fLogger.fine("File Upload parameter - value not validatable here: " + knownParam.getName());
continue; //prevents checks on values for file upload controls
}
Collection<SafeText> paramValues = aRequestParser.toSafeTexts(knownParam);
if( ! isInternalParam( knownParam) ) {
checkParamValues(knownParam, paramValues);
}
}
}
else {
String message = "Action " + aAction.getClass() + " not known to ApplicationFirewallImpl.";
fLogger.severe(message);
//this is NOT a BadRequestEx, since not outside the control of this framework.
throw new RuntimeException(message);
}
}
/** If no match is found, return <tt>null</tt>. Matches to both regular and 'internal' request params. */
private RequestParameter matchToKnownParam(String aIncomingParamName, Collection<RequestParameter> aExpectedParams){
RequestParameter result = null;
for (RequestParameter reqParam: aExpectedParams){
if ( reqParam.getName().equals(aIncomingParamName) ){
result = reqParam;
break;
}
}
if( result == null && fCSRF_REQ_PARAM.getName().equals(aIncomingParamName) ){
result = fCSRF_REQ_PARAM;
}
return result;
}
private void checkParamValues(RequestParameter aKnownReqParam, Collection<SafeText> aParamValues) throws BadRequestException {
for(SafeText paramValue: aParamValues){
if ( Util.textHasContent(paramValue) ) {
if ( ! aKnownReqParam.isValidParamValue(paramValue.getRawString()) ) {
fLogger.severe("Request parameter named " + aKnownReqParam.getName() + " has an invalid value. Its size is: " + paramValue.getRawString().length());
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
if( fIsSpamDetectionOn ){
SpamDetector spamDetector = BuildImpl.forSpamDetector();
if( spamDetector.isSpam(paramValue.getRawString()) ){
fLogger.fine("SPAM detected.");
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
}
}
}
}
private void checkSideEffectOperations(Action aAction, RequestParser aRequestParser) throws BadRequestException {
fLogger.fine("Checking for side-effect operations.");
Set<RequestParameter> expectedParams = fExpectedParams.get(aAction.getClass());
for (RequestParameter reqParam : expectedParams){
if ( "Operation".equals(reqParam.getName()) ){
String rawValue = aRequestParser.getRawParamValue(reqParam);
if (Util.textHasContent(rawValue)){
Operation operation = Operation.valueOf(rawValue);
if ( isAttemptingSideEffectOperationWithoutPOST(operation, aRequestParser) ){
fLogger.severe("Security problem. Attempted operation having side effects outside of a POST. Please use a <FORM> with method='POST'.");
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
}
}
}
}
private boolean isAttemptingSideEffectOperationWithoutPOST(Operation aOperation, RequestParser aRequestParser){
return aOperation.hasSideEffects() && !aRequestParser.getRequest().getMethod().equals("POST");
}
/**
An internal request param is not declared explicitly by the application programmer. Rather, it is defined and
used only by the framework.
*/
private boolean isInternalParam(RequestParameter aRequestParam) {
return aRequestParam.getName().equals(fCSRF_REQ_PARAM.getName());
}
private void defendAgainstCSRFAttacks(RequestParser aRequestParser) throws BadRequestException {
if( requestNeedsDefendingAgainstCSRFAttacks(aRequestParser) ) {
Id postedTokenValue = aRequestParser.toId(fCSRF_REQ_PARAM);
if ( FAILS == toIncludeCsrfTokenWithForm(postedTokenValue) ){
fLogger.severe("CSRF token not included in POSTed request. Rejecting this request, since it is likely an attack.");
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
if( FAILS == matchCurrentCSRFToken(aRequestParser, postedTokenValue) ) {
if( FAILS == matchPreviousCSRFToken(aRequestParser, postedTokenValue) ) {
fLogger.severe("CSRF token does not match the expected value. Rejecting this request, since it is likely an attack.");
throw new BadRequestException(HttpServletResponse.SC_BAD_REQUEST);
}
}
fLogger.fine("Success: no CSRF problem detected.");
}
}
private boolean requestNeedsDefendingAgainstCSRFAttacks(RequestParser aRequestParser){
boolean isPOST = aRequestParser.getRequest().getMethod().equalsIgnoreCase("POST");
boolean sessionPresent = isSessionPresent(aRequestParser);
boolean csrfFilterIsTurnedOn = false;
if( sessionPresent ) {
Id csrfTokenInSession = getCsrfTokenInSession(CURRENT_TOKEN_CSRF, aRequestParser);
csrfFilterIsTurnedOn = (csrfTokenInSession != null);
}
if( isPOST && sessionPresent && ! csrfFilterIsTurnedOn ) {
fLogger.warning("POST operation, but no CSRF form token present in existing session. This application does not have WEB4J defenses against CSRF attacks configured in the recommended way.");
}
boolean result = isPOST && sessionPresent && csrfFilterIsTurnedOn;
fLogger.fine("Session exists, and the CsrfFilter is turned on : " + csrfFilterIsTurnedOn);
fLogger.fine("Does the firewall need to check this request for CSRF attacks? : " + result);
return result;
}
private boolean toIncludeCsrfTokenWithForm(Id aCsrfToken){
return aCsrfToken != null;
}
private boolean matchCurrentCSRFToken(RequestParser aRequestParser, Id aPostedTokenValue) {
Id currentToken = getCsrfTokenInSession(CURRENT_TOKEN_CSRF, aRequestParser);
return aPostedTokenValue.equals(currentToken);
}
private boolean matchPreviousCSRFToken(RequestParser aRequestParser, Id aPostedTokenValue){
//in the case of an anonymous session, with no login, this item will be null
Id previousToken = getCsrfTokenInSession(PREVIOUS_TOKEN_CSRF, aRequestParser);
return aPostedTokenValue.equals(previousToken);
}
private boolean isSessionPresent(RequestParser aRequestParser){
boolean DO_NOT_CREATE = false;
HttpSession session = aRequestParser.getRequest().getSession(DO_NOT_CREATE);
return session != null;
}
/** Only called when session is present. No risk of null pointer exception. */
private Id getCsrfTokenInSession(String aKey, RequestParser aRequestParser){
boolean DO_NOT_CREATE = false;
HttpSession session = aRequestParser.getRequest().getSession(DO_NOT_CREATE);
return (Id)session.getAttribute(aKey);
}
}
|
package Test;
import Entity.DataIdentify1997;
import Handler.MessageHandler;
import Handler.SendHelper;
import Params.CommandType;
import Utils.ConvertUtil;
import Utils.LogUtil;
import Utils.TimeUtil;
import com.sun.org.apache.xml.internal.res.XMLErrorResources_tr;
import org.junit.Test;
import Utils.CheckUtil;
import sun.util.resources.cldr.mr.TimeZoneNames_mr;
import javax.sound.midi.SoundbankResource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
public class TestDecode {
private int low;
private int high;
@Test
public void test1() {
byte[] address = new byte[]{0x12, 0x12, 0x34, 0x37, 0x45, 0x23, 0x67};
String s = CheckUtil.GetBCDAddress(address);
System.out.println(s);
}
@Test
public void test2(){
int[] a = new int[0];
System.out.println(a.length);
}
@Test
public void test3(){
//发送地址
String s ="234567891234";
int a [] = ConvertUtil.addressToBCD(s);
System.out.println(Arrays.toString(a));
for (int i = 0; i <a.length ; i++) {
System.out.print(Integer.toHexString(a[i]));
}
System.out.println();
System.out.println();
//得到地址
byte[] b =new byte[7];
b[0]=0;//因为GetBCDAddress方法是从第一个开始的
for (int i = 0; i <6 ; i++) {
b[i+1]= (byte) a[i];
}
String str = CheckUtil.GetBCDAddress(b);
System.out.println(str);
}
@Test
public void test4(){
String src ="234567891234";
char[] c = src.toCharArray();
int[] dst= new int[6];
byte byteHigh = 0x00;
byte byteLow = 0x00;
int dstLen = src.length()/2; //如果是奇数个,3/2=1
int srcIndex = 0;
for (int bytesIndex = 0; bytesIndex < dstLen; ++bytesIndex)
{
srcIndex = bytesIndex*2;
byteHigh = (byte) (c[srcIndex] - '0');
byteLow = (byte) (c[srcIndex+1] - '0');
dst[bytesIndex] = ((byteHigh<<4) | byteLow);
}
System.out.println(Arrays.toString(dst));
}
@Test
public void test5(){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
System.out.println(year);
int month = calendar.get(Calendar.MONTH);
System.out.println(month);
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
}
@Test
public void test6(){
String str = TimeUtil.getCurrentTime();
System.out.println(str);
String year = str.substring(2,4);
System.out.println(Integer.valueOf(year));
String month = str.substring(5,7);
String day = str.substring(8,10);
String hour = str.substring(11,13);
String minutes = str.substring(14,16);
String seconds = str.substring(17,19);
System.out.println(year);
System.out.println(month);
System.out.println(day);
System.out.println(hour);
System.out.println(minutes);
System.out.println(seconds);
}
@Test
public void test7(){
String str = "123456789012";
int[] a = ConvertUtil.addressToBCD(str);
System.out.println(Arrays.toString(a));
}
@Test
public void test8(){
int a = 15;
System.out.println(a);
String c = ConvertUtil.intToHex(a);
System.out.println(c);
int ab = 0x81;
System.out.println(ConvertUtil.intToHex(ab));
}
@Test
public void test9(){
String controlCode = ConvertUtil.intToHex(129);
System.out.println(controlCode);
switch (controlCode){
case "81": //主站请求读数据应答后 -- 无后续数据帧情况
System.out.println("已经收到数据!!!");
break;
case "A1": //主站请求读数据应答后 --> 有后续数据帧情况,需要再次请求后续数据
System.out.println("eeeeee");
// System.out.println(TimeUtil.getCurrentTime() + " 主站请求读数据后" + "收到有后续数据帧情况 from "
// + readData.getDeviceAddress()
// + " " + dataTypeString
// + " = ");
//根据数据标识将获得的数据插入数据库
//
break;
default:
System.out.println("没有找到!");
break;
}
System.out.println("可以到这里!");
}
@Test
public void test10(){
int[] data = new int[]{0x10,0x90,23,34,23,41};
for (int i = 0; i <data.length ; i++) {
data[i] = data[i]+0x33;
}
byte[] a = new byte[]{(byte)0x10,(byte)0x90};
System.out.println();
System.out.println(Arrays.toString(new byte[]{(byte)0x10,(byte)0x90}));
}
@Test
public void test11(){
int a ='W';
int b = 'D';
System.out.println(a);
System.out.println(b);
System.out.println((byte)a);
System.out.println((byte)b);
}
@Test
public void test12(){
String a = "modify_Comm_Speed";
System.out.println(a.toUpperCase());
}
@Test
public void test13(){
// CommandType commandType =CommandType.CUR_NEGATIVE_ACTIVE_POWER;
// if (commandType.getValue().startsWith("0")) {
// System.out.println(commandType.getValue());
// int[] data = CheckUtil.getDataType(commandType);
// System.out.println(Arrays.toString(data));
// }
// System.out.println("*****************");
// String value = commandType.getValue();
// System.out.println(value);
// String substring1 = value.substring(0, 3);
// String substring2 = value.substring(3, 6);
// int[] dataType = new int[]{Integer.valueOf(substring1),Integer.valueOf(substring2)};
// System.out.println(Arrays.toString(dataType));
//
// byte[] bytes = {(byte) 0x10, (byte) 0x90};
// System.out.println(Arrays.toString(bytes));
}
@Test
public void test14(){
int a ='R';
String b="RRR";
byte[] bytes = b.getBytes();
System.out.println(Arrays.toString(bytes));
}
@Test
public void test15(){
//一个数字分为两个字节,高位在后
int num=2;
int offset = 0;
int[] data=new int[2];
int high = (num >>> 8);
int low = num & 0xff;
data[offset] = low;
data[offset + 1] = high;
System.out.println(Arrays.toString(data));
}
@Test
public void test16(){
////获得一个整数(不超过两位)的BCD码
int num =99;
int i = (((num / 10) << 4) & 0xf0) | ((num % 10) & 0x0f);
System.out.println(i);
}
@Test
public void test17(){
String s = "101010101001";
int[] ints = ConvertUtil.addressToBCD(s);
System.out.println(Arrays.toString(ints));
byte[] b = new byte[ints.length+1];
b[0]=0;
for (int i=0;i<ints.length;i++){
b[i+1]=(byte) ints[i];
}
System.out.println(Arrays.toString(b));
String s1 = CheckUtil.GetBCDAddress(b);
System.out.println(s1);
}
@Test
public void test18(){
String s = "459378000004";
int[] ints = ConvertUtil.addressToBCD(s);
System.out.println(Arrays.toString(ints));
int[] time = TimeUtil.getTime();
System.out.println(Arrays.toString(time));
}
}
|
package com.niit.MobileShoppingBackend.DAO;
import java.util.List;
import com.niit.MobileShoppingBackend.DTO.Cart;
import com.niit.MobileShoppingBackend.DTO.CartLine;
public interface CartLineDao {
//for adding the cartLine into the databse
public boolean add(CartLine cartLine);
//for updating the cartLine
public boolean update(CartLine cartLine);
//for deleting the cartLine
public boolean delete(CartLine cartLine);
//get the cartLine by its id for displaying the carLine
public CartLine get(int id);
//getting the list of carline by the users cartid
public List<CartLine> list(int cart_id);
//getting the list of the available cartLine by the cartId
public List<CartLine> availableCartLineList(int cart_id);
//get the cartLine by the productid and cart id
public CartLine getByProductIdAndCartId(int cart_id,int product_id);
//updating the cart
public boolean update(Cart cart);
}
|
package br.com.helpdev.quaklog.usecase.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
@Builder
public class PlayerDTO {
private Integer id;
private String name;
private List<String> items;
private Integer kills;
private Map<String, String> parameters;
@JsonProperty("kd_history")
private List<KillHistoryDTO> kdHistory;
private List<PlayerStatusDTO> status;
}
|
package com.wipe.zc.journey.http;
public class AppURL {
// 主机地址
public static String HostUrl = "http://121.42.185.7:8080/Journey/";
// public static String HostUrl = "http://10.0.3.2:8080/Journey/";
// public static String HostUrl = "http://120.27.97.82:8080/Journey/";
// 上传地址
public static String upLoad = HostUrl + "upload";
// 登陆
public static String login = HostUrl + "login";
// 注册表单
public static String reg = HostUrl + "reg";
// 获取用户信息
public static String getuser = HostUrl + "getuser";
// 获取服务端图片
public static String getimage = HostUrl + "getimage";
// 获取服务端行程
public static String getjourney = HostUrl + "getjourney";
// 获取服务端行程
public static String getjourneydate = HostUrl + "getjourneydate";
// 添加行程
public static String addjourney = HostUrl + "addjourney";
//删除行程
public static String deletejourney = HostUrl + "deletejourney";
//显示图片
public static String showimage = HostUrl + "showimage";
}
|
package vegoo.newstock.core.dao;
import java.util.Date;
public class FhsgDao extends TaggedDao{
// private String MarketType;
private String SCode;
// private String Name;
private double SZZBL; // 送转总比例
private double SGBL; // 送股比例
private double ZGBL; // 转股比例
private double XJFH; // 现金分红
private double GXL; // 股息率
private Date YAGGR; // 预案公告日
private Date GQDJR; // 股权登记日
private Date CQCXR; //股权除息日
private double YAGGRHSRZF; // 预案公告日后10日涨幅
private double GQDJRQSRZF; //股权登记日后10日涨幅
private double CQCXRHSSRZF; //股权除息日后10日涨幅
private double YCQTS; // 未知
private double TotalEquity; // 总股本
private double EarningsPerShare; // 每股收益
private double NetAssetsPerShare; // 每股净资产
private double MGGJJ; // 每股公积金
private double MGWFPLY; //每股未分配利润
private double JLYTBZZ; //净利润同比增长率
private Date RDate; // 报告期
private Date ResultsbyDate; //业绩披露日期
private String ProjectProgress; //方案进度
private String AllocationPlan; // 分配预案
private double adjustPrice;
public String getSCode() {
return SCode;
}
public void setSCode(String code) {
SCode = code;
}
public double getSZZBL() {
return SZZBL;
}
public void setSZZBL(double sZZBL) {
SZZBL = sZZBL;
}
public double getSGBL() {
return SGBL;
}
public void setSGBL(double sGBL) {
SGBL = sGBL;
}
public double getZGBL() {
return ZGBL;
}
public void setZGBL(double zGBL) {
ZGBL = zGBL;
}
public double getXJFH() {
return XJFH;
}
public void setXJFH(double xJFH) {
XJFH = xJFH;
}
public double getGXL() {
return GXL;
}
public void setGXL(double gXL) {
GXL = gXL;
}
public Date getYAGGR() {
return YAGGR;
}
public void setYAGGR(Date yAGGR) {
YAGGR = yAGGR;
}
public Date getGQDJR() {
return GQDJR;
}
public void setGQDJR(Date gQDJR) {
GQDJR = gQDJR;
}
public Date getCQCXR() {
return CQCXR;
}
public void setCQCXR(Date cQCXR) {
CQCXR = cQCXR;
}
public double getYAGGRHSRZF() {
return YAGGRHSRZF;
}
public void setYAGGRHSRZF(double yAGGRHSRZF) {
YAGGRHSRZF = yAGGRHSRZF;
}
public double getGQDJRQSRZF() {
return GQDJRQSRZF;
}
public void setGQDJRQSRZF(double gQDJRQSRZF) {
GQDJRQSRZF = gQDJRQSRZF;
}
public double getCQCXRHSSRZF() {
return CQCXRHSSRZF;
}
public void setCQCXRHSSRZF(double cQCXRHSSRZF) {
CQCXRHSSRZF = cQCXRHSSRZF;
}
public double getTotalEquity() {
return TotalEquity;
}
public void setTotalEquity(double totalEquity) {
TotalEquity = totalEquity;
}
public double getEarningsPerShare() {
return EarningsPerShare;
}
public void setEarningsPerShare(double earningsPerShare) {
EarningsPerShare = earningsPerShare;
}
public double getNetAssetsPerShare() {
return NetAssetsPerShare;
}
public void setNetAssetsPerShare(double netAssetsPerShare) {
NetAssetsPerShare = netAssetsPerShare;
}
public double getMGGJJ() {
return MGGJJ;
}
public void setMGGJJ(double mGGJJ) {
MGGJJ = mGGJJ;
}
public double getMGWFPLY() {
return MGWFPLY;
}
public void setMGWFPLY(double mGWFPLY) {
MGWFPLY = mGWFPLY;
}
public double getJLYTBZZ() {
return JLYTBZZ;
}
public void setJLYTBZZ(double jLYTBZZ) {
JLYTBZZ = jLYTBZZ;
}
public Date getRDate() {
return RDate;
}
public void setRDate(Date reportingPeriod) {
RDate = reportingPeriod;
}
public Date getResultsbyDate() {
return ResultsbyDate;
}
public void setResultsbyDate(Date resultsbyDate) {
ResultsbyDate = resultsbyDate;
}
public String getProjectProgress() {
return ProjectProgress;
}
public void setProjectProgress(String projectProgress) {
ProjectProgress = projectProgress;
}
public String getAllocationPlan() {
return AllocationPlan;
}
public void setAllocationPlan(String allocationPlan) {
AllocationPlan = allocationPlan;
}
public double getYCQTS() {
return YCQTS;
}
public void setYCQTS(double yCQTS) {
YCQTS = yCQTS;
}
public int getDataTag() {
return hashCode();
}
@Override
public int hashCode() {
String data = String.format("%s-%tF-%f-%f-%f-%f-%f-%tF-%tF-%tF-%s",
SCode,
RDate, // 报告期
SZZBL, // 送转总比例
SGBL, // 送股比例
ZGBL, // 转股比例
XJFH, // 现金分红
GXL, // 股息率
YAGGR, // 预案公告日
GQDJR, // 股权登记日
CQCXR, //股权除息日
ProjectProgress //方案进度
);
return data.hashCode();
}
public double getAdjustPrice() {
return adjustPrice;
}
public void setAdjustPrice(double adjustPrice) {
this.adjustPrice = adjustPrice;
}
}
|
import java.util.*;public class SoftmaxTest
{
public static void main(String[] args)
{
double[] inputs ={5d,2d,-1d,3d};
softmax(inputs);
System.out.println(Arrays.toString(inputs));
}
private static double[] softmax(double[] inputs)
{
if(inputs==null)
{
return null;
}
double sum = 0.0d;
double finalSum = 0.0d;
for(int i =0; i<inputs.length;i++)
{
sum = sum + Math.exp(inputs[i]);
}
for(int j=0;j<inputs.length;j++)
{
inputs[j] = Math.exp(inputs[j])/sum;
finalSum = inputs[j]+finalSum;
}
System.out.println(finalSum);
System.out.println(sum);
return inputs;
}
}
|
package com.example.tanapon.computerproject1;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* Created by Tanapon on 18/4/2560.
*/
public class Home_ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer[] imager = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3};
public Home_ViewPagerAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return imager.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.home_castom, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageResource(imager[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager)container;
View view = (View) object;
vp.removeView(view);
}
}
|
package test;
import org.apache.log4j.Logger;
public class Log4jTest {
public static Logger log = Logger.getLogger(Log4jTest.class.getName());
/**
* @param args
*/
public static void main(String[] args) {
log.info("Entering application.");
}
}
|
package net.minecraft.server;
import java.io.OutputStream;
import net.minecraft.util.LoggingPrintStream;
public class DebugLoggingPrintStream extends LoggingPrintStream {
public DebugLoggingPrintStream(String p_i47315_1_, OutputStream p_i47315_2_) {
super(p_i47315_1_, p_i47315_2_);
}
protected void logString(String string) {
StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace();
StackTraceElement stacktraceelement = astacktraceelement[Math.min(3, astacktraceelement.length)];
LOGGER.info("[{}]@.({}:{}): {}", this.domain, stacktraceelement.getFileName(), Integer.valueOf(stacktraceelement.getLineNumber()), string);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\server\DebugLoggingPrintStream.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.kiseki.test;
import org.junit.Test;
import org.redisson.api.RHyperLogLog;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class ClusterTest extends BaseTest{
@Test
public void test() throws Exception{
while (true){
try {
redissonClient.getBucket("test"+System.currentTimeMillis()).set("test", 1, TimeUnit.SECONDS);
System.out.println(LocalDateTime.now().toString() + ":ok");
}catch (Exception e){
System.out.println(LocalDateTime.now().toString() + ":error");
}finally {
Thread.sleep(1000);
}
}
}
} |
/*
FILMES
titulo, titulo original, diretor, data de lançamento, sinopse, IMAGEM, GENERO
*/
/**
*
* @author Roziana
*/
public class Filmes {
private String titulo,
tituloOriginal,
diretor,
anoLancamento,
sinopse,
imagem;
private int genero;
private float valorDiaria;
public float getValorDiaria() {
return valorDiaria;
}
public void setValorDiaria(float valorDiaria) {
this.valorDiaria = valorDiaria;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getTituloOriginal() {
return tituloOriginal;
}
public void setTituloOriginal(String tituloOriginal) {
this.tituloOriginal = tituloOriginal;
}
public String getDiretor() {
return diretor;
}
public void setDiretor(String diretor) {
this.diretor = diretor;
}
public String getAnoLancamento() {
return anoLancamento;
}
public void setAnoLancamento(String anoLancamento) {
this.anoLancamento = anoLancamento;
}
public String getSinopse() {
return sinopse;
}
public void setSinopse(String sinopse) {
this.sinopse = sinopse;
}
public String getImagem() {
return imagem;
}
public void setImagem(String imagem) {
this.imagem = imagem;
}
public int getGenero() {
return genero;
}
public void setGenero(int genero) {
this.genero = genero;
}
}
|
package com.example.billage.frontend.ui.mypage.subView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.billage.R;
public class AccountModify extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypage_account_modify);
}
@Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.slide_enter, R.anim.slide_exit);
super.onBackPressed();
}
}
|
package com.mediacom.service;
import java.util.List;
import javax.persistence.EntityManager;
//import javax.persistence.criteria.CriteriaBuilder;
//import javax.persistence.criteria.CriteriaQuery;
//import javax.persistence.criteria.Root;
import com.mediacom.domain.Member;
//import com.mediacom.domain.MemberRowMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//import com.mediacom.util.ApplicationContextProvider;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//meat and potatoes
@Service("member_service")
public class MemberServiceDaoImpl implements MemberServiceDao
{
@Autowired
private JdbcTemplate jdbcTemplate;
@SuppressWarnings({ "unchecked", "rawtypes" })
public Member findById(int id)
{
Member searchResult = new Member();
String sql = "SELECT * FROM MEMBER WHERE ID=?";
try{
searchResult = (Member)jdbcTemplate.queryForObject(
sql, new Object[] { id }, new BeanPropertyRowMapper(Member.class));
}catch(Exception e){
System.out.println("Issue searching the database! : " + searchResult.toString());
e.printStackTrace();
}
return searchResult;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Member findByEmail(String email)
{
Member searchResult = new Member();
String sql = "SELECT * FROM MEMBER WHERE EMAIL=?";
try{
searchResult = (Member)jdbcTemplate.queryForObject(
sql, new Object[] { email }, new BeanPropertyRowMapper(Member.class));
}catch(Exception e){
System.out.println("Issue searching the database! : " + searchResult.toString());
e.printStackTrace();
}
System.out.println("Search Results : " + searchResult.getName());
return searchResult;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<Member> findAllOrderedByName()
{
List<Member> members = null;
String sql = "SELECT * FROM MEMBER ORDER BY NAME ASC";
try{
members = jdbcTemplate.query(sql,
new BeanPropertyRowMapper(Member.class));
}catch(Exception e){
System.out.println("Issue searching the database!");
e.printStackTrace();
}
return members;
}
}
|
package com.singtel.nsb.mobile.processor;
import static com.singtel.nsb.mobile.constants.HeaderConstants.ID;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DeleteSubProfileConfigProcessorTest extends CamelTestSupport {
@InjectMocks
@Spy
private DeleteSubProfileConfigProcessor deleteSubProfileConfigProcessor;
@EndpointInject(uri = "mock:output")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:producer")
protected ProducerTemplate template;
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:producer").process(deleteSubProfileConfigProcessor).to("mock:output");
}
};
}
@Test
public void given_Patch_Request_Then_Process() throws InterruptedException {
String request = "{\"reqId\": \"00147952_500828\",\"name\": \"mobileActivate\"}";
resultEndpoint.setExpectedCount(1);
Map<String, Object> headers = new HashMap<>();
headers.put(ID, "12345");
template.sendBodyAndHeaders("direct:producer", request, headers);
resultEndpoint.assertIsSatisfied();
}
}
|
/*
* 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 tolteco.sigma.view;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JPanel;
import tolteco.sigma.controller.ClienteController;
import tolteco.sigma.controller.FinancaController;
import tolteco.sigma.controller.ServicoController;
import tolteco.sigma.controller.UsuarioController;
import tolteco.sigma.controller.VersionController;
import tolteco.sigma.model.dao.DatabaseException;
import tolteco.sigma.model.entidades.Access;
import tolteco.sigma.model.entidades.Version;
import tolteco.sigma.utils.DefaultConfigs;
import tolteco.sigma.utils.SDate;
import tolteco.sigma.utils.logging.BufferedPaneOutputStream;
import tolteco.sigma.utils.logging.PaneHandler;
import tolteco.sigma.view.cliente.MainCliente;
import tolteco.sigma.view.financas.MainFinanca;
import tolteco.sigma.view.servicos.MainServico;
import tolteco.sigma.view.usuarios.MainUsuario;
import tolteco.sigma.view.version.MainVersion;
/**
*
* @author Juliano
*/
public class MainFrame extends javax.swing.JFrame {
//private static final int ACCESS_LEVEL = 0; //Usado para testes - Nivel de acesso
public static final Logger LOG = Logger.getLogger(MainFrame.class.getName());
private final MainView child;
private final ClienteController clienteController;
private final FinancaController financaController;
private Version ver;
public ClienteController getClienteController(){
return clienteController;
}
private static void initLogger(MainView mainChild){
mainChild.console.setEditable(false);
BufferedPaneOutputStream oStream = new BufferedPaneOutputStream(mainChild.console);
LOG.addHandler(new PaneHandler(oStream));
LOG.setLevel(Level.FINE);
}
private JButton defineLogOutButton(){
JButton logOut = new JButton("Logout");
logOut.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/tolteco/sigma/view/images/User/LogOut.png")));
logOut.addActionListener((ActionEvent e) -> {
try {
Sistema.logout();
} catch (DatabaseException ex) {
MainFrame.LOG.severe("Falha ao tentar deslogar seguramente do sistema.");
}
this.setVisible(false);
this.dispose();
});
logOut.setPreferredSize( new Dimension (120,26));
return logOut;
}
private JButton defineExitButton(){
JButton exit = new JButton("Sair");
exit.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/tolteco/sigma/view/images/User/SystemOut.png")));
exit.addActionListener((ActionEvent e) -> {
Sistema.shutdown();
this.setVisible(false);
this.dispose();
});
exit.setPreferredSize( new Dimension (90,26));
return exit;
}
/**
* Creates new form MainFrame
* @param cliente
* @param financa
* @param servico
* @param usuario
* @param version
*/
public MainFrame(ClienteController cliente,
FinancaController financa, ServicoController servico,
UsuarioController usuario, VersionController version) {
initComponents();
clienteController = cliente;
//new Font(DefaultConfigs.SYSTEMFONT, Font.BOLD|Font.ITALIC, 16)
PainelGuias.setFont( new Font(DefaultConfigs.SYSTEMFONT, Font.PLAIN, 16) );
int titleWidth=0;
child = new MainView(this);
PainelGuias.add(child);
PainelGuias.setTitleAt(titleWidth++, "Principal");
MainFrame.initLogger(child);
JPanel panel1 = new MainCliente(this, cliente);
PainelGuias.add(panel1);
PainelGuias.setTitleAt(titleWidth++, "Clientes");
financaController = financa;
if (Sistema.getUser().getAccessLevel() != Access.FUNCIONARIO){
JPanel panel2 = new MainFinanca(this, financa);
PainelGuias.add(panel2);
PainelGuias.setTitleAt(titleWidth++, "Finanças");
} else {
child.disableActivityTable();
}
JPanel panel3 = new MainServico(this, servico);
PainelGuias.add(panel3);
PainelGuias.setTitleAt(titleWidth++, "Serviços");
BarraDeMenu.add(Box.createHorizontalGlue());
if (Sistema.getUser().getAccessLevel() == Access.ROOT){
JMenu jmenu = new JMenu("Configurações");
BarraDeMenu.add(jmenu);
JPanel panel4 = new MainUsuario(this, usuario);
PainelGuias.add(panel4);
PainelGuias.setTitleAt(titleWidth++, "Usuários");
JPanel panel5 = new MainVersion(this, version);
PainelGuias.add(panel5);
PainelGuias.setTitleAt(titleWidth++, "Versões");
}
try {
ver = version.fetchLatestVersion();
} catch (DatabaseException ex) {
LOG.severe(ex.getLocalizedMessage());
}
BarraDeMenu.add(defineLogOutButton());
BarraDeMenu.add(defineExitButton());
//BalloonTip bal = new BalloonTip(panel, "Tooltip msg");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
PainelGuias = new javax.swing.JTabbedPane();
BarraDeMenu = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("SIGMA");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
MainFrame.this.windowClosed(evt);
}
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
PainelGuias.setMinimumSize(new java.awt.Dimension(887, 580));
jMenu1.setText("Help");
jMenuItem1.setText("About");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
BarraDeMenu.add(jMenu1);
setJMenuBar(BarraDeMenu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PainelGuias, javax.swing.GroupLayout.PREFERRED_SIZE, 760, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PainelGuias, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
ViewUtils.centerFrame(this);
ViewUtils.setSIGMAIcon(this);
child.initTable();
}//GEN-LAST:event_formWindowOpened
private void windowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_windowClosed
String consoleData = child.console.getText();
final File FILE = new File("log\\" + SDate.DATE_LOG_FILE.format(new Date()) + ".LOG");
BufferedWriter bw;
try {
bw = new BufferedWriter( new FileWriter(FILE));
bw.write(consoleData);
bw.close();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_windowClosed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
About ab = new About(this, ver, ver.getMinorDate());
ab.setVisible(true);
this.setEnabled(false);
}//GEN-LAST:event_jMenuItem1ActionPerformed
/**
* Método principal para a criação de um frame.
* Coloca o sistema no "look and feel" de acordo
* com:
* {@link tolteco.sigma.view.MainFrame#LOOKANDFEEL}.
* Chama o construtor default para inicialização
* de componentes.
* @param args the command line arguments
*/
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (DefaultConfigs.SYSTEMLOOK.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Sistema.assembleMain().setVisible(true);
}
});
}
public JComponent getExceptionTab(){
return PainelGuias;
}
public MainView getMainView(){
return child;
}
public FinancaController getFinancaController(){
return financaController;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuBar BarraDeMenu;
private javax.swing.JTabbedPane PainelGuias;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration//GEN-END:variables
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.hook;
import de.hybris.platform.commerceservices.service.data.CommerceCartMetadataParameter;
/**
* A hook interface into before and after cart metadata (i.e. name, description) update lifecycle
*/
public interface CommerceCartMetadataUpdateMethodHook
{
/**
* Executed before commerce cart metadata update.
*
* @param parameter
* a bean holding any number of additional attributes a client may want to pass to the method
* @throws IllegalArgumentException
* if any attributes fail validation
*/
void beforeMetadataUpdate(CommerceCartMetadataParameter parameter);
/**
* Executed after commerce cart metadata update.
*
* @param parameter
* a bean holding any number of additional attributes a client may want to pass to the method
*/
void afterMetadataUpdate(CommerceCartMetadataParameter parameter);
}
|
/*
* Copyright 2013 Josh Broch
* All rights reserved.
*/
package net.jbroch.dao.impl;
import net.jbroch.dao.UserDao;
/**
* Implementation of {@link UserDao}.
*/
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
}
}
|
package com.huyikang.design.pattern.abstractfactory;
import com.huyikang.design.model.abstractfactory.Color;
import com.huyikang.design.model.abstractfactory.Shape;
import com.huyikang.design.model.abstractfactory.color.Blue;
import com.huyikang.design.model.abstractfactory.color.Green;
import com.huyikang.design.model.abstractfactory.color.Yellow;
public class ColorFactory extends AbstractFactory {
@Override
public Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("yellow")){
return new Yellow();
} else if(color.equalsIgnoreCase("green")){
return new Green();
} else if(color.equalsIgnoreCase("blue")){
return new Blue();
}
return null;
}
@Override
public Shape getShape(String shapeType) {
return null;
}
}
|
package com.suresh.learnings.twentynineteen.march;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RandomNumberMasker {
private List<String> zeroToNineDigitsList;
public RandomNumberMasker() {
super();
this.zeroToNineDigitsList = new ArrayList<String> (10);
}
public List<String> generateSequentialNumberList() {
for (int i = 0; i < 10; i++) {
this.zeroToNineDigitsList.add("" + i);
}
return this.zeroToNineDigitsList;
}
/**
* <ul>
* <li> 1. Generate sequential number list.</li>
* <li> 2. Shuffle the sequential number list.</li>
* <li> 3. Extract the first number in the list.</li>
* <li> 4. When the first number in the shuffled list is greater than the length
* of the string to be masked then subtract it with the mask digit length.</li>
* <li> 5. Since the digits has to be masked continuously for the given length,
* identify the indexes to be masked.</li>
* <li> 6. Once the continuous indexes are identified replace the index positions with
* masked character ('X')</li>
* <li> 7. Return the masked input.</li>
* </ul>
*/
public String generateMaskedNumber(String input, int maskDigitLength) {
String maskedInput = null;
if (input == null || input.length() < 10) {
System.out.println("Invalid Input!!!");
return maskedInput;
}
if (maskDigitLength < 3) {
System.out.println("Invalid Mask digit length!!!");
return maskedInput;
}
maskedInput = performInputMasking(input, maskDigitLength);
return maskedInput;
}
private String performInputMasking(String input, int maskDigitLength) {
String maskedInput = null;
List<String> shuffledList = generateShuffledList();
if (shuffledList == null || shuffledList.size() < 1) {
System.out.println("Invalid Shuffled list-->");
return maskedInput;
}
int[] maskNumberSeq;
maskNumberSeq = identifyIndexPositions(shuffledList, input, maskDigitLength);
maskedInput = maskInputWithIndexPosition(maskNumberSeq, input, maskDigitLength);
return maskedInput;
}
private String maskInputWithIndexPosition(int[] maskNumberSeq, String input, int maskDigitLength) {
char[] charArrayList = new char[10];
charArrayList = input.toCharArray();
int maskCountSeq = 0;
char[] maskedInput = new char[10];
for (int i = 0; i < charArrayList.length; i++) {
if (maskCountSeq < maskDigitLength && i == maskNumberSeq[maskCountSeq]) {
charArrayList[i] = 'X';
++maskCountSeq;
}
maskedInput[i] = charArrayList[i];
//System.out.print(maskedInput[i]);
}
return String.valueOf(maskedInput);
}
private int[] identifyIndexPositions(List<String> shuffledList, String input, int maskDigitLength) {
int[] maskNumberSeq = new int[3];
int startPosition = 0;
Integer firstValue = Integer.valueOf(shuffledList.get(0));
if (firstValue.intValue() > (input.length() - maskDigitLength)) {
startPosition = input.length() - maskDigitLength;
System.out.println("startPosition-->" + startPosition);
} else {
startPosition = firstValue.intValue();
}
for (int i = 0; i < maskDigitLength; i++) {
maskNumberSeq[i] = startPosition++;
System.out.println("maskNumberSeq["+ i + "]" + maskNumberSeq[i]);
}
return maskNumberSeq;
}
private List<String> generateShuffledList() {
List<String> shuffledList = null;
shuffledList = this.generateSequentialNumberList();
Collections.shuffle(shuffledList);
return shuffledList;
}
public List<String> getZeroToNineDigitsList() {
return zeroToNineDigitsList;
}
public void setZeroToNineDigitsList(List<String> zeroToNineDigitsList) {
this.zeroToNineDigitsList = zeroToNineDigitsList;
}
} |
package org.motechproject.server.filters;
import java.util.List;
public interface FilterChain<T> {
public List<T> doFilter(List<T> collection) ;
}
|
package gil.action;
import bol.BOLObject;
import gil.MainFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
public class AddMode implements ActionListener {
BOLObject obj;
MainFrame frame;
public AddMode(BOLObject obj, MainFrame frame) {
this.obj = obj;
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
Object chkBox = e.getSource();
if (chkBox == frame.getPanPara().getCbFireMode()) {
JCheckBox cb = (JCheckBox)chkBox;
if (cb.isSelected()) {
this.obj.setFireMode(true);
frame.getPanMenu().getFireItem().setSelected(true);
frame.getPanPara().getFeuCaserButton().setEnabled(true);
frame.getPanPara().getCendreCaserButton().setEnabled(true);
frame.getPanText().getNbFeu().setVisible(true);
frame.getPanText().getNbInfecte().setVisible(false);
this.obj.setInvasionMode(false);
frame.getPanMenu().getInfectItem().setSelected(false);
frame.getPanPara().getCbInvasionMode().setSelected(false);
frame.getPanPara().getInsecteCaserButton().setEnabled(false);
} else {
this.obj.setFireMode(false);
frame.getPanMenu().getFireItem().setSelected(false);
frame.getPanPara().getFeuCaserButton().setEnabled(false);
frame.getPanPara().getCendreCaserButton().setEnabled(false);
}
}
if(chkBox == frame.getPanPara().getCbInvasionMode()){
JCheckBox cb = (JCheckBox)chkBox;
if (cb.isSelected()) {
this.obj.setInvasionMode(true);
frame.getPanMenu().getInfectItem().setSelected(true);
frame.getPanPara().getInsecteCaserButton().setEnabled(true);
frame.getPanText().getNbFeu().setVisible(false);
frame.getPanText().getNbInfecte().setVisible(true);
this.obj.setFireMode(false);
frame.getPanMenu().getFireItem().setSelected(false);
frame.getPanPara().getCbFireMode().setSelected(false);
frame.getPanPara().getFeuCaserButton().setEnabled(false);
frame.getPanPara().getCendreCaserButton().setEnabled(false);
} else {
this.obj.setInvasionMode(false);
frame.getPanMenu().getInfectItem().setSelected(false);
frame.getPanPara().getInsecteCaserButton().setEnabled(false);
}
}
if (chkBox == frame.getPanMenu().getFireItem()) {
JCheckBoxMenuItem cb = (JCheckBoxMenuItem)chkBox;
if (cb.isSelected()) {
this.obj.setFireMode(true);
frame.getPanPara().getCbFireMode().setSelected(true);
frame.getPanPara().getFeuCaserButton().setEnabled(true);
frame.getPanPara().getCendreCaserButton().setEnabled(true);
frame.getPanText().getNbFeu().setVisible(true);
frame.getPanText().getNbInfecte().setVisible(false);
this.obj.setInvasionMode(false);
frame.getPanMenu().getInfectItem().setSelected(false);
frame.getPanPara().getCbInvasionMode().setSelected(false);
frame.getPanPara().getInsecteCaserButton().setEnabled(false);
} else {
this.obj.setFireMode(false);
frame.getPanPara().getCbFireMode().setSelected(false);
frame.getPanPara().getFeuCaserButton().setEnabled(false);
frame.getPanPara().getCendreCaserButton().setEnabled(false);
}
}
if (chkBox == frame.getPanMenu().getInfectItem()) {
JCheckBoxMenuItem cb = (JCheckBoxMenuItem)chkBox;
if (cb.isSelected()) {
this.obj.setInvasionMode(true);
frame.getPanPara().getCbInvasionMode().setSelected(true);
frame.getPanPara().getInsecteCaserButton().setEnabled(true);
this.obj.setFireMode(false);
frame.getPanText().getNbFeu().setVisible(false);
frame.getPanText().getNbInfecte().setVisible(true);
frame.getPanMenu().getFireItem().setSelected(false);
frame.getPanPara().getCbFireMode().setSelected(false);
frame.getPanPara().getFeuCaserButton().setEnabled(false);
frame.getPanPara().getCendreCaserButton().setEnabled(false);
} else {
this.obj.setInvasionMode(false);
frame.getPanPara().getCbInvasionMode().setSelected(false);
frame.getPanPara().getInsecteCaserButton().setEnabled(false);
}
}
}
}
|
package com.alanb.gesturetextinput;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.alanb.gesturecommon.CommonUtils;
import com.alanb.gesturecommon.MathUtils;
import com.alanb.gesturecommon.OneDInputView;
import com.alanb.gesturecommon.TouchEvent;
public class GlassOneDInputView extends OneDInputView
implements View.OnAttachStateChangeListener
{
private final String TAG = this.getClass().getName();
private static final float SWIPE_POSDIFF_THRESH = 0.2f;
public GlassOneDInputView(Context context, AttributeSet set)
{
super(context, set);
setCustomTouchWidth(context.getResources().getInteger(R.integer.glass_touchpad_w));
setCustomTouchHeight(context.getResources().getInteger(R.integer.glass_touchpad_h));
setFocusable(true);
setFocusableInTouchMode(true);
}
@Override
public void onViewAttachedToWindow(View v)
{
requestFocus();
}
@Override
public void onViewDetachedFromWindow(View v)
{
}
@Override
public boolean dispatchGenericFocusedEvent(MotionEvent event)
{
if (isFocused())
{
super.onTouchEvent(event);
}
return super.dispatchGenericFocusedEvent(event);
}
@Override
public TouchEvent generateTouchEvent(MotionEvent motionEvent)
{
TouchEvent parent_e = super.generateTouchEvent(motionEvent);
double[] vel = CommonUtils.posDiffFromMotionEvents(motionEvent);
if (Math.hypot(vel[0], vel[1]) >= SWIPE_POSDIFF_THRESH &&
Math.abs(Math.atan2(vel[1], vel[0]) + Math.PI/2) <= (Math.PI/4 - 0.1))
{
parent_e = TouchEvent.DROP;
}
return parent_e;
}
}
|
package it.objectmethod.model;
public class Country {
private String code;
private String name;
private String Continent;
private String Region;
private int surfaceArea;
private int indepYear;
private int Population;
private int lifeExpectancy;
private int GNP;
private int GNPOld;
private String localName;
private String govermentForm;
private String headOfState;
private int capital;
private String code2;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return Continent;
}
public void setContinent(String continent) {
Continent = continent;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public int getSurfaceArea() {
return surfaceArea;
}
public void setSurfaceArea(int surfaceArea) {
this.surfaceArea = surfaceArea;
}
public int getIndepYear() {
return indepYear;
}
public void setIndepYear(int indepYear) {
this.indepYear = indepYear;
}
public int getPopulation() {
return Population;
}
public void setPopulation(int population) {
Population = population;
}
public int getLifeExpectancy() {
return lifeExpectancy;
}
public void setLifeExpectancy(int lifeExpectancy) {
this.lifeExpectancy = lifeExpectancy;
}
public int getGNP() {
return GNP;
}
public void setGNP(int gNP) {
GNP = gNP;
}
public int getGNPOld() {
return GNPOld;
}
public void setGNPOld(int gNPOld) {
GNPOld = gNPOld;
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public String getGovermentForm() {
return govermentForm;
}
public void setGovermentForm(String govermentForm) {
this.govermentForm = govermentForm;
}
public String getHeadOfState() {
return headOfState;
}
public void setHeadOfState(String headOfState) {
this.headOfState = headOfState;
}
public int getCapital() {
return capital;
}
public void setCapital(int capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2;
}
@Override
public String toString() {
String value="\n"+code+" "+name+" "+ Continent+" "+Population+surfaceArea+" "+"\n";
return value;
}
}
|
package nl.rug.oop.flaps.aircraft_editor.controller.listeners.infopanel_listeners.cargo;
import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.CargoConfigPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* listens to change in the slider in the {@link CargoConfigPanel}
* if the value changes the cargoUnitWeightLabel in {@link CargoConfigPanel}
*
* */
public class CargoSliderListener implements ChangeListener {
private final CargoConfigPanel panel;
public CargoSliderListener(CargoConfigPanel panel) {
this.panel = panel;
}
@Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() == panel.getInfoSlider()) {
panel.updateCargoUnitWeightLabel();
}
}
}
|
package com.chilkens.timeset.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by hoody on 2017-08-20.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PickResponse {
Long pickId;
public static PickResponse build(Long pickId) {
return PickResponse.builder()
.pickId(pickId)
.build();
}
}
|
package com.tencent.mm.plugin.appbrand.app;
import com.tencent.mm.plugin.appbrand.widget.a.a;
import com.tencent.mm.plugin.appbrand.widget.h;
import com.tencent.mm.plugin.appbrand.widget.i;
import com.tencent.mm.plugin.appbrand.widget.m;
public final class g implements a {
public final i abc() {
return e.abc();
}
public final m abd() {
return e.abd();
}
public final h abj() {
return e.abj();
}
}
|
package com.fansolomon.Behavioral.Visitor.Computer;
import com.fansolomon.Behavioral.Visitor.Computer.impl.Computer;
import com.fansolomon.Behavioral.Visitor.Computer.impl.Keyboard;
import com.fansolomon.Behavioral.Visitor.Computer.impl.Monitor;
import com.fansolomon.Behavioral.Visitor.Computer.impl.Mouse;
public interface ComputerPartVisitor {
void visit(Computer computer);
void visit(Mouse mouse);
void visit(Keyboard keyboard);
void visit(Monitor monitor);
}
|
package Bomberman;
public enum Animation {
MOVE_EAST,MOVE_WEST,MOVE_NORTH,MOVE_SOUTH,IDLE,DIE,
APPARITION,CHEST_OPEN,
EXPLOSION, EXIT,BOMB,IMPACT,
ITEM_BOMB,HURT,ITEM_RANGE,ITEM_DAMAGE,ITEM_PV,ITEM_KEY,ITEM_SPEED,
OBSTACLE,BACKGROUND,
GRASS;
public final static int DURATION_ANIMATION_ITEM=2000;
public final static int DURATION_ANIMATION_CHEST=800;
public final static int DURATION_ANIMATION_EXIT =1500;
public final static int ANIMATION_EXPLOSION =700;
public final static int DURATION_ANIMATION_HURT=700;
public final static int DURATION_ANIMATION_HURT_PLAYER=1000;
}
|
package ba.bitcamp.LabS07D04;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class Circle {
private int x;
private int y;
private int radius;
private boolean isFilled;
private Color color;
private int speedX;
private int speedY;
private Dimension windowDimension;
private int centarX;
private int centarY;
public Circle (int x, int y, int radius, boolean isFilled, Color color, int speedX, int speedY, Dimension windowDimension) {
this.x = x;
this.y = y;
this.radius = radius;
this.isFilled = isFilled;
this.color = color;
this.speedX = speedX;
this.speedY = speedY;
this.windowDimension = windowDimension;
this.centarX = x+radius/2;
this.centarY = x+radius/2;
}
public void draw(Graphics g) {
move();
g.setColor(color);
if(isFilled == true) {
g.fillOval(x, y, radius, radius);
} else {
g.drawOval(x, y, radius, radius);
}
}
private void move() {
if (x < 0 || x > windowDimension.getWidth()-radius) {
speedX *= -1;
}
if (y < 0 || y > windowDimension.getHeight()-radius-24) {
speedY *= -1;
}
y += speedY;
x += speedX;
}
public void checkCollison(Circle other) {
}
}
|
package offer;
// 统计一个数字在排序数组中出现的次数。
public class 数字在排序数组中出现的次数 {
public static void main(String[] args) {
int[] arr={1,2,3,3,3,3};
int k= 3;
System.out.println(GetNumberOfK(arr,k));
}
public static int GetNumberOfK(int [] array , int k) {
int count = 0;
for (int i = 0; i < array.length; ) {
if(array[i] < k){
i++;
}else if(array[i]==k){
i++;
count++;
}else if(array[i] >k){
break;
}
}
return count;
}
}
|
package fr.jeanlouispiera.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import fr.jeanlouispiera.dao.ProduitRepository;
import fr.jeanlouispiera.entities.Produit;
@Controller
public class ProduitController{
@Autowired
private ProduitRepository produitRepository;
@RequestMapping(value="/index")
public String index(Model model,
@RequestParam(name="page", defaultValue="0")int p,
@RequestParam(name="size", defaultValue="5")int s,
@RequestParam(name="motCle", defaultValue="")String mc){
Page<Produit> pageProduits=
produitRepository.chercher("%"+mc+"%", PageRequest.of(p, s, Sort.unsorted()));
model.addAttribute("listProduits", pageProduits.getContent());
int[] pages=new int[pageProduits.getTotalPages()];
model.addAttribute("pages",pages);
model.addAttribute("size",s);
model.addAttribute("pageCourante",p);
model.addAttribute("motCle",mc);
return "produits";
}
@RequestMapping(value="/delete", method=RequestMethod.GET)
public String delete(Long id, String motCle, int page, int size) {
produitRepository.deleteById(id);
return "redirect:/index?page="+page+"&size="+size+"&motCle="+motCle;
}
@RequestMapping(value="/form", method=RequestMethod.GET)
public String formProduit(Model model) {
model.addAttribute("produit", new Produit());
return "FormProduit";
}
@RequestMapping(value="/save", method=RequestMethod.POST)
public String save(Model model, Produit produit) {
produitRepository.save(produit);
return "confirmation";
}
} |
public class NarcissisticNumber
{
public static void main(String[] args)
{
int count = 0;
for(int i = 100;i<1000;i++)
{
int unit = i%10;
int tens = i/10%10;
int hundreds = i/100;
if(i == unit*unit*unit+tens*tens*tens+hundreds*hundreds*hundreds)
{
count ++;
System.out.print(i+" ");
if(count % 10 == 0)
{
System.out.println();
}
}
}
}
} |
package hibernate.jpa.daoClass;
import hibernate.jpa.tableClass.Client;
import javax.persistence.EntityManager;
public class ClientDao extends AbstractDao<Client> {
public ClientDao(EntityManager entityManager) {
super(entityManager);
}
public Client findByName(String name) {
return (Client) getEntityManager().createQuery("select c from Client c where c.clientName like :name")
.setParameter("name", "%" + name + "%").setMaxResults(1).getSingleResult();
}
public Client findClientByEmail(String email) {
return (Client) getEntityManager().createQuery("select c from Client c where c.email like :email")
.setParameter("email", "%" + email + "%").setMaxResults(1).getSingleResult();
}
public Client findClientByNameAndEmail(String name, String email) {
return (Client) getEntityManager().createQuery("select c from Client c where c.clientName like :name and c.email like :email")
.setParameter("name", "%" + name + "%").setParameter("city", "%" + email + "%")
.setMaxResults(1).getSingleResult();
}
} |
/*
* 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 monocholor;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.photos.Photo;
import com.flickr4java.flickr.photos.PhotoList;
import com.flickr4java.flickr.photos.PhotosInterface;
import com.flickr4java.flickr.photos.Size;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
*
* @author Oliver
*/
public class FXMLDocumentController implements Initializable {
String apiKey = "ec7e3362915164ccab3a61299422bd7b";
String sharedSecret = "07b05df1b1c75797";
static Flickr f;
static PhotosInterface iface;
static PhotoList photos;
static Image editImg = null;
static int clickedPhoto;
double redRange;
double greenRange;
double blueRange;
ImageView editImgView;
BufferedImage bimg;
PixelReader pReader;
Color c;
@FXML
FlowPane flowPane;
@FXML
BorderPane borderPane;
@FXML
Button backBtn;
@FXML
TextField searchField;
@FXML
Rectangle pickedColor;
@FXML
Slider colWidthSlider;
@FXML
Slider redSlider;
@FXML
Slider greenSlider;
@FXML
Slider blueSlider;
@FXML
public void handleImageClicked(MouseEvent event){
System.out.println("Image clicked");
}
@FXML
public void handleSetBack(ActionEvent event){
editImgView.setImage(editImg);
}
@FXML
public void handleSearchBtn(ActionEvent event) throws FlickrException{
Set<String> extras = new HashSet<String>();
extras.add(searchField.getText());
flowPane.getChildren().remove(0, 8);
photos = iface.getRecent(null,8,0);
initPrevPics();
}
@FXML
public void handleRefresh(ActionEvent event) throws FlickrException{
flowPane.getChildren().remove(0, 8);
photos = iface.getRecent(null,8,0);
initPrevPics();
}
@FXML
public void handleSaveBtn(ActionEvent event) throws IOException{
Stage secondStage = new Stage();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Speichere Bild");
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG files (*.jpg)", "*.jpg");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(secondStage);
if (file != null) {
ImageIO.write(bimg, "jpg", file);
}
}
@FXML
public void handleLoadBtn(ActionEvent event) throws IOException{
Stage secondStage = new Stage();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Speichere Bild");
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG files (*.jpg)", "*.jpg");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(secondStage);
if(file != null){
Stage aktStage = (Stage) flowPane.getScene().getWindow();
editImg = new Image(file.toURI().toString());
Parent root = FXMLLoader.load(getClass().getResource("FXMLEditPhoto.fxml"));
Scene editScene = new Scene(root);
aktStage.setScene(editScene);
}
}
@FXML
public void handleBackButton(ActionEvent event) throws IOException{
Stage stage;
Parent root;
stage=(Stage) backBtn.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
//create a new scene with root and set the stage
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
@FXML
public void handleAnwenden(ActionEvent event){
refreshImg();
}
@Override
public void initialize(URL url, ResourceBundle rb){
/*
try {
f = new Flickr(apiKey, sharedSecret, new REST());
iface = f.getPhotosInterface();
photos = iface.getRecent(null,10,0);
} catch (FlickrException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
*/
File file = new File(url.getFile());
String fxml = file.getName();
if(fxml.equals("FXMLDocument.fxml")){
try {
Set<String> extras = new HashSet<String>();
extras.add("Landschaft");
f = new Flickr(apiKey, sharedSecret, new REST());
iface = f.getPhotosInterface();
photos = iface.getRecent(extras,8,0);
this.initPrevPics();
} catch (FlickrException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
pReader = editImg.getPixelReader();
editImgView = new ImageView(editImg);
editImgView.setPreserveRatio(true);
editImgView.setFitHeight(650);
editImgView.setFitWidth(650);
editImgView.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
//ImageView tempImgView = (ImageView)event.getSource();
c = pReader.getColor((int)event.getSceneX(), (int)event.getSceneY());
pickedColor.setFill(c);
//double randX = editImgView.getFitWidth()-editImg.getWidth();
//double randY = editImgView.getFitHeight()-editImg.getHeight();
//System.out.println("Width: "+editImg.getWidth()+", Height: "+editImg.getHeight());
//System.out.println("X: "+event.getSceneX()+", Y: "+event.getSceneY());
//System.out.println("newX: "+randX+", newY: "+randY);
}
});
colWidthSlider.valueProperty().addListener(new ChangeListener<Number>(){
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
redSlider.setValue(colWidthSlider.getValue());
greenSlider.setValue(colWidthSlider.getValue());
blueSlider.setValue(colWidthSlider.getValue());
refreshImg();
}
});
redSlider.valueProperty().addListener(new ChangeListener<Number>(){
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
redRange = redSlider.getValue();
refreshImg();
}
});
greenSlider.valueProperty().addListener(new ChangeListener<Number>(){
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
greenRange = greenSlider.getValue();
refreshImg();
}
});
blueSlider.valueProperty().addListener(new ChangeListener<Number>(){
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
blueRange = blueSlider.getValue();
refreshImg();
}
});
borderPane.setCenter(editImgView);
//System.out.println("so weit so gut " + clickedPhoto);
}
}
private void initPrevPics() throws FlickrException{
for(int i=0; i<photos.size(); i++){
VBox vb = new VBox();
vb.setPadding(new Insets(20, 30, 20, 30));
Photo tempPhoto = (Photo)photos.get(i);
tempPhoto.getId();
Image tempImg = SwingFXUtils.toFXImage(iface.getImage(tempPhoto, Size.SMALL),null);
ImageView imgView = new ImageView(tempImg);
imgView.setId(""+i);
imgView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Stage aktStage = (Stage)imgView.getScene().getWindow();
try {
clickedPhoto = Integer.parseInt(imgView.getId());
editImg = SwingFXUtils.toFXImage(iface.getImage((Photo) photos.get(clickedPhoto), Size.MEDIUM_800),null);
Parent root = FXMLLoader.load(getClass().getResource("FXMLEditPhoto.fxml"));
Scene editScene = new Scene(root);
aktStage.setScene(editScene);
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (FlickrException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
vb.getChildren().add(imgView);
flowPane.getChildren().add(vb);
}
}
private void refreshImg(){
bimg = SwingFXUtils.fromFXImage(editImg, null);
for(int x=0; x<bimg.getWidth();x++){
for(int y=0; y<bimg.getHeight();y++){
boolean inColor = false;
int rgb = bimg.getRGB(x, y);
int a = (rgb >> 24) & 0xFF;
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb & 0xFF);
int desR = (int)c.getRed();
int desG = (int)c.getBlue();
int desB = (int)c.getGreen();
double colRange = colWidthSlider.getValue();
if(r>=desR-redRange&&r<=desR+redRange){
if(g>=desG-greenRange&&g<=desG+greenRange){
if(b>=desB-blueRange&&b<=desB+blueRange){
inColor = true;
}
}
}
if(inColor) {
int grey = (r+g+b)/3;
int newRgb = (a << 24) | (grey << 16) | (grey << 8) | grey;
bimg.setRGB(x, y, newRgb);
} else {
bimg.setRGB(x, y, rgb);
}
}
}
Image newImg = SwingFXUtils.toFXImage(bimg, null);
editImgView.setImage(newImg);
}
}
|
package com.pojo;
public class POJO {
private String user;
private String password;
public POJO(String user, String password) {
super();
this.user=user;
this.password=password;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
}
|
package com.capgemini.exceptions;
public class PaymentFailureException extends Exception {
public PaymentFailureException(String message) {
super(message);
}
}
|
package net.minecraft.item;
import com.google.common.collect.Lists;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityFireworkRocket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
public class ItemFirework extends Item {
public EnumActionResult onItemUse(EntityPlayer stack, World playerIn, BlockPos worldIn, EnumHand pos, EnumFacing hand, float facing, float hitX, float hitY) {
if (!playerIn.isRemote) {
ItemStack itemstack = stack.getHeldItem(pos);
EntityFireworkRocket entityfireworkrocket = new EntityFireworkRocket(playerIn, (worldIn.getX() + facing), (worldIn.getY() + hitX), (worldIn.getZ() + hitY), itemstack);
playerIn.spawnEntityInWorld((Entity)entityfireworkrocket);
if (!stack.capabilities.isCreativeMode)
itemstack.func_190918_g(1);
}
return EnumActionResult.SUCCESS;
}
public ActionResult<ItemStack> onItemRightClick(World itemStackIn, EntityPlayer worldIn, EnumHand playerIn) {
if (worldIn.isElytraFlying()) {
ItemStack itemstack = worldIn.getHeldItem(playerIn);
if (!itemStackIn.isRemote) {
EntityFireworkRocket entityfireworkrocket = new EntityFireworkRocket(itemStackIn, itemstack, (EntityLivingBase)worldIn);
itemStackIn.spawnEntityInWorld((Entity)entityfireworkrocket);
if (!worldIn.capabilities.isCreativeMode)
itemstack.func_190918_g(1);
}
return new ActionResult(EnumActionResult.SUCCESS, worldIn.getHeldItem(playerIn));
}
return new ActionResult(EnumActionResult.PASS, worldIn.getHeldItem(playerIn));
}
public void addInformation(ItemStack stack, @Nullable World playerIn, List<String> tooltip, ITooltipFlag advanced) {
NBTTagCompound nbttagcompound = stack.getSubCompound("Fireworks");
if (nbttagcompound != null) {
if (nbttagcompound.hasKey("Flight", 99))
tooltip.add(String.valueOf(I18n.translateToLocal("item.fireworks.flight")) + " " + nbttagcompound.getByte("Flight"));
NBTTagList nbttaglist = nbttagcompound.getTagList("Explosions", 10);
if (!nbttaglist.hasNoTags())
for (int i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
List<String> list = Lists.newArrayList();
ItemFireworkCharge.addExplosionInfo(nbttagcompound1, list);
if (!list.isEmpty()) {
for (int j = 1; j < list.size(); j++)
list.set(j, " " + (String)list.get(j));
tooltip.addAll(list);
}
}
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemFirework.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package engine.resources;
import engine.resources.ResourceManager.ResourceType;
/**
*
* @author Anselme FRANÇOIS
*
*/
public enum Resource {
BACKGROUND ("res/theme/default/background.png", ResourceType.TEXTURE),
UI_WINDOW ("res/theme/default/ui.png", ResourceType.TEXTURE),
CLIENT_CONFIG ("res/conf/client.conf", ResourceType.CONFIG),
SERVER_CONFIG ("res/conf/server.conf", ResourceType.CONFIG),
DIRT_BLOCK ("res/textures/dirt.png", ResourceType.TEXTURE),
ROCK_BLOCK ("res/textures/rock.png", ResourceType.TEXTURE),
DEFAULT_SHADER ("res/shaders/default", ResourceType.SHADER),
MAIN_FONT ("res/theme/default/main_font.ttf", ResourceType.FONT),
SIMPLE_FONT ("res/theme/default/simple_font.ttf", ResourceType.FONT);
private final String path;
private final ResourceType type;
Resource(String path, ResourceType type) {
this.path = path;
this.type = type;
}
public String path() {
return path;
}
public ResourceType type() {
return type;
}
}
|
package com.saven.batch.mapper;
import com.saven.batch.domain.CustomColumnDecorator;
import com.saven.batch.domain.Row;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by nrege on 1/30/2017.
*/
public class DerivedFieldsColumnMapper extends StandardFieldsColumnMapper implements IndexedFieldSetMapper<Row>{
String ROW_CONTEXT = "ROW_CONTEXT";
CustomColumnDecorator customColumnDecorator;
@Override
public Row mapFieldSet(ExecutionContext executionContext, FieldSet fieldSet, int index) throws BindException {
Row row = (Row) super.mapFieldSet(executionContext, fieldSet, index);
Map<String, Row> rowContext = getRowContext(executionContext);
Row lastRow = rowContext.get(row.getIdentityValue());
rowContext.put(row.getIdentityValue(), row);
customColumnDecorator.decorate(identifier, row, lastRow);
return row;
}
private Map<String, Row> getRowContext(ExecutionContext executionContext) {
if (executionContext.get(ROW_CONTEXT) == null) {
executionContext.put(ROW_CONTEXT, new HashMap<String, Row>());
}
return (Map<String, Row>) executionContext.get(ROW_CONTEXT);
}
public CustomColumnDecorator getCustomColumnDecorator() {
return customColumnDecorator;
}
public void setCustomColumnDecorator(CustomColumnDecorator customColumnDecorator) {
this.customColumnDecorator = customColumnDecorator;
}
}
|
/*
* 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 cl.auter.bmp;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author drobles
*/
@Entity
@Table(name = "user_data")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "UserDataEntity.findAll", query = "SELECT u FROM UserDataEntity u")
, @NamedQuery(name = "UserDataEntity.findById", query = "SELECT u FROM UserDataEntity u WHERE u.id = :id")
, @NamedQuery(name = "UserDataEntity.findByUsername", query = "SELECT u FROM UserDataEntity u WHERE u.username = :username")
, @NamedQuery(name = "UserDataEntity.findByIdChat", query = "SELECT u FROM UserDataEntity u WHERE u.idChat = :idChat")
, @NamedQuery(name = "UserDataEntity.findByRunning", query = "SELECT u FROM UserDataEntity u WHERE u.running = :running")})
public class UserDataEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 25)
@Column(name = "username")
private String username;
@Column(name = "id_chat")
private Integer idChat;
@Column(name = "running")
private Boolean running;
public UserDataEntity() {
}
public UserDataEntity(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getIdChat() {
return idChat;
}
public void setIdChat(Integer idChat) {
this.idChat = idChat;
}
public Boolean getRunning() {
return running;
}
public void setRunning(Boolean running) {
this.running = running;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UserDataEntity)) {
return false;
}
UserDataEntity other = (UserDataEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "cl.auter.bmp.UserDataEntity[ id=" + id + " ]";
}
}
|
package com.tencent.mm.plugin.hp.tinker;
import com.tencent.mm.plugin.hp.tinker.a.a;
class a$1 implements Runnable {
final /* synthetic */ a kmW;
final /* synthetic */ a kmX;
a$1(a aVar, a aVar2) {
this.kmX = aVar;
this.kmW = aVar2;
}
public final void run() {
if (this.kmW != null) {
com.tencent.tinker.lib.f.a.i("Tinker.ScreenOffRetryPatch", "ScreenOffRetryPatch runnable try to start", new Object[0]);
this.kmW.aWq();
}
}
}
|
package com.fleet.rmi.provider.config;
import com.fleet.rmi.common.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.rmi.RmiServiceExporter;
import javax.annotation.Resource;
/**
* @author April Han
*/
@Configuration
public class RmiServer {
@Resource
UserService userService;
@Bean
public RmiServiceExporter rmiServiceExporter() {
RmiServiceExporter rmiServiceExporter = new RmiServiceExporter();
rmiServiceExporter.setServiceName("userService");
rmiServiceExporter.setService(userService);
rmiServiceExporter.setServiceInterface(UserService.class);
rmiServiceExporter.setRegistryPort(6001);
return rmiServiceExporter;
}
}
|
package com.tencent.mm.plugin.bottle.a;
public final class a {
int bWA = -1;
String content = "";
int dCV = 0;
String dCX = "";
String dCY = "";
int dSJ = 0;
String hjN = "";
int hjO = 0;
String hjP = "";
int hjQ = 0;
int hjR = 0;
long hjS = 0;
int msgType = 0;
public final String aub() {
return this.hjP == null ? "" : this.hjP;
}
public final String getContent() {
return this.content == null ? "" : this.content;
}
}
|
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
/**
* For Testing QuitOption
*/
public class QuitOptionTest {
private QuitOption quitOption;
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Before
public void setUpQuitOption() {
quitOption = new QuitOption("Quit");
}
@Test
public void nameShouldReturnQuitOptionName() {
assertEquals("Quit", quitOption.name());
}
@Test
public void runShouldSystemExitWithStatusCode0() {
exit.expectSystemExitWithStatus(0);
quitOption.run();
}
} |
package org.usfirst.frc.team5951.robot.commands.gears.floorGearsIntake;
import org.usfirst.frc.team5951.robot.Robot;
import org.usfirst.frc.team5951.robot.subsystems.FloorGearsIntake;
import edu.wpi.first.wpilibj.command.InstantCommand;
/**
*
*/
public class ChangeToGearReleasePosition extends InstantCommand {
private FloorGearsIntake floorGearsIntake;
public ChangeToGearReleasePosition() {
this.floorGearsIntake = Robot.floorGearsIntake;
}
// Called once when the command executes
protected void initialize() {
this.floorGearsIntake.getToGearReleasePosition();
}
}
|
package io.github.leonkacowicz.tictactoe.core;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static io.github.leonkacowicz.tictactoe.core.BoardState.CIRCLE_WINS;
import static io.github.leonkacowicz.tictactoe.core.BoardState.CROSS_WINS;
import static io.github.leonkacowicz.tictactoe.core.BoardState.DRAW;
import static io.github.leonkacowicz.tictactoe.core.CellState.*;
public class Board {
protected CellState[][] board;
public Board() {
this(3);
}
public Board(int n) {
board = new CellState[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = BLANK;
}
}
}
public void setCellState(int row, int column, CellState cellState) {
board[row][column] = cellState;
}
public CellState getCellState(int row, int column) {
return board[row][column];
}
public int size() {
return board.length;
}
public BoardState getBoardState() {
final int n = board.length;
int impossibleRows = 0;
int impossibleColumns = 0;
int impossibleDiag = 0;
for (int row = 0; row < n; row++) {
boolean allCircle = true;
boolean hasCircle = false;
boolean allCross = true;
boolean hasCross = false;
for (int col = 0; col < n; col++) {
allCircle = allCircle && (board[row][col] == CIRCLE);
allCross = allCross && (board[row][col] == CROSS);
hasCircle = hasCircle || (board[row][col] == CIRCLE);
hasCross = hasCross || (board[row][col] == CROSS);
}
if (allCircle) return CIRCLE_WINS;
if (allCross) return CROSS_WINS;
if (hasCircle && hasCross) ++impossibleRows;
}
for (int col = 0; col < n; col++) {
boolean allCircle = true;
boolean hasCircle = false;
boolean allCross = true;
boolean hasCross = false;
for (int row = 0; row < n; row++) {
allCircle = allCircle && (board[row][col] == CIRCLE);
allCross = allCross && (board[row][col] == CROSS);
hasCircle = hasCircle || (board[row][col] == CIRCLE);
hasCross = hasCross || (board[row][col] == CROSS);
}
if (allCircle) return CIRCLE_WINS;
if (allCross) return CROSS_WINS;
if (hasCircle && hasCross) ++impossibleColumns;
}
// main diagonal
boolean allCircle = true;
boolean hasCircle = false;
boolean allCross = true;
boolean hasCross = false;
for (int i = 0; i < n; i++) {
allCircle = allCircle && (board[i][i] == CIRCLE);
allCross = allCross && (board[i][i] == CROSS);
hasCircle = hasCircle || (board[i][i] == CIRCLE);
hasCross = hasCross || (board[i][i] == CROSS);
}
if (allCircle) return CIRCLE_WINS;
if (allCross) return CROSS_WINS;
if (hasCircle && hasCross) ++impossibleDiag;
// secondary diagonal
allCircle = true;
hasCircle = false;
allCross = true;
hasCross = false;
for (int i = 0; i < n; i++) {
int j = n - i - 1;
allCircle = allCircle && (board[i][j] == CIRCLE);
allCross = allCross && (board[i][j] == CROSS);
hasCircle = hasCircle || (board[i][j] == CIRCLE);
hasCross = hasCross || (board[i][j] == CROSS);
}
if (allCircle) return CIRCLE_WINS;
if (allCross) return CROSS_WINS;
if (hasCircle && hasCross) ++impossibleDiag;
if (impossibleRows == n && impossibleColumns == n && impossibleDiag == 2) return DRAW;
return BoardState.NOT_FINISHED;
}
public List<Move> getValidMoves() {
int size = board.length;
List<Move> validMoves = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == BLANK)
validMoves.add(new Move(i, j));
}
}
// Shuffle the list of possible moves.
Random r = new Random();
for (int i = 0; i < validMoves.size() * 3; i++) {
int p = r.nextInt(validMoves.size());
int q = r.nextInt(validMoves.size());
Move tmp = validMoves.get(p);
validMoves.set(p, validMoves.get(q));
validMoves.set(q, tmp);
}
return validMoves;
}
public void printBoard(PrintWriter printer) {
char[] map = new char[3];
map[CIRCLE.ordinal()] = 'o';
map[CROSS.ordinal()] = 'x';
map[BLANK.ordinal()] = ' ';
for (int row = 0; row < board.length - 1; row++) {
int col;
for (col = 0; col < board.length - 1; col++) {
printer.print(' ');
printer.print(map[board[row][col].ordinal()]);
printer.print(" |");
}
printer.print(' ');
printer.print(map[board[row][col].ordinal()]);
printer.print(' ');
printer.println();
for (int i = 0; i < 4 * board.length - 1; i++) printer.print('-');
printer.println();
}
int row = board.length - 1;
int col;
for (col = 0; col < board.length - 1; col++) {
printer.print(' ');
printer.print(map[board[row][col].ordinal()]);
printer.print(" |");
}
printer.print(' ');
printer.print(map[board[row][col].ordinal()]);
printer.print(' ');
printer.println();
printer.flush();
}
}
|
package io.summer;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class Recruiter extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String email = getServletConfig().getInitParameter("Email");
String website = getServletContext().getInitParameter("Website-name");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<center><h1>" + website + "</h1><p>Contact us: " + email+"</center>");
}
} |
/*
* Copyright 2016 RedRoma, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.aroma.authentication.service;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import tech.aroma.authentication.service.data.TokenCreator;
import tech.aroma.authentication.service.operations.ModuleAuthenticationOperations;
import tech.aroma.data.memory.ModuleMemoryDataRepositories;
import tech.aroma.thrift.authentication.service.AuthenticationService;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner.class)
public class ModuleAuthenticationServiceTest
{
private ModuleMemoryDataRepositories dataModule;
private ModuleAuthenticationOperations operationsModule;
private ModuleAuthenticationService instance;
@Before
public void setUp()
{
dataModule = new ModuleMemoryDataRepositories();
operationsModule = new ModuleAuthenticationOperations();
instance = new ModuleAuthenticationService();
}
@Test
public void testConfigure()
{
Injector injector = Guice.createInjector(dataModule,
operationsModule,
instance);
AuthenticationService.Iface service = injector.getInstance(AuthenticationService.Iface.class);
assertThat(service, notNullValue());
}
@Test
public void testProvideTokenCreator()
{
TokenCreator tokenCreator = instance.provideTokenCreator();
assertThat(tokenCreator, notNullValue());
}
}
|
package se.Lexicon;
//Create a class called Car. The class should contain the following
//information. Car brand, registration number, max speed and owner
//name. Instantiate an Object of the class and assign values to the
//object.
public class Car {
String carBrand = "Kia";
String registrationNumber ="ABS123";
int maxSpeed = 120;
String ownerName = "Jan Jansson";
} |
package br.com.drogaria.teste;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import br.com.drogaria.dao.FabricanteDAO;
import br.com.drogaria.domain.Fabricante;
public class FabricanteDAOTest {
@Test
@Ignore
public void salvar() {
Fabricante f1 = new Fabricante();
f1.setDescricao("DescricaoF");
Fabricante f2 = new Fabricante();
f2.setDescricao("DescricaoG");
FabricanteDAO dao = new FabricanteDAO();
dao.salvar(f1);
dao.salvar(f2);
}
@Test
@Ignore
public void listar() {
FabricanteDAO dao = new FabricanteDAO();
List<Fabricante> fabricantes = dao.listar();
for (Fabricante fabricante : fabricantes) {
System.out.println(fabricante);
}
}
@Test
@Ignore
public void buscarPorCodigo() {
FabricanteDAO dao = new FabricanteDAO();
Fabricante f1 = dao.buscarPorCodigo(2L);
System.out.println(f1);
}
@Test
@Ignore
public void excluir() {
Fabricante fabricante = new Fabricante();
fabricante.setCodigo(4L);
fabricante.setDescricao("DescricaoB");
FabricanteDAO dao = new FabricanteDAO();
dao.excluir(fabricante);
}
@Test
@Ignore
public void editar() {
Fabricante fabricante = new Fabricante();
fabricante.setCodigo(2L);
fabricante.setDescricao("testeX");
FabricanteDAO dao = new FabricanteDAO();
dao.editar(fabricante);
}
}
|
/*
* @Author : fengzhi
* @date : 2019 - 05 - 08 20 : 26
* @Description :
*/
package nowcoder_leetcode;
import java.util.ArrayList;
import java.util.HashSet;
public class p_25 {
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayList<String> list = new ArrayList<>();
private ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
private boolean flag = false;
private int size = Integer.MAX_VALUE;
public int ladderLength(String start, String end, HashSet<String> dict) {
// 深度优先遍历
arrayList.addAll(dict);
DFS(start, end);
if (flag)
return size + 2;
else
return 0;
}
public ArrayList<ArrayList<String>> ladderPath(String start, String end, HashSet<String> dict) {
arrayList.addAll(dict);
list.add(start);
DFS2(start, end);
if (arrayLists == null)
return arrayLists;
int minLen = Integer.MAX_VALUE;
ArrayList<ArrayList<String>> retArrayLists = new ArrayList<>();
for (ArrayList<String> arrayList : arrayLists) {
minLen = Math.min(arrayList.size(), minLen);
}
for (ArrayList<String> arrayList : arrayLists) {
if (arrayList.size() == minLen)
retArrayLists.add(arrayList);
}
return retArrayLists;
}
private void DFS2(String current, String end) {
if (diffOneCharacter(current, end)) {
list.add(end);
arrayLists.add((new ArrayList<String>(list)));
list.remove(list.size() - 1);
return;
}
if (arrayList.isEmpty())
return;
int length = arrayList.size();
for (int i = 0; i < length; i ++) {
String s = arrayList.get(i);
if (diffOneCharacter(current, s)) {
list.add(arrayList.remove(i));
DFS2(s, end);
list.remove(list.size() - 1);
arrayList.add(i, s);
}
}
}
private void DFS(String current, String end) {
if (flag)
return;
if (diffOneCharacter(current, end)) {
size = Math.min(size, list.size());
flag = true;
return;
}
if (arrayList.isEmpty())
return;
int length = arrayList.size();
for (int i = 0; i < length; i ++) {
String s = arrayList.get(i);
if (diffOneCharacter(current, s)) {
list.add(arrayList.remove(i));
DFS(s, end);
list.remove(list.size() - 1);
arrayList.add(i, s);
}
}
}
private boolean diffOneCharacter(String s1, String s2) {
if (s1.length() != s2.length())
return false;
int times = 0;
for (int i = 0; i < s1.length(); i ++) {
if (s1.charAt(i) != s2.charAt(i))
times ++;
}
return times == 1;
}
public static void main(String[] args) {
long startTime = System.nanoTime();
String start = "hit";
String end = "cog";
HashSet<String> dict = new HashSet<String>() {{
add("hot");
add("dot");
add("dog");
add("lot");
add("log");
}};
p_25 p = new p_25();
ArrayList<ArrayList<String>> arrayLists = p.ladderPath(start, end, dict);
for (ArrayList<String> arrayList : arrayLists)
System.out.println(arrayList);
// System.out.println(p.ladderLength(start, end, dict));
System.out.println(System.nanoTime() - startTime);
}
}
|
package com.home.closematch.controller.admin;
import com.home.closematch.entity.SysAdmin;
import com.home.closematch.pojo.Msg;
import com.home.closematch.exception.ServiceErrorException;
import com.home.closematch.service.CompanyService;
import com.home.closematch.service.HumanresoucresService;
import com.home.closematch.service.JobSeekerService;
import com.home.closematch.service.SysAdminService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@Api(value = "AdminAccount", tags = "后台管理")
@RestController
public class AdminAccountController {
@Autowired
private SysAdminService sysAdminService;
/*
admin 操作
修改其余账户的一个可用状态
*/
@PutMapping("/backStageManagement/account/{accountId}")
public Msg changeUserAccountStatus(@PathVariable("accountId") Long accountId){
sysAdminService.changeUserAccountUserByAccountId(accountId);
return Msg.success("success");
}
// @CrossOrigin(value = "http://localhost:9528")
/**
* 统一Spring Security接口, 将这个接口废弃
*/
@Deprecated
@PostMapping(value = "/backStageManagement/login")
public Msg login(@RequestBody(required = false) SysAdmin cmSysAdmin){
if (cmSysAdmin == null)
return Msg.fail(400, "Other Error");
return Msg.success("success").add("token",
sysAdminService.loginToBackStage(cmSysAdmin.getUsername(), cmSysAdmin.getPassword()));
}
}
|
package com.sinata.rwxchina.component_basic.hotel.utils;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.sinata.rwxchina.basiclib.utils.appUtils.ScreenUtils;
import com.sinata.rwxchina.basiclib.view.datepicker.DatePickerController;
import com.sinata.rwxchina.basiclib.view.datepicker.DayPickerView;
import com.sinata.rwxchina.basiclib.view.datepicker.SimpleMonthAdapter;
import com.sinata.rwxchina.component_basic.R;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @author HRR
* @datetime 2017/12/27
* @describe 酒店入住离开日历选择工具类
* @modifyRecord
*/
public class DatePickerUtils {
private static int days, year, month, day;
/**入住日期和离开日期*/
private static Date checkDate,leaveDate;
static CallDate callDate;
public static void setDatePicker(final Context context,View showView){
callDate= (CallDate) context;
//布局
View pickerView= LayoutInflater.from(context).inflate(R.layout.pop_datepicker,null);
//设置弹出框
final PopupWindow popDatePicker=new PopupWindow();
popDatePicker.setHeight(ScreenUtils.getScreenWidth(context));
popDatePicker.setWidth(ScreenUtils.getScreenWidth(context));
popDatePicker.setContentView(pickerView);
//将这两个属性设置为false,使点击popupwindow外面其他地方会消失
popDatePicker.setBackgroundDrawable(new ColorDrawable(0x00000000));
popDatePicker.setOutsideTouchable(true);
popDatePicker.setFocusable(true);
DayPickerView dayPickerView = pickerView.findViewById(R.id.dpv_calendar);
ImageView rili_quexiao = pickerView.findViewById(R.id.rili_quexiao);
TextView pop_time_sure = pickerView.findViewById(R.id.pop_time_sure);
//当前时间
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
//初始化日历
DayPickerView.DataModel dataModel = new DayPickerView.DataModel();
dataModel.yearStart = year;
dataModel.monthStart = month;
dataModel.monthCount = 12;
dataModel.defTag = "";
dataModel.leastDaysNum = 1;
dataModel.mostDaysNum = 50;
dayPickerView.setParameter(dataModel, new DatePickerController() {
@Override
public void onDayOfMonthSelected(SimpleMonthAdapter.CalendarDay calendarDay) {
}
@Override
public void onDateRangeSelected(List<SimpleMonthAdapter.CalendarDay> selectedDays) {
days = selectedDays.size() - 1;
checkDate=selectedDays.get(0).getDate();
leaveDate=selectedDays.get(selectedDays.size()-1).getDate();
callDate.getCallDate(checkDate,leaveDate);
}
@Override
public void alertSelectedFail(FailEven even) {
Toast.makeText(context, "最长订房时间为50天", Toast.LENGTH_SHORT).show();
}
});
rili_quexiao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (popDatePicker.isShowing()){
popDatePicker.dismiss();
}
}
});
pop_time_sure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (popDatePicker.isShowing()){
popDatePicker.dismiss();
}
}
});
popDatePicker.showAtLocation(showView, Gravity.BOTTOM, 0, 0);
}
public interface CallDate{
void getCallDate(Date checkDate,Date leaveDate);
}
}
|
package com.zhonghuilv.shouyin.service.impl;
import com.zhonghuilv.shouyin.service.OperatorService;
import org.springframework.stereotype.Service;
/**
* Created by llk2014 on 2018-07-04 17:13:49
*/
@Service
public class OperatorServiceImpl implements OperatorService {
}
|
package com.one.sugarcane.userinfo.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.one.sugarcane.userinfo.service.UserInfoServiceImpl;
import com.one.sugarcane.entity.PublicCourseType;
import com.one.sugarcane.entity.UserHobby;
import com.one.sugarcane.entity.UserInfo;
import com.one.sugarcane.entity.UserLogin;
import com.one.sugarcane.MD5Util.MD5Util;;
/**
*
* @author 张梦洲
* @throws IOException
* @date 2018/4/30
*/
@Controller
@RequestMapping("userInfo")
public class UserInfoController {
@Resource
private UserInfoServiceImpl userInfoServiceImpl;
/**
* 用户注册
* @author 张梦洲
* @throws IOException
* @date 2018/5/10
*/
@RequestMapping("/save")
public String save(@RequestParam String username,@RequestParam String email,@RequestParam String password,@RequestParam String phone) {
UserInfo userInfo = new UserInfo();
UserLogin userLogin = new UserLogin();
userInfo.setUserName(username);
userInfo.setUserEmail(email);
userInfo.setUserPhoneNumber(phone);
userLogin.setUserInfo(userInfo);
MD5Util md5 = new MD5Util();
String md5PWD = md5.generate(password);
userLogin.setPassword(md5PWD);
userLogin.setUserEmail(email);
userInfo.setUserLogin(userLogin);
userInfoServiceImpl.saveUserInfo(userInfo);
return "front/home";
}
/**
* 用户完善个人信息
* @author 冯海晴
* @date 2018.5.24
*/
@RequestMapping("complete")
public String completeUserInfo(@RequestParam int userGender, @RequestParam String birthday, @RequestParam String userEducation,
@RequestParam String userWork, @RequestParam String address_province, @RequestParam String address_city,
@RequestParam String address_area, @RequestParam String publicTypeName, HttpServletRequest request) {
System.out.println(userGender+birthday+userEducation+userWork+address_province+address_city+address_area+publicTypeName);
HttpSession session = request.getSession();
UserInfo userInfo = (UserInfo) session.getAttribute("user");
//添加用户兴趣爱好userHobby
Set<UserHobby> userHobbys = new HashSet<>();
String[] publicTypeNames = publicTypeName.split(",");
for(int i = 0; i<publicTypeNames.length; ++i) {
PublicCourseType publicType = this.userInfoServiceImpl.findPublicTypeByName(publicTypeNames[i]);
UserHobby userHobby = new UserHobby();
userHobby.setUserInfo(userInfo);
userHobby.setPublicType(publicType);
this.userInfoServiceImpl.saveUserHobby(userHobby);
userHobbys.add(userHobby);
}
//完善用户信息
userInfo.setUserGender(userGender);
userInfo.setBirthday(birthday);
userInfo.setUserEducation(userEducation);
userInfo.setUserWork(userWork);
userInfo.setAddress_province(address_province);
userInfo.setAddress_city(address_city);
userInfo.setAddress_area(address_area);
userInfo.setUserHobby(userHobbys);
this.userInfoServiceImpl.updateUserInfo(userInfo);
//return "redirect:/front/personinfor.jsp";
return "redirect:/front/index.jsp";
}
/**
* 修改个人信息
* @author 冯海晴
* @date 2018.5.24
*/
@RequestMapping("userpic")
public String ceshi(HttpServletRequest request, @RequestParam(value="main_img",required=false) MultipartFile file) {
HttpSession session = request.getSession();
UserInfo userInfo = (UserInfo) session.getAttribute("user");
//插入头像
String docBase = "D:/Sugarcane/user/img/";
//getOriginalFilename : 获取上传文件的原名
String imgName=new Date().getTime()+file.getOriginalFilename();
System.out.println(imgName);
String path=docBase+imgName;
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
try {
file.transferTo(newFile);
} catch (IllegalStateException | IOException e) {
System.out.println("写文件错误");
}
//将路径存入数据库代码
userInfo.setUserPicture(path);
this.userInfoServiceImpl.updateUserInfo(userInfo);
return "redirect:/publicCourseType/list1.do";
}
@RequestMapping("edit")
public String editUserInfo(@RequestParam(value="userGender",required=false) Integer userGender, @RequestParam String birthday, @RequestParam String userEducation,
@RequestParam String userWork, @RequestParam String address_province, @RequestParam String address_city,
@RequestParam String address_area, HttpServletRequest request, @RequestParam(value="publicTypeName",required=false) String publicTypeName,
@RequestParam String userName, @RequestParam String userEmail, @RequestParam String userPhoneNumber){
System.out.println(userGender+birthday+userEducation+userWork+address_province+address_city+address_area+userName+userEmail+userPhoneNumber+publicTypeName);
HttpSession session = request.getSession();
UserInfo userInfo = (UserInfo) session.getAttribute("user");
//删除之前的hobby(测试成功)
System.out.println(publicTypeName);
int num = this.userInfoServiceImpl.deleteUserHobby(userInfo);
System.out.println("删除的用户兴趣爱好个数:"+num);
//判断用户是否重新选择兴趣爱好,若重新选择,则重新添加
if(publicTypeName != null && publicTypeName.length() != 0) {
//添加用户兴趣爱好userHobby(测试成功)
Set<UserHobby> userHobbys = new HashSet<>();
String[] publicTypeNames = publicTypeName.split(",");
for(int i = 0; i<publicTypeNames.length; ++i) {
PublicCourseType publicType = this.userInfoServiceImpl.findPublicTypeByName(publicTypeNames[i]);
UserHobby userHobby = new UserHobby();
userHobby.setUserInfo(userInfo);
userHobby.setPublicType(publicType);
this.userInfoServiceImpl.saveUserHobby(userHobby);
userHobbys.add(userHobby);
}
userInfo.setUserHobby(userHobbys);
}
//更新用户信息
//若昵称未填,则使用原来数据,不修改。
if(userName != null && userName.length() != 0) {
userInfo.setUserName(userName);
}
//若邮箱未填,则使用原来数据,不修改。
if(userEmail != null && userEmail.length() != 0) {
userInfo.setUserEmail(userEmail);
UserLogin userLogin = userInfo.getUserLogin();
userLogin.setUserEmail(userEmail);
this.userInfoServiceImpl.updateUserLogin(userLogin);
}
//若性别未选,则使用原来数据,不修改。
if(userGender != null) {
userInfo.setUserGender(userGender);
}
//若电话号码未填,则使用原来数据,不修改。
if(userPhoneNumber != null && userPhoneNumber.length() != 0) {
userInfo.setUserPhoneNumber(userPhoneNumber);
}
userInfo.setBirthday(birthday);
userInfo.setUserEducation(userEducation);
userInfo.setUserWork(userWork);
userInfo.setAddress_province(address_province);
userInfo.setAddress_city(address_city);
userInfo.setAddress_area(address_area);
this.userInfoServiceImpl.updateUserInfo(userInfo);
return "redirect:/front/home.jsp";
}
} |
package paskaita11;
public class Mangas extends Egzotiniai {
@Override
void kasAsEsu(){
System.out.println("as esu egzotinis vaisius");
}
}
|
package plugin.boot;
import java.io.IOException;
import org.apache.catalina.LifecycleException;
import com.yanan.framework.boot.BootArgs;
import com.yanan.framework.boot.Plugin;
import com.yanan.framework.boot.PluginBoot;
import com.yanan.framework.boot.PluginBootServer;
import com.yanan.framework.plugin.Environment;
import com.yanan.framework.plugin.PluginEvent;
import com.yanan.framework.plugin.PlugsFactory;
import com.yanan.framework.plugin.autowired.plugin.PluginWiredHandler;
import com.yanan.framework.plugin.definition.RegisterDefinition;
import com.yanan.framework.plugin.event.EventListener;
//@EnableClassHotUpdater(contextClass=PluginBootServerTest.class);
//@WebContext(contextPath = "/", docBase = "webapp")4
//@WebApp(contextPath = "/", docBase = "webapp")
//@WebApp(contextPath = "/dcxt", docBase = "/Volumes/GENERAL/tomcat work groups/apache-tomcat-8.0.52/webapps/dcxt")
//@WebApp(contextPath = "/yananFrame", docBase = "/Volumes/GENERAL/tomcat work groups/apache-tomcat-8.0.53/webapps/yananFrame")
@PluginBoot()
@BootArgs(name="-environment-boot",value="com.yanan.framework.boot.StandEnvironmentBoot")
@BootArgs(name="-boot-configure",value="boot.yc")
//@BootArgs(name="-boot-disabled",value="-boot-configure,-environment-boot")
@Plugin(PluginWiredHandler.class)
public class PluginBootServerTest {
String contextPath; String docBase;
public static void main(String[] args) throws LifecycleException, IOException {
Environment.getEnviroment().registEventListener(PlugsFactory.getInstance().getEventSource(), new EventListener<PluginEvent>() {
@Override
public void onEvent(PluginEvent abstractEvent) {
if(abstractEvent.getEventType() == PluginEvent.EventType.add_registerDefinition) {
RegisterDefinition definition = (RegisterDefinition)abstractEvent.getEventContent();
System.out.println(definition.getId()+"==>"+definition.getRegisterClass()+":"+definition.isSignlton());
// new RuntimeException().printStackTrace();
}
}
});
// System.out.println(ResourceManager.getClassPath(PluginBootServerTest.class)[0]);
// System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
// System.out.println(ResourceManager.class.get.getSystemClassLoader().getResource("."));
PluginBootServer.run();
System.out.println(PlugsFactory.getPluginsInstance("nacosConfigureFactory")+"");
// System.out.println(PlugsFactory.getPluginsInstance("sqlSession")+" ");
// org.apache.coyote.http2.Http2Protocol
}
} |
package martin.s4a.shift4all2;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import martin.s4a.templates.SchemeTemplates;
/**
* Created by Martin on 29.12.2014.
*/
public class SchemeListAdapter extends ShiftListAdapter {
ArrayList<SchemeTemplates> schemes;
public SchemeListAdapter(Context context)
{
super(context);
schemes = database.getAllScheme();
}
@Override
public int getCount() {
return schemes.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.shift_list_item, null);
}
initialize(v);
((GradientDrawable) circle.getBackground()).setColor(v.getResources().getColor(R.color.theme_color));
title.setText(schemes.get(position).getTitle());
return v;
}
}
|
package edu.wayne.cs.severe.redress2.entity.refactoring.formulas.rmmo;
import edu.wayne.cs.severe.redress2.controller.MetricUtils;
import edu.wayne.cs.severe.redress2.controller.metric.CYCLOMetric;
import edu.wayne.cs.severe.redress2.controller.metric.CodeMetric;
import edu.wayne.cs.severe.redress2.entity.MethodDeclaration;
import edu.wayne.cs.severe.redress2.entity.TypeDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class CYCLOReplaceMethodObjectPF extends ReplaceMethodObjectPredFormula {
@Override
public HashMap<String, Double> predictMetrVal(RefactoringOperation ref,
LinkedHashMap<String, LinkedHashMap<String, Double>> prevMetrics)
throws Exception {
TypeDeclaration srcCls = getSourceClass(ref);
MethodDeclaration method = getMethod(ref);
TypeDeclaration tgtCls = getTargetClass(ref);
double cyclo = MetricUtils.getCycloMethod(srcCls, method.getObjName());
HashMap<String, Double> predMetrs = new HashMap<String, Double>();
Double prevMetr = prevMetrics.get(srcCls.getQualifiedName()).get(
getMetric().getMetricAcronym());
predMetrs.put(srcCls.getQualifiedName(), prevMetr - cyclo + 1);
predMetrs.put(tgtCls.getQualifiedName(), cyclo + 1);
return predMetrs;
}
@Override
public CodeMetric getMetric() {
return new CYCLOMetric();
}
}
|
/*
* 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 Controller;
import Model.StatusUsuario;
import Util.Classes.Conexao;
import java.util.List;
/**
*
* @author Tadeu
*/
public class StatusUsuarioDAO extends Conexao {
public void salvar(StatusUsuario status){
em.getTransaction().begin();
em.merge(status);
em.getTransaction().commit();
}
public List<StatusUsuario> listar() {
em.getTransaction().begin();
query = em.createNamedQuery("StatusUsuario.findAll");
em.getTransaction().commit();
return query.getResultList();
}
public StatusUsuario buscar(String descricao) {
em.getTransaction().begin();
query=em.createNamedQuery("StatusUsuario.findByDescricao").setParameter("descricao", descricao);
em.getTransaction().commit();
return (StatusUsuario) query.getSingleResult();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.