text stringlengths 10 2.72M |
|---|
package com.cgi.dentistapp.repository;//Autor: Robert Leht//autor: Robert Leht
import com.cgi.dentistapp.entity.DentistVisitEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DentistVisitRepository extends JpaRepository<DentistVisitEntity, Long> {
@Query(value = "SELECT e FROM DentistVisitEntity e WHERE CONCAT(e.dentistName, ' ', e.visitTime) LIKE %?1%")
List<DentistVisitEntity> search(@Param("keyword") String keyword);
}
|
package usatenko;
import usatenko.pojo.CalculationRequest;
import usatenko.services.CalculationService;
import usatenko.services.ConsoleService;
public class Main {
public static void main(String[] args) {
CalculationRequest request = ConsoleService.initRequest();
String result = CalculationService.multiply(request);
ConsoleService.printResult(result);
}
}
|
/**
* Support for generating GraalVM native configuration from runtime hints.
*/
@NonNullApi
@NonNullFields
package org.springframework.aot.nativex;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.client.web;
import java.io.IOException;
import org.apache.log4j.Logger;
import pl.edu.icm.unity.oauth.client.OAuthContext;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.webui.authn.remote.AbstractRedirectRequestHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinServletResponse;
import com.vaadin.server.VaadinSession;
/**
* Initializes OAuth login by redirecting to a given URL of OAuth2 AS.
* @author K. Benedyczak
*/
public class RedirectRequestHandler extends AbstractRedirectRequestHandler
{
private static final Logger log = Log.getLogger(Log.U_SERVER_OAUTH, RedirectRequestHandler.class);
public RedirectRequestHandler()
{
super(OAuth2Retrieval.REMOTE_AUTHN_CONTEXT);
}
@Override
protected boolean handleRequestInternal(Object contextO, VaadinSession vaadinSession,
VaadinRequest request, VaadinResponse response) throws IOException
{
OAuthContext context = (OAuthContext) contextO;
VaadinServletResponse rr = (VaadinServletResponse) response;
setCommonHeaders(response);
String redirectURL = context.getRequestURI().toString();
if (log.isDebugEnabled())
{
log.debug("Starting OAuth redirection to OAuth provider " + redirectURL);
}
rr.sendRedirect(redirectURL);
return true;
}
}
|
package com.eikesi.demoABC.service.service.mapper;
import com.eikesi.demoABC.service.domain.*;
import com.eikesi.demoABC.service.service.dto.CustomerRelationDTO;
import org.mapstruct.*;
/**
* Mapper for the entity CustomerRelation and its DTO CustomerRelationDTO.
*/
@Mapper(componentModel = "spring", uses = {CustomerMapper.class})
public interface CustomerRelationMapper extends EntityMapper<CustomerRelationDTO, CustomerRelation> {
@Mapping(source = "customer.id", target = "customerId")
@Mapping(source = "customer.firstName", target = "customerFirstName")
CustomerRelationDTO toDto(CustomerRelation customerRelation);
@Mapping(source = "customerId", target = "customer")
CustomerRelation toEntity(CustomerRelationDTO customerRelationDTO);
default CustomerRelation fromId(Long id) {
if (id == null) {
return null;
}
CustomerRelation customerRelation = new CustomerRelation();
customerRelation.setId(id);
return customerRelation;
}
}
|
package com.dassa.vo;
public class SaleInLotsFaqVO {
private int saleInLotsFaqIdx;
private String saleInLotsFaqType;
private String saleInLotsFaqTitle;
private String saleInLotsFaqContent;
public SaleInLotsFaqVO() {
super();
// TODO Auto-generated constructor stub
}
public SaleInLotsFaqVO(int saleInLotsFaqIdx, String saleInLotsFaqType, String saleInLotsFaqTitle,
String saleInLotsFaqContent) {
super();
this.saleInLotsFaqIdx = saleInLotsFaqIdx;
this.saleInLotsFaqType = saleInLotsFaqType;
this.saleInLotsFaqTitle = saleInLotsFaqTitle;
this.saleInLotsFaqContent = saleInLotsFaqContent;
}
public int getSaleInLotsFaqIdx() {
return saleInLotsFaqIdx;
}
public void setSaleInLotsFaqIdx(int saleInLotsFaqIdx) {
this.saleInLotsFaqIdx = saleInLotsFaqIdx;
}
public String getSaleInLotsFaqType() {
return saleInLotsFaqType;
}
public void setSaleInLotsFaqType(String saleInLotsFaqType) {
this.saleInLotsFaqType = saleInLotsFaqType;
}
public String getSaleInLotsFaqTitle() {
return saleInLotsFaqTitle;
}
public void setSaleInLotsFaqTitle(String saleInLotsFaqTitle) {
this.saleInLotsFaqTitle = saleInLotsFaqTitle;
}
public String getSaleInLotsFaqContent() {
return saleInLotsFaqContent;
}
public void setSaleInLotsFaqContent(String saleInLotsFaqContent) {
this.saleInLotsFaqContent = saleInLotsFaqContent;
}
}
|
package com.demo;
public class Counter {
private static int counter;
private int id = counter++;
public String toString() {
return "Counter: " + id;
}
}
|
package com.bnrc.util.collectwifi;
public class Constants {
/* 多盟账号id */
public static final String PUBLISHER_ID = "56OJyM1ouMGoaSnvCK";
public static final String InlinePPID = "16TLwebvAchksY6iO_8oSb-i";
/* 扫描wifi的一些常量 */
public static final String category_str1[] = new String[] { " 北京市 ",
" 上海市 ", " 广州市 ", " 深圳市 ", " 天津市 ", " 南京市 ", " 杭州市 ",
" 大连市 ", " 青岛市 " };
public static final String category_str2[] = new String[] { " 16wifi ",
" BNRC-Air ", " BUPT-1 " };
public static final String UPDATE_ACTION = "com.bnrc.busapp.action.UPDATE_ACTION";
public static final String SERVICE_ACTION = "com.bnrc.busapp.scanservice";
public static final String SHAREPRF_ACTION = "com.bnrc.busapp.setting_broad";
public static final String SSIDSELECT_ACTION = "com.bnrc.busapp.ui_listener_mySelectTouchListener";
public static final String SETTING = "SETTING";
public static final String SETTING_BAT = "SETTING_Battery";
public static final String SETTING_RAD = "SETTING_Radius";
public static final String SETTING_ALE = "SETTING_AlertDistance";
public static final String SETTING_MET = "SETTING_Method";
public static final String SETTING_AP = "SETTING_Ap";
public static final String SETTING_FRE = "SETTING_Frequency";
public static final String SETTING_PRECISION = "SETTING_Precision";
public static final int TYPE_NONE = 0;// 全部标签
public static final int TYPE_ALL = 1;// 全部标签
public static final int TYPE_WORK = 2;// 工作标签
public static final int TYPE_HOME = 3;// 回家标签
public static final int TYPE_OTHER = 4;// 其他标签
// public static final int TYPE_DEL = 5;// 取消收藏标签
public static final int BUSLINE = 1;// 站点
public static final int STATION = 2;// 线路
}
|
package domain;
public class ShuoshuoData {
private int Id;
private String Name;
private String Niname;
private String Posttime;
private String TextContent;
private int Replynum;
private int Visit;
private String Pictures;
private String UserTouxiang;
private String Shuoshuoname;
private int Shuoshuonum;
public int getShuoshuonum() {
return Shuoshuonum;
}
public void setShuoshuonum(int shuoshuonum) {
Shuoshuonum = shuoshuonum;
}
public String getUserTouxiang() {
return UserTouxiang;
}
public void setUserTouxiang(String userTouxiang) {
UserTouxiang = userTouxiang;
}
public String getShuoshuoname() {
return Shuoshuoname;
}
public void setShuoshuoname(String shuoshuoname) {
Shuoshuoname = shuoshuoname;
}
public int getVisit() {
return Visit;
}
public void setVisit(int visit) {
Visit = visit;
}
public String getPosttime() {
return Posttime;
}
public void setPosttime(String posttime) {
Posttime = posttime;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getNiname() {
return Niname;
}
public void setNiname(String niname) {
Niname = niname;
}
public String getPictures() {
return Pictures;
}
public void setPictures(String pictures) {
Pictures = pictures;
}
public String getTextContent() {
return TextContent;
}
public void setTextContent(String textContent) {
TextContent = textContent;
}
public int getReplynum() {
return Replynum;
}
public void setReplynum(int replynum) {
Replynum = replynum;
}
}
|
package org.framestudy.spring_mybatis.relationmag.dao;
import org.framestudy.spring_mybatis.relationmag.beans.Wife;
public interface IWifeDao {
public Wife getWifeWithHusbandByWifeId(int id); //根据妻子id查询妻子与丈夫
}
|
package com.wy.test.service;
import com.wy.test.entity.SysRoleMenu;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 角色与权限关系表 服务类
* </p>
*
* @author wenyang
* @since 2019-12-29
*/
public interface SysRoleMenuService extends IService<SysRoleMenu> {
}
|
package com.esum.framework.core.monitor;
import java.io.Serializable;
import java.lang.management.ThreadInfo;
/**
* Thread Status.
*/
public class ThreadStatus implements Serializable {
private static final long serialVersionUID = -6663797746867830059L;
private int threadCount = 0;
private int peakThreadCount = 0;
private int daemonThreadCount = 0;
private ThreadInfo[] lockThreadInfos;
public ThreadStatus(int threadCount, int peakThreadCount,
int daemonThreadCount) {
this.threadCount = threadCount;
this.peakThreadCount = peakThreadCount;
this.daemonThreadCount = daemonThreadCount;
}
public boolean hasLockedThreads() {
return (lockThreadInfos==null || lockThreadInfos.length==0)? false : true;
}
public ThreadInfo[] getLockThreadInfos() {
return lockThreadInfos;
}
public void setLockThreadInfos(ThreadInfo[] lockThreadInfos) {
this.lockThreadInfos = lockThreadInfos;
}
public int getThreadCount() {
return threadCount;
}
public void setThreadCount(int threadCount) {
this.threadCount = threadCount;
}
public int getPeakThreadCount() {
return peakThreadCount;
}
public void setPeakThreadCount(int peakThreadCount) {
this.peakThreadCount = peakThreadCount;
}
public int getDaemonThreadCount() {
return daemonThreadCount;
}
public void setDaemonThreadCount(int daemonThreadCount) {
this.daemonThreadCount = daemonThreadCount;
}
}
|
package model;
/**
* Class which contains a username and password.
* @author chris
*
*/
public abstract class User {
private String username;
private String password;
/**
* @param username
* @param password
*/
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
}
|
package com.cg.bo.model.bussiness;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.sql.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "visits")
public class Visit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long visit_id;
private Date rel_date;
private Date exp_date;
@JsonIgnore
@Column(columnDefinition = "boolean default false")
private boolean isStatus;
}
|
package com.egakat.io.conciliaciones.transformation.service.api;
import com.egakat.integration.core.transformation.service.api.TransformationService;
import com.egakat.io.conciliaciones.domain.SaldoInventario;
public interface SaldosInventarioTransformationService extends TransformationService<SaldoInventario> {
}
|
package queue.shared;
import java.io.Serializable;
public abstract class Message implements Serializable {
private static final long serialVersionUID = 1L;
private Type type;
public static enum Type {
ADD, ADD_FIRST, POP, DONE, BACK, REMOVE, RESET, GET_TODO, GET_DONE, GET_PENDING, IS_FINISHED
}
public Message(Type type) {
this.type = type;
}
public Type getType() {
return this.type;
}
}
|
package rs2.model.game.entity.character;
/**
*
* @author Jake Bellotti
* @since 1.0
*/
public enum CombatHitType {
NO_DAMAGE,// blue
NORMAL_DAMAGE,// red
POISON_DAMAGE,// green
DISEASE_DAMAGE;// orange
}
|
package by.bsac.security;
import by.bsac.model.Account;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class AbstractAccountDAO implements AccountDAO {
/*
--------------------------------------
---------- Class variables -----------
--------------------------------------
*/
public final String create_statement;
private final String find_by_name_statement;
private final String find_by_mail_statement;
/*
--------------------------------------
---------- Class constructors --------
--------------------------------------
*/
public AbstractAccountDAO() {
//Initialize statements syntax;
this.create_statement = "INSERT INTO account( user_id, user_name, user_mail, user_pass) VALUES (?, ?, ?, ?)";
this.find_by_name_statement = "SELECT * FROM account WHERE user_name = ?";
this.find_by_mail_statement = "SELECT * FROM account WHERE user_name = ?";
}
/*
--------------------------------------
---------- Class methods -------------
--------------------------------------
*/
@Override
public Account[] findByName(String a_name) throws SQLException {
return null;
}
@Override
public Account[] findByMail(String a_mail) {
return null;
}
/*
Method to create account in database;
*/
@Override
public void create(Account a_account) throws SQLException {
}
@Override
public void delete(Connection a_con, Account a_account) {
}
@Override
public void update(Connection a_con, Account a_account) {
}
}
|
package sri.bol.com;
import java.util.ArrayList;
import java.util.List;
public class PitsGameModel {
private List<Integer> pitsOfPlayer1;
private List<Integer> pitsOfPlayer2;
private boolean playerInActionWin;
private boolean extraMove;
public PitsGameModel(final List<Integer> pitsOfPlayer1, final List<Integer> pitsOfPlayer2, final boolean playerInActionWin, final boolean extraMove) {
this.pitsOfPlayer1 = pitsOfPlayer1;
this.pitsOfPlayer2 = pitsOfPlayer2;
this.playerInActionWin = playerInActionWin;
this.extraMove = extraMove;
}
public List<Integer> getPitsOfPlayer1() {
return pitsOfPlayer1;
}
public List<Integer> getPitsOfPlayer2() {
return pitsOfPlayer2;
}
public boolean isPlayerInActionWin() {
return playerInActionWin;
}
public boolean isExtraMove() {
return extraMove;
}
}
|
package com.aaa.house.service;
import com.aaa.house.entity.User;
import com.aaa.house.utils.ResultUtil;
import org.apache.ibatis.annotations.Delete;
import java.util.Map;
/**
* @Classname:UserService
* @author: L_Fly
* @Date: 2019/7/29 Time:10:47
* @Version 1.0.0
*/
public interface UserService {
/**
* 根据手机号查询是否有此用户
* @param phone 参数手机号
* @return int
*/
// User queryPhone(String phone);
ResultUtil queryPhone(String phone);
/**
* 核查验证码,动态添加用户
* @param record 实体类
* @param code 验证码
* @return int
*/
// int checkCodeInsertSelective(User record,String code);
ResultUtil checkCodeInsertSelective(User record, String code);
/**
* 根据手机号查询用户信息
* @param record 实体对象
* @return User实体对象
*/
// User checkLogin(User record);
ResultUtil checkLogin(User record);
/**
* 判断登录
*
* @return 实体对象
*/
// User judgeCusLogin();
ResultUtil judgeCusLogin();
/**
* 根据id修改用户信息
*
* @param record
* @return
*/
// boolean updateByPrimaryKeySelective(User record);
ResultUtil updateByPrimaryKeySelective(User record);
/**
* 实名验证
*
* @param record
* @return
*/
// boolean checkID(User record);
ResultUtil checkID(User record);
/**
* 密码修改
*
* @param map
* @return
*/
// boolean upPass(Map map);
ResultUtil upPass(Map map);
/**
* 取消关注
* @param map
* @return
*/
boolean delHouse(Map map);
/**
* 房屋保修
*
* @param map
* @return
*/
boolean insertRefer(Map map);
}
|
package com.mangodev;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.mangodev.exceptions.ManualException;
public class TimeStamp {
static String timeStamp = new SimpleDateFormat("HH:mm:ss").format(new Date());
public TimeStamp(String messageType, String info) {
if(messageType == "ERROR"){
System.err.println("[" + timeStamp + "][SYSTEM/" + messageType + "] " + info + "\n");
} else if(messageType == "INFO") {
System.out.println("[" + timeStamp + "][SYSTEM/" + messageType + "] " + info + "\n");
} else {
new Crash("IOException()", "Console Exception");
System.exit(1);
}
}
}
|
package com.wirelesscar.dynafleet.api;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import com.sutran.client.util.SutranClientConstants;
import javax.xml.ws.Service;
/**
* This class was generated by Apache CXF 2.7.18
* 2017-06-30T14:30:13.690-05:00
* Generated source version: 2.7.18
*
*/
@WebServiceClient(name = "DynafleetAPI",
wsdlLocation = SutranClientConstants.WEBSERVICE_DYNAFLEET_URL,
targetNamespace = "http://wirelesscar.com/dynafleet/api")
public class DynafleetAPI extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://wirelesscar.com/dynafleet/api", "DynafleetAPI");
public final static QName MessageServicePort = new QName("http://wirelesscar.com/dynafleet/api", "MessageServicePort");
public final static QName GeofenceServicePort = new QName("http://wirelesscar.com/dynafleet/api", "GeofenceServicePort");
public final static QName TransportCustomerServicePort = new QName("http://wirelesscar.com/dynafleet/api", "TransportCustomerServicePort");
public final static QName PoiServicePort = new QName("http://wirelesscar.com/dynafleet/api", "PoiServicePort");
public final static QName OrderServicePort = new QName("http://wirelesscar.com/dynafleet/api", "OrderServicePort");
public final static QName TrackingServicePort = new QName("http://wirelesscar.com/dynafleet/api", "TrackingServicePort");
public final static QName FormMessageServicePort = new QName("http://wirelesscar.com/dynafleet/api", "FormMessageServicePort");
public final static QName DTMServicePort = new QName("http://wirelesscar.com/dynafleet/api", "DTMServicePort");
public final static QName LoginServicePort = new QName("http://wirelesscar.com/dynafleet/api", "LoginServicePort");
public final static QName VehicleAndDriverAdminServicePort = new QName("http://wirelesscar.com/dynafleet/api", "VehicleAndDriverAdminServicePort");
public final static QName ServicePlanServicePort = new QName("http://wirelesscar.com/dynafleet/api", "ServicePlanServicePort");
public final static QName ReportServicePort = new QName("http://wirelesscar.com/dynafleet/api", "ReportServicePort");
public final static QName NotificationServicePort = new QName("http://wirelesscar.com/dynafleet/api", "NotificationServicePort");
public final static QName FormServicePort = new QName("http://wirelesscar.com/dynafleet/api", "FormServicePort");
static {
URL url = null;
try {
url = new URL(SutranClientConstants.WEBSERVICE_DYNAFLEET_URL);
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(DynafleetAPI.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", SutranClientConstants.WEBSERVICE_DYNAFLEET_URL);
}
WSDL_LOCATION = url;
}
public DynafleetAPI(URL wsdlLocation) {
super(wsdlLocation, SERVICE);
}
public DynafleetAPI(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public DynafleetAPI() {
super(WSDL_LOCATION, SERVICE);
}
/**
*
* @return
* returns MessageService
*/
@WebEndpoint(name = "MessageServicePort")
public MessageService getMessageServicePort() {
return super.getPort(MessageServicePort, MessageService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns MessageService
*/
@WebEndpoint(name = "MessageServicePort")
public MessageService getMessageServicePort(WebServiceFeature... features) {
return super.getPort(MessageServicePort, MessageService.class, features);
}
/**
*
* @return
* returns GeofenceService
*/
@WebEndpoint(name = "GeofenceServicePort")
public GeofenceService getGeofenceServicePort() {
return super.getPort(GeofenceServicePort, GeofenceService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns GeofenceService
*/
@WebEndpoint(name = "GeofenceServicePort")
public GeofenceService getGeofenceServicePort(WebServiceFeature... features) {
return super.getPort(GeofenceServicePort, GeofenceService.class, features);
}
/**
*
* @return
* returns TransportCustomerService
*/
@WebEndpoint(name = "TransportCustomerServicePort")
public TransportCustomerService getTransportCustomerServicePort() {
return super.getPort(TransportCustomerServicePort, TransportCustomerService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns TransportCustomerService
*/
@WebEndpoint(name = "TransportCustomerServicePort")
public TransportCustomerService getTransportCustomerServicePort(WebServiceFeature... features) {
return super.getPort(TransportCustomerServicePort, TransportCustomerService.class, features);
}
/**
*
* @return
* returns PoiService
*/
@WebEndpoint(name = "PoiServicePort")
public PoiService getPoiServicePort() {
return super.getPort(PoiServicePort, PoiService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns PoiService
*/
@WebEndpoint(name = "PoiServicePort")
public PoiService getPoiServicePort(WebServiceFeature... features) {
return super.getPort(PoiServicePort, PoiService.class, features);
}
/**
*
* @return
* returns OrderService
*/
@WebEndpoint(name = "OrderServicePort")
public OrderService getOrderServicePort() {
return super.getPort(OrderServicePort, OrderService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns OrderService
*/
@WebEndpoint(name = "OrderServicePort")
public OrderService getOrderServicePort(WebServiceFeature... features) {
return super.getPort(OrderServicePort, OrderService.class, features);
}
/**
*
* @return
* returns TrackingService
*/
@WebEndpoint(name = "TrackingServicePort")
public TrackingService getTrackingServicePort() {
return super.getPort(TrackingServicePort, TrackingService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns TrackingService
*/
@WebEndpoint(name = "TrackingServicePort")
public TrackingService getTrackingServicePort(WebServiceFeature... features) {
return super.getPort(TrackingServicePort, TrackingService.class, features);
}
/**
*
* @return
* returns FormMessageService
*/
@WebEndpoint(name = "FormMessageServicePort")
public FormMessageService getFormMessageServicePort() {
return super.getPort(FormMessageServicePort, FormMessageService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns FormMessageService
*/
@WebEndpoint(name = "FormMessageServicePort")
public FormMessageService getFormMessageServicePort(WebServiceFeature... features) {
return super.getPort(FormMessageServicePort, FormMessageService.class, features);
}
/**
*
* @return
* returns DTMService
*/
@WebEndpoint(name = "DTMServicePort")
public DTMService getDTMServicePort() {
return super.getPort(DTMServicePort, DTMService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns DTMService
*/
@WebEndpoint(name = "DTMServicePort")
public DTMService getDTMServicePort(WebServiceFeature... features) {
return super.getPort(DTMServicePort, DTMService.class, features);
}
/**
*
* @return
* returns LoginService
*/
@WebEndpoint(name = "LoginServicePort")
public LoginService getLoginServicePort() {
return super.getPort(LoginServicePort, LoginService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns LoginService
*/
@WebEndpoint(name = "LoginServicePort")
public LoginService getLoginServicePort(WebServiceFeature... features) {
return super.getPort(LoginServicePort, LoginService.class, features);
}
/**
*
* @return
* returns VehicleAndDriverAdminService
*/
@WebEndpoint(name = "VehicleAndDriverAdminServicePort")
public VehicleAndDriverAdminService getVehicleAndDriverAdminServicePort() {
return super.getPort(VehicleAndDriverAdminServicePort, VehicleAndDriverAdminService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns VehicleAndDriverAdminService
*/
@WebEndpoint(name = "VehicleAndDriverAdminServicePort")
public VehicleAndDriverAdminService getVehicleAndDriverAdminServicePort(WebServiceFeature... features) {
return super.getPort(VehicleAndDriverAdminServicePort, VehicleAndDriverAdminService.class, features);
}
/**
*
* @return
* returns ServicePlanService
*/
@WebEndpoint(name = "ServicePlanServicePort")
public ServicePlanService getServicePlanServicePort() {
return super.getPort(ServicePlanServicePort, ServicePlanService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ServicePlanService
*/
@WebEndpoint(name = "ServicePlanServicePort")
public ServicePlanService getServicePlanServicePort(WebServiceFeature... features) {
return super.getPort(ServicePlanServicePort, ServicePlanService.class, features);
}
/**
*
* @return
* returns ReportService
*/
@WebEndpoint(name = "ReportServicePort")
public ReportService getReportServicePort() {
return super.getPort(ReportServicePort, ReportService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ReportService
*/
@WebEndpoint(name = "ReportServicePort")
public ReportService getReportServicePort(WebServiceFeature... features) {
return super.getPort(ReportServicePort, ReportService.class, features);
}
/**
*
* @return
* returns NotificationService
*/
@WebEndpoint(name = "NotificationServicePort")
public NotificationService getNotificationServicePort() {
return super.getPort(NotificationServicePort, NotificationService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns NotificationService
*/
@WebEndpoint(name = "NotificationServicePort")
public NotificationService getNotificationServicePort(WebServiceFeature... features) {
return super.getPort(NotificationServicePort, NotificationService.class, features);
}
/**
*
* @return
* returns FormService
*/
@WebEndpoint(name = "FormServicePort")
public FormService getFormServicePort() {
return super.getPort(FormServicePort, FormService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns FormService
*/
@WebEndpoint(name = "FormServicePort")
public FormService getFormServicePort(WebServiceFeature... features) {
return super.getPort(FormServicePort, FormService.class, features);
}
}
|
package io.obsidian.quickstart.swarm;
import io.fabric8.arquillian.kubernetes.Session;
import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.assertj.core.api.Condition;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.fabric8.kubernetes.assertions.Assertions.assertThat;
@RunWith(Arquillian.class)
public class OpenshiftServiceKT {
private static final Logger LOG = LoggerFactory.getLogger(OpenshiftServiceKT.class);
@ArquillianResource
KubernetesClient client;
@ArquillianResource
Session session;
OkHttpClient httpClient = new OkHttpClient();
@Test
public void testHttpEndpoint() throws Exception {
LOG.info("## Testing Http endpoint & Service behind the scene");
// assert that a pod is ready from the RC... It allows to capture also the logs if they barf before trying to invoke services (which may not be ready yet)
assertThat(client).replicas("swarm-camel").pods().isPodReadyForPeriod();
String serviceURL = KubernetesHelper.getServiceURL(client,"swarm-camel",KubernetesHelper.DEFAULT_NAMESPACE,"http",true);
String req = serviceURL + "/service/say/charles";
LOG.info("### HTTP Request : " + req);
Request request = new Request.Builder()
.url(req)
.build();
Response response = httpClient.newCall(request).execute();
Assert.assertEquals("Hello from REST endpoint to charles",response.body().string());
}
} |
package org.bellatrix.services;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Holder;
import org.bellatrix.data.Header;
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.BARE)
@WebService
public interface InterBank {
@WebMethod(action = "topupRequest")
public TopupResponse topupRequest(@WebParam(header = true, name = "headerAuth") Holder<Header> headerParam,
@WebParam TopupRequest req) throws Exception;
@WebMethod(action = "topupInquiry")
public TopupResponse topupInquiry(@WebParam(header = true, name = "headerAuth") Holder<Header> headerParam,
@WebParam TopupParamRequest req) throws Exception;
@WebMethod(action = "topupPayment")
public TopupResponse topupPayment(@WebParam(header = true, name = "headerAuth") Holder<Header> headerParam,
@WebParam TopupParamRequest req) throws Exception;
@WebMethod(action = "topupReversal")
public TopupResponse topupReversal(@WebParam(header = true, name = "headerAuth") Holder<Header> headerParam,
@WebParam TopupParamRequest req) throws Exception;
}
|
/**
* This code prints all combination of r elements in an array whose sum is equal to x
* for example, in an array {1, 4, 3, 0} if r is 2 and value is 4 that mean print all possible combination of 2 elements
* that sum to a value 4. so, the output would be 04 and 13 because r is 2 .. we cant take 130.
* If r would be 3 and value is 4 then output would 130 because it contains 3 elements that sum to 4
*/
import java.util.ArrayList;
public class SumOfCombinationRelemements {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> myIntegers = new ArrayList<Integer>();
//utility function to print combinational sum of r elements. Here, value is the sum of total sum
public void printCombinationUtil(int[] arr, int value, int r) {
int start = 0;
printCombinationArr(start, arr, r);
for(int i = 0; i < myIntegers.size(); i++) {
int sum = sumofInteger(myIntegers.get(i));
if(sum == value) {
System.out.println(myIntegers.get(i));
}
}
}
//Combines all number in an interger
private static int sumofInteger(int num) {
int sum = 0;
while(num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
//print all combinations of r elements in an array and store them in an arraylist
public void printCombinationArr(int start, int[] arr, int r) {
for(int i = start; i < arr.length; i++) {
sb.append(arr[i]);
//if sb length is equal to r then only save value to arraylist
if(sb.length() == r){
//save values of sb in arraylist so that we check if those values sum to a value x
myIntegers.add(Integer.parseInt(sb.toString()));
}
if(i < arr.length) {
printCombinationArr(i + 1, arr, r);
}
sb.setLength(sb.length() - 1);
}
}
//main method
public static void main(String args[]) {
SumOfCombinationRelemements obj = new SumOfCombinationRelemements();
int [] arr = {1, 0, 2, 1};
//here, value is the combinational sum
int value = 4;
// r is the total elements in the combination. if r is 2 that mean show all combination with only 2 elements
int r = 3;
obj.printCombinationUtil(arr, value, r);
}
} |
package com.employ.employment.controller;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ProjectName: employment
* @Package: com.employ.employment.controller
* @ClassName: ApplyInfoController
* @Description: [职位申请表]
* @Author: [clh]
* @Date: 2021/6/11 15:34
**/
@RestController
@RequestMapping("/apply/")
@Api
@Slf4j
@CrossOrigin
public class ApplyInfoController {
}
|
/*
* 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.oxm.xstream;
import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
import com.thoughtworks.xstream.io.xml.QNameMap;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xmlunit.builder.Input;
import org.xmlunit.xpath.JAXPXPathEngine;
import org.springframework.core.testfixture.xml.XmlContent;
import org.springframework.util.xml.StaxUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* @author Arjen Poutsma
* @author Sam Brannen
* @author Juergen Hoeller
*/
class XStreamMarshallerTests {
private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>";
private final Flight flight = new Flight();
private XStreamMarshaller marshaller;
@BeforeEach
void createMarshaller() {
marshaller = new XStreamMarshaller();
marshaller.setTypePermissions(AnyTypePermission.ANY);
marshaller.setAliases(Collections.singletonMap("flight", Flight.class.getName()));
flight.setFlightNumber(42L);
}
@Test
void marshalDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.newDocument();
DOMResult domResult = new DOMResult(document);
marshaller.marshal(flight, domResult);
Document expected = builder.newDocument();
Element flightElement = expected.createElement("flight");
expected.appendChild(flightElement);
Element numberElement = expected.createElement("flightNumber");
flightElement.appendChild(numberElement);
Text text = expected.createTextNode("42");
numberElement.appendChild(text);
assertThat(XmlContent.of(document)).isSimilarTo(expected);
}
// see SWS-392
@Test
void marshalDOMResultToExistentDocument() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document existent = builder.newDocument();
Element rootElement = existent.createElement("root");
Element flightsElement = existent.createElement("flights");
rootElement.appendChild(flightsElement);
existent.appendChild(rootElement);
// marshall into the existent document
DOMResult domResult = new DOMResult(flightsElement);
marshaller.marshal(flight, domResult);
Document expected = builder.newDocument();
Element eRootElement = expected.createElement("root");
Element eFlightsElement = expected.createElement("flights");
Element eFlightElement = expected.createElement("flight");
eRootElement.appendChild(eFlightsElement);
eFlightsElement.appendChild(eFlightElement);
expected.appendChild(eRootElement);
Element eNumberElement = expected.createElement("flightNumber");
eFlightElement.appendChild(eNumberElement);
Text text = expected.createTextNode("42");
eNumberElement.appendChild(text);
assertThat(XmlContent.of(existent)).isSimilarTo(expected);
}
@Test
void marshalStreamResultWriter() throws Exception {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
marshaller.marshal(flight, result);
assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING);
}
@Test
void marshalStreamResultOutputStream() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult result = new StreamResult(os);
marshaller.marshal(flight, result);
String s = os.toString("UTF-8");
assertThat(XmlContent.of(s)).isSimilarToIgnoringWhitespace(EXPECTED_STRING);
}
@Test
void marshalSaxResult() throws Exception {
ContentHandler contentHandler = mock();
SAXResult result = new SAXResult(contentHandler);
marshaller.marshal(flight, result);
InOrder ordered = inOrder(contentHandler);
ordered.verify(contentHandler).startDocument();
ordered.verify(contentHandler).startElement(eq(""), eq("flight"), eq("flight"), isA(Attributes.class));
ordered.verify(contentHandler).startElement(eq(""), eq("flightNumber"), eq("flightNumber"), isA(Attributes.class));
ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2));
ordered.verify(contentHandler).endElement("", "flightNumber", "flightNumber");
ordered.verify(contentHandler).endElement("", "flight", "flight");
ordered.verify(contentHandler).endDocument();
}
@Test
void marshalStaxResultXMLStreamWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flight, result);
assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING);
}
@Test
void marshalStaxResultXMLStreamWriterDefaultNamespace() throws Exception {
QNameMap map = new QNameMap();
map.setDefaultNamespace("https://example.com");
map.setDefaultPrefix("spr");
StaxDriver driver = new StaxDriver(map);
marshaller.setStreamDriver(driver);
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
Result result = StaxUtils.createStaxResult(streamWriter);
marshaller.marshal(flight, result);
assertThat(XmlContent.from(writer)).isSimilarTo(
"<spr:flight xmlns:spr=\"https://example.com\"><spr:flightNumber>42</spr:flightNumber></spr:flight>");
}
@Test
void marshalStaxResultXMLEventWriter() throws Exception {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
Result result = StaxUtils.createStaxResult(eventWriter);
marshaller.marshal(flight, result);
assertThat(XmlContent.from(writer)).isSimilarTo(EXPECTED_STRING);
}
@Test
void converters() throws Exception {
marshaller.setConverters(new EncodedByteArrayConverter());
byte[] buf = {0x1, 0x2};
// Execute multiple times concurrently to ensure there are no concurrency issues.
// See https://github.com/spring-projects/spring-framework/issues/25017
IntStream.rangeClosed(1, 100).parallel().forEach(n -> {
try {
Writer writer = new StringWriter();
marshaller.marshal(buf, new StreamResult(writer));
assertThat(XmlContent.from(writer)).isSimilarTo("<byte-array>AQI=</byte-array>");
Reader reader = new StringReader(writer.toString());
byte[] bufResult = (byte[]) marshaller.unmarshal(new StreamSource(reader));
assertThat(bufResult).as("Invalid result").isEqualTo(buf);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
});
}
@Test
void useAttributesFor() throws Exception {
marshaller.setUseAttributeForTypes(Long.TYPE);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertThat(XmlContent.from(writer)).isSimilarTo(expected);
}
@Test
void useAttributesForStringClassMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap("flightNumber", Long.TYPE));
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertThat(XmlContent.from(writer)).isSimilarTo(expected);
}
@Test
void useAttributesForClassStringMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap(Flight.class, "flightNumber"));
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertThat(XmlContent.from(writer)).isSimilarTo(expected);
}
@Test
void useAttributesForClassStringListMap() throws Exception {
marshaller.setUseAttributeFor(Collections.singletonMap(Flight.class, Collections.singletonList("flightNumber")));
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight flightNumber=\"42\" />";
assertThat(XmlContent.from(writer)).isSimilarTo(expected);
}
@Test
void aliasesByTypeStringClassMap() throws Exception {
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("flight", Flight.class);
FlightSubclass flight = new FlightSubclass();
flight.setFlightNumber(42);
marshaller.setAliasesByType(aliases);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING);
}
@Test
void aliasesByTypeStringStringMap() throws Exception {
Map<String, String> aliases = new HashMap<>();
aliases.put("flight", Flight.class.getName());
FlightSubclass flight = new FlightSubclass();
flight.setFlightNumber(42);
marshaller.setAliasesByType(aliases);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(EXPECTED_STRING);
}
@Test
void fieldAliases() throws Exception {
marshaller.setFieldAliases(Collections.singletonMap("org.springframework.oxm.xstream.Flight.flightNumber", "flightNo"));
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
String expected = "<flight><flightNo>42</flightNo></flight>";
assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(expected);
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
void omitFields() throws Exception {
Map omittedFieldsMap = Collections.singletonMap(Flight.class, "flightNumber");
marshaller.setOmittedFields(omittedFieldsMap);
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertXpathDoesNotExist("/flight/flightNumber", writer.toString());
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
void implicitCollections() throws Exception {
Flights flights = new Flights();
flights.getFlights().add(flight);
flights.getStrings().add("42");
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("flight", Flight.class);
aliases.put("flights", Flights.class);
marshaller.setAliases(aliases);
Map implicitCollections = Collections.singletonMap(Flights.class, "flights,strings");
marshaller.setImplicitCollections(implicitCollections);
Writer writer = new StringWriter();
marshaller.marshal(flights, new StreamResult(writer));
String result = writer.toString();
assertXpathDoesNotExist("/flights/flights", result);
assertXpathExists("/flights/flight", result);
assertXpathDoesNotExist("/flights/strings", result);
assertXpathExists("/flights/string", result);
}
@Test
void jettisonDriver() throws Exception {
marshaller.setStreamDriver(new JettisonMappedXmlDriver());
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertThat(writer.toString()).as("Invalid result").isEqualTo("{\"flight\":{\"flightNumber\":42}}");
Object o = marshaller.unmarshal(new StreamSource(new StringReader(writer.toString())));
assertThat(o).as("Unmarshalled object is not Flights").isInstanceOf(Flight.class);
Flight unflight = (Flight) o;
assertThat(unflight).as("Flight is null").isNotNull();
assertThat(unflight.getFlightNumber()).as("Number is invalid").isEqualTo(42L);
}
@Test
void jsonDriver() throws Exception {
marshaller.setStreamDriver(new JsonHierarchicalStreamDriver() {
@Override
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE,
new JsonWriter.Format(new char[0], new char[0],
JsonWriter.Format.SPACE_AFTER_LABEL | JsonWriter.Format.COMPACT_EMPTY_ELEMENT));
}
});
Writer writer = new StringWriter();
marshaller.marshal(flight, new StreamResult(writer));
assertThat(writer.toString()).as("Invalid result").isEqualTo("{\"flightNumber\": 42}");
}
@Test
void annotatedMarshalStreamResultWriter() throws Exception {
marshaller.setAnnotatedClasses(Flight.class);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
Flight flight = new Flight();
flight.setFlightNumber(42);
marshaller.marshal(flight, result);
String expected = "<flight><number>42</number></flight>";
assertThat(XmlContent.from(writer)).isSimilarToIgnoringWhitespace(expected);
}
private static void assertXpathExists(String xPathExpression, String inXMLString){
Source source = Input.fromString(inXMLString).build();
Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
assertThat(nodes).as("Expecting to find matches for Xpath " + xPathExpression).isNotEmpty();
}
private static void assertXpathDoesNotExist(String xPathExpression, String inXMLString){
Source source = Input.fromString(inXMLString).build();
Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
assertThat(nodes).as("Should be zero matches for Xpath " + xPathExpression).isEmpty();
}
}
|
package com.financecrudbackend.util;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfiguration {
@Bean(name = "financeCrudApi")
public OpenAPI financeCrudApi() {
return new OpenAPI().components(new Components()).info(new Info().title("Finance Crud API")
.description("Finance Crud API implemented with Spring Boot RESTful" +
" service and documented using springdoc-openapi"));
}
}
|
package com.unisports.bl;
import com.unisports.cross.Constants;
import com.unisports.dao.NotificationDAO;
import com.unisports.dao.UserDAO;
import com.unisports.entities.Notification;
import com.unisports.entities.User;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javafx.util.Pair;
public class UserBL {
UserDAO _userDao;
NotificationDAO _notificationDao;
public UserBL(){
_userDao = new UserDAO();
_notificationDao = new NotificationDAO();
}
public Pair<Boolean, String> registerUser(User user){
if (user.getEmail().trim().isEmpty() || !user.getEmail().contains("@") || !user.getEmail().contains(".")) {
return new Pair<>(false, "El correo no es valido");
}
if (user.getPassword().length() < Constants.passwordMinLength) {
return new Pair<>(false, "La contraseña debe contener minimo " + Constants.passwordMinLength + " caracteres");
}
//UserDAO userDao = new UserDAO();
if (_userDao.createUser(user)) {
return new Pair<>(true, "El usuario fue creado");
}
return new Pair<>(false, "Error inesperado, no se pudo crear la cuenta");
}
public User getUserById(UUID userId) {
return _userDao.getUserById(userId);
}
public boolean restorePassword(String email) {
//email service
return true;
}
public boolean changePassword(String password, String paswordConfirmation) {
//email service
return true;
}
public boolean updateUser(User user) {
return _userDao.updateUser(user);
}
public boolean updateUserPhoto(String photo) {
//Photo service
return true;
}
public List<User> getUsersByName(String name) {
return new ArrayList<User>();
}
public List<User> getAllUsers() {
return _userDao.getAllUsers();
}
public boolean disableUser(UUID userId) {
return true;
}
public boolean sendEmailConfirmation(UUID userId) {
return true;
}
public List<Notification> getAllNotificationsByUserId(UUID userId) {
return new ArrayList<Notification>();
}
}
|
package com.github.iam20.proxy;
import static org.junit.Assert.assertEquals;
import com.github.iam20.proxy.model.*;
import com.github.iam20.proxy.util.CoreInfoParser;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static com.github.iam20.proxy.msg.Message.testJsonMsg;
@Slf4j
public class ParseCoreInformationTest {
private List<MacAddress> macAddressList;
private TempHumid tempHumid;
@Before
public void before() {
macAddressList = Arrays.asList(
new MacAddressBuilder()
.macAddr("ff:ff:ff:ff:ff:ff")
.vendor("apple inc")
.build()
,
new MacAddressBuilder()
.macAddr("fe:ff:ff:ff:ff:ff")
.vendor("samsung electronics")
.build()
);
tempHumid = new TempHumidBuilder()
.celsius(10.0)
.humid(0.0)
.build();
}
@Test
public void test() {
JSONObject json = new JSONObject(testJsonMsg);
CoreInformation coreInformation = CoreInfoParser.parse(json);
assertEquals(macAddressList, coreInformation.getMacAddresses());
assertEquals(tempHumid, coreInformation.getTempHumid());
log.info(coreInformation.toString());
}
}
|
package com.zantong.mobilecttx.home.bean;
import java.util.List;
/**
* Created by jianghw on 2017/5/5.
*/
public class RspInfoBean {
/**
* totcent : 2
* totcount : 99999
* totamt : 75000
* ViolationInfo : [{"violationcent":"2","processste":"1","paydate":"20170220","carnum":"XOBDdy2mbXcpO84qlNQbsg==","violationdate":"20170215","violationamt":"10000","violationnum":"3101011830480748"},{"violationcent":"0","processste":"1","paydate":"20170116","carnum":"foM4u2dTInhrAd4JPZNTYQ==","violationdate":"20161111","violationamt":"20000","violationnum":"3101017020895105"},{"violationcent":"0","processste":"1","paydate":"20161230","carnum":"huMFVtMmTJDyUZzyfy6fqw==","violationdate":"20161111","violationamt":"5000","violationnum":"3101061818052367"},{"violationcent":"0","processste":"1","paydate":"20170428","carnum":"UZDjW5GA0biHO6Y5yZvvwg==","violationdate":"20160803","violationamt":"20000","violationnum":"3101107016227413"},{"violationcent":"0","processste":"1","paydate":"20161221","carnum":"4F+/AbDLLGJJ3q+Cwr1hLg==","violationdate":"20161126","violationamt":"20000","violationnum":"3101130806985382"}]
* totcarcount : 5
*/
private int totcent;
private String totcount;
private int totamt;
private String totcarcount;
private List<ViolationInfoBean> ViolationInfo;
public int getTotcent() {
return totcent;
}
public void setTotcent(int totcent) {
this.totcent = totcent;
}
public String getTotcount() {
return totcount;
}
public void setTotcount(String totcount) {
this.totcount = totcount;
}
public int getTotamt() {
return totamt;
}
public void setTotamt(int totamt) {
this.totamt = totamt;
}
public String getTotcarcount() {
return totcarcount;
}
public void setTotcarcount(String totcarcount) {
this.totcarcount = totcarcount;
}
public List<ViolationInfoBean> getViolationInfo() {
return ViolationInfo;
}
public void setViolationInfo(List<ViolationInfoBean> ViolationInfo) {
this.ViolationInfo = ViolationInfo;
}
public static class ViolationInfoBean {
/**
* violationcent : 2
* processste : 1
* paydate : 20170220
* carnum : XOBDdy2mbXcpO84qlNQbsg==
* violationdate : 20170215
* violationamt : 10000
* violationnum : 3101011830480748
*/
private String violationcent;
private String processste;
private String paydate;
private String carnum;
private String violationdate;
private String violationamt;
private String violationnum;
public String getViolationcent() {
return violationcent;
}
public void setViolationcent(String violationcent) {
this.violationcent = violationcent;
}
public String getProcessste() {
return processste;
}
public void setProcessste(String processste) {
this.processste = processste;
}
public String getPaydate() {
return paydate;
}
public void setPaydate(String paydate) {
this.paydate = paydate;
}
public String getCarnum() {
return carnum;
}
public void setCarnum(String carnum) {
this.carnum = carnum;
}
public String getViolationdate() {
return violationdate;
}
public void setViolationdate(String violationdate) {
this.violationdate = violationdate;
}
public String getViolationamt() {
return violationamt;
}
public void setViolationamt(String violationamt) {
this.violationamt = violationamt;
}
public String getViolationnum() {
return violationnum;
}
public void setViolationnum(String violationnum) {
this.violationnum = violationnum;
}
}
}
|
package com.xixiwan.platform.module.web.util;
import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
public final class IpUtils {
// ip headers
private static final String[] IP_HEADERS_TO_TRY = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"};
/**
* 获取请求来源IP
*
* @param request
* @return IP,找不到时为null
*/
public static String getClientIpAddress(HttpServletRequest request) {
boolean found = false;
String ip = null;
for (int index = 0; index < IP_HEADERS_TO_TRY.length && !found; index++) {
ip = request.getHeader(IP_HEADERS_TO_TRY[index]);
if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
if (index == 0) { // forwarded
int spIndex = ip.indexOf(",");
if (spIndex > 0) {
ip = ip.substring(0, spIndex);
}
}
found = true;
}
}
if (!found) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "localhost" : ip;
}
/**
* 获得MAC地址
*
* @param ip
* @return
*/
public static String getMACAddress(String ip) {
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14);
break;
}
}
}
} catch (IOException e) {
return ExceptionUtils.rethrow(e);
}
return macAddress;
}
}
|
package com.example.recyclercarddemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Adapter adapter;
ArrayList<String> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<>();
items.add("A este lado del paraíso");
items.add("1984");
items.add("Crimen y castigo");
items.add("Un mundo feliz");
items.add("El maestro y Margarita");
items.add("Cien años de soledad");
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, items);
recyclerView.setAdapter(adapter);
}
}
|
package com.asgard.application;
import static com.google.common.base.Preconditions.checkNotNull;
import com.asgard.application.backend.DatabaseBackend;
import com.asgard.application.backend.DatabaseConfiguration;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.jdbi3.JdbiFactory;
import io.dropwizard.setup.Environment;
import org.immutables.value.Value;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.jdbi.v3.core.Jdbi;
/**
* Server configuration for the asgard-projects API server.
*/
@Value.Immutable
@JsonDeserialize(as = ImmutableAsgardProjectsConfiguration.class)
public abstract class AsgardProjectsConfiguration extends Configuration {
@JsonProperty("database")
abstract DatabaseConfiguration getDatabaseConfiguration();
public Jdbi createDBI(Environment environment, String name) {
final JdbiFactory factory = new JdbiFactory();
return factory.build(environment, getDatabaseConfiguration().getDataSourceFactory(), name);
}
public DatabaseBackend getDatabaseBackend(Environment environment) {
return createDBI(environment, "jdbi-backend").onDemand(DatabaseBackend.class);
}
}
|
import java.awt.image.AreaAveragingScaleFilter;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.*;
public class Game {
public class Arr {
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
private int[] data;
Arr(int[] obj){
this.data = obj;
}
@Override
public int hashCode() {
Object[] src = new Object[this.data.length+1];
ArrayList ar = new ArrayList();
for(int t : this.data){ ar.add(t); }
src = ar.toArray();
return Arrays.deepHashCode(src);
}
@Override
public boolean equals(Object obj) {
if (obj == null){return false;}
//int[] arr = new int[]{ Array.getByte(obj,0), Array.getByte(obj,1)} ;
Arr arr = (Arr)obj;
if(Arrays.equals(this.data, arr.getData())){ return true; }
return false;
}
}
Map<Arr, ShashKa> _shashka = new HashMap<>();
public class ShashKa {
public byte type = 0;
public int color;
int i;
ShashKa(int color) {
this.color = color;
}
public void walk(byte[] direction) {
// pos[0] += direction[0];
//pos[1] += direction[1];
}
public byte[][] applyToMove(int pos[]) {
byte[][] nearS = new byte[][]{{0, 0, 0, 0}, {0, 0, 0, 0}};
if(pos[0] == 0){ nearS[0][2]=1;nearS[0][3]=1;nearS[1][2]=1;nearS[1][3]=1;}//IIIIIIIIIIIII
if(pos[0] == 1){ nearS[0][3]=1;nearS[1][3]=1;}
if(pos[0] == 7){ nearS[0][0]=1;nearS[0][1]=1; nearS[1][0]=1;nearS[1][1]=1;}
if(pos[0] == 6){ nearS[0][0]=1;nearS[1][0]=1;}
if(pos[1] == 7){ nearS[0][2]=1;nearS[0][3]=1;nearS[1][1]=1;nearS[1][0]=1;}//JJJJJJJJJ
if(pos[1] == 6){ nearS[0][3]=1;nearS[1][0]=1;}
if(pos[1] == 0){ nearS[0][0]=1;nearS[0][1]=1; nearS[1][2]=1;nearS[1][3]=1;}
if(pos[1] == 1){ nearS[0][0]=1;nearS[1][3]=1;}
byte[][] nearMove = new byte[][]{{0, 0, 0, 0}, {0, 0, 0, 0}};
for (var position : _shashka.keySet()) {
if (Arrays.equals(position.getData(), new int[]{pos[0] + 1, pos[1] - 1})) {nearS[0][1] = 1;}//c
if (Arrays.equals(position.getData(), new int[]{pos[0] + 1, pos[1] + 1})) {nearS[1][1] = 1;}//g
if (Arrays.equals(position.getData(), new int[]{pos[0] + 2, pos[1] - 2})) {nearS[0][0] = 1;}//d
if (Arrays.equals(position.getData(), new int[]{pos[0] + 2, pos[1] + 2})) {nearS[1][0] = 1;}//h
if (Arrays.equals(position.getData(), new int[]{pos[0] - 1, pos[1] - 1})) {nearS[1][2] = 1;}//f
if (Arrays.equals(position.getData(), new int[]{pos[0] - 1, pos[1] + 1})) {nearS[0][2] = 1;}//b
if (Arrays.equals(position.getData(), new int[]{pos[0] - 2, pos[1] - 2})) {nearS[1][3] = 1;}//e
if (Arrays.equals(position.getData(), new int[]{pos[0] - 2, pos[1] + 2})) {nearS[0][3] = 1;}//a
}
//int[]
//System.out.print(_shashka.get(new int[]{pos[0]-1,pos[1]+1}).type != this.type);
//ROOLS TRUE
if (this.color == 1){//BLACK
if(nearS[1][0] == 0 && nearS[1][1] == 1){ nearMove[1][0] = 1; } //e
if(nearS[1][1] == 0){ nearMove[1][1] = 1; } //f
if(nearS[0][1] == 1 && nearS[0][0] == 0){ nearMove[0][0] = 1; } //a
if(nearS[0][1] == 0){nearMove[0][1] = 1; } //b
if(nearS[0][2] == 1 && nearS[0][3] == 0){ nearMove[0][3] = 1; } //d
if(nearS[0][2] == 0){nearMove[0][2] = 1; } //c
if(nearS[1][2] == 1 && nearS[1][3] == 0){ nearMove[1][3] = 1; } //h
if(nearS[1][2] == 0){ nearMove[1][2] = 1; } //g
}
return nearMove;
}
}
byte[][] map = new byte[8][8];
//byte user = 0;
public Game() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if((i+j) % 2 == 1 ) {
map[i][j]=1;
if (i < 3) {
_shashka.put(new Arr(new int[]{i, j}), new ShashKa(0));//WHITE
map[i][j] = 2;
}
if (i > 4) {
_shashka.put(new Arr(new int[]{i, j}), new ShashKa(1));//BLACK
map[i][j] = 3;
}
}
}
}
}
public void print(byte[][] arr, int leng, int hieg) {
for (int i = 0; i < leng; i++) {
for (int j = 0; j < hieg; j++) {
//if(i == 1 && j == 3) { System.out.print("a");}
//if(i == 3 && j == 1) { System.out.print("b");}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public void start(Game game){
game.print(game.map,8,8);
for(var Key : game._shashka.keySet()){
Arr ar = new Arr(new int[]{7,0});
if( ar.equals(Key)){
System.out.println(game._shashka.get(ar) + " that " + Key.hashCode() + " ///////////// " + ar.hashCode() );
}
}
for(var Key : game._shashka.keySet()){
//System.out.println(key[0] + " " + key[1]);
if(Arrays.equals(new int[] {6,1}, Key.getData())) {
// System.out.println(game._shashka);
var where = game._shashka.get(Key);
System.out.println(where.getClass() + " " + where.equals(null) + " " + where.color);
game.print(where.applyToMove(Key.getData()), 2,4);
}
}
}
public static void main(String[] args) {
Game game = new Game();
game.start(game);
}
}
|
package com.example.ecoleenligne.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView;
import com.example.ecoleenligne.ListeExercicesActivity;
import com.example.ecoleenligne.MainActivity;
import com.example.ecoleenligne.VideoContentActivity;
import com.example.ecoleenligne.ContentActivity;
import com.example.ecoleenligne.QuizActivity;
import com.example.ecoleenligne.R;
import com.example.ecoleenligne.model.CourseContent;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class CourseContentListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<CourseContent> courseContents = new ArrayList<CourseContent>();
Context context;
public CourseContentListAdapter(Context context, List<CourseContent> courseContents) {
this.courseContents.addAll(courseContents);
inflater = LayoutInflater.from(context);
this.context = context;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
CourseContent courseContent = (CourseContent) getItem(position);
if (view == null) {
view = inflater.inflate(R.layout.content_item, null);
}
ImageView mainImage = view.findViewById(R.id.content_image);
Intent intent = ((Activity) context).getIntent();
String course_id = intent.getStringExtra("course_id");
String course_image = intent.getStringExtra("course_image");
String path_img = MainActivity.IP_myspace +"/TER.git/public/upload/course/"+ course_id +"/"+ course_image;
Picasso.get().load(path_img).into(mainImage);
/*
if(courseContent.type.equals("1")) {
mainImage.setBackgroundResource(R.drawable.image_pdf);
}else if(courseContent.type.equals("3")) {
mainImage.setBackgroundResource(R.drawable.image_logo);
}
*/
TextView video_title = view.findViewById(R.id.video_title);
video_title.setText(""+ courseContent.getTitle());
ImageView content_image = view.findViewById(R.id.content_image);
content_image.setBackgroundColor(Color.TRANSPARENT);
if(courseContent.type.equals("1")) { //pdf
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.pdf));
} else if(courseContent.type.equals("3")) { //image
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.image_logo));
} else { //video
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.icons8_video_96));
}
//Start video player
final LinearLayout video_play = view.findViewById(R.id.video_play);
video_play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//pdf content
if(courseContent.type.equals("1")) {
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.pdf));
Intent intent = new Intent(context, ContentActivity.class);
intent.putExtra("lien", courseContent.getPath());
intent.putExtra("course_name", courseContent.getTitle());
context.startActivity(intent);
} else if(courseContent.type.equals("3")) {
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.image_logo));
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(courseContent.getPath()), "image/*");
context.startActivity(intent);
} else {
//video content
content_image.setImageDrawable(context.getResources().getDrawable(R.drawable.icons8_video_96));
Intent intent = new Intent(context, VideoContentActivity.class);
intent.putExtra("lien", courseContent.getPath());
intent.putExtra("course_name", courseContent.getTitle());
context.startActivity(intent);
}
}
});
/*
final int course_id = courseContent.getId();
final Button details_btn = view.findViewById(R.id.details);
details_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ListeCourseContentActivity.class);
intent.putExtra("course_id", ""+course_id);
intent.putExtra("course_title", ""+course.getName());
context.startActivity(intent);
}
});
final Button exercices_btn = view.findViewById(R.id.exercices);
exercices_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(context, ListeExercicesActivity.class);
intent1.putExtra("id",course_id);
context.startActivity(intent1);
}
});
final Button quiz_btn = view.findViewById(R.id.quiz);
quiz_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, QuizActivity.class);
intent.putExtra("course_id", ""+course_id);
context.startActivity(intent);
}
});
*/
return view;
}
@Override
public Object getItem(int position) {
return courseContents.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return courseContents.size();
}
public void setcourseContents(List<CourseContent> students) {
this.courseContents = students;
notifyDataSetChanged();
}
} |
package com.company;
import java.util.Scanner;
import java.util.Arrays;
public class Ejercicio3 {
public static void main(String[] args) {
Scanner teclado = new Scanner (System.in);
int suma_negativos=0;
int suma_positivos=0;
int total_negativos=0;
int total_positivos=0;
int ceros=0;
System.out.print("Introduzca la cantidad de numeros que quiere introducir: ");
int numeros = teclado.nextInt();
int tabla[] = new int[numeros];
for (int i = 0; i < numeros; i++){
System.out.print("Introduzca los numeros con los que quiere completar el array: ");
tabla[i]=teclado.nextInt();
if (tabla[i]<0){
suma_negativos=suma_negativos+i;
total_negativos++;
}
if (tabla[i]>0){
suma_positivos=suma_positivos+i;
total_positivos++;
}
if (tabla[i]==0){
ceros++;
}
}
System.out.println("Ceros: " + ceros);
System.out.println("La media de los numeros positivos es: " + suma_positivos/total_positivos);
System.out.println("La media de los numeros negativos es: " + suma_negativos/total_negativos);
}
} |
package hr.bosak_turk.planetdemo.pojo;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Sizes implements Parcelable {
@SerializedName("td_533x261")
@Expose
private ImageSize image;
public ImageSize getImageSize() {
return image;
}
public void setImageSize(ImageSize image) {
this.image = image;
}
protected Sizes(Parcel in) {
image = (ImageSize) in.readValue(ImageSize.class.getClassLoader());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(image);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Sizes> CREATOR = new Parcelable.Creator<Sizes>() {
@Override
public Sizes createFromParcel(Parcel in) {
return new Sizes(in);
}
@Override
public Sizes[] newArray(int size) {
return new Sizes[size];
}
};
} |
package com.ict.iodetector.service.bean;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class MoveOrStopQueue {
private Queue<Long> moveOrStopQueue;
private int stopCount;
private int moveCount;
private long stopPeriod;
public MoveOrStopQueue(){
moveOrStopQueue = new LinkedList<Long>();
}
/**
* @return moveOrStopQueue
*/
public Queue<Long> getMoveOrStopQueue(){
return moveOrStopQueue;
}
/**
* @param uiTime
*/
public void enMoveOrStopQueue(Long uiTime) {
moveOrStopQueue.offer(uiTime);
}
/**
* @return
*/
public Long deMoveOrStopQueue() {
return moveOrStopQueue.poll();
}
/**
* @return
*/
public int getSize() {
return moveOrStopQueue.size();
}
/**
* @return countsOfStop
*/
// public int getStopCount() {
// Iterator<Long> iteratorMoveOrStop = moveOrStopQueue.iterator();
// int countsOfStop = 0;
// long lastTime = 0;
// long beforeLast = 0;
// if(!iteratorMoveOrStop.hasNext()){
// return 0;
// }
// while(getTotalTime() > 240000){
// deMoveOrStopQueue();
// }
// iteratorMoveOrStop = moveOrStopQueue.iterator();
// lastTime = iteratorMoveOrStop.next().longValue();
// while (iteratorMoveOrStop.hasNext()) {
// beforeLast = iteratorMoveOrStop.next().longValue();
//// System.out.println("beforeLast" + beforeLast);
// if((beforeLast - lastTime) > 7000){
// countsOfStop ++;
//// System.out.println("counts of stop" + countsOfStop);
// }
// lastTime = beforeLast;
// }
// return countsOfStop;
// }
public int getStopCount() {
return stopCount;
}
public void calculateNumbers() {
Iterator<Long> iteratorMoveOrStop = moveOrStopQueue.iterator();
long lastTime = 0;
long beforeLast = 0;
stopCount = 0;
moveCount = 0;
stopPeriod = 0;
if(!iteratorMoveOrStop.hasNext()){
stopCount = 0;
moveCount = 0;
}
// while(getTotalTime() > 240000){
// deMoveOrStopQueue();
// }
while(getTotalTime() > 360000){
deMoveOrStopQueue();
}
iteratorMoveOrStop = moveOrStopQueue.iterator();
if(!iteratorMoveOrStop.hasNext()) {
return;
}
lastTime = iteratorMoveOrStop.next().longValue();
while (iteratorMoveOrStop.hasNext()) {
beforeLast = iteratorMoveOrStop.next().longValue();
// System.out.println("beforeLast" + beforeLast);
if(Math.abs(beforeLast - lastTime) < 5000){
moveCount ++;
} else {
stopCount ++;
stopPeriod += (Math.abs(beforeLast - lastTime));
}
lastTime = beforeLast;
}
}
public long getTotalTime() {
Iterator<Long> it = moveOrStopQueue.iterator();
long totalPeriod = 0;
long begin = 0,after = 0;
if(it.hasNext()) {
begin = it.next().longValue();
}
while (it.hasNext()) {
after = it.next().longValue();
if(after - begin < 5000){
totalPeriod += (after - begin);
}
begin = after;
}
return totalPeriod;
}
public long getTotalTimeWithStop() {
Iterator<Long> it = moveOrStopQueue.iterator();
long totalPeriod = 0;
long begin = 0,after = 0;
if(it.hasNext()) {
begin = it.next().longValue();
}
while (it.hasNext()) {
after = it.next().longValue();
totalPeriod += (after - begin);
begin = after;
}
return totalPeriod;
}
public int getMoveCount() {
return moveCount;
}
public long getStopPeriod() {
return stopPeriod;
}
// public int getMoveCount() {
// Iterator<Long> it = moveOrStopQueue.iterator();
// int countOfMove = 0;
//
// long totalPeriod = 0;
// long begin = 0,after = 0;
// if(it.hasNext()) {
// begin = it.next().longValue();
// }
// while (it.hasNext() && totalPeriod < 240000) {
// after = it.next().longValue();
// totalPeriod += (after - begin);
// begin = after;
// countOfMove ++;
// }
//
// return countOfMove;
// }
}
|
package com.invitae.emr;
import com.invitae.emr.services.DataLoader;
public class Main {
public static void main(String[] args) {
System.out.println("This is the start of your EMR programming exercise.");
try {
final var sampleData = DataLoader.loadSampleData();
} catch (Exception exception) {
System.out.println("ERROR: failed to read from sample data files.");
exception.printStackTrace();
}
}
}
|
package fr.skytasul.quests.utils.compatibility.mobs;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.inventory.ItemStack;
import fr.skytasul.quests.api.mobs.MobFactory;
import fr.skytasul.quests.editors.CancellableEditor;
import fr.skytasul.quests.gui.npc.SelectGUI;
import fr.skytasul.quests.utils.Lang;
import fr.skytasul.quests.utils.Utils;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.event.NPCDeathEvent;
import net.citizensnpcs.api.event.NPCRightClickEvent;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.trait.MobType;
public class CitizensFactory implements MobFactory<NPC> {
@Override
public String getID() {
return "citizensNPC";
}
@Override
public ItemStack getFactoryItem() {
return SelectGUI.selectNPC;
}
@Override
public void itemClick(Player p, Consumer<NPC> run) {
Lang.SELECT_KILL_NPC.send(p);
new CancellableEditor(p, () -> run.accept(null)) {
@EventHandler (priority = EventPriority.LOW)
private void onNPCClick(NPCRightClickEvent e) {
if (e.getClicker() != p) return;
e.setCancelled(true);
leave(e.getClicker());
run.accept(e.getNPC());
}
@Override
public void begin() {
super.begin();
Utils.sendMessage(p, Lang.NPC_EDITOR_ENTER.toString());
}
}.enter();
}
@Override
public NPC fromValue(String value) {
return CitizensAPI.getNPCRegistry().getById(Integer.parseInt(value));
}
@Override
public boolean bukkitMobApplies(NPC first, Entity entity) {
return first.isSpawned() && first.getEntity().equals(entity);
}
@Override
public String getValue(NPC data) {
return Integer.toString(data.getId());
}
@Override
public String getName(NPC data) {
return data.getName();
}
@Override
public EntityType getEntityType(NPC data) {
return data.getOrAddTrait(MobType.class).getType();
}
@Override
public List<String> getDescriptiveLore(NPC data) {
return Arrays.asList("§8NPC ID: §7§l" + data.getId());
}
@EventHandler
public void onNPCKilled(NPCDeathEvent e) {
LivingEntity en = (LivingEntity) e.getNPC().getEntity();
if (en.getKiller() == null) return;
callEvent(e, e.getNPC(), en, en.getKiller());
}
}
|
package com.rana_aditya.spider_task_3;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class entries {
@SerializedName("etymologies")
@Expose
private List<String> etymologies;
public entries(List<String> etymologies) {
this.etymologies = etymologies;
}
public List<String> getEtymologies() {
return etymologies;
}
public void setEtymologies(List<String> etymologies) {
this.etymologies = etymologies;
}
}
|
package com.example.textam;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeTextView extends TextView implements Runnable {
// 当前滚动的位置
private int currentScrollX;
private static int scrollspeed;
private boolean isStop = false;
private int textWidth;
private boolean isMeasure = false;
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void run() {
// TODO Auto-generated method stub
// 滚动速度
currentScrollX += scrollspeed*2 + 2;
scrollTo(currentScrollX, 0);
if (isStop) {
return;
}
if (getScrollX() >= textWidth) {
scrollTo(-(this.getWidth()), 0);
currentScrollX = -(this.getWidth());
// return;
}
postDelayed(this, 5);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (!isMeasure) {
// 问自己宽度只需获取一次就可以了
getTextWidth();
isMeasure = true;
}
}
private void getTextWidth() {
Paint paint = this.getPaint();
String str = this.getText().toString();
textWidth = (int) paint.measureText(str);
}
public void getScrollSpeed(int speed) {
scrollspeed = speed;
//if(scrollspeed < 1 || scrollspeed > 5){
//scrollspeed = 3;
//}
}
// 开始滚动
public void startScroll() {
isStop = false;
this.removeCallbacks(this);
post(this);
}
// 停止滚动
public void stopScroll() {
isStop = true;
}
// 从头开始滚动
public void startFor0() {
currentScrollX = 0;
startScroll();
}
}
|
/*
* Title: hw4_2.java
* Abstract: This program reads the user's input and displays concurrent events.
* Author: Sahil Sinha
* ID: 0183
* Date: 02/25/2021
*/
import java.util.*;
public class hw4_2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int nLines = scan.nextInt();
Map<Integer,Integer> hourCounts = new HashMap<Integer,Integer>();
scan.nextLine();
for(int i=0;i<nLines;i++){
String line = scan.nextLine();
String[] nums = line.split(" ");
int num1 = Integer.parseInt(nums[0]);
int num2 = Integer.parseInt(nums[1]);
for(int x=num1;x<num2;x++){
hourCounts.putIfAbsent(x,0);
int temp = hourCounts.get(x);
hourCounts.put(x,temp+1);
}
}
Collection<Integer> counts = hourCounts.values();
int count= Collections.max(counts);
System.out.print("Max events: "+count);
}
}
|
package com.Exam.dto;
public class ProductRequest {
int id;
String name;
double price;
int amount;
int sum;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public ProductRequest(int id, String name, double price, int amount, int sum) {
super();
this.id = id;
this.name = name;
this.price = price;
this.amount = amount;
this.sum = sum;
}
public ProductRequest() {
super();
}
}
|
package com.sirma.itt.javacourse.networkingAndGui.task4.clientInformation.client;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
/**
* The user interface of the Information client.
*
* @author Simeon Iliev
*/
public class InformationClientGUI extends JFrame {
/**
* Comment for serialVersionUID.
*/
private static final long serialVersionUID = -6264959974014685722L;
private JTextArea messageWingow;
private JButton connectButton;
private InformationClient client;
/**
* Constructor for GUI class.
*/
public InformationClientGUI() {
setUp();
}
/**
* Sets up all the UI variables.
*/
private void setUp() {
final InformationClientGUI mainWindow = this;
connectButton = new JButton("Connect");
messageWingow = new JTextArea();
messageWingow.setEditable(false);
mainWindow.setLayout(new BorderLayout());
connectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
client = new InformationClient(mainWindow);
client.start();
}
});
mainWindow.add(connectButton, BorderLayout.NORTH);
mainWindow.add(messageWingow);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(300, 200);
mainWindow.setTitle("Information Client");
mainWindow.setVisible(true);
mainWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (client != null && client.isAlive()) {
client.interrupt();
}
System.exit(0);
}
});
}
/**
* Getter method for messageWingow.
*
* @return the messageWingow the window where all the messages are.
*/
public JTextArea getMessageWingow() {
return messageWingow;
}
/**
* Setter method for messageWingow.
*
* @param messageWingow
* the messageWingow to set
*/
public void setMessageWingow(JTextArea messageWingow) {
this.messageWingow = messageWingow;
}
/**
* Main method.
*
* @param args
* arguments for the main method.
*/
public static void main(String[] args) {
new InformationClientGUI();
}
}
|
package com.project;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import com.project.battle.BattleScreen;
import com.project.ship.Ship;
import com.project.ship.Slot;
import com.project.weapons.Destructive;
import com.project.weapons.Weapon;
import com.project.weapons.WeaponEffect;
public class ProjectileAnimation implements Handleable{
private static int animationsRunning;
private Ship primary;
private Weapon weapon;
private Point click;
private int noOfProjectiles;
private int projectileGap;
private int projectilesStarted = 0;
private boolean isLeftToRight;
private boolean isCrossScreen;
private Slot slot;
private Object[] damageInfo;
private List<ProjectileInfo> projs;
private Animation animations[];
private Random rand = new Random();
private boolean outbound;
public ProjectileAnimation( Ship primary,List<ProjectileInfo> projectiles,boolean outbound) {
this.primary = primary;
this.click = projectiles.get(0).getDest();
this.slot = projectiles.get(0).getSlot();
this.projectileGap = projectiles.get(0).getWaitGap();// in pixels
this.isLeftToRight = click.x > slot.getX();
this.isCrossScreen = isLeftToRight ? click.x > Main.WIDTH/2: click.x < Main.WIDTH;
this.outbound = outbound;
this.noOfProjectiles = projectiles.size();
this.animations = new Animation[noOfProjectiles];
this.projs = projectiles;
animationsRunning++;
Rectangle2D mask = new Rectangle2D.Double(0,0,Main.WIDTH,Main.HEIGHT);
AdjustmentID align = AdjustmentID.None;
Point mid = new Point();
// set mask , end point and alignment based off of direction
if(isCrossScreen) {
if(isLeftToRight) {
mask = new Rectangle2D.Double(Main.WIDTH/2,0,Main.WIDTH,Main.HEIGHT);
align = AdjustmentID.MidUp_Left;
mid.setLocation(Main.WIDTH/2 + slot.getSlotItem().getSlotItemBody().getOnScreenWidth(),Main.HEIGHT/2);
}
else {
mask = new Rectangle2D.Double(0,0,Main.WIDTH/2,Main.HEIGHT);
align = AdjustmentID.MidUp_MidLeft;
mid.setLocation(Main.WIDTH/2,Main.HEIGHT/2);
}
for(int i = 0;i<noOfProjectiles;i++) {
Point start = new Point ();
// set animation and start & end points
Animation temp;
if(outbound){
temp = projs.get(i).getOutboundAnimation();
temp.setMonitored(false);
if(slot.isFront()) {
start.setLocation(slot.getSlotItem().getSlotItemBody().getxCoordinate()
+slot.getSlotItem().getSlotItemBody().getOnScreenWidth(),
slot.getSlotItem().getSlotItemBody().getyCoordinate()
+slot.getSlotItem().getSlotItemBody().getOnScreenHeight()/2);
}else {
start.setLocation(slot.getX(),slot.getY());
}
temp.setStartAndEnd(start,mid) ;
}
else{
temp = projs.get(i).getInboundAnimation();
temp.setMonitored(true);
temp.setStartAndEnd(mid,click) ;
}
temp.setMask(new Rectangle2D.Double(0,0,Main.WIDTH,Main.HEIGHT));//temp.setMask(mask);
temp.setAlign(align);
animations[i] = temp;
}
}
start();
}
public static boolean areAnimationsRunning() {
return (animationsRunning != 0);
}
public void render(Graphics g) {
}
public void tick() {
boolean stillRunning = false;;
for(int i = 0;i<animations.length;i++) {
if(projectilesStarted<noOfProjectiles) {
// staggered starting
if(i!=0 && animations[i-1].getxCoordinate()-slot.getX() > projectileGap){
animations[i].start();
}
}
// kill after the mid point
if(animations[i].isRunning()) {
stillRunning = true;
if(outbound){
if(isLeftToRight) {
if(animations[i].getxCoordinate()>Main.WIDTH/2) {
Animation.delete(animations[i]);
stillRunning = false;
}
}
else if((animations[i].getxCoordinate()+animations[i].getTileWidth())<Main.WIDTH/2) {
Animation.delete(animations[i]);
stillRunning = false;
}
}
}
else {
// if the animation has finished & is an inbound projectile, do effects
if(!outbound){
projs.get(i).doEffects();
}
// delete self
Animation.delete(animations[i]);
}
}
if(!stillRunning) {
animationsRunning--;
BattleScreen.handler.entitiesHighPriority.remove(this);
}
}
// start function for the group of animation
public void start() {
BattleScreen.handler.addHighPriorityEntity(this);
animations[0].start();
}
@Override
public float getZ() {
// TODO Auto-generated method stub
return 0;
}
} |
package activemq.test.p2p;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class SendMapMessage {
// 连接工厂
private ConnectionFactory factory;
// 连接对象
private Connection connection;
// Session对象
private Session session;
// 生产者
private MessageProducer producer;
public SendMapMessage() {
try {
this.factory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://localhost:61616");
this.connection = this.factory.createConnection();
this.connection.start();
this.session = connection.createSession(Boolean.FALSE,
Session.AUTO_ACKNOWLEDGE);
this.producer = this.session.createProducer(null);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void send1() {
try {
Destination destination = this.session.createQueue("first");
this.producer = session.createProducer(null);
MapMessage msg1 = this.session.createMapMessage();
// 使用Selector过来不能使用普通设置,需要使用set*Property
// msg1.setString("name", "张三");
// msg1.setString("age", "18");
msg1.setStringProperty("Group", "Group1");
msg1.setIntProperty("sal", 1);
MapMessage msg2 = this.session.createMapMessage();
// msg2.setString("name", "李四");
// msg2.setString("age", "25");
msg2.setStringProperty("Group", "Group2");
msg2.setIntProperty("sal", 2);
MapMessage msg3 = this.session.createMapMessage();
// msg3.setString("name", "王五");
// msg3.setString("age", "16");
msg3.setStringProperty("Group", "Group3");
msg3.setIntProperty("sal", 3);
MapMessage msg4 = this.session.createMapMessage();
// msg4.setString("name", "赵六");
// msg4.setString("age", "30");
msg4.setStringProperty("Group", "Group4");
msg4.setIntProperty("sal", 4);
this.producer.send(destination, msg1, DeliveryMode.NON_PERSISTENT,
2, 1000 * 60 * 10);
this.producer.send(destination, msg2, DeliveryMode.NON_PERSISTENT,
4, 1000 * 60 * 10);
this.producer.send(destination, msg3, DeliveryMode.NON_PERSISTENT,
8, 1000 * 60 * 10);
this.producer.send(destination, msg4, DeliveryMode.NON_PERSISTENT,
6, 1000 * 60 * 10);
if (this.connection != null) {
this.connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SendMapMessage s = new SendMapMessage();
s.send1();
}
}
|
/*
* Created on 09/12/2008
*
*/
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.exception.NoRowsReturnedException;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.entity.pl.BaseTplErEntity;
import com.citibank.ods.entity.pl.TplErEntity;
import com.citibank.ods.entity.pl.valueobject.TplErEntityVO;
import com.citibank.ods.persistence.pl.dao.TplErDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
import com.citibank.ods.persistence.util.CitiStatement;
/**
* @author lfabiano
* @since 09/12/2008
*/
public class OracleTplErDAO extends BaseOracleTplErDAO implements TplErDAO {
public static final String C_TPL_ER = C_PL_SCHEMA + "TPL_ER";
/**
* Este método insere um novo registro de ER
*
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#insert(com.citibank.ods.entity.pl.TplErEntity)
*/
public TplErEntity insert(TplErEntity erEntity_) {
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try {
connection = OracleODSDAOFactory.getConnection();
query.append("INSERT INTO " + C_TPL_ER + " (");
query.append(C_ER_NBR + ", ");
query.append(C_ER_RELTN_TRF_IND + ", ");
query.append(C_RELTN_END_REAS_CODE + ", ");
query.append(C_RELTN_END_REAS_TEXT + ", ");
query.append(C_EQUITY_CLASS_CODE + ", ");
query.append(C_LAST_UPD_DATE + ", ");
query.append(C_LAST_UPD_USER_ID + ", ");
query.append(C_REC_STAT_CODE + ", ");
query.append(C_LAST_AUTH_DATE + ", ");
query.append(C_LAST_AUTH_USER_ID);
query.append(") VALUES ( ");
query.append("?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
preparedStatement = new CitiStatement(connection.prepareStatement(query.toString()));
int count = 1;
preparedStatement.setString(count++, erEntity_.getData().getErNbr());
preparedStatement.setString(count++, erEntity_.getData().getErReltnTrfInd());
if (erEntity_.getData().getReltnEndReasCode() != null) {
preparedStatement.setLong(count++, erEntity_.getData().getReltnEndReasCode().longValue());
} else {
preparedStatement.setString(count++, null);
}
preparedStatement.setString(count++, erEntity_.getData().getReltnEndReasText());
if (erEntity_.getData().getEquityClassCode() != null) {
preparedStatement.setLong(count++, erEntity_.getData().getEquityClassCode().longValue());
} else {
preparedStatement.setString(count++, null);
}
preparedStatement.setTimestamp(count++, new Timestamp(erEntity_.getData().getLastUpdDate().getTime()));
preparedStatement.setString(count++, erEntity_.getData().getLastUpdUserId());
TplErEntityVO tplErEntityVO = (TplErEntityVO) erEntity_.getData();
preparedStatement.setString(count++, tplErEntityVO.getRecStatCode());
preparedStatement.setTimestamp(count++, new Timestamp(tplErEntityVO.getLastAuthDate().getTime()));
preparedStatement.setString(count++, tplErEntityVO.getLastAuthUserId());
preparedStatement.replaceParametersInQuery(query.toString());
preparedStatement.executeUpdate();
return erEntity_;
} catch (Exception e) {
throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, e);
} finally {
closeStatement(preparedStatement);
closeConnection(connection);
}
}
/* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#deleteRelations(java.lang.String)
*/
public void deleteRelations(String erNbr_) {
}
/**
* Este método altera os dados de um ER
*
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#update(com.citibank.ods.entity.pl.TplErEntity)
*/
public TplErEntity update(TplErEntity tplErEntity_) {
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try {
connection = OracleODSDAOFactory.getConnection();
query.append("UPDATE " + C_TPL_ER);
query.append(" SET ");
query.append(C_ER_RELTN_TRF_IND + " = ?, ");
query.append(C_RELTN_END_REAS_CODE + " = ?, ");
query.append(C_RELTN_END_REAS_TEXT + " = ?, ");
query.append(C_EQUITY_CLASS_CODE + " = ?, ");
query.append(C_LAST_UPD_DATE + " = ?, ");
query.append(C_LAST_UPD_USER_ID + " = ?, ");
query.append(C_LAST_AUTH_DATE + " = ?, ");
query.append(C_LAST_AUTH_USER_ID + " = ?, ");
query.append(C_REC_STAT_CODE + " = ? ");
query.append(" WHERE ");
query.append(C_ER_NBR + "= ? ");
preparedStatement = new CitiStatement(connection.prepareStatement(query.toString()));
int count = 1;
preparedStatement.setString(count++, tplErEntity_.getData().getErReltnTrfInd());
if (tplErEntity_.getData().getReltnEndReasCode() != null) {
preparedStatement.setLong(count++, tplErEntity_.getData().getReltnEndReasCode().longValue());
} else {
preparedStatement.setString(count++, null);
}
preparedStatement.setString(count++, tplErEntity_.getData().getReltnEndReasText());
if (tplErEntity_.getData().getEquityClassCode() != null) {
preparedStatement.setLong(count++, tplErEntity_.getData().getEquityClassCode().longValue());
} else {
preparedStatement.setString(count++, null);
}
preparedStatement.setTimestamp(count++, new Timestamp(tplErEntity_.getData().getLastUpdDate().getTime()));
preparedStatement.setString(count++, tplErEntity_.getData().getLastUpdUserId());
TplErEntityVO tplErEntityVO = (TplErEntityVO) tplErEntity_.getData();
preparedStatement.setTimestamp(count++, new Timestamp(tplErEntityVO.getLastAuthDate().getTime()));
preparedStatement.setString(count++, tplErEntityVO.getLastAuthUserId());
preparedStatement.setString(count++, tplErEntityVO.getRecStatCode());
preparedStatement.setString(count++, tplErEntity_.getData().getErNbr());
preparedStatement.replaceParametersInQuery(query.toString());
preparedStatement.executeUpdate();
return tplErEntity_;
} catch (Exception e) {
throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, e);
} finally {
closeStatement(preparedStatement);
closeConnection(connection);
}
}
/* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#existsRelationActive(java.lang.String)
*/
public boolean existsRelationActive(String erNbr_) {
return false;
}
/* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#existsRelation(java.lang.String, java.lang.String)
*/
public boolean existsRelation(String erNbr_, String emNbr_) {
return false;
}
/* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplErDAO#loadErNbr()
*/
public DataSet loadErNbr() {
return null;
}
/* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.BaseTplErEmDAO#find(com.citibank.ods.entity.pl.BaseTplErEmEntity)
*/
public BaseTplErEntity find(BaseTplErEntity erEntity_) {
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
ArrayList tplErEntityEntities;
BaseTplErEntity entityReturn = null;
try {
connection = OracleODSDAOFactory.getConnection();
query.append("SELECT ");
query.append(C_ER_NBR + ", ");
query.append(C_ER_RELTN_TRF_IND + ", ");
query.append(C_RELTN_END_REAS_CODE + ", ");
query.append(C_RELTN_END_REAS_TEXT + ", ");
query.append(C_EQUITY_CLASS_CODE + ", ");
query.append(C_LAST_UPD_DATE + ", ");
query.append(C_LAST_UPD_USER_ID + ", ");
query.append(C_LAST_AUTH_DATE + ", ");
query.append(C_LAST_AUTH_USER_ID + ", ");
query.append(C_REC_STAT_CODE);
query.append(" FROM ");
query.append(C_TPL_ER);
query.append(" WHERE ");
query.append(C_ER_NBR + " = ?");
preparedStatement = new CitiStatement(connection.prepareStatement(query.toString()));
preparedStatement.setString(1, erEntity_.getData().getErNbr());
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
tplErEntityEntities = instantiateFromResultSet(resultSet);
if (tplErEntityEntities.size() == 0) {
throw new NoRowsReturnedException();
} else if (tplErEntityEntities.size() > 1) {
throw new UnexpectedException(C_ERROR_TOO_MANY_ROWS_RETURNED);
} else {
entityReturn = (BaseTplErEntity) tplErEntityEntities.get(0);
}
return entityReturn;
} catch (SQLException e) {
throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e);
}
finally {
closeStatement(preparedStatement);
closeConnection(connection);
}
}
private ArrayList instantiateFromResultSet(ResultSet resultSet_) {
TplErEntity tplErEntity;
Timestamp timestamp;
Date date;
ArrayList tplErEntities = new ArrayList();
try {
while (resultSet_.next()) {
tplErEntity = new TplErEntity();
tplErEntity.getData().setErNbr(resultSet_.getString(C_ER_NBR));
if (resultSet_.getString(C_ER_RELTN_TRF_IND) != null) {
tplErEntity.getData().setErReltnTrfInd(resultSet_.getString(C_ER_RELTN_TRF_IND));
} else {
tplErEntity.getData().setErReltnTrfInd(null);
}
if (resultSet_.getString(C_RELTN_END_REAS_CODE) != null) {
tplErEntity.getData().setReltnEndReasCode(new BigInteger(resultSet_.getString(C_RELTN_END_REAS_CODE)));
} else {
tplErEntity.getData().setReltnEndReasCode(null);
}
if (resultSet_.getString(C_RELTN_END_REAS_TEXT) != null) {
tplErEntity.getData().setReltnEndReasText(resultSet_.getString(C_RELTN_END_REAS_TEXT));
} else {
tplErEntity.getData().setReltnEndReasText(null);
}
if (resultSet_.getString(C_EQUITY_CLASS_CODE) != null) {
tplErEntity.getData().setEquityClassCode(new BigInteger(resultSet_.getString(C_EQUITY_CLASS_CODE)));
} else {
tplErEntity.getData().setEquityClassCode(null);
}
timestamp = resultSet_.getTimestamp(C_LAST_UPD_DATE);
date = new Date(timestamp.getTime());
tplErEntity.getData().setLastUpdDate(date);
tplErEntity.getData().setLastUpdUserId(resultSet_.getString(C_LAST_UPD_USER_ID));
timestamp = resultSet_.getTimestamp(C_LAST_AUTH_DATE);
date = new Date(timestamp.getTime());
tplErEntity.getData().setLastAuthDate(date);
tplErEntity.getData().setLastAuthUserId(resultSet_.getString("LAST_AUTH_USER_ID"));
tplErEntity.getData().setRecStatCode(resultSet_.getString(C_REC_STAT_CODE));
tplErEntities.add(tplErEntity);
}
} catch (SQLException e) {
throw new UnexpectedException(e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e);
}
return tplErEntities;
}
}
|
package com.alibaba.druid.bvt.sql.mysql.transform;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.transform.FromSubqueryResolver;
import com.alibaba.druid.util.JdbcConstants;
import junit.framework.TestCase;
import java.util.List;
/**
* Created by wenshao on 16/07/2017.
*/
public class Trans_CreateView_1 extends TestCase {
public void test_createView() throws Exception {
String sql = " CREATE OR REPLACE FORCE VIEW \"CMIS\".\"LM_LOAN_MSGINFO\" (\"LOAN_NO\", \"OD_PRCP\", \"OD_DAYS\", \"OD_TNR\", \"ENTRYCS_DAYS\") AS \n" +
" select loan.loan_no as loan_no,coln.od_prcp,\n" +
"to_date((select cur_prcs_dt from s_ctrl),'YYYY-MM-DD')-to_date(loan.next_due_dt,'YYYY-MM-DD') as od_days,\n" +
"shd.od_tnr as od_tnr,\n" +
"to_date((select cur_prcs_dt from s_ctrl),'YYYY-MM-DD')-to_date(coln.entry_dt,'YYYY-MM-DD') as entrycs_days from lm_loan loan\n" +
"left join (select count(*) as od_tnr,loan_no\n" +
" from lm_pm_shd\n" +
" where ps_due_dt < (select cur_prcs_dt from s_ctrl)\n" +
" and setl_ind = 'N'\n" +
" and ps_od_ind = 'Y'\n" +
" and ps_perd_no <> 0 group by loan_no) shd on shd.loan_no=loan.loan_no\n" +
"left join cs_coln coln on loan.loan_no = coln.loan_no\n" +
"where loan.LOAN_OD_IND='Y' and loan.LOAN_STS='ACTV'";
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE);
assertEquals(1, stmtList.size());
SQLStatement stmt = stmtList.get(0);
List<SQLStatement> targetList = FromSubqueryResolver.resolve((SQLCreateViewStatement) stmt);
String targetSql = SQLUtils.toSQLString(targetList, JdbcConstants.ORACLE);
assertEquals(2, targetList.size());
}
}
|
package org.zhq;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author zhengquan
*/
@Data
@AllArgsConstructor
public class ServerInfo {
private String ip;
private int port;
private String sn;
}
|
package com.example.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Giphy {
private Giphy data;
private Images images;
public Giphy() {
}
public Giphy getData() {
return data;
}
public void setData(Giphy data) {
this.data = data;
}
public Images getImages() {
return images;
}
public void setImages(Images images) {
this.images = images;
}
public class Images {
private HashMap<String, String> original;
public HashMap<String, String> getOriginal() {
return original;
}
public void setOriginal(HashMap<String, String> original) {
this.original = original;
}
}
}
|
package com.ebay.screens.common;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
/**
* This Interface is used to define generic screen event methods
*/
public interface EBayElementMethods {
public void click(By locator);
public Boolean waitForVisibility(By targetElement);
public Boolean waitForInvisibility(By targetElement);
public Boolean isElementPresent(By targetElement)throws InterruptedException;
public void tap(double xPosition, double yPosition);
public WebElement findElement(By locator);
public List<WebElement> findElements(By locator);
public String getAlertText();
public void swipe(double startX, double startY, double endX, double endY, double duration);
public void scrollDown(int swipeTimes, int durationForSwipe);
public void scrollUp(int swipeTimes, int durationForSwipe);
}
|
package de.hdm.softwarepraktikum.shared.bo;
import java.sql.Timestamp;
import com.google.gwt.user.client.rpc.IsSerializable;
/*
* Die Kalsse stellt die Basisklasse dar, für alle in diesem Projekt
* relevanten Klassen zur Umsetzung der fachlichen Vorgaben.
*/
public abstract class BusinessObject implements IsSerializable{
private static final long serialVersionUID = 1L;
private int id;
private Timestamp creationdate;
private Timestamp changedate;
/**
* Konstruktor des SharedBusinessObjects
* Wird bei der Erzeugung eines neuen SharedBusinessObjects Objekts standardmäßig
* aufgerufen. Dabei wird ein Creationdate erzeugt und dem Objekt zugewiesen.
*/
public BusinessObject () {
/**
* **************************************************************************************
* ABSCHNITT Anfang: Getter und Setter der Attribute
* **************************************************************************************
*/
/*
* Setzen des Erstelldatums
*/
this.setCreationdate(new Timestamp(System.currentTimeMillis()));
this.changedate=creationdate;
}
/*
* Auslesen der ID
* @return Die ID wird zurückgegeben
*/
public int getId() {
return id;
}
/*
* Setzen der ID
*/
public void setId(int id) {
this.id = id;
}
/*
* Auslesen des Erstelldatums
* @return Das Creationdate wird zurückgegeben
*/
public Timestamp getCreationdate() {
return this.creationdate;
}
/*
* Setzen des Erstelldatums
*/
public void setCreationdate(Timestamp creationdate) {
this.creationdate = creationdate;
}
/*
* Auslesen des Änderungsdatums
* @return Das Changedate wird zurückgegeben
*/
public Timestamp getChangedate() {
return this.changedate;
}
/*
* Setzen des Änderungsdatums
*/
public void setChangedate(Timestamp changedate) {
this.changedate = changedate;
}
/*
* Rückgabe Name + ID als String
*/
public String toString() {
return this.getClass().getName() + "#" + this.id;
}
/**
* Variante der Methode getCreationDate, dabei wird das Datum allerdings verkürzt als String zurückgegeben.
*
* @return Das Creationdate wird zurückgegeben
*/
public String getCreationDateString() {
String creationDate = this.creationdate.toString().split("\\.")[0];
return creationDate;
}
/**
* Variante der Methode getChangeDate, dabei wird das Datum verkürzt als String zurückgegeben.
*
* @return Das Changedate wird zurückgegeben
*/
public String getChangeDateString() {
String changeDate = this.changedate.toString().split("\\.")[0];
return changeDate;
}
//Prüfen ob gleiches Objekt anhand der ID
public boolean equals(Object obj) {
if (obj != null && obj instanceof BusinessObject) {
BusinessObject bo = (BusinessObject) obj;
try {
if (bo.getId() == this.id)
return true;
}
catch (IllegalArgumentException e) {
return false;
}
}
/*
* Wenn bislang keine Gleichheit bestimmt werden konnte, dann müssen
* schließlich false zurückgeben.
*/
return false;
}
/**
* **************************************************************************************
* ABSCHNITT Ende: Getter und Setter der Attribute
* **************************************************************************************
*/
}
|
package myGame;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class WriteScors {
private int i=0;
private String stringInt;
private char currentCaract;
private FileInputStream fis;
private int[] savedTime = new int[Window.LEVELNUMBER+1];
private FileOutputStream file;
private int levelNumber=Window.LEVELNUMBER;
public WriteScors(){
}
public void AddScore(int milisec, int level, int action){
Decrypt DC = new Decrypt();
DC.decrypte("scores");
try {
String input = "";
fis = new FileInputStream("scores.txt");
for(i=0; i<levelNumber; i++){
stringInt = "";
do{
currentCaract = (char)fis.read();
if(currentCaract!='/' && currentCaract!='\n')stringInt += currentCaract;
}while(currentCaract !='/');
savedTime[i] = Integer.parseInt(stringInt);
}
if(action==0 && savedTime[level+1] > milisec)savedTime[level+1] = milisec;
else if(action == 1)savedTime[0]++;
for(i=0; i<levelNumber; i++){
input += Integer.toString(savedTime[i])+"/";
}
file = new FileOutputStream("scores.txt");
file.write(input.getBytes());
} catch (Exception e) {
System.out.println("Problem reading file.");
}
DC.decrypte("scores");
}
public int[] getSavedTime() {
return savedTime;
}
}
|
package codingBat.recursion1;
public class Exe12ChangeXY {
/*
Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.
changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"
*/
public String changeXY(String str) {
if (str.length() == 0) return "";
if (str.length() == 1) return str.equals("x") ? "y" : str;
return str.charAt(0) == 'x' ? "y" + changeXY(str.substring(1)) : str.charAt(0) + changeXY(str.substring(1));
}
}
|
package com.doc.spring.custom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.format.Formatter;
public class CustomDatatimeformater implements Formatter<Date> {
private String pattern;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
public CustomDatatimeformater(String pattern) {
this.pattern=pattern;
}
public String print(Date object, Locale locale) {
return sdf.format(object);
}
public Date parse(String text, Locale locale) throws ParseException {
return sdf.parse(text);
}
}
|
package exemplos.aula10.lsp.correto;
/**
* Exemplo retirado do artigo do Baeldung.
* https://www.baeldung.com/solid-principles
*/
public class Engine {
public void on() {
}
public void powerOn(int i) {
}
}
|
package com.zhibo.duanshipin.fragment;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhibo.duanshipin.R;
import com.zhibo.duanshipin.adapter.LiveListAdapter;
import com.zhibo.duanshipin.base.BaseLazyFragment;
import com.zhibo.duanshipin.bean.LiveListBean;
import com.zhibo.duanshipin.httprequest.HttpRequestPresenter;
import com.zhibo.duanshipin.httprequest.HttpRequestView;
import com.zhibo.duanshipin.utils.Consts;
import com.zhibo.duanshipin.utils.ToastUtils;
import com.zhibo.duanshipin.utils.ULog;
import com.zhibo.duanshipin.widget.recyclerview.RecyclerViewFooter;
import com.zhibo.duanshipin.widget.recyclerview.RecyclerViewStateUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jzvd.JZMediaManager;
import cn.jzvd.JZUtils;
import cn.jzvd.JZVideoPlayer;
public class LiveListFragment extends BaseLazyFragment implements HttpRequestView, LiveListAdapter.OnGridItemClickListener,OnRefreshLoadmoreListener{
private static final String TERM_ID = "term_id";
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.refreshLayout)
SmartRefreshLayout refreshLayout;
private String mTermId;
private int mPage = 1;
private HttpRequestPresenter requestPresenter;
private String url = "http://newlive.longhoo.net/index.php?g=portal&m=video&a=picinfo";
private LiveListAdapter adapter;
private List<LiveListBean.ListsBean> dataList = new ArrayList<>();
//private LRecyclerViewAdapter lRecyclerViewAdapter;
private boolean isRefreshing;
private boolean isLoadingMore;
private LinearLayoutManager manager;
boolean mFull = false;
public static LiveListFragment newInstance(String mTermId) {
LiveListFragment fragment = new LiveListFragment();
Bundle args = new Bundle();
args.putString(TERM_ID, mTermId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTermId = getArguments().getString(TERM_ID);
}
}
@Override
protected int getContentId() {
return R.layout.fragment_live_list;
}
@Override
protected void onLazyLoad() {
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
//recyclerView.setRefreshing(true);
if(recyclerView!=null&&!getActivity().isFinishing()){
refreshLayout.finishRefresh();
onRefresh(refreshLayout);
}
}
}, 200);
}
@Override
protected void initViews(View view) {
requestPresenter = new HttpRequestPresenter(getActivity(), this);
adapter = new LiveListAdapter(getActivity(), dataList);
adapter.setOnGridItemClickListener(this);
// lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
// lRecyclerViewAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(adapter);
manager = new LinearLayoutManager(this.getActivity());
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
// recyclerView.setPullRefreshEnabled(true);
// recyclerView.setOnRefreshListener(this);
// recyclerView.setOnLoadMoreListener(this);
refreshLayout.setOnRefreshLoadmoreListener(this);
// recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//
// int firstVisibleItem, lastVisibleItem;
//
// @Override
// public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// super.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// super.onScrolled(recyclerView, dx, dy);
// firstVisibleItem = manager.findFirstVisibleItemPosition();
// lastVisibleItem = manager.findLastVisibleItemPosition();
// //大于0说明有播放
// if (GSYVideoManager.instance().getPlayPosition() >= 0) {
// //当前播放的位置
// int position = GSYVideoManager.instance().getPlayPosition();
// //对应的播放列表TAG
// if (GSYVideoManager.instance().getPlayTag().equals(LiveListAdapter.TAG)
// && (position < firstVisibleItem || position > lastVisibleItem)) {
// //如果滑出去了上面和下面就是否,和今日头条一样
// if(!mFull) {
// GSYVideoPlayer.releaseAllVideos();
// adapter.notifyDataSetChanged();
// }
// }
// }
// }
// });
recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
@Override
public void onChildViewAttachedToWindow(View view) {
}
@Override
public void onChildViewDetachedFromWindow(View view) {
JZVideoPlayer jzvd = (JZVideoPlayer) view.findViewById(R.id.video_item_player);
if (jzvd != null && JZUtils.dataSourceObjectsContainsUri(jzvd.dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
JZVideoPlayer.releaseAllVideos();
}
}
});
}
@Override
protected void initToolbar() {
}
@Override
protected long setLoadInterval() {
return 0;
}
@Override
public void onNetworkError() {
ToastUtils.getInstance().showToast(getActivity(), "网络异常!");
}
@Override
public void onRefreshSuccess(String response) {
if (!isPrepared) {
return;
}
ULog.e(Consts.TAG, "播放图文:" + response);
isRefreshing = false;
//recyclerView.refreshComplete();
refreshLayout.finishRefresh();
//处理数据
List<LiveListBean.ListsBean> tempList = null;
Gson gson = new Gson();
try {
LiveListBean liveListBean = gson.fromJson(response, LiveListBean.class);
int code = liveListBean.getStatus();
if (code != 0) {
ToastUtils.getInstance().showToast(getActivity(), "获取数据失败~");
return;
}
tempList = liveListBean.getLists();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
if (tempList == null) {
ToastUtils.getInstance().showToast(getActivity(), "服务器异常~");
return;
}
dataList.clear();
if (tempList.size() > 0) {
dataList.addAll(tempList);
mPage++;
}
adapter.notifyDataSetChanged();
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
if(recyclerView!=null&&!getActivity().isFinishing()){
recyclerView.scrollToPosition(0);
}
}
},500);
}
@Override
public void onRefreshError() {
if (!isPrepared) {
return;
}
isRefreshing = false;
//recyclerView.refreshComplete();
refreshLayout.finishRefresh();
RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, RecyclerViewFooter.State.Normal, null);
ToastUtils.getInstance().showToast(getActivity(), "刷新失败~");
}
@Override
public void onLoadMoreSuccess(String response) {
if (!isPrepared) {
return;
}
ULog.e(Consts.TAG, "播放图文:" + mPage + ":" + response);
isLoadingMore = false;
//RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, RecyclerViewFooter.State.Normal, null);
refreshLayout.finishLoadmore();
//处理数据
List<LiveListBean.ListsBean> tempList = null;
Gson gson = new Gson();
try {
LiveListBean liveListBean = gson.fromJson(response, LiveListBean.class);
int code = liveListBean.getStatus();
if (code != 0) {
ToastUtils.getInstance().showToast(getActivity(), "获取数据失败~");
return;
}
tempList = liveListBean.getLists();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
if (tempList == null) {
ToastUtils.getInstance().showToast(getActivity(), "解析错误!");
return;
}
//没有数据或数据<limit,说明无更多
if (tempList.size() <= 0) {
RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, RecyclerViewFooter.State.TheEnd, null);
} else {
dataList.addAll(tempList);
mPage++;
adapter.notifyDataSetChanged();
}
}
@Override
public void onLoadMoreError() {
if (!isPrepared) {
return;
}
isLoadingMore = false;
//RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, RecyclerViewFooter.State.NetWorkError, mFooterClick);
ToastUtils.getInstance().showToast(getActivity(), "获取更多数据失败~");
}
@Override
public void onGridItemClick(int listPosition, int gridPosition) {
if (listPosition >= 0 && listPosition <= dataList.size() - 1) {
List<LocalMedia> photoList = new ArrayList<>();
for (String photo : dataList.get(listPosition).getPhotos()) {
photoList.add(new LocalMedia(photo, 0, PictureMimeType.ofImage(), ""));
}
PictureSelector.create(this).externalPicturePreview(gridPosition, photoList);
}
}
@Override
public void onLoadmore(RefreshLayout refreshlayout) {
if (isRefreshing) {
ToastUtils.getInstance().showToast(getActivity(), "正在刷新中,请稍后...");
return;
}
isLoadingMore = true;
RecyclerViewFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
if (state == RecyclerViewFooter.State.Loading) {
return;
}
//开始加载
RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, RecyclerViewFooter.State.Loading, null);
Map<String, String> params = new HashMap<>();
params.put("page", String.valueOf(mPage));
params.put("size", "10");
params.put("term_id", mTermId);
requestPresenter.doHttpData(url, Consts.REQUEST_METHOD_POST, Consts.REQUEST_LOADMORE, params);
}
@Override
public void onRefresh(RefreshLayout refreshlayout) {
if (isLoadingMore) {
ToastUtils.getInstance().showToast(getActivity(), "正在加载中,请稍后...");
return;
}
isRefreshing = true;
mPage = 1;
Map<String, String> params = new HashMap<>();
params.put("page", String.valueOf(mPage));
params.put("size", "10");
params.put("term_id", mTermId);
requestPresenter.doHttpData(url, Consts.REQUEST_METHOD_POST, Consts.REQUEST_REFRESH, params);
}
public void refreshData(String mTermId){
if(refreshLayout!=null&&!getActivity().isFinishing()){
this.mTermId = mTermId;
onRefresh(refreshLayout);
}
}
}
|
package stuff;
import java.math.BigInteger;
import java.util.stream.Stream;
public class UniqueRemainders {
public static void main(String[] args) {
// for (int i = 23; i <= 24; i++){
// System.out.println(small(i));
// }
BigInteger t = new BigInteger("1");
System.out.println(Stream.iterate(new BigInteger("1"), (BigInteger bi) -> bi.add(BigInteger.ONE)).limit(150_000).reduce(UniqueRemainders::lcm).get().subtract(t));
}
public static boolean mod(int N, int X) {
for (int i = 1; i <= N; i++) {
if (X % i != i - 1) {
return false;
}
}
return true;
}
public static boolean mod(int N, BigInteger X) {
BigInteger bn = new BigInteger(Integer.toString(N));
for (BigInteger i = new BigInteger("1"); i.compareTo(bn)<=0; i = i.add(BigInteger.ONE)) {
if (X.mod(i).compareTo(i.subtract(BigInteger.ONE)) != 0) {
return false;
}
}
return true;
}
public static BigInteger small(int N) {
BigInteger bn = new BigInteger(Integer.toString(N));
BigInteger x = new BigInteger(Integer.toString(N-1));
while (!mod(N, x)) {
x = x.add(bn);
}
return x;
}
// public static int small(int N) {
// int x = N-1;
// while (!mod(N, x)) {
// x += N;
// }
// return x;
//
// }
private static BigInteger gcd(BigInteger a, BigInteger b)
{
while (b.compareTo(BigInteger.ZERO) > 0)
{
BigInteger temp = b;
b = a.mod(b); // % is remainder
a = temp;
}
return a;
}
private static BigInteger lcm(BigInteger a, BigInteger b)
{
return a.multiply(b.divide(gcd(a,b)));
}
// private static BigInteger gcd(BigInteger[] input)
// {
// BigInteger result = input[0];
// for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
// return result;
// }
//
// private static BigInteger lcm(BigInteger[] input)
// {
// BigInteger result = input[0];
// for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
// return result;
// }
}
|
package org.xiyu.mongodbdemo.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import org.xiyu.mongodbdemo.entity.User;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
|
package com.ecole.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ecole.model.Matiere;
public class MatiereDao {
private String url = "jdbc:postgresql://localhost:5432/Ecole";
private String user = "postgres";
private String password = "n141n4";
private static final String INSERT_MATIERE_SQL =
"INSERT INTO matiere" + "(mat_nom) VALUES " + " (?)";
private static final String SELECT_MATIERE_BY_ID =
"SELECT mat_id, mat_nom FROM matiere WHERE mat_id=?";
private static final String SELECT_ALL_MATIERE =
" SELECT * FROM matiere ";
private static final String DELETE_MATIERE_SQL =
"DELETE FROM matiere WHERE mat_id = ?";
private static final String UPDATE_MATIERE_SQL =
"UPDATE matiere SET mat_nom = ? WHERE mat_id = ?";
public MatiereDao() {
super();
// TODO Auto-generated constructor stub
}
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, password);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Connexion échouée");
// TODO: handle exception
}
return connection;
}
// INSERT MATIERE
public void insertMatiere(Matiere matiere) {
System.out.println(INSERT_MATIERE_SQL);
try (Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(INSERT_MATIERE_SQL)) {
pstmt.setString(1, matiere.getMat_nom());
System.out.println(pstmt);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// SELECT MATIERE BY ID
public Matiere selectMatiere(int mat_id) {
Matiere matiere = null;
try (Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(SELECT_MATIERE_BY_ID)) {
pstmt.setInt(1, mat_id);
System.out.println(pstmt);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String mat_nom = rs.getString("mat_nom");
matiere = new Matiere(mat_id, mat_nom);
}
} catch (SQLException e) {
e.printStackTrace();
}
return matiere;
}
//SELECT ALL MATIERE
public List<Matiere> selectAllMatiere() {
List<Matiere> matiere = new ArrayList<>();
try (Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(SELECT_ALL_MATIERE)) {
System.out.println(pstmt);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int mat_id = rs.getInt("mat_id");
String mat_nom = rs.getString("mat_nom");
matiere.add(new Matiere(mat_id,mat_nom));
}
} catch (SQLException e) {
e.printStackTrace();
}
return matiere;
}
// UPDATE MATIERE
public boolean updateMatiere(Matiere matiere) throws SQLException {
boolean rowUpdated ;
try (Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(UPDATE_MATIERE_SQL)) {
System.out.println("Matiere mis à jour " + pstmt);
pstmt.setString(1, matiere.getMat_nom());
pstmt.setInt(2, matiere.getMat_id());
rowUpdated = pstmt.executeUpdate() > 0;
}
return rowUpdated;
}
// DELETE MATIERE
public boolean deleteMatiere(int id) {
boolean rowDeleted = false;
try (Connection connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(DELETE_MATIERE_SQL)) {
pstmt.setInt(1, id);
rowDeleted = pstmt.executeUpdate() > 0;
System.out.println("Matiere mis à jour " + pstmt);
} catch (SQLException e) {
e.printStackTrace();
}
return rowDeleted;
}
}
|
package tedxperiments.math.entrenamente;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
/**
* Created by fzimmerman on 4/9/17.
*/
public class AcceptanceActivity extends Activity implements View.OnClickListener {
private TextView acceptanceTextView;
private CheckBox acceptanceCheckBox;
private Button acceptanceButton;
private boolean checked=false;
private String nextActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acceptance);
Intent previousIntent= getIntent();
Bundle bundle = previousIntent.getExtras();
if(bundle!=null) {
nextActivity = (String) bundle.get("type");
}
ActionBar AB = getActionBar();
AB.hide();
acceptanceTextView = (TextView) this.findViewById(R.id.acceptanceTextView);
acceptanceCheckBox =(CheckBox) this.findViewById(R.id.acceptanceCheckBox);
acceptanceButton = (Button) this.findViewById(R.id.acceptanceButton);
acceptanceButton.setOnClickListener(this);
acceptanceButton.setText(R.string.no_acceptance_button);
acceptanceCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checked = true;
acceptanceButton.setText(R.string.yes_acceptance_button);
}
else {
checked = false;
acceptanceButton.setText(R.string.no_acceptance_button);
}
}
});
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.acceptanceButton){
if(checked){
//AVANZO
startPlay();
}
else{
super.onBackPressed();
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
public void startPlay(){
if(nextActivity.equals("arcade")){
int askpersonal = PassLevel.getAskPersonal("Ask", MainActivity.THEcontext);
if (askpersonal<1){
Intent personalIntent = new Intent(this, PersonalQuestions.class);
this.startActivity(personalIntent);
}
else {
Intent arcIntent = new Intent(this, HighList.class);
this.startActivity(arcIntent);
finish();
}
}
if(nextActivity.equals("practice")){
Intent levelIntent = new Intent(this, LevelSelect.class);
this.startActivity(levelIntent);
}
PassLevel.setAskPersonal("AcceptanceAsked", 2, MainActivity.THEcontext);
finish();
}
}
|
package com.basho.riak.client.core.operations.ts;
import com.basho.riak.client.core.operations.PBFutureOperation;
import com.basho.riak.client.core.query.timeseries.QueryResult;
import com.basho.riak.client.core.query.timeseries.PbResultFactory;
import com.basho.riak.protobuf.RiakMessageCodes;
import com.basho.riak.protobuf.RiakTsPB;
import com.google.protobuf.ByteString;
import java.util.List;
/**
* @author Alex Moore <amoore at basho dot com>
* @author Sergey Galkin <srggal at gmail dot com>
* @since 2.0.3
*/
public class ListKeysOperation extends PBFutureOperation<QueryResult, RiakTsPB.TsListKeysResp, String>
{
private final Builder builder;
private String queryInfoMessage;
private ListKeysOperation(Builder builder)
{
super(RiakMessageCodes.MSG_TsListKeysReq,
RiakMessageCodes.MSG_TsListKeysResp,
builder.reqBuilder,
RiakTsPB.TsListKeysResp.PARSER);
this.builder = builder;
}
@Override
protected QueryResult convert(List<RiakTsPB.TsListKeysResp> rawResponses)
{
return PbResultFactory.convertPbListKeysResp(rawResponses);
}
@Override
public String getQueryInfo()
{
if (this.queryInfoMessage == null)
{
this.queryInfoMessage = createQueryInfoMessage();
}
return this.queryInfoMessage;
}
private String createQueryInfoMessage()
{
return new StringBuilder("SELECT PRIMARY KEY FROM ")
.append(this.builder.tableName)
.toString();
}
@Override
protected boolean done(RiakTsPB.TsListKeysResp message)
{
return message.getDone();
}
public static class Builder
{
private final RiakTsPB.TsListKeysReq.Builder reqBuilder =
RiakTsPB.TsListKeysReq.newBuilder();
private final String tableName;
/**
* Construct a builder for a ListKeysOperation.
* @param tableName The name of the Time Series table in Riak.
*/
public Builder(String tableName)
{
if (tableName == null)
{
throw new IllegalArgumentException("Table Name cannot be null");
}
reqBuilder.setTable(ByteString.copyFromUtf8(tableName));
this.tableName = tableName;
}
public Builder withTimeout(int timeout)
{
if (timeout <= 0)
{
throw new IllegalArgumentException("Timeout can not be zero or less");
}
reqBuilder.setTimeout(timeout);
return this;
}
public ListKeysOperation build()
{
return new ListKeysOperation(this);
}
}
}
|
public class KdTree {
private KdNode root;
private int size;
private static class KdNode {
private final GraphDB.Node point;
private boolean compareX;
private KdNode leftBottom;
private KdNode rightTop;
KdNode(GraphDB.Node p, boolean compareX) {
this.point = p;
this.compareX = compareX;
}
public boolean isRightOrTopOf(GraphDB.Node q) {
return (compareX && point.lon > q.lon || (!compareX && point.lat > q.lat));
}
}
public KdTree() {
root = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void insert(GraphDB.Node p) {
if (root == null) {
root = new KdNode(p, true);
size++;
return;
}
// find node position for insertion
KdNode pre = null;
KdNode cur = root;
do {
if (cur.point.id == p.id) {
return;
}
pre = cur;
cur = cur.isRightOrTopOf(p) ? cur.leftBottom : cur.rightTop;
} while (cur != null);
// prepare new node and insert
if (pre.isRightOrTopOf(p)) {
pre.leftBottom = new KdNode(p, !pre.compareX);
} else {
pre.rightTop = new KdNode(p, !pre.compareX);
}
size++;
}
public long nearest(double lon, double lat) {
return nearest(new GraphDB.Node(0, lon, lat)).id;
}
public GraphDB.Node nearest(GraphDB.Node p) {
return nearest(p, root, Double.MAX_VALUE);
}
private GraphDB.Node nearest(GraphDB.Node p, KdTree.KdNode node, double minDist) {
if (p == null) {
throw new NullPointerException();
}
if (node.point == null) {
return null;
}
if (node.point.equals(p)) {
return node.point;
}
GraphDB.Node bestPoint = null;
double bestDist = minDist;
double nodeDist = GraphDB.distance(node.point.lon, node.point.lat, p.lon, p.lat);
if (nodeDist < minDist) {
bestPoint = node.point;
bestDist = nodeDist;
}
KdNode first = node.rightTop, second = node.leftBottom;
if ((node.compareX && p.lon <= node.point.lon)
|| (!node.compareX && p.lat <= node.point.lat)) {
first = node.leftBottom;
second = node.rightTop;
}
if (first != null) {
GraphDB.Node firstBestPoint = nearest(p, first, bestDist);
if (firstBestPoint != null) {
bestPoint = firstBestPoint;
bestDist = GraphDB.distance(bestPoint.lon, bestPoint.lat, p.lon, p.lat);
}
}
if (second == null) {
return bestPoint;
}
if (second == node.leftBottom) {
if (node.compareX && p.lon - node.point.lon >= bestDist) {
return bestPoint;
}
if (!node.compareX && p.lat - node.point.lat >= bestDist) {
return bestPoint;
}
} else if (second == node.rightTop) {
if (node.compareX && node.point.lon - p.lon >= bestDist) {
return bestPoint;
}
if (!node.compareX && node.point.lat - p.lat >= bestDist) {
return bestPoint;
}
}
GraphDB.Node secondBestPoint = nearest(p, second, bestDist);
if (secondBestPoint != null) {
bestPoint = secondBestPoint;
}
return bestPoint;
}
} |
package com.tony.pandemic.report;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@AllArgsConstructor
@Service
public class ReportServiceImpl implements IReportService {
private IListItems listItems;
private IPercentageHospital percentualHospital;
private ITimeOccupatedHospital timeOccupatedHospital;
private INegotiationHistory negotiationHistory;
@Override
public Report makeReport() {
final Report report = new Report();
report.setMediaHospitalItems(this.listItems.listItens());
report.setPercentageHighOccupation(this.percentualHospital.percentageHighOccupation());
report.setPercentageLowOccupation(this.percentualHospital.percentageLowOccupation());
report.setHighOccupationMostTime(this.timeOccupatedHospital.moreOccupatedMostTime());
report.setLowOccupationMostTime(this.timeOccupatedHospital.lessOccupatedMostTime());
report.setNegotiationHistory(this.negotiationHistory.makeNegotiationHistory());
return report;
}
}
|
package UI;
import GUIController.ValidateCredentials;
import Interfaces.LoginInformation;
import RootClasses.Infos;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
import java.sql.*;
//Kommentieren
public class Login extends Application
{
@FXML
javafx.scene.control.TextField loginFieldLogin;
@FXML
javafx.scene.control.PasswordField passwordFieldLogin;
@FXML
javafx.scene.control.Label wrongPasswordMessage;
@FXML
javafx.scene.control.Button enterButton;
private static final String DBURL = LoginInformation.DBURL;
private static final String LOGIN = LoginInformation.LOGIN;
private static final String PASSWORD = LoginInformation.PASSWORD;
public static Connection con;
public static String userName;
public static String accountType;
public static int customerNumber;
static
{
try
{
con = DriverManager.getConnection(DBURL, LOGIN, PASSWORD);
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException
{
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
Scene scene = new Scene(root);
scene.setFill(Color.TRANSPARENT);
primaryStage.setTitle("CarGateway");
primaryStage.setScene(scene);
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setResizable(false);
primaryStage.show();
}
@FXML
private void cancelButtonClickedAction()
{
Platform.exit();
}
@FXML
private void registerButtonClickedAction() throws Exception
{
try
{
Parent root = FXMLLoader.load(getClass().getResource("Register.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.initStyle(StageStyle.TRANSPARENT);
stage.show();
} catch (Exception e)
{
e.printStackTrace();
}
}
@FXML
private void loginButtonClickedAction() throws SQLException, IOException
{
boolean isValid = ValidateCredentials.login(loginFieldLogin.getText(), passwordFieldLogin.getText(), wrongPasswordMessage);
if (isValid)
{
userName = loginFieldLogin.getText();
accountType = getAccountType();
customerNumber = getCustomerNumber();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MainMenu.fxml"));
Parent parent = (AnchorPane) fxmlLoader.load();
MainMenu mainMenu = fxmlLoader.getController();
mainMenu.setUserName(getEMail());
mainMenu.setAccountTypeLabel(getAccountType());
Infos.setKartennummer(customerNumber);
Stage stage = (Stage) enterButton.getScene().getWindow();
Scene scene = new Scene(parent);
stage.setScene(scene);
}
}
@FXML
private void forgotPasswordButtonClickedAction() throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("ForgotPassword.fxml"));
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.initStyle(StageStyle.TRANSPARENT);
stage.show();
}
@FXML
public String getEMail() throws SQLException
{
PreparedStatement statement = con.prepareStatement("SELECT email FROM customer WHERE email = " + "'" + loginFieldLogin.getText() + "';");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
userName = resultSet.getString(1);
return userName;
}
@FXML
public String getAccountType() throws SQLException
{
PreparedStatement statement = con.prepareStatement("SELECT kontoart FROM customer WHERE email = " + "'" + loginFieldLogin.getText() + "';");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
accountType = resultSet.getString(1);
return accountType;
}
@FXML
public int getCustomerNumber() throws SQLException
{
PreparedStatement statement = con.prepareStatement("SELECT kundennummer FROM customer WHERE email = " + "'" + loginFieldLogin.getText() + "';");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
customerNumber = resultSet.getInt(1);
return customerNumber;
}
}
|
package com.datastax.poc.log;
import com.datastax.driver.core.utils.UUIDs;
import com.datastax.poc.log.sink.LogSinkFactory;
import com.datastax.poc.log.sink.LogSink;
import com.datastax.poc.log.utils.Random;
import org.apache.commons.cli.*;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.datastax.poc.log.sink.LogSinkFactory.SinkType;
/**
* Created by Patrick on 12/10/15.
*/
public class LogSourceSimulator {
public static void main(String[] args) {
// Simulator settings
String sink = null;
UUID[] sourceIds = null;
String[] logTypes = null;
int bucketTimeInSeconds = -1;
int threadCount = -1;
int pauseTime = -1;
int logsTosend = -1;
// Parse command line
CommandLineParser parser = new DefaultParser();
Options options = new Options();
options.addOption( "k", "sink", true, "Target sink [kafka|cassandra]. Kafka by default.");
options.addOption( "s", "sources", true, "Log source ids, as a comma separated list. Single random id by default.");
options.addOption( "l", "log-types", true, "Comma separated list of log types.");
options.addOption( "b", "bucket-time", true, "Bucket time in seconds. 300 s by default.");
options.addOption( "t", "thread-count", true, "Number of threads. 5 by default.");
options.addOption( "p", "pause", true, "Pause in ms between each created log. 5ms by default.");
options.addOption( "n", "numlogs", true, "Number of logs to send.");
try {
CommandLine line = parser.parse(options, args);
sink = line.getOptionValue("sink", "kafka").toUpperCase();
if (line.getOptionValue("sources").isEmpty()) {
sourceIds = new UUID[] {UUIDs.timeBased()};
} else {
String[] strSourceIds = line.getOptionValue("sources").split(",");
sourceIds = new UUID[strSourceIds.length];
for (int i = 0; i < strSourceIds.length; i++) {
sourceIds[i] = UUID.fromString(strSourceIds[i]);
}
}
logTypes = line.getOptionValue("log-types", "view_category,view_product,search,buy_product,like_product").split(",");
bucketTimeInSeconds = Integer.parseInt(line.getOptionValue("bucket-time", "300"));
threadCount = Integer.parseInt(line.getOptionValue("thread-count", "5"));
pauseTime = Integer.parseInt(line.getOptionValue("pause", "5"));
logsTosend = Integer.parseInt(line.getOptionValue("numlogs", "-1"));
}
catch( ParseException e ) {
System.out.println( "Unexpected exception:" + e.getMessage() );
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Log source simulator", options, true);
System.exit(1);
}
// Create simulator
final LogSourceSimulator sim = new LogSourceSimulator(SinkType.valueOf(sink), sourceIds, logTypes, bucketTimeInSeconds, threadCount, pauseTime, logsTosend);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
sim.stop();
}
});
sim.start();
}
private final UUID[] sourceIds;
private final String[] logsTypes;
private final int threadCount;
private final int sleepMs;
private int logCount;
private int bucketTimeInSeconds;
private LogSinkFactory.SinkType sinkType;
private LogSink sink;
private ExecutorService executorService;
private int logsToSend;
public LogSourceSimulator(SinkType sinkType, UUID[] sourceIds, String[] logTypes, int bucketTimeInSeconds, int threadCount, int sleepMs, int logsToSend) {
this.sinkType = sinkType;
this.sourceIds = sourceIds;
this.logsTypes = logTypes;
this.bucketTimeInSeconds = bucketTimeInSeconds;
this.threadCount = threadCount;
this.sleepMs = sleepMs;
this.logCount = 0;
this.logsToSend = logsToSend;
}
public void start() {
executorService = Executors.newFixedThreadPool(threadCount);
sink = LogSinkFactory.getInstance(sinkType);
System.out.println("[Log simulator started]");
run();
}
private void run() {
while (true) {
if (executorService.isShutdown() || (logCount >= logsToSend && logsToSend != -1)) {
break;
}
createLog();
logCount ++;
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
stop();
}
}
System.exit(0);
}
public void stop() {
executorService.shutdown();
while (!executorService.isTerminated()) {
System.out.println("Waiting for termination");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sink.shutdown();
System.out.println("[Log simulator stopped]");
System.out.println(String.format("%d logs sent", logCount));
}
private void createLog() {
executorService.execute(new Runnable() {
public void run() {
Log log = LogBuilder.buildLog(Random.getFromUUIDArray(sourceIds), new Date(), Random.getFromStringArray(logsTypes), Random.getAsciiString(1000), bucketTimeInSeconds);
sink.push(log);
System.out.print(".");
}
});
}
}
|
package de.scads.gradoop_service.server.helper.constructor;
import java.util.List;
import java.util.Map;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
import org.gradoop.flink.util.GradoopFlinkConfig;
import org.uni_leipzig.biggr.builder.GradoopOperatorConstructor;
import org.uni_leipzig.biggr.builder.InvalidSettingsException;
import de.scads.gradoop_service.server.helper.clustering.ClusteringHelper;
public class ClusteringConstructor implements GradoopOperatorConstructor{
public static final String CLUSTERING_CONFIG = "clusteringConfig";
/**
* {@inheritDoc}
*/
@Override
public Object construct(final GradoopFlinkConfig gfc, final Map<String, Object> arguments, final List<Object> dependencies) throws InvalidSettingsException {
LogicalGraph graph = (LogicalGraph)dependencies.get(0);
String clusteringConfig = (String)arguments.get(CLUSTERING_CONFIG);
LogicalGraph resultGraph = null;
try {
resultGraph = ClusteringHelper.runClustering(graph, clusteringConfig);
} catch (Exception e) {
e.printStackTrace();
}
return resultGraph;
}
}
|
package online.lahloba.www.lahloba.data.model;
public class SubMenuItem {
String id;
String parentId;
String image;
String title;
boolean hasChild;
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public boolean isHasChild() {
return hasChild;
}
public void setId(String id) {
this.id = id;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public void setImage(String image) {
this.image = image;
}
public void setTitle(String title) {
this.title = title;
}
public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}
}
|
package com.calc.server;
import com.calc.antlr.service.AntlrCalculator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@Controller
public class CalcController {
AntlrCalculator antlrCalculator = new AntlrCalculator();
@GetMapping("/calc")
public @ResponseBody
BigDecimal calculate(@RequestParam String expr) {
return antlrCalculator.evaluate(expr);
}
@PostMapping("/calc")
public @ResponseBody
BigDecimal jsonCalculate(@RequestBody String expr) {
return antlrCalculator.evaluate(expr);
}
}
|
package org.lsmr.usecases;
import java.math.BigDecimal;
import org.lsmr.selfcheckout.Barcode;
import org.lsmr.selfcheckout.devices.AbstractDevice;
import org.lsmr.selfcheckout.devices.BarcodeScanner;
import org.lsmr.selfcheckout.devices.listeners.AbstractDeviceListener;
import org.lsmr.selfcheckout.devices.listeners.BarcodeScannerListener;
import org.lsmr.selfcheckout.external.ProductDatabases;
import org.lsmr.selfcheckout.products.BarcodedProduct;
public class ScanItem extends UseCases {
private BigDecimal itemPrice;
private BarcodedProduct barcodedProduct;
private BarcodeScannerListener listener;
public ScanItem() {
listener = new BarcodeScannerListener() {
@Override
public void enabled(AbstractDevice<? extends AbstractDeviceListener> device) {
// TODO Auto-generated method stub
}
@Override
public void disabled(AbstractDevice<? extends AbstractDeviceListener> device) {
// TODO Auto-generated method stub
}
// This event occurs when an item is scanned. It retrieves the barcoded product and the price of the product, then updates the cart.
@Override
public void barcodeScanned(BarcodeScanner barcodeScanner, Barcode barcode) {
// Checking if the barcode corresponds to a BarcodedProduct in the database.
if (ProductDatabases.BARCODED_PRODUCT_DATABASE.containsKey(barcode)) {
barcodedProduct = ProductDatabases.BARCODED_PRODUCT_DATABASE.get(barcode);
itemPrice = barcodedProduct.getPrice();
// Updating cart.
addToCart(barcodedProduct);
updateCartTotal(itemPrice);
updateAmountOwed(itemPrice);
updateNumberOfItems(1);
// Disabling scanners. They will be enabled when the item has been bagged.
station.mainScanner.disable();
station.handheldScanner.disable();
}
}
};
station.mainScanner.register(listener);
station.handheldScanner.register(listener);
}
}
|
package com.xh.util;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.xh.reflect.ClassManager;
import com.xh.reflect.FieldManager;
import android.database.Cursor;
import android.os.Bundle;
/**
* @version 创建时间:2017-12-26 下午12:59:37 项目:repair 包名:com.xh.util
* 文件名:Cursor2Object.java 作者:lhl 说明:
*/
public class Cursor2Object {
public static List<Object> cursor2Object(Cursor cursor, Class cl) {
List<Object> objects = new ArrayList<>();
try {
Field[] fields = FieldManager.fields(cl);
if (fields == null || fields.length == 0)
return objects;
while (cursor.moveToNext()) {
Object object = ClassManager.new_object(cl);
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (ClassManager
.is_integer(FieldManager.field_class(field))) {
int value = cursor.getInt(cursor
.getColumnIndex(FieldManager.name(field)));
FieldManager.set_field(object, field, value);
} else if (ClassManager.is_float(FieldManager
.field_class(field))) {
float value = cursor.getFloat(cursor
.getColumnIndex(FieldManager.name(field)));
FieldManager.set_field(object, field, value);
} else {
FieldManager.set_field(object, field, cursor
.getString(cursor.getColumnIndex(FieldManager
.name(field))));
}
}
objects.add(object);
}
cursor.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return objects;
}
}
|
package nxpense.domain;
import javax.persistence.*;
import java.util.Arrays;
@Embeddable
public class Attachment {
private String filename;
@Lob
@Column(name = "CONTENT")
@Basic(fetch = FetchType.LAZY)
private byte[] byteContent;
private Integer size;
public Attachment() {
}
public Attachment(String filename, byte[] byteContent) {
this.filename = filename;
this.byteContent = byteContent;
this.size = byteContent.length;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public byte[] getByteContent() {
return byteContent;
}
public Integer getSize() {
return size;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Attachment that = (Attachment) o;
if (!filename.equals(that.filename)) {
return false;
}
if (!Arrays.equals(byteContent, that.byteContent)) {
return false;
}
return !(size != null ? !size.equals(that.size) : that.size != null);
}
@Override
public int hashCode() {
int result = filename.hashCode();
result = 31 * result + (byteContent != null ? Arrays.hashCode(byteContent) : 0);
result = 31 * result + (size != null ? size.hashCode() : 0);
return result;
}
}
|
package com.mibo.modules.data.model;
import com.mibo.common.constant.ConstUtils;
import com.mibo.modules.data.base.BaseUser;
import java.util.Date;
@SuppressWarnings("serial")
public class User extends BaseUser<User> {
/* 12 */ public static final User dao = (User) new User().dao();
public User queryUserByPhone(String phone) {
/* 20 */ return (User) findFirst(getSql("user.queryUserByPhone"), new Object[] { phone });
}
public User register(String phone, String password, Date regDate) {
/* 31 */ User user = new User();
/* 32 */ user.setPhone(phone);
/* 33 */ user.setPassword(password);
/* 34 */ user.setRegisterTime(regDate);
/* 35 */ user.setAccountStatus(ConstUtils.ACCOUNT_STATUS.NORMAL.getValue());
/* 36 */ user.save();
/* 37 */ return user;
}
public User queryUserByGgatewayId(Integer gatewayId) {
/* 46 */ String sql = "SELECT b.* FROM t_user_gateway a LEFT JOIN t_user b ON a.user_id = b.id WHERE a.gateway_id = ? ORDER BY register_time DESC LIMIT 1";
/* 48 */ return (User) findFirst(sql, new Object[] { gatewayId });
}
} |
package references.socialnetwork;
import java.util.ArrayList;
import java.util.List;
public class SocialNetwork {
private List<Member> members = new ArrayList<>();
public void addMember(String name) {
members.add(new Member(name));
}
public void connect(String name, String otherName) {
Member member1 = null;
Member member2 = null;
for (Member item : members) {
if (item.getName().equals(name)) {
member1 = item;
}
if (item.getName().equals(otherName)) {
member2 = item;
}
if (member1 != null && member2 != null) {
member1.connectMember(member2);
return;
}
}
}
public Member findByName(String name) {
for (Member item : members) {
if (item.getName().equals(name)) {
return item;
}
}
return null;
}
public List<String> bidirectionalConnections() {
List<String> connections = new ArrayList<>();
for (Member item1 : members) {
for (Member item2 : item1.getConnections()) {
if (item2.getConnections().contains(item1)) {
connections.add(item1.getName() + " -> " + item2.getName());
}
}
}
return connections;
}
@Override
public String toString() {
return "SocialNetwork{" +
"members=" + members.toString() +
'}';
}
}
|
package f.star.iota.milk.ui.gamersky.gamer;
import android.os.Bundle;
import f.star.iota.milk.base.ScrollImageFragment;
public class GamerSkyFragment extends ScrollImageFragment<GamerSkyPresenter, GamerSkyAdapter> {
public static GamerSkyFragment newInstance(String url) {
GamerSkyFragment fragment = new GamerSkyFragment();
Bundle bundle = new Bundle();
bundle.putString("base_url", url);
bundle.putString("page_suffix", "}");
fragment.setArguments(bundle);
return fragment;
}
@Override
protected GamerSkyPresenter getPresenter() {
return new GamerSkyPresenter(this);
}
@Override
protected GamerSkyAdapter getAdapter() {
return new GamerSkyAdapter();
}
}
|
package dev.mher.taskhunter.models.misc.authentication;
import dev.mher.taskhunter.models.misc.Response;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
/**
* User: MheR
* Date: 12/4/19.
* Time: 5:48 PM.
* Project: taskhunter.
* Package: dev.mher.taskhunter.models.responses.
*/
@Getter
@Setter
public class SignInResponse extends Response {
private HashMap<String, String> user;
private CharSequence accessToken;
public SignInResponse() {
}
public SignInResponse(HashMap<String, String> user, CharSequence accessToken) {
this.setError(false);
this.setUser(user);
this.setAccessToken(accessToken);
}
}
|
package com.example.pokeapppro.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.pokeapppro.R;
import com.example.pokeapppro.viewmodel.PokemonViewModel;
import com.squareup.picasso.Picasso;
public class PokemonDetailFragment extends Fragment {
private ImageView imageViewPokemon;
private TextView textViewDetailName;
private TextView textViewDetail;
private PokemonViewModel detailViewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
detailViewModel = new ViewModelProvider(this).get(PokemonViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
imageViewPokemon = view.findViewById(R.id.imageViewPokemon);
textViewDetailName = view.findViewById(R.id.textViewDetailName);
textViewDetail = view.findViewById(R.id.textViewDetail);
textViewDetailName.setText(PokemonDetailFragmentArgs.fromBundle(getArguments()).getPokemonName());
Picasso.get().load(PokemonDetailFragmentArgs.fromBundle(getArguments()).getPokemonImageURL()).into(imageViewPokemon);
String pokemonId = PokemonDetailFragmentArgs.fromBundle(getArguments()).getPokemonId();
detailViewModel.getPokemonTypeListServer(pokemonId);
detailViewModel.getTypeList().observe(this.getViewLifecycleOwner(), pokemonTypeDetails -> {
String pokemonTypeList = pokemonTypeDetails.get(0).getType().getTypeName();
String pokemonTypes = "";
textViewDetail.setText(pokemonTypeList);
});
}
}
|
package com.edasaki.rpg.help;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.edasaki.core.menus.MenuItem;
public class ListedCommand implements Comparable<ListedCommand> {
public String name, strippedName, desc;
public String[] fullLore;
@Override
public int compareTo(ListedCommand o) {
return this.strippedName.compareTo(o.strippedName);
}
@Override
public String toString() {
return this.strippedName;
}
protected MenuItem generate(int row, int col) {
MenuItem mi = new MenuItem(row, col, new ItemStack(Material.PAPER), name, fullLore, null);
return mi;
}
}
|
package vazkii.morphtool;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.Phase;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import vazkii.arl.util.ClientTicker;
import vazkii.morphtool.network.MessageMorphTool;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@OnlyIn(Dist.CLIENT)
public class ClientHandler {
public static final ClientHandler INSTANCE = new ClientHandler();
protected static boolean autoMode = true;
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onTick(ClientTickEvent event) {
PlayerEntity player = Minecraft.getInstance().player;
if(player != null && event.phase == Phase.END && autoMode) {
ItemStack mainHandItem = player.getHeldItem(ConfigHandler.invertHandShift.get() ? Hand.OFF_HAND : Hand.MAIN_HAND);
if (MorphingHandler.isMorphTool(mainHandItem)) {
ItemStack newStack = mainHandItem;
RayTraceResult res = MorphingHandler.raycast(player, 4.5);
//Get looked at Mod
if (res != null && res.getType() == RayTraceResult.Type.BLOCK) {
BlockState state = player.world.getBlockState(((BlockRayTraceResult) res).getPos());
String modlook = MorphingHandler.getModFromState(state);
//Morph tool to looked at Mod
newStack = MorphingHandler.getShiftStackForMod(mainHandItem, modlook);
}
if (newStack != mainHandItem && !ItemStack.areItemsEqual(newStack, mainHandItem)) {
player.inventory.setInventorySlotContents(ConfigHandler.invertHandShift.get() ? player.inventory.getSizeInventory() - 1 : player.inventory.currentItem, newStack);
MorphTool.NETWORKHANDLER.sendToServer(new MessageMorphTool(newStack, player.inventory.currentItem));
MorphTool.proxy.updateEquippedItem();
}
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onMouseEvent(InputEvent.MouseScrollEvent event) {
PlayerEntity player = Minecraft.getInstance().player;
if(player != null) {
ItemStack mainHandItem = player.getHeldItem(ConfigHandler.invertHandShift.get() ? Hand.OFF_HAND : Hand.MAIN_HAND);
if (MorphingHandler.isMorphTool(mainHandItem)) {
ItemStack newStack = mainHandItem;
String mod = MorphingHandler.getModFromStack(mainHandItem);
RayTraceResult res = MorphingHandler.raycast(player, 4.5);
String modlook = "";
//Get looked at Mod
if (res != null && res.getType() == RayTraceResult.Type.BLOCK) {
BlockState state = player.world.getBlockState(((BlockRayTraceResult) res).getPos());
modlook = MorphingHandler.getModFromState(state);
}
//Manual Scroll for Morph (excluding looked at a mod block incase it also needs scrolling)
if (event.getScrollDelta() != 0 && player.isCrouching() && !modlook.equals(mod)) {
if (mainHandItem.getTag() != null) {
CompoundNBT morphData = mainHandItem.getTag().getCompound(MorphingHandler.TAG_MORPH_TOOL_DATA);
mod = event.getScrollDelta() < 0 ? nextMod(morphData, mod) : previousMod(morphData, mod);
newStack = MorphingHandler.getShiftStackForMod(mainHandItem, mod);
autoMode = mod.equals("morphtool");
event.setCanceled(true);
}
}
if (newStack != mainHandItem && !ItemStack.areItemsEqual(newStack, mainHandItem)) {
player.inventory.setInventorySlotContents(ConfigHandler.invertHandShift.get() ? player.inventory.getSizeInventory() - 1 : player.inventory.currentItem, newStack);
MorphTool.NETWORKHANDLER.sendToServer(new MessageMorphTool(newStack, player.inventory.currentItem));
MorphTool.proxy.updateEquippedItem();
}
}
}
}
public static String nextMod(CompoundNBT morphData, String mod) {
List<String> mods = new ArrayList<>(morphData.keySet());
mods.add("morphtool");
if (!mod.equals("morphtool")){
mods.add(mod);
}
Collections.sort(mods);
int id = mods.indexOf(mod);
int retid = 0;
//Move up the Array
if(mods.size() > (id + 1)){
retid = id + 1;
}
return mods.get(retid);
}
public static String previousMod(CompoundNBT morphData, String mod) {
List<String> mods = new ArrayList<>(morphData.keySet());
mods.add("morphtool");
if (!mod.equals("morphtool")){
mods.add(mod);
}
Collections.sort(mods);
int id = mods.indexOf(mod);
int retid = mods.size() - 1;
//Move down the Array
if(0 <= (id - 1)){
retid = (id - 1);
}
return mods.get(retid);
}
}
|
package com.github.grimpy.gotifier;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneEventMngr extends Service{
private static String TAG = "Gotifier";
public boolean register(){
TelephonyManager phnMngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneListener lst = new PhoneListener(this);
phnMngr.listen(lst, PhoneStateListener.LISTEN_CALL_STATE);
return true;
}
@Override
public void onCreate() {
Log.i(TAG, "Service got created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
register();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
|
package net.bdsc.eth.common;
import com.fasterxml.jackson.annotation.JsonView;
import net.bdsc.entity.BaseEntity;
/**
* 消息
*
* @author IGOMALL Team
* @version 1.0
*/
public class Result {
@JsonView({BaseEntity.ViewView.class, BaseEntity.ListView.class, BaseEntity.EditView.class, BaseEntity.BaseView.class})
private Integer code;
private Integer type;
private String content;
@JsonView({BaseEntity.ViewView.class, BaseEntity.ListView.class, BaseEntity.EditView.class, BaseEntity.BaseView.class})
private String message;
@JsonView({BaseEntity.ViewView.class, BaseEntity.ListView.class, BaseEntity.EditView.class, BaseEntity.BaseView.class})
private Object data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
/**
* 构造方法
*/
public Result() {
}
public Result(Integer type,Integer code, String message,String content, Object data) {
this.code = code;
this.type = type;
this.message = message;
this.content = content;
this.data = data;
}
public static Result success(String message, Object data) {
return new Result(200,0, message,message, data);
}
public static Result success(Object data) {
return new Result(200,0, "请求成功","请求成功", data);
}
public static Result error(String message) {
return new Result(400,-1, message,message, null);
}
} |
package model;
/**
* Created by SAJJAD on 4/7/2017.
*/
public class RegisterResponseData {
public RegisterResponseUser user;
}
|
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class TelaUsuario extends JPanel{
// public class TelaUsuario extends JScrollPane{
// private Container container;
private JPanel telaUsuario;
// private JLabel lblTeste;
// private JLabel lblTeste2;
// private JLabel lblId = new JLabel("ID");
// private JLabel lblNome = new JLabel("Nome");
// private JLabel lblLocal = new JLabel("Local");
// private JTextField txtId;
// private JTextField txtNome;
// private JTextField txtLocal;
public TelaUsuario (){
telaUsuario = this;
telaUsuario.setLayout(new BoxLayout(telaUsuario, BoxLayout.Y_AXIS));
CriarTela();
}
private void CriarTela(){
ConstruirLayout();
}
private void ConstruirLayout(){
telaUsuario.setSize(500, 500);
// Criação da Estrutura do Título
JLabel lblTitulo = new JLabel("Lista IoTs");
lblTitulo.setBorder(new LineBorder(Color.RED));
lblTitulo.setPreferredSize(new Dimension(500, 50));
lblTitulo.setHorizontalAlignment(SwingConstants.CENTER);
lblTitulo.setVerticalAlignment(SwingConstants.CENTER);
lblTitulo.setFont(lblTitulo.getFont().deriveFont(20f));
Box boxTitulo = Box.createHorizontalBox();
boxTitulo.setBorder(new LineBorder(Color.ORANGE));
boxTitulo.add(Box.createHorizontalGlue());
boxTitulo.add(Box.createVerticalStrut(50));
boxTitulo.add(lblTitulo);
boxTitulo.add(Box.createHorizontalGlue());
// Criação da Estrutura do Cabeçalho da Tabela
JLabel lblCabecalho01 = new JLabel("Cabeçalho01");
lblCabecalho01.setBorder(new LineBorder(Color.YELLOW));
lblCabecalho01.setPreferredSize(new Dimension(75, 50));
lblCabecalho01.setHorizontalAlignment(SwingConstants.CENTER);
JLabel lblCabecalho02 = new JLabel("Cabeçalho02");
lblCabecalho02.setBorder(new LineBorder(Color.GREEN));
lblCabecalho02.setPreferredSize(new Dimension(150, 50));
lblCabecalho02.setHorizontalAlignment(SwingConstants.CENTER);
lblCabecalho02.setBackground(Color.MAGENTA);
lblCabecalho02.setForeground(Color.BLUE);
JButton btnCabecalhoBotao = new JButton("CabeçalhoBotão");
btnCabecalhoBotao.setBorder(new LineBorder(Color.BLUE));
btnCabecalhoBotao.setPreferredSize(new Dimension(150, 150));
// Box boxCabecalho = Box.createHorizontalBox();
// boxCabecalho.setBorder(new LineBorder(Color.MAGENTA));
// boxCabecalho.add(lblCabecalho01);
// boxCabecalho.add(lblCabecalho02);
// boxCabecalho.add(btnCabecalhoBotao);
// boxCabecalho.add(Box.createHorizontalGlue());
// boxCabecalho.add(Box.createVerticalStrut(100));
JPanel boxCabecalho = new JPanel();
boxCabecalho.setBorder(new LineBorder(Color.MAGENTA));
boxCabecalho.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
boxCabecalho.setPreferredSize(new Dimension(500, 100));
boxCabecalho.add(Box.createRigidArea(new Dimension(10,0)));
boxCabecalho.add(lblCabecalho01);
boxCabecalho.add(Box.createRigidArea(new Dimension(10,0)));
boxCabecalho.add(lblCabecalho02);
boxCabecalho.add(Box.createRigidArea(new Dimension(10,0)));
boxCabecalho.add(btnCabecalhoBotao);
// Criação da Estrutura da Tabela
JLabel lblTeste4 = new JLabel("Usuário");
lblTeste4.setBorder(new LineBorder(Color.YELLOW));
lblTeste4.setPreferredSize(new Dimension(50, 150));
JLabel lblTeste5 = new JLabel("Usuário2");
lblTeste5.setBorder(new LineBorder(Color.GREEN));
lblTeste5.setPreferredSize(new Dimension(75, 75));
JButton btnTeste6 = new JButton("Botão");
btnTeste6.setBorder(new LineBorder(Color.BLUE));
btnTeste6.setPreferredSize(new Dimension(150, 50));
// Box boxTabela = Box.createHorizontalBox();
// boxTabela.setBorder(new LineBorder(Color.BLACK));
// boxTabela.setLayout(new BoxLayout(boxTabela, BoxLayout.X_AXIS));
// boxTabela.add(lblTeste4);
// boxTabela.add(lblTeste5);
// boxTabela.add(btnTeste6);
// boxTabela.add(Box.createHorizontalGlue());
// boxTabela.add(Box.createVerticalStrut(30));
JPanel boxTabela = new JPanel();
boxTabela.setBorder(new LineBorder(Color.BLACK));
boxTabela.setLayout(new FlowLayout());
// boxTabela.setLayout(new BoxLayout(boxTabela, BoxLayout.X_AXIS));
boxTabela.setPreferredSize(new Dimension(500, 200));
boxTabela.setAlignmentX(SwingConstants.LEFT);
boxTabela.add(lblTeste4);
boxTabela.add(lblTeste5);
boxTabela.add(btnTeste6);
telaUsuario.add(boxTitulo);
telaUsuario.add(boxCabecalho);
telaUsuario.add(boxTabela);
telaUsuario.setVisible(true);
}
public JComponent getTelaUsuario(){
return telaUsuario;
}
}
|
package com.nisira.core.dao;
import com.nisira.core.entity.*;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import com.nisira.core.database.DataBaseClass;
import android.content.ContentValues;
import android.database.Cursor;
import com.nisira.core.util.ClaveMovil;
import java.util.ArrayList;
import java.util.LinkedList;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MotivosproduccionDao extends BaseDao<Motivosproduccion> {
public MotivosproduccionDao() {
super(Motivosproduccion.class);
}
public MotivosproduccionDao(boolean usaCnBase) throws Exception {
super(Motivosproduccion.class, usaCnBase);
}
public Boolean insert(Motivosproduccion motivosproduccion) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",motivosproduccion.getIdempresa());
initialValues.put("IDMOTIVO",motivosproduccion.getIdmotivo());
initialValues.put("DESCRIPCION",motivosproduccion.getDescripcion());
initialValues.put("NOMBRE_CORTO",motivosproduccion.getNombre_corto());
initialValues.put("EXIGE_OCC",motivosproduccion.getExige_occ());
initialValues.put("INSUMOS_OCC",motivosproduccion.getInsumos_occ());
initialValues.put("GENERA_INGRESO",motivosproduccion.getGenera_ingreso());
initialValues.put("ESTADO",motivosproduccion.getEstado());
initialValues.put("SINCRONIZA",motivosproduccion.getSincroniza());
initialValues.put("FECHACREACION",dateFormat.format(motivosproduccion.getFechacreacion() ) );
initialValues.put("IDMOTSALIDA",motivosproduccion.getIdmotsalida());
initialValues.put("IPIDECOTIZACION",motivosproduccion.getIpidecotizacion());
initialValues.put("IPIDESOLICITUD",motivosproduccion.getIpidesolicitud());
initialValues.put("ES_PREVENTIVO",motivosproduccion.getEs_preventivo());
initialValues.put("EXIGE_REQI",motivosproduccion.getExige_reqi());
initialValues.put("NO_EXIGE_EQP",motivosproduccion.getNo_exige_eqp());
initialValues.put("NO_EXIGE_OPM",motivosproduccion.getNo_exige_opm());
initialValues.put("IDDOCUMENTO_S",motivosproduccion.getIddocumento_s());
initialValues.put("IDMOTIVO_S",motivosproduccion.getIdmotivo_s());
initialValues.put("IDSUCURSAL_S",motivosproduccion.getIdsucursal_s());
initialValues.put("IDALMACEN_S",motivosproduccion.getIdalmacen_s());
initialValues.put("IDDOCUMENTO_I",motivosproduccion.getIddocumento_i());
initialValues.put("IDMOTIVO_I",motivosproduccion.getIdmotivo_i());
initialValues.put("IDSUCURSAL_I",motivosproduccion.getIdsucursal_i());
initialValues.put("IDALMACEN_I",motivosproduccion.getIdalmacen_i());
initialValues.put("ALMACEN_AUTO",motivosproduccion.getAlmacen_auto());
initialValues.put("SERIE_I",motivosproduccion.getSerie_i());
initialValues.put("SERIE_S",motivosproduccion.getSerie_s());
initialValues.put("SUCURSAL_CC",motivosproduccion.getSucursal_cc());
initialValues.put("IDCONSUMIDOR",motivosproduccion.getIdconsumidor());
initialValues.put("IDDOCUMENTO_OP",motivosproduccion.getIddocumento_op());
initialValues.put("DIAS",motivosproduccion.getDias());
initialValues.put("IDDOCUMENTO",motivosproduccion.getIddocumento());
initialValues.put("SERIE",motivosproduccion.getSerie());
initialValues.put("ES_PREDICTIVO",motivosproduccion.getEs_predictivo());
initialValues.put("IDMOTIVOREQINTERNO",motivosproduccion.getIdmotivoreqinterno());
initialValues.put("ES_COTIZACION",motivosproduccion.getEs_cotizacion());
initialValues.put("ES_REQUERIMIENTO",motivosproduccion.getEs_requerimiento());
initialValues.put("ES_INGPERSONAL",motivosproduccion.getEs_ingpersonal());
resultado = mDb.insert("MOTIVOSPRODUCCION",null,initialValues)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public Boolean update(Motivosproduccion motivosproduccion,String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",motivosproduccion.getIdempresa()) ;
initialValues.put("IDMOTIVO",motivosproduccion.getIdmotivo()) ;
initialValues.put("DESCRIPCION",motivosproduccion.getDescripcion()) ;
initialValues.put("NOMBRE_CORTO",motivosproduccion.getNombre_corto()) ;
initialValues.put("EXIGE_OCC",motivosproduccion.getExige_occ()) ;
initialValues.put("INSUMOS_OCC",motivosproduccion.getInsumos_occ()) ;
initialValues.put("GENERA_INGRESO",motivosproduccion.getGenera_ingreso()) ;
initialValues.put("ESTADO",motivosproduccion.getEstado()) ;
initialValues.put("SINCRONIZA",motivosproduccion.getSincroniza()) ;
initialValues.put("FECHACREACION",dateFormat.format(motivosproduccion.getFechacreacion() ) ) ;
initialValues.put("IDMOTSALIDA",motivosproduccion.getIdmotsalida()) ;
initialValues.put("IPIDECOTIZACION",motivosproduccion.getIpidecotizacion()) ;
initialValues.put("IPIDESOLICITUD",motivosproduccion.getIpidesolicitud()) ;
initialValues.put("ES_PREVENTIVO",motivosproduccion.getEs_preventivo()) ;
initialValues.put("EXIGE_REQI",motivosproduccion.getExige_reqi()) ;
initialValues.put("NO_EXIGE_EQP",motivosproduccion.getNo_exige_eqp()) ;
initialValues.put("NO_EXIGE_OPM",motivosproduccion.getNo_exige_opm()) ;
initialValues.put("IDDOCUMENTO_S",motivosproduccion.getIddocumento_s()) ;
initialValues.put("IDMOTIVO_S",motivosproduccion.getIdmotivo_s()) ;
initialValues.put("IDSUCURSAL_S",motivosproduccion.getIdsucursal_s()) ;
initialValues.put("IDALMACEN_S",motivosproduccion.getIdalmacen_s()) ;
initialValues.put("IDDOCUMENTO_I",motivosproduccion.getIddocumento_i()) ;
initialValues.put("IDMOTIVO_I",motivosproduccion.getIdmotivo_i()) ;
initialValues.put("IDSUCURSAL_I",motivosproduccion.getIdsucursal_i()) ;
initialValues.put("IDALMACEN_I",motivosproduccion.getIdalmacen_i()) ;
initialValues.put("ALMACEN_AUTO",motivosproduccion.getAlmacen_auto()) ;
initialValues.put("SERIE_I",motivosproduccion.getSerie_i()) ;
initialValues.put("SERIE_S",motivosproduccion.getSerie_s()) ;
initialValues.put("SUCURSAL_CC",motivosproduccion.getSucursal_cc()) ;
initialValues.put("IDCONSUMIDOR",motivosproduccion.getIdconsumidor()) ;
initialValues.put("IDDOCUMENTO_OP",motivosproduccion.getIddocumento_op()) ;
initialValues.put("DIAS",motivosproduccion.getDias()) ;
initialValues.put("IDDOCUMENTO",motivosproduccion.getIddocumento()) ;
initialValues.put("SERIE",motivosproduccion.getSerie()) ;
initialValues.put("ES_PREDICTIVO",motivosproduccion.getEs_predictivo()) ;
initialValues.put("IDMOTIVOREQINTERNO",motivosproduccion.getIdmotivoreqinterno()) ;
initialValues.put("ES_COTIZACION",motivosproduccion.getEs_cotizacion()) ;
initialValues.put("ES_REQUERIMIENTO",motivosproduccion.getEs_requerimiento()) ;
initialValues.put("ES_INGPERSONAL",motivosproduccion.getEs_ingpersonal()) ;
resultado = mDb.update("MOTIVOSPRODUCCION",initialValues,where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Boolean delete(String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
resultado = mDb.delete("MOTIVOSPRODUCCION",where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public ArrayList<Motivosproduccion> listar(String where,String order,Integer limit) {
if(limit == null){
limit =0;
}
ArrayList<Motivosproduccion> lista = new ArrayList<Motivosproduccion>();
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
Cursor cur = mDb.query("MOTIVOSPRODUCCION",
new String[] {
"IDEMPRESA" ,
"IDMOTIVO" ,
"DESCRIPCION" ,
"NOMBRE_CORTO" ,
"EXIGE_OCC" ,
"INSUMOS_OCC" ,
"GENERA_INGRESO" ,
"ESTADO" ,
"SINCRONIZA" ,
"FECHACREACION" ,
"IDMOTSALIDA" ,
"IPIDECOTIZACION" ,
"IPIDESOLICITUD" ,
"ES_PREVENTIVO" ,
"EXIGE_REQI" ,
"NO_EXIGE_EQP" ,
"NO_EXIGE_OPM" ,
"IDDOCUMENTO_S" ,
"IDMOTIVO_S" ,
"IDSUCURSAL_S" ,
"IDALMACEN_S" ,
"IDDOCUMENTO_I" ,
"IDMOTIVO_I" ,
"IDSUCURSAL_I" ,
"IDALMACEN_I" ,
"ALMACEN_AUTO" ,
"SERIE_I" ,
"SERIE_S" ,
"SUCURSAL_CC" ,
"IDCONSUMIDOR" ,
"IDDOCUMENTO_OP" ,
"DIAS" ,
"IDDOCUMENTO" ,
"SERIE" ,
"ES_PREDICTIVO" ,
"IDMOTIVOREQINTERNO" ,
"ES_COTIZACION" ,
"ES_REQUERIMIENTO" ,
"ES_INGPERSONAL"
},
where, null, null, null, order);
if (cur!=null){
cur.moveToFirst();
int i=0;
while (cur.isAfterLast() == false) {
int j=0;
Motivosproduccion motivosproduccion = new Motivosproduccion() ;
motivosproduccion.setIdempresa(cur.getString(j++));
motivosproduccion.setIdmotivo(cur.getString(j++));
motivosproduccion.setDescripcion(cur.getString(j++));
motivosproduccion.setNombre_corto(cur.getString(j++));
motivosproduccion.setExige_occ(cur.getDouble(j++));
motivosproduccion.setInsumos_occ(cur.getDouble(j++));
motivosproduccion.setGenera_ingreso(cur.getDouble(j++));
motivosproduccion.setEstado(cur.getDouble(j++));
motivosproduccion.setSincroniza(cur.getString(j++));
motivosproduccion.setFechacreacion(dateFormat.parse(cur.getString(j++)) );
motivosproduccion.setIdmotsalida(cur.getString(j++));
motivosproduccion.setIpidecotizacion(cur.getInt(j++));
motivosproduccion.setIpidesolicitud(cur.getInt(j++));
motivosproduccion.setEs_preventivo(cur.getDouble(j++));
motivosproduccion.setExige_reqi(cur.getDouble(j++));
motivosproduccion.setNo_exige_eqp(cur.getDouble(j++));
motivosproduccion.setNo_exige_opm(cur.getDouble(j++));
motivosproduccion.setIddocumento_s(cur.getString(j++));
motivosproduccion.setIdmotivo_s(cur.getString(j++));
motivosproduccion.setIdsucursal_s(cur.getString(j++));
motivosproduccion.setIdalmacen_s(cur.getString(j++));
motivosproduccion.setIddocumento_i(cur.getString(j++));
motivosproduccion.setIdmotivo_i(cur.getString(j++));
motivosproduccion.setIdsucursal_i(cur.getString(j++));
motivosproduccion.setIdalmacen_i(cur.getString(j++));
motivosproduccion.setAlmacen_auto(cur.getDouble(j++));
motivosproduccion.setSerie_i(cur.getString(j++));
motivosproduccion.setSerie_s(cur.getString(j++));
motivosproduccion.setSucursal_cc(cur.getDouble(j++));
motivosproduccion.setIdconsumidor(cur.getString(j++));
motivosproduccion.setIddocumento_op(cur.getString(j++));
motivosproduccion.setDias(cur.getInt(j++));
motivosproduccion.setIddocumento(cur.getString(j++));
motivosproduccion.setSerie(cur.getString(j++));
motivosproduccion.setEs_predictivo(cur.getDouble(j++));
motivosproduccion.setIdmotivoreqinterno(cur.getString(j++));
motivosproduccion.setEs_cotizacion(cur.getDouble(j++));
motivosproduccion.setEs_requerimiento(cur.getDouble(j++));
motivosproduccion.setEs_ingpersonal(cur.getDouble(j++));
lista.add(motivosproduccion);
i++;
if(i == limit){
break;
}
cur.moveToNext();
}
cur.close();
}
} catch (Exception e) {
}finally {
mDb.close();
}
return lista;
}
} |
package com.cpro.rxjavaretrofit.views.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cpro.rxjavaretrofit.R;
import com.cpro.rxjavaretrofit.constant.InterfaceUrl;
import com.cpro.rxjavaretrofit.entity.RoleTaskSupervisionFileListEntity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by lx on 2016/6/20.
*/
public class RoleTaskSupervisionDetailAnnexesAdapter extends RecyclerView.Adapter {
List<RoleTaskSupervisionFileListEntity> list;
public void setList(List<RoleTaskSupervisionFileListEntity> list) {
this.list = list;
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_common_detail_annexes, parent, false);
return new RoleTaskSupervisionDetailAnnexesViewHoleder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
RoleTaskSupervisionDetailAnnexesViewHoleder roleTaskSupervisionDetailAnnexesViewHoleder = (RoleTaskSupervisionDetailAnnexesViewHoleder) holder;
roleTaskSupervisionDetailAnnexesViewHoleder.tv_common_detail_annex_name.setText(list.get(position).getImageId().substring(list.get(position).getImageId().lastIndexOf("/") + 1, list.get(position).getImageId().length()));
roleTaskSupervisionDetailAnnexesViewHoleder.file_url = list.get(position).getImageId();
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
public static class RoleTaskSupervisionDetailAnnexesViewHoleder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_common_detail_annex_name)
TextView tv_common_detail_annex_name;
@BindView(R.id.tv_common_detail_download_label)
public TextView tv_common_detail_download_label;
public String file_url;
public RoleTaskSupervisionDetailAnnexesViewHoleder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
tv_common_detail_download_label.getBackground().setAlpha(100);
}
}
}
|
package models;
import io.ebean.annotation.WhenCreated;
import io.ebean.annotation.WhenModified;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.annotation.Nonnull;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.time.LocalDateTime;
/**
* 包含时间的模型
*/
@MappedSuperclass
@Data
@EqualsAndHashCode(callSuper = true)
public abstract class ModelWithTime extends Model {
protected ModelWithTime(@Nonnull String serverName) {
super(serverName);
}
/**
* 创建时间
*/
@WhenCreated
@Column(name = "FCreatedTime", columnDefinition = "DATETIME", nullable = false, updatable = false)
private LocalDateTime createdTime;
/**
* 修改时间
*/
@WhenModified
@Column(name = "FLastModTime", columnDefinition = "DATETIME", nullable = false)
private LocalDateTime lastModTime;
/**
* 乐观锁
*/
@Version
@Column(name = "FOptLock", columnDefinition = "INT UNSIGNED")
private Integer version;
}
|
package src;
import java.util.Hashtable;
public class ClipBoard {
private Hashtable<Integer,DoubleLinkedList> hash;
/**
* this is the construct of the ClipBoard and inicialize the hashtable
*/
public ClipBoard(){
this.hash=new Hashtable<>();
}
/**
* This function put in the hashTable the list at the n key
* @param n
* @param list
*/
public void copy(int n, DoubleLinkedList list){
hash.put(n,list);
}
/**
* This function get the list from the hastable at the n key
* @param n
* @return
*/
public DoubleLinkedList paste(int n){
return hash.get(n);
}
/**
* This function get the list from hashtable with the key n
* @param n
* @return
*/
public String show(int n){
return "ClibBoard["+n+"]==>{"+hash.get(n).toString()+"}";
}
}
|
package top.ysccx.myfirstapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.LinkedList;
public class RankingAdapter extends BaseAdapter {
private LinkedList<Ranking> mData;
private Context mContext;
public RankingAdapter(LinkedList<Ranking> mData, Context mContext) {
this.mData = mData;
this.mContext = mContext;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.ranking_item,null);
TextView uid = convertView.findViewById(R.id.uid);
TextView uname = convertView.findViewById(R.id.uname);
TextView utime = convertView.findViewById(R.id.utime);
TextView udate = convertView.findViewById(R.id.udate);
uid.setText(mData.get(position).getId());
uname.setText(mData.get(position).getName());
utime.setText(mData.get(position).getTime());
udate.setText(mData.get(position).getDate());
return convertView;
}
}
|
package com.operacloud.pages;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.aventstack.extentreports.ExtentTest;
import com.operacloud.selenium.actions.extensions.OperaCloudSeleniumActions;
public class OperaCloud_CreateReportsPage extends OperaCloudSeleniumActions {
public OperaCloud_CreateReportsPage(ChromeDriver driver, ExtentTest node) {
this.driver = driver;
this.node = node;
initPage();
// to do, verify title of the login page
}
@FindBy(xpath = "//label[text()='Customized Report']")
private WebElement clickCustomizedReport;
public OperaCloud_CreateReportsPage clickOnCustomizedReport() throws InterruptedException, IOException {
try{
Thread.sleep(5000);
//wait.until(ExpectedConditions.elementToBeClickable(clickCustomizedReport));
clickCustomizedReport.click();
Thread.sleep(5000);
reportStep("successfully clicked on customized report", "pass");
}
catch(Exception e)
{
reportStep("click on customized report unsuccessful", "fail");
}
return this;
}
@FindBy(xpath = "//label[text()='Display Name']")
private WebElement clickOnScreen;
public OperaCloud_CreateReportsPage clickAnywhereOnScreen() throws InterruptedException, IOException {
try {
clickElement(clickOnScreen);
Thread.sleep(5000);
reportStep("successfully clicked on screen", "pass");
}
catch(Exception e)
{
reportStep("click on screen unsuccessful", "fail");
}
return this;
}
@FindBy(xpath = "//input[contains(@id,'lov7:odec_lov_itLovetext')]")
private WebElement enterReportsName;
public OperaCloud_CreateReportsPage enterTheReportName(String customRep) throws InterruptedException, IOException {
try {
enterTextToWebElement(enterReportsName, customRep);
Thread.sleep(5000);
reportStep("successfully entered report name", "pass");
}
catch(Exception e)
{
reportStep("report name couldnt be entered", "fail");
}
return this;
}
@FindBy(xpath = "//span[contains(text(),'Download Sample Report')]")
private WebElement dwnldrprt;
public OperaCloud_CreateReportsPage clickDownloadReportAndRename(String fileName)
throws InterruptedException, IOException {
try {
clickElement(dwnldrprt);
Thread.sleep(5000);
Path downloadedFile = Paths.get("S:\\Cloud Workspace\\resources\\sample_alert.rtf");
Files.move(downloadedFile, downloadedFile.resolveSibling("alert.rtf"));
reportStep("successfully clicked on download report and renamed the file", "pass");
}
catch(Exception e)
{
reportStep("click on download report is unsuccessful", "fail");
}
return this;
}
@FindBy(xpath = "//input[contains(@id,'inFile')]/..")
private WebElement chooseFile;
public OperaCloud_CreateReportsPage chooseFileToUpload(String fileNameToUpload) throws InterruptedException, IOException {
try {
WebElement browse = chooseFile;
browse.click();
Thread.sleep(3000);
Robot rb = new Robot();
StringSelection str = new StringSelection("S:\\Cloud Workspace\\resources\\alert.rtf");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
// release Contol+V for pasting
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);
// for pressing and releasing Enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
reportStep("successfully clicked on chooseFileToUpload", "pass");
}
catch(Exception e)
{
reportStep("click on chooseFileToUpload failed", "fail");
}
return this;
}
@FindBy(xpath = "//select[contains(@id,'lov3')]//option[contains(text(),'Accounts')]")
private WebElement reportGrp;
public OperaCloud_CreateReportsPage selectReportGroup() throws InterruptedException, IOException {
try {
clickElement(reportGrp);
Thread.sleep(5000);
reportStep("successfully clicked on report group", "pass");
}
catch (Exception e)
{
reportStep("click on report group unsuccessful", "fail");
}
return this;
}
}
|
//The Main class to run all threads.
/**
* @author Luc Saunders-Grant
* @version 1.0
*/
public class Main
{
private int n = 400;
private int m = 4;
private Data data = new Data(m);
public static void main(String[] args) throws InterruptedException
{
new Main().startProgram();
}
private void startProgram() throws InterruptedException
{
Thread a = new ThreadA(n, data);
Thread b = new ThreadB(n, data);
Thread c = new ThreadC(n, data);
a.start();
b.start();
c.start();
a.join();
b.join();
c.join();
}
}
|
package com.ideal.cash.register.models;
/**
* 商品类别
* @author Ideal
*/
public enum Commodity {
/**
* 食品
*/
FOOD("食品"),
/**
* 酒水
*/
DRINKS("酒水"),
/**
* 体育用品
*/
SPORTS("体育用品");
/**
* 商品类别名称
*/
private String name;
private Commodity(String name) {
this.name = name;
}
/**
* 读取商品类别名称
* @return
*/
public String getName() {
return name;
}
}
|
package edu.banking.savelyev.denis;
import edu.jenks.dist.banking.*;
public class Customer extends AbstractCustomer{
public Customer(String name) {
super(name);
}
public Customer(String name, AbstractCheckingAccount checkingAccount, AbstractSavingsAccount savingsAccount) {
super(name, checkingAccount, savingsAccount);
if(savingsAccount != null) {
checkingAccount.setLinkedSavingsAccount(savingsAccount);
}
}
public int compareTo(AbstractCustomer o) {
return 0;
}
}
|
/*
* Created on Jul 28, 2015
*/
package basics;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class EffectExample extends Application {
@Override
public void start(Stage stage) {
DropShadow shadow = new DropShadow();
shadow.setRadius(5.0);
shadow.setColor(Color.BLACK);
shadow.setOffsetX(3.0);
shadow.setOffsetY(3.0);
Text text = new Text("This text has a shadow");
text.setLayoutY(200);
text.setFill(Color.CRIMSON);
text.setEffect(shadow);
text.setFont(Font.font(40));
Group root = new Group(text);
Scene scene = new Scene(root,600,400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package designpattern.factory.simple_factory;
/**
* 工厂类:工厂类在接到订单后按照客户提供的参数制造
*
* 工厂类是本模式的核心,含有一定的商业逻辑和判断逻辑,用来创建产品
*/
public class Factory {
public BMW createBMW(int type){
switch(type){
case 320:
return new BMW320();
case 523:
return new BMW523();
default:
break;
}
return null;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fms.gui.bottomtabpane;
import fms.FMS;
import javafx.scene.control.Tab;
import javafx.scene.layout.GridPane;
/**
*
* @author FMS
*/
public class FCUI extends Tab {
public FCUI(FMS fms) {
GridPane grid = new GridPane();
grid.add(new PrestartButton(fms), 1, 1);
this.setText("FCUI");
this.setClosable(false);
this.setContent(grid);
}
}
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[]args) {
BattleGame game = new BattleGame();
game.playGame();
}
} |
package util;
import java.util.Random;
import configuration.TestConfig;
public class RandomNumber {
private static final int DEFAULT_SEED = 123456789;
private static final Random RANDOM = new Random(DEFAULT_SEED);
public static double random() {
return !TestConfig.USE_RANDOMNESS ? RANDOM.nextDouble() : Math.random();
}
}
|
package com.citibank.ods.entity.pl.valueobject;
import java.util.Date;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
public class BaseTplTermAdhesionMovEntityVO extends BaseEntityVO {
private String trsrySysInd;
private String dpSysInd;
private String adhTermTypeCode;
private Date lastApprvDate;
private String lastApprvUserId;
private Date lastUpdDate;
private String lastUpdUserId;
private String opernTypeCode;
public String getTrsrySysInd() {
return trsrySysInd;
}
public void setTrsrySysInd(String trsrySysInd) {
this.trsrySysInd = trsrySysInd;
}
public String getDpSysInd() {
return dpSysInd;
}
public void setDpSysInd(String dpSysInd) {
this.dpSysInd = dpSysInd;
}
public String getAdhTermTypeCode() {
return adhTermTypeCode;
}
public void setAdhTermTypeCode(String adhTermTypeCode) {
this.adhTermTypeCode = adhTermTypeCode;
}
public Date getLastApprvDate() {
return lastApprvDate;
}
public void setLastApprvDate(Date lastApprvDate) {
this.lastApprvDate = lastApprvDate;
}
public String getLastApprvUserId() {
return lastApprvUserId;
}
public void setLastApprvUserId(String lastApprvUserId) {
this.lastApprvUserId = lastApprvUserId;
}
public Date getLastUpdDate() {
return lastUpdDate;
}
public void setLastUpdDate(Date lastUpdDate) {
this.lastUpdDate = lastUpdDate;
}
public String getLastUpdUserId() {
return lastUpdUserId;
}
public void setLastUpdUserId(String lastUpdUserId) {
this.lastUpdUserId = lastUpdUserId;
}
public String getOpernTypeCode() {
return opernTypeCode;
}
public void setOpernTypeCode(String opernTypeCode) {
this.opernTypeCode = opernTypeCode;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.