text stringlengths 10 2.72M |
|---|
/*
* @(#)Interaction.java 1.0 09/05/2000
*
*/
package org.google.code.netapps.chat.primitive;
import java.io.*;
import java.util.*;
/**
* Class for presenting single interaction between cusromer and CSR.
* A set of interactions compose a single session.
*
* @version 1.0 09/05/2000
* @author Alexander Shvets
*/
public class Interaction implements Nameable, Serializable {
static final long serialVersionUID = 6398581304440326365L;
/** Session for this interaction */
private Session session;
/** Assosiated comment for this interaction */
private String comment = new String("");
/** Assosiated transcript for this interaction */
private Transcript transcript = new Transcript();
/** An owner of this interaction */
private String owner = new String("");
/** The name of interaction */
protected String name;
/**
* Constructs an interaction with the specified name.
*
* @param name the name of interaction
*/
public Interaction(String name) {
this.name = name;
}
/**
* Get name of interaction.
*
* @return name of interaction
*/
public String getName() {
return name;
}
/**
* Get qualified name of interaction.
*
* @return qualified name of interaction
*/
public String getQualifiedName() {
return "interaction" + " " + name;
}
/**
* Get comment for this interaction.
*
* @return comment for this interaction
*/
public String getComment() {
return comment;
}
/**
* Set comment for this interaction.
*
* @param name comment for this interaction
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Get the owner of this interaction.
*
* @return owner of this interaction.
*/
public String getOwner() {
return owner;
}
/**
* Set the owner of this interaction.
*
* @param owner owner of this interaction.
*/
public void setOwner(String owner) {
this.owner = owner;
}
/**
* Get the transcript of this interaction.
*
* @return transcript of this interaction.
*/
public Transcript getTranscript() {
return transcript;
}
/**
* Get the session for this interaction.
*
* @return session for this interaction
*/
public Session getSession() {
return session;
}
/**
* Set the session for this interaction.
*
* @param session for this interaction
*/
public void setSession(Session session) {
this.session = session;
}
/**
* Compares two Objects for equality. Two interactions will be equal
* if they both have the same name.
*
* @param object the reference object with which to compare.
* @return true if this object is the same as the obj
* argument; false otherwise.
*/
public boolean equals(Object object) {
if(object instanceof String) {
String name = (String)object;
return this.name.equals(name);
}
else if(object instanceof Interaction) {
Interaction interaction = (Interaction)object;
return this.name.equals(interaction.name);
}
return false;
}
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
return getQualifiedName();
}
public static void main(String[] args) throws Exception {
Interaction interaction1 = new Interaction("interaction1");
System.out.println("Interaction interaction1 : " + interaction1);
Transcript t1 = interaction1.getTranscript();
t1.append("Hello, friend!");
t1.append("line1");
t1.append("line2");
t1.append("line3");
t1.append("end.");
interaction1.setComment("No matter");
System.out.println("Print interaction1:\n");
System.out.println("Comment: " + interaction1.getComment());
System.out.println();
System.out.println("Report: ");
Vector verbatim = t1.getVerbatim();
for(int i=0; i < verbatim.size(); i++) {
System.out.println(verbatim.elementAt(i));
}
}
} |
package egovframework.adm.hom.trs.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import egovframework.rte.psl.dataaccess.EgovAbstractDAO;
@Repository("trainingDAO")
public class TrainingDAO extends EgovAbstractDAO {
public int selectTrainingListTotCnt(Map<String, Object> commandMap) throws Exception{
return (Integer)getSqlMapClientTemplate().queryForObject("trainingDAO.selectTrainingListTotCnt", commandMap);
}
/**
* 설문 문제 관리 리스트
* @param commandMap
* @return
* @throws Exception
*/
public List<?> selectTrainingList(Map<String, Object> commandMap) throws Exception{
return list("trainingDAO.selectTrainingList", commandMap);
}
//연간연수 일정 등록
public Object insertTraining(Map<String, Object> commandMap) throws Exception{
return insert("trainingDAO.insertTraining", commandMap);
}
//교과목 및 시간 배당 파일
public Object insertTrainingFile(Map<String, Object> commandMap) throws Exception{
return insert("trainingDAO.insertTrainingFile", commandMap);
}
//사용여부 N
public int updateTrainingUseN(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTrainingUseN", commandMap);
}
public int selectTrainingSeq(Map<String, Object> commandMap) throws Exception{
return (Integer)getSqlMapClientTemplate().queryForObject("trainingDAO.selectTrainingSeq", commandMap);
}
//보기
public Map<?, ?> selectTrainingView(Map<String, Object> commandMap) throws Exception {
return (Map<?, ?>)selectByPk("trainingDAO.selectTrainingView", commandMap);
}
//파일
public List selectTrainingFileList(Map<String, Object> commandMap) throws Exception{
return list("trainingDAO.selectTrainingFileList", commandMap);
}
public int updateTraining(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTraining", commandMap);
}
public int deleteTrainingFile(Map<String, Object> commandMap) throws Exception{
return delete("trainingDAO.deleteTrainingFile", commandMap);
}
public int deleteTraining(Map<String, Object> commandMap) throws Exception{
return delete("trainingDAO.deleteTraining", commandMap);
}
public int deleteTrainingSchedule(Map<String, Object> commandMap) throws Exception{
return delete("trainingDAO.deleteTrainingSchedule", commandMap);
}
public int selectTrainingScheduleListTotCnt(Map<String, Object> commandMap) throws Exception{
return (Integer)getSqlMapClientTemplate().queryForObject("trainingDAO.selectTrainingScheduleListTotCnt", commandMap);
}
public List<?> selectTrainingScheduleList(Map<String, Object> commandMap) throws Exception{
return list("trainingDAO.selectTrainingScheduleList", commandMap);
}
public Map<?, ?> selectTrainingScheduleView(Map<String, Object> commandMap) throws Exception {
return (Map<?, ?>)selectByPk("trainingDAO.selectTrainingScheduleView", commandMap);
}
public Object insertTrainingSchedule(Map<String, Object> commandMap) throws Exception{
return insert("trainingDAO.insertTrainingSchedule", commandMap);
}
public int updateTrainingSchedule(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTrainingSchedule", commandMap);
}
public int updateTrainingScheduleOrderNum(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTrainingScheduleOrderNum", commandMap);
}
public int selectTrainingCourseListTotCnt(Map<String, Object> commandMap) throws Exception{
return (Integer)getSqlMapClientTemplate().queryForObject("trainingDAO.selectTrainingCourseListTotCnt", commandMap);
}
public List<?> selectTrainingCourseList(Map<String, Object> commandMap) throws Exception{
return list("trainingDAO.selectTrainingCourseList", commandMap);
}
public Map<?, ?> selectTrainingCourseView(Map<String, Object> commandMap) throws Exception {
return (Map<?, ?>)selectByPk("trainingDAO.selectTrainingCourseView", commandMap);
}
public Object insertTrainingCourse(Map<String, Object> commandMap) throws Exception{
return insert("trainingDAO.insertTrainingCourse", commandMap);
}
public int updateTrainingCourse(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTrainingCourse", commandMap);
}
public int deleteTrainingCourse(Map<String, Object> commandMap) throws Exception{
return delete("trainingDAO.deleteTrainingCourse", commandMap);
}
public int updateTrainingCourseOrderNum(Map<String, Object> commandMap) throws Exception{
return update("trainingDAO.updateTrainingCourseOrderNum", commandMap);
}
}
|
package miniProgram;
import miniProgram.schoolGrade.MachinLearningClass;
import miniProgram.schoolGrade.NetworkClass;
import miniProgram.schoolGrade.ProgrammingClass;
import miniProgram.schoolGrade.SchoolClass;
public class RunSchoolGrade {
public static void main(String[] args) {
test(new ProgrammingClass());
test(new NetworkClass());
test(new MachinLearningClass());
}
public static void test(SchoolClass s) {
System.out.println("---------------------------------------");
s.showGrade();
}
}
|
package com.nclodger.mail;
/**
* Created with IntelliJ IDEA.
* User: Julia
* Date: 12.10.13
* Time: 12:50
* To change this template use File | Settings | File Templates.
*/
public class EmailConfirmation {
}
|
package be.darkshark.parkshark.api.dto.division;
public class DivisionDto {
private long id;
private String name;
private String originalName;
private long director_id;
private String parent_division_id;
public DivisionDto(long id, String name, String originalName, long director_id, String parent_division_id) {
this.id = id;
this.name = name;
this.originalName = originalName;
this.director_id = director_id;
this.parent_division_id = parent_division_id;
}
public DivisionDto(){};
public String getName() {
return name;
}
public DivisionDto setName(String name) {
this.name = name;
return this;
}
public String getOriginalName() {
return originalName;
}
public DivisionDto setOriginalName(String originalName) {
this.originalName = originalName;
return this;
}
public long getDirector_id() {
return director_id;
}
public DivisionDto setDirector_id(long director_id) {
this.director_id = director_id;
return this;
}
public String getParent_division_id() {
return parent_division_id;
}
public DivisionDto setParent_division_id(String parent_division_id) {
this.parent_division_id = parent_division_id;
return this;
}
public long getId() {
return id;
}
public DivisionDto setId(long id) {
this.id = id;
return this;
}
}
|
package com.design.factory.NormalFactory;
public class NYPizzaStyleClam extends Pizza {
public NYPizzaStyleClam() {
name = "NY Style Clam Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
toppings.add("Grated Reggiano Cheese");
toppings.add("Fresh Clams from Long Island Sound");
}
}
|
package com.alibaba.druid.bvt.sql.mysql.createTable;
import com.alibaba.druid.sql.MysqlTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.statement.SQLTableLike;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement;
public class MySqlCreateTableTest160 extends MysqlTest {
public void test_0() throws Exception {
//for ADB
String sql = "CREATE TABLE IF NOT EXISTS bar (LIKE a INCLUDING PROPERTIES)";
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) SQLUtils.parseSingleMysqlStatement(sql);
assertTrue(stmt.getTableElementList().get(0) instanceof SQLTableLike);
assertEquals("CREATE TABLE IF NOT EXISTS bar (\n" +
"\tLIKE a INCLUDING PROPERTIES\n" +
")", stmt.toString());
}
public void test_1() throws Exception {
//for ADB
String sql = "CREATE TABLE IF NOT EXISTS bar2 (c TIMESTAMP, LIKE bar, d DATE)";
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) SQLUtils.parseSingleMysqlStatement(sql);
assertTrue(stmt.getTableElementList().get(1) instanceof SQLTableLike);
assertEquals("CREATE TABLE IF NOT EXISTS bar2 (\n" +
"\tc TIMESTAMP,\n" +
"\tLIKE bar,\n" +
"\td DATE\n" +
")", stmt.toString());
}
} |
package in.adavi.pradyot;
import in.adavi.pradyot.application.MysqlDbExperimentApplication;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws Exception {
new MysqlDbExperimentApplication().run(args);
}
}
|
package ar.gob.ambiente.servicios.especiesforestales.managedBeans;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Cites;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Especie;
import ar.gob.ambiente.servicios.especiesforestales.entidades.util.JsfUtil;
import ar.gob.ambiente.servicios.especiesforestales.facades.CitesFacade;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.List;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;
/**
* Bean de respaldo para la gestión de Cites
* @author rincostante
*/
public class MbCites implements Serializable{
/**
* Variable privada: Cites Entidad que se gestiona mediante el bean
*/
private Cites current;
/**
* Variable privada: List<Cites> Listado de Cites para poblar la tabla con todos los registrados
*/
private List<Cites> listado = null;
/**
* Variable privada: List<Cites> para el filtrado de la tabla
*/
private List<Cites> listaFilter;
/**
* Listado que muestra las Especies vinculadas a tipo de Cites
*/
private List<Especie> listEspFilter;
/**
* Variable privada: EJB inyectado para el acceso a datos de Cites
*/
@EJB
private CitesFacade citesFacade;
/**
* Variable privada: boolean que indica si se inició el bean
*/
private boolean iniciado;
/**
* Constructor
*/
public MbCites() {
}
public List<Especie> getListEspFilter() {
return listEspFilter;
}
public void setListEspFilter(List<Especie> listEspFilter) {
this.listEspFilter = listEspFilter;
}
public Cites getCurrent() {
return current;
}
public void setCurrent(Cites current) {
this.current = current;
}
/**
* Método que obtiene el listado de todos los Cites, solo si no está instanciado ya
* @return List<Cites> listado con todos los Cites registrados
*/
public List<Cites> getListado() {
if (listado == null || listado.isEmpty()) {
listado = getFacade().findAll();
}
return listado;
}
public void setListado(List<Cites> listado) {
this.listado = listado;
}
public List<Cites> getListaFilter() {
return listaFilter;
}
public void setListaFilter(List<Cites> listaFilter) {
this.listaFilter = listaFilter;
}
/****************************
* Métodos de inicialización
****************************/
/**
* Método que se ejecuta luego de instanciada la clase e inicializa los datos del usuario
*/
@PostConstruct
public void init(){
iniciado = false;
}
/**
* Método que borra de la memoria los MB innecesarios al cargar el listado
*/
public void iniciar(){
if(!iniciado){
String s;
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(true);
Enumeration enume = session.getAttributeNames();
while(enume.hasMoreElements()){
s = (String)enume.nextElement();
if(s.substring(0, 2).equals("mb")){
if(!s.equals("mbLogin")){
session.removeAttribute(s);
}
}
}
}
}
/**
* Redireccionamiento a la vista con el listado
* @return String nombre de la vista
*/
public String prepareList() {
recreateModel();
return "list";
}
/**
* Redireccionamiento a la vista detalle
* @return String nombre de la vista
*/
public String prepareView() {
return "view";
}
/**
* Redireccionamiento a la vista new para crear un Cites
* @return String nombre de la vista
*/
public String prepareCreate() {
current = new Cites();
return "new";
}
/**
* Redireccionamiento a la vista edit para editar un Cites
* @return String nombre de la vista
*/
public String prepareEdit() {
return "edit";
}
/**
* Método que verifica que el Cites que se quiere eliminar no esté siento utilizado por otra entidad y redirecciona a la vista detalle
* @return String nombre de la vista
*/
public String prepareDestroy(){
boolean libre = getFacade().noTieneDependencias(current.getId());
if (libre){
// Elimina
performDestroy();
recreateModel();
}else{
//No Elimina
JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("CitesNonDeletable"));
}
return "view";
}
/****************************
* Métodos de validación
****************************/
/**
* Método para validar que no exista ya una entidad con este nombre al momento de crearla
* @param arg0: vista jsf que llama al validador
* @param arg1: objeto de la vista que hace el llamado
* @param arg2: contenido del campo de texto a validar
*/
public void validarInsert(FacesContext arg0, UIComponent arg1, Object arg2){
validarExistente(arg2);
}
/**
* Método para validar que no exista una entidad con este nombre, siempre que dicho nombre no sea el que tenía originalmente
* @param arg0: vista jsf que llama al validador
* @param arg1: objeto de la vista que hace el llamado
* @param arg2: contenido del campo de texto a validar
*/
public void validarUpdate(FacesContext arg0, UIComponent arg1, Object arg2){
if(!current.getNombre().equals((String)arg2)){
validarExistente(arg2);
}
}
/**********************
* Métodos de operación
**********************/
/**
* Método para la creación de un nuevo Cites
* @return String nombre de la vista detalle o null si hay error
*/
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CitesCreated"));
return "view";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("CitesCreatedErrorOccured"));
return null;
}
}
/**
* Método para la actualización de un Autor existente
* @return String nombre de la vista detalle o null si hay error
*/
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CitesUpdated"));
return "view";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("CitesUpdatedErrorOccured"));
return null;
}
}
/**
* Método que restea la entidad
*/
private void recreateModel() {
listado.clear();
}
/**
* Método que instancia a la entidad Cites
* @return Cites entidad a gestionar
*/
public Cites getSelected() {
if (current == null) {
current = new Cites();
}
return current;
}
/**
* Método que obtiene un Cites según su id
* @param id Long equivalente al id de la entidad persistida
* @return Cites la entidad correspondiente
*/
public Cites getCites(java.lang.Long id) {
return citesFacade.find(id);
}
/*********************
** Métodos privados **
**********************/
/**
* Método que devuelve el facade para el acceso a datos del Cites
* @return EJB CitesFacade Acceso a datos
*/
private CitesFacade getFacade() {
return citesFacade;
}
/**
* Método para validar que el Cites cuyo nombre se recibe ya está registrado
* @param arg2 Object Contenido del campo de texto correspondiente al nombre
* @throws ValidatorException
*/
private void validarExistente(Object arg2) throws ValidatorException{
if(!getFacade().existe((String)arg2)){
throw new ValidatorException(new FacesMessage(ResourceBundle.getBundle("/Bundle").getString("CreateCitesExistente")));
}
}
/**
* Opera el borrado de la entidad
*/
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CitesDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("CitesDeletedErrorOccured"));
}
}
/********************************************************************
** Converter. Se debe actualizar la entidad y el facade respectivo **
*********************************************************************/
@FacesConverter(forClass = Cites.class)
public static class EspecieControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
MbCites controller = (MbCites) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "mbCites");
return controller.getCites(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
String getStringKey(java.lang.Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Cites) {
Cites o = (Cites) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Cites.class.getName());
}
}
}
}
|
package edu.ycp.cs320.groupProject.webapp.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
import edu.ycp.cs320.groupProject.webapp.shared.model.Ball;
public interface GameStateServiceAsync {
void getUpdatedBall(AsyncCallback<Ball> callback);
}
|
package com.mibo.common.util;
import java.io.Serializable;
public class SavaFile implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String url;
private String imgSlt;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImgSlt() {
return this.imgSlt;
}
public void setImgSlt(String imgSlt) {
this.imgSlt = imgSlt;
}
public SavaFile(String name, String url, String imgSlt) {
this.name = name;
this.url = url;
this.imgSlt = imgSlt;
}
public SavaFile(String name, String url) {
this.name = name;
this.url = url;
}
public SavaFile(String name) {
this.name = name;
}
public SavaFile() {
}
public String toString() {
return "SavaFile [name=" + this.name + ", url=" + this.url + ", imgSlt=" + this.imgSlt + "]";
}
} |
package com.covidresponse.covidcontacttracer.utils;
import android.content.Context;
import android.location.Location;
import com.covidresponse.covidcontacttracer.R;
import java.text.DateFormat;
import java.util.Date;
public class Utils {
public static String getLocationText(Location location) {
return location == null ? "Unknown location" :
"(" + location.getLatitude() + ", " + location.getLongitude() + ")";
}
public static String getLocationTitle(Context context) {
return context.getResources().getString(R.string.location_updated,
DateFormat.getDateTimeInstance().format(new Date()));
}
}
|
package hwarang.artg.mapper;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import hwarang.artg.exhibition.model.ExhibitionVO;
import hwarang.artg.exhibition.model.FavoriteMarkVO;
import hwarang.artg.exhibition.service.ExhibitionListService;
import hwarang.artg.exhibition.service.FavoriteMarkService;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "file:src/main/webapp/WEB-INF/spring/root-context.xml" })
@Log4j
public class ItemTests {
@Setter(onMethod_ = { @Autowired })
ExhibitionMapper mapper;
@Setter(onMethod_ = { @Autowired })
ExhibitionListService service;
@Setter(onMethod_ = { @Autowired })
FavoriteMarkService fService;
@Autowired
MemberMapper mMapper;
@Test
public void testInsert() {
try {
service.apiParserSearch();
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
// public void testSelectAll() {
// System.out.println(mapper.selectAll());
// }
// @Test
// public void testSelectItem() {
// System.out.println(mapper.select(132851));
// }
// @Test
// public void testFavorite() {
// System.out.println(fService.getFavoriteList("id"));
// }
// @Test
// public void testInsert() {
// FavoriteMarkVO fav = new FavoriteMarkVO();
// fav.setExh_seq(152825);
// fav.setMember_id("id");
// fav.setFavorite_group("찜 목록");
// fService.addFavorite(fav);
// System.out.println(fService.getOne(fav));
// }
// @Test
// public void testSeq() {
// FavoriteMarkVO fav = new FavoriteMarkVO();
// fav.setMember_id("id");
// fav.setExh_seq(152825);
// System.out.println(fService.getSeq(fav));
// }
// @Test
// public void getMember() {
// System.out.println(mMapper.selectMember("id1"));
// }
// @Test
// public void getPlace() {
// System.out.println(mapper.getPlaceList("서울"));
// }
}
|
package f.star.iota.milk.ui.artstation.art;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import f.star.iota.milk.base.PVContract;
import f.star.iota.milk.base.StringPresenter;
public class ArtStationPresenter extends StringPresenter<List<ArtStationBean>> {
public ArtStationPresenter(PVContract.View view) {
super(view);
}
@Override
protected List<ArtStationBean> dealResponse(String s, HashMap<String, String> headers) {
Pattern pattern = Pattern.compile("\"data\":\\[(.*?)\\]");
Matcher matcher = pattern.matcher(s);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group(1)).append(",");
}
String result = "[" + sb.substring(0, sb.lastIndexOf(",")) + "]";
return new Gson().fromJson(result, new TypeToken<List<ArtStationBean>>() {
}.getType());
}
}
|
package business.concretes;
import java.util.List;
import business.abstracts.CourseService;
import dataAccess.abstracts.CourseDao;
import entities.concretes.Course;
public class CourseManager implements CourseService {
CourseDao courseDao;
public CourseManager(CourseDao courseDao) {
super();
this.courseDao = courseDao;
}
@Override
public List<Course> getAll() {
return this.courseDao.getAll();
}
@Override
public void add(Course course) {
this.courseDao.add(course);
}
@Override
public void update(Course course) {
this.courseDao.update(course);
}
@Override
public void delete(Course course) {
this.courseDao.delete(course);
}
@Override
public List<Course> search(String text) {
if(!courseDao.getByTeacherName(text).isEmpty()) {
return courseDao.getByTeacherName(text);
}else if(!courseDao.getByCourseName(text).isEmpty())
{
return courseDao.getByCourseName(text);
}
else
{
return null;
}
}
}
|
package com.example.mav_mr_fpv_osu_2020.lib.usb;
public interface IButtonCallback {
void onButton(int button, int state);
}
|
package com.energytrade.app.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the kiot_user_mappings database table.
*
*/
@Entity
@Table(name="kiot_user_mappings")
@NamedQuery(name="KiotUserMapping.findAll", query="SELECT k FROM KiotUserMapping k")
public class KiotUserMapping implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="kiot_user_mapping_id")
private int kiotUserMappingId;
@Column(name="bearer_token")
private String bearerToken;
@Column(name="contract_number")
private String contractNumber;
@Column(name="created_by")
private String createdBy;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_ts")
private Date createdTs;
@Column(name="kiot_user_id")
private String kiotUserId;
private byte softdeleteflag;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="sync_ts")
private Date syncTs;
@Column(name="updated_by")
private String updatedBy;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="updated_ts")
private Date updatedTs;
//bi-directional many-to-one association to AllKiotSwitch
@OneToMany(mappedBy="kiotUserMapping")
private List<AllKiotSwitch> allKiotSwitches;
public KiotUserMapping() {
}
public int getKiotUserMappingId() {
return this.kiotUserMappingId;
}
public void setKiotUserMappingId(int kiotUserMappingId) {
this.kiotUserMappingId = kiotUserMappingId;
}
public String getBearerToken() {
return this.bearerToken;
}
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
public String getContractNumber() {
return this.contractNumber;
}
public void setContractNumber(String contractNumber) {
this.contractNumber = contractNumber;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedTs() {
return this.createdTs;
}
public void setCreatedTs(Date createdTs) {
this.createdTs = createdTs;
}
public String getKiotUserId() {
return this.kiotUserId;
}
public void setKiotUserId(String kiotUserId) {
this.kiotUserId = kiotUserId;
}
public byte getSoftdeleteflag() {
return this.softdeleteflag;
}
public void setSoftdeleteflag(byte softdeleteflag) {
this.softdeleteflag = softdeleteflag;
}
public Date getSyncTs() {
return this.syncTs;
}
public void setSyncTs(Date syncTs) {
this.syncTs = syncTs;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public Date getUpdatedTs() {
return this.updatedTs;
}
public void setUpdatedTs(Date updatedTs) {
this.updatedTs = updatedTs;
}
public List<AllKiotSwitch> getAllKiotSwitches() {
return this.allKiotSwitches;
}
public void setAllKiotSwitches(List<AllKiotSwitch> allKiotSwitches) {
this.allKiotSwitches = allKiotSwitches;
}
public AllKiotSwitch addAllKiotSwitch(AllKiotSwitch allKiotSwitch) {
getAllKiotSwitches().add(allKiotSwitch);
allKiotSwitch.setKiotUserMapping(this);
return allKiotSwitch;
}
public AllKiotSwitch removeAllKiotSwitch(AllKiotSwitch allKiotSwitch) {
getAllKiotSwitches().remove(allKiotSwitch);
allKiotSwitch.setKiotUserMapping(null);
return allKiotSwitch;
}
} |
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class Breeder {
Robot bot;
public boolean breed;
public boolean breeding;
public boolean abort;
public Breeder() {
bot = ArkBot.bot;
breed = false;
breeding = false;
abort = false;
}
public void Breedin() {
if (breeding) {
Breed();
}
}
public void Breed() {
// Breed!
while (breeding && !abort) {
// Transfer Food Attempts
bot.keyPress(KeyEvent.VK_T);
bot.delay(50);
bot.keyRelease(KeyEvent.VK_T);
bot.delay(345);
}
abort = false;
}
private void leftClick()
{
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.delay(10);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
bot.delay(10);
}
}
|
package layeredimage;
import imageasgraph.FixedSizeGraph;
import imageasgraph.OutputType;
import layeredimage.blend.Blend;
/**
* Represents an image which is stored as multiple layered images, and which can access and mutate
* those layers, save and export one or multiple.
*/
public interface LayeredImage extends ViewModel {
/**
* Adds a new, blank layer at the top of the current layered image.
*
* @param layerName The name of the new layer to be added, which does not already exist
* @throws IllegalArgumentException If the given string is null, or if layerName is a name that
* already exists, or if the layerName is more than one word
*/
void addLayer(String layerName) throws IllegalArgumentException;
/**
* Adds a new layer as a copy of an existing at the top of the current layered image.
*
* @param layerName The name of the new layer to be added, which does not already exist
* @param toCopy The name of the layer, which must already exist, to be copied.
* @throws IllegalArgumentException If the given string is null, or if layerName is a name that
* already exists, or if toCopy is a name that does not exist, or
* if the layerName is more than one word
*/
void addLayer(String layerName, String toCopy) throws IllegalArgumentException;
/**
* Moves the layer with the given name to the given index in the pile.
*
* @param layerName The name of the layer to be moved
* @param toIndex The index to move the layer to
* @throws IllegalArgumentException If the layerName is null, or is not a valid layer, or if
* toIndex is not a valid index for the pile.
*/
void moveLayer(String layerName, int toIndex) throws IllegalArgumentException;
/**
* Sets the visibility of the layer referenced by the given string to the given boolean.
*
* @param layerName The name of the layer
* @param isVisible Whether or not it should be visible
* @throws IllegalArgumentException If layerName is null or refers to a non-existent layer
*/
void setVisibility(String layerName, boolean isVisible) throws IllegalArgumentException;
/**
* Returns whether or not the referenced layer is visible.
*
* @param layerName The name of the layer
* @return Whether or not it is visible
* @throws IllegalArgumentException If layerName is null or refers to a non-existent layer
*/
boolean getVisibility(String layerName) throws IllegalArgumentException;
/**
* Returns whether or not the referenced layer is visible.
*
* @param layerIndex The index of the layer
* @return Whether or not it is visible
* @throws IllegalArgumentException If layerIndex is out of bounds
*/
boolean getVisibility(int layerIndex) throws IllegalArgumentException;
/**
* Returns the number of layers in this layeredImage.
*
* @return The number of layers in this image
*/
int getNumLayers();
/**
* Removes the layer with the given name from this LayeredImage.
*
* @param layerName The layer to be removed, must be a layer that already exists
* @throws IllegalArgumentException If the given string is null, or if the layerName does not
* exist
*/
void removeLayer(String layerName) throws IllegalArgumentException;
/**
* Loads the specified image file as a new layer, at the top of the image, with the specified
* name.
*
* @param layerName The name for the layer to be saved with
* @param fileName The name of the image to be imported
* @throws IllegalArgumentException If either input is null, if the specified layerName already
* maps to a layer, or if the specified file either does not
* exist or is not of a valid type to be made into an image.
*/
void loadImageAsLayer(String layerName, String fileName) throws IllegalArgumentException;
/**
* Returns the image represented by the given layerName.
*
* @param layerName The name of the layer to be accessed.
* @return The layer that is represented by the given name.
* @throws IllegalArgumentException If given a layerName that is null or that does not exist.
*/
FixedSizeGraph getLayer(String layerName) throws IllegalArgumentException;
/**
* Returns the image represented by the given layerIndex.
*
* @param layerIndex The name of the layer to be accessed.
* @return The layer that is represented by the given name.
* @throws IllegalArgumentException If layerIndex is out of bounds
*/
FixedSizeGraph getLayer(int layerIndex) throws IllegalArgumentException;
/**
* Saves a copy of this Layered image as an image of the given outputType, blended as specified by
* the given Blend object, and with the given fileName.
*
* @param blendType The way the layers will be blended together
* @param outputType The type of image file to be outputted
* @param fileName The name of the file to be outputted
* @throws IllegalArgumentException If the given filename is null
*/
void saveAsImage(Blend blendType, OutputType outputType, String fileName)
throws IllegalArgumentException;
/**
* Saves a copy of this Layered image as a layered-image file, with the given name.
*
* @param fileName The naem of the file to be outputted
* @throws IllegalArgumentException If the given filename is null
*/
void saveAsLayeredImage(String fileName) throws IllegalArgumentException;
/**
* Gets the common width of all layers.
*
* @return An integer representing the width in pixels of all layers.
*/
int getWidth();
/**
* Gets the common height of all layers.
*
* @return An integer representing the height in pixels of all layers.
*/
int getHeight();
}
|
/*
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
*/
/*
* CommandPrompt.java
*
*/
package pwnbrew.shell;
import java.util.concurrent.Executor;
/**
*
*
*/
public class CommandPrompt extends Shell {
private static String[] CMD_EXE_STR = new String[]{ "cmd", "/k"};
private static final String ENCODING = "UTF-8";
private static final String PROMPT_REGEX = "^[a-zA-Z]:(\\\\|(\\\\[^\\\\/:*\"<>|]+)+)>";
// ==========================================================================
/**
* Constructor
*
* @param passedExecutor
* @param passedListener
*/
public CommandPrompt(Executor passedExecutor, ShellListener passedListener) {
super(passedExecutor, passedListener);
}
// ==========================================================================
/**
* Get the command string
*
* @return
*/
@Override
public String[] getCommandStringArray(){
return CMD_EXE_STR;
}
// ==========================================================================
/**
* Get character encoding.
*
* @return
*/
@Override
public String getEncoding() {
return ENCODING;
}
// ==========================================================================
/**
*
* @return
*/
@Override
public String toString(){
return "Command Prompt";
}
}
|
package com.mart.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tutorialmaster")
public class Tutorial extends BaseModel
{
@Id
@Column(name="Tutorial_ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int Tutorial_ID;
private String Tutorial_Header;
private String Tutorial_Description;
public void SetTutorialHeader(String Tutorial_Header)
{
this.Tutorial_Header = Tutorial_Header;
}
public void SetTutorial_Description(String Tutorial_Description)
{
this.Tutorial_Description = Tutorial_Description;
}
public String GetTutorial_Description()
{
return Tutorial_Description;
}
public String GetTutorial_Header()
{
return Tutorial_Header;
}
public int GetTutorial_ID()
{
return Tutorial_ID;
}
}
|
package fj.swsk.cn.guidetest;
import android.app.Activity;
import android.content.Intent;
import android.os.*;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import fj.swsk.cn.guidetest.util.CommonUtils;
/**
* Created by apple on 16/7/14.
*/
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
static int flag = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
@Override
public void finishActivityFromChild(Activity child, int requestCode) {
super.finishActivityFromChild(child, requestCode);
CommonUtils.log(child+" ==================");
CommonUtils.log(getClass().getName() + " finishActivityFromChild");
}
@Override
public void onClick(View v) {
startActivityForResult(new Intent(this, MainActivity.class), 22);
}
}
|
/* Evaluators.java
Purpose:
Description:
History:
Fri Sep 14 12:24:23 2007, Created by tomyeh
Copyright (C) 2007 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.xel.util;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Enumeration;
import java.net.URL;
import org.zkoss.lang.Classes;
import org.zkoss.lang.SystemException;
import org.zkoss.util.logging.Log;
import org.zkoss.util.resource.Locator;
import org.zkoss.util.resource.ClassLocator;
import org.zkoss.idom.input.SAXBuilder;
import org.zkoss.idom.Document;
import org.zkoss.idom.Element;
import org.zkoss.idom.util.IDOMs;
import org.zkoss.xel.XelContext;
import org.zkoss.xel.VariableResolver;
import org.zkoss.xel.VariableResolverX;
/**
* It mapps a name with an evaluator implementation.
*
* @author tomyeh
* @since 3.0.0
*/
public class Evaluators {
private static final Log log = Log.lookup(Evaluators.class);
/** Map(name, Class/String class); */
private static final Map _evals = new HashMap(8);
private static boolean _loaded;
private Evaluators() {} //prevent from being instantiated
/** Returns the implementation for the specified evaluator name.
*
* @param name the name of the evaluator, say, MVEL.
* @exception SystemException if not found or the class not found.
*/
public static final Class getEvaluatorClass(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("empty or null");
if (!_loaded) load();
final String evalnm = name.toLowerCase();
final Object clsnm;
synchronized (_evals) {
clsnm = _evals.get(evalnm);
}
if (clsnm == null)
throw new SystemException("Evaluator not found: " + name);
if (clsnm instanceof Class) {
return (Class)clsnm;
} else {
try {
return Classes.forNameByThread((String)clsnm);
} catch (ClassNotFoundException ex) {
throw new SystemException("Failed to load class "+clsnm);
}
}
}
/** Tests whether the evaluator (aka., the expression factory)
* for the specified evaluator name
* exists.
*
* @param name the name of the evaluator, say, MVEL.
*/
public static final boolean exists(String name) {
if (name == null) return false;
if (!_loaded) load();
name = name.toLowerCase();
synchronized (_evals) {
return _evals.containsKey(name);
}
}
/** Adds an evaluator
* (aka., the expression factory, {@link org.zkoss.xel.ExpressionFactory}).
*
* @param name the name of the evaluator, say, MVEL.
* It is case insensitive.
* @param evalcls the class name of the evaluator, aka., the expression factory
* ({@link org.zkoss.xel.ExpressionFactory}).
* @return the previous class name, or null if not defined yet
*/
public static final String add(String name, String evalcls) {
if (name == null || name.length() == 0
|| evalcls == null || evalcls.length() == 0)
throw new IllegalArgumentException("emty or null");
if (log.debugable()) log.debug("Evaluator is added: "+name+", "+evalcls);
final String evalnm = name.toLowerCase();
final Object old;
synchronized (_evals) {
old = _evals.put(evalnm, evalcls);
}
return old instanceof Class ? ((Class)old).getName(): (String)old;
}
/** Adds an evaluator based on the XML declaration.
* The evaluator is also known as the expression factory,
* {@link org.zkoss.xel.ExpressionFactory}.
*
* <pre><code>
<xel-config>
<evaluator-name>SuperEL</evaluator-name><!-- case insensitive --!>
<evaluator-class>my.MySuperEvaluator</evaluator-class>
</xel-config>
* </code></pre>
*
* @param config the XML element called zscript-config
* @return the previous class, or null if not defined yet
*/
public static final String add(Element config) {
//Spec: it is OK to declare an nonexist factory, since
//deployer might remove unused jar files.
final String name =
IDOMs.getRequiredElementValue(config, "evaluator-name");
final String clsnm =
IDOMs.getRequiredElementValue(config, "evaluator-class");
return add(name, clsnm);
}
/** Loads from metainfo/xel/config
*/
synchronized static final void load() {
if (_loaded)
return;
try {
final ClassLocator loc = new ClassLocator();
for (Enumeration en = loc.getResources("metainfo/xel/config.xml");
en.hasMoreElements();) {
final URL url = (URL)en.nextElement();
if (log.debugable()) log.debug("Loading "+url);
try {
final Document doc = new SAXBuilder(false, false, true).build(url);
if (IDOMs.checkVersion(doc, url))
parseConfig(doc.getRootElement(), loc);
} catch (Exception ex) {
log.error("Failed to parse "+url, ex); //keep running
}
}
} catch (Exception ex) {
log.error(ex); //keep running
} finally {
_loaded = true;
}
}
/** Parse config.xml. */
private static void parseConfig(Element root, Locator loc) {
for (Iterator it = root.getElements("xel-config").iterator();
it.hasNext();) {
add((Element)it.next());
}
}
/** Resolves the variable based on the the specified context and
* variable resolver.
* @since 5.0.0
*/
public static Object resolveVariable(XelContext ctx,
VariableResolver resolver, Object base, Object name) {
if (resolver instanceof VariableResolverX) {
if (ctx == null)
ctx = new SimpleXelContext(resolver);
return ((VariableResolverX)resolver).resolveVariable(ctx, base, name);
} else if (resolver != null && base == null && name != null)
return resolver.resolveVariable(name.toString());
return null;
}
/** Resolves the variable based on the specified context.
* If the variable resolver ({@link XelContext#getVariableResolver}
* is an instance of {@link VariableResolverX}, then
* {@link VariableResolverX#resolveVariable(XelContext,Object,Object)}
* will be invoked.
* @param ctx the context. If null, null will be returned.
* @since 5.0.0
*/
public static Object resolveVariable(XelContext ctx, Object base, Object name) {
if (ctx != null) {
VariableResolver resolver = ctx.getVariableResolver();
if (resolver instanceof VariableResolverX)
return ((VariableResolverX)resolver).resolveVariable(ctx, base, name);
else if (resolver != null && base == null && name != null)
return resolver.resolveVariable(name.toString());
}
return null;
}
/** Resolves the variable based on the specified resolver.
* If the resolver is an instance of {@link VariableResolverX}, then
* {@link VariableResolverX#resolveVariable(XelContext,Object,Object)}
* will be invoked.
* <p>Notice that it is always better to invoke {@link #resolveVariable(XelContext,Object,Object)}
* if {@link XelContext} is available.
* @param resolver the variable resolver. If null, null will be returned.
* @since 5.0.0
*/
public static Object resolveVariable(VariableResolver resolver, String name) {
return resolver != null ?
resolveVariable(new SimpleXelContext(resolver), null, name): null;
}
}
|
package com.takeaway.gameofthree.logger.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.takeaway.gameofthree.common.constants.Constants;
import com.takeaway.gameofthree.common.dto.GameMessage;
@Component
public class LoggsHandler {
@Value("${queueName}")
private String queueName;
private static final Logger LOGGER = LogManager.getLogger(LoggsHandler.class);
@JmsListener(destination = "${queueName}", containerFactory = "myFactory")
public void receiveMessage(GameMessage message) throws InterruptedException {
if(message.isWinner()) {
LOGGER.info(message.getPlayerId() + " WIN!!!");
}
else {
LOGGER.info("GAME ID: " + message.getGameId() + " :: Number = " + message.getNumber()
+ " recieved by " + message.getPlayerId());
}
}
}
|
/*
* 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.context.event;
import java.util.function.Predicate;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by objects that can manage a number of
* {@link ApplicationListener} objects and publish events to them.
*
* <p>An {@link org.springframework.context.ApplicationEventPublisher}, typically
* a Spring {@link org.springframework.context.ApplicationContext}, can use an
* {@code ApplicationEventMulticaster} as a delegate for actually publishing events.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Stephane Nicoll
* @see ApplicationListener
*/
public interface ApplicationEventMulticaster {
/**
* Add a listener to be notified of all events.
* @param listener the listener to add
* @see #removeApplicationListener(ApplicationListener)
* @see #removeApplicationListeners(Predicate)
*/
void addApplicationListener(ApplicationListener<?> listener);
/**
* Add a listener bean to be notified of all events.
* @param listenerBeanName the name of the listener bean to add
* @see #removeApplicationListenerBean(String)
* @see #removeApplicationListenerBeans(Predicate)
*/
void addApplicationListenerBean(String listenerBeanName);
/**
* Remove a listener from the notification list.
* @param listener the listener to remove
* @see #addApplicationListener(ApplicationListener)
* @see #removeApplicationListeners(Predicate)
*/
void removeApplicationListener(ApplicationListener<?> listener);
/**
* Remove a listener bean from the notification list.
* @param listenerBeanName the name of the listener bean to remove
* @see #addApplicationListenerBean(String)
* @see #removeApplicationListenerBeans(Predicate)
*/
void removeApplicationListenerBean(String listenerBeanName);
/**
* Remove all matching listeners from the set of registered
* {@code ApplicationListener} instances (which includes adapter classes
* such as {@link ApplicationListenerMethodAdapter}, e.g. for annotated
* {@link EventListener} methods).
* <p>Note: This just applies to instance registrations, not to listeners
* registered by bean name.
* @param predicate the predicate to identify listener instances to remove,
* e.g. checking {@link SmartApplicationListener#getListenerId()}
* @since 5.3.5
* @see #addApplicationListener(ApplicationListener)
* @see #removeApplicationListener(ApplicationListener)
*/
void removeApplicationListeners(Predicate<ApplicationListener<?>> predicate);
/**
* Remove all matching listener beans from the set of registered
* listener bean names (referring to bean classes which in turn
* implement the {@link ApplicationListener} interface directly).
* <p>Note: This just applies to bean name registrations, not to
* programmatically registered {@code ApplicationListener} instances.
* @param predicate the predicate to identify listener bean names to remove
* @since 5.3.5
* @see #addApplicationListenerBean(String)
* @see #removeApplicationListenerBean(String)
*/
void removeApplicationListenerBeans(Predicate<String> predicate);
/**
* Remove all listeners registered with this multicaster.
* <p>After a remove call, the multicaster will perform no action
* on event notification until new listeners are registered.
* @see #removeApplicationListeners(Predicate)
*/
void removeAllListeners();
/**
* Multicast the given application event to appropriate listeners.
* <p>Consider using {@link #multicastEvent(ApplicationEvent, ResolvableType)}
* if possible as it provides better support for generics-based events.
* <p>If a matching {@code ApplicationListener} does not support asynchronous
* execution, it must be run within the calling thread of this multicast call.
* @param event the event to multicast
* @see ApplicationListener#supportsAsyncExecution()
*/
void multicastEvent(ApplicationEvent event);
/**
* Multicast the given application event to appropriate listeners.
* <p>If the {@code eventType} is {@code null}, a default type is built
* based on the {@code event} instance.
* <p>If a matching {@code ApplicationListener} does not support asynchronous
* execution, it must be run within the calling thread of this multicast call.
* @param event the event to multicast
* @param eventType the type of event (can be {@code null})
* @since 4.2
* @see ApplicationListener#supportsAsyncExecution()
*/
void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);
}
|
package egovframework.svt.adm.prop.auto;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import egovframework.rte.psl.dataaccess.EgovAbstractDAO;
@Repository
public class AdminAutoMemberDAO extends EgovAbstractDAO {
public void insertAutoMember(Map<String, Object> commandMap) {
insert("adminAutoMember.insertAutoMember", commandMap);
}
public void deleteAutoMember(Map<String, Object> commandMap) {
delete("adminAutoMember.deleteAutoMember", commandMap);
}
public List<?> getAutoMemberList(Map<String, Object> commandMap) {
return list("adminAutoMember.getAutoMemberList", commandMap);
}
}
|
package lotro.my.reports;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lotro.models.Alliance;
import lotro.models.Character;
import lotro.models.Equipment;
import lotro.models.Item;
import lotro.models.Kinship;
import lotro.models.Player;
import lotro.models.Slot;
import lotro.models.Stats;
import lotro.my.xml.KinshipXML;
public final class ReportGear extends Report
{
public ReportGear (final Kinship kinship, final String name)
{
super (kinship, name);
}
@Override
public void exportAsHTML (final List<String> lines)
{
List<Character> sorted = new ArrayList<Character> (getCharacters());
Collections.sort (sorted, new Character.ByClass());
addTitle (lines);
List<String> headers = new ArrayList<String>();
if (isAlliance())
headers.add ("Kinship");
if (hasPlayers())
headers.add ("Player");
headers.add ("Character");
headers.add ("Class");
headers.add ("Level");
headers.add ("Morale");
headers.add ("Power");
headers.add ("Armor");
for (Slot slot : Slot.values())
headers.add (slot.getAbbrev());
lines.add (getTableTag());
lines.add (" <thead>");
lines.add (" <tr bgcolor=yellow>");
for (String header : headers)
lines.add (" <th>" + header + "</th>");
lines.add (" </tr>");
lines.add (" </thead>");
for (Character ch : sorted)
exportCharacter (ch, lines);
lines.add ("</table>\n");
addFooter (lines, "The data for this chart was provided by mylotro.com, " +
"which only shows the gear that you had equipped when you last logged out.");
}
private void exportCharacter (final Character ch, final List<String> lines)
{
lines.add (" <tr>");
if (isAlliance())
lines.add (" <td align=left bgcolor=white>" + ch.getKinship() + "</td>");
if (hasPlayers())
{
Player player = ch.getPlayer();
String playerName = player != null ? player.getName() : " ";
lines.add (" <td align=left bgcolor=white>" + playerName + "</td>");
}
lines.add (" <td align=left bgcolor=white>" + Report.getLink (ch) + "</td>");
String bg = ch.getKlass().getColorBG ("#");
String fg = ch.getKlass().getColorFG();
lines.add (" <td align=left bgcolor=" + bg + "><font color=" + fg + ">" +
ch.getKlass() + "</font></td>");
lines.add (getLine (ch.getLevel() + "", null, "center", "white"));
lines.add (getLine (ch, Stats.Morale, null));
lines.add (getLine (ch, Stats.Power, null));
lines.add (getLine (ch, Stats.Armour, null));
Equipment eq = ch.getEquipment();
for (Slot slot : Slot.values())
if (eq != null)
lines.add (getLine (eq.getItem (slot)));
else
lines.add ("<td> </td>");
lines.add (" </tr>");
}
private String getLine (final Item item)
{
StringBuilder sb = new StringBuilder();
if (item != null && item.getSlot() != null)
{
sb.append (" <td align=center bgcolor=" + item.getSlot().getColor() + ">");
sb.append ("<a href=\"" + item.getLorebookLink() + "\"");
sb.append (" title=\"" + item.getName() + "\""); // tooltip
sb.append (" target=_blank>");
sb.append (item.getSlot().getAbbrev());
sb.append ("</a");
sb.append ("</td>");
}
else
sb.append ("<td> </td>");
return sb.toString();
}
public static void main (final String[] args) throws Exception
{
KinshipXML xml = new KinshipXML();
xml.setIncludeDetails (true);
xml.setLookupPlayer (true);
// Kinship kinship = xml.scrapeURL ("Landroval", "The Palantiri");
// kinship.setFilter (FilterFactory.getLevelFilter (50));
Kinship kinship = xml.scrapeURL ("Elendilmir", "Black Isle");
Report app = new ReportGear (kinship, "Gear");
app.saveFile();
}
}
|
package com.servicos.model;
import java.io.Serializable;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.servicos.dao.UsuarioDao;
import com.servicos.secoes.SessionUtils;
@ManagedBean
@SessionScoped
public class Login implements Serializable {
private static final long serialVersionUID = 1094801825228386363L;
private int idUsuario;
private String nomeUsuario;
private String login;
private String senha;
private String cargo;
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String nomeUsuario) {
this.nomeUsuario = nomeUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public String validateUsernamePassword() {
boolean valid = UsuarioDao.validate(login, senha);
if (valid) {
HttpSession session = SessionUtils.getSession();
session.setAttribute("usuario", login);
System.out.println("Login validado.");
return "sucesso";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Login ou senha inválidos", "Entre com as credenciais corretas"));
return "erro";
}
}
// logout event, invalidate session
public String logout() {
HttpSession session = SessionUtils.getSession();
session.invalidate();
return "login";
}
public String validaInsert() throws SQLException{
boolean validado = UsuarioDao.adicionaUsuario(nomeUsuario, login, senha,cargo);
if (validado){
System.out.println("Cadastrado.");
//Fazer update no GRID
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Cadastado com sucesso!.", ""));
return "cadastrado";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Erro ao cadastrar.", "Favor reportar erro a TI."));
return "ncadastrado";
}
}
}
|
/*
2021-10-10
[Leetcode][Hard] 282. Expression Add Operators
*/
import java.util.*;
class ExpressionAndOperators {
/*
Runtime: 115 ms
Memory Usage: 40 MB
참고 ) https://cheonhyangzhang.gitbooks.io/leetcode-solutions/content/282-expression-add-operators.html
*/
public List<String> addOperators(String num, int target) {
List<String> result = new LinkedList<>();
process("", 0, 0, num, target, result);
return result;
}
private void process(String cur, long sum, long addToSum, String num, int target, List<String> result ) {
if ( num.length()==0 && target==sum ) {
result.add(cur);
return;
}
for(int i=1; i<=num.length(); i++) { // 놓친 부분 - Sting 을 substring 으로 나누기. (처음에 모두다 split 후 연산하려고 했음.)
String first = num.substring(0, i);
String second = num.substring(i);
if ( first.charAt(0) == '0' && first.length()>1 ) {
return;
}
long firstLong = Long.parseLong(first);
if ( cur.equals("") ) {
process(first, firstLong, firstLong, second, target, result);
} else {
process(cur+"+"+ first, sum+firstLong, firstLong, second, target, result);
process(cur+"-"+ first, sum-firstLong, -firstLong, second, target, result);
process(cur+"*"+ first, (sum - addToSum) + addToSum * firstLong, addToSum * firstLong, second, target, result);
}
}
}
public static void main(String[] args) {
ExpressionAndOperators eo = new ExpressionAndOperators();
String num = "105";
int target = 5;
List<String> result = eo.addOperators(num, target);
for(String str : result) {
System.out.println(str);
}
}
}
/*
leetcode solution
*/
class ExpressionAndOperators2 {
public ArrayList<String> answer;
public String digits;
public long target;
public void recurse(
int index, long previousOperand, long currentOperand, long value, ArrayList<String> ops) {
String nums = this.digits;
// Done processing all the digits in num
if (index == nums.length()) {
// If the final value == target expected AND
// no operand is left unprocessed
if (value == this.target && currentOperand == 0) {
StringBuilder sb = new StringBuilder();
ops.subList(1, ops.size()).forEach(v -> sb.append(v));
this.answer.add(sb.toString());
}
return;
}
// Extending the current operand by one digit
currentOperand = currentOperand * 10 + Character.getNumericValue(nums.charAt(index));
String current_val_rep = Long.toString(currentOperand);
int length = nums.length();
// To avoid cases where we have 1 + 05 or 1 * 05 since 05 won't be a
// valid operand. Hence this check
if (currentOperand > 0) {
// NO OP recursion
recurse(index + 1, previousOperand, currentOperand, value, ops);
}
// ADDITION
ops.add("+");
ops.add(current_val_rep);
recurse(index + 1, currentOperand, 0, value + currentOperand, ops);
ops.remove(ops.size() - 1);
ops.remove(ops.size() - 1);
if (ops.size() > 0) {
// SUBTRACTION
ops.add("-");
ops.add(current_val_rep);
recurse(index + 1, -currentOperand, 0, value - currentOperand, ops);
ops.remove(ops.size() - 1);
ops.remove(ops.size() - 1);
// MULTIPLICATION
ops.add("*");
ops.add(current_val_rep);
recurse(
index + 1,
currentOperand * previousOperand,
0,
value - previousOperand + (currentOperand * previousOperand),
ops);
ops.remove(ops.size() - 1);
ops.remove(ops.size() - 1);
}
}
public List<String> addOperators(String num, int target) {
if (num.length() == 0) {
return new ArrayList<String>();
}
this.target = target;
this.digits = num;
this.answer = new ArrayList<String>();
this.recurse(0, 0, 0, 0, new ArrayList<String>());
return this.answer;
}
}
|
package com.codingchili.realmregistry;
import com.codingchili.realmregistry.configuration.RealmRegistrySettings;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Robin Duda
*/
@RunWith(VertxUnitRunner.class)
public class ConfigurationTest {
@Test
public void testTrustedRealm() {
RealmRegistrySettings auth = new RealmRegistrySettings();
auth.getRealms().add("realmName");
Assert.assertTrue(auth.isTrustedRealm("realmName"));
}
@Test
public void testNotTrustedRealm() {
Assert.assertFalse(new RealmRegistrySettings().isTrustedRealm("not trusted"));
}
}
|
package slh.services.usermodel;
import java.io.IOException;
import java.net.URI;
import java.util.Properties;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import slh.Util;
import slh.services.usermodel.UserModelResponse.TraitTreeNode;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class UserModelService
{
// in case its local
private static final String serviceName = "user_modeling";
private static String baseURL, username, password;
// init
static
{
//get proeprty auth data
Properties props = Util.getProperties();
baseURL = props.getProperty(serviceName + ".url");
username = props.getProperty(serviceName + ".username");
password = props.getProperty(serviceName + ".password");
// THEN get the VCAP data...
getCloudAuthData();
}
/**
* Get authorization from the cloud!
*/
private static void getCloudAuthData()
{
JsonObject sysEnv = null;
String envServices = System.getenv("VCAP_SERVICES");
if (envServices == null)
return;
sysEnv = (new JsonParser()).parse(envServices).getAsJsonObject();
if (sysEnv.has(serviceName))
{
JsonObject creds = sysEnv.get(serviceName).getAsJsonArray().get(0).getAsJsonObject().get("credentials").getAsJsonObject();
baseURL = creds.get("url").getAsString();
username = creds.get("username").getAsString();
password = creds.get("password").getAsString();
}
}
/**
* @param content
* @return returns null if anything goes wrong.
*/
public static UserModelResponse getUserModel(String content)
{
return getUserModel(new UserModelRequest(content));
}
/**
* @param request
* @return returns null if anything goes wrong.
*/
public static UserModelResponse getUserModel(UserModelRequest request)
{
try
{
Executor executor = Executor.newInstance().auth(username, password);
URI profileURI = new URI(baseURL + "api/v2/profile").normalize();
Request profileRequest = Request.Post(profileURI)
.addHeader("Accept", "application/json")
.bodyString(Util.GSON.toJson(request), ContentType.APPLICATION_JSON);
String profileString = executor.execute(profileRequest).handleResponse(new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse r) throws ClientProtocolException, IOException
{
if (r.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
return EntityUtils.toString(r.getEntity());
else
return null;
}
});
if (profileString != null)
{ //System.out.println(profileString);
return Util.GSON.fromJson(profileString, UserModelResponse.class);
}
}
catch (Throwable t)
{
t.printStackTrace();
return null;
}
return null;
}
public static int[] getCategory(UserModelResponse user)
{
if (user == null)
return null;
String[] artistCats = { "Artistic interests", "Imagination", "Liberalism", "Curiosity", "Self-expression" };
double[] artistRanks = { 0.5, 0.5, 0.5, 0.5, 0.5 };
String[] outdoorCats = { "Adventurousness", "Activity level", "Friendliness", "Excitement", "Challenge" };
double[] outdoorRanks = { 0.5, 0.5, 0.5, 0.5, 0.5 };
String[] intellectualCats = { "Intellect", "Orderliness", "Self-efficacy", "Morality", "Self-enhancement", };
double[] intellectualRanks = { 0.5, 0.5, 0.5, 0.5, 0.5 };
String[] sociableCats = { "Liberalism", "Cheerfulness", "Trust", "Self-consciousness", "Closeness", "Self-expression" };
double[] sociableRanks = { 0.5, 0.5, 0.5, 0.5, 0.5 };
int artistScore = 0;
int intellectualScore = 0;
int sociableScore = 0;
int outdoorsScore = 0;
int i = 0, j = 0, k = 0, m = 0;
//System.out.println(user);
TraitTreeNode t = user.tree;
for (TraitTreeNode child1 : t.children)
{
if (!child1.isNotHeading())
{
for (TraitTreeNode child2 : child1.children)
{
if (!child2.isNotHeading())
{
for (TraitTreeNode child3 : child2.children)
{
if (!child3.isNotHeading())
{
for (TraitTreeNode child4 : child3.children)
{
//System.out.println(child4.name);
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
if (child4.name.toUpperCase().equals(artistCats[i].toUpperCase()))
{
if (child4.percentage > artistRanks[i])
artistScore++;
//System.out.println(i);
i++;
}
if (child4.name.toUpperCase().equals(outdoorCats[j].toUpperCase()))
{
if (child4.percentage > outdoorRanks[j])
outdoorsScore++;
j++;
}
if (child4.name.toUpperCase().equals(intellectualCats[k].toUpperCase()))
{
if (child4.percentage > intellectualRanks[k])
intellectualScore++;
k++;
}
if (child4.name.toUpperCase().equals(sociableCats[m].toUpperCase()))
{
if (child4.percentage > sociableRanks[m])
sociableScore++;
m++;
}
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
}
}
else
{
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
if (child3.name.toUpperCase().equals(artistCats[i].toUpperCase()))
{
if (child3.percentage > artistRanks[i])
artistScore++;
i++;
}
if (child3.name.toUpperCase().equals(outdoorCats[j].toUpperCase()))
{
if (child3.percentage > outdoorRanks[j])
outdoorsScore++;
j++;
}
if (child3.name.toUpperCase().equals(intellectualCats[k].toUpperCase()))
{
if (child3.percentage > intellectualRanks[k])
intellectualScore++;
k++;
}
if (child3.name.toUpperCase().equals(sociableCats[m].toUpperCase()))
{
if (child3.percentage > sociableRanks[m])
sociableScore++;
m++;
}
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
}
}
}
else
{
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
if (child2.name.toUpperCase().equals(artistCats[i].toUpperCase()))
{
if (child2.percentage > artistRanks[i])
artistScore++;
i++;
}
if (child2.name.toUpperCase().equals(outdoorCats[j].toUpperCase()))
{
if (child2.percentage > outdoorRanks[j])
outdoorsScore++;
j++;
}
if (child2.name.toUpperCase().equals(intellectualCats[k].toUpperCase()))
{
if (child2.percentage > intellectualRanks[k])
intellectualScore++;
k++;
}
if (child2.name.toUpperCase().equals(sociableCats[m].toUpperCase()))
{
if (child2.percentage > sociableRanks[m])
sociableScore++;
m++;
}
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
}
}
}
else
{
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
if (child1.name.toUpperCase().equals(artistCats[i].toUpperCase()))
{
if (child1.percentage > artistRanks[i])
artistScore++;
i++;
}
if (child1.name.toUpperCase().equals(outdoorCats[j].toUpperCase()))
{
if (child1.percentage > outdoorRanks[j])
outdoorsScore++;
j++;
}
if (child1.name.toUpperCase().equals(intellectualCats[k].toUpperCase()))
{
if (child1.percentage > intellectualRanks[k])
intellectualScore++;
k++;
}
if (child1.name.toUpperCase().equals(sociableCats[m].toUpperCase()))
{
if (child1.percentage > sociableRanks[m])
sociableScore++;
m++;
}
if (i > 4 || j > 4 || k > 4 || m > 4)
break;
}
//System.out.println(i);
}
System.out.println(m);
int[] scores = new int[4];
scores[0] = artistScore;
scores[1] = outdoorsScore;
scores[2] = intellectualScore;
scores[3] = sociableScore;
return scores;
}
}
|
package drivetrain.unused;
import org.usfirst.frc.team1640.robot.Robot;
import org.usfirst.frc.team1640.robot.Robot.State;
import drivetrain.DriveControl;
import drivetrain.DriveControlDecorator;
import drivetrain.DriveIO;
import utilities.PIDOutputDouble;
import utilities.PIDSourceDouble;
import utilities.Utilities;
import edu.wpi.first.wpilibj.PIDController;
public class DualAxisDriveDecorator extends DriveControlDecorator{ //use triggers to drive arcade (not currently in use)
private DriveIO driveIO = DriveIO.getInstance();
public DualAxisDriveDecorator(DriveControl driveControl) {
super(driveControl);
}
public void execute(double x1, double y1, double x2, double y2){
y1 = driveIO.getRightTrigger() - driveIO.getLeftTrigger();
super.execute(x2,y1,0,0);
}
}
|
package com.example.bulingzhuang.sesamecreditdemo.custom;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import com.example.bulingzhuang.sesamecreditdemo.R;
import com.example.bulingzhuang.sesamecreditdemo.utils.Tools;
/**
* Created by bulingzhuang
* on 2016/11/30
* E-mail:bulingzhuang@foxmail.com
*/
public class CreditView extends View {
private String[] texts = {"较差", "中等", "良好", "优秀", "极好"};
private int mMaxNum, mStartAngle, mSweepAngle;
private int mSweepInWidth, mSweepOutWidth;
private Paint mPaint, mPaint_1, mPaint_2, mPaint_3;
private int mWSize, mHSize;
private int mWMode, mHMode;
private int mWidth, mHeight;
private int mRadius;
private Context mContext;
private int[] indicatorColor = {0xffffffff, 0x00ffffff, 0x99ffffff, 0xffffffff};
private int currentNum;
public int getCurrentNum() {
return currentNum;
}
public void setCurrentNum(int currentNum) {
this.currentNum = currentNum;
invalidate();
}
public void setCurrentNumAnim(int num) {
float duration = (float) Math.abs(num - currentNum) / mMaxNum * 1500 + 500;
ObjectAnimator anim = ObjectAnimator.ofInt(this, "currentNum", num);
anim.setDuration((long) Math.min(duration, 2000));
anim.setInterpolator(new AccelerateDecelerateInterpolator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (int) valueAnimator.getAnimatedValue("currentNum");
int color = calculateColor(value);
setBackgroundColor(color);
}
});
anim.start();
}
private int calculateColor(int value) {
ArgbEvaluator argbEvaluator = new ArgbEvaluator();
float fraction;
int color;
if (value <= mMaxNum / 2) {
fraction = (float) value/(mMaxNum/2);
color = (int) argbEvaluator.evaluate(fraction,0xFFFF6347,0xFFFF8C00);//由红到橙
}else {
fraction = ( (float)value-mMaxNum/2 ) / (mMaxNum/2);
color = (int) argbEvaluator.evaluate(fraction,0xFFFF8C00,0xFF00CED1); //由橙到蓝
}
return color;
}
public CreditView(Context context) {
this(context, null);
}
public CreditView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
//对当前控件不使用硬件加速
setLayerType(LAYER_TYPE_SOFTWARE, null);
initAttr(context, attrs);
initPaint();
}
private void initPaint() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.WHITE);
mPaint_1 = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint_2 = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint_3 = new Paint(Paint.ANTI_ALIAS_FLAG);
}
private void initAttr(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CreditView);
mMaxNum = typedArray.getInt(R.styleable.CreditView_maxNum, 500);
mStartAngle = typedArray.getInt(R.styleable.CreditView_startAngle, 160);
mSweepAngle = typedArray.getInt(R.styleable.CreditView_sweepAngle, 220);
//内外圆环弧度的宽度
mSweepInWidth = Tools.dp2px(context, 8);
mSweepOutWidth = Tools.dp2px(context, 3);
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWSize = MeasureSpec.getSize(widthMeasureSpec);
mWMode = MeasureSpec.getMode(widthMeasureSpec);
mHSize = MeasureSpec.getSize(heightMeasureSpec);
mHMode = MeasureSpec.getMode(heightMeasureSpec);
if (mWMode == MeasureSpec.EXACTLY) {
mWidth = mWSize;
} else {
mWidth = Tools.dp2px(mContext, 300);
}
if (mHMode == MeasureSpec.EXACTLY) {
mHeight = mHSize;
} else {
mHeight = Tools.dp2px(mContext, 400);
}
setMeasuredDimension(mWidth, mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mRadius = getMeasuredWidth() / 4;
canvas.save();
canvas.translate(mWidth / 2, mHeight / 2);
drawRound(canvas);//画内外圆弧
drawScale(canvas);//画刻度
drawIndicator(canvas);//画当前进度值
drawCenterText(canvas);//画中间文字
canvas.restore();
}
private void drawCenterText(Canvas canvas) {
canvas.save();
mPaint_3.setStyle(Paint.Style.FILL);
mPaint_3.setTextSize(mRadius / 2);
mPaint_3.setColor(0xffffffff);
Log.e("blz","画数值:"+currentNum);
canvas.drawText(currentNum + "", -mPaint_3.measureText(currentNum + "") / 2, 0, mPaint_3);
mPaint_3.setTextSize(mRadius / 4);
String content = "信用";
if (currentNum < mMaxNum / 5) {
content += texts[0];
} else if (currentNum >= mMaxNum / 5 && currentNum < mMaxNum * 2 / 5) {
content += texts[1];
} else if (currentNum >= mMaxNum * 2 / 5 && currentNum < mMaxNum * 3 / 5) {
content += texts[2];
} else if (currentNum >= mMaxNum * 3 / 5 && currentNum < mMaxNum * 4 / 5) {
content += texts[3];
} else if (currentNum >= mMaxNum * 4 / 5) {
content += texts[4];
}
Rect rect = new Rect();
mPaint_3.getTextBounds(content, 0, content.length(), rect);
canvas.drawText(content, -rect.width() / 2, rect.height() + 20, mPaint_3);
canvas.restore();
}
private void drawIndicator(Canvas canvas) {
canvas.save();
mPaint_1.setStyle(Paint.Style.STROKE);
int sweep;
if (currentNum <= mMaxNum) {
sweep = (int) ((float) currentNum / (float) mMaxNum * mSweepAngle);
} else {
sweep = mSweepAngle;
}
mPaint_1.setStrokeWidth(mSweepOutWidth);
SweepGradient sweepGradient = new SweepGradient(0, 0, indicatorColor, null);
mPaint_1.setShader(sweepGradient);
int w = Tools.dp2px(mContext, 10);
RectF rectF = new RectF(-mRadius - w, -mRadius - w, mRadius + w, mRadius + w);
canvas.drawArc(rectF, mStartAngle, sweep, false, mPaint_1);
float x = (float) ((mRadius + Tools.dp2px(mContext, 10)) * Math.cos(Math.toRadians(mStartAngle + sweep)));
float y = (float) ((mRadius + Tools.dp2px(mContext, 10)) * Math.sin(Math.toRadians(mStartAngle + sweep)));
mPaint_2.setStyle(Paint.Style.FILL);
mPaint_2.setColor(0xffffffff);
mPaint_2.setMaskFilter(new BlurMaskFilter(Tools.dp2px(mContext, 3), BlurMaskFilter.Blur.SOLID));
canvas.drawCircle(x, y, Tools.dp2px(mContext, 3), mPaint_2);
canvas.restore();
}
private void drawScale(Canvas canvas) {
canvas.save();
float angle = (float) mSweepAngle / 30;//刻度间隔
canvas.rotate(-270 + mStartAngle);
for (int i = 0; i <= 30; i++) {
if (i % 6 == 0) {//画粗刻度和刻度值
mPaint.setStrokeWidth(Tools.dp2px(mContext, 2));
mPaint.setAlpha(0x70);
canvas.drawLine(0, -mRadius - mSweepInWidth / 2, 0, -mRadius + mSweepInWidth / 2 + Tools.dp2px(mContext, 1), mPaint);
drawText(canvas, i * mMaxNum / 30 + "", mPaint);
} else {
mPaint.setStrokeWidth(Tools.dp2px(mContext, 1));
mPaint.setAlpha(0x50);
canvas.drawLine(0, -mRadius - mSweepInWidth / 2, 0, -mRadius + mSweepInWidth / 2, mPaint);
}
if (i == 3 || i == 9 || i == 15 || i == 21 || i == 27) {
mPaint.setStrokeWidth(Tools.dp2px(mContext, 2));
mPaint.setAlpha(0x90);
drawText(canvas, texts[(i - 3) / 6], mPaint);
}
canvas.rotate(angle);
}
canvas.restore();
}
private void drawText(Canvas canvas, String str, Paint paint) {
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(Tools.sp2px(mContext, 8));
float textWidth = mPaint.measureText(str);
//下面方法获得的数据有字的长和高,但是数值是int型,在小字上会很不精确
// Rect rect = new Rect();
// mPaint.getTextBounds(str,0,str.length(),rect);
canvas.drawText(str, -textWidth / 2, -mRadius + Tools.dp2px(mContext, 15), mPaint);
paint.setStyle(Paint.Style.STROKE);
}
private void drawRound(Canvas canvas) {
canvas.save();
//内圆
mPaint.setAlpha(0x40);
mPaint.setStrokeWidth(mSweepInWidth);
RectF rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
canvas.drawArc(rectF, mStartAngle, mSweepAngle, false, mPaint);
//外圆
mPaint.setStrokeWidth(mSweepOutWidth);
int w = Tools.dp2px(mContext, 10);
RectF rectF1 = new RectF(-mRadius - w, -mRadius - w, mRadius + w, mRadius + w);
canvas.drawArc(rectF1, mStartAngle, mSweepAngle, false, mPaint);
canvas.restore();
}
}
|
package dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import entities.FestivalObj;
import hibernate.HibernateUtil;
public class FestivalDAO {
private SessionFactory factory=HibernateUtil.getSessionFactory();
Session session;
public FestivalDAO() {
}
@SuppressWarnings("unchecked")
public List<FestivalObj> selectAll(){
session=factory.getCurrentSession();
session.beginTransaction();
List<FestivalObj> list=new ArrayList<FestivalObj>();
list=(List<FestivalObj>) session.createQuery("from FestivalObj").getResultList();
session.close();
return list;
}
public FestivalObj selectByID(int ID) {
session=factory.getCurrentSession();
session.beginTransaction();
FestivalObj festival=null;
festival=(FestivalObj)session.get(FestivalObj.class, ID);
session.getTransaction().commit();
session.close();
return festival;
}
public int insert(String name,String genre,String description) {
session=factory.getCurrentSession();
session.beginTransaction();
int ID=0;
FestivalObj match=new FestivalObj(name,genre,description);
ID=(Integer) session.save(match);
session.getTransaction().commit();
session.close();
return ID;
}
public void update(int ID,String name,String genre,String description) {
session=factory.getCurrentSession();
session.beginTransaction();
FestivalObj fest=null;
fest=session.get(FestivalObj.class, ID);
if(name==null || name=="") {
fest.setName(fest.getName());
}
else {
fest.setName(name);
}
if(genre==null || genre=="") {
fest.setGenre(fest.getGenre());
}
else {
fest.setGenre(genre);
}
if(description==null || description=="") {
fest.setDescription(fest.getDescription());
}
else {
fest.setDescription(description);
}
session.getTransaction().commit();
session.close();
}
public void delete(int ID) {
session=factory.getCurrentSession();
session.beginTransaction();
FestivalObj match=null;
System.out.println(ID+"------------------");
//if(ID!=null) {
match=session.get(FestivalObj.class, ID);
session.delete(match);
session.getTransaction().commit();
//}
session.close();
}
public void closeConnection() {
factory.close();
}
}
|
package pl.lukabrasi.weatheronline.entities;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Data
@Table(name = "weather_user")
public class UserEntity {
private @Id
@GeneratedValue
int id;
private String login;
private String password;
private String email;
}
|
package action.com.logIn;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import pojo.businessObject.UserBO;
import tool.BeanFactory;
import tool.JSONHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by GR on 2017/4/15.
*/
public class getUserInfoAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, Object> session;
private JSONObject jsonObject;
@Override
public String execute() throws Exception {
UserBO userBO = BeanFactory.getBean("userBO",UserBO.class);
try {
jsonObject = userBO.getInfo(session);
System.out.println("jsonObject = " + jsonObject);
//43行调用的logIn已经对result赋值了?
// jsonObject.put("result", "success");
JSONHandler.sendJSON(jsonObject,response);
System.out.println("获取用户信息");
System.out.println(jsonObject);
return "success";
}catch(Exception e){
e.printStackTrace();
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
try {
this.request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
this.response.setCharacterEncoding("UTF-8");
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
}
|
package com.windtalker.ui.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import com.windtalker.dto.DTOContact;
import com.windtalker.ui.FragmentChat;
import com.windtalker.ui.FragmentContactDetails;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jaapo on 11-11-2017.
*/
public class PagerAdapterChannel extends FragmentStatePagerAdapter {
List<String> mChannelKeyList;
public PagerAdapterChannel(FragmentManager fragmentManager, DTOContact contact, List<String> channelKeyList) {
super(fragmentManager);
mChannelKeyList = new ArrayList<>(channelKeyList);
}
@Override
public Fragment getItem(int position) {
Log.e("position", "position: " + position );
if (position == 0) {
return new FragmentContactDetails();
}else {
return new FragmentChat();
}
}
@Override
public int getCount() {
return mChannelKeyList.size() + 1;
}
} |
package io.github.yanhu32.xpathkit.filter;
import io.github.yanhu32.xpathkit.utils.Strings;
/**
* 去除 XPath 表达式空格
*
* @author yh
* @since 2021/4/22
*/
public class SpaceXPathFilter implements XPathFilter {
@Override
public String filter(String xpath) {
return Strings.remove(xpath, " ");
}
}
|
package net.datacrow.console.windows.filerenamer;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.Layout;
import net.datacrow.console.components.DcLongTextField;
import net.datacrow.console.components.tables.DcTable;
import net.datacrow.console.menu.DcFileRenamerPreviewPopupMenu;
import net.datacrow.console.menu.FileRenamerMenu;
import net.datacrow.console.windows.DcDialog;
import net.datacrow.core.DcRepository;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.resources.DcResources;
import net.datacrow.filerenamer.FilePattern;
import net.datacrow.settings.DcSettings;
import net.datacrow.util.DcSwingUtilities;
public class FileRenamerPreviewDialog extends DcDialog implements ActionListener, MouseListener {
private DcTable table = ComponentFactory.getDCTable(true, false);
private JProgressBar progressBar = new JProgressBar();
private JButton buttonStart = ComponentFactory.getButton(DcResources.getText("lblStart"));
private JButton buttonCancel = ComponentFactory.getButton(DcResources.getText("lblCancel"));
private PreviewGenerator generator;
private FileRenamerDialog parent;
private boolean affirmative = false;
public FileRenamerPreviewDialog(FileRenamerDialog parent,
Collection<DcObject> objects,
FilePattern pattern,
File baseDir) {
super(parent);
this.parent = parent;
JMenu menu = new FileRenamerMenu(this);
JMenuBar menuBar = ComponentFactory.getMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setHelpIndex("dc.tools.filerenamer");
setTitle(DcResources.getText("lblFileRenamePreview"));
build(pattern.getModule());
generatePreview(objects, pattern, baseDir);
setSize(DcSettings.getDimension(DcRepository.Settings.stFileRenamerPreviewDialogSize));
setCenteredLocation();
setModal(true);
}
private void generatePreview(Collection<DcObject> items, FilePattern pattern, File baseDir) {
if (generator != null)
generator.cancel();
generator = new PreviewGenerator(this, items, pattern, baseDir);
generator.start();
}
protected void addPreviewResult(DcObject dco, String oldFilename, String newFilename) {
table.addRow(new Object[] {dco, oldFilename, newFilename});
}
protected void setBusy(boolean b) {
buttonStart.setEnabled(!b);
}
protected void initProgressBar(int max) {
progressBar.setValue(0);
progressBar.setMaximum(max);
}
protected void updateProgressBar() {
progressBar.setValue(progressBar.getValue() + 1);
}
public boolean isAffirmative() {
return affirmative;
}
public Collection<DcObject> getObjects() {
Collection<DcObject> items = new ArrayList<DcObject>();
for (int row = 0; row < table.getRowCount(); row++) {
items.add((DcObject) table.getValueAt(row, 0));
}
return items;
}
public void clear() {
DcSettings.set(DcRepository.Settings.stFileRenamerPreviewDialogSize, getSize());
table.clear();
table = null;
if (generator != null)
generator.cancel();
generator = null;
buttonCancel = null;
buttonStart = null;
progressBar = null;
parent = null;
super.close();
}
@Override
public void close() {
setVisible(false);
parent.notifyJobStopped();
if (generator != null)
generator.cancel();
}
private void build(int module) {
//**********************************************************
//Help panel
//**********************************************************
DcLongTextField textHelp = ComponentFactory.getLongTextField();
JPanel helpPanel = new JPanel();
helpPanel.setLayout(Layout.getGBL());
textHelp.setBorder(null);
JScrollPane scroller = new JScrollPane(textHelp);
scroller.setBorder(null);
scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
textHelp.setEditable(false);
textHelp.setText(DcResources.getText("msgFileRenamePreviewHelp"));
textHelp.setMargin(new Insets(5,5,5,5));
scroller.setPreferredSize(new Dimension(100, 60));
scroller.setMinimumSize(new Dimension(100, 60));
scroller.setMaximumSize(new Dimension(800, 60));
helpPanel.add(scroller, Layout.getGBC(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
//**********************************************************
//Preview panel
//**********************************************************
JPanel panelPreview = new JPanel();
table.setColumnCount(3);
TableColumn tcDescription = table.getColumnModel().getColumn(0);
JTextField textField = ComponentFactory.getTextFieldDisabled();
tcDescription.setCellEditor(new DefaultCellEditor(textField));
tcDescription.setHeaderValue(DcModules.get(module).getObjectName());
TableColumn tcOldFilename = table.getColumnModel().getColumn(1);
textField = ComponentFactory.getTextFieldDisabled();
tcOldFilename.setCellEditor(new DefaultCellEditor(textField));
tcOldFilename.setHeaderValue(DcResources.getText("lblOldFilename"));
TableColumn tcNewFilename = table.getColumnModel().getColumn(2);
textField = ComponentFactory.getTextFieldDisabled();
tcNewFilename.setCellEditor(new DefaultCellEditor(textField));
tcNewFilename.setHeaderValue(DcResources.getText("lblNewFilename"));
table.addMouseListener(this);
table.applyHeaders();
panelPreview.setLayout(Layout.getGBL());
panelPreview.add(new JScrollPane(table), Layout.getGBC( 0, 0, 5, 1, 10.0, 10.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new Insets( 5, 5, 5, 5), 0, 0));
// **********************************************************
//Action panel
//**********************************************************
JPanel panelAction = new JPanel();
buttonStart.setEnabled(false);
buttonStart.addActionListener(this);
buttonCancel.addActionListener(this);
buttonStart.setActionCommand("confirm");
buttonCancel.setActionCommand("cancel");
panelAction.add(buttonStart);
panelAction.add(buttonCancel);
//**********************************************************
//Main panel
//**********************************************************
this.getContentPane().setLayout(Layout.getGBL());
this.getContentPane().add(helpPanel, Layout.getGBC( 0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets( 5, 5, 5, 5), 0, 0));
this.getContentPane().add(panelPreview, Layout.getGBC( 0, 1, 1, 1, 10.0, 10.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new Insets( 5, 5, 5, 5), 0, 0));
this.getContentPane().add(panelAction, Layout.getGBC( 0, 2, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHEAST, GridBagConstraints.NONE,
new Insets( 5, 5, 5, 5), 0, 0));
this.getContentPane().add(progressBar, Layout.getGBC( 0, 3, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets( 5, 5, 5, 5), 0, 0));
pack();
}
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("confirm")) {
affirmative = true;
close();
} else if (ae.getActionCommand().equals("remove")) {
int[] rows = table.getSelectedRows();
if (rows != null && rows.length > 0)
table.remove(rows);
else
DcSwingUtilities.displayMessage("msgNoItemsSelectedToRemove");
} else if (ae.getActionCommand().equals("cancel")) {
close();
}
}
private static class PreviewGenerator extends Thread {
private Collection<DcObject> objects;
private FilePattern pattern;
private FileRenamerPreviewDialog dlg;
private File baseDir;
private boolean keepOnRunning = true;
public PreviewGenerator(FileRenamerPreviewDialog dlg,
Collection<DcObject> objects,
FilePattern pattern,
File baseDir) {
this.dlg = dlg;
this.objects = objects;
this.pattern = pattern;
this.baseDir = baseDir;
}
public void cancel() {
keepOnRunning = false;
}
@Override
public void run() {
dlg.initProgressBar(objects.size());
dlg.setBusy(true);
for (DcObject dco : objects) {
if (!keepOnRunning) break;
if (dco.getFilename() != null) {
File oldFile = new File(dco.getFilename());
String newFilename = pattern.getFilename(dco, oldFile, baseDir);
dlg.addPreviewResult(dco, oldFile.toString(), newFilename);
}
dlg.updateProgressBar();
}
dlg.setBusy(false);
objects = null;
pattern = null;
dlg = null;
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
DcFileRenamerPreviewPopupMenu popupmenu = new DcFileRenamerPreviewPopupMenu(this);
popupmenu.validate();
popupmenu.show(table, e.getX(), e.getY());
}
}
}
|
package com.crunchshop.resolver.mutation.user;
import com.crunchshop.resolver.mutation.MutationResolver;
import com.crunchshop.service.UserService;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class CreateUserMutation implements MutationResolver {
public static final String METHOD_NAME = "createUser";
@Autowired
UserService userService;
public String getSchemaMethodName() {
return METHOD_NAME;
}
@Override
public Object get(DataFetchingEnvironment env) {
// FIGURE OUT A GOOD WAY TO DO INPUT VALIDATION HERE!!!
Map<String, Object> input = env.getArgument("input");
String name = (String) input.get("name");
String email = (String) input.get("email");
return userService.create(name, email);
}
}
|
package com.sola.webdemo;
import com.sola.webdemo.kafka.Producer;
import com.sola.webdemo.kafka.SampleMessage;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@EnableAutoConfiguration
@MapperScan(basePackages = "com.sola.webdemo.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//kafka发送消息
// @Bean
public ApplicationRunner runner(Producer producer) {
producer.send(new SampleMessage(1, "A simple test message"));
return null;
}
}
|
import java.util.Scanner;
public class ConversosDeNumeros {
public static void main(String[] args) {
int menu = 0;
Scanner entrada = new Scanner(System.in);
System.out.println("--------------------------");
System.out.println("---CONVERSOR DE NUMEROS---");
System.out.println("--------------------------");
System.out.println();
System.out.println("Seleccione la forma de conversion");
System.out.println("1-Convertir de Arabigo a Romano");
System.out.println("2-Convertir de Romano a Arabigo");
menu = entrada.nextInt();
switch(menu){
case 1:
//CONVERSOR DE ARABIGO A ROMANO
ArabigoRomano();
break;
case 2:
//CONVERSOR DE ROMANO A ARABIGO
RomanoArabigo();
break;
default:
System.out.println("Finalizo el programa");
break;
}
}
static void ArabigoRomano(){
int u;//Unidades
int d;//Decenas
int c;//Centenas
int temp = 0;
int num;//Numero
Scanner entrada = new Scanner(System.in);
String[] unidad = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
String[] decena = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
//String centena = "C";
//System.out.println("---------------------------------------");
//System.out.println("-Ingrese el numero que desea convertir-");
//System.out.println("---------------------------------------");
do{
System.out.println("---------------------------------------");
System.out.println("-Ingrese el numero que desea convertir-");
System.out.println("---------------------------------------");
num = entrada.nextInt();
if(num == 100){
System.out.println("C");
break;
}
}while(num < 0 || num > 101);
u = num % 10;
num /= 10;
d = num % 10;
num /= 10;
for (int i=0;i < decena.length; i++){
if (d == 9) {
System.out.printf("%s", decena[8]);
break;
}else if (d == i && d != 0) {
temp = i - 1;
System.out.printf("%s", decena[temp]);
}
}
for (int i=0;i < unidad.length; i++){
if (u == 9) {
System.out.printf("%s", unidad[8]);
break;
}else
if (u == i && u != 0) {
temp = i - 1;
System.out.printf("%s", unidad[temp]);
}
}
}
static void RomanoArabigo(){
String[] numRomanos = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
"XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI",
"XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX", "XXXI",
"XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL",
"XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L", "LI",
"LII", "LIII", "LIV", "LV", "LVI", "LVII", "LVIII", "LIX", "LX", "LXI", "LXII", "LXIII",
"LXIV", "LXV", "LXVI", "LXVII", "LXVIII", "LXIX", "LXX", "LXXI", "LXXII", "LXXIII", "LXXIV",
"LXXV", "LXXVI", "LXXVII", "LXXVIII", "LXXIX", "LXXX", "LXXXI", "LXXXII", "LXXXIII", "LXXXIV",
"LXXXV", "LXXXVI", "LXXXVII", "LXXXVIII", "LXXXIX", "XC", "XCI", "XCII", "XCIII", "XCIV", "XCV",
"XCVI", "XCVII", "XCVIII", "XCIX", "C"};
String num;
Scanner entrada = new Scanner(System.in);
System.out.println("---------------------------------------");
System.out.println("-Ingrese el numero que desea convertir-");
System.out.println("---------------------------------------");
num = entrada.nextLine();
for(int i=0; i<100;i++){
if(num.equalsIgnoreCase(numRomanos[i])){
i+=1;
System.out.println(i);
break;
}
}
}
}
|
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.pooling;
import java.io.Serializable;
/**
* @author douglas
* @since 20/03/2017
*/
public class PoolingCol1DTO implements Serializable {
private static final long serialVersionUID = 3544325374927970582L;
private PoolingCol1CreditRequestDTO creditrequest;
public PoolingCol1CreditRequestDTO getCreditrequest() {
return creditrequest;
}
public void setCreditrequest(PoolingCol1CreditRequestDTO creditrequest) {
this.creditrequest = creditrequest;
}
}
|
package org.cronhub.managesystem.commons.dao.bean;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Daemon {
private Long id;
private String machine_ip;
private Integer machine_port;
private String daemon_version_name;
private Boolean must_lostconn_email;
private String lostconn_emailaddress;
private Boolean conn_status;
private String comment;
private Date update_time;
/**
*
*/
private Integer task_count;
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
public Boolean getMust_lostconn_email() {
return must_lostconn_email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMachine_ip() {
return machine_ip;
}
public void setMachine_ip(String machine_ip) {
this.machine_ip = machine_ip;
}
public Integer getMachine_port() {
return machine_port;
}
public void setMachine_port(Integer machine_port) {
this.machine_port = machine_port;
}
public String getDaemon_version_name() {
return daemon_version_name;
}
public void setDaemon_version_name(String daemon_version_name) {
this.daemon_version_name = daemon_version_name;
}
public String getLostconn_emailaddress() {
return lostconn_emailaddress;
}
public void setLostconn_emailaddress(String lostconn_emailaddress) {
this.lostconn_emailaddress = lostconn_emailaddress;
}
public Boolean getConn_status() {
return conn_status;
}
public void setConn_status(Boolean conn_status) {
this.conn_status = conn_status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Boolean isMust_lostconn_email() {
return must_lostconn_email;
}
public void setMust_lostconn_email(Boolean must_lostconn_email) {
this.must_lostconn_email = must_lostconn_email;
}
public Integer getTask_count() {
return task_count;
}
public void setTask_count(Integer task_count) {
this.task_count = task_count;
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.clusterjtestapp;
import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;
@PersistenceCapable(table = "employee")
@Index(name = "idx_uhash")
public interface Employee {
@PrimaryKey
int getId();
void setId(int id);
String getFirst();
void setFirst(String first);
String getLast();
void setLast(String last);
@Column(name = "municipality")
@Index(name = "idx_municipality")
String getCity();
void setCity(String city);
String getStarted();
void setStarted(String date);
String getEnded();
void setEnded(String date);
Integer getDepartment();
void setDepartment(Integer department);
} |
package com.shady.finalc;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity3 extends AppCompatActivity {
int lavaQtt =0 , greenQtt=0, pumQtt=0;
String theReceipt , lavaIn = " " , greenIn= " ", pumIn= " ", total = " ";
TextView receipt , lavaQ,greenQ,pumQ;
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
lavaQ = findViewById(R.id.lavaQ);
greenQ = findViewById(R.id.greenQ);
pumQ = findViewById(R.id.pumQ);
receipt = findViewById(R.id.receipt);
}
public void toPay (View v){
if((lavaQtt+greenQtt+pumQtt)==0){
Toast.makeText(this,"You didn't chose anything!",Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(this,MainActivity4.class);
i.putExtra("key",theReceipt);
startActivity(i);
}
}
public void lavaAdd(View v){
lavaQtt++;
lavaInRec();
Toast.makeText(this,good(),Toast.LENGTH_SHORT).show();
}
public void lavaMin(View v){
if(lavaQtt>0){
lavaQtt--;
Toast.makeText(this,bad(),Toast.LENGTH_SHORT).show();
}
lavaInRec();
}
public void lavaInRec(){
lavaQ.setText(String.valueOf(lavaQtt));
if(lavaQtt>0){
lavaIn = "\n 1- Lava Chips X "+ lavaQtt +"\n" + lavaQtt + " X 6.00$ = " + (lavaQtt*6)+".00";
}else{
lavaIn = " ";
}
setReceipt();
}
public void greenAdd(View v){
greenQtt++;
greenInRec();
Toast.makeText(this,good(),Toast.LENGTH_SHORT).show();
}
public void greenMin(View v){
if(greenQtt>0){
greenQtt--;
Toast.makeText(this,bad(),Toast.LENGTH_SHORT).show();
}
greenInRec();
}
public void greenInRec(){
greenQ.setText(String.valueOf(greenQtt));
if(greenQtt>0){
greenIn = "\n \n 2- Green Salad X "+ greenQtt +"\n" + greenQtt + " X 7.00$ = " + (greenQtt*7)+".00";
}else{
greenIn = " ";
}
setReceipt();
}
public void pumAdd(View v){
pumQtt++;
pumInRec();
Toast.makeText(this,good(),Toast.LENGTH_SHORT).show();
}
public void pumMin(View v){
if(pumQtt>0){
pumQtt--;
Toast.makeText(this,bad(),Toast.LENGTH_SHORT).show();
}
pumInRec();
}
public void pumInRec(){
pumQ.setText(String.valueOf(pumQtt));
if(pumQtt>0){
pumIn = "\n \n 3- Pum Salad X "+pumQtt +"\n" + pumQtt + " X 8.00$ = " + (pumQtt*8)+".00";
}else{
pumIn = " ";
}
setReceipt();
}
public void setReceipt(){
total = "Total = "+((lavaQtt * 6) + (greenQtt * 7) + (pumQtt*8) ) + " CAD$";
theReceipt ="Your Order:\n"+lavaIn+greenIn+pumIn + "\n________________ \n \n"+total;
receipt.setText(theReceipt);
}
public native String bad();
public native String good();
} |
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import models.Cliente;
public class ClienteDAO {
private static Cliente extractClienteFromRs(ResultSet rs) throws SQLException {
return new Cliente(
rs.getInt("idCliente"),
rs.getString("nome"),
rs.getString("telefone1"),
rs.getString("telefone2"),
rs.getString("logradouro"),
rs.getInt("numero"),
rs.getString("bairro"),
rs.getString("cidade"),
rs.getString("referencia")
);
}
public static void insertCliente(Cliente cliente) {
try {
Connection conn = DriverManager.getConnection(DAOPaths.dbPath);
String sql = "INSERT INTO cliente(nome, telefone1, telefone2, logradouro, numero, bairro, cidade, referencia) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, cliente.getNome());
ps.setString(2, cliente.getTelefone1());
ps.setString(3, cliente.getTelefone2());
ps.setString(4, cliente.getLogradouro());
ps.setInt(5, cliente.getNumero());
ps.setString(6, cliente.getBairro());
ps.setString(7, cliente.getCidade());
ps.setString(8, cliente.getReferencia());
ps.executeUpdate();
conn.close();
JOptionPane.showMessageDialog(null, "Cliente cadastrado com sucesso", "Informação", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException ex) {
Logger.getLogger(EntregaDAO.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Erro na inserção do cliente", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static ArrayList<Cliente> selectTodosClientes() {
try {
Connection conn = DriverManager.getConnection(DAOPaths.dbPath);
Statement stmt = conn.createStatement();
ResultSet rs;
ArrayList<Cliente> arrayClientes = new ArrayList<>();
rs = stmt.executeQuery("SELECT * FROM cliente");
while (rs.next()) {
arrayClientes.add(extractClienteFromRs(rs));
}
conn.close();
return arrayClientes;
} catch (SQLException ex) {
Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Erro na seleção", "Error", JOptionPane.ERROR_MESSAGE);
}
return null;
}
public static void updateCliente(Cliente cliente) {
try {
Connection conn = DriverManager.getConnection(DAOPaths.dbPath);
String sql = "UPDATE cliente SET nome = ?, telefone1 = ?, telefone2 = ?, logradouro = ?, numero = ?, bairro = ?, cidade = ?, referencia = ? WHERE idCliente = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, cliente.getNome());
ps.setString(2, cliente.getTelefone1());
ps.setString(3, cliente.getTelefone2());
ps.setString(4, cliente.getLogradouro());
ps.setInt(5, cliente.getNumero());
ps.setString(6, cliente.getBairro());
ps.setString(7, cliente.getCidade());
ps.setString(8, cliente.getReferencia());
ps.setInt(9, cliente.getIdCliente());
ps.executeUpdate();
conn.close();
JOptionPane.showMessageDialog(null, "Cliente atualizado com sucesso", "Informação", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException ex) {
Logger.getLogger(EntregaDAO.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Erro na inserção do cliente", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
|
package com.t11e.discovery.datatool;
import org.springframework.jdbc.core.RowCallbackHandler;
public interface CompletionAwareRowCallbackHandler
extends RowCallbackHandler
{
void flushItem();
}
|
package com.ipincloud.iotbj.vehicle.service;
import com.alibaba.fastjson.JSONObject;
public interface VehicleService {
Object syncVehicleDevice(JSONObject jsonObj);
Object vehiclegateadd(JSONObject jsonObj);
Object vehiclegateopen(JSONObject jsonObj);
}
|
package Model.Statement;
import Model.ADT.IDictionary;
import Model.ADT.IStack;
import Model.Exception.ToyException;
import Model.ProgramState.ProgramState;
import Model.Type.Type;
public class CompStatement implements IStatement{
private IStatement firstStmt;
private IStatement secondStmt;
public CompStatement(IStatement first, IStatement second){
firstStmt = first;
secondStmt = second;
}
public String toString(){
return firstStmt.toString() + "; " + secondStmt.toString();
}
@Override
public ProgramState execute(ProgramState state) throws ToyException{
IStack<IStatement> stk = state.getExeStack();
stk.push(secondStmt);
stk.push(firstStmt);
return null;
}
@Override
public IDictionary<String, Type> typeCheck(IDictionary<String, Type> typeEnv) {
return secondStmt.typeCheck(firstStmt.typeCheck(typeEnv));
}
@Override
public IStatement deepCopy() {
return new CompStatement(firstStmt.deepCopy(), secondStmt.deepCopy());
}
}
|
package com.igalata.viewpager.ui;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import com.igalata.viewpager.model.MyFragmentPagerAdapter;
import com.igalata.viewpager.R;
public class MainActivity extends FragmentActivity {
ViewPager pager;
PagerAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), 10);
pager.setAdapter(pagerAdapter);
}
} |
package com.robin.springboot.demo.java_random;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;
public class Test {
public static void main(String[] args) {
// for(int i = 0; i < 100; i++){
// BigDecimal a = getRandom(0.31, 0.71);
// System.out.println(a);
// }
System.out.println(new Date(1545119611761L));
// System.out.println(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN));
}
private static void test(){
double d = 5.333;
int b = (int) Math.ceil(d);
System.out.println( b);
int a = (int) Math.floor(d);
System.out.println( a);
System.out.println((int) 2.999999999);
}
private static BigDecimal getRandom(double min, double max) {
if (min == max) {
return new BigDecimal(String.valueOf(min)).setScale(2, BigDecimal.ROUND_DOWN);
}
int minInt = (int) (min * 100);
int maxInt = (int) (max * 100);
Random random = new Random();
int result = random.nextInt(maxInt - minInt + 1) + minInt;
return BigDecimalUtils.mul(result, 0.01);
}
}
|
package example.mapbox.sla.mapboxdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
import com.mapbox.mapboxsdk.style.layers.PropertyFactory;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import java.util.ArrayList;
import java.util.List;
public class AddPolylineActivity extends AppCompatActivity {
MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_polyline);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Add polyline");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
mapView = findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState); //This is essential for mapbox to work
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
mapboxMap.setStyle(Constants.DEFAULT_BASEMAP_URL, new Style.OnStyleLoaded() { //SET CUSTOM BASE MAP URL
@Override
public void onStyleLoaded(@NonNull Style style) {
List<Point> routeCoordinates = new ArrayList<>();
routeCoordinates.add(Point.fromLngLat(103.711346, 1.405050));
routeCoordinates.add(Point.fromLngLat(103.925236, 1.334003));
LineString lineString = LineString.fromLngLats(routeCoordinates);
FeatureCollection featureCollection =
FeatureCollection.fromFeatures(new Feature[]{Feature.fromGeometry(lineString)});
GeoJsonSource geoJsonSource = new GeoJsonSource("LAYER_SOURCE_ID", featureCollection);
mapboxMap.getStyle().addSource(geoJsonSource);
LineLayer lineLayer = new LineLayer("LINE_LAYER_ID", "LAYER_SOURCE_ID");
lineLayer.setProperties(
PropertyFactory.lineColor(Color.RED),
PropertyFactory.fillOpacity(1f));
mapboxMap.getStyle().addLayer(lineLayer);
}
});
}
});
}
//........................................
//Do not remove, essential to use Mapbox
//........................................
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
//........................................
}
|
package com.tdr.registrationv3.bean;
import java.util.List;
public class CityBean {
/**
* cityCode : 4101
* unitName : 郑州市
* fullSpell : Zhengzhou
* abbrSpell : ZZ
* subsystemList : [{"id":1,"subsystemName":"1223"},{"id":4,"subsystemName":"新增测试子系统1"},{"id":6,"subsystemName":"子系统1"}]
*/
private String cityCode;
private String unitName;
private String fullSpell;
private String abbrSpell;
private List<SubsystemListBean> subsystemList;
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getFullSpell() {
return fullSpell;
}
public void setFullSpell(String fullSpell) {
this.fullSpell = fullSpell;
}
public String getAbbrSpell() {
return abbrSpell;
}
public void setAbbrSpell(String abbrSpell) {
this.abbrSpell = abbrSpell;
}
public List<SubsystemListBean> getSubsystemList() {
return subsystemList;
}
public void setSubsystemList(List<SubsystemListBean> subsystemList) {
this.subsystemList = subsystemList;
}
public static class SubsystemListBean {
/**
* id : 1
* subsystemName : 1223
*/
private int id;
private String subsystemName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubsystemName() {
return subsystemName;
}
public void setSubsystemName(String subsystemName) {
this.subsystemName = subsystemName;
}
}
}
|
/*
* Units.java
*
* Created on December 11, 2003, 10:10 AM
*/
package com.pcauto.util;
/**
*
* @author genec
*/
public abstract class Units implements java.io.Serializable {
public int getId() {
return id;
}
public String getString() {
return str;
}
public String getDesc() {
return desc;
}
public String toString() {
return getDesc();
}
public abstract Units[] getAll();
public abstract double convertFrom(double value, Units srcUnits);
/** Creates a new instance of Units */
protected Units(String str, String desc) {
this.str = str;
this.desc = desc;
}
protected String str;
protected String desc;
protected int id;
}
|
package mihau.eu.githubsearch;
import android.app.Activity;
import com.facebook.stetho.Stetho;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.DaggerApplication;
import mihau.eu.githubsearch.di.component.AppComponent;
import mihau.eu.githubsearch.di.component.DaggerAppComponent;
import mihau.eu.githubsearch.di.module.AppModule;
import mihau.eu.githubsearch.di.module.RestModule;
public class GitHubApplication extends DaggerApplication {
@Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Stetho.initializeWithDefaults(this);
}
}
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
AppComponent appComponent = DaggerAppComponent
.builder()
.application(this)
.appModule(new AppModule(this))
.restModule(new RestModule())
.build();
appComponent.inject(this);
return appComponent;
}
}
|
package com.dassa.vo;
public class DriverApplyImgVO {
//MOVE_APPLY_IMG_TBL
private int imgIdx; //이미지 인덱스번호
private String imgName; //이미지 이름 (사용자가 올린거)
private String imgPath; //이미지 경로 (사용자가 올린거)
public DriverApplyImgVO(int imgIdx, String imgName, String imgPath) {
super();
this.imgIdx = imgIdx;
this.imgName = imgName;
this.imgPath = imgPath;
}
public DriverApplyImgVO() {
super();
}
public int getImgIdx() {
return imgIdx;
}
public void setImgIdx(int imgIdx) {
this.imgIdx = imgIdx;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
}
|
package mx.com.otss.saec.acceso;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import mx.com.otss.saec.R;
import mx.com.otss.saec.menu_inferior.PrincipalActivity;
public class PortadaActivity extends AppCompatActivity {
private TextView btnIngresar,btnSalir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portada);
btnIngresar = (TextView)findViewById(R.id.txt_portada_acceder);
btnSalir = (TextView)findViewById(R.id.txt_portada_salir);
btnIngresar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PrincipalActivity.class);
finish();
startActivity(intent);
}
});
btnSalir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
|
package examples;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile {
private static Formatter output;
public static void main(String[] args) {
openFile();
addRecord();
closeFile();
}
public static void openFile() {
try {
output = new Formatter("clients.txt");
}catch(SecurityException securityEx) {
System.err.println("Write permission denied. Terminating...");
System.exit(1);
}catch(FileNotFoundException fileNotFound) {
System.err.println("Error opening file. Terminating...");
System.exit(1);
}
}
public static void addRecord() {
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ","Enter account number, first name, last name, and balance", "Enter end-of-file insicator to end input");
while(input.hasNext()) {
try {
output.format("%d %s %s %.2f%n", input.nextInt(), input.next(), input.next(), input.nextDouble());
}catch(FormatterClosedException formatEx) {
System.err.println("Error writing to file. Terminating...");
break;
}catch(NoSuchElementException ex) {
// ex.printStackTrace();
System.err.println("Invalid input. please try again.");
input.nextLine();
}
System.out.print("? ");
}
}
public static void closeFile() {
if(output != null)
output.close();
}
}
|
package com.example.sembi.logingui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.util.LinkedList;
import static com.example.sembi.logingui.StaticMethods.ADDRESS_INDEX;
import static com.example.sembi.logingui.StaticMethods.ADD_KID_INDEX;
import static com.example.sembi.logingui.StaticMethods.ADD_PARENT_INDEX;
import static com.example.sembi.logingui.StaticMethods.ADD_PARTNER_INDEX;
import static com.example.sembi.logingui.StaticMethods.BDAY_INDEX;
import static com.example.sembi.logingui.StaticMethods.CITY_INDEX;
import static com.example.sembi.logingui.StaticMethods.EMAIL_INDEX;
import static com.example.sembi.logingui.StaticMethods.NAME_INDEX;
import static com.example.sembi.logingui.StaticMethods.PHONE_INDEX;
import static com.example.sembi.logingui.StaticMethods.famFields;
import static com.example.sembi.logingui.StaticMethods.get;
import static com.example.sembi.logingui.StaticMethods.getFamilyMembers;
import static com.example.sembi.logingui.StaticMethods.prepareStringToDataBase;
import static com.example.sembi.logingui.StaticMethods.valueEventListenerAndRefLinkedList;
public class Profile extends AppCompatActivity {
//Set TV & ET array length to thr NUMBER_OF_PARAMETERS
final static int NUMBER_OF_PARAMETERS = 6;
private TextView[] TextDataArray;
private EditText[] EditTextDataArray;
//Flag - enable/disable editing
static Boolean EDIT_MODE = false;
//Flag - if true, will set EDIT_MODE to true
private static boolean firstTime = true;
//Flag - if true, will set EDIT_MODE to false
private static boolean secondTime = true;
private LinkedList<String> requestSentTo;
private LinkedList<String> kids;
private LinkedList<String> parents;
private String partner;
//Set what user to show
private String currentUser;
private String[] publicData;
private Button[] RequestButtonsArray;
//for uploading image
private static int RESULT_LOAD_IMAGE = 1;
private ImageView profileImage;
private ImageView goToHomeBtn;
private ImageView editIcon;
private Spinner phoneSpinner, bdaySpinner, citySpinner, addressSpinner;
private FirebaseAuth mAuth;
private LinkedList<String> allUsers;
private LinkedList<DataSnapshot> allRequests;
private LinkedList<DataSnapshot> allPermissions;
private boolean shownUsrIsCurrentUsr;
private boolean replacedPhoto;
private ProfileModel profileData;
//for adding media
private StorageReference mStorageRef;
private Class nextClass;
private LinkedList<String> alertsShownKeys;
private boolean bUploadingPhoto;
private void setCurrentUserToMyUser() {
currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
String usrToShow; //get from putExtra
Intent intent = getIntent();
usrToShow = intent.getExtras().getString("USER_MAIL");
if (usrToShow != null
&& prepareStringToDataBase(usrToShow).equals(
prepareStringToDataBase(
FirebaseAuth.getInstance().getCurrentUser().getEmail()
)
)
) {
setCurrentUserToMyUser();
shownUsrIsCurrentUsr = true;
} else {
currentUser = usrToShow;
shownUsrIsCurrentUsr = false;
}
replacedPhoto = false;
bUploadingPhoto = false;
publicData = new String[NUMBER_OF_PARAMETERS];
alertsShownKeys = new LinkedList<>();
setSpinners();
allPermissions = new LinkedList<>();
profileImage = findViewById(R.id.profile_imageView);
//for safety
allUsers = new LinkedList<>();
allRequests = new LinkedList<>();
requestSentTo = new LinkedList<>();
kids = new LinkedList<>();
parents = new LinkedList<>();
partner = null;
mAuth = FirebaseAuth.getInstance();
profileData = new ProfileModel();
setMyUserName();
//uploading img
FirebaseStorage storage = FirebaseStorage.getInstance();
mStorageRef = storage.getReference();
editIcon = findViewById(R.id.editImageV_Button_);
if (!shownUsrIsCurrentUsr) {
editIcon.setVisibility(View.GONE);
}
goToHomeBtn = findViewById(R.id.backHomeBtn);
TextDataArray = new TextView[NUMBER_OF_PARAMETERS];
EditTextDataArray = new EditText[NUMBER_OF_PARAMETERS];
RequestButtonsArray = new Button[3];
//initialize =>
setRequestButtonsArray();
setTextDataArrray();
setEditTextDataArrray();
setDataUpdaterFromDataBase();
setPublicDataUpdaterFromDataBase();
setFamilyDataUpdaterFromDataBase();
setAllUsersListener();
setDateListener();
setRequestsListener();
setPermissionsListener();
setProfileImageFromStorage();
}
private void setProfileImageFromStorage() {
String mail = currentUser;
if (shownUsrIsCurrentUsr)
mail = mAuth.getCurrentUser().getEmail();
StorageReference ref = FirebaseStorage.getInstance().getReference().child(getString(R.string.profile_images))
.child(prepareStringToDataBase(mail) + ".jpg");
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
int resizeTO = 180;
Picasso.get()
.load(uri)
.error(getDrawable(R.drawable.logo))
.into(profileImage);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
profileImage.setImageDrawable(getDrawable(R.drawable.logo_with_white));
profileImage.setAdjustViewBounds(true);
}
});
}
private void setFamilyDataUpdaterFromDataBase() {
String mail = currentUser;
if (shownUsrIsCurrentUsr)
mail = mAuth.getCurrentUser().getEmail();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mail))
.child("fam");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
setFamilyDataFromDataBase(dataSnapshot);
setTopButtons();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
ref.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(ref, valueEventListener));
}
private void setFamilyDataFromDataBase(DataSnapshot dataSnapshot) {
setRequestsSentToListFromDataBase(dataSnapshot.child("requestsSentTo"));
setKidsFromDataBase(dataSnapshot.child("kids"));
setParentsFromDataBase(dataSnapshot.child("parents"));
setPartnerFromDataBase(dataSnapshot.child("partner"));
}
private void setPartnerFromDataBase(DataSnapshot partner) {
this.partner = partner.getValue(String.class);
}
private void setParentsFromDataBase(DataSnapshot parents) {
this.parents = new LinkedList<>();
for (DataSnapshot ds : parents.getChildren()) {
this.parents.add(ds.getValue().toString());
}
}
private void setKidsFromDataBase(DataSnapshot kids) {
this.kids = new LinkedList<>();
for (DataSnapshot ds : kids.getChildren()) {
this.kids.add(ds.getValue().toString());
}
}
private void setTopButtons() {
if (shownUsrIsCurrentUsr)
return;
RequestButtonsArray[ADD_KID_INDEX].setText("Add as a\nkid");
RequestButtonsArray[ADD_PARENT_INDEX].setText("Add as a\nparent");
RequestButtonsArray[ADD_PARTNER_INDEX].setText("Add as a\npartner");
LinkedList<String> mailList = new LinkedList<>();
for (ProfileModel pm : getFamilyMembers(mAuth.getCurrentUser().getEmail(), 1)) {
mailList.add(pm.getEmail());
}
if (mailList.contains(currentUser)) {
String myEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
TextView relationText = findViewById(R.id.profileRelationTextView);
relationText.setVisibility(View.VISIBLE);
if (kids.contains(myEmail))
relationText.setText("My Parent");
if (parents.contains(myEmail))
relationText.setText("My Kid");
if (partner != null && partner.equals(myEmail))
relationText.setText("My Love");
LinkedList<ProfileModel> brothersModels = get(currentUser, famFields.brothers);
for (ProfileModel pm : brothersModels) {
if (pm.getEmail().equals(myEmail))
relationText.setText("My Sibling");
}
for (Button b : RequestButtonsArray)
b.setVisibility(View.GONE);
}
}
private void setRequestsListener() {
if (!shownUsrIsCurrentUsr)
return;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference myRef = db.getReference().child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam").child("requests");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
handleRequests(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
};
myRef.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(myRef, valueEventListener));
}
private void handleRequests(DataSnapshot dataSnapshot) {
allRequests = new LinkedList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
allRequests.add(ds);
}
if (allRequests.size() > 0) {
showRequests();
}
}
private void showRequests() {
for (final DataSnapshot s : allRequests) {
if (!alertsShownKeys.contains(s.getKey()) && s.child("connection").getValue() != null) {
alertsShownKeys.add(s.getKey());
final String email = s.child("email").getValue().toString();
final String connection = s.child("connection").getValue().toString();
final String name = s.child("name").getValue().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("is " + name + " your " + connection + "? (" + email + ")");
// Set up the buttons
builder.setNeutralButton("Show Profile", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Profile.this, Profile.class);
intent.putExtra(getString(R.string.profile_extra_mail_tag), email);
startActivity(intent);
}
});
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!allUsers.contains(email)) {
Toast.makeText(Profile.this,
"user doesn't exists anymore",
Toast.LENGTH_LONG).show();
s.getRef().removeValue();
return;
}
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(email))
.child("fam")
.child("permissions").push();
ref.child("email")
.setValue(mAuth.getCurrentUser().getEmail());
ref.child("name")
.setValue(profileData.getName());
if (connection.equals("parent")) {
ref.child("connection")
.setValue("kid");
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("parents").push();
newMember.setValue(email);
} else if (connection.equals("kid")) {
ref.child("connection")
.setValue("parent");
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("kids").push();
newMember.setValue(email);
} else {
ref.child("connection")
.setValue("partner");
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("partner");
newMember.setValue(email);
}
removeRequestSentTo(email);
s.getRef().removeValue();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
removeRequestSentTo(email);
s.getRef().removeValue();
}
});
builder.show();
}
}
}
private void handlePermissions(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
boolean flag = true;
for (DataSnapshot ds2 : allPermissions) {
if (ds2.getKey().equals(ds.getKey()))
flag = false;
}
if (flag) {
allPermissions.add(ds);
i++;
}
}
if (i > 0 && allPermissions.size() > 0) {
showPermissions();
}
}
private void setPermissionsListener() {
if (!shownUsrIsCurrentUsr)
return;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference myRef = db.getReference().child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam").child("permissions");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
handlePermissions(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
};
myRef.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(myRef, valueEventListener));
}
private void setAllUsersListener() {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference myRef = db.getReference().child("allUsers");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
setAllUsersLL(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
};
myRef.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(myRef, valueEventListener));
}
private void setAllUsersLL(DataSnapshot dataSnapshot) {
allUsers = new LinkedList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
allUsers.add(ds.getValue().toString());
}
}
private void setSpinners() {
phoneSpinner = findViewById(R.id.phoneSpinner);
bdaySpinner = findViewById(R.id.bdaySpinner);
citySpinner = findViewById(R.id.citySpinner);
addressSpinner = findViewById(R.id.addressSpinner);
if (!shownUsrIsCurrentUsr) {
phoneSpinner.setVisibility(View.GONE);
bdaySpinner.setVisibility(View.GONE);
citySpinner.setVisibility(View.GONE);
addressSpinner.setVisibility(View.GONE);
return;
}
setSpinner(phoneSpinner);
setSpinner(bdaySpinner);
setSpinner(citySpinner);
setSpinner(addressSpinner);
}
private void setSpinner(Spinner spinner) {
ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(this, R.array.privacyOptions, android.R.layout.simple_spinner_item);
spinner.setAdapter(arrayAdapter);
}
private void showPermissions() {
for (final DataSnapshot s : allPermissions) {
if (!alertsShownKeys.contains(s.getKey()) && s.child("connection").getValue() != null) {
alertsShownKeys.add(s.getKey());
final String email = s.child("email").getValue().toString();
final String connection = s.child("connection").getValue().toString();
final String name = s.child("name").getValue().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(name + " accepted your request");
// Set up the buttons
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!allUsers.contains(email)) {
Toast.makeText(Profile.this,
"user doesn't exists anymore",
Toast.LENGTH_LONG).show();
s.getRef().removeValue();
return;
}
if (connection.equals("parent")) {
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("parents").push();
newMember.setValue(email);
} else if (connection.equals("kid")) {
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("kids").push();
newMember.setValue(email);
//TODO sendKid_newParentRequest(email, partner);
} else if (connection.equals("kid")) {
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("parents").push();
newMember.setValue(email);
} else {
DatabaseReference newMember = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child("fam")
.child("partner"); //TODO add date to know who's the current partner
newMember.setValue(email);
}
allPermissions.remove(s);
s.getRef().removeValue();
}
});
builder.show();
}
}
}
private void setPrivacy(int i, String privacy) {
String[] titles = {"phone", "email", "date", "city", "adress", "name"};
String[] data = {profileData.getPhone(), profileData.getEmail(), profileData.getDate(), profileData.getCity(), profileData.getAddress(), profileData.getName()};
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
databaseReference = databaseReference.child("publicUsers").child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail())).child("personalData");
if (privacy.equals("Only me"))
databaseReference.child(titles[i]).setValue("");
else if (privacy.equals("My family"))
databaseReference.child(titles[i]).setValue("%f" + data[i]);
else if (privacy.equals("Everyone"))
databaseReference.child(titles[i]).setValue(data[i]);
}
private void setDateListener() {
EditTextDataArray[3].addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String s = EditTextDataArray[3].getText().toString();
if (s.length() == 3 && s.charAt(2) != '/')
EditTextDataArray[3].setText(s.substring(0, 2) + "/" + s.charAt(2));
else if (s.length() == 6 && s.charAt(5) != '/')
EditTextDataArray[3].setText(s.substring(0, 5) + "/" + s.charAt(5));
else if (s.length() > 10)
EditTextDataArray[3].setText(s.substring(0, 10));
EditTextDataArray[3].setSelection(EditTextDataArray[3].getText().length());
}
@Override
public void afterTextChanged(Editable editable) {
if (EditTextDataArray[3].getText().toString().length() != 10)
EditTextDataArray[3].setTextColor(Color.RED);
else
EditTextDataArray[3].setTextColor(Color.BLACK);
}
});
}
public void setMyUserName() {
if (currentUser == null)
setCurrentUserToMyUser();
}
private void setDataUpdaterFromDataBase() {
if (!shownUsrIsCurrentUsr) {
//a different user
return;
}
FirebaseDatabase databaseRef = FirebaseDatabase.getInstance();
DatabaseReference myRef = databaseRef
.getReference("users")
.child(currentUser)
.child("personalData");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
setDataUpdaterFromDataBase(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
};
myRef.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(myRef, valueEventListener));
}
//will work only if shownUsrIsCurrentUsr == true
private void setDataUpdaterFromDataBase(DataSnapshot dataSnapshot) {
profileData.setName(dataSnapshot.getValue(ProfileModel.class).getName());
profileData.setAddress(dataSnapshot.getValue(ProfileModel.class).getAddress());
profileData.setCity(dataSnapshot.getValue(ProfileModel.class).getCity());
profileData.setDate(dataSnapshot.getValue(ProfileModel.class).getDate());
profileData.setEmail(dataSnapshot.getValue(ProfileModel.class).getEmail());
profileData.setPhone(dataSnapshot.getValue(ProfileModel.class).getPhone());
refreshFromDataUpdater();
}
private void setPublicDataUpdaterFromDataBase() {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(getString(R.string.public_usersDB));
String mail = currentUser;
if (shownUsrIsCurrentUsr)
mail = mAuth.getCurrentUser().getEmail();
myRef = myRef.child(prepareStringToDataBase(mail)).child(getString(R.string.personal_dataDB));
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
setPublicDataUpdaterFromDataBase(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
};
myRef.addValueEventListener(valueEventListener);
valueEventListenerAndRefLinkedList.add(new ValueEventListenerAndRef(myRef, valueEventListener));
}
private void setRequestsSentToListFromDataBase(DataSnapshot dataSnapshot) {
requestSentTo = new LinkedList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
requestSentTo.add(ds.getValue().toString());
}
}
private void setPublicDataUpdaterFromDataBase(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null)
return;
publicData[PHONE_INDEX] = dataSnapshot.getValue(ProfileModel.class).getPhone();
publicData[EMAIL_INDEX] = dataSnapshot.getValue(ProfileModel.class).getEmail();
publicData[BDAY_INDEX] = dataSnapshot.getValue(ProfileModel.class).getDate();
publicData[CITY_INDEX] = dataSnapshot.getValue(ProfileModel.class).getCity();
publicData[ADDRESS_INDEX] = dataSnapshot.getValue(ProfileModel.class).getAddress();
publicData[NAME_INDEX] = dataSnapshot.getValue(ProfileModel.class).getName();
saveChangesInTextViews();
setPrivacySpinners();
}
private void refreshFromDataUpdater() {
refreshFirstTime();
changeVisibility();
changeIcon();
setEditTextFromDataBase();
saveChangesInTextViews();
}
private void refresh(boolean hasChangedData) {
refreshFirstTime();
refreshEditMode(hasChangedData);
}
private void savePrivacyInDatabase() {
final String[] selectionsOptions = getResources().getStringArray(R.array.privacyOptions);
setPrivacy(NAME_INDEX, selectionsOptions[2]);
setPrivacy(PHONE_INDEX, phoneSpinner.getSelectedItem().toString());
setPrivacy(EMAIL_INDEX, selectionsOptions[2]);
setPrivacy(BDAY_INDEX, bdaySpinner.getSelectedItem().toString());
setPrivacy(CITY_INDEX, citySpinner.getSelectedItem().toString());
setPrivacy(ADDRESS_INDEX, addressSpinner.getSelectedItem().toString());
}
private void refreshEditMode(boolean hasChangedData) {
changeVisibility();
changeIcon();
if (hasChangedData) {
saveChangesInDataBase();
savePrivacyInDatabase();
savePhotoInDataBase();
} else {
setEditTextFromDataBase();
setPrivacySpinners();
}
saveChangesInTextViews();
}
private void savePhotoInDataBase() {
if (!replacedPhoto)
return;
replacedPhoto = false;
bUploadingPhoto = true;
final ProgressBar profileImageProgressBar = findViewById(R.id.profileImageProgressBar);
profileImageProgressBar.setVisibility(View.VISIBLE);
profileImageProgressBar.setEnabled(true);
profileImage.setDrawingCacheEnabled(true);
profileImage.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) profileImage.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageReference ref = FirebaseStorage.getInstance().getReference().child(getString(R.string.profile_images))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()) + ".jpg");
UploadTask uploadTask = ref.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
bUploadingPhoto = false;
goTo(nextClass);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
profileImageProgressBar.setEnabled(false);
profileImageProgressBar.setVisibility(View.GONE);
bUploadingPhoto = false;
goTo(nextClass);
}
});
}
private void setPrivacySpinners() {
if (shownUsrIsCurrentUsr) {
setSelectionPrivacySpinnersPrivate(phoneSpinner, publicData[0]);
setSelectionPrivacySpinnersPrivate(bdaySpinner, publicData[2]);
setSelectionPrivacySpinnersPrivate(citySpinner, publicData[3]);
setSelectionPrivacySpinnersPrivate(addressSpinner, publicData[4]);
} else {
phoneSpinner.setVisibility(View.GONE);
bdaySpinner.setVisibility(View.GONE);
citySpinner.setVisibility(View.GONE);
addressSpinner.setVisibility(View.GONE);
}
}
private void setSelectionPrivacySpinnersPrivate(Spinner spinner, String spinnerSelection) {
if (spinnerSelection.equals(""))
spinner.setSelection(0);
else if (spinnerSelection.substring(0, 2).equals("%f"))
spinner.setSelection(1);
else
spinner.setSelection(2);
}
private void refreshFirstTime() {
if (profileData.getName().equals("")) {
EDIT_MODE = true;
for (Button B : RequestButtonsArray) {
B.setVisibility(View.INVISIBLE);
}
//probably canceling the medical button ---->
//medicIDBtn.setVisibility(View.INVISIBLE);
//probably canceling the medical button ---->
//goToMedicBtn.setVisibility(View.VISIBLE);
setPrivacyFirstTime();
firstTime = false;
secondTime = true;
} else {
for (Button B : RequestButtonsArray) {
B.setVisibility(View.VISIBLE);
}
//probably canceling the medical button ---->
//medicIDBtn.setVisibility(View.VISIBLE);
//probably canceling the medical button ---->
//goToMedicBtn.setVisibility(View.INVISIBLE);
goToHomeBtn.setVisibility(View.VISIBLE);
firstTime = false;
secondTime = false;
}
}
private void setPrivacyFirstTime() {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference();
ref = ref.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail()))
.child(getString(R.string.personal_dataDB));
ref.child("phone").setValue("%f" + profileData.getPhone());
ref.child("email").setValue("%f" + profileData.getEmail());
ref.child("date").setValue("%f" + profileData.getDate());
ref.child("city").setValue("%f" + profileData.getCity());
ref.child("adress").setValue("%f" + profileData.getAddress());
}
private void changeVisibility() {
int textVisibality = View.VISIBLE, editTextVisibality = View.GONE;
if (EDIT_MODE) {
textVisibality = View.GONE;
editTextVisibality = View.VISIBLE;
}
for (EditText ET : EditTextDataArray) {
ET.setVisibility(editTextVisibality);
}
for (TextView TV : TextDataArray) {
TV.setVisibility(textVisibality);
if (TV.getId() == R.id.NameTextV && textVisibality == View.GONE)
TV.setVisibility(View.INVISIBLE);
}
findViewById(R.id.replaceProfileImage_Button_).setVisibility(editTextVisibality);
goToHomeBtn.setVisibility(textVisibality);
phoneSpinner.setVisibility(editTextVisibality);
bdaySpinner.setVisibility(editTextVisibality);
citySpinner.setVisibility(editTextVisibality);
addressSpinner.setVisibility(editTextVisibality);
}
private void changeIcon() {
if (EDIT_MODE)
editIcon.setImageDrawable(getDrawable(R.drawable.ic_mode_edit_on_24dp));
else
editIcon.setImageDrawable(getDrawable(R.drawable.ic_mode_edit_off_24dp));
}
private void saveChangesInTextViews() {
if (!shownUsrIsCurrentUsr) {
TextDataArray[NAME_INDEX].setText(getPublicField(NAME_INDEX));
TextDataArray[PHONE_INDEX].setText(getPublicField(PHONE_INDEX));
TextDataArray[EMAIL_INDEX].setText(getPublicField(EMAIL_INDEX));
TextDataArray[BDAY_INDEX].setText(getPublicField(BDAY_INDEX));
TextDataArray[CITY_INDEX].setText(getPublicField(CITY_INDEX));
TextDataArray[ADDRESS_INDEX].setText(getPublicField(ADDRESS_INDEX));
return;
}
TextDataArray[NAME_INDEX].setText(profileData.getName());
TextDataArray[PHONE_INDEX].setText(profileData.getPhone());
TextDataArray[EMAIL_INDEX].setText(profileData.getEmail());
TextDataArray[BDAY_INDEX].setText(profileData.getDate());
TextDataArray[CITY_INDEX].setText(profileData.getCity());
TextDataArray[ADDRESS_INDEX].setText(profileData.getAddress());
}
private void saveChangesInDataBase() {
if (!EDIT_MODE) {
profileData = new ProfileModel(getPersonalDataFromEditTexts(0), getPersonalDataFromEditTexts(1),
getPersonalDataFromEditTexts(2), getPersonalDataFromEditTexts(3), getPersonalDataFromEditTexts(4), getPersonalDataFromEditTexts(5));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users");
myRef.child(mAuth.getCurrentUser().getUid()).child("personalData").setValue(profileData);
}
}
private void setEditTextFromDataBase() {
EditTextDataArray[0].setText(profileData.getName());
EditTextDataArray[1].setText(profileData.getPhone());
EditTextDataArray[2].setText(profileData.getEmail());
EditTextDataArray[3].setText(profileData.getDate());
EditTextDataArray[4].setText(profileData.getCity());
EditTextDataArray[5].setText(profileData.getAddress());
}
public String getPersonalDataFromEditTexts(int i) {
if (i < 0 || i > 5) {
Toast.makeText(this, "problem in code!!!", Toast.LENGTH_LONG).show();
return "___BUG________";
}
return EditTextDataArray[i].getText().toString();
}
private void setEditTextDataArrray() {
EditText[] ET_id_s = {findViewById(R.id.editNameV),
findViewById(R.id.editPhoneV),
findViewById(R.id.editEmailV),
findViewById(R.id.editBdayV),
findViewById(R.id.editCityV),
findViewById(R.id.editAdressV)};
for (int i = 0; i < NUMBER_OF_PARAMETERS; i++) {
EditTextDataArray[i] = ET_id_s[i];
}
}
private void setTextDataArrray() {
TextView[] TV_id_s = {findViewById(R.id.PhoneTextV),
findViewById(R.id.EmailTextV),
findViewById(R.id.BdayTextV),
findViewById(R.id.cityTextV),
findViewById(R.id.AdressTextV),
findViewById(R.id.NameTextV)};
for (int i = 0; i < NUMBER_OF_PARAMETERS; i++) {
TextDataArray[i] = TV_id_s[i];
}
findViewById(R.id.NameTextV).setSelected(true);
}
private void setRequestButtonsArray() {
Button[] B_id_s =
{
findViewById(R.id.addChildBtn),
findViewById(R.id.addParentBtn),
findViewById(R.id.addPartnerBtn)
};
for (int i = 0; i < B_id_s.length; i++) {
RequestButtonsArray[i] = B_id_s[i];
}
}
public void onOffEditMode(View view) {
if (!shownUsrIsCurrentUsr)
return;
onOffEditModePrivate();
}
// private void cheatTheSystem() {
// FirebaseDatabase database = FirebaseDatabase.getInstance();
// DatabaseReference myRef = database.getReference("users");
// myRef = myRef.child(mAuth.getCurrentUser().getUid());
// myRef = myRef.child("CTS");
// myRef.setValue("CTS");
// }
private void onOffEditModePrivate() {
EDIT_MODE = !EDIT_MODE;
refreshEditMode(!EDIT_MODE);
}
private void viBtnMoveOn(Class s) {
if (!shownUsrIsCurrentUsr) {
onBackPressed();
// goTo(s);
}
setDefaultName();
if (EDIT_MODE)
onOffEditModePrivate();
else
refresh(false);
if (dataIsLegal()) {
onBackPressed();
// goTo(s);
}
}
private void setDefaultName() {
if (profileData.getName() == "")
profileData.setName("VERY LAZY");
}
private void createEmptyFieldsDialog() {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.empty_fields_dialog_message)
.setTitle(R.string.empty_fields_dialog_title);
builder.setPositiveButton(R.string.keep_on_with_un_filled_fields_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
viBtnMoveOn(nextClass);
}
});
builder.setNegativeButton(R.string.cancel_keep_on_with_un_filled_fields_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
return;
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
private boolean allFieldsCompleted() {
for (EditText ET : EditTextDataArray) {
if (ET.getText().toString().equals(""))
return false;
}
return true;
}
private boolean dataIsLegal() {
return checkData() == 0;
}
private int checkData() {
//TODO 0-good 1-problem in 1 2- problem in 2 3-...
return 0;
}
public void goToHomeAttempt(View view) {
nextClass = HomeScreen.class;
if (shownUsrIsCurrentUsr && !allFieldsCompleted())
createEmptyFieldsDialog();
else
viBtnMoveOn(nextClass);
}
// public void setBDay(View view) {
// Calendar cal = Calendar.getInstance();
// int year = cal.get(Calendar.YEAR);
// int month = cal.get(Calendar.MONTH);
// int day = cal.get(Calendar.DAY_OF_MONTH);
//
// DatePickerDialog dialog = new DatePickerDialog(this,
// android.R.style.Theme_Holo_Light_Dialog_MinWidth,
// mDateSetListener,
// year,month,day);
// dialog.setOnDateSetListener();
// }
private void goTo(Class S) {
if (bUploadingPhoto) {
nextClass = S;
return;
}
Intent intent = new Intent(this, S);
startActivity(intent);
}
private String getPublicField(int index) {
if (index < 0 || index >= NUMBER_OF_PARAMETERS)
return null;
LinkedList<String> mailList = new LinkedList<>();
for (ProfileModel pm : getFamilyMembers(mAuth.getCurrentUser().getEmail(), 1)) {
mailList.add(pm.getEmail());
}
if (publicData[index] == null
|| publicData[index].length() == 0
|| (!shownUsrIsCurrentUsr && publicData[index].startsWith("%f") && !mailList.contains(currentUser))
) {
return "";
}
if (publicData[index].startsWith("%f"))
return publicData[index].substring(2);
return publicData[index];
}
//functionality:
public void sendEmail(View view) {
if (EDIT_MODE)
return;
String mail = TextDataArray[EMAIL_INDEX].getText().toString();
Intent mailIntent = new Intent(Intent.ACTION_SENDTO);
mailIntent.setType("*/*").setData(Uri.parse("mailto:" + mail))
.putExtra(Intent.EXTRA_SUBJECT, "subject");
if (mailIntent.resolveActivity(getPackageManager()) != null)
startActivity(mailIntent);
}
public void call(View view) {
if (EDIT_MODE)
return;
String phoneNumber = TextDataArray[PHONE_INDEX].getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL);
final int REQUEST_PHONE_CALL = 1;
callIntent.setData(Uri.parse("tel:" + phoneNumber));// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PHONE_CALL);
} else {
startActivity(callIntent);
}
} else {
startActivity(callIntent);
}
}
public void navigate(View view) {
if (EDIT_MODE)
return;
String city = TextDataArray[CITY_INDEX].getText().toString(),
address = TextDataArray[ADDRESS_INDEX].getText().toString();
if (city.length() == 0 && address.length() == 0) {
return;
}
city = setStringsCompatibleWithUri(city);
address = setStringsCompatibleWithUri(address);
if (address.length() != 0 && city.length() != 0)
address = "+" + address;
Uri geoLocation = Uri.parse("geo:0,0?q=" + city + address);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
private static String setStringsCompatibleWithUri(String s) {
if (s.length() == 0) {
return "";
}
String compString = "";
s = s.trim();
while ((s.length() > 0)) {
int nextSpace = s.indexOf(" ");
if (nextSpace < 0)
nextSpace = s.length();
compString += s.substring(0, nextSpace) + "+";
s = s.substring(nextSpace);
s = s.trim();
}
compString = compString.substring(0, compString.lastIndexOf("+"));
return compString;
}
public void addParent(View view) {
if (!shownUsrIsCurrentUsr) {
sendFather_newKidRequest(currentUser, mAuth.getCurrentUser().getEmail());
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Fill in your parents email:");
// Set up the input
final EditText input = new EditText(this);
// Specifies the type of input expected; this, sets the input as a text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Data-Base play
sendFather_newKidRequest(input.getText().toString(), mAuth.getCurrentUser().getEmail());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public boolean isRequestToUserPermitted(String user_mail){
if (!allUsers.contains(user_mail)) {
Toast.makeText(Profile.this,
"User doesn't exists",
Toast.LENGTH_LONG).show();
return false;
}
if (requestSentTo.contains(user_mail)) {
Toast.makeText(Profile.this,
"User already has a pending request.",
Toast.LENGTH_LONG).show();
return false;
}
if (user_mail.equals(partner)){
Toast.makeText(Profile.this,
"User is already your partner.",
Toast.LENGTH_LONG).show();
return false;
} else if (parents.contains(user_mail)){
Toast.makeText(Profile.this,
"User is already your parent.",
Toast.LENGTH_LONG).show();
return false;
} else if (kids.contains(user_mail)){
Toast.makeText(Profile.this,
"User is already your kid.",
Toast.LENGTH_LONG).show();
return false;
}
LinkedList<ProfileModel> brothersModels = get(currentUser, famFields.brothers);
for (ProfileModel pm : brothersModels) {
if (pm.getEmail().equals(mAuth.getCurrentUser().getEmail())) {
Toast.makeText(Profile.this,
"User is already your sibling.",
Toast.LENGTH_LONG).show();
return false;
}
}
return true;
}
public void sendFather_newKidRequest(String mail, String senderMail) {
if (!isRequestToUserPermitted(mail))
return;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mail))
.child("fam")
.child("requests").push();
ref.child("email")
.setValue(mAuth.getCurrentUser().getEmail());
ref.child("connection")
.setValue("kid");
ref.child("name")
.setValue(profileData.getName());
addRequestSentTo(mail, senderMail);
Toast.makeText(Profile.this, "request sent to " + mail, Toast.LENGTH_LONG).show();
}
public void addKid(View view) {
if (!shownUsrIsCurrentUsr) {
sendKid_newParentRequest(currentUser, mAuth.getCurrentUser().getEmail());
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Fill in your kids email:");
// Set up the input
final EditText input = new EditText(this);
// Specifies the type of input expected; this, sets the input as a text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Data-Base play
sendKid_newParentRequest(input.getText().toString(), mAuth.getCurrentUser().getEmail());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void sendKid_newParentRequest(String mail, String senderMail) {
if (!isRequestToUserPermitted(mail))
return;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mail))
.child("fam")
.child("requests").push();
ref.child("email")
.setValue(mAuth.getCurrentUser().getEmail());
ref.child("connection")
.setValue("parent");
ref.child("name")
.setValue(profileData.getName());
addRequestSentTo(mail, senderMail);
Toast.makeText(Profile.this, "request sent to " + mail, Toast.LENGTH_LONG).show();
}
public void addPartner(View view) {
if (!shownUsrIsCurrentUsr) {
sendPartner_newPartnerRequest(currentUser, mAuth.getCurrentUser().getEmail());
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Fill in your partners email:");
// Set up the input
final EditText input = new EditText(this);
// Specifies the type of input expected; this, sets the input as a text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Data-Base play
sendPartner_newPartnerRequest(input.getText().toString(), mAuth.getCurrentUser().getEmail());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void sendPartner_newPartnerRequest(String mail, String senderMail) {
if (!isRequestToUserPermitted(mail))
return;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mail))
.child("fam")
.child("requests").push();
ref.child("email")
.setValue(senderMail);
ref.child("connection")
.setValue("partner");
if (senderMail.equals(mAuth.getCurrentUser().getEmail()))
ref.child("name").setValue(profileData.getName());
else
ref.child("name").setValue(senderMail.substring(0,senderMail.indexOf('@')));
addRequestSentTo(mail, senderMail);
Toast.makeText(Profile.this, "request sent to " + mail, Toast.LENGTH_LONG).show();
}
private void addRequestSentTo(String mail, String senderMail) {
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(senderMail))
.child("fam").child("requestsSentTo")
.child(prepareStringToDataBase(mail)).setValue(mail);
}
private void removeRequestSentTo(String mail) {
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.public_usersDB))
.child(prepareStringToDataBase(mail))
.child("fam").child("requestsSentTo")
.child(prepareStringToDataBase(mAuth.getCurrentUser().getEmail())).removeValue();
}
public void replaceProfileImage(View view) {
replacedPhoto = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 100);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
new Thread(new Runnable() {
@Override
public void run() {
if (resultCode == RESULT_OK) {
if (requestCode == 100) {
// Get the url from data
final Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i("TAG", "Image Path : " + path);
// Set the image in ImageView
findViewById(R.id.profile_imageView).post(new Runnable() {
@Override
public void run() {
((ImageView) findViewById(R.id.profile_imageView)).setImageURI(selectedImageUri);
}
});
}
}
}
}
}).start();
}
/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
// public void changeImage(View view) {
// Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
// StorageReference riversRef = mStorageRef.child("images/rivers.jpg");
//
// riversRef.putFile(file)
// .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
// @Override
// public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// // Get a URL to the uploaded content
// Uri downloadUrl = taskSnapshot.();
// }
// })
// .addOnFailureListener(new OnFailureListener() {
// @Override
// public void onFailure(@NonNull Exception exception) {
// // Handle unsuccessful uploads
// // ...
// }
// });
// }
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class MergeCounts {
public ArrayList<String> readTxt(String Path) throws IOException{
File file=new File(Path);
ArrayList<String> list=new ArrayList<String>();
if(file.isFile() && file.exists()){
InputStreamReader read = new InputStreamReader(
new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
String[] newLine;
//ArrayList<String> list=new ArrayList<String>();
while((lineTxt = bufferedReader.readLine()) != null){
newLine=lineTxt.split(",");
list.add(newLine[0]);
}
read.close();
}else{
System.out.println("file not found");
}
return list;
}
public static void main(String arg[]) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
String context;
String nContext;
int wordNum=0;
String key;
MergeCounts mc = new MergeCounts();
//ArrayList<String> amc=mc.readTxt("Desktop:\\wordInfo.txt");
//BufferedReader br = new BufferedReader(new FileReader("wordInfo.txt"));
while((context = f.readLine()) != null){
boolean flag=true;
int uNum = 0;
ArrayList<String> amc=mc.readTxt("Desktop:\\wordInfo.txt");
for(int i=0;i<amc.size();i++){
if(amc.get(i).equals(context)){
flag=false;
break;
}
}
int words=1;
wordNum++;
if(flag){
uNum++;
File file = new File("Desktop:\\wordInfo.txt");
String str;
while((nContext = f.readLine()) != null){
if(nContext.equals(context)){
words++;
}
}
FileWriter writer = new FileWriter(file);
str=f.readLine()+","+words;
writer.write(str);
writer.flush();
writer.close();
}
}
}
}
|
package com.mega.swipeit.Api;
public class ApiConst {
public static final String API_HOST ="http://demo.magespider.com/QuestionGame/api/";
public static final String SIGN_UP ="auth/signup";
}
|
package br.com.alura.leilao.acceptance.steps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import br.com.alura.leilao.model.Lance;
import br.com.alura.leilao.model.Leilao;
import br.com.alura.leilao.model.Usuario;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.pt.Dado;
import io.cucumber.java.pt.Entao;
import io.cucumber.java.pt.Quando;
public class PropondoLancesSteps {
private Lance lance;
private Leilao leilao;
private ArrayList<Lance> lista;
@Before
public void setup(){
this.lista = new ArrayList<Lance>();
leilao = new Leilao("Tablet XPTO");
}
@After
public void clean() {
this.lista = null;
this.leilao = null;
}
@Dado("um lance valido")
public void umLanceValido() {
Usuario usuario = new Usuario("fulano");
lance = new Lance(usuario, BigDecimal.TEN);
}
@Quando("propoe o lance ao leilao")
public void propoeOLance() {
leilao.propoe(lance);
}
@Entao("o lance eh aceito")
public void lanceAceito() {
assertEquals(1, leilao.getLances().size());
assertEquals(BigDecimal.TEN, leilao.getLances().get(0).getValor());
}
/*@Dado("varios lances sendo propostos")
public void varios_lances_sendo_propostos() {
Usuario usuario1 = new Usuario("fulano");
lance10 = new Lance(usuario1, BigDecimal.TEN);
Usuario usuario2 = new Usuario("beltrano");
lance15 = new Lance(usuario2, new BigDecimal("15.0"));
leilao = new Leilao("Tablet XPTO");
}*/
@Dado("um lance de {double} reais do usuario {string}")
public void varios_lance_de_reais_do_usuario(Double valor, String nomeUser) {
Lance lance = new Lance(new Usuario(nomeUser), new BigDecimal(valor));
lista.add(lance);
}
//@E("")
@Quando("propoe varios lances ao leilao")
public void propoe_o_lance_os_lances_ao_leilao() {
this.lista.forEach(lance -> leilao.propoe(lance));
}
@Entao("os lances sao aceitos")
public void os_lances_sao_aceitos() {
assertEquals(this.lista.size(), leilao.getLances().size());
assertEquals(this.lista.get(0).getValor(), leilao.getLances().get(0).getValor());
assertEquals(this.lista.get(1).getValor(), leilao.getLances().get(1).getValor());
}
@Dado("um lance invalido de {double} reais e dos usuarios {string}")
public void um_lance_invalido_de_reais_do_usuario(Double valor, String nomeUsuario) {
this.lance = new Lance( new BigDecimal(valor));
}
@Entao("o lance nao eh aceito")
public void o_lance_nao_eh_aceito() {
assertEquals(0, leilao.getLances().size());
}
@Dado("dois lances sendo propostos")
public void dois_lances_sendo_propostos(DataTable dataTable) {
List<Map<String, String>> valores = dataTable.asMaps();
for(Map<String, String> valorMapa: valores) {
String valorNum = valorMapa.get("valor");
String valorString = valorMapa.get("nomedoUsuario");
Lance lance = new Lance(new Usuario(valorString), new BigDecimal(valorNum));
lista.add(lance);
}
}
@Entao("o segundo nao e aceito")
public void o_segundo_nao_e_aceito() {
assertEquals(1, leilao.getLances().size());
assertEquals(this.lista.get(0).getValor(), leilao.getLances().get(0).getValor());
}
}
|
package com.example.light_the_led;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
public class Log_in_activity extends AppCompatActivity
//this class is for the log in screen
{
EditText user_name_edit_text;
@Override
protected void onCreate(Bundle savedInstanceState)
//initialize all the objects on the screen
{
super.onCreate(savedInstanceState);
setContentView(R.layout.log_in_activity_layout);
user_name_edit_text = (EditText)findViewById(R.id.Log_in_edit_text_user_name);
startService(new Intent(this , musicService.class));
}
public void Log_in_button_method(View view) throws ExecutionException, InterruptedException
//the method for log in button log into the main screen
{
// on login get user name and action string
String user_name = user_name_edit_text.getText().toString().trim();
if(user_name.isEmpty())
{
Toast.makeText(this , "put in a user name" , Toast.LENGTH_LONG).show();
return;
}
Connection connect_to_server_first_time = new Connection(getApplicationContext());
connect_to_server_first_time.execute(user_name);
String action_string = connect_to_server_first_time.get(); //connection returns the action string after finishing
if(action_string.equals("f")) //if couldn't connect to server just stop
return;
Intent start_main_activity = new Intent(this , MainActivity.class);
start_main_activity.putExtra("action_string" , action_string);
start_main_activity.putExtra("user_name" , user_name); // sending user name and action string to the main activity
startActivity(start_main_activity);
}
public void open_settings_fab_method(View view)
//the method for the floating action button open settings screen
{
Intent open_settings_intent = new Intent(this , Settings_activity.class);
startActivityForResult(open_settings_intent , 2);
}
}
|
package com.stackroute.movieservice.domain;
import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Movie {
@Id
//@GeneratedValue(strategy=GenerationType.AUTO)
private int movieId;
private String movieTitle;
private int movieRating;
private int movieYear;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(int movieId, String movieTitle, int movieRating, int movieYear) {
this.movieId = movieId;
this.movieTitle = movieTitle;
this.movieRating = movieRating;
this.movieYear = movieYear;
}
public int getMovieId() {
return movieId;
}
public void setMovieId(int movieId) {
this.movieId = movieId;
}
public String getMovieTitle() {
return movieTitle;
}
public void setMovieTitle(String movieTitle) {
this.movieTitle = movieTitle;
}
public int getMovieRating() {
return movieRating;
}
public void setMovieRating(int movieRating) {
this.movieRating = movieRating;
}
public int getMovieYear() {
return movieYear;
}
public void setMovieYear(int movieYear) {
this.movieYear = movieYear;
}
} |
package com.jaiaxn.design.pattern.behavioral.iterator;
/**
* @author: wang.jiaxin
* @date: 2019年08月27日
* @description:
**/
public interface Iterator {
/**
* 是否存在下一个元素
*
* @return 结果
*/
boolean hasNext();
/**
* 返回下一个元素
*
* @return 下一个元素
*/
Object next();
}
|
package com.gxtc.huchuan.adapter;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.AddressBean;
import com.gxtc.huchuan.ui.mine.address.UpdataAddressActivity;
import java.util.List;
public class SelectAddressAdapter extends BaseRecyclerAdapter<AddressBean> {
public SelectAddressAdapter(Context context, List<AddressBean> list, int itemLayoutId) {
super(context, list, itemLayoutId);
}
@Override
public void bindData(final ViewHolder holder, int position, AddressBean bean) {
ImageView imgSelect = (ImageView) holder.getView(R.id.iv_select);
ImageView imgEdit = (ImageView) holder.getView(R.id.img_address_edit);
TextView tvName = (TextView) holder.getView(R.id.tv_name);
TextView tvPhone = (TextView) holder.getView(R.id.tv_phone);
TextView tvAddr = (TextView) holder.getView(R.id.tv_address);
TextView tvDefult = (TextView) holder.getView(R.id.tv_address_defult);
String name = bean.getName();
String phone = bean.getPhone();
String defult = bean.getIsdefault();
String address = bean.getProvince()+bean.getCity();
String area = bean.getArea();
if (!TextUtils.isEmpty(area)) {
address += area;
}
address += bean.getAddress();
tvAddr.setText(address);
tvName.setText(name);
tvPhone.setText(phone);
if("1".equals(defult)){
tvDefult.setVisibility(View.VISIBLE);
}else{
tvDefult.setVisibility(View.INVISIBLE);
}
if(bean.isSelect()){
imgSelect.setVisibility(View.VISIBLE);
}else{
imgSelect.setVisibility(View.INVISIBLE);
}
imgEdit.setTag(bean);
imgEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddressBean bean = (AddressBean) v.getTag();
Intent intent = new Intent(getContext(), UpdataAddressActivity.class);
intent.putExtra(Constant.INTENT_DATA,bean);
getContext().startActivity(intent);
}
});
}
}
|
// https://www.youtube.com/watch?v=eVQiFuJRfsU
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> res = new ArrayList<>();
int n = products.length;
int lo = 0, hi = n - 1;
int len = searchWord.length();
Arrays.sort(products);
for (int i = 0; i < len; i++) {
while ((lo <= hi) && (products[lo].length() <= i ||
products[lo].charAt(i) != searchWord.charAt(i))) {
lo++;
}
while ((lo <= hi) && (products[hi].length() <= i ||
products[hi].charAt(i) != searchWord.charAt(i))) {
hi--;
}
int min = Math.min(lo + 3, hi + 1);
List<String> list = new ArrayList<>();
for (int j = lo; j < min; j++) {
list.add(products[j]);
}
res.add(list);
}
return res;
}
} |
package common;
import cmdline.FbCollector;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.*;
public class PostsCollector
{
private Page page;
private String since;
private String until;
public List<String> postIds;
public static String fields;
public PostsCollector(Page page, String since, String until)
{
this.page = page;
this.since = since;
this.until = until;
postIds = new ArrayList<String>();
if(null == Config.postFields || Config.postFields.isEmpty())
{
fields = "id,message,created_time,updated_time,place,tags,shares," +
"likes.limit(1).summary(true),comments.limit(1).summary(true)";
}
else
{
fields = Config.postFields;
}
}
public void collect()
{
String url = Config.baseUrl + ("/") + (page.getUsername()) + "/posts";
url += "?access_token=" + Config.accessToken;
url += "&include_hidden=" + true;
url += "&since=" + since;
url += "&until=" + until;
url += "&fields=" + fields;
collect(url);
}
private void collect(String url)
{
JSONObject posts = Util.getJson(url);
if(null != posts)
{
JSONArray postsData = (JSONArray) posts.get("data");
Iterator itr = postsData.iterator();
while (itr.hasNext())
{
JSONObject postJson = (JSONObject) itr.next();
Post post = new Post(page, postJson, null);
post.writeJson();
postIds.add(post.getId());
}
JSONObject paging = (JSONObject) posts.get("paging");
if(null != paging && null != paging.get("next"))
{
collect(paging.get("next").toString());
}
}
else
{
System.err.println("reading posts failed for url: " + url);
}
}
}
|
package com.zxq.spring.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
public class ZKController {
@Value("${server.port}")
private String ServerPort;
@GetMapping("/payment/zK")
public String GetZK(){
return "this is zookeeper serverPort:"+ServerPort+"\t"+ UUID.randomUUID().toString();
}
}
|
package com.asiainfo.worktime.service;
import java.util.List;
import com.asiainfo.worktime.model.ProcTypeModel;
public interface ProcTypeService {
List<ProcTypeModel> getAllProcTypes();
}
|
package com.minismap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import com.minismap.data.MapArray;
import java.util.ArrayList;
/**
* Created by nbp184 on 2016/03/22.
*/
public class AddEnemyDialog extends DialogFragment {
public static final String MAP_INDEX = "map index";
public static final String X = "x";
public static final String Y = "y";
public interface OnClickListener {
public void onEnemyAdd(String name, String abbreviation, int x, int y);
}
private AddEnemyDialog.OnClickListener listener = null;
private int x;
private int y;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof AddEnemyDialog.OnClickListener) {
listener = (AddEnemyDialog.OnClickListener)activity;
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_enemy, null);
Bundle args = getArguments();
int mapIndex = args.getInt(MAP_INDEX);
x = args.getInt(X);
y = args.getInt(Y);
ArrayList<String> names = MapArray.getInstance().getMap(mapIndex).getUniqueEnemyNames();
Spinner spinner = (Spinner)view.findViewById(R.id.spinner_names);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names);
if(names.isEmpty()) {
RadioButton rb = (RadioButton)view.findViewById(R.id.radio_edit);
rb.setChecked(true);
spinner.setEnabled(false);
} else {
RadioButton rb = (RadioButton)view.findViewById(R.id.radio_dropdown);
rb.setChecked(true);
view.findViewById(R.id.edit_name).setEnabled(false);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
builder.setView(view)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, null)
.setCancelable(true);
AlertDialog dialog = builder.create();
return dialog;
}
public void radioChange(View view) {
getDialog().findViewById(R.id.spinner_names).setEnabled(view.getId() == R.id.radio_dropdown);
getDialog().findViewById(R.id.edit_name).setEnabled(view.getId() == R.id.radio_edit);
}
private void doPositiveClick() {
if (listener != null) {
String name;
RadioButton rb = (RadioButton)getDialog().findViewById(R.id.radio_dropdown);
if(rb.isChecked()) {
Spinner spinner = (Spinner)getDialog().findViewById(R.id.spinner_names);
name = (String)spinner.getSelectedItem();
} else {
EditText et = (EditText)getDialog().findViewById(R.id.edit_name);
name = et.getText().toString();
}
EditText et = (EditText)getDialog().findViewById(R.id.edit_abbreviation);
String abbreviation = et.getText().toString();
listener.onEnemyAdd(name, abbreviation, x, y);
}
}
}
|
package com.stk123.service.support;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Oracle12cDialect;
import org.hibernate.type.StandardBasicTypes;
import java.sql.Types;
import java.util.Map;
public class CustomOracleDialect extends Oracle12cDialect {
public CustomOracleDialect(){
super();
// registerHibernateType( Types.NUMERIC, StandardBasicTypes.LONG.getName() );
}
public String getHibernateTypeName(int code, int length, int precision, int scale) throws HibernateException {
String result = super.getHibernateTypeName( code, length, precision, scale );
if(code == Types.NUMERIC){
// System.out.println("hibernate type name:"+result);
// System.out.println("length:"+length+",precision:"+precision+",scale:"+scale);
if(scale == 0) {
result = "long";
if(length == 0 && precision == 0){
result = "big_decimal";
}
} else if(scale > 0 && precision <= 20)
result = "double";
}
return result;
}
@Override
public String getQuerySequencesString() {
return "select SEQUENCE_OWNER, SEQUENCE_NAME, greatest(MIN_VALUE, -9223372036854775807) MIN_VALUE,\n"+
"Least(MAX_VALUE, 9223372036854775808) MAX_VALUE, INCREMENT_BY, CYCLE_FLAG, ORDER_FLAG, CACHE_SIZE,\n"+
"Least(greatest(LAST_NUMBER, -9223372036854775807), 9223372036854775808) LAST_NUMBER\n"+
// ",PARTITION_COUNT, SESSION_FLAG, KEEP_VALUE\n"+
"from all_sequences";
}
}
|
package net.music.demo.controller;
import net.music.demo.exception.ResourceNotFoundException;
import net.music.demo.model.Artist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import net.music.demo.repository.Artist_Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/")
public class ArtistController {
@Autowired
private Artist_Repository artistRepository;
private ResponseEntity<Object> ReponseEntity;
// get all artists
@GetMapping("/artists")
public List<Artist> getAllArtists() {
return artistRepository.findAll();
}
// post artist
@PostMapping("/artists")
public Artist createArtist(@RequestBody Artist artist) {
return artistRepository.save(artist);
}
// get a single artist
@GetMapping("/artists/{id}")
public ResponseEntity<Artist> getArtistById(@PathVariable Long id) {
Artist artist = artistRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Artist Not Found With ID: " + id));
return ResponseEntity.ok(artist);
}
// edit an artist
@PutMapping("/artists/{id}")
public ResponseEntity<Artist> updateArtist(@PathVariable Long id, @RequestBody Artist artistDetails) {
Artist artist = artistRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Artist Not Found With ID: " + id));
artist.setArtistName(artistDetails.getArtistName());
artist.setCountry(artistDetails.getCountry());
artist.setGenre(artistDetails.getGenre());
Artist updatedArtist = artistRepository.save(artist);
return ResponseEntity.ok(updatedArtist);
}
// delete artist
@DeleteMapping("/artists/{id}")
public ResponseEntity<Map<String, Boolean>> deleteArtist(@PathVariable Long id) {
Artist artist = artistRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Artist Not Found With ID: " + id));
artistRepository.delete(artist);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
|
package jarjestaminen.algoritmit;
import java.util.Arrays;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class IntroSortTest {
private int[] arr;
private int[] arr2;
@Before
public void setUp() throws Exception {
arr = new int[20];
Random generator = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = generator.nextInt(100);
}
arr2 = new int[20000];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = generator.nextInt(100);
}
}
/**
* Testataan toimiiko Introsort-järjestäminen pienellä taulukolla.
*/
@Test
public void IntroSortJarjestaminenToimiiPienellaTaulukolla() {
IntroSort intro = new IntroSort(arr);
intro.sort();
Arrays.sort(arr);
Assert.assertArrayEquals(intro.getArr(), arr);
}
/**
* Testataan toimiiko Introsort-järjestäminen suurella taulukolla.
*/
@Test
public void IntroSortJarjestaminenToimiiSuurellaTaulukolla() {
IntroSort intro = new IntroSort(arr2);
intro.sort();
Arrays.sort(arr2);
Assert.assertArrayEquals(intro.getArr(), arr2);
}
/**
* Testataan toimiiko Introsort-järjestäminen jos taulukko on tyhjä.
*/
@Test
public void IntroSortJarjestaminenToimiiTyhjallaTaulukolla() {
int[] arrEmpty = new int[0];
IntroSort intro = new IntroSort(arrEmpty);
intro.sort();
Assert.assertArrayEquals(intro.getArr(), arrEmpty);
}
/**
* Testataan toimiiko Introsort-järjestäminen jos taulukossa on useampi sama
* arvo.
*/
@Test
public void IntroSortJarjestaminenToimiiJosTaulukossaSamojaArvoja() {
int[] arr3 = {0, 1, 7, 3, 9, 2, 2, 3, 4, 1, 1, 5};
IntroSort intro = new IntroSort(arr3);
intro.sort();
Arrays.sort(arr3);
Assert.assertArrayEquals(intro.getArr(), arr3);
}
/**
* Testataan toimiiko Introsort-järjestäminen jos taulukossa on vain yksi
* arvo.
*/
@Test
public void IntroSortJarjestaminenToimiiJosTaulukossaOnVainYksiArvo() {
int[] arr4 = {7};
IntroSort intro = new IntroSort(arr4);
intro.sort();
Arrays.sort(arr4);
Assert.assertArrayEquals(intro.getArr(), arr4);
}
@After
public void tearDown() {
}
}
|
package com.aliyun.oss.model;
import java.util.ArrayList;
import java.util.List;
public class BucketList {
private List<Bucket> buckets = new ArrayList<Bucket>();
private String prefix;
private String marker;
private Integer maxKeys;
private boolean isTruncated;
private String nextMarker;
public List<Bucket> getBucketList() {
return buckets;
}
public void setBucketList(List<Bucket> buckets) {
this.buckets = buckets;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getMarker() {
return marker;
}
public void setMarker(String marker) {
this.marker = marker;
}
public Integer getMaxKeys() {
return maxKeys;
}
public void setMaxKeys(Integer maxKeys) {
this.maxKeys = maxKeys;
}
public boolean isTruncated() {
return isTruncated;
}
public void setTruncated(boolean isTruncated) {
this.isTruncated = isTruncated;
}
public String getNextMarker() {
return nextMarker;
}
public void setNextMarker(String nextMarker) {
this.nextMarker = nextMarker;
}
}
|
package com.flushoutsolutions.foheart.design;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.flushoutsolutions.foheart.globals.Menu;
import com.flushoutsolutions.foheart.json.JSONParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
/**
* Created by Manuel on 10/08/2014.
*/
public class ButtonMenuAdapter extends BaseAdapter{
private Context mContext;
private MenuButton[] btns = new MenuButton[90];
private JSONArray jsonArray;
public ButtonMenuAdapter(Context c) throws IOException, JSONException {
mContext = c;
JSONParser menuJson = new JSONParser("mainmenu.json");
jsonArray = new JSONArray();
jsonArray = menuJson.get_json_array();
for (int x=0; x<jsonArray.length(); x++)
{
JSONObject jsonObject = jsonArray.getJSONObject(x);
int notif = 0;
if (!jsonObject.isNull("notifications")) notif = jsonObject.getInt("notifications");
btns[x]= new MenuButton(mContext, jsonObject.get("title").toString(), jsonObject.get("icon").toString(), jsonObject.get("color").toString(), notif);
Menu.add(jsonObject.get("name").toString(), btns[x]);
}
}
public MenuButton[] get_menu_buttons()
{
return this.btns;
}
public int getCount() {
return jsonArray.length();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent)
{
return btns[position];
}
}
|
package sda.credit.cards.issuers;
public interface Detector {
String detect(String number);
}
|
package br.com.senac.Servicos;
import br.com.senac.Classes.Mamifero;
import br.com.senac.Dao.MamiferoDao;
import br.com.senac.Exceptions.DataSourceException;
import br.com.senac.Exceptions.MamiferoException;
import br.com.senac.Validadores.MamiferoValidador;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
public class MamiferoServico {
public static void cadastrarMamifero(Mamifero mamifero) throws MamiferoException, DataSourceException, SQLException, ClassNotFoundException {
MamiferoValidador.validar(mamifero);
try {
MamiferoDao.incluirMamifero(mamifero);
} catch (Exception e) {
e.printStackTrace();
throw new DataSourceException("Erro na fonte de dados", e);
}
}
public static void atualizarMamifero(Mamifero mamifero) throws MamiferoException, DataSourceException {
MamiferoValidador.validar(mamifero);
try {
MamiferoDao.atualizarMamifero(mamifero);
return;
} catch (Exception e) {
e.printStackTrace();
throw new DataSourceException("Erro na fonte de dados", e);
}
}
public static ArrayList<Mamifero> procurarMamifero(String valor) throws SQLException, ClassNotFoundException, DataSourceException, ParseException {
try {
if (valor == null) {
return MamiferoDao.listarMamifero();
} else {
return MamiferoDao.procurarMamifero(valor);
}
} catch (Exception e) {
e.printStackTrace();
throw new DataSourceException("Erro na fonte de dados", e);
}
}
public static Mamifero obterMamifero(Integer id) throws MamiferoException, DataSourceException {
try {
return MamiferoDao.obterMamifero(id);
} catch (Exception e) {
e.printStackTrace();
throw new DataSourceException("Erro na fonte de dados", e);
}
}
public static void excluirMamifero(Integer id) throws MamiferoException, DataSourceException {
try {
MamiferoDao.excluirMamifero(id);
} catch (Exception e) {
e.printStackTrace();
throw new DataSourceException("Erro na fonte de dados", e);
}
}
}
|
package com.mongo.embeded;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.mongo.embeded.Company;
import com.mongo.embeded.Contact;
import com.mongo.embeded.Product;
import com.mongo.embeded.CompanyRepository;
@SpringBootApplication
public class SpringDataMongoDbApplication implements CommandLineRunner{
@Autowired
CompanyRepository companyRepo;
@Override
public void run(String... args) throws Exception {
// clear database
System.out.println("==========Delete all company entities==========");
companyRepo.deleteAll();
// save Documents to MongoDB
System.out.println("==========Save list of company entities for Apple==========");
Product p1=new Product("A-123", "Iphone 7", "Price: 649.00 USD & FREE shipping");
Product p2=new Product("A-456", "IPadPro", "Price: 417.67 USD & FREE shipping");
List<Product> listProduct1=new ArrayList<Product>();
listProduct1.add(p1);
listProduct1.add(p2);
Contact c1=new Contact("Cupertino, CA 95014", "1-408-996-1010");
//For Samsung
System.out.println("==========Save list of company entities for Samsung==========");
Product p3=new Product("Jprime", "Samsung Galaxy 7", "Price: 649.00 USD & FREE shipping");
Product p4=new Product("Jprime Pro", "Samsung Galaxy 7 Pro", "Price: 649.00 USD & FREE shipping");
List<Product> listProduct2=new ArrayList<Product>();
listProduct2.add(p3);
listProduct2.add(p4);
Contact c2=new Contact("Japan, CA 95014", "1-408-996-1010");
List<Company> company=Arrays.asList(new Company(1, "Apollo",listProduct1, c1),new Company(2, "Samsung",listProduct2, c2));
companyRepo.save(company);
// initial List Companies variable
List<Company> companies = null;
// fetch all documents
System.out.println("==========Fetch aLL companies:==========");
companies = companyRepo.findAll();
companies.forEach(System.out::println);
// find Company by name
System.out.println("==========Find a company by name:==========");
companies = companyRepo.findByName("Samsung");
companies.forEach(System.out::println);
// find Company by address
System.out.println("==========Find a company by address:==========");
companies = companyRepo.findByAddress("Cupertino, CA 95014");
companies.forEach(System.out::println);
}
public static void main(String[] args) {
SpringApplication.run(SpringDataMongoDbApplication.class, args);
}
}
|
package ornek16;
public class Liste {
Eleman bas;
Eleman son;
public Liste() {
bas = null;
son = null;
}
void basaEkle(Eleman yeni) {
if (bas == null) {
bas = yeni;
son = yeni;
} else {
yeni.ileri = bas;
bas = yeni;
}
}
void sonaEkle(Eleman yeni) {
if (bas == null) {
son = yeni;
bas = yeni;
} else {
son.ileri = yeni;
son = son.ileri;
}
}
void yazdir() {
Eleman tmp = bas;
System.out.print("liste : ");
while (tmp != null) {
System.out.print(tmp.icerik + " ");
tmp = tmp.ileri;
}
}
//bir bağlı listenin belirli bir parçasını kesip diğer bir listeye yapıştırmak istiyoruz
//kesmenin başladığı ve bittiği yer ile kopyalanacak yerin adreslerinin verildğini varsayarak
//bu işlemi yapan fonksiyon
void belirliParcaKesipYapıstırma(Eleman basla, Eleman bitis, Eleman kopyalanan) {
Eleman baslatmp = bas;
Eleman bitistmp = bas;
Eleman once = null;
//başla elemanın bulunduğu kısım
while (baslatmp != null && baslatmp != basla) {
once = baslatmp;
baslatmp = baslatmp.ileri;
}
//bitis elemanın bulunduğu kısım
while (bitistmp != null && bitistmp != bitis) {
bitistmp = bitistmp.ileri;
}
//eğer kesilecek eleman baş ise
if (basla == bas) {
baslatmp = bitis.ileri;
bas = baslatmp;
bitistmp.ileri = null;
} //diğer durumlarda
else {
once.ileri = bitistmp.ileri;
bitistmp.ileri = null;
}
//kesilen elemanları diğer listeye eklenmesi
kopyalanan.ileri = basla;
}
}
|
/*
* 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 controlador;
import Modelo.Avance;
import Modelo.Programa;
import persistencia.Avances;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author gateway1
*/
@WebServlet(name = "Dateupdate", urlPatterns = {"/Dateupdate"})
public class Dateupdate extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.o
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Calendar fecha = Calendar.getInstance();
int año = fecha.get(Calendar.YEAR);
int mes1 = fecha.get(Calendar.MONTH) + 1;
int dia = fecha.get(Calendar.DAY_OF_MONTH);
String fechac = año + "/" + mes1 + "/" + dia;
HttpSession objSesion = request.getSession(true);
ArrayList<String> arr= new ArrayList<>();
//i_d
String usuario = (String) objSesion.getAttribute("usuario");
String tiposs = (String) objSesion.getAttribute("tipo");
System.out.println(tiposs);
try{
if (usuario != null && tiposs != null ) {
if(tiposs.equals("ADMIN")){
}else{
response.sendRedirect("../index.jsp");
}
} else {
response.sendRedirect("../index.jsp");
}
Avance deps = new Avance();
Avances a = new Avances();
arr=deps.alldepcharge(arr);
a.dateupdate(arr, fechac);
System.out.println("Completo");
response.sendRedirect("admin/index.jsp");
}catch(Exception e){
System.out.println(e);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
public boolean explote(String lote){
boolean flag =false;
String patl="\\d{1,6}";
Pattern pat2 =Pattern.compile(patl);
Matcher match2 = pat2.matcher(lote);
if(match2.matches()){
flag=true;
System.out.println("Lote bien :D");
}
return flag;
}
}
|
package chartsManager;
import hadoopManager.SingleUrlGenerator;
import hadoopManager.UrlGenerator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.jfree.util.Log;
/**
*
* @author Romano Simone - www.sromano.altervista.org
* This class groups each created chart.
*/
public class Chart_sCollector {
private static final int DATA_PERCENTAGE = 60;
private static final String RAM_COL_REF = "used";
private static final String CPU_COL_REF = "% usr";
private static HashMap<String,ArrayList<Chart>> chart_s;
private static HashMap<String,ArrayList<Chart>> positiveWarningChart_s, negativeWarningChart_s;
private static double CPU_POSITIVE_LIMIT, RAM_POSITIVE_LIMIT, IO_POSITIVE_LIMIT;
private static double SWAP_NEGATIVE_LIMIT, NETWORK_NEGATIVE_LIMIT, RAM_NEGATIVE_LIMIT;
public static void addChart(Chart toAdd){
if(chart_s == null)
chart_s = new HashMap<String,ArrayList<Chart>>();
if(chart_s.get(toAdd.getSlave()) == null)
chart_s.put(toAdd.getSlave(), new ArrayList<Chart>());
if(!alreadyIn(chart_s.get(toAdd.getSlave()), toAdd))
chart_s.get(toAdd.getSlave()).add(toAdd);
Log.info("New chart added to collection: " + toAdd.getTitle() + "_" + toAdd.getSlave());
}
private static boolean alreadyIn(ArrayList<Chart> arrayList, Chart toAdd) {
for(Chart c:arrayList)
if(c.equals(toAdd))
return true;
return false;
}
public static double getCPU_POSITIVE_LIMIT() {
return CPU_POSITIVE_LIMIT;
}
public static void setCPU_POSITIVE_LIMIT(double cPU_POSITIVE_LIMIT) {
CPU_POSITIVE_LIMIT = cPU_POSITIVE_LIMIT;
}
public static double getRAM_POSITIVE_LIMIT() {
return RAM_POSITIVE_LIMIT;
}
public static void setRAM_POSITIVE_LIMIT(double rAM_POSITIVE_LIMIT) {
RAM_POSITIVE_LIMIT = rAM_POSITIVE_LIMIT;
}
public static double getIO_POSITIVE_LIMIT() {
return IO_POSITIVE_LIMIT;
}
public static void setIO_POSITIVE_LIMIT(double iO_POSITIVE_LIMIT) {
IO_POSITIVE_LIMIT = iO_POSITIVE_LIMIT;
}
public static double getSWAP_NEGATIVE_LIMIT() {
return SWAP_NEGATIVE_LIMIT;
}
public static void setSWAP_NEGATIVE_LIMIT(double sWAP_NEGATIVE_LIMIT) {
SWAP_NEGATIVE_LIMIT = sWAP_NEGATIVE_LIMIT;
}
public static double getNETWORK_NEGATIVE_LIMIT() {
return NETWORK_NEGATIVE_LIMIT;
}
public static void setNETWORK_NEGATIVE_LIMIT(double nETWORK_NEGATIVE_LIMIT) {
NETWORK_NEGATIVE_LIMIT = nETWORK_NEGATIVE_LIMIT;
}
public static double getRAM_NEGATIVE_LIMIT() {
return RAM_NEGATIVE_LIMIT;
}
public static void setRAM_NEGATIVE_LIMIT(double rAM_NEGATIVE_LIMIT) {
RAM_NEGATIVE_LIMIT = rAM_NEGATIVE_LIMIT;
}
public static HashMap<String, ArrayList<Chart>> getPositiveWarningChart_s(){
positiveWarningChart_s = new HashMap<String, ArrayList<Chart>>();
Set<Entry<String, ArrayList<Chart>>> setChart = chart_s.entrySet();
for (Entry<String, ArrayList<Chart>> c:setChart)
if(isPositiveWarningChart(c)){
positiveWarningChart_s.put(c.getKey(), c.getValue());
Log.info("Positive warning chart found: " + c.getKey());
}
return positiveWarningChart_s;
}
public static HashMap<String, ArrayList<Chart>> getNegativeWarningChart_s(){
negativeWarningChart_s = new HashMap<String, ArrayList<Chart>>();
Set<Entry<String, ArrayList<Chart>>> setChart = chart_s.entrySet();
for (Entry<String, ArrayList<Chart>> c:setChart)
if(isNegativeWarningChart(c))
negativeWarningChart_s.put(c.getKey(), c.getValue());
return negativeWarningChart_s;
}
/**
* to be positive a set of chart must have:
* Cpu, Ram and disk IO under a specific threshold
*/
public static boolean isPositiveWarningChart(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> CPU_Usage_Chart_s = getCpuUsageChart_s(allChart_s);
ArrayList<Chart> RAM_Usage_Chart_s = getRamUSageChart_s(allChart_s);
ArrayList<Chart> IO_Usage_Chart_s = getIOUsageChart_s(allChart_s);
if(underCpuLimit(CPU_Usage_Chart_s) && underRamLimit(RAM_Usage_Chart_s) && underIOLimit(IO_Usage_Chart_s))
return true;
return false;
}
/**
* This method extract from all input chart only
* the one relative to IO usage.
* @param allChart_s
* @return
*/
private static ArrayList<Chart> getIOUsageChart_s(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> toReturn = new ArrayList<Chart>();
for(Chart chart:allChart_s.getValue()){
if(chart.getTitle() == UrlGenerator.DISK_INPUT || chart.getTitle() == UrlGenerator.DISK_OUTPUT)
toReturn.add(chart);
}
return toReturn;
}
/**
* This method extract from all input chart only
* the one relative to RAM usage.
* @param allChart_s
* @return
*/
private static ArrayList<Chart> getRamUSageChart_s(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> toReturn = new ArrayList<Chart>();
for(Chart chart:allChart_s.getValue()){
if(chart.getTitle() == UrlGenerator.RAM_USAGE)
toReturn.add(chart);
}
return toReturn;
}
/**
* This method extract from all input chart only
* the one relative to cpu usage.
* @param allChart_s
* @return
*/
private static ArrayList<Chart> getCpuUsageChart_s(Entry<String, ArrayList<Chart>> allChart_s){
ArrayList<Chart> toReturn = new ArrayList<Chart>();
for(Chart chart:allChart_s.getValue()){
if(chart.getTitle() == UrlGenerator.CPU_USAGE)
toReturn.add(chart);
}
return toReturn;
}
private static boolean underIOLimit(ArrayList<Chart> iO_Usage_Chart_s) {
for(Chart c:iO_Usage_Chart_s){
if(c.getTitle().equals(SingleUrlGenerator.DISK_INPUT)){
if(under(DATA_PERCENTAGE, c.getData(), IO_POSITIVE_LIMIT))
return true;
}
if(c.getTitle().equals(SingleUrlGenerator.DISK_OUTPUT)){
if(under(DATA_PERCENTAGE, c.getData(), IO_POSITIVE_LIMIT))
return true;
}
}
return false;
}
private static boolean underRamLimit(ArrayList<Chart> rAM_Usage_Chart_s) {
for(Chart c:rAM_Usage_Chart_s)
if(c.getyLabel().equals(RAM_COL_REF)){
if(under(DATA_PERCENTAGE, c.getData(), RAM_POSITIVE_LIMIT*1000))
return true;
}
return false;
}
private static boolean underCpuLimit(ArrayList<Chart> cPU_Usage_Chart_s) {
for(Chart c:cPU_Usage_Chart_s)
if(c.getyLabel().equals(CPU_COL_REF)){
if(under(DATA_PERCENTAGE,c.getData(),CPU_POSITIVE_LIMIT))
return true;
return false;
}
return false;
}
private static boolean under(int percentageOfElemUnderLimit, double[] data, double limit) {
double numOfEl = (double)data.length/100*percentageOfElemUnderLimit;
int num = 0;
for(double d:data){
if(d<limit)
num++;
if(num>numOfEl)
return true;
}
return false;
}
public static boolean isNegativeWarningChart(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> SWAP_Usage_Chart_s = getSwapUsageChart_s(allChart_s);
ArrayList<Chart> RAM_Usage_Chart_s = getRamUSageChart_s(allChart_s);
ArrayList<Chart> NETWORK_Usage_Chart_s = getNetworkUsageChart_s(allChart_s);
boolean upperSwap = upperSwapLimit(SWAP_Usage_Chart_s);
boolean upperRam = upperRamLimit(RAM_Usage_Chart_s);
boolean upperNet = upperNetworkLimit(NETWORK_Usage_Chart_s);
if(upperSwap || upperRam || upperNet)
return true;
return false;
}
private static boolean upperNetworkLimit(ArrayList<Chart> nETWORK_Usage_Chart_s) {
boolean toReturn = false;
for(Chart c:nETWORK_Usage_Chart_s){
if(c.getTitle().equals(SingleUrlGenerator.NETWORK_THROUGHPUT_RECEIVED)){
if(upper(DATA_PERCENTAGE, c.getData(), NETWORK_NEGATIVE_LIMIT)){
c.setNETWORK_Negative_Warning(true);
toReturn = true;
}
else
c.setNETWORK_Negative_Warning(false);
}
if(c.getTitle().equals(SingleUrlGenerator.NETWORK_THROUGHPUT_SEND)){
if(upper(DATA_PERCENTAGE, c.getData(), NETWORK_NEGATIVE_LIMIT)){
c.setNETWORK_Negative_Warning(true);
toReturn = true;
}
else
c.setNETWORK_Negative_Warning(false);
}
}
return toReturn;
}
private static boolean upperRamLimit(ArrayList<Chart> rAM_Usage_Chart_s) {
for(Chart c:rAM_Usage_Chart_s)
if(c.getyLabel().equals(RAM_COL_REF)){
if(upper(DATA_PERCENTAGE, c.getData(), RAM_NEGATIVE_LIMIT*1000)){
c.setRAM_Negative_Warning(true);
return true;
}
c.setRAM_Negative_Warning(false);
}
return false;
}
private static boolean upperSwapLimit(ArrayList<Chart> sWAP_Usage_Chart_s) {
for(Chart c:sWAP_Usage_Chart_s)
if(c.getTitle().equals(SingleUrlGenerator.USED_SWAP)){
if(upper(DATA_PERCENTAGE, c.getData(), SWAP_NEGATIVE_LIMIT*1000)){
c.setSWAP_Negative_Warning(true);
return true;
}
c.setSWAP_Negative_Warning(false);
}
return false;
}
private static boolean upper(int percentageOfElemUnderLimit, double[] data, double limit) {
double numOfEl = (double)data.length/100*percentageOfElemUnderLimit;
int num = 0;
for(double d:data){
if(d>limit)
num++;
if(num>numOfEl)
return true;
}
return false;
}
private static ArrayList<Chart> getNetworkUsageChart_s(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> toReturn = new ArrayList<Chart>();
for(Chart chart:allChart_s.getValue()){
if(chart.getTitle() == UrlGenerator.NETWORK_THROUGHPUT_RECEIVED || chart.getTitle() == UrlGenerator.NETWORK_THROUGHPUT_SEND)
toReturn.add(chart);
}
return toReturn;
}
private static ArrayList<Chart> getSwapUsageChart_s(Entry<String, ArrayList<Chart>> allChart_s) {
ArrayList<Chart> toReturn = new ArrayList<Chart>();
for(Chart chart:allChart_s.getValue()){
if(chart.getTitle() == UrlGenerator.USED_SWAP)
toReturn.add(chart);
}
return toReturn;
}
/**
* This method return an html code describing
* positive warning criteria.
* @return positive warning criteria
*/
public static String getPositiveWarningHtml(){
return("In this section there are slave in which: <br>"
+ "<ul><li>Cpu usage has been under " + Chart_sCollector.CPU_POSITIVE_LIMIT
+ " in the column " + Chart_sCollector.CPU_COL_REF + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run <b>AND</b></li>"
+ "<li>I/O usage has been under " + Chart_sCollector.IO_POSITIVE_LIMIT + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run <b>AND</b></li>"
+ "<li>Ram usage has been under " + Chart_sCollector.RAM_POSITIVE_LIMIT
+ " in the column " + Chart_sCollector.RAM_COL_REF + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run</li></lu>");
}
/**
* This method return an html code describing
* negative warning criteria.
* @return negative warning criteria
*/
public static String getNegativeWarningHtml(){
return("In this section there are slave in which: <br>"
+ "<ul><li>Swap usage has been upper " + Chart_sCollector.SWAP_NEGATIVE_LIMIT + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run <b>OR</b></li>"
+ "<li>Network usage has been upper " + Chart_sCollector.NETWORK_NEGATIVE_LIMIT + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run <b>OR</b></li>"
+ "<li>Ram usage has been upper " + Chart_sCollector.RAM_NEGATIVE_LIMIT
+ " in the column " + Chart_sCollector.RAM_COL_REF + " for the "
+ Chart_sCollector.DATA_PERCENTAGE +"% of run</li></lu>");
}
}
|
package hw5.task7;
public class ArrayMinMax {
public static void arrayIntShow(int[] varArr) {
for (int i = 0; i < varArr.length; i++) {
System.out.print(varArr[i] + " ");
}
}
public static void array2DShow(int[][] varArr) {
for (int i = 0; i < varArr.length; i++) {
arrayIntShow(varArr[i]);
System.out.println();
}
}
public static int arrayMin(int[] varArr) {
int min = varArr[0];
for (int i = 1; i < varArr.length; i++) {
if (min > varArr[i]) {
min = varArr[i];
}
}
return min;
}
public static int arrayMax(int[] varArr) {
int max = varArr[0];
for (int i = 1; i < varArr.length; i++) {
if (max < varArr[i]) {
max = varArr[i];
}
}
return max;
}
}
|
package RestAssuredAPI.SampleProject;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import org.junit.Assert;
import io.restassured.response.Response;
import io.cucumber.java.en.*;
import io.cucumber.datatable.*;
public class GetWeatherDetailsSteps {
Scanner sc = new Scanner(System.in) ;
String s = sc.next();
String city;
String appID;
Response response;
String uri = "https://samples.openweathermap.org/data/2.5/weather";
@Given("^I have set the City parameters as \"(.*)\"$")
public void Given_I_Have_Set_the_City_Parameter(String City)
{
this.city=City;
}
@Given("^Appid for the request URI as \"(.*)\"$")
public void Given_AppId_For_the_Request_URI(String appid)
{
this.appID=appid;
}
@When("^I send the Api GetWeatherDetails get request$")
public void When_I_send_API_GetWeatherDeatils_Request()
{
response= given()
.param("q", "London")
.param("appid","439d4b804bc8187953eb36d2a8c26a02")
.when()
.get(uri)
.then()
.extract()
.response();
}
@Then("^status code of the response will be (.*)$")
public void Then_Status_Code_Of_the_Response_will_be(int statuscode)
{
Assert.assertEquals("Validating the Status code of Response",statuscode,response.statusCode());
}
@Then("City name in the response should be {string}")
public void city_name_in_the_response_should_be(String city)
{
Assert.assertEquals("Validating the City name in Response",response.body().jsonPath().get("name"),city);
}
}
|
package com.mwi.aws.dynamodb.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fluttercode.datafactory.impl.DataFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.mfg.Contact;
import com.mfg.OwnerConfig;
import com.mfg.SensorConfig;
public class SensorConfigService {
/** logger. */
private static Logger logger = LoggerFactory.getLogger(OwnerConfigService.class);
/** DynamoDBMapper. */
private DynamoDBMapper mapper;
public SensorConfigService(DynamoDBMapper aMapper) {
mapper = aMapper;
}
public SensorConfig createSensorConfigDummy(String owner) {
DataFactory dataFactory = new DataFactory();
SensorConfig sensorConfig = new SensorConfig();
sensorConfig.setSensorId("SensorId");
sensorConfig.setAddress("");
sensorConfig.setAlias("");
sensorConfig.setAwsThing("EC2GW-NodeRed");
sensorConfig.setEnablePoll(false);
sensorConfig.setInstallationDate("01/01/2018");
sensorConfig.setInstalledBy(" ");
sensorConfig.setLocation("office");
sensorConfig.setMaintContract("monthly");
sensorConfig.setMaintStartDate("01/01/2018");
sensorConfig.setMaintEndDate("01/01/2019");
sensorConfig.setManufacturer("Polaroid");
sensorConfig.setModel("Polaroid 420T");
sensorConfig.setOwner(owner);
sensorConfig.setPollInterval(900001L);
sensorConfig.setSerialNumber("");
sensorConfig.setSoftwareInstalled("");
sensorConfig.setSoftwareLicense("");
sensorConfig.setType("Printer");
sensorConfig.setWarrantyStartDate("");
sensorConfig.setWarrantyEndDate("10/01/2017");
List<String> contactNames = new ArrayList();
sensorConfig.setContactNames(contactNames);
return sensorConfig;
}
}
|
/*
* 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 ldamallet;
import cc.mallet.topics.DMRTopicModel;
import cc.mallet.types.InstanceList;
import java.io.File;
import java.io.IOException;
/**
*
* @author jrobledo
*/
public class DMR {
private int k;
public DMR(int k) {
this.k = k;
}
public void classify(String filename, String output) throws IOException{
InstanceList training = InstanceList.load (new File(filename));
DMRTopicModel lda = new DMRTopicModel(k);
lda.setOptimizeInterval(100);
lda.setTopicDisplay(100, 10);
lda.addInstances(training);
lda.estimate();
lda.writeParameters(new File(output+"_dmr.parameters"));
lda.printState(new File(output+"_dmr.state.gz"));
}
}
|
package com.agharibi.hibernate;
import com.agharibi.hibernate.inheritance.*;
import com.agharibi.hibernate.model.Employee;
import com.agharibi.hibernate.model.Employer;
import com.agharibi.hibernate.model.Movie;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Utils {
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration
.addAnnotatedClass(Student.class)
.addAnnotatedClass(Employee.class)
.addAnnotatedClass(Movie.class)
.addAnnotatedClass(Employer.class)
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(User.class)
.addAnnotatedClass(Engineer.class)
.addAnnotatedClass(Dev.class)
.addAnnotatedClass(DevOps.class)
.addAnnotatedClass(Banker.class)
.addAnnotatedClass(Teller.class)
.addAnnotatedClass(Financier.class)
.addAnnotatedClass(Teacher.class)
.addAnnotatedClass(Principle.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
|
package db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ACID {
public ACID (Context context){
setContext(context);
}
public boolean addUserIDandpassword(String UserID,String password,String Databasename){
Cursor cursor = null;
boolean bool = false;
ImportDB importdb = new ImportDB(context, Databasename);
SQLiteDatabase db = importdb.openDatabase(true);
String sql = "select count(*) as c from sqlite_master where type ='table' and name ='usertable' ";
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
bool = true;
}
}
if(bool == true){
db.execSQL("insert into usertable(userID,password)values(?,?)",
new String[]{UserID,password});
}else{
db.execSQL("create table usertable(userID varchar primary key,password varchar)");
db.execSQL("insert into usertable(userID,password)values(?,?)",
new String[]{UserID,password});
bool = true;
}
return bool;
}
public Word searchword(String word){
Cursor cursor = null;
boolean bool = false;
ImportDB importdb = new ImportDB(context, "englishword");
SQLiteDatabase db = importdb.openDatabase(true);
Word w = new Word();
cursor=db.rawQuery("select * from words where Word = ?",new String[]{word});
if(cursor.moveToFirst()){
do {
w.setSpelling(cursor.getString(cursor.getColumnIndex("Word")));
w.setExample(cursor.getString(cursor.getColumnIndex("lx")));
w.setParaphrase(cursor.getString(cursor.getColumnIndex("meaning")));
w.setSoundmark(cursor.getString(cursor.getColumnIndex("Soundmark")));
w.setPronounce(cursor.getBlob(cursor.getColumnIndex("Pronounce")));
}while (cursor.moveToNext());
}
return w;
}
public void updateOrder(List<Wordbook>list){
System.out.println(list.get(0).getName());
Cursor cursor;
ImportDB importdb = new ImportDB(context,"wordbooklist");
SQLiteDatabase db = importdb.openDatabase(true);
for(int i = 0;i < list.size();i++ ) {
if(list.get(i).getOrder()!= i+1 )
db.execSQL("Update Wordbooklist set ord = ? where name = ?",new String[]{String.valueOf(i+1),list.get(i).getName()});
}
}
public void addwordbooklist(Wordbook wb , String usestate){
Cursor cursor;
ImportDB importdb = new ImportDB(context,"wordbooklist");
SQLiteDatabase db = importdb.openDatabase(true);
cursor = db.rawQuery("select count(*) from Wordbooklist",null);
cursor.moveToFirst();
long count = cursor.getLong(0);
cursor.close();
db.execSQL("insert into Wordbooklist(name,author,picture," +
"Downnumber,Collectnumber,type,wordnumber,state,usestate,ord)values(?,?,?,?,?,?,?,?,?,?)",
new String[]{wb.getName(),wb.getAuthor(),String.valueOf(wb.getPicture()),String.valueOf(wb.getDownnumber()),String.valueOf(wb.getCollectnumber())
,wb.getType(),String.valueOf(wb.getWordnumber()),String.valueOf(wb.getstate()),usestate,String.valueOf(count+1)});
}
public Wordbook openwordbook(String name){
Cursor cursor;
ImportDB importdb = new ImportDB(context,name);
SQLiteDatabase db = importdb.openDatabase(true);
Wordbook wd = new Wordbook();
cursor=db.rawQuery("selet * from Wordbooklist where name = ?",new String[]{name});
if(cursor.moveToFirst()){
do {
wd.setCollectnumber(cursor.getInt(cursor.getColumnIndex("Collectnumber")));
wd.setDownnumber(cursor.getInt(cursor.getColumnIndex("Downnumber")));
wd.setPicture(cursor.getBlob(cursor.getColumnIndex("picture")));
wd.setAuthor(cursor.getString(cursor.getColumnIndex("author")));
wd.setName(cursor.getString(cursor.getColumnIndex("name")));
wd.setType(cursor.getString(cursor.getColumnIndex("type")));
wd.setWordnumber(cursor.getInt(cursor.getColumnIndex("wordnumber")));
wd.setState(cursor.getString(cursor.getColumnIndex("state")));
}while (cursor.moveToNext());
}
return wd;
}
public List<Wordbook> getwordbooklist(String userstate){
Cursor cursor;
List<Wordbook> list =new ArrayList<Wordbook>();
ImportDB importdb = new ImportDB(context,"wordbooklist");
SQLiteDatabase db = importdb.openDatabase(true);
if(userstate==null){
cursor=db.rawQuery("select * from wordbooklist",new String[]{});
}else{
cursor=db.rawQuery("select * from wordbooklist where usestate = ? order by ord",new String[]{userstate});}
if(cursor.moveToFirst()) {
do {
Wordbook wd = new Wordbook();
wd.setCollectnumber(cursor.getInt(cursor.getColumnIndex("Collectnumber")));
wd.setDownnumber(cursor.getInt(cursor.getColumnIndex("Downnumber")));
wd.setPicture(cursor.getBlob(cursor.getColumnIndex("picture")));
wd.setAuthor(cursor.getString(cursor.getColumnIndex("author")));
wd.setName(cursor.getString(cursor.getColumnIndex("name")));
wd.setType(cursor.getString(cursor.getColumnIndex("type")));
wd.setWordnumber(cursor.getInt(cursor.getColumnIndex("wordnumber")));
wd.setState(cursor.getString(cursor.getColumnIndex("state")));
list.add(wd);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
public List<Word> getwordfromwb(String name,String laststring){
Cursor cursor=null;
List<Word> list =new ArrayList<Word>();
ImportDB importdb = new ImportDB(context,name);//
ImportDB importdb1 = new ImportDB(context,"englishword");
SQLiteDatabase db = importdb.openDatabase(true);
SQLiteDatabase db1 = importdb1.openDatabase(true);
int number = 0;
if(db==null)return null;
if(laststring==null){
number=0;
}else{
cursor=db.rawQuery("select * from ? where name = ?",new String[]{name,laststring});
if(cursor.moveToFirst()){
do{
number=cursor.getInt(cursor.getColumnIndex("rowid"));
}while (cursor.moveToNext());
}}
cursor=db.rawQuery("select * from "+name+" order by rowid desc limit ?,?"
,new String[]{String.valueOf(number),String.valueOf(number+10)});
if(cursor.moveToFirst()){
do{
Cursor cursor1=null;
cursor1=db1.rawQuery("select * from words where Word = ?",
new String[]{cursor.getString(cursor.getColumnIndex("name"))});
if(cursor1.moveToFirst()){
do {
Word w = new Word();
w.setSpelling(cursor1.getString(cursor1.getColumnIndex("Word")));
w.setExample(cursor1.getString(cursor1.getColumnIndex("lx")));
w.setParaphrase(cursor1.getString(cursor1.getColumnIndex("meaning")));
w.setSoundmark(cursor1.getString(cursor1.getColumnIndex("Soundmark")));
w.setPronounce(cursor1.getBlob(cursor1.getColumnIndex("Pronounce")));
list.add(w);
}while (cursor1.moveToNext());
}
}while (cursor.moveToNext());
}
return list;
}
public void addword(String name,String word){
ImportDB importdb = new ImportDB(context,name);
SQLiteDatabase db = importdb.openDatabase(true);
db.execSQL("insert into "+name+"(name)values(?);",new String[]{word});
}
public void addword(String name,String word,String familarity){
ImportDB importdb = new ImportDB(context,name);
SQLiteDatabase db = importdb.openDatabase(true);
db.execSQL("insert into "+name+"(name,familarity)values(?,?)",new String[]{word});
}
public void deleteword(String name,String word){
ImportDB importdb = new ImportDB(context,name);
SQLiteDatabase db = importdb.openDatabase(true);
db.execSQL("delete from "+name+" where name = ?",new String[]{word});
}
public boolean createwordbook(String name,String Discri,String Prim,byte[] picture){
Cursor cursor=null;
ImportDB importdb = new ImportDB(context,name);
SQLiteDatabase db = importdb.openDatabase(true);
db.execSQL("create table "+name+"([name] VARCHAR(100) PRIMARY KEY ON CONFLICT REPLACE)");
importdb = new ImportDB(context,"wordbooklist");
db = importdb.openDatabase(true);
db.execSQL("insert into wordbooklist(name,author,picture,Downnumber," +
"Collectnumber,type,wordnumber,state,usestate,ord,discri,prim)",new String[]{name,"asdsf",String.valueOf(picture),
String.valueOf(0),String.valueOf(0),"备考",String.valueOf(0),String.valueOf(0),"自定义",String.valueOf(1),"fsgdh",String.valueOf(false)});
return true;
}
// public List<Word> getword(String name){
// Cursor cursor = null;
// Cursor cursor1 = null;
// ImportDB importdb = new ImportDB(context,name);
// ImportDB importdb1 = new ImportDB(context,"mywords");
// SQLiteDatabase db = importdb.openDatabase(true);
// SQLiteDatabase db1 = importdb1.openDatabase(true);
// List<Word> list =new ArrayList<Word>();
// Random r = new Random();
// String[] word = new String[10];
// cursor = db.rawQuery("select count(*) from "+name,null);
// cursor.moveToFirst();
// long count = cursor.getLong(0);
// int c=0;
// while (c<10) {
// int num = r.nextInt((int) count) + 1 % (int) count;
// cursor = db.rawQuery("select name from " + name + " where rowid = ?", new String[]{String.valueOf(num)});
// cursor.moveToFirst();
// boolean bool=true;
// for(int i=0;i<c;i++){
// if(word[i].equals(cursor.getString(cursor.getColumnIndex("name"))))bool=false;
// }
// if(bool==false);else{
// //System.out.println(cursor.getString(cursor.getColumnIndex("name")));
// cursor1 = db1.rawQuery("select familarity from mywords where name = ?", new String[]{
// cursor.getString(cursor.getColumnIndex("name"))});
// cursor1.moveToFirst();
// if (cursor1.getCount() == 0) {
// word[c] = cursor.getString(cursor.getColumnIndex("name"));
// c++;
// } else {
// if (Integer.parseInt(cursor1.getString(cursor1.getColumnIndex("familarity"))) == 3) {
// //r.nextInt((int)count+1);
// } else {
// word[c] = cursor.getString(cursor.getColumnIndex("name"));
// c++;
// }
// }
// }
// }
// System.out.println("word"+word[9]);
// importdb = new ImportDB(context,"englishword");
// db=importdb.openDatabase(true);
// int d=0;
// while (d<10){
// cursor= db.rawQuery("select * from words where Word = ?",new String[]{word[d]});
// cursor.moveToFirst();
// Word w = new Word();
// w.setSpelling(cursor.getString(cursor.getColumnIndex("Word")));
// w.setExample(cursor.getString(cursor.getColumnIndex("lx")));
// w.setParaphrase(cursor.getString(cursor.getColumnIndex("meaning")));
// w.setSoundmark(cursor.getString(cursor.getColumnIndex("Soundmark")));
// w.setPronounce(cursor.getBlob(cursor.getColumnIndex("Pronounce")));
// list.add(w);
// d++;
// }
// return list;
// }
public List<Word> getword(String name){
Cursor cursor = null;
Cursor cursor1 = null;
ImportDB importdb = new ImportDB(context,name);
ImportDB importdb1 = new ImportDB(context,"mywords");
SQLiteDatabase db = importdb.openDatabase(true);
SQLiteDatabase db1 = importdb1.openDatabase(true);
List<Word> list =new ArrayList<Word>();
List<String> word =new ArrayList<String>();
Random r = new Random();
cursor=db.rawQuery("select name from "+name,new String[]{});
if(cursor.moveToFirst()){
do {
cursor1 = db1.rawQuery("select familarity from mywords where name = ?", new String[]{
cursor.getString(cursor.getColumnIndex("name"))});
cursor1.moveToFirst();
if(cursor1.getString(cursor1.getColumnIndex("familarity")).equals("3"));
else word.add(cursor.getString(cursor.getColumnIndex("name")));
}while (cursor.moveToNext());
}
int count = 0;
if(word.size()>50)count=50;
else count=word.size();
String[] Word = new String[count];
for(int i=0;i<count;i++) {
int num=r.nextInt(word.size())+1%word.size();
Word[i]=word.get(num);
word.remove(num);
}
importdb = new ImportDB(context,"englishword");
db=importdb.openDatabase(true);
int c=0;
while (c<count){
cursor= db.rawQuery("select * from words where Word = ?",new String[]{Word[c]});
cursor.moveToFirst();
Word w = new Word();
w.setSpelling(cursor.getString(cursor.getColumnIndex("Word")));
w.setExample(cursor.getString(cursor.getColumnIndex("lx")));
w.setParaphrase(cursor.getString(cursor.getColumnIndex("meaning")));
w.setSoundmark(cursor.getString(cursor.getColumnIndex("Soundmark")));
w.setPronounce(cursor.getBlob(cursor.getColumnIndex("Pronounce")));
list.add(w);
c++;
}
return list;
}
public void addintomywords(List<Word> L){
ImportDB importdb = new ImportDB(context,"mywords");
SQLiteDatabase db=importdb.openDatabase(true);
for(int i=0;i<L.size();i++){
db.execSQL("insert into mywords(name,familarity)values(?,?)",new String[]{L.get(i).getSpelling(),
String.valueOf(L.get(i).getFamilarity())});
}
// Cursor cursor =null;
// cursor=db.rawQuery("select * from mywords where name=?",new String[]{L.get(1).getSpelling()});
// cursor.moveToFirst();
// System.out.println(cursor.getString(cursor.getColumnIndex("name")));
// System.out.println(cursor.getString(cursor.getColumnIndex("familarity")));
}
public void addxmlnode(String word,String xmlDocname){
}
public void getxmlnode(String xmlDocname){
ImportxmlDoc importxmlDoc = new ImportxmlDoc(context,xmlDocname);
}
void setContext(Context pcontext){
context = pcontext;
}
Context getContext(){
return context;
}
private Context context;
}
|
/*
Copyright 2005-2015, Foundations of Success, Bethesda, Maryland
on behalf of the Conservation Measures Partnership ("CMP").
Material developed between 2005-2013 is jointly copyright by Beneficent Technology, Inc. ("The Benetech Initiative"), Palo Alto, California.
This file is part of Miradi
Miradi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3,
as published by the Free Software Foundation.
Miradi 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Miradi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.miradi.objects;
import org.miradi.objecthelpers.ORef;
import org.miradi.project.ProjectForTesting;
import org.miradi.schemas.ThreatRatingCommentsDataSchema;
public class TestThreatRatingCommentsData extends ObjectTestCase
{
public TestThreatRatingCommentsData(String name)
{
super(name);
}
public void testFields() throws Exception
{
verifyFields(ThreatRatingCommentsDataSchema.getObjectType());
}
public void testFindComment() throws Exception
{
ORef threatRatingCommentsDataRef = getProject().getSingletonObjectRef(ThreatRatingCommentsDataSchema.getObjectType());
assertTrue("singlton threat rating comments data does not exist?", !threatRatingCommentsDataRef.isInvalid());
ThreatRatingCommentsData threatRatingCommentsData = ThreatRatingCommentsData.find(getProject(), threatRatingCommentsDataRef);
Cause cause = getProject().createCause();
Target target = getProject().createTarget();
getProject().populateThreatRatingCommentsData(threatRatingCommentsData, cause.getRef(), target.getRef());
assertTrue("project is not in simple threat rating mode?", getProject().isSimpleThreatRatingMode());
String simpleThreatRatingComment = threatRatingCommentsData.findComment(cause.getRef(), target.getRef());
assertEquals("wrong simple based threat rating comment?", ProjectForTesting.SIMPLE_THREAT_RATING_COMMENT, simpleThreatRatingComment);
getProject().switchToStressBaseMode();
assertTrue("project is not in stress based threat rating mode?", getProject().isStressBaseMode());
String stressBasedThreatRatingComment = threatRatingCommentsData.findComment(cause.getRef(), target.getRef());
assertEquals("wrong simple based threat rating comment?", ProjectForTesting.STRESS_BASED_THREAT_RATING_COMMENT, stressBasedThreatRatingComment);
}
}
|
package ch09.test;
public class Test03_2 {
}
|
package com.client;
import com.ringoram.BucketMetadata;
public interface ClientInterface {
/*when read or write block, first read path from server
* @param pathID: path that need to get from server
* @param blockIndex: block that want to request
*/
public void read_path(int pathID, int blockIndex);
//when request time reaches shuffle rate, evict path
public void evict_path(int pathID);
//when block in bucket almost all accessed, early re-shuffle the bucket
public void early_reshuffle(int pathID, BucketMetadata[] meta_list);
}
|
/* __
* \ \
* _ _ \ \ ______
* | | | | > \( __ )
* | |_| |/ ^ \| || |
* | ._,_/_/ \_\_||_|
* | |
* |_|
*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <rob ∂ CLABS dot CC> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
package cc.clabs.stratosphere.mlp.utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.EntityArrays;
import org.apache.commons.lang3.text.translate.LookupTranslator;
/**
*
* @author rob
*/
public class StringUtils {
/**
* map of alphabetic chars to their unicode superscript codepoints
*/
private final static Map<String,String> superscripts = Collections.unmodifiableMap(new HashMap<String,String>() {
{
// 0-9
put( "0", "⁰" ); put( "1", "¹" ); put( "2", "²" ); put( "3", "³" );
put( "4", "⁴" ); put( "5", "⁵" ); put( "6", "⁶" ); put( "7", "⁷" );
put( "8", "⁸" ); put( "9", "⁹" );
// a-z (except q)
put( "a", "ᵃ" ); put( "b", "ᵇ" ); put( "c", "ᶜ" ); put( "d", "ᵈ" );
put( "e", "ᵉ" ); put( "f", "ᶠ" ); put( "g", "ᵍ" ); put( "h", "ʰ" );
put( "i", "ⁱ" ); put( "j", "ʲ" ); put( "k", "ᵏ" ); put( "l", "ˡ" );
put( "m", "ᵐ" ); put( "n", "ⁿ" ); put( "o", "ᵒ" ); put( "p", "ᵖ" );
put( "r", "ʳ" ); put( "s", "ˢ" ); put( "t", "ᵗ" ); put( "u", "ᵘ" );
put( "v", "ᵛ" ); put( "w", "ʷ" ); put( "x", "ˣ" ); put( "y", "ʸ" );
put( "z", "ᶻ" );
// most uppercases
put( "A", "ᴬ" ); put( "b", "ᴮ" ); put( "D", "ᴰ" ); put( "E", "ᴱ" );
put( "G", "ᴳ" ); put( "H", "ᴴ" ); put( "I", "ᴵ" ); put( "J", "ᴶ" );
put( "K", "ᴷ" ); put( "L", "ᴸ" ); put( "M", "ᴹ" ); put( "N", "ᴺ" );
put( "O", "ᴼ" ); put( "P", "ᴾ" ); put( "R", "ᴿ" ); put( "T", "ᵀ" );
put( "U", "ᵁ" ); put( "V", "ⱽ" ); put( "W", "ᵂ" );
// some greeks
put( "α", "ᵅ" ); put( "β", "ᵝ" ); put( "γ", "ᵞ" ); put( "δ", "ᵟ" );
put( "ε", "ᵋ" ); put( "θ", "ᶿ" ); put( "ι", "ᶥ" ); put( "Φ", "ᶲ" );
put( "φ","ᵠ" ); put( "χ", "ᵡ" );
}
});
/**
* map of alphabetic chars to their unicode subscript codepoints
*/
private static Map<String,String> subscripts = Collections.unmodifiableMap(new HashMap<String,String>() {
{
// 0-9
put( "0", "₀" ); put( "1", "₁" ); put( "2", "₂" ); put( "3", "₃" );
put( "4", "₄" ); put( "5", "₅" ); put( "6", "₆" ); put( "7", "₇" );
put( "8", "₈" ); put( "9", "₉" );
// few lowercases
put( "a", "ₐ" ); put( "e", "ₑ" ); put( "i", "ᵢ" ); put( "j", "ⱼ" );
put( "o", "ₒ" ); put( "r", "ᵣ" ); put( "u", "ᵤ" );
put( "v", "ᵥ" ); put( "x", "ₓ" );
// some greeks
put( "β", "ᵦ" ); put( "γ", "ᵧ" ); put( "ρ", "ᵨ" );
put( "φ","ᵩ" ); put( "χ", "ᵪ" );
}
});
/**
* Unescapes special entity char sequences like < to its UTF-8 representation.
* All ISO-8859-1, HTML4 and Basic entities will be translated.
*
* @param text the text that will be unescaped
* @return the unescaped version of the string text
*/
public static String unescapeEntities( String text ) {
CharSequenceTranslator iso = new LookupTranslator( EntityArrays.ISO8859_1_UNESCAPE() );
CharSequenceTranslator basic = new LookupTranslator( EntityArrays.BASIC_UNESCAPE() );
CharSequenceTranslator html4 = new LookupTranslator( EntityArrays.HTML40_EXTENDED_UNESCAPE() );
return subsup( html4.translate( iso.translate( basic.translate( text ) ) ) );
}
public static String getSuperscriptChar( String chr ) {
return superscripts.containsKey( chr ) ?
superscripts.get( chr ) : chr;
}
public static String getSubscriptChar( String chr ) {
return subscripts.containsKey( chr ) ?
subscripts.get( chr ) : chr;
}
private static String subsup( String html ) {
// match <sub|sup> tags as well as wikipedias {{sub|}} {{sup|}} templates
Pattern subsuper = Pattern.compile( "(?:\\{\\{|<)(sub|sup)(?:>|\\|)(.)(?:\\}\\}|<\\/\\1>)" );
Matcher m;
while ( (m = subsuper.matcher( html )).find() ) {
String where = m.group( 1 );
String what = m.group( 2 );
if ( where.equals( "sub" ) ) {
what = getSubscriptChar( what );
} else {
what = getSuperscriptChar( what );
}
html = m.replaceFirst( what );
}
return html;
}
}
|
package com.example.proyectogrupal;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.storage.StorageManager;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.proyectogrupal.entidades.IncidenciaDto;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import static com.example.proyectogrupal.util.Constants.MAPVIEW_BUNDLE_KEY;
public class RegistrarIncidencia extends AppCompatActivity implements OnMapReadyCallback {
private static final int PICK_IMAGE_REQUEST = 1;
double latitud, longitud;
private EditText editTextTextNombreIncidencia, editTextDescripcionIncidencia;
private ImageView imageViewAgregarFoto;
private Button buttonEnviarIncidencia, buttonSubirFoto;
private ProgressBar progressbar_SubirFoto;
private Uri myImageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private StorageTask storageTask;
private MapView mMapView;
private GoogleMap gMap;
private FusedLocationProviderClient fusedLocationProviderClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_incidencia);
editTextTextNombreIncidencia = findViewById(R.id.editTextTextNombreIncidencia);
editTextDescripcionIncidencia = findViewById(R.id.editTextDescripcionIncidencia);
imageViewAgregarFoto = findViewById(R.id.imageViewAgregarFoto);
buttonEnviarIncidencia = findViewById(R.id.buttonEnviarIncidencia);
buttonSubirFoto = findViewById(R.id.buttonSubirFoto);
progressbar_SubirFoto = findViewById(R.id.progressbar_SubirFoto);
mMapView = (MapView) findViewById(R.id.mapView_IncidenciaUser);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
storageReference = FirebaseStorage.getInstance().getReference("Incidencias");
databaseReference = FirebaseDatabase.getInstance().getReference("Incidencias");
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
buttonSubirFoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ElegirImagen();
}
});
buttonEnviarIncidencia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (storageTask != null && storageTask.isInProgress()) {
Toast.makeText(RegistrarIncidencia.this, "Envío en proceso", Toast.LENGTH_SHORT).show();
} else {
EnviarIncidencia();
}
}
});
}
private String extensionArchivo(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void EnviarIncidencia() {
final String nombre = editTextTextNombreIncidencia.getText().toString();
final String descripcion = editTextDescripcionIncidencia.getText().toString();
final boolean estado = false;
final String comentario = null;
if (nombre.isEmpty()) {
editTextTextNombreIncidencia.setError("Nombre no debe quedar vacío");
} else if (descripcion.isEmpty()) {
editTextDescripcionIncidencia.setError("Descripción no debe quedar vacio");
} else {
if (myImageUri != null) {
//ASIGNACIÓN DEL NOMBRE DE LA IMAGEN Y SU EXTENSIÓN
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + extensionArchivo(myImageUri));
storageTask = fileReference.putFile(myImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
progressbar_SubirFoto.setProgress(0);
}
}, 500);
String id = databaseReference.push().getKey();
String url = taskSnapshot.getUploadSessionUri().toString();
if (id != null) {
//SE AGREGAN LOS DATOS OBTENIDOS A DATABSE
IncidenciaDto incidenciaDto = new IncidenciaDto(id, nombre, url, descripcion, latitud, longitud, estado, comentario);
databaseReference.child(id).setValue(incidenciaDto);
Toast.makeText(RegistrarIncidencia.this, "Registro exitoso", Toast.LENGTH_SHORT).show();
finish();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(RegistrarIncidencia.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressbar_SubirFoto.setProgress((int) progress);
}
});
} else {
Toast.makeText(RegistrarIncidencia.this, "No se seleccionó fotografía", Toast.LENGTH_SHORT).show();
}
}
}
private void ElegirImagen() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
myImageUri = data.getData();
Picasso.with(this).load(myImageUri).into(imageViewAgregarFoto);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
@Override
public void onMapReady(GoogleMap map) {
gMap = map;
miUbicacion(map);
//map.addMarker(new MarkerOptions().position(new LatLng(latitud, longitud)).title("Marker"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
}
public void miUbicacion(GoogleMap googleMap){
gMap = googleMap;
Log.d("localizacion", "Obteniendo ubicación");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if(task.isSuccessful() ){
Location location = task.getResult();
LatLng miUbicacion = new LatLng(location.getLatitude(), location.getLongitude());
gMap.addMarker(new MarkerOptions().position(miUbicacion).title("Incidencia"));
gMap.moveCamera(CameraUpdateFactory.newLatLng(miUbicacion));
latitud = location.getLatitude();
longitud = location.getLongitude();
Log.d("localizacion", "Lat = "+ latitud);
Log.d("localizacion", "Long = "+ longitud);
}
}
});
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Composition;
/**
*
* @author rm
*/
public class program1 {
private String s1;
private program2 object;
public program1(program2 myopj, String name) {
s1 = name;
object = myopj;
}
// Override
@Override
public String toString() {
return String.format(" %s, and My cit is %s ", object, s1);
}
}
|
import br.com.rafagonc.tjdata.database.ESAJDatabase;
import br.com.rafagonc.tjdata.database.ESAJDatabaseManager;
import br.com.rafagonc.tjdata.models.ESAJPesquisaFoneticaProcesso;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import java.util.UUID;
/**
* Created by rafagonc on 13/08/17.
*/
public class ESAJPesquisaFoneticaProcessoTest {
private ESAJDatabase db;
private ESAJDatabaseManager manager;
@Before
public void setUp() throws Exception {
manager = ESAJDatabaseManager.share();
db = manager.getDatabase();
}
@Test
public void testCreate() throws Exception {
create();
}
@Test
public void testDelete() throws Exception {
ESAJPesquisaFoneticaProcesso pf = create();
Transaction t = manager.begin();
db.getPesquisaFoneticaProcessoRepository().delete(pf);
t.commit();
}
private ESAJPesquisaFoneticaProcesso create() {
Transaction t = manager.begin();
ESAJPesquisaFoneticaProcesso pf = new ESAJPesquisaFoneticaProcesso();
pf.setNomeParte(UUID.randomUUID().toString());
pf.setNumero(UUID.randomUUID().toString());
pf.setDataProcesso(new Date());
pf.setForo(503);
db.getPesquisaFoneticaProcessoRepository().save(pf);
t.commit();
return pf;
}
}
|
package packageone;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.BeforeTest;
public class ClassMain extends Course_Schedule{
@BeforeTest
public void MethodMain() throws IOException, InterruptedException {
int Coulmn_Count=0;
LinkedList<String> Key = new LinkedList<String>();
LinkedList<String> Value = new LinkedList<String>();
File Excel = new File("C:\\Users\\Satish\\eclipse-workspace\\Sample_Project\\DataFolder\\TestData.xlsx");
FileInputStream Read_Write = new FileInputStream(Excel);
XSSFWorkbook wb = new XSSFWorkbook(Read_Write);
XSSFSheet DataSheet = wb.getSheet("TestDataSheet");
DataFormatter formatter = new DataFormatter();
int Row_Count = DataSheet.getLastRowNum()-DataSheet.getFirstRowNum();
System.out.println(Row_Count);
for(int i=0;i<Row_Count;i++) {
Coulmn_Count = DataSheet.getRow(i).getLastCellNum();
for(int j=0;j<Coulmn_Count;j++) {
String Value1 = formatter.formatCellValue(DataSheet.getRow(i).getCell(j));
Key.add(Value1);
}
}
System.out.println(Key);
for(int i=1;i<=Row_Count;i++) {
for(int j=0;j<Coulmn_Count;j++) {
String Value1 = formatter.formatCellValue(DataSheet.getRow(i).getCell(j));
Value.add(Value1);
}
}
System.out.println(Value);
for(int i=0;i<Key.size();i++) {
MapData.put(Key.get(i), Value.get(i));
}
System.out.println(MapData);
}
}
|
/**
* Copyright (c) 2011 SORMA
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Author: sorma@gaoshin.com
*/
package common.util;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
public class ImageUtil {
public static void resize(InputStream in, OutputStream out, int width, int height) throws IOException {
BufferedImage img = ImageIO.read(in);
int w = img.getWidth();
int h = img.getHeight();
int newWidth = 0;
int newHeight = 0;
if (width <= 0) {
float ratio = (float) height / (float) h;
newWidth = (int) ((float) w * ratio);
newHeight = (int) ((float) h * ratio);
} else if (height <= 0) {
float ratio = (float) width / (float) w;
newWidth = (int) ((float) w * ratio);
newHeight = (int) ((float) h * ratio);
} else {
float wratio = (float) width / (float) w;
float hratio = (float) height / (float) h;
newWidth = (int) (w * wratio);
newHeight = (int) (h * hratio);
}
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(img, 0, 0, newWidth, newHeight, null);
g.dispose();
ImageIO.write(resizedImage, "png", out);
}
}
|
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class DBHelper
{
//数据库连接地址
private final static String url = "jdbc:mysql://localhost:3306/doubanmovie?characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true";
//用户名
private final static String userName = "root";
//密码
private final static String password = "08111001";
//驱动类
private final static String driver = "com.mysql.cj.jdbc.Driver";
private static Connection connection = null;
private DBHelper()
{
// 不准实例化
}
/**
* 连接数据库
*
* @return conn
*/
public static Connection getConnection()
{
try
{
if (connection == null || connection.isClosed())
{
Class.forName(driver);
connection = DriverManager.getConnection(url, userName, password);
}
}
catch (Exception e)
{
UtilLogger.log(e);
}
return connection;
}
/**
* 关闭连接对象
*
* @param conn 连接对象
* @param pstmt 预编译对象
*/
public static void close(Connection conn, PreparedStatement pstmt)
{
try
{
if (pstmt != null)
{
pstmt.close();
}
if (conn != null)
{
conn.close();
}
}
catch (Exception e)
{
UtilLogger.log(e);
}
}
public static int update(String sql)
{
int result=0;
Statement state = null;
try
{
state = getConnection().createStatement();
result = state.executeUpdate(sql);
return result;
}
catch (SQLException e)
{
UtilLogger.log(e);
return 0;
}
}
public static int update(String sql, Object... args)
{
int result = 0;
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
if (args != null)
{
for (int i = 1; i <= args.length; i++)
{
preparedStatement.setObject(i, args[i]);
}
}
result = preparedStatement.executeUpdate();
}
catch (Exception e)
{
UtilLogger.log(e);
}
finally
{
close(connection, preparedStatement);
}
return result;
}
public static boolean updateBatch(String sql, Object... args)
{
boolean flag = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = getConnection();
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= args.length; i++)
{
preparedStatement.setObject(i, args[i]);
}
preparedStatement.addBatch();
int [] results=preparedStatement.executeBatch(); //批量执行
connection.commit();//提交事务
preparedStatement.clearBatch();
flag = true;
}
catch (SQLException e)
{
try
{
connection.rollback(); //进行事务回滚
}
catch (SQLException ex)
{
UtilLogger.log(e);
}
}
finally
{
close(connection, preparedStatement);
}
return flag;
}
}
|
package com.appsala.app.controllers;
import java.util.List;
import com.appsala.app.entities.Unidade;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.appsala.app.services.UnidadeService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
@RestController
@RequestMapping("/unidade")
public class UnidadeController {
@Autowired
private UnidadeService unidadeService;
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> findById(@PathVariable Integer id) {
Unidade unidade= unidadeService.findById(id);
return new ResponseEntity<>(unidade, HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<Unidade>> findAll() {
List<Unidade> unidadeList = unidadeService.findAll();
return new ResponseEntity<>(unidadeList, HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<Void> update(@PathVariable Integer id, @RequestBody Unidade unidade) {
unidade = unidadeService.update(unidade);
return ResponseEntity.noContent().build();
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> create(@RequestBody Unidade unidade) {
unidade = unidadeService.create(unidade);
return ResponseEntity.noContent().build();
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> deleteById(@PathVariable Integer id) {
unidadeService.deleteById(id);
return ResponseEntity.noContent().build();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.