text stringlengths 10 2.72M |
|---|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* 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 org.neuro4j.studio.flow.utils;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl;
public class FlowResourceFactoryImpl extends ResourceFactoryImpl
{
public Resource createResource(URI uri)
{
if ("n4j".equals(uri.fileExtension()))
{
return new FlowResourceImpl(uri);
}
Resource result = new FlowResourceImpl(uri);
return result;
}
}
|
package com.XJK.dao.impl;
import com.XJK.dao.ArticleDao;
import com.XJK.pojo.Article;
import java.util.List;
public class ArticleDaoImpl extends BaseDao implements ArticleDao {
/**
* 根据title查询文章内容
* @param title
* @return
*/
@Override
public Article queryContentByTitle(String title) {
String sql = "select id, title, putTime, introduct, img, content from t_article where title = ?";
List<Article> articleList = queryArticle(sql, title);
if (articleList.size() > 0 ){
return (Article) articleList.get(0);
}
return null;
}
/**
* 添加文章
* @param article
* @return
*/
@Override
public int saveArticle(Article article) {
String sql = "insert into t_article(title, putTime, introduct, img, content) values (?,?,?,?,?)";
return update(sql, article.getTitle(), article.getPutTime(), article.getIntroduct(), article.getImg(), article.getContent());
}
/**
* 获取所有文章
* @return
*/
@Override
public List<Article> queryAllArticle() {
String sql = "select * from t_article order by id desc";
return queryArticle(sql);
}
/**
* 根据文章名删除文章
* @param title
* @return
*/
@Override
public int deleteArticleByTitle(String title) {
String sql = "delete from t_article where title = ?";
return update(sql, title);
}
/**
* 更新存在的文章的内容
* @param article
* @return
*/
@Override
public int updateArticleByTitle(Article article) {
// //先获取id
// Long id = queryContentByTitle(article.getTitle()).getId();
//根据id更新content
String sql = "update t_article set putTime=?, introduct=?, img=?, content=? where title = ?";
return update(sql, article.getPutTime(), article.getIntroduct(), article.getImg(),article.getContent(), article.getTitle());
}
/**
* 重新排序数据库id
* @return
*/
@Override
public void reOrderId() {
String sql1 = "ALTER TABLE `t_article` DROP `id`" ;
String sql2 = "ALTER TABLE `t_article` ADD `id` BIGINT NOT NULL FIRST" ;
String sql3 = "ALTER TABLE `t_article` MODIFY COLUMN `id` BIGINT NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(id);";
update(sql1);
update(sql2);
update(sql3);
}
}
|
package projecteuler;
import java.util.ArrayList;
import java.util.Collections;
public class Divisors {
// Return the sum of the divisors of n
public static long getDivisorSum(long n) {
long sum = 0;
double sqrt = Math.sqrt(n);
for (long i = 1; i <= sqrt; i++) {
if (i == sqrt) {
sum += i;
} else {
if (n % i == 0) {
sum += i;
if (i > 1) {
// only include proper divisors
sum += n / i;
}
}
}
}
return sum;
}
public static long getNumDivisors(long n) {
long num = 0;
double sqrt = Math.sqrt(n);
for (long i = 1; i <= sqrt; i++) {
if (i == sqrt) {
num++;
} else {
if (n % i == 0) {
if (i > 1) {
num += 2;
} else {
num++;
}
}
}
}
return num;
}
public static ArrayList<Long> getDivisors(long n) {
ArrayList<Long> divisors = new ArrayList<Long>();
double sqrt = Math.sqrt(n);
for (long i = 1; i <= sqrt; i++) {
if (i == sqrt) {
divisors.add(i);
} else {
if (n % i == 0) {
divisors.add(i);
if (i > 1) {
// only include proper divisors
divisors.add(n / i);
}
}
}
}
Collections.sort(divisors);
return divisors;
}
public static boolean isAbundant(long n) {
return getDivisorSum(n) > n;
}
public static boolean isDeficit(long n) {
return getDivisorSum(n) < n;
}
public static boolean isPerfect(long n) {
return getDivisorSum(n) == n;
}
}
|
package pomSatyaAvasarala;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class AdminLoginPage {
WebDriver driver;
WebElement email;
WebElement password;
WebElement submit;
public AdminLoginPage(WebDriver driver) {
this.driver = driver;
driver.get("http://pageobjectpattern.wordpress.com/wp-admin");
email = driver.findElement(By.id("user_login"));
password = driver.findElement(By.id("user_pass"));
submit = driver.findElement(By.id("wp-submit"));
}
public void login() throws InterruptedException {
Thread.sleep(5000);
email.sendKeys("pageobjectpattern@gmail.com");
Thread.sleep(5000);
password.sendKeys("webdriver123");
Thread.sleep(5000);
submit.click();
}
}
|
package userdaoimp;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import userdao.UserDAO;
import utils.Database;
import bean.bookbean.BookBean;
import bean.bookbean.BookIssueBean;
import bean.users.AuthBean;
import bean.users.UserBean;
public class UserDaoImpl implements UserDAO {
private SessionFactory factory = utils.HConnection.getSessionFactory();
private Session session = null;
private Transaction tr = null;
private List<UserBean> list = null;
private Database connection;
public UserDaoImpl() {
list = new ArrayList<>();
//connection = new Database();
}
@Override
public int insert(UserBean c) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
int id = (Integer) session.save(c);
tr.commit();
session.close();
return id;
}
@Override
public List<UserBean> getAll() throws ClassNotFoundException, SQLException {
list = new ArrayList<>();
session = factory.openSession();
tr = session.beginTransaction();
list = session.createQuery("FROM UserBean").list();
tr.commit();
session.close();
factory.close();
return list;
}
@Override
public UserBean getById(int id) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.eq("id", id));
UserBean bean = (UserBean) criteria.uniqueResult();
tr.commit();
session.close();
factory.close();
return bean;
}
@Override
public int update(int id, UserBean c) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
UserBean b = (UserBean) session.get(UserBean.class, id);
b.setFirstName(c.getFirstName());
b.setLastName(c.getLastName());
b.setStatus(c.getStatus());
b.setRoles(c.getRoles());
session.update(b);
session.getTransaction().commit();
session.close();
return id;
}
@Override
public int delete(int id) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
UserBean b = (UserBean) session.get(UserBean.class, id);
session.delete(b);
tr.commit();
session.close();
return id;
}
@Override
public int softDelete(int id) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
UserBean b = (UserBean) session.get(UserBean.class, id);
b.setStatus("0");
return id;
}
@Override
public int requestBook(BookIssueBean i) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
int id = (Integer) session.save(i);
tr.commit();
session.close();
return id;
}
@Override
public BookIssueBean getBookIssueById(int id) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.eq("id", id));
BookIssueBean bean = (BookIssueBean) criteria.uniqueResult();
tr.commit();
session.close();
factory.close();
return bean;
}
@Override
public BookIssueBean getBookIssueRequestByBookId(int id, int approve) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.eq("bookId", id));
if(approve != -1){
criteria.add(Restrictions.eq("agentId", approve));
}
BookIssueBean bean = (BookIssueBean) criteria.uniqueResult();
tr.commit();
session.close();
factory.close();
return bean;
}
@Override
public List<BookIssueBean> getBookIssueByUserId(int id) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(BookIssueBean.class);
criteria.add(Restrictions.eq("bookId", id));
criteria.add(Restrictions.eq("agentId", 0));
List<BookIssueBean> list = criteria.list();
session.close();
factory.close();
return list;
}
@Override
public int removeRequestBookByBookBeanUserBean(BookBean b, UserBean ub) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(BookIssueBean.class);
criteria.add(Restrictions.eq("book", b));
criteria.add(Restrictions.eq("user", ub));
BookIssueBean bean = (BookIssueBean) criteria.setMaxResults(1).uniqueResult();
System.out.println(bean);
session.delete(bean);
tr.commit();
session.close();
return b.getId();
}
@Override
public int acceptBookRequest(int id, BookIssueBean c) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
BookIssueBean b = (BookIssueBean) session.get(BookIssueBean.class, id);
b.setStatus(c.getStatus());
b.setAgentId(c.getAgentId());
session.update(b);
session.getTransaction().commit();
session.close();
return id;
}
@Override
public int rejectedBookRequest(int id, int userId) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
BookIssueBean b = (BookIssueBean) session.get(BookIssueBean.class, id);
b.setStatus("2");
b.setAgentId(userId);
session.update(b);
session.getTransaction().commit();
session.close();
return id;
}
public Long getBookIssueLimit(UserBean user) throws ClassNotFoundException, SQLException {
session = factory.openSession();
Query query = session.createQuery("select count(*) from BookIssueBean where user_id = :userId").setParameter("userId", user);
Long count=(Long) query.uniqueResult();
return count;
}
@Override
public BookIssueBean getBookIssueRequestByBookIdUserId(int bookId, int userId, int approve) throws ClassNotFoundException, SQLException {
session = factory.openSession();
tr = session.beginTransaction();
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.eq("bookId", bookId));
criteria.add(Restrictions.eq("userId", userId));
if(approve != -1){
criteria.add(Restrictions.eq("agentId", approve));
}
BookIssueBean bean = (BookIssueBean) criteria.uniqueResult();
session.close();
factory.close();
return bean;
}
@Override
public BookIssueBean getBookIssueRequestByBookBeanUserBean(BookBean bookId, UserBean userId, int approve, String status) throws ClassNotFoundException, SQLException {
session = factory.openSession();
Criteria criteria = session.createCriteria(BookIssueBean.class);
criteria.add(Restrictions.eq("book", bookId));
criteria.add(Restrictions.eq("user", userId));
if(approve != -1){
criteria.add(Restrictions.eq("agentId", approve));
}
if(status != null){
criteria.add(Restrictions.eq("status", status));
}
BookIssueBean bean = (BookIssueBean) criteria.setMaxResults(1).uniqueResult();
session.close();
factory.close();
return bean;
}
@Override
public int setActiveUser(int id, UserBean ub) {
session = factory.openSession();
tr = session.beginTransaction();
UserBean b = (UserBean) session.get(UserBean.class, id);
b.setStatus(ub.getStatus());
session.update(b);
session.getTransaction().commit();
session.close();
return id;
}
@Override
public int setActiveUserAuth(int id, AuthBean auth) {
session = factory.openSession();
tr = session.beginTransaction();
AuthBean b = (AuthBean) session.get(AuthBean.class, id);
b.setStatus(auth.getStatus());
session.update(b);
session.getTransaction().commit();
session.close();
return id;
}
@Override
public List<UserBean> searchUserByKeyWord(String keyWord) {
List<UserBean> list = new ArrayList<>();
session = factory.openSession();
String hql = "SELECT u from UserBean u INNER JOIN u.authBean auth where auth.email like :em OR u.firstName like :fName OR u.lastName like :lName";
list = session.createQuery(hql)
.setParameter("fName", "%"+keyWord+"%")
.setParameter("em", "%"+keyWord+"%")
.setParameter("lName", "%"+keyWord+"%").list();
session.close();
factory.close();
return list;
}
}
|
package jnouse;
import jalgo.StudentTest;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jclient.VideoFile;
import jmckoi.MatrixRetrieve;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.FDistributionImpl;
import Jama.Matrix;
public class Anova2 {
/**
* Significant level of the two-sided test of statistics
*/
static final double alpha = 0.1;
/**group the 256 color values into nobins */
private static final int nobins = 256;
/**
* p.values for every column of mat match with corresponding
* columns of matrices videoMat. The probability values are
* obtained using the student distribution;
* dim=[#videosToTest][256]
*
*/
double[]pvalues;
boolean showtest = true;
List<String> thevideos = new ArrayList<String>();
static int totest = 0;
//Results of test after completing test
private static StringBuffer res[]= new StringBuffer[3] ;
private static Logger mLog =
Logger.getLogger(StudentTest.class.getName());
private boolean debug = true;
public static double getAlpha(){
return alpha;
}
//it will exclude the video to test or index totest
public List<String> getThevideos(){
return thevideos;
}
public void setThevideos(List<String> vt){
thevideos=vt;
}
public static StringBuffer[] getRes(){
return res;
}
public Anova2(String args[])throws MathException{
if(!debug)
mLog.setLevel(Level.WARNING);
//true is for the mean otherwise it is the median
MatrixRetrieve vstore = new MatrixRetrieve("TbVideoColt", true, true);
List<String> similar = new ArrayList<String>();
//videos are input as arguments of main
if(args.length > 1) {
vstore.retreiveMat(args);
for(int a=0; a < args.length; ++a)
thevideos.add(args[a]);
}
int cnt = args.length;
//videos are input in a file
if (args.length == 1){ //reading from file
args[0].trim();
thevideos = VideoFile.readFile(args[0]);
String [] argsf = thevideos.toArray(new String[thevideos.size()]);
vstore.retreiveMat(argsf);
cnt = argsf.length;
}
//
int sz = thevideos.size();
String testvid = thevideos.get(totest);
List<String> pass = new ArrayList<String>();
pass.addAll(thevideos);
StringBuffer r[] = meanDifTest(vstore, totest);
for(int k=0; k<3; ++k)
this.res[k]=r[k];
String toprint="\n\nTest video: "+ testvid +
"\nStudent test at significant level= " + Anova2.alpha;
StringBuffer sim =new StringBuffer(toprint);
mLog.info(toprint);
}
public StringBuffer[] meanDifTest(MatrixRetrieve vstore,int totest)
throws MathException{
String testvid = thevideos.get(totest);
if(!showtest)
thevideos.remove(totest);
StringBuffer res0 = new StringBuffer("Test video "+ testvid);
StringBuffer[] res = new StringBuffer[3];
String mess1 = "Testing video: " + testvid;
//JOptionPane.showMessageDialog(null, mess1, "Test videos",
// JOptionPane.INFORMATION_MESSAGE);
Matrix [] matG = MatrixRetrieve.studentMats(vstore.getMeangreen());
Matrix [] matR = MatrixRetrieve.studentMats(vstore.getMeanred());
Matrix [] matB = MatrixRetrieve.studentMats(vstore.getMeanblue());
StringBuffer rtest = anovatest(matR,thevideos, "RED");
res[0] = new StringBuffer("\n"+res0);
res[0].append(rtest);
StringBuffer gtest = anovatest(matG,thevideos,"GREEN");
res[1] = new StringBuffer("\n"+res0);
res[1].append(gtest);
StringBuffer btest = anovatest(matB,thevideos,"BLUE");
res[2] = new StringBuffer("\n"+res0);
res[2].append( btest);
return res;
}
public StringBuffer anovatest(Matrix[]base, List<String> thevid, String col )
throws MathException{
double [][] arr = new double[base.length][256];
double []rwsum = new double[base.length];
double M= 0;
int cnt=0;
double SST =0;
for(Matrix mm : base){
arr[cnt] = mm.transpose().getArrayCopy()[0];
cnt++;
}
int sz = base.length;
double[][] basearr=groupbins(arr,sz);
double r = 256/nobins;
for(cnt=0; cnt < base.length; ++cnt){
for(double d:basearr[cnt]){
rwsum[cnt]=rwsum[cnt]+(d);
M= M+d;
SST =SST + d*d;
}
}
double norow = base.length;
double [] colsum = new double[nobins];
double nocol = 0;
for(int cl=0; cl< nobins; ++cl ){
for(int n=0; n < base.length; ++n) {
colsum[cl] += basearr[n][cl];
}
if(colsum[cl] > 1.e-5) nocol+=1;
}
double CM = M*M/(r*norow*nocol + 1.e-10);
SST = SST-CM;
double SSA = 0;
for(double d: rwsum) SSA = SSA+ d*d;
SSA = SSA/(r*nocol+1.e-10)-CM;
double SSB = 0;
cnt=0;
for(double dd:colsum){
SSB = SSB+ dd*dd;
}
SSB = SSB/(r*norow+1.e-10)-CM;
double SSAB =0;
for(int n=0; n < base.length; ++n)
for(int k=0; k < nobins; ++k)
SSAB += basearr[n][k]* basearr[n][k];
SSAB =SSAB/r-CM-SSA-SSB;
double SSE = SST- SSA - SSB - SSAB;
double MSA = SSA/(norow-1);
double MSB = SSB/(nocol-1);
double MSAB = SSAB/((nocol-1)*(norow-1));
double df = r>1 ?nocol*norow*(r-1):nocol*norow;
double error = SSE/df;
double FA = MSA/(error+1.e-5);
double FB = MSB/(error+1.e-5);
double FAB = MSAB/(error+1.e-5);
System.out.println(""+FA+"\t"+FB+"\t"+FAB+"\t"+df+"\t"+CM);
FDistributionImpl paf = new FDistributionImpl(norow-1,df);
double pA=1- paf.cumulativeProbability(FA);
FDistributionImpl pbf = new FDistributionImpl(nocol-1,df);
double pB=1- pbf.cumulativeProbability(FB);
FDistributionImpl pabf = new FDistributionImpl((nocol-1)*(norow-1),df);
double pAB=1- pabf.cumulativeProbability(FAB);
pvalues = new double[3];
pvalues[0] = pA;
pvalues[1] = pB;
pvalues[2] = pAB;
StringBuffer res = new StringBuffer();
res.append("\nanova test at significant level= "+
Anova2.alpha);
res.append("\nColor component "+ col + ": ");
res.append("\nMean frames "+pA);
res.append("\nColor values "+pB);
res.append("\nInteraction "+pAB);
return res;
}
private double[][] groupbins(double[][]basearr,int len){
double [][] basebin = new double[basearr.length][nobins];
int sz = 256/nobins;
int cnt =0;
if(sz >1){
for(int n=0; n < len;++n){
cnt=0;
for(int c=0; c < 256;++c){
if(c <=0){
basebin[n][cnt]=0;
}else if(c > 0 && c%sz <= 0) {
cnt++;
basebin[n][cnt]= basearr[n][c];
}else{
basebin[n][cnt] += basearr[n][c];
}
}
}
}else
basebin = basearr;
double[] basemn = new double[nobins];
/* for(int c=0; c < nobins;++c)
for(int r= 0; r < len; ++r)
basemn[c]+= basebin[r][c]/len;
for(int n=0; n < len; ++n)
for(int c= 0; c < nobins; ++c)
basebin[n][c] = Math.abs(basebin[n][c]-basemn[c]);
*/
return basebin;
}
public static void main(String[]args) throws MathException{
Anova2 chi = new Anova2(args);
StringBuffer[] res = chi.getRes();
for(StringBuffer buf:res)
mLog.info(buf.toString());
}
}
|
package com.netcracker.services.Channels;
import com.netcracker.RenderTemplate.DataParser;
import com.netcracker.entities.InfoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sound.midi.MidiDevice;
import java.util.Collection;
import java.util.Map;
public class FillInfoContent {
private Map<String, String> data;
public FillInfoContent(Map<String, String> data) {
this.data = data;
}
public Collection<InfoMap> fill(Collection<InfoMap> infoMaps) {
infoMaps.forEach( v -> v.setInfoValue(data.getOrDefault(v.getInfoKey(), "null")));
return infoMaps;
}
} |
package by.client.android.railwayapp.support.base;
import android.os.AsyncTask;
/**
* Базовый класс для реализации асинхронных запросов с возможностью отображения индикатора выполнения
* <p>Основные методы класса.</p>
* <ul>
* <li>{@link BaseAsyncTask#runTask(Object[])} выполняет задачу в фоне</li>
* <li>{@link BaseAsyncTask#onCompleted(Object)} выполняется после успешного выполнения задачи</li>
* <li>{@link BaseAsyncTask#onFinish(boolean)} срабатывает после выполнения задачи</li>
* <li>{@link BaseAsyncTask#onError(Exception)} выполняется при возникновении ошибки при выполнении задачи</li>
* </ul>
*
* @param <Params> тип входного параметра
* @param <Result> тип возвращаемого результата при успешном выполнении задачи
*
* @author ROMAN PANTELEEV
*/
public abstract class BaseAsyncTask<Params, Result> extends AsyncTask<Params, Void, Result> {
private Exception exception = null;
/**
* Метод для обработки завершения операции
*
* @param param результат выполения
*/
protected abstract void onCompleted(Result param);
/**
* Метод срабатывающий перез выполнением асинхронной задачи
*/
protected abstract void onStart();
/**
* Метод срабатывает после выполнения асинхронной задачи
*
* @param successful индикатор успешного выполнения задачи
*/
protected abstract void onFinish(boolean successful);
/**
* Метод выполнения операции
*
* @param param параметры для выполнения операции
*/
protected abstract Result runTask(Params... param) throws Exception;
/**
* Метод для обработки ошибки выполнения
*
* @param exception ошибка при выполнении операции
*/
protected abstract void onError(Exception exception);
@Override
protected Result doInBackground(Params... params) {
try {
return runTask(params);
}
catch (Exception ex) {
exception = ex;
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
onStart();
}
@Override
protected void onPostExecute(Result response) {
super.onPostExecute(response);
if (exception == null) {
onCompleted(response);
} else {
onError(exception);
}
onFinish(exception == null);
}
}
|
package Bookshelf.controller;
import Bookshelf.domain.User;
import Bookshelf.service.AddFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
@Controller
@Service
public class FolderController {
@Autowired
private AddFilesService addFilesService;
@GetMapping("/addfromfile")
public String addFromFile(@AuthenticationPrincipal User user) throws IOException {
addFilesService.addFiles(user);
return "redirect:/main";
}
} |
package wpp.android;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.text.Html;
import android.text.Spanned;
import android.widget.EditText;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
public class AMapUtil {
/**
* 判断edittext是否null
*/
public static String checkEditText(EditText editText) {
if (editText != null && editText.getText() != null
&& !(editText.getText().toString().trim().equals(""))) {
return editText.getText().toString().trim();
} else {
return "";
}
}
public static Spanned stringToSpan(String src) {
return src == null ? null : Html.fromHtml(src.replace("\n", "<br />"));
}
public static String colorFont(String src, String color) {
StringBuffer strBuf = new StringBuffer();
strBuf.append("<font color=").append(color).append(">").append(src)
.append("</font>");
return strBuf.toString();
}
public static String makeHtmlNewLine() {
return "<br />";
}
public static String makeHtmlSpace(int number) {
final String space = " ";
StringBuilder result = new StringBuilder();
for (int i = 0; i < number; i++) {
result.append(space);
}
return result.toString();
}
public static String getFriendlyLength(int lenMeter) {
if (lenMeter > 10000) // 10 km
{
int dis = lenMeter / 1000;
return dis + ChString.Kilometer;
}
if (lenMeter > 1000) {
float dis = (float) lenMeter / 1000;
DecimalFormat fnum = new DecimalFormat("##0.0");
String dstr = fnum.format(dis);
return dstr + ChString.Kilometer;
}
if (lenMeter > 100) {
int dis = lenMeter / 50 * 50;
return dis + ChString.Meter;
}
int dis = lenMeter / 10 * 10;
if (dis == 0) {
dis = 10;
}
return dis + ChString.Meter;
}
public static boolean IsEmptyOrNullString(String s) {
return (s == null) || (s.trim().length() == 0);
}
/**
* 把LatLng对象转化为LatLonPoint对象
*/
public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
return new LatLonPoint(latlon.latitude, latlon.longitude);
}
/**
* 把LatLonPoint对象转化为LatLon对象
*/
public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
}
/**
* 把集合体的LatLonPoint转化为集合体的LatLng
*/
public static ArrayList<LatLng> convertArrList(List<LatLonPoint> shapes) {
ArrayList<LatLng> lineShapes = new ArrayList<LatLng>();
for (LatLonPoint point : shapes) {
LatLng latLngTemp = AMapUtil.convertToLatLng(point);
lineShapes.add(latLngTemp);
}
return lineShapes;
}
/**
* long类型时间格式化
*/
public static String convertToTime(long time) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(time);
return df.format(date);
}
public static final String HtmlBlack = "#000000";
public static final String HtmlGray = "#808080";
}
|
package com.example.rest.resource;
import com.example.rest.entity.Genre;
import com.fasterxml.jackson.annotation.JsonInclude;
public class GenreResource extends BaseResource
{
private Integer id;
private String name;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Genre_MusicalCompositionResource[] genre_MusicalCompositionResourcesItems;
public GenreResource()
{
}
public GenreResource(Genre genre)
{
this.id = genre.getId();
this.name = genre.getName();
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Genre_MusicalCompositionResource[] getGenre_MusicalCompositionResourcesItems()
{
return genre_MusicalCompositionResourcesItems;
}
public void setGenre_MusicalCompositionResourcesItems(Genre_MusicalCompositionResource[] genre_MusicalCompositionResourcesItems)
{
this.genre_MusicalCompositionResourcesItems = genre_MusicalCompositionResourcesItems;
}
public Genre toEntity()
{
return new Genre(
this.id,
this.name);
}
}
|
package com.example.favorite;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FavoriteApplicationTests {
@Test
void contextLoads() {
}
}
|
/*
* Dryuf framework
*
* ----------------------------------------------------------------------------------
*
* Copyright (C) 2000-2015 Zbyněk Vyškovský
*
* ----------------------------------------------------------------------------------
*
* LICENSE:
*
* This file is part of Dryuf
*
* Dryuf is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* Dryuf is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Dryuf; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @author 2000-2015 Zbyněk Vyškovský
* @link mailto:kvr@matfyz.cz
* @link http://kvr.matfyz.cz/software/java/dryuf/
* @link http://github.com/dryuf/
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3
*/
package net.dryuf.comp.rating.jpadao;
import net.dryuf.comp.rating.RatingHeader;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional("dryuf")
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class RatingHeaderDaoJpa extends net.dryuf.dao.DryufDaoContext<RatingHeader, Long> implements net.dryuf.comp.rating.dao.RatingHeaderDao
{
public RatingHeaderDaoJpa()
{
super(RatingHeader.class);
}
@Override
@Transactional("dryuf")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateStatistics(long ratingId)
{
entityManager.flush();
entityManager.createQuery("UPDATE RatingHeader rh SET counts = COALESCE((SELECT COUNT(*) FROM RatingRecord rr WHERE rr.pk.ratingId = rh.ratingId), 0), total = COALESCE((SELECT SUM(value) FROM RatingRecord rr WHERE rr.pk.ratingId = rh.ratingId), 0) WHERE rh.ratingId = :ratingId")
.setParameter("ratingId", ratingId)
.executeUpdate();
entityManager.createQuery("UPDATE RatingHeader rh SET rating = COALESCE(rh.total/COALESCE(CASE WHEN rh.counts = 0 THEN 1 ELSE rh.counts END, 0), 0) WHERE rh.ratingId = :ratingId")
.setParameter("ratingId", ratingId)
.executeUpdate();
}
}
|
package utils;
public class ErrorCode {
/**
* ErrorCode List
*/
public ErrorCode() { }
/**
* Invalidation
*/
public static int invalidArgumentLength = 3000;
public static int invalidPeerID = 3001;
/**
* Missing Important Objects
* - Singleton object error occurs
*/
public static int missSystemInfo = 4000;
public static int missLogHandler = 4001;
public static int missFileManager = 4002;
public static int missServerConn = 4003;
public static int missServerOpStream = 4004;
public static int missClientConn = 4005;
public static int missClientOpStream = 4006;
public static int missActMsgObj = 4007;
/**
* System error
*/
public static int failParsePeerInfo = 5000;
public static int failHandshake = 5001;
public static int invalidHandshakeHeader = 5002;
public static int invalidNeighbor = 5003;
}
|
package me.darkeet.android.demo.adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import com.android.volley.Listener;
import com.android.volley.core.RequestManager;
import com.android.volley.image.NetworkImageView;
import me.darkeet.android.demo.R;
import me.darkeet.android.demo.model.ViewModel;
import android.support.v7.extensions.PaletteManager;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private Context context;
private List<ViewModel> mDataList;
private PaletteManager paletteManager;
public RecyclerViewAdapter(Context context) {
this.context = context;
this.mDataList = new ArrayList<>();
this.paletteManager = new PaletteManager();
}
public void addItems(List<ViewModel> items) {
this.mDataList.addAll(items);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.recyclerview_item, parent, false));
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final ViewModel item = mDataList.get(position);
holder.itemView.setTag(item);
holder.text.setText(item.getText());
holder.image.setImageListener(new Listener<Bitmap>() {
@Override
public void onSuccess(Bitmap bitmap) {
holder.updatePalette(paletteManager, bitmap);
}
});
holder.image.setImageUrl(item.getImage(), RequestManager.loader().useDefaultLoader().obtain());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
remove((ViewModel) view.getTag());
}
});
}
@Override
public int getItemCount() {
return mDataList.size();
}
public void add(ViewModel item, int position) {
mDataList.add(position, item);
notifyItemInserted(position);
}
public void remove(ViewModel item) {
int position = mDataList.indexOf(item);
mDataList.remove(position);
notifyItemRemoved(position);
}
private static int setColorAlpha(int color, int alpha) {
return (alpha << 24) | (color & 0x00ffffff);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public NetworkImageView image;
public ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
image = (NetworkImageView) itemView.findViewById(R.id.image);
}
public void updatePalette(PaletteManager paletteManager, Bitmap bitmap) {
String key = ((ViewModel) itemView.getTag()).getImage();
paletteManager.getPalette(key, bitmap, new PaletteManager.Callback() {
@Override
public void onPaletteReady(Palette palette) {
int bgColor = palette.getVibrantSwatch().getRgb();
text.setBackgroundColor(setColorAlpha(bgColor, 192));
text.setTextColor(bgColor);
}
});
}
}
} |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionaltests.workflow;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Assert;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.Job;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.job.factories.JobFactory;
import org.ow2.proactive.scheduler.common.task.Task;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.flow.FlowActionType;
import org.ow2.tests.FunctionalTest;
import functionaltests.SchedulerTHelper;
/**
* Tests the correctness of workflow-controlled jobs
*
* @author The ProActive Team
* @since ProActive Scheduling 2.2
*/
public abstract class TWorkflowJobs extends FunctionalTest {
protected final String jobSuffix = ".xml";
/**
* Each array is a job named $(array index).xml :
* {{ job1 }, { job2 } ... { jobn }}
* Each cell in the matrix is a task and its integer result :
* {{"Task1_name Task1_result", "Task2_name Task2_result", .... "Taskn_name Taskn_result"}}
*
* Each task and result must match exactly once for each job,
* except when using {@link FlowActionType#IF}: there will be no
* result for {@link TaskStatus#SKIPPED} tasks, they must be present in the
* array but with a negative (ie -1) result value
*
* @return the task names / result matrix
*/
public abstract String[][] getJobs();
/**
* @return the search path on the filesystem for job descriptors
*/
public abstract String getJobPrefix();
/**
* For each job described in {@link #jobs}, submit the job,
* wait for finished state, and compare expected result for each task with the actual result
*
* @throws Throwable
*/
protected void internalRun() throws Throwable {
String[][] jobs = getJobs();
for (int i = 0; i < jobs.length; i++) {
Map<String, Long> tasks = new HashMap<String, Long>();
for (int j = 0; j < jobs[i].length; j++) {
String[] val = jobs[i][j].split(" ");
try {
tasks.put(val[0], Long.parseLong(val[1]));
} catch (Throwable t) {
System.out.println(jobs[i][j]);
t.printStackTrace();
}
}
String path = new File(TWorkflowJobs.class.getResource(getJobPrefix() + (i + 1) + jobSuffix)
.toURI()).getAbsolutePath();
SchedulerTHelper.log("Testing job: " + path);
testJob(path, tasks);
}
}
/**
* See @{link {@link SchedulerTHelper#testJobSubmission(Job)}; does about the same,
* but skips the part that expects the initial submitted task set to be identical to
* the finished task set.
*
* @param jobToSubmit
* @param skip tasks that will be skipped due to {@link FlowActionType#IF}, do not wait for their completion
* @return
* @throws Exception
*/
public static JobId testJobSubmission(Job jobToSubmit, List<String> skip) throws Exception {
JobId id = SchedulerTHelper.submitJob(jobToSubmit);
SchedulerTHelper.log("Job submitted, id " + id.toString());
SchedulerTHelper.log("Waiting for jobSubmitted");
JobState receivedstate = SchedulerTHelper.waitForEventJobSubmitted(id);
Assert.assertEquals(id, receivedstate.getId());
SchedulerTHelper.log("Waiting for job running");
JobInfo jInfo = SchedulerTHelper.waitForEventJobRunning(id);
Assert.assertEquals(jInfo.getJobId(), id);
Assert.assertEquals(JobStatus.RUNNING, jInfo.getStatus());
if (jobToSubmit instanceof TaskFlowJob) {
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
if (skip != null && skip.contains(t.getName())) {
continue;
}
TaskInfo ti = SchedulerTHelper.waitForEventTaskRunning(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
Assert.assertEquals(TaskStatus.RUNNING, ti.getStatus());
}
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
if (skip != null && skip.contains(t.getName())) {
continue;
}
TaskInfo ti = SchedulerTHelper.waitForEventTaskFinished(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
Assert.assertTrue(TaskStatus.FINISHED.equals(ti.getStatus()));
}
}
SchedulerTHelper.log("Waiting for job finished");
jInfo = SchedulerTHelper.waitForEventJobFinished(id);
Assert.assertEquals(JobStatus.FINISHED, jInfo.getStatus());
SchedulerTHelper.log("Job finished");
return id;
}
/**
* Submits the job located at <code>jobPath</code>, compares its results with the ones provided
* in <code>expectedResults</code>
*
* Each task for the provided jobs is a org.ow2.proactive.scheduler.examples.IncrementJob
* which adds all the parameters result + 1.
* Testing each task's result enforces that all expected tasks are present, with the right dependency graph,
* thus the correctness of the job.
*
* @param jobPath
* @param expectedResults
* @throws Throwable
*/
public static void testJob(String jobPath, Map<String, Long> expectedResults) throws Throwable {
List<String> skip = new ArrayList<String>();
for (Entry<String, Long> er : expectedResults.entrySet()) {
if (er.getValue() < 0) {
skip.add(er.getKey());
}
}
JobId id = testJobSubmission(jobPath, skip);
JobResult res = SchedulerTHelper.getJobResult(id);
Assert.assertFalse(SchedulerTHelper.getJobResult(id).hadException());
for (Entry<String, TaskResult> result : res.getAllResults().entrySet()) {
Long expected = expectedResults.get(result.getKey());
Assert.assertNotNull(jobPath + ": Not expecting result for task '" + result.getKey() + "'",
expected);
Assert.assertTrue("Task " + result.getKey() + " should be skipped, but returned a result",
expected >= 0);
if (!(result.getValue().value() instanceof Long)) {
System.out.println(result.getValue().value() + " " + result.getValue().value().getClass());
}
Assert.assertTrue(jobPath + ": Result for task '" + result.getKey() + "' is not an Long", result
.getValue().value() instanceof Long);
Assert.assertEquals(jobPath + ": Invalid result for task '" + result.getKey() + "'", expected,
(Long) result.getValue().value());
}
int skipped = 0;
// tasks SKIPPED are short-circuited by an IF flow action
// they are still in the tasks list, but do not return a result
for (Entry<String, Long> expected : expectedResults.entrySet()) {
if (expected.getValue() < 0) {
Assert.assertFalse("Task " + expected.getKey() + " should be skipped, but returned a result",
res.getAllResults().containsKey(expected.getKey()));
skipped++;
}
}
Assert.assertEquals("Expected and actual result sets are not identical in " + jobPath + " (skipped " +
skipped + "): ", expectedResults.size(), res.getAllResults().size() + skipped);
SchedulerTHelper.removeJob(id);
SchedulerTHelper.waitForEventJobRemoved(id);
}
public static JobId testJobSubmission(String jobDescPath, List<String> skip) throws Exception {
Job jobToTest = JobFactory.getFactory().createJob(jobDescPath);
return testJobSubmission(jobToTest, skip);
}
}
|
package gil.server.router;
import gil.server.http.HTTPProtocol;
import gil.server.http.Request;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class RoutesTest {
Router router = new Router();
@Test
public void shouldSetARootRouteOnTheRouter() {
Request request = new Request();
Routes routes = new Routes();
request.setMethod(HTTPProtocol.GET);
request.setURI("/");
request.setHttpVersion(HTTPProtocol.PROTOCOL);
routes.addRoutes(router);
assertTrue(router.getRouteController(request).isPresent());
}
}
|
package com.fsClothes.pojo;
/**
* @author MrDCG
* @version 创建时间:2020年3月7日 下午4:43:27
* 分页实现
*/
import java.io.Serializable;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Page<T> implements Serializable {
/**
* 序列化
*/
private static final long serialVersionUID = 3322298153884734243L;
// 每页显示条数
private Integer pageSize;
// 总条数
private Integer totalRecord;
// 当前请求页
private Integer pageNum;
// 存放当前页请求数据集合
List<T> list;
// 总页数:计算
private Integer totalPage;
// 起始下标
private Integer startIndex;
public void setTotalRecord(Integer totalRecord) {
this.totalRecord = totalRecord;
if (totalRecord % pageSize == 0) {
totalPage = totalRecord / pageSize;
} else {
totalPage = totalRecord / pageSize + 1;
}
}
public Integer getStartIndex() {
startIndex = (pageNum - 1) * pageSize;
return startIndex;
}
}
|
package com.nit.car.Model;
import java.util.List;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Entity
@Table
@Component
public class Supplier {
@Id
private String sid;
private String sname;
private String address;
@OneToMany(mappedBy="sup")
List<Product> p;
public List<Product> getP()
{
return p;
}
public Supplier()
{
this.sid="S"+UUID.randomUUID().toString().substring(30).toUpperCase();
}
public void setP(List<Product> p) {
this.p = p;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math.*;
public class MaxwellDemon extends JFrame implements ActionListener {
// Game Window
JFrame gameWindow;
// Buttons at top of view
JPanel buttonPanel;
JButton addButton;
JButton resetButton;
// Game panel and painted view in center of screen
JPanel gamePanel;
GameView game;
// Temperature at bottom of view
JPanel temperaturePanel;
JLabel leftTemperature;
JLabel rightTemperature;
// Tallies number of times wall is opened
int wallTimes;
// Timer and click counter to manage ball movements and temperature math
Timer clicky;
int clicks = 0;
// Balls instantiation
FastBall[] fast;
SlowBall[] slow;
int fastCount;
int slowCount;
// Timer multiple for clicker and ball math
double deltat = 0.05; // in seconds
// MaxwellDemon default constructor
public MaxwellDemon() {
gameWindow = new JFrame("Maxwell's Demon");
gameWindow.setSize(1000, 600);
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Walls opened tally set to 0
wallTimes = 0;
// Start timer
clicky = new Timer((int)(1000 * deltat), this);
clicky.start();
// Instantiating balls and adding 4 balls to the frame
fastCount = 0;
slowCount = 0;
fast = new FastBall[1000];
slow = new SlowBall[1000];
addBalls();
// Load gameView
game = new GameView();
gameWindow.add(game);
// Create button panel at the top of the view
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.GRAY);
addButton = new JButton("Add Particles");
resetButton = new JButton("Reset");
addButton.addActionListener(this);
resetButton.addActionListener(this);
buttonPanel.add(addButton);
buttonPanel.add(resetButton);
buttonPanel.setLayout(new GridLayout(1,2));
gameWindow.add(buttonPanel, BorderLayout.PAGE_START);
// Create temperature panel at the bottom of the view
temperaturePanel = new JPanel();
temperaturePanel.setBackground(Color.GRAY);
leftTemperature = new JLabel("Left", SwingConstants.CENTER);
rightTemperature = new JLabel("Right", SwingConstants.CENTER);
leftTemperature.setFont(new Font("Courier", Font.BOLD, 18));
rightTemperature.setFont(new Font("Courier", Font.BOLD, 18));
temperaturePanel.add(leftTemperature);
temperaturePanel.add(rightTemperature);
temperaturePanel.setLayout(new GridLayout(1,2));
gameWindow.add(temperaturePanel, BorderLayout.PAGE_END);
// Add a mouse listener to open and close the wall
gameWindow.addMouseListener(new MouseAdapter(){
public void mousePressed( MouseEvent m ) {
wallTimes++;
game.openWall();
game.repaint();
}
public void mouseReleased( MouseEvent m) {
game.closeWall();
game.repaint();
}
});
// Set all changes to visible
gameWindow.setVisible(true);
}
// GameView class to build the central game view
public class GameView extends JComponent {
// to track wall status
private boolean haveWall = true;
public void openWall() {
haveWall = false;
}
public void closeWall() {
haveWall = true;
}
public boolean getWallStatus() {
return haveWall;
}
public void paintComponent(Graphics g) {
super.paintComponent(g); // call to JFrame paintComponent()
// Creates central green rectangle
g.setColor(Color.green);
g.fillRect(50, 80, 900, 440);
// Creates the two room labels
g.setColor(Color.black);
g.drawString("Left Room", 50, 75);
g.drawString("Right Room", 879, 75);
// Draws wall
if (getWallStatus()) {
g.setColor(Color.black);
g.drawLine(499, 0, 499, 600);
g.drawLine(500, 0, 500, 600);
g.drawLine(501, 0, 501, 600);
}
// Draws abcense of wall
if (!getWallStatus()) {
g.drawLine(499, 0, 499, 80);
g.drawLine(500, 0, 500, 80);
g.drawLine(501, 0, 501, 80);
g.drawLine(499, 520, 499, 600);
g.drawLine(500, 520, 500, 600);
g.drawLine(501, 520, 501, 600);
g.setColor(Color.green);
g.drawLine(499, 80, 499, 520);
g.drawLine(500, 80, 500, 520);
g.drawLine(501, 80, 501, 520);
}
// Draws balls
for ( int i=0; i<slowCount; i++) {
slow[i].drawMe(g);
fast[i].drawMe(g);
}
}
}
// Ball class to handle the balls on screen
public class Ball
{
double x, y;
double vx, vy;
double oldx, oldy;
public Ball( int x1, int y1 )
{
x = x1; y = y1;
vx = Math.random() * 100 - 50;
vy = Math.random() * 100 - 50;
}
public Ball()
{
x = Math.random() * 400 + 100;
y = Math.random() * 400 + 100;
vx = Math.random() * 100 - 50;
vy = Math.random() * 100 - 50;
}
public double getX() {
return x;
}
public void move( double deltat )
{
oldx = x; oldy = y;
x += vx * deltat;
y += vy * deltat;
stayOnScreen();
}
public void stayOnScreen(){
if (game.getWallStatus()) {
if (x < 55) { vx *= -1; }
if (y < 85) { vy *= -1; }
if ((x > 493) && (x < 507)) { vx *= -1; }
if (x > 945) { vx *= -1; }
if (y > 515) { vy *= -1; }
}
if (!game.getWallStatus()) {
if (x < 55) { vx *= -1; }
if (y < 85) { vy *= -1; }
if (x > 895) { vx *= -1; }
if (y > 515) { vy *= -1; }
}
}
public void drawMe( Graphics g ) { }
}
// FastBall inherits Ball, creates the fast balls
public class FastBall extends Ball {
FastBall() {
super();
}
FastBall(int x, int y) {
super(x, y);
}
public void drawMe ( Graphics g )
{
g.setColor( Color.RED );
g.fillOval( (int)(x-2), (int)(y-2), 5, 5 );
}
}
// SlowBall inherits Ball, creates the slow balls
public class SlowBall extends Ball {
SlowBall() {
super();
}
SlowBall(int x, int y) {
super(x, y);
}
public void drawMe (Graphics g)
{
g.setColor( Color.BLUE );
g.fillOval( (int)(x-2), (int)(y-2), 5, 5 );
}
}
// Moves all the balls
public void moveAll()
{
for (int i=0; i<slowCount; i++ ) {
slow[i].move(2.5*deltat);
fast[i].move(5*deltat);
}
}
// Adds Balls in the center of each room and randomizes direction of travel
public void addBalls()
{
// Creates a fast ball in each room
fast[fastCount++] = new FastBall(250, 300);
fast[fastCount++] = new FastBall(750, 300);
// Creates a slow ball in each room
slow[slowCount++] = new SlowBall(250, 300);
slow[slowCount++] = new SlowBall(750, 300);
}
// computes the temperature of each room
public double[] getTemperatures() {
double leftTemp;
double rightTemp;
double[] temperatures = new double[2];
int slowLeft = 0;
int fastLeft = 0;
int slowRight = 0;
int fastRight = 0;
for (int i = 0; i < fastCount; i++) {
if (fast[i].getX() < 500) { fastLeft++; }
else { fastRight++; }
}
for (int i = 0; i < slowCount; i++) {
if (slow[i].getX() < 500) { slowLeft++; }
else { slowRight++; };
}
leftTemp = 3 * fastLeft + 1 * slowLeft;
rightTemp = 3 * fastRight + 1 * slowRight;
temperatures[0] = leftTemp;
temperatures[1] = rightTemp;
return temperatures;
}
// Updates the two temperature JLabel at the bottom of the view with the appropriate values
public void setTemperatures() {
double[] temperatures = getTemperatures();
leftTemperature.setText(String.valueOf(temperatures[0]) + " °");
rightTemperature.setText(String.valueOf(temperatures[1]) + " °");
}
// Computes the response to the timer and the two buttons at the top of the view
@Override
public void actionPerformed( ActionEvent e )
{
// moves all balls with each click
// To save compute, calculates temperature every 20 clicks
if ( e.getSource()==clicky ) {
moveAll();
if (clicks == 0) { setTemperatures(); }
else if (clicks > 20) { clicks = 0; }
else { clicks++; }
}
else if ( e.getSource()==resetButton ) {
double[] temperatures = getTemperatures();
double temperatureDiff = Math.abs(temperatures[0] - temperatures[1]);
JOptionPane.showMessageDialog(null, "The wall was closed " + wallTimes + " times.\n" + "The final " +
"difference in temperature was " + temperatureDiff,
"Maxwell's Demon Score", JOptionPane.INFORMATION_MESSAGE);
FastBall[] reset_fast = new FastBall[1000];
SlowBall[] reset_slow = new SlowBall[1000];
wallTimes = 0;
fast = reset_fast;
fastCount = 0;
slow = reset_slow;
slowCount = 0;
addBalls();
}
else if ( e.getSource()==addButton ) {
addBalls();
}
game.repaint();
}
// Main function for the Maxwell Class. Creates an instance.
public static void main(String[] args) {
MaxwellDemon test = new MaxwellDemon();
}
} |
package Project4.Group3Solutions_4;
import java.util.HashSet;
public class TotalLength {
/*
Given getTotalLength method
Parameter is one Set of Strings
Return type is an int
Get the total length of each String in the Set
return the total
Example:
Set String is "repl" "is" "homework"
result should be 14
NOTE : IF RESULT IS EQUAL TO 0 THEN CHANGE IT TO -1
*/
public int getTotalLength(HashSet<String> mySet) {
int sum = 0;
for (String str : mySet) {
sum += str.length();
}
/*
ArrayList<String> list = new ArrayList<>(mySet);
int sum=0;
int sum_t = 0;
for (int i = 0; i < list.size(); i++) {
sum_t = list.get(i).length();
sum = sum +sum_t;
}
*/
if (sum == 0) {
return -1;
} else
return sum;
}
}
|
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
public class SampleProducer {
public SampleProducer(){
Properties properties = new Properties();
properties.put("bootstrap.servers", "127.0.0.1:9092");
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
ProducerRecord producerRecord = new ProducerRecord("channel", "name", "Message sent to consumer!");
KafkaProducer kafkaProducer = new KafkaProducer(properties);
kafkaProducer.send(producerRecord);
kafkaProducer.close();
}
}
|
package ok;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
public class JButtonWithData extends JButton {
/**
*
*/
private static final long serialVersionUID = 3618587312341785897L;
private Object[] cycle = new Object[] {true,false};
private String[] cycle_text = new String[] {""};
private int index=0;
private int index_text=0;
private long lastpress = System.currentTimeMillis();
private long timespressed = 0;
private Map<Object,Color> colors = new HashMap<Object,Color>();
private JComponent[] targets = null;
public String[] getCycle_text() {
return cycle_text;
}
public void setCycle_text(String[] cycle_text) {
this.cycle_text = cycle_text;
}
public Object[] getCycle() {
return cycle;
}
public void setCycle(Object[] cycle) {
this.cycle = cycle;
}
public Object getData() {
return cycle[index];
}
public long getLastpress() {
return lastpress;
}
public void setLastpress(long lastpress) {
this.lastpress = lastpress;
}
public JButtonWithData() {
super();
colors.put(true, new Color(32,224,64));
colors.put(false, new Color(196,196,196));
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
index++;
index_text++;
if(index>=cycle.length) {
index = 0;
}
if(index_text>=cycle_text.length) {
index_text = 0;
}
setTimespressed(getTimespressed() + 1);
lastpress = System.currentTimeMillis();
setBackground(colors.get(cycle[index]));
setText(cycle_text[index_text]);
toggleTargets();
}
});
setBackground(colors.get(cycle[index]));
}
public JButtonWithData(String text) {
super(text);
cycle_text= new String[]{text};
colors.put(true, new Color(32,224,64));
colors.put(false, new Color(196,196,196));
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
cycle();
}
});
colors.put(true, new Color(32,224,64));
colors.put(false, new Color(196,196,196));
setBackground(colors.get(cycle[index]));
}
public long getTimespressed() {
return timespressed;
}
public void setTimespressed(long timespressed) {
this.timespressed = timespressed;
}
public Map<Object,Color> getColors() {
return colors;
}
public void setColors(Map<Object,Color> colors) {
this.colors = colors;
}
public void setColor(Object key,Color color) {
colors.put(key, color);
this.setBackground(colors.get(cycle[index]));
}
public void toggleTargets() {
if(targets!=null&&targets.length>0) {
for(JComponent c:targets) {
c.setVisible((index%2==0));
}
}
}
public JComponent[] getTargets() {
return targets;
}
public void setTargets(JComponent[] targets) {
this.targets = targets;
}
public void cycle() {
index++;
index_text++;
if(index>=cycle.length) {
index = 0;
}
if(index_text>=cycle_text.length) {
index_text = 0;
}
setTimespressed(getTimespressed() + 1);
lastpress = System.currentTimeMillis();
setBackground(colors.get(cycle[index]));
setText(cycle_text[index_text]);
toggleTargets();
}
}
|
package com.meizu.scriptkeeper.schedule.monkey;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.annotation.JSONType;
import java.util.ArrayList;
import java.util.List;
/**
* Author: jinghao
* Date: 2015-03-25
*/
@JSONType(orders = {"date", "device", "version", "type", "module", "command", "log", "crash", "serial", "imei"}, asm = false)
public class MonkeyReport {
@JSONField(name = "date")
private String date;
@JSONField(name = "device")
private String device;
@JSONField(name = "version")
private String version;
@JSONField(name = "type")
private String type;
@JSONField(name = "module")
private String module;
@JSONField(name = "command")
private String command;
@JSONField(name = "log")
private String log;
@JSONField(name = "crash")
private List<MonkeyCrash> crash = new ArrayList<MonkeyCrash>();
@JSONField(name = "serial")
private String serial = "";
@JSONField(name = "imei")
private String imei = "";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
public List<MonkeyCrash> getCrash() {
return crash;
}
public void setCrash(List<MonkeyCrash> crash) {
this.crash = crash;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package util;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class WebRequest {
public static String callHttpsSelfSigned(final String url) throws ConnectionException {
Validate.notNull(url, "URL cannot be null");
HttpGet request = new HttpGet(url);
String response = "";
try {
CloseableHttpClient httpClient = getHttpClientTrustedSelfSigned();
HttpResponse httpResponse = httpClient.execute(request);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
throw new ConnectionException(e.getMessage());
}
return response;
}
private static CloseableHttpClient getHttpClientTrustedSelfSigned() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
builder.build());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
sslSocketFactory).build();
return httpClient;
}
}
|
package Problem_2083;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while(true) {
StringTokenizer st = new StringTokenizer(br.readLine());
String name = st.nextToken();
if(name.equals("#")) {
break;
}
sb.append(name).append(" ");
int age = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
if(age > 17 || weight >= 80) sb.append("Senior");
else sb.append("Junior");
sb.append("\n");
}
System.out.print(sb.toString());
}
}
|
package interpreter.exceptions;
public class WrongTypeException extends Throwable {
}
|
package main.java.com.stackroute.pe1;
import java.util.Scanner;
public class Palindrome {
//main class
public static void main(String args[]) {
long number;
Scanner sc = new Scanner(System.in);
number = sc.nextLong();
CheckPalindrome(number);
}
public static void CheckPalindrome(long num) {
//check whether the given number is palindrome or not
long res = num, sum = 0;
while (num > 0) {
long dig = num % 10;
sum = (sum * 10) + dig;
num = num / 10;
}
if (res == sum) {
//sum of even digits
long sum2 = 0;
while (sum > 0) {
long dig = sum % 10;
if (dig % 2 == 0) {
sum2 = sum2 + dig;
}
sum = sum / 10;
}
//check sum is greater than 25 or not
if (sum2 > 25) {
System.out.println(res + " is main.java.com.stackroute.pe1.Palindrome and the sum of even numbers is greater than 25");
} else {
System.out.println(res + " is main.java.com.stackroute.pe1.Palindrome and the sum of even numbers is less than 25");
}
} else {
System.out.println(res + " is not main.java.com.stackroute.pe1.Palindrome");
}
}
}
|
package com.mtl.demo.serviceA.service.impl;
import com.mtl.hulk.annotation.MTLDTActivity;
import com.mtl.hulk.annotation.MTLTwoPhaseAction;
import com.mtl.hulk.context.BusinessActivityContext;
import com.mtl.demo.serviceA.feign.HulkClientB;
import com.mtl.demo.serviceA.feign.HulkClientC;
import com.mtl.demo.serviceA.service.HulkServiceA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@SuppressWarnings("all")
@Component
public class HulkServiceAImpl implements HulkServiceA {
@Autowired
private HulkClientB hulkClientB;
@Autowired
private HulkClientC hulkClientC;
private final static Logger logger = LoggerFactory.getLogger(HulkServiceAImpl.class);
@MTLTwoPhaseAction(confirmMethod = "confirmMysqlSaveAssetCard", cancelMethod = "cancelMysqlSaveAssetCard")
@MTLDTActivity(businessDomain = "mtl", businessActivity = "test", entityId = "a")
@Override
public String getHulkServiceA(int a) {
String hulkServiceB = this.hulkClientB.getHulkServiceB(a, 2222);
String hulkServiceC = this.hulkClientC.getHulkServiceC(a);
if (hulkServiceB != null && hulkServiceC != null) {
return "hulkServiceA........................" + a;
}
return null;
}
public boolean confirmMysqlSaveAssetCard(BusinessActivityContext context) {
logger.info("confirm A params: {}", context.getParams().get("getHulkServiceA"));
return true;
}
public boolean cancelMysqlSaveAssetCard(BusinessActivityContext context) {
logger.info("cancel A params: {}", context.getParams().get("getHulkServiceA"));
return true;
}
}
|
/**
* @author Sayed Ali Mosavi
* @since May 21, 2020
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.util.MathUtil;
import com.sun.jndi.toolkit.ctx.Continuation;
/**
* The Local Regression (LR) VM allocation policy.
*
* If you are using any algorithms, policies or workload included in the power
* package, please cite the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic
* Algorithms and Adaptive Heuristics for Energy and Performance Efficient
* Dynamic Consolidation of Virtual Machines in Cloud Data Centers", Concurrency
* and Computation: Practice and Experience (CCPE), Volume 24, Issue 13, Pages:
* 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 3.0
*/
public class PowerVmAllocationPolicyMigrationHybridLocalRegression extends PowerVmAllocationPolicyMigrationAbstract {
/** The scheduling interval. */
private double schedulingInterval;
/** The safety parameter. */
private double safetyParameter;
/** The fallback vm allocation policy. */
private PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy;
/**
* Instantiates a new power vm allocation policy migration local regression.
*
* @param hostList the host list
* @param vmSelectionPolicy the vm selection policy
* @param schedulingInterval the scheduling interval
* @param fallbackVmAllocationPolicy the fallback vm allocation policy
* @param utilizationThreshold the utilization threshold
*/
public PowerVmAllocationPolicyMigrationHybridLocalRegression(List<? extends Host> hostList,
PowerVmSelectionPolicy vmSelectionPolicy, double safetyParameter, double schedulingInterval,
PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy, double utilizationThreshold) {
super(hostList, vmSelectionPolicy);
setSafetyParameter(safetyParameter);
setSchedulingInterval(schedulingInterval);
setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
}
/**
* Instantiates a new power vm allocation policy migration local regression.
*
* @param hostList the host list
* @param vmSelectionPolicy the vm selection policy
* @param schedulingInterval the scheduling interval
* @param fallbackVmAllocationPolicy the fallback vm allocation policy
*/
public PowerVmAllocationPolicyMigrationHybridLocalRegression(List<? extends Host> hostList,
PowerVmSelectionPolicy vmSelectionPolicy, double safetyParameter, double schedulingInterval,
PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
super(hostList, vmSelectionPolicy);
setSafetyParameter(safetyParameter);
setSchedulingInterval(schedulingInterval);
setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
}
/**
* Checks if is host over utilized.
*
* @param host the host
* @return true, if is host over utilized
*/
@Override
protected boolean isHostOverUtilized(PowerHost host) {
PowerHostUtilizationHistory _host = (PowerHostUtilizationHistory) host;
double[] cpuUtilizationHistory = removeZeros(_host.getUtilizationHistory());
double[] ramUtilizationHistory = removeZeros(_host.getRamUtilizationHistory());
double[] bwUtilizationHistory = removeZeros(_host.getBWUtilizationHistory());
double[] utilizationHistory = new double[cpuUtilizationHistory.length];
for(int i=0;i<cpuUtilizationHistory.length; i++) {
double w1 = getMaxValueOfArray(cpuUtilizationHistory);
double w2 = getMaxValueOfArray(ramUtilizationHistory);
double w3 = getMaxValueOfArray(bwUtilizationHistory);
double volCpu = w1 / 1-cpuUtilizationHistory[i] ;
double volRam = w2 / 1-ramUtilizationHistory[i];
double volBw = w3 / 1-bwUtilizationHistory[i];
utilizationHistory[i] = volCpu * volRam * volBw;
}
int length = 5; // we use 10 to make the regression responsive enough to latest values
if (utilizationHistory.length < length) {
return getFallbackVmAllocationPolicy().isHostOverUtilized(host);
}
double[] utilizationHistoryReversed = new double[length];
for (int i = 0; i < length; i++) {
utilizationHistoryReversed[i] = utilizationHistory[length - i - 1];
}
double[] estimates = null;
try {
estimates = getParameterEstimates(utilizationHistoryReversed);
} catch (IllegalArgumentException e) {
return getFallbackVmAllocationPolicy().isHostOverUtilized(host);
}
double migrationIntervals = Math.ceil(getMaximumVmMigrationTime(_host) / getSchedulingInterval());
double predictedUtilization = estimates[0] + estimates[1] * (length + migrationIntervals);
predictedUtilization *= getSafetyParameter();
addHistoryEntry(host, predictedUtilization);
return predictedUtilization >= 1;
}
/**
* Gets the parameter estimates.
*
* @param utilizationHistoryReversed the utilization history reversed
* @return the parameter estimates
*/
protected double[] getParameterEstimates(double[] utilizationHistoryReversed) {
return MathUtil.getLoessParameterEstimates(utilizationHistoryReversed);
}
/**
* Gets the maximum vm migration time.
*
* @param host the host
* @return the maximum vm migration time
*/
protected double getMaximumVmMigrationTime(PowerHost host) {
int maxRam = Integer.MIN_VALUE;
for (Vm vm : host.getVmList()) {
int ram = vm.getRam();
if (ram > maxRam) {
maxRam = ram;
}
}
return maxRam / ((double) host.getBw() / (2 * 8000));
}
/**
* Sets the scheduling interval.
*
* @param schedulingInterval the new scheduling interval
*/
protected void setSchedulingInterval(double schedulingInterval) {
this.schedulingInterval = schedulingInterval;
}
/**
* Gets the scheduling interval.
*
* @return the scheduling interval
*/
protected double getSchedulingInterval() {
return schedulingInterval;
}
/**
* Sets the fallback vm allocation policy.
*
* @param fallbackVmAllocationPolicy the new fallback vm allocation policy
*/
public void setFallbackVmAllocationPolicy(PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
this.fallbackVmAllocationPolicy = fallbackVmAllocationPolicy;
}
/**
* Gets the fallback vm allocation policy.
*
* @return the fallback vm allocation policy
*/
public PowerVmAllocationPolicyMigrationAbstract getFallbackVmAllocationPolicy() {
return fallbackVmAllocationPolicy;
}
public double getSafetyParameter() {
return safetyParameter;
}
public void setSafetyParameter(double safetyParameter) {
this.safetyParameter = safetyParameter;
}
// Function to print the array by
// removing leading zeros
static double[] removeZeros(double[] array) {
int targetIndex = 0;
for (int sourceIndex = 0; sourceIndex < array.length; sourceIndex++) {
if (array[sourceIndex] != 0.0)
array[targetIndex++] = array[sourceIndex];
}
double[] newArray = new double[targetIndex];
System.arraycopy(array, 0, newArray, 0, targetIndex);
return newArray;
}
static double getMaxValueOfArray(double[] array) {
double max = 0;
for(int i=0; i<array.length; i++ ) {
if(array[i]>max) {
max = array[i];
}
}
return max;
}
static double getMinValueOfArray(double[] array)
{
double min = array[0];
for(int i=0; i<array.length; i++ ) {
if(array[i]<min) {
min = array[i];
}
}
return min;
}
}
|
package com.site.blog.my.core.entity;
import java.util.List;
public class stateWith7dayData {
private String state;
private String country;
private String date;
private List<Integer> sevenDayData;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<Integer> getSevenDayData() {
return sevenDayData;
}
public void setSevenDayData(List<Integer> sevenDayData) {
this.sevenDayData = sevenDayData;
}
}
|
package com.atguigu.lgl;
import java.util.Arrays;
//二分法
public class BinarySearch_Luo {
public static void main(String[] args) {
int[] a = {1,5,3,7,6,8,9,4,2};
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
int findnum = 9;
int start = 0;
int end = a.length-1;
int index = -1;
while (start <= end) {
int mid = (start + end)/2;
if (findnum == a[mid]) {
index = mid;
break;
} else if(findnum > a[mid]) {
start = mid + 1;
}else{
end = mid -1;
}
}
if (index == -1) {
System.out.println("no index = " + index);
} else {
System.out.println("yes,at " + index);
}
}
}
|
package ar.edu.utn.d2s.model.points;
import ar.edu.utn.d2s.model.addres.Address;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.uqbar.geodds.Point;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
public class StoreTest {
private Store store;
@Before
public void setUp() throws Exception {
Address address = mock(Address.class);
when(address.getPoint()).thenReturn(new Point(-34.580691, -58.421132)); // Plaza Italia
Category category = mock(Category.class);
when(category.getCloseRange()).thenReturn(0.9);
store = new Store("Store", "", address, null, category, null);
}
@After
public void tearDown() throws Exception {
}
@Test
public void isCloseTest() throws Exception {
assertTrue(store.isClose(new Point(-34.577246, -58.429091)));
assertFalse(store.isClose(new Point(-34.576460, -58.431999)));
}
} |
package all;
public interface Junkable {
public boolean canJunk();
}
|
/*
* Copyright 2020 Erik Amzallag
*
* 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 org.dajlab.mondialrelayapi.vo;
/**
* Statut du retour du webservice.
*
* @author Erik
*
*/
public enum MRStatut {
STAT0(0, "Opération effectuée avec succès"), STAT80(80, "Code tracing : Colis enregistré"),
STAT81(81, "Code tracing : Colis en traitement chez Mondial Relay"), STAT82(82, "Code tracing : Colis livré"),
STAT83(83, "Code tracing : Anomalie"), STAT94(94, "Colis Inexistant"), STAT95(95, "Compte Enseigne non activé"),
STAT96(96, "Type d'enseigne incorrect en Base"), STAT97(97, "Clé de sécurité invalide"),
STAT98(98, "Erreur générique (Paramètres invalides)"), STAT99(99, "Erreur générique du service");
/**
* Code.
*/
private int code;
/**
* Libellé.
*/
private String libelle;
/**
* Constructeur.
*
* @param code code
* @param libelle libelle
*/
private MRStatut(int code, String libelle) {
this.code = code;
this.libelle = libelle;
}
/**
* Recherche l'enum à partir du code.
*
* @param code code
* @return l'enum, ou null si non trouvé.
*/
public static MRStatut fromCode(int code) {
for (MRStatut codeType : MRStatut.values()) {
if (codeType.getCode() == code) {
return codeType;
}
}
return null;
}
/**
* Recherche l'enum à partir du code.
*
* @param code code
* @return l'enum, ou null si non trouvé.
*/
public static MRStatut fromCode(String code) {
int codeInt = -1;
try {
codeInt = Integer.parseInt(code);
} catch (NumberFormatException e) {
}
for (MRStatut codeType : MRStatut.values()) {
if (codeType.getCode() == codeInt) {
return codeType;
}
}
return null;
}
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @return the libelle
*/
public String getLibelle() {
return libelle;
}
}
|
package com.vivek.sampleapp.activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.vivek.sampleapp.R;
import com.vivek.sampleapp.adapter.MySimpleArrayAdapter;
import com.vivek.sampleapp.adapter.RVAdapter;
import com.vivek.sampleapp.interfaces.ClickListener;
import butterknife.Bind;
import butterknife.ButterKnife;
public class RecyclerViewActivity extends BaseActivity implements ClickListener {
@Bind(R.id.my_recycler_view)
RecyclerView rcview;
@Bind(R.id.RVTextView)
TextView textView;
@Override
public void itemClicked(int position, String type) {
textView.setText("Item clicked is" + position + " and type is " + type);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ButterKnife.bind(this);
RVAdapter adapter= new RVAdapter(this,(ClickListener)this);
StaggeredGridLayoutManager linearLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
rcview.setLayoutManager(linearLayoutManager);
rcview.setAdapter(adapter);
rcview.addOnItemTouchListener(new MySimpleArrayAdapter.RVItemClickListener(this, new MySimpleArrayAdapter.RVItemClickListener.ItemClickListener() {
@Override
public void itemclicked(View v, int position) {
Toast.makeText(getApplicationContext(),"position is " + position,Toast.LENGTH_SHORT).show();
}
}));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
|
package com.other;
import java.util.ArrayList;
import java.util.List;
public class CalConflict {
public static void main(String[] args) {
List<calendarDetails> events = new ArrayList<calendarDetails>();
events.add(new calendarDetails(1, 2, "a"));
events.add(new calendarDetails(2, 4, "b"));
events.add(new calendarDetails(3, 5, "c"));
events.add(new calendarDetails(6, 7, "k"));
events.add(new calendarDetails(9, 13, "e"));
events.add(new calendarDetails(12, 15, "f"));
events.add(new calendarDetails(16, 18, "f"));
List<calendarDetails> conflicts = find_conflicts(events);
for(calendarDetails conflict : conflicts) {
System.out.println("start:"+conflict.start +" end:"+conflict.end +" event name is:"+conflict.details);
}
}
public static List<calendarDetails> find_conflicts(List<calendarDetails> events) {
List<calendarDetails> conflicts = new ArrayList<calendarDetails>();
int openEventEnd = events.get(0).end;
List<calendarDetails> tempConflicts = new ArrayList<calendarDetails>();
tempConflicts.add(events.get(0));
for (int i = 1; i < events.size(); i++) {
if (events.get(i).start >= openEventEnd) {
if (tempConflicts.size() > 1) {
for (calendarDetails tempConflict : tempConflicts) {
conflicts.add(tempConflict);
}
}
tempConflicts = new ArrayList<calendarDetails>();
}
openEventEnd = Math.max(events.get(i).end,openEventEnd);
tempConflicts.add(events.get(i));
}
if (tempConflicts.size() > 1) {
for (calendarDetails tempConflict : tempConflicts) {
conflicts.add(tempConflict);
}
}
return conflicts;
}
}
class calendarDetails{
public calendarDetails(int start, int end, String details) {
super();
this.start = start;
this.end = end;
this.details = details;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
int start;
int end;
String details;
} |
//Fig 2-23
static final int N = 100; // Size of the buffer
static int count = 0; // Number of items in buffer
public class Producer extends Thread { // Producer thread
private Consumer c; // Remember my associated consumer
public void run() {
Item data;
while(true) {
data = produce_item(); // Generate the next item
try{
if(count == N) suspend(); // If the buffer is full, go to
// sleep
} catch(InterruptedException) {};
insert_item(data); // Add the item to the buffer
count++; // Increment count of items in
// buffer
if(count == 1) c.resume(); // Was the buffer empty?
}
...
}
public class Consumer extends Thread { // Consumer thread
private Producer p; // Remember my associated producer
public void run() {
Item data;
while(true) {
try{
if(count == 0) suspend(); // If the buffer is empty, go to
// sleep
} catch(InterruptedException) {};
item = remove_item(); // Get the item from the buffer
count--; // Decrement count of items in
// buffer
if(count == N-1) p.resume(); // Was the buffer full?
consume_item(item); // Do something with the item
}
}
...
}
|
package oo;
import java.util.Scanner;
public class GustavoProva {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("============================\n"
+ "Informe a operação desejada:\n"
+ "(1)Adição\n"
+ "(2)Subtração\n"
+ "(3)Multiplicação\n"
+ "(4)Divisão\n"
+ "(5)Saida\n"
+ "============================");
double opcao = entrada.nextDouble();
/*
* PRIMEIRO IF FORA DO WHILE PARA CASO O USUARIO QUEIRA SAIR SEM FAZER ALGUM CALCULO
*/
if(opcao == 1 || opcao == 2 || opcao == 3 || opcao == 4) { // VERIFICANDO AS OPÇÕES
System.out.print("Informe o primeiro número: ");
double n1 = entrada.nextDouble();
System.out.print("Informe o segundo número: ");
double n2 = entrada.nextDouble();
if(opcao == 1) {
double somar = n1 + n2;
System.out.println("Resultado: " + somar);
}else if(opcao == 2){
double subtrair = n1 - n2;
System.out.println("Resultado: " + subtrair);
}else if(opcao == 3) {
double multiplicar = n1 * n2;
System.out.println("Resultado: " + multiplicar);
}else {
double dividir = n1 / n2;
System.out.println("Resultado: " + dividir);
}
}else {
System.out.println("Programa Finalizado");
}
while(opcao != 5) {
System.out.println("============================\n"
+ "Informe a operação desejada:\n"
+ "(1)Adição\n"
+ "(2)Subtração\n"
+ "(3)Multiplicação\n"
+ "(4)Divisão\n"
+ "(5)Saida\n"
+ "============================");
opcao = entrada.nextInt();
if(opcao == 1 || opcao == 2 || opcao == 3 || opcao == 4) { // VERIFICANDO AS OPÇÕES
System.out.print("Informe o primeiro número: ");
double n1 = entrada.nextDouble();
System.out.print("Informe o segundo número: ");
double n2 = entrada.nextDouble();
if(opcao == 1) {
double somar = n1 + n2;
System.out.println("Resultado: " + somar);
}else if(opcao == 2){
double subtrair = n1 - n2;
System.out.println("Resultado: " + subtrair);
}else if(opcao == 3) {
double multiplicar = n1 * n2;
System.out.println("Resultado: " + multiplicar);
}else {
double dividir = n1 / n2;
System.out.println("Resultado: " + dividir);
}
}else {
System.out.println("Programa Finalizado");
}
}
entrada.close();
}
} |
package com.example.ecommerce;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.example.ecommerce.databinding.ActivityRegisterBinding;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class RegisterActivity extends AppCompatActivity {
ActivityRegisterBinding activityRegisterBinding;
private User user;
private ProgressDialog loadingBar;
private String dbName = "Users";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
loadingBar = new ProgressDialog(this);
user = new User();
activityRegisterBinding.setUser(user);
ClickHandler clickHandler = new ClickHandler(this);
activityRegisterBinding.setClickHandler(clickHandler);
}
public class ClickHandler {
private Context context;
public ClickHandler(Context context) {
this.context = context;
}
public void registerButtonClick(View view) {
createAccount();
}
}
private void createAccount() {
if (user.getName() == null || activityRegisterBinding.getUser().getName().isEmpty()) {
Toast.makeText(this, "Please enter your name....", Toast.LENGTH_SHORT).show();
} else if (user.getPhoneNumber() == null || activityRegisterBinding.getUser().getPhoneNumber().isEmpty()) {
Toast.makeText(this, "Please enter your phone number ....", Toast.LENGTH_SHORT).show();
} else if (user.getPassword() == null || activityRegisterBinding.getUser().getPassword().isEmpty()) {
Toast.makeText(this, "Please enter your password ....", Toast.LENGTH_SHORT).show();
} else if (user.getPhoneNumber().length() < 10) {
Toast.makeText(this, "Please enter your phone number ....", Toast.LENGTH_SHORT).show();
} else {
String name = user.getName();
String password = user.getPassword();
String phoneNumber = user.getPhoneNumber();
loadingBar.setTitle("Creating Account");
loadingBar.setMessage("Your Account is currently being created");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
ValidatePhoneNumber(name, password, phoneNumber);
}
}
private void ValidatePhoneNumber(final String name, final String password, final String phoneNumber) {
final DatabaseReference RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!(dataSnapshot.child("Users").child(phoneNumber).exists())) {
HashMap<String, Object> userdatamap = new HashMap<>();
userdatamap.put("phoneNumber", phoneNumber);
userdatamap.put("password", password);
userdatamap.put("name", name);
userdatamap.put("dbName",dbName);
RootRef.child("Users").child(phoneNumber).updateChildren(userdatamap)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Congratulations, your account has been made", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
} else {
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Network Error: Please Try Again...", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(RegisterActivity.this, "This phone number: " + phoneNumber + " already exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Please try again using another phone number", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
package com.ak.texasholdem.winconditions;
import java.util.ArrayList;
import java.util.List;
import com.ak.texasholdem.cards.Card;
import com.ak.texasholdem.player.Player;
public interface HighCardGetter {
default public List<Card> getHighCard(Player player) {
List<Card> highCardInHand = new ArrayList<>();
highCardInHand.add(player.getCard1());
highCardInHand.add(player.getCard2());
highCardInHand.removeAll(player.getBestCards());
return highCardInHand;
}
}
|
package com.prep.quiz83;
import java.util.Scanner;
//Implement division without using the division operator
public class Drill7 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int result=division(a,b);
System.out.println(result);
}
public static int division(int a,int b){
if(a<b || a<0 || b<0)
return 0;
else{
int count=0;
while(a>=b){
a=a-b;
count++;
}
return count;
}
}
}
|
package io.rong.app.map;
import io.rong.imkit.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.SupportMapFragment;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
public class ChooseLocationActivity extends FragmentActivity implements
View.OnClickListener, LocationSource, AMapLocationListener {
private TextView title_bar_left;
private TextView titleTextView;
private TextView title_bar_right;
private SupportMapFragment chooseLocationFragment;
private LatLng selectPoint;
private OnLocationChangedListener mListener;
private LocationManagerProxy mAMapLocationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_select_location);
title_bar_left = (TextView) findViewById(R.id.title_bar_left);
titleTextView = (TextView) findViewById(R.id.title_bar_center);
title_bar_right = (TextView) findViewById(R.id.title_bar_rigth);
chooseLocationFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.chooseLocationFragment);
titleTextView.setText("选择您的位置");
title_bar_left.setOnClickListener(this);
title_bar_right.setOnClickListener(this);
setupMap();
}
private void setupMap() {
AMap aMap = chooseLocationFragment.getMap();
// 自定义系统定位小蓝点
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory
.fromResource(R.drawable.location_gd));// 设置小蓝点的图标
myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
myLocationStyle.strokeWidth(0.2f);// 设置圆形的边框粗细
aMap.setMyLocationStyle(myLocationStyle);
aMap.setLocationSource(this);// 设置定位监听
aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
aMap.setMyLocationEnabled(true);//
chooseLocationFragment.getMap().setOnMapClickListener(
new AMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latlng) {
// TODO Auto-generated method stub
selectPoint = latlng;
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.title_bar_rigth) {
Intent data = new Intent();
data.putExtra("latlng", selectPoint);
setResult(RESULT_OK, data);
finish();
} else if (v.getId() == R.id.title_bar_left) {
setResult(RESULT_CANCELED);
finish();
}
}
@Override
public void activate(OnLocationChangedListener arg0) {
mListener = arg0;
if (mAMapLocationManager == null) {
mAMapLocationManager = LocationManagerProxy.getInstance(this);
/*
* mAMapLocManager.setGpsEnable(false);
* 1.0.2版本新增方法,设置true表示混合定位中包含gps定位,false表示纯网络定位,默认是true Location
* API定位采用GPS和网络混合定位方式
* ,第一个参数是定位provider,第二个参数时间最短是2000毫秒,第三个参数距离间隔单位是米,第四个参数是定位监听者
*/
mAMapLocationManager.requestLocationData(
LocationProviderProxy.AMapNetwork, 2000, 10, this);
}
}
@Override
public void deactivate() {
// TODO Auto-generated method stub
mListener = null;
if (mAMapLocationManager != null) {
mAMapLocationManager.removeUpdates(this);
mAMapLocationManager.destroy();
}
mAMapLocationManager = null;
}
@Override
public void onLocationChanged(Location aLocation) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(AMapLocation aLocation) {
// TODO Auto-generated method stub
if (mListener != null && aLocation != null) {
mListener.onLocationChanged(aLocation);// 显示系统小蓝点
}
}
}
|
package com.game.cwtetris.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by gena on 12/29/2016.
*/
public class GameDataUndo implements Serializable{
private Set<CellPoint> cells = new HashSet<CellPoint>();
private Set<ShapeData> shapes = new HashSet<>();
public GameDataUndo(Set<CellPoint> cells, Set<ShapeData> shapes) {
this.cells = cells;
this.shapes = shapes;
}
public Set<CellPoint> getCells() {
return cells;
}
public Set<ShapeData> getShapes() {
return shapes;
}
}
|
package main.android.com.popularmoviesapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class MovieDetailsActivity extends AppCompatActivity {
public TextView mTitle, mReleaseDate, mOverview, mFavorite, mMovieVoteAverage;
public ImageView mMoviePic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
mMoviePic = findViewById(R.id.movieDetailPic);
mTitle = findViewById(R.id.title);
mReleaseDate = findViewById(R.id.year);
mOverview = findViewById(R.id.overview);
mFavorite = findViewById(R.id.favorite);
mMovieVoteAverage = findViewById(R.id.vote_average);
Intent intentThatCreatedThisActivity = getIntent();
if (intentThatCreatedThisActivity != null &&
intentThatCreatedThisActivity.hasExtra(getString(R.string.movieTitle)) &&
intentThatCreatedThisActivity.hasExtra(getString(R.string.movieReleaseDate)) &&
intentThatCreatedThisActivity.hasExtra(getString(R.string.movieOverview)) &&
intentThatCreatedThisActivity.hasExtra(getString(R.string.movieFullPosterPath)) &&
intentThatCreatedThisActivity.hasExtra(getString(R.string.movieVoteAverage))) {
String mMovieTitle = intentThatCreatedThisActivity.getStringExtra(getString(R.string.movieTitle));
String mMovieReleaseDate = intentThatCreatedThisActivity.getStringExtra(getString(R.string.movieReleaseDate));
String mMovieOverview = intentThatCreatedThisActivity.getStringExtra(getString(R.string.movieOverview));
String mMovieFullPosterPath = intentThatCreatedThisActivity.getStringExtra(getString(R.string.movieFullPosterPath));
String movieVoteAverage = intentThatCreatedThisActivity.getStringExtra(getString(R.string.movieVoteAverage));
mTitle.setText(mMovieTitle);
mReleaseDate.setText(mMovieReleaseDate);
mOverview.setText(mMovieOverview);
mMovieVoteAverage.setText(movieVoteAverage + getString(R.string.forwardSlashTen));
Picasso.get()
.load(mMovieFullPosterPath)
.fit()
.centerCrop()
.into(mMoviePic);
}
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
/*
* HostMsg.java
*
* Created on Oct 18, 2013, 10:12:33 PM
*/
package pwnbrew.network.control.messages;
import java.io.UnsupportedEncodingException;
import pwnbrew.network.ControlOption;
import pwnbrew.utilities.SocketUtilities;
/**
*
*
*/
public final class HostMsg extends MaltegoMessage{
private static final byte OPTION_HOSTNAME = 60;
private static final byte OPTION_ARCH = 61;
private static final byte OPTION_OS = 62;
private static final byte OPTION_CONNECTED = 63;
private static final byte OPTION_HOST_ID = 64;
private static final byte OPTION_SLEEPABLE = 65;
private static final byte OPTION_RELAY_PORT = 67;
private static final byte OPTION_PID = 68;
public static final short MESSAGE_ID = 0x6d;
// ==========================================================================
/**
* Constructor
*
* @param dstHostId
* @param passeHostname
* @param passedOS
* @param passedArch
* @param passedPid
* @param hostId
* @param isConnected
* @param isSleepable
* @throws java.io.UnsupportedEncodingException
*/
public HostMsg( int dstHostId, String passeHostname, String passedOS,
String passedArch, String passedPid, int hostId, boolean isConnected,
boolean isSleepable ) throws UnsupportedEncodingException {
super( MESSAGE_ID, dstHostId );
//Add file type
byte[] tempBytes = passeHostname.getBytes("US-ASCII");
ControlOption aTlv = new ControlOption( OPTION_HOSTNAME, tempBytes);
addOption(aTlv);
//Add file path
tempBytes = passedArch.getBytes("US-ASCII");
aTlv = new ControlOption( OPTION_ARCH, tempBytes);
addOption(aTlv);
//Add pid
tempBytes = passedPid.getBytes("US-ASCII");
aTlv = new ControlOption( OPTION_PID, tempBytes);
addOption(aTlv);
//Add additional param
tempBytes = passedOS.getBytes("US-ASCII");
aTlv = new ControlOption( OPTION_OS, tempBytes);
addOption(aTlv);
//Add file type
tempBytes = SocketUtilities.intToByteArray(hostId);
aTlv = new ControlOption( OPTION_HOST_ID, tempBytes);
addOption(aTlv);
//Add file type
byte aByte = 0;
if( isConnected )
aByte = 1;
tempBytes = new byte[]{ aByte };
aTlv = new ControlOption( OPTION_CONNECTED, tempBytes);
addOption(aTlv);
//Sleepable flag
aByte = 0;
if( isSleepable )
aByte = 1;
tempBytes = new byte[]{ aByte };
aTlv = new ControlOption( OPTION_SLEEPABLE, tempBytes);
addOption(aTlv);
}
// ==========================================================================
/**
*
* @param parseInt
*/
public void addRelayPort(int parseInt) {
//Add file type
byte[] tempBytes = SocketUtilities.intToByteArray(parseInt);
ControlOption aTlv = new ControlOption( OPTION_RELAY_PORT, tempBytes);
addOption(aTlv);
}
}/* END CLASS HostMsg */
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.support;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link DefaultHandlerExceptionResolver}.
*
* @author Arjen Poutsma
*/
public class DefaultHandlerExceptionResolverTests {
private final DefaultHandlerExceptionResolver exceptionResolver = new DefaultHandlerExceptionResolver();
private final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
private final MockHttpServletResponse response = new MockHttpServletResponse();
@BeforeEach
public void setup() {
exceptionResolver.setWarnLogCategory(exceptionResolver.getClass().getName());
}
@Test
public void handleHttpRequestMethodNotSupported() {
HttpRequestMethodNotSupportedException ex =
new HttpRequestMethodNotSupportedException("GET", Arrays.asList("POST", "PUT"));
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(405);
assertThat(response.getHeader("Allow")).as("Invalid Allow header").isEqualTo("POST, PUT");
}
@Test
public void handleHttpMediaTypeNotSupported() {
HttpMediaTypeNotSupportedException ex = new HttpMediaTypeNotSupportedException(new MediaType("text", "plain"),
Collections.singletonList(new MediaType("application", "pdf")));
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(415);
assertThat(response.getHeader("Accept")).as("Invalid Accept header").isEqualTo("application/pdf");
}
@Test
public void patchHttpMediaTypeNotSupported() {
HttpMediaTypeNotSupportedException ex = new HttpMediaTypeNotSupportedException(
new MediaType("text", "plain"),
Collections.singletonList(new MediaType("application", "pdf")),
HttpMethod.PATCH);
MockHttpServletRequest request = new MockHttpServletRequest("PATCH", "/");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(415);
assertThat(response.getHeader("Accept-Patch")).as("Invalid Accept header").isEqualTo("application/pdf");
}
@Test
public void handleMissingPathVariable() throws NoSuchMethodException {
Method method = getClass().getMethod("handle", String.class);
MethodParameter parameter = new MethodParameter(method, 0);
MissingPathVariableException ex = new MissingPathVariableException("foo", parameter);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500);
assertThat(response.getErrorMessage()).isEqualTo("Required path variable 'foo' is not present.");
}
@Test
public void handleMissingServletRequestParameter() {
MissingServletRequestParameterException ex = new MissingServletRequestParameterException("foo", "bar");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
assertThat(response.getErrorMessage()).isEqualTo("Required parameter 'foo' is not present.");
}
@Test
public void handleServletRequestBindingException() {
String message = "Missing required value - header, cookie, or pathvar";
ServletRequestBindingException ex = new ServletRequestBindingException(message);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
@Test
public void handleTypeMismatch() {
TypeMismatchException ex = new TypeMismatchException("foo", String.class);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
@Test
@SuppressWarnings("deprecation")
public void handleHttpMessageNotReadable() {
HttpMessageNotReadableException ex = new HttpMessageNotReadableException("foo");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
@Test
public void handleHttpMessageNotWritable() {
HttpMessageNotWritableException ex = new HttpMessageNotWritableException("foo");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500);
}
@Test
public void handleMethodArgumentNotValid() throws Exception {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(new TestBean(), "testBean");
errors.rejectValue("name", "invalid");
MethodParameter parameter = new MethodParameter(this.getClass().getMethod("handle", String.class), 0);
MethodArgumentNotValidException ex = new MethodArgumentNotValidException(parameter, errors);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
@Test
public void handleMissingServletRequestPartException() {
MissingServletRequestPartException ex = new MissingServletRequestPartException("name");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
assertThat(response.getErrorMessage()).contains("part");
assertThat(response.getErrorMessage()).contains("name");
assertThat(response.getErrorMessage()).contains("not present");
}
@Test
public void handleBindException() {
BindException ex = new BindException(new Object(), "name");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
@Test
public void handleNoHandlerFoundException() {
ServletServerHttpRequest req = new ServletServerHttpRequest(
new MockHttpServletRequest("GET","/resource"));
NoHandlerFoundException ex = new NoHandlerFoundException(req.getMethod().name(),
req.getServletRequest().getRequestURI(),req.getHeaders());
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(404);
}
@Test
public void handleNoResourceFoundException() {
NoResourceFoundException ex = new NoResourceFoundException(HttpMethod.GET, "/resource");
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(404);
}
@Test
public void handleConversionNotSupportedException() {
ConversionNotSupportedException ex =
new ConversionNotSupportedException(new Object(), String.class, new Exception());
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500);
// SPR-9653
assertThat(request.getAttribute("jakarta.servlet.error.exception")).isSameAs(ex);
}
@Test // SPR-14669
public void handleAsyncRequestTimeoutException() {
Exception ex = new AsyncRequestTimeoutException();
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertThat(mav).as("No ModelAndView returned").isNotNull();
assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
assertThat(response.getStatus()).as("Invalid status code").isEqualTo(503);
}
@Test
public void customModelAndView() {
ModelAndView expected = new ModelAndView();
HandlerExceptionResolver resolver = new DefaultHandlerExceptionResolver() {
@Override
protected ModelAndView handleHttpRequestMethodNotSupported(
HttpRequestMethodNotSupportedException ex, HttpServletRequest request,
HttpServletResponse response, @Nullable Object handler) {
return expected;
}
};
HttpRequestMethodNotSupportedException ex = new HttpRequestMethodNotSupportedException("GET");
ModelAndView actual = resolver.resolveException(request, response, null, ex);
assertThat(actual).isSameAs(expected);
}
@SuppressWarnings("unused")
public void handle(String arg) {
}
}
|
package algdemo;
public class NineNine {
public static void main(String[] args) {
//full();
downThree();
//upThree();
}
public static void full() {
int i = 0;
int j = 0;
for (i = 1; i <= 9; i++) {
for (j = 1; j <= 9; j++)
System.out.print(i + "*" + j + "=" + i * j + "\t");
System.out.println();
}
}
// 不出现重复的乘积(下三角)
public static void downThree() {
int i = 0;
int j = 0;
for (i = 1; i <= 9; i++) {
for (j = 1; j <= i; j++)
System.out.print(i + "*" + j + "=" + i * j + "\t");
System.out.println();
}
}
// 上三角
public static void upThree() {
int i = 0;
int j = 0;
for (i = 1; i <= 9; i++) {
for (j = i; j <= 9; j++)
System.out.print(i + "*" + j + "=" + i * j + "\t");
System.out.println();
}
}
}
|
package edu.neu.ccs.cs5010;
import org.junit.Before;
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.*;
/**
* Created by wenfei on 10/30/17.
*/
public class RSASignatureTest {
private Client client;
private BigInteger[][] keyPair;
private RSAKeyGenerator keyGenerator;
private RandomNumber randomNum;
private RSASignature signature;
@Before
public void setUp() throws Exception {
keyGenerator = new RSAKeyGenerator();
keyPair = keyGenerator.generateKey();
randomNum = new RandomNumber();
signature = new RSASignature();
client = new Client(
102193,
keyPair[RSAKeyGenerator.publicKeyIndex], keyPair[RSAKeyGenerator.privateKeyIndex],
1000,
300
);
}
@Test
public void generateSignature() throws Exception {
int message = 22324;
BigInteger sig = signature.generateSignature(message, client);
int newMessage = signature.verifySignature(sig, client);
assertEquals(message, newMessage);
}
} |
//
// MessagePack for Java
//
// Copyright (C) 2011 Muga Nishizawa
//
// 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 org.msgpack.io;
abstract class AbstractInput implements Input {
private int readByteCount = 0;
public int getReadByteCount() {
return readByteCount;
}
public void resetReadByteCount() {
readByteCount = 0;
}
protected final void incrReadByteCount(int size) {
readByteCount += size;
}
protected final void incrReadOneByteCount() {
readByteCount += 1;
}
}
|
package training;
import java.util.Scanner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.basic.training.JavaBaiscTraning;
public class TestTrainining {
private JavaBaiscTraning jbt = new JavaBaiscTraning();
@Before
public void before() {
System.out.println("测试开始");
}
@After
public void after() {
System.out.println("测试结束");
}
@Test
public void testInsertSort() {
int[] arr = { 5, 1, 6, 23, 4, 8, 6, 7 };
int[] newArr = jbt.insertSort(arr);
for (int i : newArr) {
System.out.print(i + " ");
}
}
@Test
public void testBubbleSort() {
int[] arr = { 5, 1, 6, 23, 4, 8, 6, 7 };
int[] newArr = jbt.bubbleSort(arr);
for (int i : newArr) {
System.out.print(i + " ");
}
}
@Test
public void testStringCompareToStringBuilder() {
jbt.stringCompareToStringBuilder();
}
@Test
@SuppressWarnings("resource")
public void testTransFormSum() {
Scanner sc = new Scanner(System.in);
while (true) {
String sum = sc.nextLine();
if (sum.equals("end")) {
break;
} else {
System.out.println(jbt.transformSum(sum));
}
}
}
}
|
/**
*/
package Metamodell.model.metamodell.tests;
import Metamodell.model.metamodell.MetamodellFactory;
import Metamodell.model.metamodell.Motor;
import junit.textui.TestRunner;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Motor</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class MotorTest extends PeripheralTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(MotorTest.class);
}
/**
* Constructs a new Motor test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MotorTest(String name) {
super(name);
}
/**
* Returns the fixture for this Motor test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private Motor getFixture() {
return (Motor)fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
protected void setUp() throws Exception {
setFixture(MetamodellFactory.eINSTANCE.createMotor());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
protected void tearDown() throws Exception {
setFixture(null);
}
} //MotorTest
|
package com.next.odata4.config;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ODataServiceConfig
{
@Autowired
ApplicationContext appContext;
}
|
package pers.mine.scratchpad.poi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class WordReplaceTest {
WordReplace wordReplace = null;
@Before
public void init() throws FileNotFoundException, IOException {
File file = new File("D:\\Mine\\Desktop\\test.docx");
FileInputStream fileInputStream = new FileInputStream(file);
wordReplace = new WordReplace(fileInputStream);
wordReplace.setKitFlag(true);
}
@After
public void write() throws IOException, WordReplaceException {
File outFile = new File(
"D:\\Mine\\Desktop\\test_out.docx");
OutputStream os = new FileOutputStream(outFile);
wordReplace.write(os);
os.close();
}
@Test
public void wrTest4() throws WordReplaceException{
WordParameterSet parameter = new WordParameterSet();
parameter.addOptionParameter("A1", false);
parameter.addOptionParameter("A2", false);
parameter.addOptionParameter("A3", false);
parameter.addOptionParameter("A4", false);
parameter.addOptionParameter("A5", false);
parameter.addOptionParameter("A6", false);
parameter.addOptionParameter("A11", false);
parameter.addOptionParameter("A12", false);
parameter.addOptionParameter("A13", false);
parameter.addOptionParameter("A14", false);
parameter.addOptionParameter("A15", false);
parameter.addOptionParameter("A16", false);
wordReplace.replace(parameter);
}
@Test
public void wrTest3() throws WordReplaceException{
WordParameterSet parameter = new WordParameterSet();
parameter.addOptionParameter("AF-PRE-PF-PAGE", true);
parameter.addStringParameter("AF-PRE-PF-No-A", "附件10086");
parameter.addStringParameter("基础信息-合同名称", "测试合同名称");
parameter.addStringParameter("融资主体提前到期-行权期", "测试合同名称");
parameter.addStringParameter("基础信息-合同编号", "测试合同编号");
parameter.addOptionParameter("A10086", true);
wordReplace.replace(parameter);
}
}
|
package model;
import javafx.scene.paint.Color;
public class Grain {
private int state, nextState, id, newId;
private Color color, newColor;
public Grain() {
state = nextState = 0;
id = newId = -1;
newColor = Color.WHITE;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getNextState() {
return nextState;
}
public void setNextState(int nextState) {
this.nextState = nextState;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNewId() {
return newId;
}
public void setNewId(int newId) {
this.newId = newId;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Color getNewColor() {
return newColor;
}
public void setNewColor(Color newColor) {
this.newColor = newColor;
}
}
|
/**
* @author lxm
* @create_date 2019.5.3
* @description 答案类
* */
package com.code.model;
public class Answer {
private Integer answerId;
private Integer simproblemId;
private Integer pos;
private String content;
public Integer getAnswerId() {
return answerId;
}
public void setAnswerId(Integer answerId) {
this.answerId = answerId;
}
public Integer getSimproblemId() {
return simproblemId;
}
public void setSimproblemId(Integer simproblemId) {
this.simproblemId = simproblemId;
}
public Integer getPos() {
return pos;
}
public void setPos(Integer pos) {
this.pos = pos;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
} |
package sr.hakrinbank.intranet.api.controller;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sr.hakrinbank.intranet.api.dto.BusinessAccountTypeDto;
import sr.hakrinbank.intranet.api.dto.ResponseDto;
import sr.hakrinbank.intranet.api.model.BusinessAccountType;
import sr.hakrinbank.intranet.api.service.BusinessAccountTypeService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.util.ArrayList;
import java.util.List;
/**
* Created by clint on 6/5/17.
*/
@RestController
@RequestMapping(value = "/api/businessaccounttype")
public class BusinessAccountTypeController {
@Autowired
private BusinessAccountTypeService businessAccountTypeService;
@Autowired
private ModelMapper modelMapper;
//-------------------Retrieve All BusinessAccountTypes--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listAllBusinessAccountTypes() {
List<BusinessAccountType> businessAccountTypes = businessAccountTypeService.findAllActiveBusinessAccountTypes();
if(businessAccountTypes.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT);
}
List<BusinessAccountTypeDto> businessAccountTypesDtoList = new ArrayList<>();
ModelMapper modelMapper = new ModelMapper();
for(BusinessAccountType businessAccountType: businessAccountTypes){
businessAccountTypesDtoList.add(modelMapper.map(businessAccountType, BusinessAccountTypeDto.class));
}
return new ResponseEntity<ResponseDto>(new ResponseDto(businessAccountTypesDtoList, null), HttpStatus.OK);
}
//-------------------Retrieve All BusinessAccountTypes By Search--------------------------------------------------------
@RequestMapping(value = "search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listBusinessAccountTypesBySearchQuery(@RequestParam String qry) {
List<BusinessAccountType> businessAccountTypes = businessAccountTypeService.findAllActiveBusinessAccountTypesBySearchQuery(qry);
if(businessAccountTypes.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT);
}
List<BusinessAccountTypeDto> businessAccountTypesDtoList = new ArrayList<>();
ModelMapper modelMapper = new ModelMapper();
for(BusinessAccountType businessAccountType: businessAccountTypes){
businessAccountTypesDtoList.add(modelMapper.map(businessAccountType, BusinessAccountTypeDto.class));
}
return new ResponseEntity<ResponseDto>(new ResponseDto(businessAccountTypesDtoList, businessAccountTypesDtoList.size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK);
}
//-------------------Retrieve All BusinessAccountTypes With Pagination--------------------------------------------------------
// @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// public ResponseEntity<Page<BusinessAccountType>> listAllBusinessAccountTypes(Pageable pageable) {
// Page<BusinessAccountType> businessAccountTypes = businessAccountTypeService.findAllBusinessAccountTypesByPage(pageable);
// return new ResponseEntity<Page<BusinessAccountType>>(businessAccountTypes, HttpStatus.OK);
// }
//-------------------Retrieve Single BusinessAccountType--------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BusinessAccountType> getBusinessAccountType(@PathVariable("id") long id) {
System.out.println("Fetching BusinessAccountType with id " + id);
BusinessAccountType businessAccountType = businessAccountTypeService.findById(id);
if (businessAccountType == null) {
System.out.println("BusinessAccountType with id " + id + " not found");
return new ResponseEntity<BusinessAccountType>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<BusinessAccountType>(businessAccountType, HttpStatus.OK);
}
//-------------------Create a BusinessAccountType--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> createBusinessAccountType(@RequestBody BusinessAccountTypeDto businessAccountTypeDto) {
System.out.println("Creating BusinessAccountType with name " + businessAccountTypeDto.getName());
if (businessAccountTypeDto.getId() != null) {
System.out.println("A BusinessAccountType with id " + businessAccountTypeDto.getId() + " already exist");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "A BusinessAccountType with id " + businessAccountTypeDto.getId() + " already exist"), HttpStatus.CONFLICT);
}
businessAccountTypeService.updateBusinessAccountType(modelMapper.map(businessAccountTypeDto, BusinessAccountType.class));
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_SAVED), HttpStatus.CREATED);
}
//------------------- Update a BusinessAccountType --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> updateBusinessAccountType(@PathVariable("id") long id, @RequestBody BusinessAccountType businessAccountType) {
System.out.println("Updating BusinessAccountType " + id);
BusinessAccountType currentBusinessAccountType = businessAccountTypeService.findById(id);
if (currentBusinessAccountType==null) {
System.out.println("BusinessAccountType with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "BusinessAccountType with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
businessAccountTypeService.updateBusinessAccountType(businessAccountType);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_UPDATED), HttpStatus.OK);
}
//------------------- Delete a BusinessAccountType --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseDto> deleteBusinessAccountType(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting BusinessAccountType with id " + id);
BusinessAccountType businessAccountType = businessAccountTypeService.findById(id);
if (businessAccountType == null) {
System.out.println("Unable to delete. BusinessAccountType with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "Unable to delete. BusinessAccountType with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
businessAccountType.setDeleted(true);
businessAccountTypeService.updateBusinessAccountType(businessAccountType);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_DELETED), HttpStatus.OK);
}
//------------------- Delete All BusinessAccountTypes --------------------------------------------------------
// @RequestMapping(value = "", method = RequestMethod.DELETE)
// public ResponseEntity<BusinessAccountType> deleteAllBusinessAccountTypes() {
// System.out.println("Deleting All BusinessAccountTypes");
//
// BusinessAccountTypeservice.deleteAllBusinessAccountTypes();
// return new ResponseEntity<BusinessAccountType>(HttpStatus.NO_CONTENT);
// }
}
|
/**
*
*/
package com.justin.fitbit.scribe_oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.github.scribejava.apis.FitbitApi20;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.justin.fitbit.config.AppConfig;
import com.justin.fitbit.config.IPropsPersistance;
/**
*/
@Component
@ConfigurationProperties("call-fitbit-api")
public class CallFitbitAPI
{
static final FitbitApi20 FITBIT_SERVICE = FitbitApi20.instance();
@Autowired
private AppConfig appConfig;
@Autowired
private IPropsPersistance propsPersistance;
private String fitbitAuthUrl;
// Full list here: https://dev.fitbit.com/build/reference/web-api/oauth2/#scope
private String fitbitScope;
public String getFitbitAuthUrl() {
return fitbitAuthUrl;
}
public void setFitbitAuthUrl(String fitbitAuthUrl) {
this.fitbitAuthUrl = fitbitAuthUrl;
}
public String getFitbitScope() {
return fitbitScope;
}
public void setFitbitScope(String fitbitScope) {
this.fitbitScope = fitbitScope;
}
/**
*/
public OAuth20Service buildService() throws Exception
{
OAuth20Service service = new ServiceBuilder(appConfig.getClientId())
.apiSecret(appConfig.getClientSecret())
.scope(fitbitScope)
.callback(appConfig.getCallbackURL())
.build(FITBIT_SERVICE);
return service;
}
/**
* Example CURL
*
* curl -X GET \
* https://api.fitbit.com/1/user/3BZ2KZ/profile.json \
* -H 'authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzQloyS1oiLCJhdWQiOiIyMkNWNlAiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJ3aHIgd3BybyB3YWN0IiwiZXhwIjoxNTIyMjYxMjAxLCJpYXQiOjE1MjIyMzI0MDF9.SAXMRF-5hrSR8TLExmWx06qYa-UGFPVpEr4_fLsQxuw'
*
* Other examples:
* - https://api.fitbit.com/1/user/3BZ2KZ/activities/date/2018-03-26.json
*/
public void runRequest(
OAuth20Service service,
String accessToken,
String requestUrl) throws Exception
{
String fullURL = fitbitAuthUrl + propsPersistance.loadCurrentUserId() + "/" + requestUrl;
final OAuthRequest request = new OAuthRequest(Verb.GET, fullURL);
service.signRequest(accessToken, request); // the access token from step 4
final Response response = service.execute(request);
prettyPrintJson(response.getBody());
}
/**
*/
private static final void prettyPrintJson(String jsonStr) throws Exception
{
org.json.JSONObject jsonObject = new org.json.JSONObject(jsonStr);
System.out.println(jsonObject.toString(4));
}
}
|
package br.com.tn.cap14;
public class Ex04 {
public static void main(String[] args) {
Integer x1;
String s1 = "10";
String s2 = "abc";
System.out.println("ParseInt s1");
x1 = Integer.parseInt(s1);
// System.out.println("ParseInt s2");
// x1 = Integer.parseInt(s2);
// Não Roda, pois estamos passando letras
}
}
|
package tests;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import java.io.IOException;
import java.net.URL;
public class BaseTest {
@BeforeMethod
@Parameters({"deviceName", "platformVersion"})
public void setup (String deviceName, String platformVersion) throws IOException {
String pathToApp = System.getProperty("user.dir") + "/kumparan.apk";
System.out.println(pathToApp);
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", deviceName);
caps.setCapability("platformVersion", platformVersion);
caps.setCapability("platformName", "Android");
caps.setCapability("automationName", "UiAutomator2");
caps.setCapability("app", pathToApp);
caps.setCapability("noReset","false");
ThreadLocalDriver.setDriver(new AndroidDriver (new URL("http://0.0.0.0:4723/wd/hub"),caps));
}
@AfterMethod
public synchronized void teardown(){
ThreadLocalDriver.getDriver().quit();
}
}
|
package testo.pl.giphyapitest;
/**
* Created by Lukasz Marczak on 2015-08-08.
*
*/
public class Item {
public String capital;
public String text;
public String Pokemon;
public Item(String _capital, String _text) {
capital = _capital;
text = _text;
}
}
|
package com.example.mav_mr_fpv_osu_2020.old.utils;
import com.example.vfsmav_osu20_fpv.mavdata.MAVRepo;
import com.google.gson.Gson;
public class MAVUtils {
private final static String MAV_CONNECT = "http://192.192.192.192/";
static class MAVTelemetryResults {
MAVRepo item;
}
public static MAVRepo parseMAVTelemetryResults(String json) {
Gson gson = new Gson();
MAVTelemetryResults results = gson.fromJson(json, MAVTelemetryResults.class);
if (results != null && results.item != null) {
return results.item;
} else {
return null;
}
}
public static String getMAVTelemetryURL() {
return MAV_CONNECT;
}
}
|
package DAO;
import java.util.ArrayList;
import models.Professor;
import models.Serializar;
public class ProfessorDAO implements DAO<Professor>{
private ArrayList<Professor> lista = Serializar.load("listaProfessores.ser");
public boolean update(Professor object, Professor newObject) {
if(object.copy(newObject)){
Serializar.serializar("listaProfessores.ser", lista);
return true;
}
return false;
}
//search teacher by Name
@Override
public Professor search(String name) {
for(Professor i : lista) {
if (i.getNome().equals(name)) {
return i;
}
}
//if don't match...
return null;
}
public ArrayList<Professor> getLista() {
return lista;
}
@Override
public boolean add(Professor object) {
if(lista.add(object)){
Serializar.serializar("listaProfessores.ser", lista);
return true;
}
return false;
}
@Override
public boolean remove(Professor object) {
if(lista.remove(object)){
Serializar.serializar("listaProfessores.ser", lista);
return true;
}
return false;
}
}
|
package algorithms.fundamentals.sub3_collection.exercises.linkedlist;
import algorithms.fundamentals.sub3_collection.exercises.linkedlist.LinkedListOperations;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Chen Li on 2017/4/26.
*/
public class LinkedListOperationsTest {
@Test
public void deleteLastNodeFromFirstInEmptyQueue() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
intQueue.deleteLastNodeFromFirst();
assertTrue("delete last node from first node from an empty queue, size==0", intQueue.size() == 0);
}
@Test
public void deleteLastNodeFromFirst() throws Exception {
for (int i = 1; i < 10; i++) {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
List<Integer> ints = new ArrayList<>();
for (int j = 0; j < i; j++) {
ints.add(j);
intQueue.enqueue(j);
}
intQueue.deleteLastNodeFromFirst();
assertEquals(intQueue.size(), i - 1);
int k = 0;
for (Integer integer : intQueue) {
Integer value = ints.get(k++);
assertEquals(value, integer);
}
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void deleteAtIndexWhenEmpty() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
intQueue.deleteNodeAtIndex(0);
}
@Test
public void deleteAtIndexStart() {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
intQueue.enqueue(1);
intQueue.deleteNodeAtIndex(0);
assertTrue(intQueue.size() == 0);
}
@Test
public void deleteAtIndexStartWith2Nodes() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
intQueue.enqueue(1);
intQueue.enqueue(2);
intQueue.deleteNodeAtIndex(0);
assertTrue(intQueue.size() == 1);
assertEquals(2, (int) intQueue.dequeue());
}
@Test
public void deleteAtIndexEndWith2Nodes() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
intQueue.enqueue(1);
intQueue.enqueue(2);
intQueue.deleteNodeAtIndex(1);
assertTrue(intQueue.size() == 1);
assertEquals(1, (int) intQueue.dequeue());
}
@Test
public void testFindMax() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
for (int i = 0; i < 100; i++) {
intQueue.enqueue(100 - i);
}
assertEquals(100, intQueue.findMax().intValue());
}
@Test
public void testRecursivelyFindMax() throws Exception {
LinkedListOperations<Integer> intQueue = new LinkedListOperations();
for (int i = 0; i < 100; i++) {
intQueue.enqueue(100 - i);
}
intQueue.enqueue(101);
assertEquals(101, intQueue.recursivelyFindMax().intValue());
}
} |
package com.doohong.shoesfit.relation.service;
import com.doohong.shoesfit.relation.RelationRepository;
import com.doohong.shoesfit.relation.domain.Relation;
import com.doohong.shoesfit.shoes.domain.Shoes;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RelationSaveService {
private final RelationRepository relationRepository;
public List<Relation> relationSave(List<Shoes> shoesList){
List<Relation> relationList = new ArrayList<>();
for(Shoes shoes1 : shoesList){
for(Shoes shoes2 : shoesList){
if(shoes1.getIndex()<shoes2.getIndex()){
Relation relation = relationRepository.findByShoes1AndShoes2(shoes1,shoes2);
if(relation!=null){
relation.addCount();
}
else{
relation = new Relation(shoes1,shoes2);
}
relationList.add(relationRepository.save(relation));
}
}
}
return relationList;
}
}
|
package com.metoo.core.loader;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.metoo.core.security.SecurityManager;
import com.metoo.core.tools.SpringUtil;
/**
*
* <p>Title: ServletContextLoaderListener.java</p>
* <p>Description:系统基础信息加载监听器,目前用来加载系统权限数据,也可以将系统语言包在这里加载进来,该监听器会在系统系统的时候进行一次数据加载
* 1)WEB容器监听器ServletContextListener主要用来监听容器启动和销毁的时候需要做一些操作,就可以使用这个监听器来做。
* ServletContextListener在Spring启动前启动。
2)ServletContextListener 接口有两个方法:contextInitialized,contextDestroyed。
a. 在服务器加载web应用的时候,这个Listener将被调用。
b. spring在contextInitialized中进行spring容器的初始化。
生命周期监听器
* </p>
* <p>Copyright: Copyright (c) 2014</p>
* <p>Company: </p>
* @author
* @date 2014-4-24
* @version koala_b2b2c v2.0 2015版
*/
public class ServletContextLoaderListener implements ServletContextListener {
/**
*
* 当Servlet 容器启动Web应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化,
* 并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。
*/
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
//获取系统权限
SecurityManager securityManager = this
.getSecurityManager(servletContext);
Map<String, String> urlAuthorities = securityManager
.loadUrlAuthorities();
servletContext.setAttribute("urlAuthorities", urlAuthorities);
SpringUtil.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(servletContext));
}
/**
* 当Servlet 容器终止Web应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。
*/
public void contextDestroyed(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().removeAttribute(
"urlAuthorities");
}
/**
* @description 获取加载权限的bean
* @param servletContext
* @return
*/
protected SecurityManager getSecurityManager(ServletContext servletContext) {
return (SecurityManager) WebApplicationContextUtils
.getWebApplicationContext(servletContext).getBean(
"securityManager");
}
}
|
package ru.job4j.calculator;
/**
* Class Calculator выполняет простейщие математические операции:
* сложение, вычитание, умножение и деление.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 0.1
*/
public class Calculator {
/**
* Хранит результат вычислительной операции.
*/
private double result;
/**
* Производит операцию сложения над двумя числами.
* @param first первое слагаемое.
* @param second второе слагаемое.
*/
public void add(double first, double second) {
this.result = first + second;
}
/**
* Производит операцию вычитания над двумя числами.
* @param first уменьшаемое.
* @param second вычитаемое.
*/
public void substruct(double first, double second) {
this.result = first - second;
}
/**
* Производит операцию умножения над двумя числами.
* @param first первый множитель.
* @param second второй множитель.
*/
public void multiple(double first, double second) {
this.result = first * second;
}
/**
* Производит операцию деления над двумя числами.
* @param first делимое.
* @param second делитель.
*/
public void div(double first, double second) {
this.result = first / second;
}
/**
* Возвращает результат вычислительной операции.
* @return результат.
*/
public double getResult() {
return this.result;
}
}
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Caculators extends JFrame implements ActionListener{
// JButton array
JButton[] jbt = new JButton[15];
JTextField jtf = new JTextField();
public Caculators(){
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(5,3));
// add 1~9 to the button
for(int i = 0;i < 9;i++){
p1.add(jbt[i] = new JButton(""+(i+1)));
}
// add the others to the button
p1.add(jbt[9] = new JButton(""+0));
p1.add(jbt[10] = new JButton("+"));
p1.add(jbt[11] = new JButton("-"));
p1.add(jbt[12] = new JButton("x"));
p1.add(jbt[13] = new JButton("/"));
p1.add(jbt[14] = new JButton("="));
for(int i =0;i < 15; i++){
jbt[i].addActionListener(this);
}
JPanel p2 = new JPanel(new BorderLayout());
p2.add(jtf,BorderLayout.NORTH);
p2.add(p1,BorderLayout.CENTER);
add(p2);
}
// event
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbt[0])
jtf.setText("1");
if(e.getSource() == jbt[1])
jtf.setText("2");
if(e.getSource() == jbt[2])
jtf.setText("3");
if(e.getSource() == jbt[3])
jtf.setText("4");
if(e.getSource() == jbt[4])
jtf.setText("5");
if(e.getSource() == jbt[5])
jtf.setText("6");
if(e.getSource() == jbt[6])
jtf.setText("7");
if(e.getSource() == jbt[7])
jtf.setText("8");
if(e.getSource() == jbt[8])
jtf.setText("9");
if(e.getSource() == jbt[9])
jtf.setText("0");
}
//set frame
public static void main(String[] args) {
// TODO Auto-generated method stub
Caculators frame = new Caculators();
frame.setSize(300,450);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
package br.com.salon.carine.lima.models;
import javax.persistence.Entity;
import br.com.salon.carine.lima.enuns.BandeiraCartao;
@Entity
public class Debito extends Pagamento {
private static final long serialVersionUID = 1L;
private BandeiraCartao bandeiraCartao;
public Debito() {
}
public Debito(BandeiraCartao bandeiraCartao) {
this.bandeiraCartao = bandeiraCartao;
}
public BandeiraCartao getBandeiraCartao() {
return bandeiraCartao;
}
public void setBandeiraCartao(BandeiraCartao bandeira) {
this.bandeiraCartao = bandeira;
}
}
|
package com.fly;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class TestTreeSet {
public static void main(String[] args) {
long p = ChronoUnit.DAYS.between(LocalDate.of(2019, 11, 14), LocalDate.of(2021, 4, 9));
System.out.println("两天之间的差在天数 : " + p);
Map<String, String> map = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
// Map<String, String> map = new TreeMap<>();
// Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.put("a", "111");
map.put("b", "222");
map.put("c", "333");
map.put("T", "444");
for (Map.Entry<String, String> kv: map.entrySet()) {
System.out.println(kv.getKey() + " : " + kv.getValue());
}
}
}
|
package com.github.reubuisnessgame.gamebank.stockexchangeservice.form;
public class NewNewsForm {
private Long companyId;
private double changingPrice;
private String heading;
private String article;
public NewNewsForm(Long companyId, double changingPrice, String heading, String article) {
this.companyId = companyId;
this.changingPrice = changingPrice;
this.heading = heading;
this.article = article;
}
public Long getCompanyId() {
return companyId;
}
public double getChangingPrice() {
return changingPrice;
}
public String getHeading() {
return heading;
}
public String getArticle() {
return article;
}
}
|
package com.siss.web.bean;
import com.icesoft.faces.component.ext.RowSelectorEvent;
import com.siss.dto.amb.ActividadEconomica;
import com.siss.dto.amb.PtoDescarga;
import com.siss.dto.riles.ReporteCumplimiento;
import com.siss.dto.riles.ReporteParametro;
import com.siss.entity.amb.CronogramaAE;
import com.siss.exception.EntityException;
import com.siss.web.resource.WebConstants;
import com.siss.web.FacesUtil;
import com.siss.web.MensajesBean;
import com.siss.web.Util;
import com.siss.web.delegate.amb.ActividadEconomicaDelegate;
import com.siss.web.model.HitoIcemodel;
import com.siss.web.model.ModeloExcel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* @author hmoya
*
* Bean encargado de manipular el cronograma de una empresa específica, mostrando información detallada de las
* plantas asociadas a la empresa. Lo principal es la generación de cronogramas de trabajo, en la que los fiscalizadores pueden establecer
* pautas que ellos mismos deben seguir, estos cronogramas son especificos de una fecha de término, cuando llega esta
* fecha, el cronograma pasa a ser un historial, el cual no puede ser modificado o eliminado.
*/
public class CronogramaBean {
public static final String REPORTE_CRONOGRAMA = "REPORTE_CRONOGRAMA";
/**
* Establece la visibilidad de la pantalla emergente.
*/
private boolean visible = false;
/**
* Identificador de la empresa seleccionada.
*/
private Integer empresaId = null;
/**
* Identificador de la actividad económica seleccionada.
*/
private Integer actividadEconomicaId = null;
/**
* Detalle de la empresa seleccionada.
*/
private ActividadEconomica empresa = null;
/**
* Fecha de vencimiento para crear o modificar un cronograma.
*/
private Date fechaVencimiento = null;
/**
* Descripción del hito para acciones como crear o modificar.
*/
private String hito = null;
/**
* Identificador del hito a modificar o eliminar.
*/
private Integer idHito;
/**
* Boolean que establece el modo de edición de la data de un cronograma.
*/
private boolean editar = false;
/**
* Boolean que establece la actualización de los datos del cronograma.
*/
private boolean cambiar = false;
/**
* Lista con el modelo que representa la data de un cronograma asociado a una empresa.
*/
private List<HitoIcemodel> listaCronograma = new ArrayList<HitoIcemodel>();
/**
* Nombre de la columna antigua para la que se desea ordenar la lista.
*/
private String oldSort = "";
/**
* Tipo de ordenamiento anterior.
*/
private boolean oldAscending = false;
/**
* Nombre de la columna por la cual se va a ordenar la lista.
*/
private String sortColumnName = "";
/**
* Boolean con el tipo de oredenamiento indicando si es ascendente o descendente.
*/
private boolean ascending;
/**
* Instancia al bean de mensajes.
*/
private MensajesBean mensajes;
/**
* contexto web de la aplicación.
*/
private FacesContext facesContext;
/**
* Representa la región donde se está ejecutando la aplicación y permite cambier el idioma.
*/
private Locale aLocale;
private String reporteExcelCronograma = "";
/**
* Constructor de la clase.
* Aca, se inicializan el contexto web, el idioma y el bean de mensajes.
*/
public CronogramaBean() {
facesContext = FacesContext.getCurrentInstance();
aLocale = facesContext.getExternalContext().getRequestLocale();
if (mensajes == null) {
mensajes = (MensajesBean) FacesUtil.getManagedBeanExpression(facesContext, WebConstants.BEAN_MENSAJES, MensajesBean.class);
}
iniciaParam();
}
/**
* Método que resetea los valores de los controles que permiten la creación o modificación de un cronograma.
* El calendario es seteado a un día posterior a la fecha actual, y la descripción del hito es seteada a vacío.
*/
private void iniciaParam() {
Calendar calendar = Calendar.getInstance(aLocale);
calendar.add(Calendar.DAY_OF_MONTH, 1);
fechaVencimiento = calendar.getTime();
hito = "";
}
/**
* Método encargado de realizar la carga de los datos de la empresa seleccionada, junto con hacer visibler la
* ventana de cronogramas de la empresa.
* @param actionEvent Método generado al presionar el link del cronograma especifico de una empresa.
* @see ActionEvent
*/
public void openPopup(ActionEvent actionEvent) {
try {
UIComponent componenteOrigen = actionEvent.getComponent();
this.empresaId = Integer.parseInt(String.valueOf(componenteOrigen.getAttributes().get("paramEmpresaId")));
this.actividadEconomicaId = Integer.parseInt(String.valueOf(componenteOrigen.getAttributes().get("paramActividadEconomicaId")));
if (empresaId != null & actividadEconomicaId != null) {
empresa = ActividadEconomicaDelegate.getInstance().getEIndustrialInformacion(empresaId, actividadEconomicaId);
ActividadEconomica empresaRca = ActividadEconomicaDelegate.getInstance().getEIndustrialRca(empresaId, actividadEconomicaId);
if (empresa != null) {
String noDefinido = Util.getString(facesContext, "NoDefinido");
if (empresaRca != null) {
if (empresaRca.getRca() != null) {
empresa.setRca(empresaRca.getRca());
} else {
empresa.setRca(noDefinido);
}
if (empresaRca.getFechaRca() != null) {
empresa.setFechaRca(empresaRca.getFechaRca());
} else {
empresa.setFechaRca(noDefinido);
}
} else {
empresa.setRca(noDefinido);
empresa.setFechaRca(noDefinido);
}
cargarCronogramas(empresaId, actividadEconomicaId);
visible = true;
}
}
} catch (EntityException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_WARN);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.WARNING, Util.getText(ex));
} catch (EJBException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_FATAL);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, Util.getText(ex));
} catch (Exception ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
Util.mostrarError(ex);
}
}
/**
* Obtiene la lista con los cronogramas asociados a la empresa.
* @param rut Identificador de la empresa.
* @param actEconomicaId Identificador de la planta o actividad económica.
* @see CronogramaAE
* @see InvocarEjb#getCronogramaAEByRutByActividadEconomica(long, long)
*/
private void cargarCronogramas(long rut, long actEconomicaId) throws Exception {
try {
List<CronogramaAE> listaCrono = ActividadEconomicaDelegate.getInstance().getCronogramaAEByRutByActividadEconomica(rut, actEconomicaId);
listaCronograma = new ArrayList<HitoIcemodel>();
if (listaCrono != null && !listaCrono.isEmpty()) {
int contador = 0;
for (CronogramaAE crma : listaCrono) {
HitoIcemodel hitoModel = new HitoIcemodel(crma);
hitoModel.setIndice(contador++);
listaCronograma.add(hitoModel.getIndice(), hitoModel);
}
sort();
getReporteExcelCronograma();
}
} catch (EntityException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_WARN);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.WARNING, Util.getText(ex));
} catch (EJBException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_FATAL);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, Util.getText(ex));
} catch (Exception ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
Util.mostrarError(ex);
}
}
public void setReporteExcelCronograma(String reporteExcelCronograma) {
this.reporteExcelCronograma = reporteExcelCronograma;
}
public String getReporteExcelCronograma() {
ModeloExcel modeloExcel = new ModeloExcel();
try {
if (!getListaCronograma().isEmpty()) {
modeloExcel.setTitulo(CronogramaBean.REPORTE_CRONOGRAMA);
modeloExcel.setFecha("");
modeloExcel.setIndustrias(new ArrayList<PtoDescarga>());
modeloExcel.setReporteCumplimiento(new ArrayList<ReporteCumplimiento>());
modeloExcel.setReporteParametro(new ArrayList<ReporteParametro>());
modeloExcel.setPeriodoInicial("");
modeloExcel.setPeriodoFinal("");
modeloExcel.setIndustria(getEmpresa().getEmpresa());
modeloExcel.setPlanta(getEmpresa().getActividadEconomica());
modeloExcel.setRegion(getEmpresa().getRegion());
modeloExcel.setComuna(getEmpresa().getComuna());
modeloExcel.setRca(getEmpresa().getRca());
modeloExcel.setFechaRca(getEmpresa().getFechaRca());
modeloExcel.setNorma(getEmpresa().getNorma());
modeloExcel.setFechaNorma(getEmpresa().getFechaResolucion());
modeloExcel.setReporteCronograma(getListaCronograma());
}
ExportarExcelBean exportarExcelBean = (ExportarExcelBean)FacesUtil.getManagedBeanExpression(FacesContext.getCurrentInstance(), "#{exportarExcelBean}", ExportarExcelBean.class);
if (exportarExcelBean != null) {
exportarExcelBean.setModeloExcel(modeloExcel);
}
} catch (Exception ex) {
Logger.getLogger(ExportarExcelBean.class.getName()).log(Level.SEVERE, null, ex);
}
return "";
}
/**
* Método de ordenamiento de una lista, el ordenamiento se produce dado un nombre de campo FechaVencimiento,
* y un boolean indicando si es ascendente o descendente.
* @see HitoIcemodel
* @see Comparator
* @see Collections#sort(java.util.List, java.util.Comparator)
*/
protected void sort() {
Comparator comparator = new Comparator() {
public int compare(Object o1, Object o2) {
String fechaVencimiento = Util.getString(facesContext, "FechaVencimiento");
HitoIcemodel c1 = (HitoIcemodel) o1;
HitoIcemodel c2 = (HitoIcemodel) o2;
if (sortColumnName.equals(fechaVencimiento)) {
return ascending ? c1.getFechaTermino().compareTo(c2.getFechaTermino()) : c2.getFechaTermino().compareTo(c1.getFechaTermino());
} else {
return ascending ? c1.getFechaTermino().compareTo(c2.getFechaTermino()) : c2.getFechaTermino().compareTo(c1.getFechaTermino());
}
}
};
Collections.sort(this.listaCronograma, comparator);
List<HitoIcemodel> lista = new ArrayList<HitoIcemodel>();
Iterator<HitoIcemodel> it = this.listaCronograma.iterator();
int contador = 0;
while (it.hasNext()) {
HitoIcemodel hitoModel = it.next();
hitoModel.setIndice(contador++);
lista.add(hitoModel.getIndice(), hitoModel);
}
this.listaCronograma = lista;
}
/**
* Método encagado de establecer la data de un cronograma en los componentes encargados de realizar la modificación.
* @param actionEvent Acción al hacer click en el botón modificar de un cronograma.
*/
public void editarCronograma(ActionEvent actionEvent) {
try {
UIComponent componenteOrigen = actionEvent.getComponent();
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
HitoIcemodel modelo = (HitoIcemodel) componenteOrigen.getAttributes().get("paramHito");
if (modelo != null) {
if (modelo.isEnabled()) {
if (modelo.isSelected()) {
setFechaVencimiento(formato.parse(modelo.getFechaTermino()));
setHito(modelo.getDescripcion());
setIdHito(modelo.getId());
setEditar(false);
setCambiar(true);
}
}
}
} catch (ParseException ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Metodo que establece el cronograma seleccionado a modo de edición.
* @param event Evento ocurre cuando hace click en una fila de la tabla.
*/
public void rowSelectionListenerCronograma(RowSelectorEvent event) {
if (event.isSelected()) {
iniciaParam();
setEditar(true);
setCambiar(false);
} else {
iniciaParam();
setEditar(false);
setCambiar(false);
}
}
/**
* Método encargado de realizar la actualización de la data del cronograma que se desea modificar.
* @param actionEvent Evento de botón asociado a la acción de modificar.
*/
public void updateCronograma(ActionEvent actionEvent) {
try {
if (cambiar) {
if (validarHito()) {
ActividadEconomicaDelegate.getInstance().updateCronogramaAE(idHito, empresaId, actividadEconomicaId, hito, fechaVencimiento);
Util.mostrarMensaje(Util.getString(facesContext, "MensajeActualiza"));
iniciaParam();
cargarCronogramas(empresaId, actividadEconomicaId);
setEditar(false);
setCambiar(false);
getReporteExcelCronograma();
}
}
} catch (EntityException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_WARN);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.WARNING, Util.getText(ex));
} catch (EJBException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_FATAL);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, Util.getText(ex));
} catch (Exception ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
Util.mostrarError(ex);
}
}
/**
* Método encargado de agregar un cronograma a una empresa específica.
* @param actionEvent Evento de botón asociado al agregar cronograma.
*/
public void agregarHito(ActionEvent actionEvent) {
try {
if (validarHito()) {
ActividadEconomicaDelegate.getInstance().createCronogramaAE(empresaId, actividadEconomicaId, hito, fechaVencimiento);
cargarCronogramas(empresaId, actividadEconomicaId);
iniciaParam();
Util.mostrarMensaje(Util.getString(facesContext, "MensajeInserta"));
getReporteExcelCronograma();
}
} catch (EntityException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_WARN);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.WARNING, Util.getText(ex));
} catch (EJBException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_FATAL);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, Util.getText(ex));
} catch (Exception ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
Util.mostrarError(ex);
}
}
/**
* Método encargado de eliminar un cronograma a una empresa específica.
* @param actionEvent Evento de botón asociado al eliminar cronograma.
*/
public void eliminarHito(ActionEvent actionEvent) {
try {
UIComponent componenteOrigen = actionEvent.getComponent();
HitoIcemodel selectedHito = (HitoIcemodel) componenteOrigen.getAttributes().get("paramHito");
if (selectedHito != null) {
ActividadEconomicaDelegate.getInstance().deleteCronogramaAE(selectedHito.getId(), selectedHito.getRut(), selectedHito.getActividadEconomicaId());
cargarCronogramas(selectedHito.getRut(), selectedHito.getActividadEconomicaId());
Util.mostrarMensaje(Util.getString(facesContext, "MensajeElimina"));
getReporteExcelCronograma();
}
} catch (EntityException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_WARN);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.WARNING, Util.getText(ex));
} catch (EJBException ex) {
String msjDialog = Util.getString(FacesContext.getCurrentInstance(), "ErrorInternoAplicacion") + "<br>" +
Util.getString(FacesContext.getCurrentInstance(), "ErrorPeristente");
Util.errorExeption(msjDialog, "Error", FacesMessage.SEVERITY_FATAL);
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, Util.getText(ex));
} catch (Exception ex) {
Logger.getLogger(CronogramaBean.class.getName()).log(Level.SEVERE, null, ex);
Util.mostrarError(ex);
}
}
/**
* Método encargado de validar la data de un cronograma antes de asociarlo a una empresa.
* @return verdadero si se asoció correctamente, Falso, si no se asoció.
*/
public boolean validarHito() {
boolean resp = true;
if (fechaVencimiento == null || Calendar.getInstance().getTime().after(fechaVencimiento)) {
Util.mostrarMensaje(Util.getString(facesContext, "HitoFechaPosteriorActual"));
resp = false;
}
if (hito == null || hito.isEmpty()) {
Util.mostrarMensaje(Util.getString(facesContext, "HitoNoDescripcion"));
resp = false;
}
return resp;
}
/**
* Método encargado de cerrar la ventana de cronogramas de la empresa.
*/
public void closePopup() {
visible = false;
this.editar = false;
this.cambiar = false;
this.iniciaParam();
}
/**
* Método capaz de cancelar la modificación de la data de un cronograma.
* @param actionEvent Evento de botón asociado a cacelar modificar.
*/
public void cancelarUpdateCronograma(ActionEvent actionEvent) {
this.editar = false;
this.cambiar = false;
this.iniciaParam();
}
/**
* Obtiene la visibilidad de la pantalla emergente de cronograma.
* @return Boolean visibilidad de la pantalla emergente de cronograma.
*/
public boolean isVisible() {
return visible;
}
/**
* Setea la visibilidad de la pantalla emergente de cronograma.
* @param visible Boolean visibilidad de la pantalla emergente de cronograma.
*/
public void setVisible(boolean visible) {
this.visible = visible;
}
/**
* Obtiene el identificador de la actividad económica seleccionada.
* @return El identificador de la actividad económica seleccionada.
*/
public Integer getActividadEconomicaId() {
return actividadEconomicaId;
}
/**
* Setea el identificador de la actividad económica seleccionada.
* @param actividadEconomicaId Identificador de la actividad económica seleccionada.
*/
public void setActividadEconomicaId(Integer actividadEconomicaId) {
this.actividadEconomicaId = actividadEconomicaId;
}
/**
* Obtiene el detalle de la empresa seleccionada.
* @return Detalle de la empresa seleccionada.
* @see ActividadEconomica
*/
public ActividadEconomica getEmpresa() {
return empresa;
}
/**
* Setea el detalle de la empresa seleccionada.
* @param empresa Detalle de la empresa seleccionada.
* @see ActividadEconomica
*/
public void setEmpresa(ActividadEconomica empresa) {
this.empresa = empresa;
}
/**
* Obtiene el identificador de la empresa.(rut de la empresa)
* @return Identificador de la empresa.
*/
public Integer getEmpresaId() {
return empresaId;
}
/**
* Setea el identificador de la empresa.(rut de la empresa)
* @param empresaId Identificador de la empresa.
*/
public void setEmpresaId(Integer empresaId) {
this.empresaId = empresaId;
}
/**
* Obtiene la fecha de vencimiento de un nuevo cronograma.
* @return Fecha de vencimiento de un nuevo cronograma.
* @see Date
*/
public Date getFechaVencimiento() {
return fechaVencimiento;
}
/**
* Setea la fecha de vencimiento de un nuevo cronograma.
* @param fechaVencimiento Fecha de vencimiento de un nuevo cronograma.
* @see Date
*/
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
/**
* Obtiene la descripción de un cronograma que se va a insertar o modificar.
* @return Descripción de un cronograma.
*/
public String getHito() {
return hito;
}
/**
* Setea la descripción de un cronograma que se va a insertar o modificar.
* @param hito Descripción de un cronograma.
*/
public void setHito(String hito) {
this.hito = hito;
}
/**
* Retorna la lista con los cronogramas asociados a la empresa.
* @return Lista con los cronogramas asociados a la empresa.
*/
public List<HitoIcemodel> getListaCronograma() {
if (!oldSort.equals(sortColumnName) || oldAscending != ascending) {
sort();
oldSort = sortColumnName;
oldAscending = ascending;
}
return listaCronograma;
}
/**
* Setea la lista con los cronogramas asociados a la empresa.
* @param listaCronograma Lista con los cronogramas asociados a la empresa.
*/
public void setListaCronograma(List<HitoIcemodel> listaCronograma) {
this.listaCronograma = listaCronograma;
}
/**
* Obtiene el tipo de ordenamiento.
* @return boolean con el tipo de ordenamiento.
*/
public boolean isAscending() {
return ascending;
}
/**
* Establece el tipode ordenamiento.
* @param ascending tipo de ordenamiento, true si es ascendente, false si es descendente.
*/
public void setAscending(boolean ascending) {
this.ascending = ascending;
}
/**
* Obtiene el nombre de la columna por la cual se va a ordenar la lista.
* @return String con el nombre de la columna por la cual se va a ordenar la lista.
*/
public String getSortColumnName() {
return sortColumnName;
}
/**
* Establece el nombre de la columna por la cual se va a ordenar la lista.
* @param sortColumnName Nombre de la columna por la cual se va a ordenar la lista.
*/
public void setSortColumnName(String sortColumnName) {
this.sortColumnName = sortColumnName;
}
/**
* Retorna el identificador del cronograma que se va a eliminar o modificar.
* @return Identificador del cronograma que se va a eliminar o modificar.
*/
public Integer getIdHito() {
return idHito;
}
/**
* Establece el identificador del cronograma que se va a eliminar o modificar.
* @param idHito Identificador del cronograma que se va a eliminar o modificar.
*/
public void setIdHito(Integer idHito) {
this.idHito = idHito;
}
/**
* Retorna el indicador de modo de edición.
* @return boolean con el indicador de modo de edición.
*/
public boolean isEditar() {
return editar;
}
/**
* Establece el modo de edición
* @param editar Boolean que establece el modo de edición.
*/
public void setEditar(boolean editar) {
this.editar = editar;
}
/**
* Obtiene la zona horaria por defecto.
* @return Zona horaria por defecto.
*/
public TimeZone getTimeZone() {
return java.util.TimeZone.getDefault();
}
/**
* Retorna el indicador de actualización.
* @return Boolean con el indicador de actualización.
*/
public boolean isCambiar() {
return cambiar;
}
/**
* Establece el indicador de actualización.
* @param cambiar Boolean con el indicador de actualización.
*/
public void setCambiar(boolean cambiar) {
this.cambiar = cambiar;
}
} |
package com.github.yangxy81118.loghunter.service.delegator;
import com.github.yangxy81118.loghunter.core.support.ExceptionThrow;
import com.github.yangxy81118.loghunter.distribute.bean.ActionConstraints;
import com.github.yangxy81118.loghunter.distribute.bean.LogConfigAction;
import com.github.yangxy81118.loghunter.distribute.bean.LoggerApplication;
import com.github.yangxy81118.loghunter.service.LoggerAppContainer;
/**
* 客户端应用注册处理类
*
* @author yangxy8
*
*/
public class RegisterService implements ServerEndPointService {
@Override
public LogConfigAction execute(LogConfigAction clientAction) {
LoggerApplication application = clientAction.getLoggerApplication();
ExceptionThrow.argumentNull(application, "LoggerApplication");
LoggerAppContainer.addApplication(application);
clientAction.setResponseCode(ActionConstraints.RESPONSE_OK);
return clientAction;
}
}
|
package Problem_11508;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static Integer[] sorted;
public static void merge(Integer a[], int m, int middle, int n) {
int i = m;
int j = middle + 1;
int k = m;
while (i <= middle && j <= n) {
if (a[i] >= a[j]) {
sorted[k] = a[i++];
} else {
sorted[k] = a[j++];
}
k++;
}
if (i > middle) {
for (int t = j; t <= n; t++, k++) {
sorted[k] = a[t];
}
} else{
for (int t = i; t <= middle; t++, k++) {
sorted[k] = a[t];
}
}
for (int t = m; t <= n; t++) {
a[t] = sorted[t];
}
}
static void mergeSort(Integer a[], int m, int n) {
int middle;
if (m < n) {
middle = (m + n) / 2;
mergeSort(a, m, middle);
mergeSort(a, middle + 1, n);
merge(a, m, middle, n);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[N];
sorted = new Integer[N];
long sum = 0;
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
mergeSort(arr, 0, N - 1);
for (int i = 0; i < N; i++) {
if ((i + 1) % 3 == 0)
continue;
sum += arr[i];
}
System.out.println(sum);
}
}
|
package br.mg.puc.sica.notificacao.service;
import br.mg.puc.sica.notificacao.model.Mensagem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(Mensagem mensagem) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo(mensagem.getDestinatarios().toArray(new String[mensagem.getDestinatarios().size()]));
mail.setSubject(mensagem.getAssunto());
mail.setText(mensagem.getCorpo());
javaMailSender.send(mail);
}
}
|
package com.example.andrew.colorpicker.EyeChallenge;
import com.example.andrew.colorpicker.framework.Screen;
import com.example.andrew.colorpicker.framework.impl.AndroidGame;
public class EyeChallengeGame extends AndroidGame {
public Screen getStartScreen() {
return new LoadingScreen(this);
}
}
|
package com.appfountain.component;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.appfountain.R;
import com.appfountain.model.App;
import com.appfountain.util.Common;
public class QuestionAppAdapter extends ArrayAdapter<App> {
private static final String TAG = QuestionAppAdapter.class.getSimpleName();
private List<App> apps;
private int resource;
private Context context;
private ImageLoader imageLoader;
public QuestionAppAdapter(Context context, int resource, List<App> apps,
ImageLoader imageLoader) {
super(context, resource);
this.apps = apps;
this.resource = resource;
this.imageLoader = imageLoader;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final QuestionAppItemHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resource, parent, false);
holder = new QuestionAppItemHolder();
holder.name = (TextView) view
.findViewById(R.id.list_item_question_app_name);
holder.icon = (NetworkImageView) view
.findViewById(R.id.list_item_question_app_network_image_view);
view.setTag(holder);
} else {
holder = (QuestionAppItemHolder) view.getTag();
}
final App app = apps.get(position);
holder.name.setText(app.getName());
holder.icon.setImageUrl(getImageResourceURL(app), imageLoader);
return view;
}
private String getImageResourceURL(App app) {
return Common.getIconBaseUrl(context) + app.getPackageName() + ".png";
}
@Override
public int getCount() {
return apps.size();
}
static class QuestionAppItemHolder {
NetworkImageView icon;
TextView name;
}
}
|
package com.zd.christopher.bean;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import com.zd.christopher.cipher.MD5CipherMaker;
public class User extends Entity
{
private static final long serialVersionUID = 1L;
private static final String USER_ENTITY_PATH = ENTITY_PATH + "/user";
private Integer id;
private String userId;
private transient String pwd;
private String userName;
private String encryptedPwd;
private String avatar;
private Date birthday;
private String gender;
private String email;
private String phone;
private String fax;
private String address;
private String zipCode;
private String country;
private String nationality;
private String idCard;
private Set<Course> favorCourse = new HashSet<Course>();
private Administrator administrator;
private Set<Document> favorDocument = new HashSet<Document>();
private Set<Document> authorDocument = new HashSet<Document>();
private Set<Video> favorVideo = new HashSet<Video>();
private Set<Video> authorVideo = new HashSet<Video>();
private Faculty faculty;
private Student student;
public User()
{
}
public User(Integer id)
{
this.id = id;
}
public User(String userId)
{
this.userId = userId;
}
public User(String userId, String pwd)
{
this.userId = userId;
this.pwd = pwd;
setDefaultUserName();
setDefaultEmail();
calculateEncryptedPwd();
}
public User(String userId, String pwd, String avatar,
Date birthday, String gender, String email, String phone,
String fax, String address, String zipCode, String country,
String nationality, String idCard)
{
this.userId = userId;
this.pwd = pwd;
this.avatar = avatar;
this.birthday = birthday;
this.gender = gender;
this.email = email;
this.phone = phone;
this.fax = fax;
this.address = address;
this.zipCode = zipCode;
this.country = country;
this.nationality = nationality;
this.idCard = idCard;
setDefaultUserName();
setDefaultEmail();
calculateEncryptedPwd();
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getUserId()
{
return userId;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getAvatar()
{
return avatar;
}
public void setAvatar(String avatar)
{
this.avatar = avatar;
}
public Faculty getFaculty()
{
return faculty;
}
public void setFaculty(Faculty faculty)
{
this.faculty = faculty;
}
public Student getStudent()
{
return student;
}
public void setStudent(Student student)
{
this.student = student;
}
public String getPwd()
{
return pwd;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
calculateEncryptedPwd();
}
public String getEncryptedPwd()
{
return encryptedPwd;
}
public void setEncryptedPwd(String encryptedPwd)
{
this.encryptedPwd = encryptedPwd;
}
public Date getBirthday()
{
return birthday;
}
public String getGender()
{
return gender;
}
public String getEmail()
{
return email;
}
public String getPhone()
{
return phone;
}
public String getFax()
{
return fax;
}
public String getAddress()
{
return address;
}
public String getZipCode()
{
return zipCode;
}
public String getCountry()
{
return country;
}
public String getNationality()
{
return nationality;
}
public String getIdCard()
{
return idCard;
}
public void setBirthday(Date birthday)
{
this.birthday = birthday;
}
public void setGender(String gender)
{
this.gender = gender;
}
public void setEmail(String email)
{
this.email = email;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public void setFax(String fax)
{
this.fax = fax;
}
public void setAddress(String address)
{
this.address = address;
}
public void setZipCode(String zipCode)
{
this.zipCode = zipCode;
}
public void setCountry(String country)
{
this.country = country;
}
public void setNationality(String nationality)
{
this.nationality = nationality;
}
public void setIdCard(String idCard)
{
this.idCard = idCard;
}
public Set<Course> getFavorCourse()
{
return favorCourse;
}
public void setFavorCourse(Set<Course> favorCourse)
{
this.favorCourse = favorCourse;
}
public Set<Video> getFavorVideo()
{
return favorVideo;
}
public void setFavorVideo(Set<Video> favorVideo)
{
this.favorVideo = favorVideo;
}
public Set<Video> getAuthorVideo()
{
return authorVideo;
}
public void setAuthorVideo(Set<Video> authorVideo)
{
this.authorVideo = authorVideo;
}
public Administrator getAdministrator()
{
return administrator;
}
public void setAdministrator(Administrator administrator)
{
this.administrator = administrator;
}
public Set<Document> getFavorDocument()
{
return favorDocument;
}
public void setFavorDocument(Set<Document> favorDocument)
{
this.favorDocument = favorDocument;
}
public Set<Document> getAuthorDocument()
{
return authorDocument;
}
public void setAuthorDocument(Set<Document> authorDocument)
{
this.authorDocument = authorDocument;
}
private boolean calculateEncryptedPwd()
{
if(pwd == null)
return false;
this.encryptedPwd = MD5CipherMaker.cipher(pwd);
return true;
}
private boolean setDefaultUserName()
{
if(userId == null)
return false;
userName = userId;
return true;
}
private boolean setDefaultEmail()
{
if(userId == null)
return false;
email = userId;
return true;
}
public String findPath()
{
if(id == null)
return null;
return USER_ENTITY_PATH + "user" + getUserId();
}
public static User toJson(User user)
{
User tempUser = null;
try
{
tempUser = (User) user.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
User jsonUser = user;
jsonUser.faculty = new Faculty();
jsonUser.student = new Student();
jsonUser.administrator = new Administrator();
jsonUser.favorCourse = new HashSet<Course>();
jsonUser.favorDocument = new HashSet<Document>();
jsonUser.favorVideo = new HashSet<Video>();
jsonUser.authorDocument = new HashSet<Document>();
jsonUser.authorVideo = new HashSet<Video>();
if(tempUser.getFaculty() != null)
jsonUser.faculty.setId(tempUser.getFaculty().getId());
if(tempUser.getStudent() != null)
jsonUser.student.setId(tempUser.getStudent().getId());
if(tempUser.getAdministrator() != null)
jsonUser.administrator.setId(tempUser.getAdministrator().getId());
for(Course favorCourse : tempUser.getFavorCourse())
{
Course course = new Course(favorCourse.getId());
jsonUser.favorCourse.add(course);
}
for(Document favorDocument : tempUser.getFavorDocument())
{
Document document = new Document(favorDocument.getId());
jsonUser.favorDocument.add(document);
}
for(Video favorVideo : tempUser.getFavorVideo())
{
Video video = new Video(favorVideo.getId());
jsonUser.favorVideo.add(video);
}
for(Document authorDocument : tempUser.getAuthorDocument())
{
Document document = new Document(authorDocument.getId());
jsonUser.authorDocument.add(document);
}
for(Video authorVideo : tempUser.getAuthorVideo())
{
Video video = new Video(authorVideo.getId());
jsonUser.authorVideo.add(video);
}
return jsonUser;
}
}
|
package com.codingchili.social.controller;
import com.codingchili.common.Strings;
import com.codingchili.social.configuration.SocialContext;
import com.codingchili.social.model.*;
import com.codingchili.core.listener.CoreHandler;
import com.codingchili.core.listener.Request;
import com.codingchili.core.protocol.*;
import static com.codingchili.core.protocol.RoleMap.PUBLIC;
/**
* @author Robin Duda
* <p>
* Online handler called by realms on connect/disconnect.
* <p>
* Note: if a player logs in to a single realm multiple times, then disconnects once
* the online status will be offline. Should realms prevent this? probably.
*/
@Roles(PUBLIC)
@Address(Strings.ONLINE_SOCIAL_NODE)
public class OnlineHandler implements CoreHandler {
private Protocol<Request> protocol = new Protocol<>(this);
private OnlineDB online;
private AsyncFriendStore friends;
private SocialContext context;
/**
* @param context the context to run the handler on.
*/
public OnlineHandler(SocialContext context) {
this.context = context;
this.online = context.online();
this.friends = context.friends();
}
@Api
public void social_online(SocialRequest request) {
online.add(request.target(), request.realm());
notifyAllFriends(new FriendOnlineEvent(request, true));
}
@Api
public void social_offline(SocialRequest request) {
if (online.is(request.target())) {
notifyAllFriends(new FriendOnlineEvent(request, false));
// leave current parties
context.party().leave(request.target());
}
online.remove(request.target(), request.realm());
}
private void notifyAllFriends(FriendOnlineEvent event) {
friends.list(event.getFriend()).setHandler(list -> {
list.result().getFriends().forEach(friend -> {
if (online.is(friend)) {
context.send(friend, event.setTarget(friend));
}
});
});
}
@Override
public void handle(Request request) {
protocol.process(new SocialRequest(request));
}
}
|
package com.jgw.supercodeplatform.trace.enums;
/**
* 功能类型
*
* @author wzq
* @date: 2019-03-28
*/
public enum RegulationTypeEnum {
ProcedureNode(1,"过程节点"),
ControlNode(2,"控制节点"),
SingleForm(3,"单一表单");
private final int key;
private final String value;
private RegulationTypeEnum(int key,String value){
this.key=key;
this.value=value;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
}
|
package br.com.salon.carine.lima.validations;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import br.com.salon.carine.lima.dto.PasswordDTO;
public class PasswordConfirmValidator implements
ConstraintValidator<PasswordConfirmInsertValidator, PasswordDTO> {
@Override
public boolean isValid(PasswordDTO password, ConstraintValidatorContext context) {
if(password.getSenha().equals(password.getConfirmacaoSenha())) {
return true;
}
return false;
}
}
|
package com.asiainfo.worktime.converter;
import org.springframework.beans.BeanUtils;
import com.asiainfo.worktime.entity.ProcEntity;
import com.asiainfo.worktime.model.ProcModel;
public class ProcConverter {
public static ProcEntity getEntity(ProcModel model) {
ProcEntity entity = new ProcEntity();
BeanUtils.copyProperties(model, entity);
return entity;
}
public static ProcModel getModel(ProcEntity entity) {
ProcModel model = new ProcModel();
BeanUtils.copyProperties(entity, model);
BeanUtils.copyProperties(entity.getTbRpocType(), model.getTbRpocType());
return model;
}
}
|
package gov.nih.mipav.view.renderer.WildMagic.Poisson.CmdLine;
import gov.nih.mipav.view.renderer.WildMagic.Poisson.Geometry.*;
public class cmdLinePoint3D extends cmdLineReadable {
public Point3D value = new Point3D();
public cmdLinePoint3D(){
value.coords[0]=value.coords[1]=value.coords[2]=0;
}
public cmdLinePoint3D(Point3D v){
value.coords[0]=v.coords[0];value.coords[1]=v.coords[1];value.coords[2]=v.coords[2];
}
public cmdLinePoint3D(float v0, float v1, float v2){
value.coords[0]=v0;value.coords[1]=v1;value.coords[2]=v2;
}
public int read(String[] argv,int argc){
if(argc>2){
value.coords[0]= Float.valueOf(argv[0]);
value.coords[1]= Float.valueOf(argv[1]);
value.coords[2]= Float.valueOf(argv[2]);
set=1;
return 3;
}
else{return 0;}
}
} |
/**
* This package houses some of the pojos that are being used internally by this library.
*/
package com.rationaleemotions.pojo;
|
import java.util.Objects;
public class Balagan {
public String open, name;
public Balagan(String open, String name) {
this.open=open;
this.name=name;
}
public String open() {
return open;
}
public String getName() {
return name;
}
public void openFull() {
if (open()=="Закрыт") {
System.out.print(getName() + " скоро откроется ");
} else {
System.out.println(getName() + open());
}
}
@Override
public String toString() {
return "Balagan{" +
"open='" + open + '\'' +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Balagan balagan = (Balagan) o;
return Objects.equals(open, balagan.open) &&
Objects.equals(name, balagan.name);
}
@Override
public int hashCode() {
return Objects.hash(open, name);
}
}
|
package com.logic;
import com.entity.entities.User;
public interface UserService {
User getUser(String email);
User createUser(User user);
User createUser(User newUser, String adminUsername);
}
|
package Keywords;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import AdditionalSetup.ResultUpdation;
import AdditionalSetup.Objects;
import Common.Information;
public class GoToUrl implements Information{
WebDriver driver;
Objects obj;
boolean cond=false;
public GoToUrl(WebDriver driver,ExtentTest test) throws Exception{
this.driver=driver;
obj = new Objects(driver, test);
}
public String testing(Properties p,String[] record,int row, String sh, int resultRow,String[] imp) throws Exception{
try {
driver.get(p.getProperty(record[OBJECTNAME]));
String title_name=driver.getTitle();
String actual="Problem loading page";
if (title_name != null && (title_name.startsWith("http://") || title_name.startsWith("https://"))) {
if(title_name.equals(actual.trim())){
cond= false;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.FAIL,imp);
obj.getExtentTest().log(LogStatus.FAIL, record[STEPNUMBER],"URL is not running. Please run again"); // for failure purpose
return Information.FAIL;
}
else{
cond= true;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.PASS,imp);
obj.getExtentTest().log(LogStatus.PASS, record[STEPNUMBER],"Description: "+record[DESCRIPTION]+"<html><br></html> Output: "+record[EXPECTED_COLUMN]); // for pass purpose
return Information.PASS;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
ResultUpdation noe=new ResultUpdation(obj);
noe.testing(p, record, row, sh, resultRow, Information.FAIL+": Driver is failed to run '"+p.getProperty(record[OBJECTNAME])
+"' because of "+e.getClass().getSimpleName(),imp);
return FAIL;
}
return FAIL;
}
public String urlVerify(Properties p,String[] record,int row, String sh, int resultRow,String[] imp) throws Exception{
try {
driver.get(p.getProperty(record[OBJECTNAME]));
String title_name=driver.getCurrentUrl();
VALUE_STORAGE.put(record[OBJECTNAME]+VALUE_END, title_name);
if(title_name.equals(record[VALUE])){
cond= true;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.FAIL,imp);
obj.getExtentTest().log(LogStatus.PASS, record[STEPNUMBER], record[DESCRIPTION]);
return Information.PASS;
}
else{
cond= false;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.FAIL,imp);
obj.getExtentTest().log(LogStatus.FAIL, record[STEPNUMBER],"Description: "+ "Current URL verification is failed"); // for pass purpose
return Information.FAIL;
}
} catch (Exception e) {
// TODO Auto-generated catch block
ResultUpdation noe=new ResultUpdation(obj);
noe.testing(p, record, row, sh, resultRow, Information.FAIL+": Driver is failed to run '"+p.getProperty(record[OBJECTNAME])
+"' because of "+e.getClass().getSimpleName(),imp);
VALUE_STORAGE.put(record[OBJECTNAME]+VALUE_END, ERROR);
return FAIL;
}
}
}
|
package com.bwie.juan_mao.jingdong_kanglijuan.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bwie.juan_mao.jingdong_kanglijuan.R;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.AddressBean;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by 卷猫~ on 2018/10/18.
*/
public class AddrManageAdapter extends RecyclerView.Adapter<AddrManageAdapter.MyViewHolder> {
private Context context;
private List<AddressBean.DataBean> list;
public AddrManageAdapter(Context context, List<AddressBean.DataBean> list) {
this.context = context;
this.list = list;
}
public interface OnEditClickListener {
void onEditClick(long addrid, int position);
}
private OnEditClickListener editListener;
public void setOnEditClickListener(OnEditClickListener editClickListener) {
this.editListener = editClickListener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.item_addr_manage, null);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
holder.txtName.setText(list.get(position).getName());
long mobile = list.get(position).getMobile();
if (String.valueOf(mobile).length() >= 8) {
String strPre = String.valueOf(mobile).substring(0, 3);
String strHou = String.valueOf(mobile).substring(7, String.valueOf(mobile).length());
holder.txtPhone.setText(strPre + "****" + strHou);
} else {
holder.txtPhone.setText(mobile + "");
}
if (list.get(position).getStatus() == 1) {
holder.txtDefault.setVisibility(View.VISIBLE);
} else {
holder.txtDefault.setVisibility(View.GONE);
}
holder.txtAddress.setText(list.get(position).getAddr());
holder.imgEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editListener.onEditClick(list.get(position).getAddrid(), position);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.txt_name)
TextView txtName;
@BindView(R.id.txt_phone)
TextView txtPhone;
@BindView(R.id.txt_default)
TextView txtDefault;
@BindView(R.id.txt_address)
TextView txtAddress;
@BindView(R.id.img_edit)
ImageView imgEdit;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
|
package cn.kgc.dao;
import cn.kgc.domain.Administrator;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AdministratorDao {
/**
* 查询所用用户
*/
@Select("select * from administrator ")
public List<Administrator> findAD();
}
|
package classfile;
import java.io.*;
import java.lang.String;
import java.util.*;
public class SingleLinkedList {
public Node head;
public SingleLinkedList() {
head = null;
}
public void addFirst(int n) {
Node curr = head;
head = new Node(n);
head.next = curr;
}
public void addFirst(Node node) {
Node curr = head;
head = node;
head.next = curr;
}
public int count() {
Node curr = head;
int count = 0;
while(curr != null){
count++;
curr = curr.next;
}
return count;
}
public void print() {
Node curr = head;
while(curr != null){
if(curr.data != null)
Print.pbl(curr.data);
curr = curr.next;
}
}
public void append(int n) {
Node curr = head;
if(head == null)
head = new Node(n);
else {
while(curr.next != null) {
curr = curr.next;
}
curr.next = new Node(n);
}
}
public void add(int n) {
append(n);
}
public void append(Node no) {
Node curr = head;
if(head == null)
head = no;
else {
while(curr.next != null) {
curr = curr.next;
}
curr.next = no;
}
}
public void add(Node no) {
append(no);
}
// prev = null
// [
static Node reverseLL(Node curr){
Node head = curr;
if(curr != null){
head = reverseLL(curr.next);
if(curr.next != null){
curr.next.next = curr;
curr.next = null;
}
else
head = curr;
}
return head;
}
//recursive
static Node next=null;
public void Reverse(Node curr) {
if(curr != null) {
Reverse(curr.next);
if(next != null)
next.next = curr;
else
head = curr;
next = curr;
curr.next = null;
}
}
//iteration
public void reverseIte(Node curr) {
if(head != null) {
Node prev = null;
Node next = curr.next;
while(curr != null) {
curr.next = prev;
prev = curr;
curr = next;
if(next != null)
next = next.next;
}
head = prev;
}
}
public Node getHead() {
return head;
}
public Node getTail() {
Node curr = head;
while(curr != null && curr.next != null) {
curr = curr.next;
}
return curr;
}
public void remove(Node no) {
Node curr = head;
Node prev = null;
while(curr != null){
if(curr == no){
if(prev == null){ // first node
head = curr.next;
curr.next = null;
}else{
prev.next = curr.next;
curr.next = null;
}
break;
}
prev = curr;
curr = curr.next;
}
}
public void delete(Node no) {
remove(no);
}
public List<Node> toList() {
Node curr = head;
List<Node> list = new ArrayList<Node>();
while(curr != null){
list.add(new Node(curr.data));
curr = curr.next;
}
return list;
}
// public void Remove(Node no) {
// if(no != null && head != null) {
// Node curr = head;
// Node prev = null;
// while(curr != no) {
// prev = curr;
// curr = curr.next;
// }
// if(prev != null && no.next != null) {
// prev.next = no.next;
// no.next = null;
// } else if(prev == null && no.next != null) {
// head = no.next;
// no.next = null;
// } else if(prev != null && no.next == null) {
// prev.next = null;
// } else {
// no = null;
// head = null;
// }
// }
// }
}
|
package LinkedList;
public class note {
/*
链表是空节点,或者有一个值和一个指向下一个链表的指针,因此很多链表问题可以用递归来处理。
*/
}
|
package kr.co.shop.constant;
import kr.co.shop.common.constant.BaseMailCode;
public class MailCode extends BaseMailCode {
public final static String PAYMENT_DELAY_ART = "EC-01003-0";
public final static String PAYMENT_DELAY_OTS = "EC-01003-1";
public final static String PAYMENT_DELAY_CANCLE_ART = "EC-01004-0";
public final static String PAYMENT_DELAY_CANCLE_OTS = "EC-01004-1";
}
|
package com.scf.core.ebus;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author wub
*
*/
public class EventBusProvidor {
/**
*
*/
public static final String TYPE_GUAVA = "guava";
/**
*
*/
private EventBusProvidor() {
}
/**
*
* @param name
* @param type
* @param async
* @return
*/
public static IEventBus create(String name, String type, boolean async) {
IEventBus eb = null;
if (type == null) {
type = TYPE_GUAVA;
}
if (type.equalsIgnoreCase(TYPE_GUAVA)) {
if (async) {
ExecutorService pool = Executors.newCachedThreadPool();
eb = new GuavaAsyncEventBus(name, pool);
} else {
eb = new GuavaEventBus(name);
}
}
if (eb == null) {
throw new EventBusException("Can not create event bus instance for type '" + type + "'");
}
return eb;
}
}
|
package com.holodec.models.util;
import java.net.URL;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateListener implements ServletContextListener {
private Configuration configuration;
private SessionFactory factory;
private ServiceRegistry registry;
private String path = "/hibernate.cfg.xml";
private static Class<HibernateListener> clazz = HibernateListener.class;
public static final String KEY_NAME = clazz.getName();
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event) {
try {
URL url = HibernateListener.class.getResource(path);
configuration = new Configuration().configure(url);
registry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(registry);
event.getServletContext().setAttribute(KEY_NAME, factory);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static SessionFactory getFactory() {
return (SessionFactory) ServletActionContext.getServletContext().getAttribute(KEY_NAME);
}
public static Session openSession() {
return getFactory().openSession();
}
}
|
/*
* 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 exceptionprograms;
public class CreateOwnException {
public static void main( String[] args )
{
int x = 27;
if(x>60)
throw new TooOldException( "Too old Exception" );
else if( x<18 )
throw new TooYoungException( "too young exception");
else
System.out.println("Age is ok");
}
}
class TooOldException extends RuntimeException /*it is recommended to extend RtE*/
{
TooOldException( String s )
{
super( s );
}
}
class TooYoungException extends RuntimeException /*it is recommended to extend RtE*/
{
TooYoungException( String s )
{
super( s );
}
}
|
package com.example.admin.model;
public class ModelSymtoms {
public static String CHILD= "SYMTOMS";
String id, description;
public ModelSymtoms() {
}
public ModelSymtoms(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.goldenasia.lottery.data;
import java.util.ArrayList;
/**
* Created by Sakura on 2016/10/10.
*/
public class GgcPlay2
{
private ArrayList<Integer> open_numbers;
private ArrayList<GgcMoneyNumberEntity> my_numbers;
public ArrayList<GgcMoneyNumberEntity> getMy_numbers()
{
return my_numbers;
}
public void setMy_numbers(ArrayList<GgcMoneyNumberEntity> my_numbers)
{
this.my_numbers = my_numbers;
}
public ArrayList<Integer> getOpen_numbers()
{
return open_numbers;
}
public void setOpen_numbers(ArrayList<Integer> open_numbers)
{
this.open_numbers = open_numbers;
}
}
|
package in.msmartpay.agent.utility;
/**
* Created by Yuganshu on 11/02/2017.
*/
public class Service {
public String validateMobileNumber(String number)
{
if (number.startsWith("+91")) {
String no = number.substring(3);
String newno = no.trim();
newno = newno.replaceAll(" ", "");
if (newno.length() == 10) {
return newno;
}else if (number.startsWith("+91-")||number.startsWith("+91 ")) {
String no1 = number.substring(4);
String newno1 = no1.trim();
newno = newno1.replaceAll(" ", "");
if (newno.length() == 10) {
return newno1;
} else {
return null;
}
} else {
return null;
}
} else if (number.startsWith("91")) {
String no = number.substring(2);
String newno = no.trim();
newno = newno.replaceAll(" ", "");
if (newno.length() == 10) {
return newno;
} else if (number.startsWith("91 ")) {
String no1 = number.substring(1);
String newno1 = no1.trim();
newno1 = newno1.replaceAll(" ", "");
if (newno1.length() == 10) {
return newno1;
} else {
return null;
}
}else {
return null;
}
} else if (number.startsWith("0")) {
String no = number.substring(1);
String newno = no.trim();
newno = newno.replaceAll(" ", "");
if (newno.length() == 10) {
return newno;
} else {
return null;
}
} else if (number.length() == 10) {
return number;
} else {
return null;
}
}
/* public static boolean isValidEmail(String enteredEmail){
Pattern p = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+", Pattern.CASE_INSENSITIVE);
//Pattern p = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(enteredEmail);
if(m.find()){
return true;
} else {
return false;
}
}*/
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
/* public static boolean isValidEmail(String paramString)
{
return Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE).matcher(paramString).find();
}*/
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.teamcode.enums.Color;
import org.openftc.easyopencv.OpenCvCamera;
import org.openftc.easyopencv.OpenCvCameraFactory;
import org.openftc.easyopencv.OpenCvCameraRotation;
@TeleOp(name = "pooMode", group = "TeleOp")
public class RedTeleop extends LinearOpMode {
RobotHardware robotHardware = new RobotHardware(this, telemetry);
TeleOpControls teleOpControls = new TeleOpControls(this, robotHardware, telemetry);
Constants constants = new Constants();
Movement movement = new Movement(this, robotHardware, telemetry);
OpenCvCamera backboardCamera;
@Override
public void runOpMode() {
telemetry.addLine("Initializing...");
telemetry.update();
robotHardware.init(hardwareMap, true);
telemetry.addLine("Starting Camera...");
telemetry.update();
BackboardPipeline pipeline = new BackboardPipeline(Color.RED);
backboardCamera = OpenCvCameraFactory.getInstance().createWebcam(robotHardware.backboardWebcam);
backboardCamera.setPipeline(pipeline);
backboardCamera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() {
@Override
public void onOpened() {
backboardCamera.startStreaming(constants.cameraWidth, constants.cameraHeight, OpenCvCameraRotation.SIDEWAYS_LEFT);
}
});
telemetry.addLine("Ready for Start");
while (!opModeIsActive() && !isStopRequested()) {
telemetry.addData("right", robotHardware.rightEgg.getPosition());
telemetry.addData("left", robotHardware.leftEgg.getPosition());
telemetry.update();
idle();
sleep(50);
}
robotHardware.wobbleClamp.setPosition(constants.clampOpen);
while (opModeIsActive() && !isStopRequested()) {
teleOpControls.notDriving();
teleOpControls.eggs1();
if (this.gamepad1.y) {
movement.resetPower();
if (pipeline.detected() && movement.angleCloseTo(10)) {
if (teleOpControls.bPressed)
movement.goToPoint(199, 120, pipeline);
else
movement.goToPoint(133, (int) (124 + Math.abs(pipeline.getAngle() * 1.25)), pipeline);
}
else
movement.turnTo(0);
movement.setPowers();
}
else {
teleOpControls.normalDrive();
teleOpControls.noCheckBlocker();
}
telemetry.addData("imu", robotHardware.imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle);
telemetry.addData("Mode", teleOpControls.getB() ? "low" : "high");
telemetry.addData("Shooter Vel", robotHardware.shooter.getVelocity());
telemetry.update();
}
}
}
|
package kr.or.ddit.reviewboard.service;
import java.util.List;
import java.util.Map;
import kr.or.ddit.vo.ReviewBoardVO;
public interface IReviewBoardService {
public List<Map<String, String>> reviewboardList() throws Exception;
public int insertReviewBoard(ReviewBoardVO reviewboardInfo) throws Exception;
public int deleteReviewBoard(Map<String, String> params) throws Exception;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.