blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a4d9ebc269cd48d078ac5cb21c938d88b40d3963 | 6c967830481b8a71655059efa8596e7a2aa2f8dc | /menu/src/com/example/menu/notice/NoticeAdapter.java | 7d5d3314d9fb2c92de23f31e768f7a835dc7067e | [] | no_license | fordream/Link_Android | f243216e62eef4acf80e1fac862fbe29008f4c74 | 12d2492f8f700906ccf55fd89eb7d392c4d67434 | refs/heads/master | 2021-01-18T05:07:53.928962 | 2015-11-28T07:57:24 | 2015-11-28T07:57:24 | 47,870,658 | 1 | 0 | null | 2015-12-12T08:34:47 | 2015-12-12T08:34:47 | null | UTF-8 | Java | false | false | 2,675 | java | package com.example.menu.notice;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
public class NoticeAdapter extends BaseExpandableListAdapter {
ArrayList<DataNoticeTitle> items = new ArrayList<DataNoticeTitle>();
Context mContext;
public void add(String groupKey, String content)
{
DataNoticeTitle newTitle = null;
if(newTitle == null)
{
newTitle = new DataNoticeTitle();
newTitle.title = groupKey;
items.add(newTitle);
}
if(newTitle != null)
{
DataNoticeContent newContent = new DataNoticeContent();
newContent.content = content;
newTitle.content.add(newContent);
}
notifyDataSetChanged();
}
public NoticeAdapter(Context context) {
mContext = context;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition).content.size();
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition).content.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return ((long)groupPosition) << 32|0xffffffff;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return ((long)groupPosition) << 32|(long)childPosition;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewNoticeTitle view;
if(convertView == null)
{ view = new ViewNoticeTitle(mContext); }
else
{ view = (ViewNoticeTitle)convertView; }
view.setNoticTitle(items.get(groupPosition));
return view;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ViewNoticeContent view;
if(convertView == null)
{ view = new ViewNoticeContent(mContext); }
else
{ view = (ViewNoticeContent)convertView; }
view.setNoticeContent(items.get(groupPosition).content.get(childPosition));
return view;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
| [
"shy817@naver.com"
] | shy817@naver.com |
af308caf6397e710a513753f2d38193fef68692d | 4537423a5e50edf77bf48b2e52b1b73c3fc5d696 | /tokamak-core/src/main/java/com/wrmsr/tokamak/core/tree/node/TAliasableRelation.java | d039248d497616de193a0110851a387bfb061cb7 | [
"Apache-2.0"
] | permissive | wrmsr/tokamak | 5a662ec6ee2b34321f772a881d3bfe4f413da82a | 3ebf3395c5bb78b80e0445199958cb81f4cf9be8 | refs/heads/master | 2022-12-22T13:27:58.158522 | 2021-03-29T21:03:00 | 2021-03-29T21:03:00 | 191,827,182 | 3 | 0 | Apache-2.0 | 2022-12-12T21:43:15 | 2019-06-13T20:14:55 | Java | UTF-8 | Java | false | false | 676 | java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wrmsr.tokamak.core.tree.node;
public abstract class TAliasableRelation
extends TRelation
{
}
| [
"timwilloney@gmail.com"
] | timwilloney@gmail.com |
f5a1fe2d8bb6aec67ebf05178f3514ac399bf28d | 8306789663a11368acc6e51803aec1fa8ccde900 | /CommonListeners/src/main/java/me/elvis/common/listeners/ServletContextAttributeListener.java | bceb26f8b40b2cc909761dad87cfcac3529b8c62 | [] | no_license | zjs1224522500/JavaWebUtils | b436c87a58b1fff88aea339062c2baf5da23f0ff | ae0240397367a9e9211e979e1045971101862869 | refs/heads/master | 2022-12-24T21:52:03.151355 | 2021-04-04T09:48:06 | 2021-04-04T09:48:06 | 108,950,592 | 2 | 0 | null | 2022-12-10T06:22:03 | 2017-10-31T05:42:36 | Java | UTF-8 | Java | false | false | 605 | java | package me.elvis.common.listeners;
import javax.servlet.ServletContextAttributeEvent;
/**
* Version:v1.0 (description: 用于监听context中属性的变化,对应的被监听对象执行add/update/remove ) Date:2017/11/22 0022 Time:12:31
*/
public class ServletContextAttributeListener implements
javax.servlet.ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
}
@Override
public void attributeReplaced(ServletContextAttributeEvent scae) {
}
}
| [
"1224522500@qq.com"
] | 1224522500@qq.com |
8ec2124c77ec9107886b46873a2677e13f019ffa | 8140b0a57296a0c6c784de2d64fc71574e00dcb8 | /Evaluator/src/main/java/org/kakaobank/kafka/ConsumerCreator.java | 86f2b78f86771bb6abf8f5ec29849b39383da1ec | [] | no_license | deviscreen/FDS01 | c0468179d08b28ab84ede339c73450e86102be15 | 8d02383c570930fb6ec5248cee87cfb439cfc176 | refs/heads/master | 2022-12-05T11:38:42.563712 | 2020-08-25T15:00:44 | 2020-08-25T15:00:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,333 | java | package org.kakaobank.kafka;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.Collections;
import java.util.Properties;
public class ConsumerCreator {
public static Consumer<String, String> createConsumer() {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, IKafkaConfig.KAFKA_BROKERS);
props.put(ConsumerConfig.GROUP_ID_CONFIG, IKafkaConfig.GROUP_ID_CONFIG);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, IKafkaConfig.MAX_POLL_RECORDS);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, IKafkaConfig.OFFSET_RESET_EALIER);
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(IKafkaConfig.TOPIC_NAME));
return consumer;
}
}
| [
"kdy0573@daum.net"
] | kdy0573@daum.net |
4160200eadc60afd8c253a97ea10fdcb57164700 | a4a51084cfb715c7076c810520542af38a854868 | /src/main/java/com/shopee/protocol/shop/CoinGlobalExtInfo.java | 349c2c567689560d88af98acc6cbcaf3bb5cbe06 | [] | no_license | BharathPalanivelu/repotest | ddaf56a94eb52867408e0e769f35bef2d815da72 | f78ae38738d2ba6c9b9b4049f3092188fabb5b59 | refs/heads/master | 2020-09-30T18:55:04.802341 | 2019-12-02T10:52:08 | 2019-12-02T10:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,963 | java | package com.shopee.protocol.shop;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import java.util.Collections;
import java.util.List;
public final class CoinGlobalExtInfo extends Message {
public static final List<Integer> DEFAULT_RULE_RANK_IDS = Collections.emptyList();
private static final long serialVersionUID = 0;
@ProtoField(label = Message.Label.REPEATED, tag = 1, type = Message.Datatype.INT32)
public final List<Integer> rule_rank_ids;
public CoinGlobalExtInfo(List<Integer> list) {
this.rule_rank_ids = immutableCopyOf(list);
}
private CoinGlobalExtInfo(Builder builder) {
this(builder.rule_rank_ids);
setBuilder(builder);
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CoinGlobalExtInfo)) {
return false;
}
return equals((List<?>) this.rule_rank_ids, (List<?>) ((CoinGlobalExtInfo) obj).rule_rank_ids);
}
public int hashCode() {
int i = this.hashCode;
if (i == 0) {
List<Integer> list = this.rule_rank_ids;
i = list != null ? list.hashCode() : 1;
this.hashCode = i;
}
return i;
}
public static final class Builder extends Message.Builder<CoinGlobalExtInfo> {
public List<Integer> rule_rank_ids;
public Builder() {
}
public Builder(CoinGlobalExtInfo coinGlobalExtInfo) {
super(coinGlobalExtInfo);
if (coinGlobalExtInfo != null) {
this.rule_rank_ids = CoinGlobalExtInfo.copyOf(coinGlobalExtInfo.rule_rank_ids);
}
}
public Builder rule_rank_ids(List<Integer> list) {
this.rule_rank_ids = checkForNulls(list);
return this;
}
public CoinGlobalExtInfo build() {
return new CoinGlobalExtInfo(this);
}
}
}
| [
"noiz354@gmail.com"
] | noiz354@gmail.com |
268fe1e777120ed5480336d5309b91d1ca086e96 | 179f41638aa9e3ba18d64a4ed01bb4d88fa79c5b | /src/Client/ClientSender.java | 30e8123b713917e8ef4048ea8efe164ef7438c06 | [] | no_license | AnnMir/Rest_chat | 352f36d7fc2e3a07eea81ff87b51294a7a8ef4b0 | 443452567831ae8bc73a5777798e904f7b608266 | refs/heads/master | 2020-04-08T01:34:51.671338 | 2018-11-30T13:46:38 | 2018-11-30T13:46:38 | 158,900,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,459 | java | package Client;
import Common.Data;
import org.json.simple.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import static Common.Commons.*;
public class ClientSender implements Runnable {
private BufferedWriter bufferedWriter;
private String method;
private LinkedBlockingQueue<Data> toSendQueue;
void setToken(String token) {
this.token = token;
}
private String token;
ClientSender(final Socket socket) {
try {
method = "default";
toSendQueue = new LinkedBlockingQueue<>();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
void work(final String methodName, final String message) {
try {
toSendQueue.put(new Data(methodName, message));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
Data data;
try {
data = toSendQueue.take();
executeMethod(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void executeMethod(Data data) {
method = data.getNameOfMethod();
String nameOrMessage = data.getMessage();
switch (method) {
case KEY_POST_LOGIN: {
sendPostLogin(nameOrMessage);
method = "default";
break;
}
case KEY_POST_LOGOUT: {
sendPostLogout();
method = "default";
break;
}
case KEY_POST_MESSAGE: {
sendPostMessage(nameOrMessage);
method = "default";
break;
}
case KEY_GET_ONE_USER: {
sendGetOneUser(nameOrMessage);
method = "default";
break;
}
case KEY_GET_ALL_USERS: {
sendGetAllUsers();
method = "default";
break;
}
case KEY_GET_MESSAGES: {
sendGetAllMessages(nameOrMessage);
method = "default";
break;
}
default: {
break;
}
}
}
private void sendPostMessage(final String msg) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", msg);
String message = "POST /"+KEY_POST_MESSAGE+ " HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "Content-Type: application/json " + "\r\n"
+ "\r\n"
+ jsonObject.toJSONString() + "\r\n";
System.out.println("post message: "+message);
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPostLogin(final String name) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", name);
String message = "POST /"+KEY_POST_LOGIN+" HTTP/1.1" + "\r\n"
+ "Content-Type: application/json" + "\r\n"
+ "\r\n"
+ jsonObject.toJSONString() + "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPostLogout() {
try {
String message = "POST /"+KEY_POST_LOGOUT +" HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
System.out.println(message);
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetOneUser(final String nameOrMessage) {
try {
String message = "GET /"+KEY_GET_ONE_USER+nameOrMessage + " HTTP/1.1\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetAllUsers() {
try {
String message = "GET /"+ KEY_GET_ALL_USERS+" HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetAllMessages(String numberOfMessage) {
try {
String message = "GET /"+KEY_GET_MESSAGES+"?offset=" + numberOfMessage + "&count=10" + " HTTP/1.1\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"a.mirianova@g.nsu.ru"
] | a.mirianova@g.nsu.ru |
6e254a41ed3446b5a19247bd1a7dc79ffa247428 | 78897cc7463a2b79d60d2c087a34693b37be9b60 | /Proyecto_A_CreditoEJB/ejbModule/proyecto/model/entities/Transaccion.java | 63789b99569f17b82c16569ebedd9c35a0db4127 | [] | no_license | QuilismalM/AhorroyCredito | 0583274a2e44c5d92017e45c30fc91a138e38697 | 3926f720888e1f68c5a965cf41f5747ae7df1d37 | refs/heads/master | 2020-06-14T04:26:06.652652 | 2019-07-16T00:10:33 | 2019-07-16T00:10:33 | 194,898,812 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,734 | java | package proyecto.model.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* The persistent class for the transaccion database table.
*
*/
@Entity
@Table(name="transaccion")
@NamedQuery(name="Transaccion.findAll", query="SELECT t FROM Transaccion t")
public class Transaccion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="TRANSACCION_IDTRANSACCION_GENERATOR", sequenceName="SEQ_TRANSACCION",allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TRANSACCION_IDTRANSACCION_GENERATOR")
@Column(name="id_transaccion", unique=true, nullable=false)
private Integer idTransaccion;
@Column(name="cuenta_destino")
private Integer cuentaDestino;
@Temporal(TemporalType.DATE)
@Column(name="fecha_transaccion", nullable=false)
private Date fechaTransaccion;
@Column(name="monto_transaccion", precision=10, scale=2)
private BigDecimal montoTransaccion;
@Column(name="saldo_transaccion", nullable=false)
private Integer saldoTransaccion;
//bi-directional many-to-one association to CuentaCliente
@ManyToOne
@JoinColumn(name="nro_cuenta_cl", nullable=false)
private CuentaCliente cuentaCliente;
//bi-directional many-to-one association to TipoTransaccion
@ManyToOne
@JoinColumn(name="id_tipo_transaccion", nullable=false)
private TipoTransaccion tipoTransaccion;
public Transaccion() {
}
public Integer getIdTransaccion() {
return this.idTransaccion;
}
public void setIdTransaccion(Integer idTransaccion) {
this.idTransaccion = idTransaccion;
}
public Integer getCuentaDestino() {
return this.cuentaDestino;
}
public void setCuentaDestino(Integer cuentaDestino) {
this.cuentaDestino = cuentaDestino;
}
public Date getFechaTransaccion() {
return this.fechaTransaccion;
}
public void setFechaTransaccion(Date fechaTransaccion) {
this.fechaTransaccion = fechaTransaccion;
}
public BigDecimal getMontoTransaccion() {
return this.montoTransaccion;
}
public void setMontoTransaccion(BigDecimal montoTransaccion) {
this.montoTransaccion = montoTransaccion;
}
public Integer getSaldoTransaccion() {
return this.saldoTransaccion;
}
public void setSaldoTransaccion(Integer saldoTransaccion) {
this.saldoTransaccion = saldoTransaccion;
}
public CuentaCliente getCuentaCliente() {
return this.cuentaCliente;
}
public void setCuentaCliente(CuentaCliente cuentaCliente) {
this.cuentaCliente = cuentaCliente;
}
public TipoTransaccion getTipoTransaccion() {
return this.tipoTransaccion;
}
public void setTipoTransaccion(TipoTransaccion tipoTransaccion) {
this.tipoTransaccion = tipoTransaccion;
}
} | [
"quilismalm@localhost"
] | quilismalm@localhost |
142df89b778a9e8d87e1a3f2d0ab6d067b072572 | 55cda70a591be9e15d972aac5b12203433105386 | /4. Microservices/Microservices_O8ITO8_Movies/src/main/java/movies/MovieDirectorComparator.java | 0b0ade377b7b3094e4b1e4986f27e12d48f16534 | [] | no_license | wkrea/soi | 4c881eaacd1a20b8f329cbdc77c710ee8a0c4477 | 4c9b785ab6074bcd388f0ecd27ad450c6598ea7b | refs/heads/master | 2021-12-14T22:55:13.701574 | 2017-06-18T18:59:36 | 2017-06-18T18:59:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 245 | java | package movies;
import java.util.Comparator;
public class MovieDirectorComparator implements Comparator<Movie> {
@Override
public int compare(Movie a, Movie b) {
return (a.getDirector().compareTo(b.getDirector()) >= 0) ? 1 : -1;
}
}
| [
"mail@peterbartha.com"
] | mail@peterbartha.com |
41e45adbdd0e30a0f746260d36519e43fa132d99 | e5915db1aef7162ef4a9c28b022937070a92a2a7 | /src/main/java/qlhvt/dao/impl/DriverDaoImpl.java | 988e3f70df728116b94ed8bd0979b7fa9de32be6 | [] | no_license | ductq1999/QLHVT | 04409daf44dc45fb2c650bc10539ce71f4045263 | 98f6e2e63c02d056e405fda6473d5fa824a272f8 | refs/heads/master | 2023-02-11T05:47:58.050294 | 2021-01-11T11:07:58 | 2021-01-11T11:07:58 | 314,599,002 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,272 | java | package qlhvt.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import qlhvt.dao.DriverDao;
import qlhvt.entities.Driver;
@Transactional
@Repository(value = "driverDao")
public class DriverDaoImpl implements DriverDao {
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
@Override
public List<Driver> getAllDriver() {
// TODO Auto-generated method stub
String hql = "FROM Driver as d WHERE d.status = 1";
return (List<Driver>) entityManager.createQuery(hql).getResultList();
}
@Override
public Driver getDriverById(Integer id) {
// TODO Auto-generated method stub
return entityManager.find(Driver.class, id);
}
@Override
public void addDriver(Driver driver) {
// TODO Auto-generated method stub
entityManager.persist(driver);
}
@Override
public void updateDriver(Driver driver) {
// TODO Auto-generated method stub
Driver mDriver = entityManager.find(Driver.class, driver.getId());
driver.setId(mDriver.getId());
entityManager.merge(driver);
}
@Override
public void deleteDriverById(Integer id) {
// TODO Auto-generated method stub
Driver driver = entityManager.find(Driver.class, id);
driver.setStatus(0);
entityManager.merge(driver);
}
@SuppressWarnings("unlikely-arg-type")
@Override
public List<Driver> searchDriverByCondition(int page, int pageSize, String columnSortName, Boolean asc, String name,
String idNumber, String licenseType, String address, Integer status) {
// TODO Auto-generated method stub
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Driver> from = criteriaQuery.from(Driver.class);
CriteriaQuery<Object> select = criteriaQuery.select(from);
List<Predicate> predicates = new ArrayList<Predicate>();
if (name != null && !name.equals("")) {
predicates.add(criteriaBuilder.like(from.get("name"), "%" + name + "%"));
}
if (idNumber != null && !idNumber.equals("")) {
predicates.add(criteriaBuilder.like(from.get("idNumber"), "%" + idNumber + "%"));
}
if (licenseType != null && !licenseType.equals("")) {
predicates.add(criteriaBuilder.like(from.get("licenseType"), "%" + licenseType + "%"));
}
if (address != null && !address.equals("")) {
predicates.add(criteriaBuilder.like(from.get("address"), "%" + address + "%"));
}
if (status != null && !status.equals("")) {
predicates.add(criteriaBuilder.equal(from.get("status"), status));
}
select.select(from).where(predicates.toArray(new Predicate[] {}));
if (columnSortName != null && !columnSortName.equals("")) {
if (asc == null || asc) {
select.orderBy(criteriaBuilder.asc(from.get(columnSortName)));
} else {
select.orderBy(criteriaBuilder.desc(from.get(columnSortName)));
}
}
Query query = entityManager.createQuery(criteriaQuery);
if (page >= 0 && pageSize >= 0) {
query.setFirstResult((page - 1) * pageSize);
query.setMaxResults(pageSize);
}
@SuppressWarnings("unchecked")
List<Driver> lstResult = query.getResultList();
return lstResult;
}
@SuppressWarnings("unlikely-arg-type")
@Override
public int getRowCount(String name, String idNumber, String licenseType, String address, Integer status) {
// TODO Auto-generated method stub
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Driver> from = criteriaQuery.from(Driver.class);
CriteriaQuery<Object> select = criteriaQuery.select(from);
List<Predicate> predicates = new ArrayList<Predicate>();
if (name != null && !name.equals("")) {
predicates.add(criteriaBuilder.like(from.get("name"), "%" + name + "%"));
}
if (idNumber != null && !idNumber.equals("")) {
predicates.add(criteriaBuilder.like(from.get("idNumber"), "%" + idNumber + "%"));
}
if (licenseType != null && !licenseType.equals("")) {
predicates.add(criteriaBuilder.like(from.get("licenseType"), "%" + licenseType + "%"));
}
if (address != null && !address.equals("")) {
predicates.add(criteriaBuilder.like(from.get("address"), "%" + address + "%"));
}
;
if (status != null && !status.equals("")) {
predicates.add(criteriaBuilder.equal(from.get("status"), status));
}
select.select(from).where(predicates.toArray(new Predicate[] {}));
Query query = entityManager.createQuery(criteriaQuery);
@SuppressWarnings("unchecked")
List<Driver> lstResult = query.getResultList();
return lstResult.size();
}
@Override
public Boolean isExist(Driver driver) {
// TODO Auto-generated method stub
String hql = "FROM Driver as d WHERE d.status = 1 AND d.idNumber = :idNumber";
return entityManager.createQuery(hql).setParameter("idNumber", driver.getIdNumber()).getResultList().size() > 0 ? true : false;
}
}
| [
"47981725+ductq1999@users.noreply.github.com"
] | 47981725+ductq1999@users.noreply.github.com |
126b0d7b220cfefa837fe40baf806634d03e9723 | 87c16c410b8ba1d66376f22ebc5c494b4b8b6294 | /study/study/datastructnew/main/java/bitalgo/CountSetBits.java | 711119995219263bbd3eb1dbaa2d5714a263cd57 | [] | no_license | DRahul89/ds-algo-practise | 47bb6f887b9aaca73df69dba98da834abdb4a4d6 | 93c164a3e0de07aba50c1508983e7f28d7ce5552 | refs/heads/master | 2021-08-28T04:45:12.460967 | 2017-12-11T07:26:29 | 2017-12-11T07:26:29 | 110,454,062 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 951 | java | package main.java.bitalgo;
/**
* By using Kernighan’s Algorithm
*
* @author rahul2065
*
*/
public class CountSetBits {
public static int countSetBits(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count++;
}
return count;
}
public static int addOne(int x) {
return (-(~x));
}
public static int decreaseOne(int x) {
int one = 1;
for (int i = 1; i <= 32; i++) {
if ((x & one) != 0) {
x = x ^ one;
break;
} else {
x = x | one;
}
one = 1 << i;
}
return x;
}
public static int addOneByPattern(int x) {
int one = 1;
for (int i = 1; i <= 32; i++) {
if ((x & one) != 0) {
x = x ^ one;
} else {
x = x | one;
break;
}
one = 1 << i;
}
return x;
}
public static void main(String[] args) {
System.out.println(countSetBits(10));
System.out.println(addOne(10));
System.out.println(decreaseOne(10));
System.out.println(addOneByPattern(-200));
}
}
| [
"dixit.rahul09@gmail.com"
] | dixit.rahul09@gmail.com |
a5e7675b782340ddb993d880442c459610bf7f7a | 59b6d97d8a053697becba4418a83ed4ffc855d6b | /src/main/java/JDBC/PsRolePermissionDao.java | 76923d8ec47729958722a491e7455d450affe11d | [] | no_license | HanaSakuI/shixun | ff0ead2904f22b342cbb6a1926c13deae2854b55 | 7533538468a1c47fbee337e4f4ab65409ef03ff4 | refs/heads/master | 2023-06-20T09:28:52.083889 | 2021-07-22T07:29:32 | 2021-07-22T07:29:32 | 385,191,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,199 | java | package JDBC;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author yt
* 实体类PsRolePermission的Dao
*/
public class PsRolePermissionDao extends BaseDao {
/**
* 根据roleId获取functionCode
*
* @param roleId 角色ID
* @return functionCode
*/
public String getFunctionCodeByRoleId(String roleId) throws SQLException {
String sql = "SELECT * FROM ps_role_permission where roleId = '" + roleId + "'";
String functionCode = "";
ResultSet rs = executeQuery(sql);
while (rs.next()) {
functionCode = rs.getString("functionCode");
}
closeAll();
return functionCode;
}
/**
* 根据roleId修改functionCode
*
* @param roleId 角色ID
* @param functionCode 权限编号
* @return row
*/
public int updateFunctionCodeByRoleId(String roleId, String functionCode) {
String sql = "update ps_role_permission set functionCode = ? where roleId = '" + roleId + "'";
Object[] param = {
functionCode
};
int row = executeUpdate(sql, param);
closeAll();
return row;
}
}
| [
"19201323@stu.nchu.edu.cn"
] | 19201323@stu.nchu.edu.cn |
3eeaf7eca9adf37e3b36d3dc930b463bde8c1250 | ced2a6643a41e167bdacec5d9d9533c269476fa0 | /java/sortings/bubblesort/BubbleSort.java | 0bbb5c110da3494dd49079c701ec1da7bf505910 | [] | no_license | atsuya/algorithms | 7c157996d949e8da37f3475aede74adb2fa58ded | 1e3e708dd39cc8f55445ae59818435a5c2028f7d | refs/heads/master | 2021-06-06T18:28:55.377542 | 2021-06-06T06:13:43 | 2021-06-06T06:13:43 | 17,336,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,218 | java | import java.util.Vector;
public class BubbleSort {
public BubbleSort() {
}
public void sort(Vector<Integer> list) {
boolean swapped;
do {
swapped = false;
for (int index = 0; index < list.size(); index++) {
if (index + 1 < list.size()) {
if (list.get(index) > list.get(index + 1)) {
Integer temp = list.get(index);
list.set(index, list.get(index + 1));
list.set(index + 1, temp);
swapped = true;
}
}
}
} while (swapped);
}
public void print(Vector<Integer> list) {
for (Integer value : list) {
System.out.printf("%d ", value.intValue());
}
System.out.println();
}
public static void main(String[] args) {
Vector<Integer> list = new Vector<Integer>();
list.add(new Integer(8));
list.add(new Integer(22));
list.add(new Integer(2));
list.add(new Integer(40));
list.add(new Integer(9));
list.add(new Integer(11));
list.add(new Integer(2));
list.add(new Integer(15));
list.add(new Integer(4));
BubbleSort bubbleSort = new BubbleSort();
bubbleSort.print(list);
bubbleSort.sort(list);
bubbleSort.print(list);
}
}
| [
"asoftonight@gmail.com"
] | asoftonight@gmail.com |
f2a449245fb64dcfd246ac28d043b8a0a8f584ef | 0168ec3bec7e8475fb64df897d11be3fde1e2e6e | /src/main/java/com/example/demo/HomeController.java | d2628e6dbf8fbbeee25e998252c287fa40e6664f | [] | no_license | DerekLorimer/SpringCourse | 3c3236a1edacbd0feb261308832b8c24f61d7798 | c0eea131bba1f6a6a3367a4027959027b25d3411 | refs/heads/master | 2023-07-26T03:21:18.169690 | 2021-09-04T06:32:03 | 2021-09-04T06:32:03 | 402,982,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 886 | java | package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@Autowired
PersonRepo repo;
@RequestMapping("home")
public ModelAndView home(@RequestParam("name") String name) {
ModelAndView mv = new ModelAndView();
System.out.println("hello ModelAndView " + name);
mv.addObject("name", name);
mv.setViewName("home");
return mv;
}
@RequestMapping("addPerson")
public ModelAndView addPerson(Person person) {
ModelAndView mv = new ModelAndView();
mv.setViewName("home");
repo.save(person);
return mv;
}
}
| [
"dereklorime@bigpond.com"
] | dereklorime@bigpond.com |
3adf71aacaf51b142143a12bfff59de1ccd09502 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/29/29_e2bc2614fabc2bdee8f52d764f84f474b859ea84/RedisAsyncConnection/29_e2bc2614fabc2bdee8f52d764f84f474b859ea84_RedisAsyncConnection_t.java | 7b75f962c0008516a76bb4e6b7d0288e7ee9aa3a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 44,772 | java | // Copyright (C) 2011 - Will Glozer. All rights reserved.
package com.lambdaworks.redis;
import com.lambdaworks.codec.Base16;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.output.*;
import com.lambdaworks.redis.protocol.*;
import org.jboss.netty.channel.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.*;
import static com.lambdaworks.redis.protocol.CommandKeyword.*;
import static com.lambdaworks.redis.protocol.CommandType.*;
/**
* An asynchronous thread-safe connection to a redis server. Multiple threads may
* share one {@link RedisAsyncConnection} provided they avoid blocking and transactional
* operations such as {@link #blpop} and {@link #multi()}/{@link #exec}.
*
* A {@link ConnectionWatchdog} monitors each connection and reconnects
* automatically until {@link #close} is called. All pending commands will be
* (re)sent after successful reconnection.
*
* @author Will Glozer
*/
public class RedisAsyncConnection<K, V> extends SimpleChannelUpstreamHandler {
protected BlockingQueue<Command<K, V, ?>> queue;
protected RedisCodec<K, V> codec;
protected Channel channel;
protected long timeout;
protected TimeUnit unit;
protected MultiOutput<K, V> multi;
private String password;
private int db;
private boolean closed;
/**
* Initialize a new connection.
*
* @param queue Command queue.
* @param codec Codec used to encode/decode keys and values.
* @param timeout Maximum time to wait for a response.
* @param unit Unit of time for the timeout.
*/
public RedisAsyncConnection(BlockingQueue<Command<K, V, ?>> queue, RedisCodec<K, V> codec, long timeout, TimeUnit unit) {
this.queue = queue;
this.codec = codec;
this.timeout = timeout;
this.unit = unit;
}
/**
* Set the command timeout for this connection.
*
* @param timeout Command timeout.
* @param unit Unit of time for the timeout.
*/
public void setTimeout(long timeout, TimeUnit unit) {
this.timeout = timeout;
this.unit = unit;
}
public Future<Long> append(K key, V value) {
return dispatch(APPEND, new IntegerOutput<K, V>(codec), key, value);
}
public String auth(String password) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(password);
Command<K, V, String> cmd = dispatch(AUTH, new StatusOutput<K, V>(codec), args);
String status = await(cmd, timeout, unit);
if ("OK".equals(status)) this.password = password;
return status;
}
public Future<String> bgrewriteaof() {
return dispatch(BGREWRITEAOF, new StatusOutput<K, V>(codec));
}
public Future<String> bgsave() {
return dispatch(BGSAVE, new StatusOutput<K, V>(codec));
}
public Future<Long> bitcount(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(BITCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitcount(K key, long start, long end) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(end);
return dispatch(BITCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopAnd(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(AND).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopNot(K destination, K source) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(NOT).addKey(destination).addKey(source);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopOr(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(OR).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopXor(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(XOR).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<KeyValue<K, V>> blpop(long timeout, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys).add(timeout);
return dispatch(BLPOP, new KeyValueOutput<K, V>(codec), args);
}
public Future<KeyValue<K, V>> brpop(long timeout, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys).add(timeout);
return dispatch(BRPOP, new KeyValueOutput<K, V>(codec), args);
}
public Future<V> brpoplpush(long timeout, K source, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(source).addKey(destination).add(timeout);
return dispatch(BRPOPLPUSH, new ValueOutput<K, V>(codec), args);
}
public Future<K> clientGetname() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GETNAME);
return dispatch(CLIENT, new KeyOutput<K, V>(codec), args);
}
public Future<String> clientSetname(K name) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(SETNAME).addKey(name);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<String> clientKill(String addr) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(KILL).add(addr);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<String> clientList() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LIST);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<List<String>> configGet(String parameter) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET).add(parameter);
return dispatch(CONFIG, new StringListOutput<K, V>(codec), args);
}
public Future<String> configResetstat() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(RESETSTAT);
return dispatch(CONFIG, new StatusOutput<K, V>(codec), args);
}
public Future<String> configSet(String parameter, String value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(SET).add(parameter).add(value);
return dispatch(CONFIG, new StatusOutput<K, V>(codec), args);
}
public Future<Long> dbsize() {
return dispatch(DBSIZE, new IntegerOutput<K, V>(codec));
}
public Future<String> debugObject(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(OBJECT).addKey(key);
return dispatch(DEBUG, new StatusOutput<K, V>(codec), args);
}
public Future<Long> decr(K key) {
return dispatch(DECR, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> decrby(K key, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(DECRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> del(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(DEL, new IntegerOutput<K, V>(codec), args);
}
public Future<String> discard() {
multi = null;
return dispatch(DISCARD, new StatusOutput<K, V>(codec));
}
public Future<byte[]> dump(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(DUMP, new ByteArrayOutput<K, V>(codec), args);
}
public Future<V> echo(V msg) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addValue(msg);
return dispatch(ECHO, new ValueOutput<K, V>(codec), args);
}
public <T> Future<T> eval(V script, ScriptOutputType type, K[] keys, V... values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addValue(script).add(keys.length).addKeys(keys).addValues(values);
CommandOutput<K, V, T> output = newScriptOutput(codec, type);
return dispatch(EVAL, output, args);
}
public <T> Future<T> evalsha(String digest, ScriptOutputType type, K[] keys, V... values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(digest).add(keys.length).addKeys(keys).addValues(values);
CommandOutput<K, V, T> output = newScriptOutput(codec, type);
return dispatch(EVALSHA, output, args);
}
public Future<Boolean> exists(K key) {
return dispatch(EXISTS, new BooleanOutput<K, V>(codec), key);
}
public Future<Boolean> expire(K key, long seconds) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(seconds);
return dispatch(EXPIRE, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> expireat(K key, Date timestamp) {
return expireat(key, timestamp.getTime() / 1000);
}
public Future<Boolean> expireat(K key, long timestamp) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(timestamp);
return dispatch(EXPIREAT, new BooleanOutput<K, V>(codec), args);
}
public Future<List<Object>> exec() {
MultiOutput<K, V> multi = this.multi;
this.multi = null;
if (multi == null) multi = new MultiOutput<K, V>(codec);
return dispatch(EXEC, multi);
}
public Future<String> flushall() throws Exception {
return dispatch(FLUSHALL, new StatusOutput<K, V>(codec));
}
public Future<String> flushdb() throws Exception {
return dispatch(FLUSHDB, new StatusOutput<K, V>(codec));
}
public Future<V> get(K key) {
return dispatch(GET, new ValueOutput<K, V>(codec), key);
}
public Future<Long> getbit(K key, long offset) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset);
return dispatch(GETBIT, new IntegerOutput<K, V>(codec), args);
}
public Future<V> getrange(K key, long start, long end) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(end);
return dispatch(GETRANGE, new ValueOutput<K, V>(codec), args);
}
public Future<V> getset(K key, V value) {
return dispatch(GETSET, new ValueOutput<K, V>(codec), key, value);
}
public Future<Long> hdel(K key, K... fields) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKeys(fields);
return dispatch(HDEL, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> hexists(K key, K field) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field);
return dispatch(HEXISTS, new BooleanOutput<K, V>(codec), args);
}
public Future<V> hget(K key, K field) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field);
return dispatch(HGET, new ValueOutput<K, V>(codec), args);
}
public Future<Long> hincrby(K key, K field, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).add(amount);
return dispatch(HINCRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> hincrbyfloat(K key, K field, double amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).add(amount);
return dispatch(HINCRBYFLOAT, new DoubleOutput<K, V>(codec), args);
}
public Future<Map<K, V>> hgetall(K key) {
return dispatch(HGETALL, new MapOutput<K, V>(codec), key);
}
public Future<List<K>> hkeys(K key) {
return dispatch(HKEYS, new KeyListOutput<K, V>(codec), key);
}
public Future<Long> hlen(K key) {
return dispatch(HLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<List<V>> hmget(K key, K... fields) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKeys(fields);
return dispatch(HMGET, new ValueListOutput<K, V>(codec), args);
}
public Future<String> hmset(K key, Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(map);
return dispatch(HMSET, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> hset(K key, K field, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).addValue(value);
return dispatch(HSET, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> hsetnx(K key, K field, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).addValue(value);
return dispatch(HSETNX, new BooleanOutput<K, V>(codec), args);
}
public Future<List<V>> hvals(K key) {
return dispatch(HVALS, new ValueListOutput<K, V>(codec), key);
}
public Future<Long> incr(K key) {
return dispatch(INCR, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> incrby(K key, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(INCRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> incrbyfloat(K key, double amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(INCRBYFLOAT, new DoubleOutput<K, V>(codec), args);
}
public Future<String> info() {
return dispatch(INFO, new StatusOutput<K, V>(codec));
}
public Future<String> info(String section) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(section);
return dispatch(INFO, new StatusOutput<K, V>(codec), args);
}
public Future<List<K>> keys(K pattern) {
return dispatch(KEYS, new KeyListOutput<K, V>(codec), pattern);
}
public Future<Date> lastsave() {
return dispatch(LASTSAVE, new DateOutput<K, V>(codec));
}
public Future<V> lindex(K key, long index) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(index);
return dispatch(LINDEX, new ValueOutput<K, V>(codec), args);
}
public Future<Long> linsert(K key, boolean before, V pivot, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(before ? BEFORE : AFTER).addValue(pivot).addValue(value);
return dispatch(LINSERT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> llen(K key) {
return dispatch(LLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<V> lpop(K key) {
return dispatch(LPOP, new ValueOutput<K, V>(codec), key);
}
public Future<Long> lpush(K key, V... values) {
return dispatch(LPUSH, new IntegerOutput<K, V>(codec), key, values);
}
public Future<Long> lpushx(K key, V value) {
return dispatch(LPUSHX, new IntegerOutput<K, V>(codec), key, value);
}
public Future<List<V>> lrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(LRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<Long> lrem(K key, long count, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(count).addValue(value);
return dispatch(LREM, new IntegerOutput<K, V>(codec), args);
}
public Future<String> lset(K key, long index, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(index).addValue(value);
return dispatch(LSET, new StatusOutput<K, V>(codec), args);
}
public Future<String> ltrim(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(LTRIM, new StatusOutput<K, V>(codec), args);
}
public Future<String> migrate(String host, int port, K key, int db, long timeout) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(host).add(port).addKey(key).add(db).add(timeout);
return dispatch(MIGRATE, new StatusOutput<K, V>(codec), args);
}
public Future<List<V>> mget(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(MGET, new ValueListOutput<K, V>(codec), args);
}
public Future<Boolean> move(K key, int db) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(db);
return dispatch(MOVE, new BooleanOutput<K, V>(codec), args);
}
public Future<String> multi() {
Command<K, V, String> cmd = dispatch(MULTI, new StatusOutput<K, V>(codec));
multi = (multi == null ? new MultiOutput<K, V>(codec) : multi);
return cmd;
}
public Future<String> mset(Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(map);
return dispatch(MSET, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> msetnx(Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(map);
return dispatch(MSETNX, new BooleanOutput<K, V>(codec), args);
}
public Future<String> objectEncoding(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(ENCODING).addKey(key);
return dispatch(OBJECT, new StatusOutput<K, V>(codec), args);
}
public Future<Long> objectIdletime(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(IDLETIME).addKey(key);
return dispatch(OBJECT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> objectRefcount(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(REFCOUNT).addKey(key);
return dispatch(OBJECT, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> persist(K key) {
return dispatch(PERSIST, new BooleanOutput<K, V>(codec), key);
}
public Future<Boolean> pexpire(K key, long milliseconds) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(milliseconds);
return dispatch(PEXPIRE, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> pexpireat(K key, Date timestamp) {
return pexpireat(key, timestamp.getTime());
}
public Future<Boolean> pexpireat(K key, long timestamp) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(timestamp);
return dispatch(PEXPIREAT, new BooleanOutput<K, V>(codec), args);
}
public Future<String> ping() {
return dispatch(PING, new StatusOutput<K, V>(codec));
}
public Future<Long> pttl(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(PTTL, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> publish(K channel, V message) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(channel).addValue(message);
return dispatch(PUBLISH, new IntegerOutput<K, V>(codec), args);
}
public Future<String> quit() {
return dispatch(QUIT, new StatusOutput<K, V>(codec));
}
public Future<V> randomkey() {
return dispatch(RANDOMKEY, new ValueOutput<K, V>(codec));
}
public Future<String> rename(K key, K newKey) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(newKey);
return dispatch(RENAME, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> renamenx(K key, K newKey) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(newKey);
return dispatch(RENAMENX, new BooleanOutput<K, V>(codec), args);
}
public Future<String> restore(K key, long ttl, byte[] value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(ttl).add(value);
return dispatch(RESTORE, new StatusOutput<K, V>(codec), args);
}
public Future<V> rpop(K key) {
return dispatch(RPOP, new ValueOutput<K, V>(codec), key);
}
public Future<V> rpoplpush(K source, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(source).addKey(destination);
return dispatch(RPOPLPUSH, new ValueOutput<K, V>(codec), args);
}
public Future<Long> rpush(K key, V... values) {
return dispatch(RPUSH, new IntegerOutput<K, V>(codec), key, values);
}
public Future<Long> rpushx(K key, V value) {
return dispatch(RPUSHX, new IntegerOutput<K, V>(codec), key, value);
}
public Future<Long> sadd(K key, V... members) {
return dispatch(SADD, new IntegerOutput<K, V>(codec), key, members);
}
public Future<String> save() {
return dispatch(SAVE, new StatusOutput<K, V>(codec));
}
public Future<Long> scard(K key) {
return dispatch(SCARD, new IntegerOutput<K, V>(codec), key);
}
public Future<List<Boolean>> scriptExists(String... digests) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(EXISTS);
for (String sha : digests) args.add(sha);
return dispatch(SCRIPT, new BooleanListOutput<K, V>(codec), args);
}
public Future<String> scriptFlush() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(FLUSH);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<String> scriptKill() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(KILL);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<String> scriptLoad(V script) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LOAD).addValue(script);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<Set<V>> sdiff(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SDIFF, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sdiffstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SDIFFSTORE, new IntegerOutput<K, V>(codec), args);
}
public String select(int db) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(db);
Command<K, V, String> cmd = dispatch(SELECT, new StatusOutput<K, V>(codec), args);
String status = await(cmd, timeout, unit);
if ("OK".equals(status)) this.db = db;
return status;
}
public Future<String> set(K key, V value) {
return dispatch(SET, new StatusOutput<K, V>(codec), key, value);
}
public Future<Long> setbit(K key, long offset, int value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset).add(value);
return dispatch(SETBIT, new IntegerOutput<K, V>(codec), args);
}
public Future<String> setex(K key, long seconds, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(seconds).addValue(value);
return dispatch(SETEX, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> setnx(K key, V value) {
return dispatch(SETNX, new BooleanOutput<K, V>(codec), key, value);
}
public Future<Long> setrange(K key, long offset, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset).addValue(value);
return dispatch(SETRANGE, new IntegerOutput<K, V>(codec), args);
}
@Deprecated
public void shutdown() {
dispatch(SHUTDOWN, new StatusOutput<K, V>(codec));
}
public void shutdown(boolean save) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
dispatch(SHUTDOWN, new StatusOutput<K, V>(codec), save ? args.add(SAVE) : args.add(NOSAVE));
}
public Future<Set<V>> sinter(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SINTER, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sinterstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SINTERSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> sismember(K key, V member) {
return dispatch(SISMEMBER, new BooleanOutput<K, V>(codec), key, member);
}
public Future<Boolean> smove(K source, K destination, V member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(source).addKey(destination).addValue(member);
return dispatch(SMOVE, new BooleanOutput<K, V>(codec), args);
}
public Future<String> slaveof(String host, int port) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(host).add(port);
return dispatch(SLAVEOF, new StatusOutput<K, V>(codec), args);
}
public Future<String> slaveofNoOne() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(NO).add(ONE);
return dispatch(SLAVEOF, new StatusOutput<K, V>(codec), args);
}
public Future<List<Object>> slowlogGet() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET);
return dispatch(SLOWLOG, new NestedMultiOutput<K, V>(codec), args);
}
public Future<List<Object>> slowlogGet(int count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET).add(count);
return dispatch(SLOWLOG, new NestedMultiOutput<K, V>(codec), args);
}
public Future<Long> slowlogLen() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LEN);
return dispatch(SLOWLOG, new IntegerOutput<K, V>(codec), args);
}
public Future<String> slowlogReset() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(RESET);
return dispatch(SLOWLOG, new StatusOutput<K, V>(codec), args);
}
public Future<Set<V>> smembers(K key) {
return dispatch(SMEMBERS, new ValueSetOutput<K, V>(codec), key);
}
public Future<List<V>> sort(K key) {
return dispatch(SORT, new ValueListOutput<K, V>(codec), key);
}
public Future<List<V>> sort(K key, SortArgs sortArgs) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
sortArgs.build(args, null);
return dispatch(SORT, new ValueListOutput<K, V>(codec), args);
}
public Future<Long> sortStore(K key, SortArgs sortArgs, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
sortArgs.build(args, destination);
return dispatch(SORT, new IntegerOutput<K, V>(codec), args);
}
public Future<V> spop(K key) {
return dispatch(SPOP, new ValueOutput<K, V>(codec), key);
}
public Future<V> srandmember(K key) {
return dispatch(SRANDMEMBER, new ValueOutput<K, V>(codec), key);
}
public Future<Set<V>> srandmember(K key, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(count);
return dispatch(SRANDMEMBER, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> srem(K key, V... members) {
return dispatch(SREM, new IntegerOutput<K, V>(codec), key, members);
}
public Future<Set<V>> sunion(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SUNION, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sunionstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SUNIONSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<String> sync() {
return dispatch(SYNC, new StatusOutput<K, V>(codec));
}
public Future<Long> strlen(K key) {
return dispatch(STRLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> ttl(K key) {
return dispatch(TTL, new IntegerOutput<K, V>(codec), key);
}
public Future<String> type(K key) {
return dispatch(TYPE, new StatusOutput<K, V>(codec), key);
}
public Future<String> watch(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(WATCH, new StatusOutput<K, V>(codec), args);
}
public Future<String> unwatch() {
return dispatch(UNWATCH, new StatusOutput<K, V>(codec));
}
public Future<Long> zadd(K key, double score, V member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(score).addValue(member);
return dispatch(ZADD, new IntegerOutput<K, V>(codec), args);
}
@SuppressWarnings("unchecked")
public Future<Long> zadd(K key, Object... scoresAndValues) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
for (int i = 0; i < scoresAndValues.length; i += 2) {
args.add((Double) scoresAndValues[i]);
args.addValue((V) scoresAndValues[i + 1]);
}
return dispatch(ZADD, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> zcard(K key) {
return dispatch(ZCARD, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> zcount(K key, double min, double max) {
return zcount(key, string(min), string(max));
}
public Future<Long> zcount(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> zincrby(K key, double amount, K member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount).addKey(member);
return dispatch(ZINCRBY, new DoubleOutput<K, V>(codec), args);
}
public Future<Long> zinterstore(K destination, K... keys) {
return zinterstore(destination, new ZStoreArgs(), keys);
}
public Future<Long> zinterstore(K destination, ZStoreArgs storeArgs, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).add(keys.length).addKeys(keys);
storeArgs.build(args);
return dispatch(ZINTERSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<List<V>> zrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangeWithScores(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(stop).add(WITHSCORES);
return dispatch(ZRANGE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrangebyscore(K key, double min, double max) {
return zrangebyscore(key, string(min), string(max));
}
public Future<List<V>> zrangebyscore(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrangebyscore(K key, double min, double max, long offset, long count) {
return zrangebyscore(key, string(min), string(max), offset, count);
}
public Future<List<V>> zrangebyscore(K key, String min, String max, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(LIMIT).add(offset).add(count);
return dispatch(ZRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, double min, double max) {
return zrangebyscoreWithScores(key, string(min), string(max));
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(WITHSCORES);
return dispatch(ZRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, double min, double max, long offset, long count) {
return zrangebyscoreWithScores(key, string(min), string(max), offset, count);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, String min, String max, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(WITHSCORES).add(LIMIT).add(offset).add(count);
return dispatch(ZRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<Long> zrank(K key, V member) {
return dispatch(ZRANK, new IntegerOutput<K, V>(codec), key, member);
}
public Future<Long> zrem(K key, V... members) {
return dispatch(ZREM, new IntegerOutput<K, V>(codec), key, members);
}
public Future<Long> zremrangebyrank(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZREMRANGEBYRANK, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> zremrangebyscore(K key, double min, double max) {
return zremrangebyscore(key, string(min), string(max));
}
public Future<Long> zremrangebyscore(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZREMRANGEBYSCORE, new IntegerOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZREVRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangeWithScores(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(stop).add(WITHSCORES);
return dispatch(ZREVRANGE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrangebyscore(K key, double max, double min) {
return zrevrangebyscore(key, string(max), string(min));
}
public Future<List<V>> zrevrangebyscore(K key, String max, String min) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(max).add(min);
return dispatch(ZREVRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrangebyscore(K key, double max, double min, long offset, long count) {
return zrevrangebyscore(key, string(max), string(min), offset, count);
}
public Future<List<V>> zrevrangebyscore(K key, String max, String min, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(LIMIT).add(offset).add(count);
return dispatch(ZREVRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, double max, double min) {
return zrevrangebyscoreWithScores(key, string(max), string(min));
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, String max, String min) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(WITHSCORES);
return dispatch(ZREVRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, double max, double min, long offset, long count) {
return zrevrangebyscoreWithScores(key, string(max), string(min), offset, count);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, String max, String min, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(WITHSCORES).add(LIMIT).add(offset).add(count);
return dispatch(ZREVRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<Long> zrevrank(K key, V member) {
return dispatch(ZREVRANK, new IntegerOutput<K, V>(codec), key, member);
}
public Future<Double> zscore(K key, V member) {
return dispatch(ZSCORE, new DoubleOutput<K, V>(codec), key, member);
}
public Future<Long> zunionstore(K destination, K... keys) {
return zunionstore(destination, new ZStoreArgs(), keys);
}
public Future<Long> zunionstore(K destination, ZStoreArgs storeArgs, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(destination).add(keys.length).addKeys(keys);
storeArgs.build(args);
return dispatch(ZUNIONSTORE, new IntegerOutput<K, V>(codec), args);
}
/**
* Wait until commands are complete or the connection timeout is reached.
*
* @param futures Futures to wait for.
*
* @return True if all futures complete in time.
*/
public boolean awaitAll(Future<?>... futures) {
return awaitAll(timeout, unit, futures);
}
/**
* Wait until futures are complete or the supplied timeout is reached.
*
* @param timeout Maximum time to wait for futures to complete.
* @param unit Unit of time for the timeout.
* @param futures Futures to wait for.
*
* @return True if all futures complete in time.
*/
public boolean awaitAll(long timeout, TimeUnit unit, Future<?>... futures) {
boolean complete;
try {
long nanos = unit.toNanos(timeout);
long time = System.nanoTime();
for (Future<?> f : futures) {
if (nanos < 0) return false;
f.get(nanos, TimeUnit.NANOSECONDS);
long now = System.nanoTime();
nanos -= now - time;
time = now;
}
complete = true;
} catch (TimeoutException e) {
complete = false;
} catch (Exception e) {
throw new RedisCommandInterruptedException(e);
}
return complete;
}
/**
* Close the connection.
*/
public synchronized void close() {
if (!closed && channel != null) {
ConnectionWatchdog watchdog = channel.getPipeline().get(ConnectionWatchdog.class);
watchdog.setReconnect(false);
closed = true;
channel.close();
}
}
public String digest(V script) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(codec.encodeValue(script));
return new String(Base16.encode(md.digest(), false));
} catch (NoSuchAlgorithmException e) {
throw new RedisException("JVM does not support SHA1");
}
}
@Override
public synchronized void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = ctx.getChannel();
List<Command<K, V, ?>> tmp = new ArrayList<Command<K, V, ?>>(queue.size() + 2);
if (password != null) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(password);
tmp.add(new Command<K, V, String>(AUTH, new StatusOutput<K, V>(codec), args, false));
}
if (db != 0) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(db);
tmp.add(new Command<K, V, String>(SELECT, new StatusOutput<K, V>(codec), args, false));
}
tmp.addAll(queue);
queue.clear();
for (Command<K, V, ?> cmd : tmp) {
if (!cmd.isCancelled()) {
queue.add(cmd);
channel.write(cmd);
}
}
tmp.clear();
}
@Override
public synchronized void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (closed) {
for (Command<K, V, ?> cmd : queue) {
cmd.getOutput().setError("Connection closed");
cmd.complete();
}
queue.clear();
queue = null;
channel = null;
}
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output) {
return dispatch(type, output, (CommandArgs<K, V>) null);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(type, output, args);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addValue(value);
return dispatch(type, output, args);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key, V[] values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addValues(values);
return dispatch(type, output, args);
}
public synchronized <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, CommandArgs<K, V> args) {
Command<K, V, T> cmd = new Command<K, V, T>(type, output, args, multi != null);
try {
if (multi != null) {
multi.add(cmd);
}
queue.put(cmd);
if (channel != null) {
channel.write(cmd);
}
} catch (NullPointerException e) {
throw new RedisException("Connection is closed");
} catch (InterruptedException e) {
throw new RedisCommandInterruptedException(e);
}
return cmd;
}
public <T> T await(Command<K, V, T> cmd, long timeout, TimeUnit unit) {
if (!cmd.await(timeout, unit)) {
cmd.cancel(true);
throw new RedisException("Command timed out");
}
CommandOutput<K, V, T> output = cmd.getOutput();
if (output.hasError()) throw new RedisException(output.getError());
return output.get();
}
@SuppressWarnings("unchecked")
protected <K, V, T> CommandOutput<K, V, T> newScriptOutput(RedisCodec<K, V> codec, ScriptOutputType type) {
switch (type) {
case BOOLEAN: return (CommandOutput<K, V, T>) new BooleanOutput<K, V>(codec);
case INTEGER: return (CommandOutput<K, V, T>) new IntegerOutput<K, V>(codec);
case STATUS: return (CommandOutput<K, V, T>) new StatusOutput<K, V>(codec);
case MULTI: return (CommandOutput<K, V, T>) new NestedMultiOutput<K, V>(codec);
case VALUE: return (CommandOutput<K, V, T>) new ValueOutput<K, V>(codec);
default: throw new RedisException("Unsupported script output type");
}
}
public String string(double n) {
if (Double.isInfinite(n)) {
return (n > 0) ? "+inf" : "-inf";
}
return Double.toString(n);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
73dcdb9c209f349557d136b0e1c8a1d4be08092a | 6974e49496049f3cd8033c2c7712bb9c95172263 | /src/main/java/presentation/Bootstrap.java | 9d70dac98152173035dc2b3dfdfbb7bf2316a547 | [] | no_license | alot210/praktikum.webeng | 17ea11159711e9ef4b7fe6a321d5fc962c1b07df | 2faede28bd934ea5487ae67667cb7c2be8c04bfc | refs/heads/master | 2020-03-18T17:47:50.664675 | 2018-05-27T13:58:19 | 2018-05-27T13:58:19 | 135,051,277 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,248 | java | package presentation;
import businesslogic.ArticleManager;
import transferobject.Article;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
@WebServlet(urlPatterns ={ "/Bootstrap" })
public class Bootstrap extends HttpServlet {
public Bootstrap() {
super();
}
public void init() throws ServletException {
super.init();
ArticleManager manager = new ArticleManager();
manager.createArticleTable();
manager.createArticle(1, "Kaffee", 2, 10);
manager.createArticle(2, "Tee", 2, 20);
manager.createArticle(3, "Mate", 3, 8);
manager.createArticle(4, "Matcha", 5, 12);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
ArticleManager manager = new ArticleManager();
ArrayList<Article> a = manager.getArticle();
writer.println("<!doctype html>");
writer.println("<html>");
writer.println("<head><title>2. Praktikum WebEng</title></head>");
writer.println("<body>");
writer.println("<h3>Artikel im Shop</h3><br>");
writer.println("<table width = \"50%\" border = \"1 solid\" align = \"center\">");
writer.println("<tr>");
writer.println("<th>ID </th>");
writer.println("<th>Name </th>");
writer.println("<th>Price </th>");
writer.println("<th>Amount </th>");
writer.println("</tr>");
for(Article article : a ) {
writer.println("<tr>");
writer.println("<td>"+article.id+"</td>");
writer.println("<td>"+article.name+"</td>");
writer.println("<td>"+article.price+"</td>");
writer.println("<td>"+article.amount+"</td>");
writer.println("</tr>");
}
writer.println("</table>");
writer.println("<body>");
writer.println("</html>");
writer.close();
}
}
| [
"alinaotten@web.de"
] | alinaotten@web.de |
86e644bbc2e859fd8c2972bf97bcbb895cdf16f1 | 89a8bb56d27ab4479a5e5f0b49f368e2d70b09ff | /src/main/java/web/UsuarioFiltrar.java | c9193834651c3d72eb5e971b2053d95b0f7e1a07 | [] | no_license | renzorodrigues/Leilao-de-Livros | 6bfa6c0d2b90f21a2995b093e20f5bfe398e9fe6 | beacae1a3b27c857086b30f235ae142f41b9c80d | refs/heads/master | 2021-01-21T13:25:42.277708 | 2016-05-31T02:07:52 | 2016-05-31T02:07:52 | 53,894,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 907 | java | package web;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dominio.Usuario;
import servico.UsuarioServico;
@WebServlet("/usuarios/filtrar")
public class UsuarioFiltrar extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String DESTINO = "/usuarios/listar.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UsuarioServico uS = new UsuarioServico();
String nome = request.getParameter("busca");
List<Usuario> itens = uS.buscarPorNome(nome);
request.setAttribute("itens", itens);
request.getRequestDispatcher(DESTINO).forward(request, response);
}
}
| [
"renzors@gmail.com"
] | renzors@gmail.com |
1f19de836f6588354b89be1dfb430dbc9c7942cf | 0b0dbdc0d12c8eb60fdfbd48c4afc37147d0082e | /itests/standalone/basic/src/test/java/org/wildfly/camel/test/mail/MailIntegrationCDITest.java | f7b3fba086d038d30b76b4dda27e82a0f9ae6a4a | [
"Apache-2.0"
] | permissive | ppalaga/wildfly-camel | f99a35e36f9c80b8251d44ee1330c912a2916cb6 | 7376bb102149939da99063215c3f186424681fbc | refs/heads/master | 2021-07-09T01:44:01.018465 | 2019-06-21T08:46:17 | 2019-06-21T08:47:04 | 101,184,017 | 0 | 1 | Apache-2.0 | 2018-05-25T13:17:42 | 2017-08-23T13:36:21 | Java | UTF-8 | Java | false | false | 5,606 | java | /*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wildfly.camel.test.mail;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.common.utils.DMRUtils;
import org.wildfly.camel.test.mail.subA.MailSessionProducer;
import org.wildfly.extension.camel.CamelAware;
import org.wildfly.extension.camel.CamelContextRegistry;
@CamelAware
@ServerSetup({MailIntegrationCDITest.MailSessionSetupTask.class})
@RunWith(Arquillian.class)
public class MailIntegrationCDITest {
private static final String GREENMAIL_WAR = "greenmail.war";
@ArquillianResource
CamelContextRegistry contextRegistry;
static class MailSessionSetupTask implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String s) throws Exception {
ModelNode batchNode = DMRUtils.batchNode()
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-smtp", "add(host=localhost, port=10025)")
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-pop3", "add(host=localhost, port=10110)")
.addStep("subsystem=mail/mail-session=greenmail", "add(jndi-name=java:jboss/mail/greenmail)")
.addStep("subsystem=mail/mail-session=greenmail/server=smtp", "add(outbound-socket-binding-ref=mail-greenmail-smtp, username=user1, password=password)")
.addStep("subsystem=mail/mail-session=greenmail/server=pop3", "add(outbound-socket-binding-ref=mail-greenmail-pop3, username=user2, password=password2)")
.build();
managementClient.getControllerClient().execute(batchNode);
}
@Override
public void tearDown(ManagementClient managementClient, String s) throws Exception {
ModelNode batchNode = DMRUtils.batchNode()
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-smtp", "remove")
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-pop3", "remove")
.addStep("subsystem=mail/mail-session=greenmail", "remove")
.addStep("subsystem=mail/mail-session=greenmail/server=smtp", "remove")
.addStep("subsystem=mail/mail-session=greenmail/server=pop3", "remove")
.build();
managementClient.getControllerClient().execute(batchNode);
}
}
@Deployment(order = 1, testable = false, name = GREENMAIL_WAR)
public static WebArchive createGreenmailDeployment() {
File mailDependencies = Maven.configureResolverViaPlugin().
resolve("com.icegreen:greenmail-webapp:war:1.4.0").
withoutTransitivity().
asSingleFile();
return ShrinkWrap.createFromZipFile(WebArchive.class, mailDependencies);
}
@Deployment(order = 2)
public static JavaArchive createDeployment() throws IOException {
final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "camel-mail-cdi-tests.jar");
archive.addPackage(MailSessionProducer.class.getPackage());
archive.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return archive;
}
@Test
public void testMailEndpointWithCDIContext() throws Exception {
CamelContext camelctx = contextRegistry.getCamelContext("camel-mail-cdi-context");
Assert.assertNotNull("Camel context not null", camelctx);
MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockEndpoint.setExpectedMessageCount(1);
Map<String, Object> mailHeaders = new HashMap<>();
mailHeaders.put("from", "user1@localhost");
mailHeaders.put("to", "user2@localhost");
mailHeaders.put("message", "Hello Kermit");
ProducerTemplate template = camelctx.createProducerTemplate();
template.requestBodyAndHeaders("direct:start", null, mailHeaders);
mockEndpoint.assertIsSatisfied(5000);
}
}
| [
"jamesnetherton@gmail.com"
] | jamesnetherton@gmail.com |
fd5250f99b9ceb8a948958e0dcca7553002a496e | 6b7159ff2a4e40e5ca0240018ac67433c26ced6c | /src/com/example/articlesManagement/ArticleDetailActivity.java | 70f7cf71fabb0b5c77d610c5f8ff031ef2bd29ca | [] | no_license | chenxiaobin001/maple.fm | 401c4419b53b427dd2ae887d4eaa54d70ef06b71 | 713e99a20596c16feaadc4f4311c5dbc7ec45d0f | refs/heads/master | 2021-07-05T06:26:26.370841 | 2015-07-02T16:15:05 | 2015-07-02T16:15:05 | 104,799,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,460 | java | package com.example.articlesManagement;
import java.util.ArrayList;
import com.code.freeMarket.R;
import com.example.acountManagement.AccessAcountSettings;
import com.example.asyncTasks.HandleCommentsTask;
import com.example.asyncTasks.RetriveJSONAPITask;
import com.example.infoClasses.Article;
import com.github.curioustechizen.ago.RelativeTimeTextView;
import com.nhaarman.listviewanimations.appearance.simple.ScaleInAnimationAdapter;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.example.infoClasses.Comment;
import com.example.interfaces.MyAsyncTaskListener;
public class ArticleDetailActivity extends ActionBarActivity implements MyAsyncTaskListener{
private ListView listView;
private CommentArrayAdapter adapter;
private ProgressBar progressBar;
static final int REQUEST = 1; // The request code
private ViewHolder viewHolder;
private Article article;
static class ViewHolder {
public TextView articleTitleTextView;
public RelativeTimeTextView articleTimeTextView;
public TextView articleContentTextView;
public TextView articleAuthorTextView;
public TextView articleLikeTextView;
public TextView articleDislikeTextView;
public TextView articleCommentTextView;
public TextView articleEditTextView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
article = ((Article) i.getParcelableExtra("article"));
setContentView(R.layout.article_detail_activity);
listView = (ListView) findViewById(R.id.commentListView);
adapter = new CommentArrayAdapter(this, new ArrayList<Comment>());
ScaleInAnimationAdapter animationAdapter = new ScaleInAnimationAdapter(adapter);
animationAdapter.setAbsListView(listView);
listView.setAdapter(animationAdapter);
progressBar = (ProgressBar) findViewById(R.id.commentsProgress);
progressBar.setVisibility(View.GONE);
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
replyDialog((Comment) adapter.getItemAtPosition(position));
}
});
setArticleInfo();
listView.postDelayed(new Runnable() {
public void run() {
loadComments();
}
}, 1000); //Every 120000 ms (2 minutes)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.article_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_refresh:
try {
loadComments();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.action_edit:
replyDialog(new Comment());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Article article = data.getParcelableExtra("article");
viewHolder.articleTitleTextView.setText(article.getTitle());
viewHolder.articleContentTextView.setText(article.getContent());
this.article.setContent(article.getContent());
this.article.setTitle(article.getTitle());
}
}
}
private void loadComments() {
AsyncTask<String, Void, String> asyncTask = new HandleCommentsTask(this, findViewById(android.R.id.content), adapter);
new RetriveJSONAPITask(this, asyncTask, 3).execute(String.valueOf(article.getId()));
progressBar.setVisibility(View.VISIBLE);
}
private void setArticleInfo() {
viewHolder = new ViewHolder();
viewHolder.articleAuthorTextView = (TextView) findViewById(R.id.articleAuthorTextView);
viewHolder.articleTitleTextView = (TextView) findViewById(R.id.articleTitleTextView);
viewHolder.articleTimeTextView = (RelativeTimeTextView) findViewById(R.id.articleTimeTextView);
viewHolder.articleContentTextView = (TextView) findViewById(R.id.articleContentTextView);
viewHolder.articleLikeTextView = (TextView) findViewById(R.id.articleLikeTextView);
viewHolder.articleDislikeTextView = (TextView) findViewById(R.id.articleDislikeTextView);
viewHolder.articleCommentTextView = (TextView) findViewById(R.id.articleCommentTextView);
viewHolder.articleEditTextView = (TextView) findViewById(R.id.articleEditTextView);
viewHolder.articleContentTextView.setMovementMethod(new ScrollingMovementMethod());
AccessAcountSettings account = AccessAcountSettings.getInstance();
String user = account.getAccountName();
if (user != null && user.equals(article.getAuthor())) {
viewHolder.articleEditTextView.setVisibility(View.VISIBLE);
viewHolder.articleEditTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(ArticleDetailActivity.this, NewPostActivity.class);
myIntent.putExtra("type", 1); //1-edit mode, 0-new mode
myIntent.putExtra("article", article);
startActivityForResult(myIntent, REQUEST);
}
});
}
// date = sdf.parse(dateString);
// long startDate = date.getTime();
viewHolder.articleTimeTextView.setReferenceTime(article.getLastEditTimeL());
viewHolder.articleTitleTextView.setText(article.getTitle());
viewHolder.articleAuthorTextView.setText(article.getAuthor());
viewHolder.articleContentTextView.setText(article.getContent());
viewHolder.articleLikeTextView.setText("O " + String.valueOf(article.getLike()));
viewHolder.articleDislikeTextView.setText("X " + String.valueOf(article.getDislike()));
viewHolder.articleCommentTextView.setText("Reply " + String.valueOf(article.getComment()));
}
private void replyDialog(Comment comment) {
String[] args = new String[4];
AccessAcountSettings account = AccessAcountSettings.getInstance();
args[0] = account.getAccountName();
args[1] = String.valueOf(comment.getId());
args[2] = comment.getCommenter1();
args[3] = String.valueOf(article.getId());
ReplyArticleDialog dialog = ReplyArticleDialog.newInstance(args);
dialog.show(getFragmentManager(), "reply");
}
@Override
public void onAsyncTaskFinished(String foo) {
HandleCommentsTask task = new HandleCommentsTask(this, findViewById(android.R.id.content), adapter);
task.execute(foo);
}
}
| [
"lakayiiii@gmail.com"
] | lakayiiii@gmail.com |
e0b4af7fdb51748b8d54ba32608dd7f5a1df1a8c | 09c9ee4b342571423ada8186c881b4fca1660a07 | /src/main/java/org/primefaces/showcase/view/input/CheckboxView2.java | 5062ba55458e76cef63adc38508d88524a19ecbf | [] | no_license | GeorgeSalu/Primefaces | 4a0c93a14c922ab8c53066fd1675d2017c2478a5 | 9f77599c6f5edb5a7eaf891c39665b131472d9de | refs/heads/master | 2020-06-24T19:19:47.327176 | 2016-12-22T00:30:58 | 2016-12-22T00:30:58 | 74,625,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package org.primefaces.showcase.view.input;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class CheckboxView2 {
private String[] selectedConsoles;
public String[] getSelectedConsoles() {
return selectedConsoles;
}
public void setSelectedConsoles(String[] selectedConsoles) {
this.selectedConsoles = selectedConsoles;
}
}
| [
"george.salu10@gmail.com"
] | george.salu10@gmail.com |
eb5fdc31d768709a82e5c674cf453f1c7c6fee6f | f9fcde801577e7b9d66b0df1334f718364fd7b45 | /icepdf-6.0.2_P01/icepdf/core/src/org/icepdf/core/pobjects/annotations/Annotation.java | a67c154d521b99c21fb8550c74310819c7a80469 | [
"Apache-2.0"
] | permissive | numbnet/icepdf_FULL-versii | 86d74147dc107e4f2239cd4ac312f15ebbeec473 | b67e1ecb60aca88cacdca995d24263651cf8296b | refs/heads/master | 2021-01-12T11:13:57.107091 | 2016-11-04T16:43:45 | 2016-11-04T16:43:45 | 72,880,329 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 76,371 | java | /*
* Copyright 2006-2016 ICEsoft Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icepdf.core.pobjects.annotations;
import org.icepdf.core.pobjects.Dictionary;
import org.icepdf.core.pobjects.*;
import org.icepdf.core.pobjects.acroform.FieldDictionary;
import org.icepdf.core.pobjects.acroform.FieldDictionaryFactory;
import org.icepdf.core.pobjects.actions.Action;
import org.icepdf.core.pobjects.graphics.Shapes;
import org.icepdf.core.pobjects.security.SecurityManager;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.icepdf.core.util.Library;
import java.awt.*;
import java.awt.geom.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.*;
import java.util.List;
import java.util.logging.Logger;
/**
* <p>An <code>Annotation</code> class associates an object such as a note, sound, or movie with
* a location on a page of a PDF document, or provides a way to interact with
* the user by means of the mouse and keyboard.</p>
* <p/>
* <p>This class allows direct access to the a Annotations dictionary.
* Developers can take advantage of this information as they see fit. It is
* important to note that an annotations' rectangle coordinates are defined
* in the PDF document space. In order to map the rectangle coordinates to
* a view, they must be converted from the Cartesian plain to the the Java2D
* plain. The PageView method getPageBounds() can be used to locate the position
* of a page within its parent component.</p>
* <p/>
* Base class of all the specific Annotation types
* <p/>
* Taken from the PDF 1.6 spec, here is some relevant documentation,
* along with some additional commentary
* <p/>
* <h2>8.4.1 Annotation Dictionaries</h2>
* <table border=1>
* <tr>
* <td>Key</td>
* <td>Type</td>
* <td>Value</td>
* </tr>
* <tr>
* <td><b>Type</b></td>
* <td>name</td>
* <td>(<i>Optional</i>) The type of PDF object that this dictionary describes;
* if present, must be <b>Annot</b> for an annotation dictionary.</td>
* </tr>
* <tr>
* <td><b>Subtype</b></td>
* <td>name</td>
* <td>(<i>Required</i>) The type of annotation that this dictionary describes.</td>
* </tr>
* <tr>
* <td><b>Rect</b></td>
* <td>rectangle</td>
* <td>(<i>Required</i>) The <i>annotation rectangle</i>, defining the location of the
* annotation on the page in default user space units.</td>
* <td>getUserspaceLocation()</td>
* </tr>
* <tr>
* <td><b>Contents</b></td>
* <td>text string</td>
* <td>(<i>Optional</i>) Text to be displayed for the annotation or, if this type of annotation
* does not display text, an alternate description of the annotation's contents
* in human-readable form.'s contents in support of accessibility to users with
* disabilities or for other purposes (see Section 10.8.2, "Alternate Descriptions").
* See Section 8.4.5, "Annotation Types" for more details on the meaning
* of this entry for each annotation type.</td>
* </tr>
* <tr>
* <td><b>P</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.3; not used in FDF files</i>) An indirect reference to the page
* object with which this annotation is associated.</td>
* </tr>
* <tr>
* <td><b>NM</b></td>
* <td>text string</td>
* <td>(<i>Optional; PDF 1.4</i>) The <i>annotation name</i>, a text string uniquely identifying it
* among all the annotations on its page.</td>
* </tr>
* <tr>
* <td><b>M</b></td>
* <td>date or string</td>
* <td>(<i>Optional; PDF 1.1</i>) The date and time when the annotation was most
* recently modified. The preferred format is a date string as described in Section
* 3.8.3, "Dates," but viewer applications should be prepared to accept and
* display a string in any format. (See implementation note 78 in Appendix H.)</td>
* </tr>
* <tr>
* <td><b>F</b></td>
* <td>integer</td>
* <td>(<i>Optional; PDF 1.1</i>) A set of flags specifying various characteristics of the annotation
* (see Section 8.4.2, "Annotation Flags"). Default value: 0.</td>
* </tr>
* <tr>
* <td><b>BS</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) A border style dictionary specifying the characteristics of
* the annotation's border (see Section 8.4.3, "Border Styles"; see also implementation
* notes 79 and 86 in Appendix H).<br>
* <br>
* <i><b>Note:</b> This entry also specifies the width and dash pattern for the lines drawn by
* line, square, circle, and ink annotations. See the note under <b>Border</b> (below) for
* additional information.</i><br>
* <br>
* Table 8.13 summarizes the contents of the border style dictionary. If neither
* the <b>Border</b> nor the <b>BS</b> entry is present, the border is drawn as a solid line with a
* width of 1 point.</td>
* </tr>
* <tr>
* <td><b>AP</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) An <i>appearance dictionary</i> specifying how the annotation
* is presented visually on the page (see Section 8.4.4, "Appearance Streams" and
* also implementation notes 79 and 80 in Appendix H). Individual annotation
* handlers may ignore this entry and provide their own appearances.<br>
* <br>
* For convenience in managing appearance streams that are used repeatedly, the AP
* entry in a PDF document's name dictionary (see Section 3.6.3, "Name Dictionary")
* can contain a name tree mapping name strings to appearance streams. The
* name strings have no standard meanings; no PDF objects refer to appearance
* streams by name.</td>
* </tr>
* <tr>
* <td><b>AS</b></td>
* <td>name</td>
* <td>(<i>Required if the appearance dictionary <b>AP</b> contains one or more subdictionaries;
* PDF 1.2</i>) The annotation's <i>appearance state</i>, which selects the applicable
* appearance stream from an appearance subdictionary (see Section 8.4.4, "Appearance
* Streams" and also implementation note 79 in Appendix H).</td>
* </tr>
* <tr>
* <td><b>Border</b></td>
* <td>array</td>
* <td>(<i>Optional</i>) An array specifying the characteristics of the annotation's border.
* The border is specified as a rounded rectangle.<br>
* <br>
* In PDF 1.0, the array consists of three numbers defining the horizontal corner
* radius, vertical corner radius, and border width, all in default user space
* units. If the corner radii are 0, the border has square (not rounded) corners; if
* the border width is 0, no border is drawn. (See implementation note 81 in
* Appendix H.) <br>
* <br>
* In PDF 1.1, the array may have a fourth element, an optional <i>dash array</i>
* defining a pattern of dashes and gaps to be used in drawing the border. The
* dash array is specified in the same format as in the line dash pattern parameter
* of the graphics state (see "Line Dash Pattern" on page 187). For example, a
* <b>Border</b> value of [0 0 1 [3 2]] specifies a border 1 unit wide, with square corners,
* drawn with 3-unit dashes alternating with 2-unit gaps. Note that no
* dash phase is specified; the phase is assumed to be 0. (See implementation
* note 82 in Appendix H.)<br>
* <br>
* <i><b>Note:</b> In PDF 1.2 or later, this entry may be ignored in favor of the <b>BS</b>
* entry (see above); see implementation note 86 in Appendix H.</i><br>
* <br>
* Default value: [0 0 1].</td>
* </tr>
* <tr>
* <td><b>BE</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.5</i>) Some annotations (square, circle, and polygon) may
* have a <b>BE</b> entry, which is a <i>border effect</i> dictionary that specifies an effect
* to be applied to the border of the annotations. Its entries are listed in Table 8.14.</td>
* </tr>
* <tr>
* <td><b>C</b></td>
* <td>array</td>
* <td>(<i>Optional; PDF 1.1</i>) An array of three numbers in the range 0.0 to 1.0, representing
* the components of a color in the <b>DeviceRGB</b> color space. This color is
* used for the following purposes:
* <ul>
* <li>The background of the annotation's icon when closed
* <li>The title bar of the annotation's pop-up window
* <li>The border of a link annotation
* </ul></td>
* </tr>
* <tr>
* <td><b>A</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.1</i>) An action to be performed when the annotation is activated
* (see Section 8.5, "Actions").<br>
* <br>
* <i><b>Note:</b> This entry is not permitted in link annotations if a Dest entry is present
* (see "Link Annotations" on page 587). Also note that the A entry in movie annotations
* has a different meaning (see "Movie Annotations" on page 601).</i></td>
* </tr>
* <tr>
* <td><b>AA</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) An additional-actions dictionary defining the annotation's
* behavior in response to various trigger events (see Section 8.5.2,
* "Trigger Events"). At the time of publication, this entry is used only by widget
* annotations.</td>
* </tr>
* <tr>
* <td><b>StructParent</b></td>
* <td>integer</td>
* <td>(<i>(Required if the annotation is a structural content item; PDF 1.3</i>) The integer
* key of the annotation's entry in the structural parent tree (see "Finding Structure
* Elements from Content Items" on page 797).</td>
* </tr>
* <tr>
* <td><b>OC</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.5</i>) An optional content group or optional content membership
* dictionary (see Section 4.10, "Optional Content") specifying the optional
* content properties for the annotation. Before the annotation is drawn, its visibility
* is determined based on this entry as well as the annotation flags specified
* in the <b>F</b> entry (see Section 8.4.2, "Annotation Flags"). If it is determined
* to be invisible, the annotation is skipped, as if it were not in the document.</td>
* </tr>
* </table>
* <p/>
* <p/>
* <h2>8.4.2 Annotation Flags</h2>
* The value of the annotation dictionary's <b>F</b> entry is an unsigned 32-bit integer containing
* flags specifying various characteristics of the annotation. Bit positions
* within the flag word are numbered from 1 (low-order) to 32 (high-order). Table
* 8.12 shows the meanings of the flags; all undefined flag bits are reserved and must
* be set to 0.
* <table border=1>
* <tr>
* <td>Bit position</td>
* <td>Name</td>
* <td>Meaning</td>
* </tr>
* <tr>
* <td>1</td>
* <td>Invisible</td>
* <td>If set, do not display the annotation if it does not belong to one of the standard
* annotation types and no annotation handler is available. If clear, display such an
* unknown annotation using an appearance stream specified by its appearance
* dictionary, if any (see Section 8.4.4, "Appearance Streams").</td>
* </tr>
* <tr>
* <td>2</td>
* <td>Hidden</td>
* <td>If set, do not display or print the annotation or allow it to interact
* with the user, regardless of its annotation type or whether an annotation
* handler is available. In cases where screen space is limited, the ability to hide
* and show annotations selectively can be used in combination with appearance
* streams (see Section 8.4.4, "Appearance Streams") to display auxiliary pop-up
* information similar in function to online help systems. (See implementation
* note 83 in Appendix H.)</td>
* </tr>
* <tr>
* <td>3</td>
* <td>Print</td>
* <td>If set, print the annotation when the page is printed. If clear, never
* print the annotation, regardless of whether it is displayed on the screen. This
* can be useful, for example, for annotations representing interactive pushbuttons,
* which would serve no meaningful purpose on the printed page. (See
* implementation note 83 in Appendix H.)</td>
* </tr>
* <tr>
* <td>4</td>
* <td>NoZoom</td>
* <td>If set, do not scale the annotation's appearance to match the magnification
* of the page. The location of the annotation on the page (defined by the
* upper-left corner of its annotation rectangle) remains fixed, regardless of the
* page magnification. See below for further discussion.</td>
* </tr>
* <tr>
* <td>5</td>
* <td>NoRotate</td>
* <td>If set, do not rotate the annotation's appearance to match the rotation
* of the page. The upper-left corner of the annotation rectangle remains in a fixed
* location on the page, regardless of the page rotation. See below for further discussion.</td>
* </tr>
* <tr>
* <td>6</td>
* <td>NoView</td>
* <td>If set, do not display the annotation on the screen or allow it to
* interact with the user. The annotation may be printed (depending on the setting
* of the Print flag) but should be considered hidden for purposes of on-screen
* display and user interaction.</td>
* </tr>
* <tr>
* <td>7</td>
* <td>ReadOnly</td>
* <td>If set, do not allow the annotation to interact with the user. The
* annotation may be displayed or printed (depending on the settings of the
* NoView and Print flags) but should not respond to mouse clicks or change its
* appearance in response to mouse motions.<br>
* <br>
* <i><b>Note:</b> This flag is ignored for widget annotations; its function is subsumed by the
* ReadOnly flag of the associated form field (see Table 8.66 on page 638).</i></td>
* </tr>
* <tr>
* <td>8</td>
* <td>Locked</td>
* <td>If set, do not allow the annotation to be deleted or its properties (including
* position and size) to be modified by the user. However, this flag does
* not restrict changes to the annotation's contents, such as the value of a form
* field. (See implementation note 84 in Appendix H.)</td>
* </tr>
* <tr>
* <td>9</td>
* <td>ToggleNoView</td>
* <td>If set, invert the interpretation of the NoView flag for certain events. A
* typical use is to have an annotation that appears only when a mouse cursor is
* held over it; see implementation note 85 in Appendix H.</td>
* </tr>
* </table>
*
* @author Mark Collette
* @since 2.5
*/
public abstract class Annotation extends Dictionary {
private static final Logger logger =
Logger.getLogger(Annotation.class.toString());
public static final Name TYPE = new Name("Annot");
public static final Name RESOURCES_VALUE = new Name("Resources");
public static final Name BBOX_VALUE = new Name("BBox");
public static final Name PARENT_KEY = new Name("Parent");
/**
* Dictionary constants for Annotations.
*/
public static final Name TYPE_VALUE = new Name("Annot");
/**
* Annotation subtype and types.
*/
public static final Name SUBTYPE_LINK = new Name("Link");
public static final Name SUBTYPE_LINE = new Name("Line");
public static final Name SUBTYPE_SQUARE = new Name("Square");
public static final Name SUBTYPE_CIRCLE = new Name("Circle");
public static final Name SUBTYPE_POLYGON = new Name("Polygon");
public static final Name SUBTYPE_POLYLINE = new Name("PolyLine");
public static final Name SUBTYPE_HIGHLIGHT = new Name("Highlight");
public static final Name SUBTYPE_POPUP = new Name("Popup");
public static final Name SUBTYPE_WIDGET = new Name("Widget");
public static final Name SUBTYPE_INK = new Name("Ink");
public static final Name SUBTYPE_FREE_TEXT = new Name("FreeText");
public static final Name SUBTYPE_TEXT = new Name("Text");
/**
* If set, do not display the annotation if it does not belong to one of the
* standard annotation types and no annotation handler is available. If clear,
* display such an unknown annotation using an appearance stream specified
* by its appearance dictionary, if any
*/
public static final int FLAG_INVISIBLE = 0x0001;
/**
* If set, do not display or print the annotation or allow it to interact
* with the user, regardless of its annotation type or whether an annotation
* handler is available.
*/
public static final int FLAG_HIDDEN = 0x0002;
/**
* If set, print the annotation when the page is printed. If clear, never
* print the annotation, regardless of whether it is displayed on the screen.
*/
public static final int FLAG_PRINT = 0x0004;
/**
* If set, do not scale the annotation’s appearance to match the magnification
* of the page. The location of the annotation on the page (defined by the
* upper-left corner of its annotation rectangle) shall remain fixed,
* regardless of the page magnification. See further discussion following
* this Table.
*/
public static final int FLAG_NO_ZOOM = 0x0008;
/**
* If set, do not rotate the annotation’s appearance to match the rotation
* of the page. The upper-left corner of the annotation rectangle shall
* remain in a fixed location on the page, regardless of the page rotation.
* See further discussion following this Table.
*/
public static final int FLAG_NO_ROTATE = 0x0010;
/**
* If set, do not display the annotation on the screen or allow it to interact
* with the user. The annotation may be printed (depending on the setting of
* the Print flag) but should be considered hidden for purposes of on-screen
* display and user interaction.
*/
public static final int FLAG_NO_VIEW = 0x0020;
/**
* If set, do not allow the annotation to interact with the user. The
* annotation may be displayed or printed (depending on the settings of the
* NoView and Print flags) but should not respond to mouse clicks or change
* its appearance in response to mouse motions.
* <p/>
* This flag shall be ignored for widget annotations; its function is
* subsumed by the ReadOnly flag of the associated form field.
*/
public static final int FLAG_READ_ONLY = 0x0040;
/**
* If set, do not allow the annotation to be deleted or its properties
* (including position and size) to be modified by the user. However, this
* flag does not restrict changes to the annotation’s contents, such as the
* value of a form field.
*/
public static final int FLAG_LOCKED = 0x0080;
/**
* If set, invert the interpretation of the NoView flag for certain events.
*/
public static final int FLAG_TOGGLE_NO_VIEW = 0x0100;
/**
* If set, do not allow the contents of the annotation to be modified by the
* user. This flag does not restrict deletion of the annotation or changes
* to other annotation properties, such as position and size.
*/
public static final int FLAG_LOCKED_CONTENTS = 0x0200;
/**
* Border style
*/
public static final Name BORDER_STYLE_KEY = new Name("BS");
/**
* The annotation location on the page in user space units.
*/
public static final Name RECTANGLE_KEY = new Name("Rect");
/**
* The action to be performed whenteh annotation is activated.
*/
public static final Name ACTION_KEY = new Name("A");
/**
* Page that this annotation is associated with.
*/
public static final Name PARENT_PAGE_KEY = new Name("P");
/**
* Annotation border characteristics.
*/
public static final Name BORDER_KEY = new Name("Border");
/**
* Annotation border characteristics.
*/
public static final Name FLAG_KEY = new Name("F");
/**
* RGB colour value for background, titlebars and link annotation borders
*/
public static final Name COLOR_KEY = new Name("C");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page.
*/
public static final Name APPEARANCE_STREAM_KEY = new Name("AP");
/**
* Appearance state selecting default from multiple AP's.
*/
public static final Name APPEARANCE_STATE_KEY = new Name("AS");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for normal display.
*/
public static final Name APPEARANCE_STREAM_NORMAL_KEY = new Name("N");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for rollover display.
*/
public static final Name APPEARANCE_STREAM_ROLLOVER_KEY = new Name("R");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for down display.
*/
public static final Name APPEARANCE_STREAM_DOWN_KEY = new Name("D");
/**
* (Optional) Text that shall be displayed for the annotation or, if this
* type of annotation does not display text, an alternate description of the
* annotation’s contents in human-readable form. In either case, this text
* is useful when extracting the document’s contents in support of accessibility
* to users with disabilities or for other purposes (see 14.9.3,
* “Alternate Descriptions”). See 12.5.6, “Annotation Types” for more details
* on the meaning of this entry for each annotation type.
*/
public static final Name CONTENTS_KEY = new Name("Contents");
/**
* The date and time when the annotation was most recently modified. The
* format should be a date string as described in 7.9.4, “Dates,” but
* conforming readers shall accept and display a string in any format.
*/
public static final Name M_KEY = new Name("M");
/**
* (Optional; PDF 1.4) The annotation name, a text string uniquely
* identifying it among all the annotations on its page.
*/
public static final Name NM_KEY = new Name("NM");
/**
* Border property indexes for the border vector, only applicable
* if the border style has not been set.
*/
public static final int BORDER_HORIZONTAL_CORNER_RADIUS = 0;
public static final int BORDER_VERTICAL_CORNER_RADIUS = 1;
public static final int BORDER_WIDTH = 2;
public static final int BORDER_DASH = 3;
/**
* Annotion may or may not have a visible rectangle border
*/
public static final int VISIBLE_RECTANGLE = 1;
public static final int INVISIBLE_RECTANGLE = 0;
protected PropertyChangeSupport changeSupport;
/**
* Debug flag to turn off appearance stream compression for easier
* human file reading.
*/
protected static boolean compressAppearanceStream = true;
protected HashMap<Name, Appearance> appearances = new HashMap<Name, Appearance>(3);
protected Name currentAppearance;
// modified date.
protected PDate modifiedDate;
protected boolean hasBlendingMode;
// security manager need for decrypting strings.
protected SecurityManager securityManager;
// type of annotation
protected Name subtype;
// content flag
protected String content;
// borders style of the annotation, can be null
protected BorderStyle borderStyle;
// border defined by vector
protected List border;
// border color of annotation.
protected Color color;
// annotation bounding rectangle in user space.
protected Rectangle2D.Float userSpaceRectangle;
// test for borderless annotation types
protected boolean canDrawBorder;
/**
* Creates a new instance of an Annotation.
*
* @param l document library.
* @param h dictionary entries.
*/
public Annotation(Library l, HashMap h) {
super(l, h);
}
/**
* Should only be called from Parser, Use AnnotationFactory if you
* creating a new annotation.
*
* @param library document library
* @param hashMap annotation properties.
* @return annotation instance.
*/
@SuppressWarnings("unchecked")
public static Annotation buildAnnotation(Library library, HashMap hashMap) {
Annotation annot = null;
Name subType = (Name) hashMap.get(SUBTYPE_KEY);
if (subType != null) {
if (subType.equals(Annotation.SUBTYPE_LINK)) {
annot = new LinkAnnotation(library, hashMap);
}
// highlight version of a TextMarkup annotation.
else if (subType.equals(TextMarkupAnnotation.SUBTYPE_HIGHLIGHT) ||
subType.equals(TextMarkupAnnotation.SUBTYPE_STRIKE_OUT) ||
subType.equals(TextMarkupAnnotation.SUBTYPE_UNDERLINE)) {
annot = new TextMarkupAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_LINE)) {
annot = new LineAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_SQUARE)) {
annot = new SquareAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_CIRCLE)) {
annot = new CircleAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_INK)) {
annot = new InkAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_FREE_TEXT)) {
annot = new FreeTextAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_TEXT)) {
annot = new TextAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_POPUP)) {
annot = new PopupAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_WIDGET)) {
Name fieldType = library.getName(hashMap, FieldDictionary.FT_KEY);
if (fieldType == null) {
// get type from parent object if we the widget and field dictionary aren't combined.
Object tmp = library.getObject(hashMap, FieldDictionary.PARENT_KEY);
if (tmp instanceof HashMap) {
fieldType = library.getName((HashMap) tmp, FieldDictionary.FT_KEY);
}
}
if (FieldDictionaryFactory.TYPE_BUTTON.equals(fieldType)) {
annot = new ButtonWidgetAnnotation(library, hashMap);
} else if (FieldDictionaryFactory.TYPE_CHOICE.equals(fieldType)) {
annot = new ChoiceWidgetAnnotation(library, hashMap);
} else if (FieldDictionaryFactory.TYPE_TEXT.equals(fieldType)) {
annot = new TextWidgetAnnotation(library, hashMap);
}
// todo signatures widget.
else if (FieldDictionaryFactory.TYPE_SIGNATURE.equals(fieldType)) {
annot = new WidgetAnnotation(library, hashMap);
} else {
annot = new WidgetAnnotation(library, hashMap);
}
}
}
if (annot == null) {
annot = new GenericAnnotation(library, hashMap);
}
// annot.init();
return annot;
}
public static void setCompressAppearanceStream(boolean compressAppearanceStream) {
Annotation.compressAppearanceStream = compressAppearanceStream;
}
@SuppressWarnings("unchecked")
public void init() {
super.init();
// type of Annotation
subtype = (Name) getObject(SUBTYPE_KEY);
securityManager = library.getSecurityManager();
content = library.getString(entries, CONTENTS_KEY);
// no borders for the following types, not really in the
// spec for some reason, Acrobat doesn't render them.
// todo add other annotations types.
canDrawBorder = !(
SUBTYPE_LINE.equals(subtype) ||
SUBTYPE_CIRCLE.equals(subtype) ||
SUBTYPE_SQUARE.equals(subtype) ||
SUBTYPE_POLYGON.equals(subtype) ||
SUBTYPE_POLYLINE.equals(subtype));
// parse out border style if available
Object BS = getObject(BORDER_STYLE_KEY);
if (BS != null) {
if (BS instanceof HashMap) {
borderStyle = new BorderStyle(library, (HashMap) BS);
} else if (BS instanceof BorderStyle) {
borderStyle = (BorderStyle) BS;
}
}
// else build out a border style from the old B entry or create
// a default invisible border.
else {
HashMap<Name, Object> borderMap = new HashMap<Name, Object>();
// get old school border
Object borderObject = getObject(BORDER_KEY);
if (borderObject != null && borderObject instanceof List) {
border = (List) borderObject;
// copy over the properties to border style.
if (border.size() == 3) {
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_SOLID);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, border.get(2));
} else if (border.size() == 4) {
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_DASHED);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, border.get(2));
borderMap.put(BorderStyle.BORDER_DASH_KEY, Arrays.asList(3f));
}
} else {
// default to invisible border
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_SOLID);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, 0f);
}
borderStyle = new BorderStyle(library, borderMap);
entries.put(BORDER_STYLE_KEY, borderStyle);
}
// parse out border colour, specific to link annotations.
color = null; // null as some borders are set as transparent via no colour
List C = (List) getObject(COLOR_KEY);
// parse thought rgb colour.
if (C != null && C.size() >= 3) {
float red = ((Number) C.get(0)).floatValue();
float green = ((Number) C.get(1)).floatValue();
float blue = ((Number) C.get(2)).floatValue();
red = Math.max(0.0f, Math.min(1.0f, red));
green = Math.max(0.0f, Math.min(1.0f, green));
blue = Math.max(0.0f, Math.min(1.0f, blue));
color = new Color(red, green, blue);
}
// if no creation date check for M or modified.
Object value = library.getObject(entries, M_KEY);
if (value != null && value instanceof StringObject) {
StringObject text = (StringObject) value;
modifiedDate = new PDate(securityManager,
text.getDecryptedLiteralString(securityManager));
}
// process the streams if available.
Object AP = getObject(APPEARANCE_STREAM_KEY);
if (AP instanceof HashMap) {
// assign the default AS key as the default appearance
currentAppearance = APPEARANCE_STREAM_NORMAL_KEY;
Name appearanceState = (Name) getObject(APPEARANCE_STATE_KEY);
if (appearanceState == null) {
appearanceState = APPEARANCE_STREAM_NORMAL_KEY;
}
// The annotations normal appearance.
Object appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_NORMAL_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_NORMAL_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_NORMAL_KEY,
appearance));
appearances.get(APPEARANCE_STREAM_NORMAL_KEY).setSelectedName(appearanceState);
}
// (Optional) The annotation’s rollover appearance.
// Default value: the value of the N entry.
appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_ROLLOVER_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_ROLLOVER_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_ROLLOVER_KEY,
appearance));
}
// (Optional) The annotation’s down appearance.
// Default value: the value of the N entry.
appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_DOWN_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_DOWN_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_DOWN_KEY,
appearance));
}
} else {
// new annotation, so setup the default appearance states.
Appearance newAppearance = new Appearance();
HashMap appearanceDictionary = new HashMap();
Rectangle2D rect = getUserSpaceRectangle();
if (rect == null){
// we need a rect in order to render correctly, bail if not found. PDF-964
throw new IllegalStateException("Annotation is missing required /rect value");
}
if (rect.getWidth() <= 1) {
rect.setRect(rect.getX(), rect.getY(), 15, rect.getHeight());
}
if (rect.getHeight() <= 1) {
rect.setRect(rect.getX(), rect.getY(), rect.getWidth(), 15);
}
appearanceDictionary.put(BBOX_VALUE, rect);
newAppearance.addAppearance(APPEARANCE_STREAM_NORMAL_KEY,
new AppearanceState(library, appearanceDictionary));
appearances.put(APPEARANCE_STREAM_NORMAL_KEY, newAppearance);
currentAppearance = APPEARANCE_STREAM_NORMAL_KEY;
}
}
private Appearance parseAppearanceDictionary(Name appearanceDictionary,
Object streamOrDictionary) {
Appearance appearance = new Appearance();
// iterate over all of the keys so we can index the various annotation
// state names.
if (streamOrDictionary instanceof HashMap) {
HashMap dictionary = (HashMap) streamOrDictionary;
Set keys = dictionary.keySet();
Object value;
for (Object key : keys) {
value = dictionary.get(key);
if (value instanceof Reference) {
appearance.addAppearance((Name) key,
new AppearanceState(library, dictionary,
library.getObject((Reference) value)));
}
}
}
// single entry so assign is using the default key name
else {
appearance.addAppearance(appearanceDictionary,
new AppearanceState(library, entries, streamOrDictionary));
}
return appearance;
}
/**
* Gets the type of annotation that this dictionary describes.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getSubType()
*
* @return subtype of annotation
*/
public Name getSubType() {
return library.getName(entries, SUBTYPE_KEY);
}
public void setSubtype(Name subtype) {
entries.put(SUBTYPE_KEY, subtype);
this.subtype = subtype;
}
/**
* Gets the annotation rectangle, and defines the location of the annotation on
* the page in default user space units.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getRectangle()
*
* @return rectangle of annotation
*/
public Rectangle2D.Float getUserSpaceRectangle() {
if (userSpaceRectangle == null) {
Object tmp = getObject(RECTANGLE_KEY);
if (tmp instanceof List) {
userSpaceRectangle = library.getRectangle(entries, RECTANGLE_KEY);
}
}
return userSpaceRectangle;
}
/**
* Sets the users page rectangle for this annotation action instance
*/
public void setUserSpaceRectangle(Rectangle2D.Float rect) {
if (userSpaceRectangle != null && rect != null) {
userSpaceRectangle = new Rectangle2D.Float(rect.x, rect.y,
rect.width, rect.height);
entries.put(Annotation.RECTANGLE_KEY,
PRectangle.getPRectangleVector(userSpaceRectangle));
}
}
public void setBBox(Rectangle bbox) {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
appearanceState.setBbox(bbox);
}
public Rectangle2D getBbox() {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
return appearanceState.getBbox();
}
protected void resetNullAppearanceStream() {
// try and generate an appearance stream.
if (!hasAppearanceStream()) {
Object tmp = getObject(RECTANGLE_KEY);
Rectangle2D.Float rectangle = null;
if (tmp instanceof java.util.List) {
rectangle = library.getRectangle(entries, RECTANGLE_KEY);
}
if (rectangle != null) {
setBBox(rectangle.getBounds());
}
resetAppearanceStream(new AffineTransform());
}
}
public Name getCurrentAppearance() {
return currentAppearance;
}
public void setCurrentAppearance(Name currentAppearance) {
this.currentAppearance = currentAppearance;
}
/**
* Creates a Java2D strok from the propties tht make up the BorderStyle object.
*
* @return dashed or solid stoke.
*/
public Stroke getBorderStyleStroke() {
if (borderStyle.isStyleDashed()) {
return new BasicStroke(
borderStyle.getStrokeWidth(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
borderStyle.getStrokeWidth() * 2.0f, borderStyle.getDashArray(), 0.0f);
} else {
return new BasicStroke(borderStyle.getStrokeWidth());
}
}
/**
* Gets the action to be performed when the annotation is activated.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getAction()
*
* @return action to be activated, if no action, null is returned.
*/
public org.icepdf.core.pobjects.actions.Action getAction() {
Object tmp = library.getDictionary(entries, ACTION_KEY);
// initial parse will likely have the action as a dictionary, so we
// create the new action object on the fly. However it is also possible
// that we are parsing an action that has no type specification and
// thus we can't use the parser to create the new action.
if (tmp != null) {
Action action = Action.buildAction(library, (HashMap) tmp);
// assign reference if applicable
if (action != null &&
library.isReference(entries, ACTION_KEY)) {
action.setPObjectReference(
library.getReference(entries, ACTION_KEY));
}
return action;
}
// subsequent new or edit actions will put in a reference and property
// dictionary entry.
tmp = getObject(ACTION_KEY);
if (tmp != null && tmp instanceof Action) {
return (Action) tmp;
}
return null;
}
/**
* Adds the specified action to this annotation instance. If the annotation
* instance already has an action then this action replaces it.
* <p/>
* todo: future enhancement add support of next/muliple action chains.
*
* @param action action to add to this annotation. This action must
* be created using the the ActionFactory in order to correctly setup
* the Pobject reference.
* @return action that was added to Annotation, null if it was not success
* fully added.
*/
public Action addAction(Action action) {
// if no object ref we bail early.
if (action.getPObjectReference() == null) {
logger.severe("Addition of action was rejected null Object reference "
+ action);
return null;
}
// gen instance of state manager
StateManager stateManager = library.getStateManager();
// check if there is a 'dest' entry, if so we need to add this as a new
// action, flag it for later processing.
boolean isDestKey = getObject(LinkAnnotation.DESTINATION_KEY) != null;
// check the annotation dictionary for an instance of an existing action
if (getObject(ACTION_KEY) != null) {
// if found we will add the new action at the beginning of the
// next chain.
boolean isReference = library.isReference(getEntries(),
ACTION_KEY);
// we have a next action that is an object, mark it for delete.
// Because its a reference no need to flag the annotation as changed.
if (isReference) {
// mark this action for delete.
Action oldAction = (Action) action.getObject(ACTION_KEY);
oldAction.setDeleted(true);
stateManager.addChange(new PObject(oldAction,
oldAction.getPObjectReference()));
}
// not a reference, we have an inline dictionary and we'll be
// clearing it later, so we only need to add this annotation
// to the state manager.
else {
getEntries().remove(ACTION_KEY);
stateManager.addChange(new PObject(this, getPObjectReference()));
}
}
// add the new action as per usual
getEntries().put(ACTION_KEY, action.getPObjectReference());
stateManager.addChange(new PObject(this, getPObjectReference()));
// if this is a link annotation and there is a dest, we need to remove
// as it is not allowed once an action has bee added.
if (isDestKey && this instanceof LinkAnnotation) {
// remove the dest key from the dictionary
this.getEntries().remove(LinkAnnotation.DESTINATION_KEY);
// mark the annotation as changed.
stateManager.addChange(new PObject(this, getPObjectReference()));
}
// add the new action to the state manager.
action.setNew(true);
stateManager.addChange(new PObject(action, action.getPObjectReference()));
// add it to the library so we can get it again.
library.addObject(action, action.getPObjectReference());
return action;
}
/**
* Deletes the annotation action specified as a paramater. If an instance
* of the specified action can not be found, no delete is make.
*
* @param action action to remove
* @return true if the delete was successful, false otherwise.
*/
public boolean deleteAction(Action action) {
// gen instance of state manager
StateManager stateManager = library.getStateManager();
if (getObject(ACTION_KEY) != null) {
// mark this action for delete.
Action currentAction = getAction();
if (currentAction.similar(action)) {
// clear the action key for the annotation and add it as changed.
// add the new action to the annotation
getEntries().remove(ACTION_KEY);
currentAction.setDeleted(true);
// mark the action as changed.
stateManager.addChange(new PObject(currentAction,
currentAction.getPObjectReference()));
// mark the action as change.d
stateManager.addChange(new PObject(this, getPObjectReference()));
return true;
}
}
return false;
}
/**
* Update the current annotation action with this entry. This is very similar
* to add but this method will return false if there was no previous annotation.
* In such a case a call to addAction should be made.
*
* @param action action to update
* @return true if the update was successful, othere; false.
*/
public boolean updateAction(Action action) {
// get instance of state manager
StateManager stateManager = library.getStateManager();
if (getObject(ACTION_KEY) != null) {
Action currentAction = getAction();
// check if we are updating an existing instance
if (!currentAction.similar(action)) {
stateManager.addChange(new PObject(action,
action.getPObjectReference()));
currentAction.setDeleted(true);
stateManager.addChange(new PObject(currentAction,
currentAction.getPObjectReference()));
}
// add the action to the annotation
getEntries().put(ACTION_KEY, action.getPObjectReference());
stateManager.addChange(new PObject(action,
action.getPObjectReference()));
return true;
}
return false;
}
public boolean allowScreenNormalMode() {
return allowScreenOrPrintRenderingOrInteraction() && !getFlagNoView();
}
public boolean allowScreenRolloverMode() {
return allowScreenOrPrintRenderingOrInteraction() && !(getFlagNoView()
&& !getFlagToggleNoView()) && !getFlagReadOnly();
}
public boolean allowScreenDownMode() {
return allowScreenOrPrintRenderingOrInteraction() && !(getFlagNoView() &&
!getFlagToggleNoView()) && !getFlagReadOnly();
}
public boolean allowPrintNormalMode() {
return allowScreenOrPrintRenderingOrInteraction() && getFlagPrint();
}
public boolean allowAlterProperties() {
return !getFlagLocked();
}
public BorderStyle getBorderStyle() {
return borderStyle;
}
public void setBorderStyle(BorderStyle borderStyle) {
this.borderStyle = borderStyle;
entries.put(Annotation.BORDER_STYLE_KEY, this.borderStyle);
}
@SuppressWarnings("unchecked")
public List<Number> getBorder() {
return border;
}
public Object getParentAnnotation() {
Annotation parent = null;
Object ob = getObject(PARENT_KEY);
if (ob instanceof Reference)
ob = library.getObject((Reference) ob);
if (ob instanceof Annotation)
parent = (Annotation) ob;
else if (ob instanceof HashMap)
return FieldDictionaryFactory.buildField(library, (HashMap) ob);
return parent;
}
public Page getPage() {
Page page = (Page) getObject(PARENT_PAGE_KEY);
if (page == null) {
Object annot = getParentAnnotation();
if (annot instanceof Annotation)
page = ((Annotation) annot).getPage();
}
return page;
}
/**
* Gets the Link type, can be either VISIBLE_RECTANGLE or
* INVISIBLE_RECTANGLE, it all depends on the if the border or BS has
* border width > 0.
*
* @return VISIBLE_RECTANGLE if the annotation has a visible borde, otherwise
* INVISIBLE_RECTANGLE
*/
public int getBorderType() {
// border style has W value for border with
if (borderStyle != null) {
if (borderStyle.getStrokeWidth() > 0) {
return VISIBLE_RECTANGLE;
}
}
// look for a border, 0,0,1 has one, 0,0,0 doesn't
else if (border != null) {
if (border.size() >= 3 && ((Number) border.get(2)).floatValue() > 0) {
return VISIBLE_RECTANGLE;
}
}
// should never happen
return INVISIBLE_RECTANGLE;
}
/**
* Gets the Annotation border style for the given annotation. If no
* annotation line style can be found the default value of BORDER_STYLE_SOLID
* is returned. Otherwise the bordStyle and border dictionaries are used
* to deduse a line style.
*
* @return BorderSTyle line constants.
*/
public Name getLineStyle() {
// check for border style
if (borderStyle != null) {
return borderStyle.getBorderStyle();
}
// check the border entry, will be solid or dashed
else if (border != null) {
if (border.size() > 3) {
return BorderStyle.BORDER_STYLE_DASHED;
} else if (((Number) border.get(2)).floatValue() > 1) {
return BorderStyle.BORDER_STYLE_SOLID;
}
}
// default value
return BorderStyle.BORDER_STYLE_SOLID;
}
/**
* Gets the line thickness assoicated with this annotation.
*
* @return point value used when drawing line thickness.
*/
public float getLineThickness() {
// check for border style
if (borderStyle != null) {
return borderStyle.getStrokeWidth();
}
// check the border entry, will be solid or dashed
else if (border != null) {
if (border.size() >= 3) {
return ((Number) border.get(2)).floatValue();
}
}
return 0;
}
/**
* Checks to see if the annotation has defined a drawable border width.
*
* @return true if a border will be drawn; otherwise, false.
*/
public boolean isBorder() {
boolean borderWidth = false;
Object border = getObject(BORDER_KEY);
if (border != null && border instanceof List) {
List borderProps = (List) border;
if (borderProps.size() == 3) {
borderWidth = ((Number) borderProps.get(2)).floatValue() > 0;
}
}
return (getBorderStyle() != null &&
getBorderStyle().getStrokeWidth() > 0) || borderWidth;
}
public void render(Graphics2D origG, int renderHintType,
float totalRotation, float userZoom,
boolean tabSelected) {
if (!allowScreenOrPrintRenderingOrInteraction())
return;
if (renderHintType == GraphicsRenderingHints.SCREEN && !allowScreenNormalMode())
return;
if (renderHintType == GraphicsRenderingHints.PRINT && !allowPrintNormalMode())
return;
//System.out.println("render(-) " + this);
Rectangle2D.Float rect = getUserSpaceRectangle();
// Show original ractangle, without taking into consideration NoZoom and NoRotate
//System.out.println("Original rectangle: " + rect);
//origG.setColor( Color.blue );
//origG.draw( rect );
//origG.setColor( Color.red );
//Line2D.Double topLine = new Line2D.Double( rect.getMinX(), rect.getMaxY(), rect.getMaxX(), rect.getMaxY() );
//origG.draw( topLine );
//origG.setColor( Color.yellow );
//Line2D.Double bottomLine = new Line2D.Double( rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMinY() );
//origG.draw( bottomLine );
AffineTransform oldAT = origG.getTransform();
Shape oldClip = origG.getClip();
// Simply uncomment the //// lines to use a different Graphics object
Graphics2D g = origG;
////Graphics2D g = (Graphics2D) origG.create();
AffineTransform at = new AffineTransform(oldAT);
// move canvas to paint annotation for page rendering only.
at.translate(rect.getMinX(), rect.getMinY());
boolean noRotate = getFlagNoRotate();
if (noRotate) {
float unRotation = -totalRotation;
while (unRotation < 0.0f)
unRotation += 360.0f;
while (unRotation > 360.0f)
unRotation -= 360.0f;
if (unRotation == -0.0f)
unRotation = 0.0f;
if (unRotation != 0.0) {
double radians = Math.toRadians(unRotation); // unRotation * Math.PI / 180.0
AffineTransform rotationTransform =
AffineTransform.getRotateInstance(radians);
Point2D.Double origTopLeftCorner = new Point2D.Double(0.0, Math.abs(rect.getHeight()));
Point2D rotatedTopLeftCorner = rotationTransform.transform(origTopLeftCorner, null);
at.translate(origTopLeftCorner.getX() - rotatedTopLeftCorner.getX(),
origTopLeftCorner.getY() - rotatedTopLeftCorner.getY());
at.rotate(radians);
}
}
boolean noZoom = getFlagNoZoom();
if (noZoom) {
double scaleY = Math.abs(at.getScaleY());
if (scaleY != 1.0) {
double scaleX = Math.abs(at.getScaleX());
double rectHeight = Math.abs(rect.getHeight());
double resizedY = rectHeight * ((scaleY - 1.0) / scaleY);
at.translate(0.0, resizedY);
at.scale(1.0 / scaleX, 1.0 / scaleY);
}
}
GraphicsRenderingHints grh = GraphicsRenderingHints.getDefault();
g.setRenderingHints(grh.getRenderingHints(renderHintType));
g.setTransform(at);
Shape preAppearanceStreamClip = g.getClip();
// Shape annotationShape = deriveDrawingRectangle();
g.clip(deriveDrawingRectangle());
renderAppearanceStream(g);
g.setTransform(at);
g.setClip(preAppearanceStreamClip);
if (tabSelected) {
renderBorderTabSelected(g);
} else {
renderBorder(g);
}
g.setTransform(oldAT);
g.setClip(oldClip);
////g.dispose();
// Show the top left corner, that NoZoom and NoRotate annotations cling to
//origG.setColor( Color.blue );
//Rectangle2D.Double topLeft = new Rectangle2D.Double(
// rect.getMinX(), rect.getMaxY()-3, 3, 3 );
//origG.fill( topLeft );
}
protected void renderAppearanceStream(Graphics2D g) {
Appearance appearance = appearances.get(currentAppearance);
if (appearance == null) return;
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
if (appearanceState.getShapes() != null) {
AffineTransform matrix = appearanceState.getMatrix();
Rectangle2D bbox = appearanceState.getBbox();
// g.setColor( Color.blue );
// Rectangle2D.Float newRect = deriveDrawingRectangle();
// g.draw( newRect );
// step 1. appearance bounding box (BBox) is transformed, using
// Matrix, to produce a quadrilateral with arbitrary orientation.
Rectangle2D tBbox = matrix.createTransformedShape(bbox).getBounds2D();
// Step 2. matrix a is computed that scales and translates the
// transformed appearance box (tBbox) to align with the edges of
// the annotation's rectangle (Ret).
Rectangle2D rect = getUserSpaceRectangle();
AffineTransform tAs = AffineTransform.getScaleInstance(
(rect.getWidth() / tBbox.getWidth()),
(rect.getHeight() / tBbox.getHeight()));
if (matrix.getTranslateX() > 0 || matrix.getTranslateY() > 0) {
// we have to align the boxes.
matrix.setToTranslation(rect.getX() - matrix.getTranslateX(),
rect.getY() - matrix.getTranslateY());
}
// Step 3. matrix is concatenated with A to form a matrix AA
// that maps from the appearance's coordinate system to the
// annotation's rectangle in default user space.
tAs.concatenate(matrix);
g.transform(tAs);
// regular paint
appearanceState.getShapes().paint(g);
}
}
protected void renderBorder(Graphics2D g) {
// if( false ) {
// float width = 1.0f;
// Rectangle2D.Float jrect = deriveBorderDrawingRectangle( width );
// g.setColor( Color.red );
// g.setStroke( new BasicStroke(width) );
// g.draw( jrect );
// return;
// }
// we don't paint some borders as the BS has a different meanings.
if (this instanceof SquareAnnotation ||
this instanceof CircleAnnotation ||
this instanceof LineAnnotation ||
this instanceof FreeTextAnnotation ||
this instanceof InkAnnotation) {
return;
}
Color borderColor = getColor();
if (borderColor != null) {
g.setColor(borderColor);
}
BorderStyle bs = getBorderStyle();
if (bs != null) {
float width = bs.getStrokeWidth();
if (width > 0.0f && borderColor != null && canDrawBorder) {
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
if (bs.isStyleSolid()) {
g.setStroke(new BasicStroke(width));
g.draw(jrect);
} else if (bs.isStyleDashed()) {
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
width * 2.0f, bs.getDashArray(), 0.0f);
g.setStroke(stroke);
g.draw(jrect);
} else if (bs.isStyleBeveled()) {
jrect = deriveDrawingRectangle();
g.setStroke(new BasicStroke(1.0f));
Line2D.Double line;
// Upper top
g.setColor(BorderStyle.LIGHT);
line = new Line2D.Double( // Top line
jrect.getMinX() + 1.0, jrect.getMaxY() - 1.0, jrect.getMaxX() - 2.0, jrect.getMaxY() - 1.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 1.0f, jrect.getMinY() + 2.0, jrect.getMinX() + 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
// Inner top
g.setColor(BorderStyle.LIGHTEST);
line = new Line2D.Double( // Top line
jrect.getMinX() + 2.0, jrect.getMaxY() - 2.0, jrect.getMaxX() - 3.0, jrect.getMaxY() - 2.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 2.0f, jrect.getMinY() + 3.0, jrect.getMinX() + 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Inner bottom
g.setColor(BorderStyle.DARK);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 2.0, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0, jrect.getMinY() + 2.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 2.0f, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Lower bottom
g.setColor(BorderStyle.DARKEST);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 1.0, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0, jrect.getMinY() + 1.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 1.0f, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
} else if (bs.isStyleInset()) {
jrect = deriveDrawingRectangle();
g.setStroke(new BasicStroke(1.0f));
Line2D.Double line;
// Upper top
g.setColor(BorderStyle.DARK);
line = new Line2D.Double( // Top line
jrect.getMinX() + 1.0, jrect.getMaxY() - 1.0, jrect.getMaxX() - 1.0, jrect.getMaxY() - 1.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 1.0f, jrect.getMinY() + 1.0, jrect.getMinX() + 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
// Inner top
g.setColor(BorderStyle.DARKEST);
line = new Line2D.Double( // Top line
jrect.getMinX() + 2.0, jrect.getMaxY() - 2.0, jrect.getMaxX() - 2.0, jrect.getMaxY() - 2.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 2.0f, jrect.getMinY() + 2.0, jrect.getMinX() + 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Inner bottom
g.setColor(BorderStyle.LIGHTEST);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 3.0, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0, jrect.getMinY() + 2.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 2.0f, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0f, jrect.getMaxY() - 3.0);
g.draw(line);
// Lower bottom
g.setColor(BorderStyle.LIGHT);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 2.0, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0, jrect.getMinY() + 1.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 1.0f, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0f, jrect.getMaxY() - 2.0);
g.draw(line);
} else if (bs.isStyleUnderline()) {
g.setStroke(new BasicStroke(width));
Line2D.Double line = new Line2D.Double(
jrect.getMinX(), jrect.getMinY(), jrect.getMaxX(), jrect.getMinY());
g.draw(line);
}
}
} else {
List borderVector = (List) getObject(BORDER_KEY);
if (borderVector != null) {
if (borderColor != null) {
float horizRadius = 0.0f;
float vertRadius = 0.0f;
float width = 1.0f;
float[] dashArray = null;
if (borderVector.size() >= 1)
horizRadius = ((Number) borderVector.get(0)).floatValue();
if (borderVector.size() >= 2)
vertRadius = ((Number) borderVector.get(1)).floatValue();
if (borderVector.size() >= 3)
width = ((Number) borderVector.get(2)).floatValue();
if (borderVector.size() >= 4) {
Object dashObj = borderVector.get(3);
// I guess some encoders like having fun with us,
// and feed a number when a number-array is appropriate. The problem
// is that for the specific PDF given, apparently no border is to be
// drawn, especially not the hugely thinck one described. So,
// instead of interpretting the 4th element (Number) into a Vector,
// I'm just not going to do the border if it's the Number. I know, hack.
// The only theory I have is that LinkAnnotation defaults the border
// color to black, when maybe it should be to null, but that could
// change a _lot_ of stuff, so I won't touch it now.
if (dashObj instanceof Number) {
// Disable border drawing
width = 0.0f;
} else if (dashObj instanceof List) {
List dashVector = (List) borderVector.get(3);
int sz = dashVector.size();
dashArray = new float[sz];
for (int i = 0; i < sz; i++) {
Number num = (Number) dashVector.get(i);
dashArray[i] = num.floatValue();
}
}
}
if (width > 0.0f) {
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
RoundRectangle2D.Double roundRect = new RoundRectangle2D.Double(
jrect.getX(), jrect.getY(), jrect.getWidth(), jrect.getHeight(),
horizRadius, vertRadius);
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dashArray, 0.0f);
g.setStroke(stroke);
g.draw(roundRect);
}
}
} else {
// Draw a solid rectangle, 1 pixel wide
if (borderColor != null && SUBTYPE_LINK.equals(subtype)) {
float width = 1.0f;
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
g.setStroke(new BasicStroke(width));
g.draw(jrect);
}
}
}
}
protected void renderBorderTabSelected(Graphics2D g) {
float width = 1.0f;
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
g.setColor(Color.black);
float[] dashArray = new float[]{2.0f};
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dashArray, 0.0f);
g.setStroke(stroke);
g.draw(jrect);
}
/**
* Gest the RGB colour of the annotation used for the following purposes:
* <ul>
* <li>the background of the annotaiton's icon when closed</li>
* <li>the title bar of the anntoation's pop-up window</li>
* <li>the border of a link annotation</li>
* </ul>
*
* @return A Color for the border, or null if none is to be used
*/
public Color getColor() {
return color;
}
/**
* Sets the Annotation colour and underlying
*
* @param color new colour value
*/
public void setColor(Color color) {
this.color = new Color(color.getRGB());
// put colour back in to the dictionary
float[] compArray = new float[3];
this.color.getColorComponents(compArray);
List<Float> colorValues = new ArrayList<Float>(compArray.length);
for (float comp : compArray) {
colorValues.add(comp);
}
entries.put(Annotation.COLOR_KEY, colorValues);
}
protected Rectangle2D.Float deriveDrawingRectangle() {
Rectangle2D.Float origRect = getUserSpaceRectangle();
Rectangle2D.Float jrect = new Rectangle2D.Float(origRect.x, origRect.y,
origRect.width, origRect.height);
jrect.x = 0.0f;
jrect.y = 0.0f;
return jrect;
}
private Rectangle2D.Float deriveBorderDrawingRectangle(float borderWidth) {
Rectangle2D.Float jrect = deriveDrawingRectangle();
float halfBorderWidth = borderWidth / 2.0f;
double minX = jrect.getMinX() + halfBorderWidth;
double minY = jrect.getMinY() + halfBorderWidth;
double maxX = jrect.getMaxX() - halfBorderWidth;
double maxY = jrect.getMaxY() - halfBorderWidth;
jrect.setFrameFromDiagonal(minX, minY, maxX, maxY);
return jrect;
}
/**
* @return Whether this annotation may be shown in any way to the user
*/
protected boolean allowScreenOrPrintRenderingOrInteraction() {
// Based off of the annotation flags' Invisible and Hidden values
if (getFlagHidden())
return false;
return !(getFlagInvisible() && isSupportedAnnotationType());
}
/**
* The PDF spec defines rules for displaying annotation subtypes that the viewer
* does not recognise. But, from a product point of view, we may or may not
* wish to make a best attempt at showing an unsupported annotation subtype,
* as that may make users think we're quality deficient, instead of
* feature deficient.
* Subclasses should override this, and return true, indicating that that
* particular annotation is supported.
*
* @return true, if this annotation is supported; else, false.
*/
protected boolean isSupportedAnnotationType() {
return true;
}
public boolean getFlagInvisible() {
return ((getInt(FLAG_KEY) & FLAG_INVISIBLE) != 0);
}
public boolean getFlagHidden() {
return ((getInt(FLAG_KEY) & FLAG_HIDDEN) != 0);
}
public boolean getFlagPrint() {
return ((getInt(FLAG_KEY) & FLAG_PRINT) != 0);
}
public boolean getFlagNoZoom() {
return ((getInt(FLAG_KEY) & FLAG_NO_ZOOM) != 0);
}
public boolean getFlagNoRotate() {
return ((getInt(FLAG_KEY) & FLAG_NO_ROTATE) != 0);
}
public boolean getFlagNoView() {
return ((getInt(FLAG_KEY) & FLAG_NO_VIEW) != 0);
}
public boolean getFlagReadOnly() {
return ((getInt(FLAG_KEY) & FLAG_READ_ONLY) != 0);
}
public boolean getFlagToggleNoView() {
return ((getInt(FLAG_KEY) & FLAG_TOGGLE_NO_VIEW) != 0);
}
public boolean getFlagLockedContents() {
return ((getInt(FLAG_KEY) & FLAG_LOCKED_CONTENTS) != 0);
}
public boolean getFlagLocked() {
return ((getInt(FLAG_KEY) & FLAG_LOCKED) != 0);
}
/**
* Set the specified flag key to either enabled or disabled.
*
* @param flagKey flag key to set.
* @param enable true or false key value.
*/
public void setFlag(final int flagKey, boolean enable) {
int flag = getInt(FLAG_KEY);
boolean isEnabled = (flag & flagKey) != 0;
if (!enable && isEnabled) {
flag = flag ^ flagKey;
entries.put(FLAG_KEY, flag);
} else if (enable && !isEnabled) {
flag = flag | flagKey;
entries.put(FLAG_KEY, flag);
}
}
public void setModifiedDate(String modifiedDate) {
entries.put(M_KEY, new LiteralStringObject(modifiedDate));
this.modifiedDate = new PDate(securityManager, modifiedDate);
}
public boolean hasAppearanceStream() {
return library.getObject(entries, APPEARANCE_STREAM_KEY) != null;
}
/**
* Returns the appearance stream as defined by the AP dictionary key N
*
* @return N appearance stream or null.
*/
public Stream getAppearanceStream() {
Object AP = getObject(APPEARANCE_STREAM_KEY);
if (AP instanceof HashMap) {
Object N = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_NORMAL_KEY);
if (N instanceof HashMap) {
Object AS = getObject(APPEARANCE_STATE_KEY);
if (AS != null && AS instanceof Name)
N = library.getObject((HashMap) N, (Name) AS);
}
// n should be a Form but we have a few cases of Stream
if (N instanceof Stream) {
return (Stream) N;
}
}
return null;
}
/**
* Gets the Appearance Form object associated with the annotation's appearances. Many encoders do no create
* the stream if there is no data in the widget. This method insure that an appearance XObject/Form is
* created. The object new object is not added to the state manager.
*
* @return appearance for annotation.
*/
public Form getOrGenerateAppearanceForm() {
StateManager stateManager = library.getStateManager();
Form form = null;
if (hasAppearanceStream()) {
Stream stream = getAppearanceStream();
if (stream instanceof Form) {
form = (Form) stream;
} else if (stream != null) {
// build out an appearance stream, corner case iText 2.1
// didn't correctly set type = form on the appearance stream obj.
form = new Form(library, stream.getEntries(), null);
form.setPObjectReference(stream.getPObjectReference());
form.setRawBytes(stream.getDecodedStreamBytes());
form.init();
}
}// else a stream, we won't support this for annotations.
else {
// create a new xobject/form object
HashMap<Name, Object> formEntries = new HashMap<Name, Object>();
formEntries.put(Form.TYPE_KEY, Form.TYPE_VALUE);
formEntries.put(Form.SUBTYPE_KEY, Form.SUB_TYPE_VALUE);
form = new Form(library, formEntries, null);
form.setPObjectReference(stateManager.getNewReferencNumber());
library.addObject(form, form.getPObjectReference());
}
return form;
}
public String getContents() {
return content;
}
public void setContents(String content) {
this.content = content;
entries.put(CONTENTS_KEY, new LiteralStringObject(content));
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ANNOTATION= {");
Set keys = entries.keySet();
for (Object key : keys) {
Object value = entries.get(key);
sb.append(key.toString());
sb.append('=');
if (value == null)
sb.append("null");
else if (value instanceof StringObject)
sb.append(((StringObject) value).getDecryptedLiteralString(library.securityManager));
else
sb.append(value.toString());
sb.append(',');
}
sb.append('}');
if (getPObjectReference() != null) {
sb.append(" ");
sb.append(getPObjectReference());
}
for (int i = sb.length() - 1; i >= 0; i--) {
if (sb.charAt(i) < 32 || sb.charAt(i) >= 127)
sb.deleteCharAt(i);
}
return sb.toString();
}
public void syncBBoxToUserSpaceRectangle(Rectangle2D bbox) {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
appearanceState.setBbox(bbox);
Rectangle2D tBbox = appearanceState.getMatrix().createTransformedShape(bbox).getBounds2D();
setUserSpaceRectangle(new Rectangle2D.Float(
(float) tBbox.getX(), (float) tBbox.getY(),
(float) tBbox.getWidth(), (float) tBbox.getHeight()));
}
public abstract void resetAppearanceStream(double dx, double dy, AffineTransform pageSpace);
public void resetAppearanceStream(AffineTransform pageSpace) {
resetAppearanceStream(0, 0, pageSpace);
}
public Shapes getShapes() {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
return appearanceState.getShapes();
}
public HashMap<Name, Appearance> getAppearances() {
return appearances;
}
public void addPropertyChangeListener(
PropertyChangeListener listener) {
synchronized (this) {
if (listener == null) {
return;
}
if (changeSupport == null) {
changeSupport = new PropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
}
}
| [
"patrick.corless@8668f098-c06c-11db-ba21-f49e70c34f74"
] | patrick.corless@8668f098-c06c-11db-ba21-f49e70c34f74 |
5d8726548e494da03ae22a84ab3c1d81a7fb6812 | 9b1fc35c32ae6acd6bbde87d9184735bb8f1ea6f | /1/Fundamental/src/controlflow/Main.java | fc8d992ebaef59f5927b63ac269289d88cf61a77 | [] | no_license | adasoraninda/mosh-java | b599f13b5b778515f65b7de4260185a63acaa401 | bf02c5f03498afa5e4814d8bbab1b2de28dc475d | refs/heads/main | 2023-05-07T02:18:47.101729 | 2021-06-14T06:07:01 | 2021-06-14T06:07:01 | 376,719,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,406 | java | package controlflow;
import java.text.NumberFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final byte MONTHS_IN_YEAR = 12;
final byte PERCENT = 100;
final int PRINCIPAL_MINIMUM = 1000;
final int PRINCIPAL_MAXIMUM = 1_000_000;
final float ANNUAL_INTEREST_MINIMUM = 1F;
final float ANNUAL_INTEREST_MAXIMUM = 30F;
final byte YEARS_MINIMUM = 1;
final byte YEARS_MAXIMUM = 30;
Scanner scanner = new Scanner(System.in);
int principal = 0;
float annualInterest = 0F;
float monthlyInterest = 0F;
byte years = 0;
int numberOfPayments = 0;
// Principal
while (true) {
System.out.print("Principal ($1K - $1M): ");
principal = scanner.nextInt();
if (principal >= PRINCIPAL_MINIMUM && principal <= PRINCIPAL_MAXIMUM) {
break;
}
System.out.println("Enter a number between 1,000 and 1,000,000.");
}
// Annual Interest
while (true) {
System.out.print("Annual Interest Rate: ");
annualInterest = scanner.nextFloat();
if (annualInterest >= ANNUAL_INTEREST_MINIMUM && annualInterest <= ANNUAL_INTEREST_MAXIMUM) {
monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;
break;
}
System.out.println("Enter a value greater than " + (int) ANNUAL_INTEREST_MINIMUM
+ " and less than or equal to " + (int) ANNUAL_INTEREST_MAXIMUM + ".");
}
// Years
while (true) {
System.out.print("Period (Years): ");
years = scanner.nextByte();
if (years >= YEARS_MINIMUM && years <= YEARS_MAXIMUM) {
numberOfPayments = years * MONTHS_IN_YEAR;
break;
}
System.out.println("Enter a value between " + YEARS_MINIMUM + " and " + YEARS_MAXIMUM + ".");
}
double mortgage = principal * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments))
/ (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);
String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage: " + mortgageFormatted);
scanner.close();
}
}
| [
"adasoraninda@gmail.com"
] | adasoraninda@gmail.com |
e2ed39346843d43ff3be09ff0c82a87ccdcba942 | 986abddca774fd196545e71da96a19c5a1f18a4f | /src/chapter2/code/ClassLoaderTest2.java | 5ac905eae4d79e5cafe0a88edf4a27dce45e71e3 | [] | no_license | yunyatian/JVMcode | 9bbda5d4a0e4f7aaf6a780dc01f921e429add6be | 7a2b0cc754dc16804ddd84bee69b3d940db0c3e1 | refs/heads/master | 2023-06-28T06:51:57.077962 | 2021-07-28T11:09:33 | 2021-07-28T11:09:33 | 385,200,203 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,289 | java | package chapter2.code;
import sun.security.ec.point.Point;
import java.net.URL;
import java.security.Provider;
public class ClassLoaderTest2 {
public static void main(String[] args) {
System.out.println("-------------启动类(引导类)加载器-----------------");
//获取bootstrapClassLoader能够加载的所有Api路径
URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
for (URL element:urls) {
System.out.println(element.toExternalForm());
}
//以上jar包任取一个解压,获取其中某一类的加载器
ClassLoader classLoader = Provider.class.getClassLoader();
System.out.println(classLoader);//null
System.out.println();
System.out.println("-------------扩展类加载器-----------------");
//获取扩展类加载器能够加载的所有API路径
String extDirs = System.getProperty("java.ext.dirs");
for (String path:extDirs.split(";")) {
System.out.println(path);
}
//以上jar包任取一个解压,获取其中某一类的加载器
ClassLoader classLoader1 = Point.class.getClassLoader();
System.out.println(classLoader1);//sun.misc.Launcher$ExtClassLoader@3af49f1c
}
}
| [
"jsyuan@iflytek.com"
] | jsyuan@iflytek.com |
e91a61ba34fd6e70b54e818ce9841dfeea89f1dd | b770b8799b43ca5ffe2fea9b293fb37d929c80cc | /JavaExamples/src/examples/google/GoogleSample2.java | 1962088a0394043be4d118f62baa01cead354ddd | [] | no_license | Malifter/Examples | 868a2714a962782343524cde64d15f2a46cfe5fd | 16ab6ef818dd370ae10e0405b2bcd8b1735f3c8c | refs/heads/master | 2021-01-10T17:03:55.661693 | 2016-01-09T01:45:34 | 2016-01-09T01:45:34 | 46,088,244 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,770 | java | package examples.google;
public class GoogleSample2 {
public static void main(String [] args) {
String S = "dir1\n"
+ " dir11\n"
+ " dir12\n"
+ " picturepicturepicturepicturepicture.jpeg\n"
+ " dir121\n"
+ " file1.txt\n"
+ " dir3\n"
+ " file3.txt\n"
+ " dir5\n"
+ " longpicture.png\n"
+ " dir4\n"
+ "dir2\n"
+ " longpicturelongpicture.gif\n";
System.out.println(solution3(S));
}
// O(n) if we solve it backwards because now we don't have to backtrack at all
public static int solution3(String S) {
int max = 0;
String [] parts = S.split("\n");
max = solution3Recursive(parts, parts.length, parts.length-1, "");
return max;
}
public static int solution3Recursive(String [] parts, int lastLevel, int i, String path) {
if(i == -1) return 0;
String part = parts[i];
int level = part.lastIndexOf(' ') + 1;
part = part.replaceAll("\\s+", "");
int max = 0;
if(level > lastLevel) {
path = "/" + part;
} else if(level < lastLevel) {
path = "/" + part + path;
} else if((part.contains(".jpeg") ||
part.contains(".png") ||
part.contains(".gif")) &&
part.length()+1 > path.length()) {
path = "/" + part;
}
System.out.println(path);
max = Math.max(path.length(), solution3Recursive(parts, level, i-1, path));
return max;
}
// O(h*n) time complexity
public static int solution2(String S) {
int max = 0;
String [] parts = S.split("\n");
max = solution2Recursive(parts, -1, 0, "");
return max;
}
public static int solution2Recursive(String [] parts, int lastLevel, int i, String path) {
if(i == parts.length) return 0;
String part = parts[i];
int level = part.lastIndexOf(' ') + 1;
part = part.replaceAll("\\s+", "");
int max = 0;
if(level > lastLevel) {
path += "/" + part;
} else if(level < lastLevel) {
for(int dif = (lastLevel - level); dif > 0; dif--) {
path = path.substring(0, path.lastIndexOf('/'));
}
if(level == 0) {
path = "/" + part;
} else {
path = path.substring(0, path.lastIndexOf('/'));
path += "/" + part;
}
} else {
path = path.substring(0, path.lastIndexOf('/'));
path += "/" + part;
}
System.out.println(path);
max = Math.max(max, solution2Recursive(parts, level, i+1, path));
if((path.contains(".jpeg") ||
path.contains(".png") ||
path.contains(".gif") &&
level >= lastLevel)) {
return Math.max(max, path.length());
}
return max;
}
// O(h*n) time complexity
public static int solution1(String S) {;
String longestPath = "";
String currentPath = "";
String [] parts = S.split("\n");
int lastLevel = -1;
for(int i = 0; i < parts.length; i++) {
String part = parts[i];
int level = part.lastIndexOf(' ')+1;
part = part.replaceAll("\\s+", "");
if(level > lastLevel) {
currentPath += "/" + part;
} else if(level < lastLevel) {
for(int dif = (lastLevel - level); dif > 0; dif--) {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
}
if(level == 0) {
currentPath = "/" + part;
} else {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
currentPath += "/" + part;
}
} else {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
currentPath += "/" + part;
}
lastLevel = level;
if((currentPath.contains(".jpeg") ||
currentPath.contains(".png") ||
currentPath.contains(".gif")) &&
currentPath.length() > longestPath.length()) {
longestPath = currentPath;
}
System.out.println(currentPath);
}
return longestPath.length();
}
}
| [
"Garrett_Benoit@baylor.edu"
] | Garrett_Benoit@baylor.edu |
6514d45bf854a4c77a8fea62f61735af14656d5c | 78a7a33adca4836c51c5fa7811150d535b19313d | /src/main/java/com/pms/model/appointment/AppointmentKey.java | 30be80cad6b82c51d7cbbade71706b13e0aed8d2 | [] | no_license | DimMilios/Pms-backend | 4390d095a92709d6698b4980cf2479f72030f451 | 574dd608586d90aab5847390e41a53b74c8dc052 | refs/heads/master | 2023-07-19T13:27:54.495311 | 2022-05-03T09:11:36 | 2022-05-03T09:11:36 | 231,906,841 | 0 | 0 | null | 2023-07-07T21:57:03 | 2020-01-05T11:26:02 | Java | UTF-8 | Java | false | false | 1,153 | java | package com.pms.model.appointment;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class AppointmentKey implements Serializable {
@Column(name = "doctor_id")
private Long doctorId;
@Column(name = "ssn")
private Long patientSsn;
public void setDoctorId(Long doctorId) {
this.doctorId = doctorId;
}
public void setPatientSsn(Long patientSsn) {
this.patientSsn = patientSsn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AppointmentKey that = (AppointmentKey) o;
return Objects.equals(doctorId, that.doctorId) &&
Objects.equals(patientSsn, that.patientSsn);
}
@Override
public int hashCode() {
return Objects.hash(doctorId, patientSsn);
}
@Override
public String toString() {
return "AppointmentKey{" +
"doctorId=" + doctorId +
", patientSsn=" + patientSsn +
'}';
}
}
| [
"elles1992@yahoo.gr"
] | elles1992@yahoo.gr |
6ac4ca279ff95ec45775422f594354af71658e54 | 2c2dcf30857f38c10ebf8190d980a61cff44ca1a | /app/src/test/java/com/android/ingan/prueba/ExampleUnitTest.java | fb870ebe93425d8251d92216334f89dd4c826254 | [] | no_license | araad1992/Prueba | 84141fca5ee76d5f561dd6578a8b95cf7a83bd73 | 2e5baef0c3b02fa6f2647407fa0448f5629f2438 | refs/heads/master | 2021-01-25T06:06:59.323784 | 2017-06-06T15:46:41 | 2017-06-06T15:46:41 | 93,528,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package com.android.ingan.prueba;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"inganuarraad@hotmail.com"
] | inganuarraad@hotmail.com |
b7bb1971897db4b4879d1357a83a9160ff7ccc54 | f95165ad67734b791cd902e310cbc9be405f9a0d | /Game Engine/src/LevelMaker/LevelMakerData.java | ef60922b0ea7d66c7bf926cdc5cfce5634aa64ee | [] | no_license | kevino5233/GameEngine | 29bd51f71ba80431b76d996b990b4d5ddd9d66f6 | d2bfafdbba649611beb0ef7e77b3de8b75d4f581 | refs/heads/master | 2021-01-25T12:24:16.585224 | 2014-05-31T09:13:19 | 2014-05-31T09:13:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,655 | java | package LevelMaker;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import Event.TextEvent;
public class LevelMakerData {
private BufferedImage tileMap;
private int[][] tileTypes;
private String[][] enemyData;
private ArrayList<String> events;
private LevelMakerData(BufferedImage tm, int[][] tt, String[][] ed, ArrayList<String> ev){
tileMap = tm;
tileTypes = tt;
enemyData = ed;
events = ev;
}
public BufferedImage getTileMap(){ return tileMap; }
public int[][] getTileTypes(){ return tileTypes; }
public String[][] getEnemyData(){ return enemyData; }
public ArrayList<String> getEvents(){ return events; }
public static String getSaveableData(BufferedImage tileMap, int[][] tileTypes, String[][] enemyData, TextEvent[][] textEvents){
String contents = "";
contents += String.format("%d %d\n", tileMap.getHeight(), tileMap.getWidth());
for (int j = 0; j < tileMap.getHeight(); j++){
for (int i = 0; i < tileMap.getWidth(); i++){
contents += tileMap.getRGB(i, j) + " ";
}
contents += '\n';
}
contents += String.format("%d %d\n", tileTypes.length, tileTypes[0].length);
for (int j = 0; j < tileTypes.length; j++){
for (int i = 0; i < tileTypes[0].length; i++){
contents += tileTypes[j][i] + " ";
}
contents += '\n';
}
for (int j = 0; j < enemyData.length; j++){
for (int i = 0; i < enemyData[0].length; i++){
if (enemyData[j][i] == null){
contents += "None ";
} else {
contents += enemyData[j][i] + " ";
}
}
contents += '\n';
}
for (int j = 0; j < textEvents.length; j++){
for (int i = 0; i < textEvents[0].length; i++){
if (textEvents[j][i] != null){
contents += i + "|" + j + "|" + textEvents[j][i] + "\n";
}
}
}
return contents;
}
public static LevelMakerData getLevelMakerData(BufferedImage tileMap, int cols, int rows){
return new LevelMakerData(tileMap, new int[rows][cols], new String[rows][cols], new ArrayList<String>());
}
public static LevelMakerData parse(String levelName)throws IOException{
/*
* Switch to InputStreamReader
* parse until a space, then parse that String
*/
InputStream in = Main.class.getResourceAsStream("/Resources/Levels/" + levelName + ".lvmk");
BufferedReader level =
new BufferedReader(
new InputStreamReader(in)
);
String[] dat = level.readLine().split(" ");
int rows = Integer.parseInt(dat[0]);
int cols = Integer.parseInt(dat[1]);
BufferedImage tm = new BufferedImage(cols, rows, BufferedImage.TYPE_INT_RGB);
for (int j = 0; j < rows; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < cols; i++){
tm.setRGB(i, j, Integer.parseInt(dat[i]));
}
}
dat = level.readLine().split(" ");
rows = Integer.parseInt(dat[0]);
cols = Integer.parseInt(dat[1]);
int[][] tt = new int[rows][cols];
for (int j = 0; j < tt.length; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < tt[0].length; i++){
tt[j][i] = Integer.parseInt(dat[i]);
}
}
String[][] ed = new String[tt.length][tt[0].length];
for (int j = 0; j < tt.length; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < tt[0].length; i++){
ed[j][i] = dat[i];
}
}
int num = 0;
try{
num = Integer.parseInt(level.readLine());
} catch (Exception e){}
ArrayList<String> ev = new ArrayList<String>();
while(num-- > 0){
ev.add(level.readLine());
}
level.close();
return new LevelMakerData(tm, tt, ed, ev);
}
}
| [
"kevin.sun96@gmail.com"
] | kevin.sun96@gmail.com |
75e1ecdb3fea83d12cf535c6ec8b86e51eab8257 | 83a5dd42ec8ab543d0d9e588d15d6d88df8e8aab | /CineOnline/CineOnline-ejb/src/java/model/factories/AwardFacadeLocal.java | d3b349dbe26989e1fb2a04444b05bb4f53292bcc | [] | no_license | AleKrabbe/CineOnline | 8e8374b24d28ed92907d7d0daeab1c00064becc4 | b4c718a5a173e27a63b074b172b6ec2e787f937f | refs/heads/master | 2020-04-07T00:33:59.743600 | 2018-12-06T04:23:59 | 2018-12-06T04:23:59 | 157,909,083 | 1 | 0 | null | 2018-11-20T20:32:00 | 2018-11-16T18:55:41 | Java | UTF-8 | Java | false | false | 583 | java | /*
* 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 model.factories;
import java.util.List;
import javax.ejb.Local;
import model.entities.Award;
/**
*
* @author Alexandre Krabbe
*/
@Local
public interface AwardFacadeLocal {
void create(Award award);
void edit(Award award);
void remove(Award award);
Award find(Object id);
List<Award> findAll();
List<Award> findRange(int[] range);
int count();
}
| [
"alekrabbe@gmail.com"
] | alekrabbe@gmail.com |
a8c4ef49ecd85ad69cf44b31b9b203dc9bcaacbf | 25ac334bb00a50245223eaa1bd3d6ca2968ae182 | /android/app/src/main/java/com/jinjerkeihi/nfcfelica/transit/Station.java | dc53b2eb8c4ea46650ecff84d127ae5221d929b9 | [] | no_license | buixuanthe2212/reduxThunk | 2e3c66bfb15f6d883ced6eebab673c04f3f207bb | 7fa8793c027a21815bd37e6f19195b71aab21168 | refs/heads/master | 2020-03-18T14:13:22.646564 | 2018-05-25T09:53:54 | 2018-05-25T09:53:54 | 134,836,725 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,987 | java | /*
* Station.java
*
* Copyright (C) 2011 Eric Butler <eric@codebutler.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jinjerkeihi.nfcfelica.transit;
import android.os.Parcel;
import android.os.Parcelable;
public class Station implements Parcelable {
public static final Creator<Station> CREATOR = new Creator<Station>() {
public Station createFromParcel(Parcel parcel) {
return new Station(parcel);
}
public Station[] newArray(int size) {
return new Station[size];
}
};
protected final String mCompanyName, mLineName, mStationName, mShortStationName, mLatitude, mLongitude, mLanguage;
public Station(String stationName, String latitude, String longitude) {
this(stationName, null, latitude, longitude);
}
public Station(String stationName, String shortStationName, String latitude, String longitude) {
this(null, null, stationName, shortStationName, latitude, longitude);
}
public Station(String companyName, String lineName, String stationName, String shortStationName, String latitude, String longitude) {
this(companyName, lineName, stationName, shortStationName, latitude, longitude, null);
}
public Station(String companyName, String lineName, String stationName, String shortStationName, String latitude, String longitude, String language) {
mCompanyName = companyName;
mLineName = lineName;
mStationName = stationName;
mShortStationName = shortStationName;
mLatitude = latitude;
mLongitude = longitude;
mLanguage = language;
}
protected Station(Parcel parcel) {
mCompanyName = parcel.readString();
mLineName = parcel.readString();
mStationName = parcel.readString();
mShortStationName = parcel.readString();
mLatitude = parcel.readString();
mLongitude = parcel.readString();
mLanguage = parcel.readString();
}
public String getStationName() {
return mStationName;
}
public String getShortStationName() {
return (mShortStationName != null) ? mShortStationName : mStationName;
}
public String getCompanyName() {
return mCompanyName;
}
public String getLineName() {
return mLineName;
}
public String getLatitude() {
return mLatitude;
}
public String getLongitude() {
return mLongitude;
}
/**
* Language that the station line name and station name are written in. If null, then use
* the system locale instead.
*
* https://developer.android.com/reference/java/util/Locale.html#forLanguageTag(java.lang.String)
*/
public String getLanguage() {
return mLanguage;
}
public boolean hasLocation() {
return getLatitude() != null && !getLatitude().isEmpty()
&& getLongitude() != null && !getLongitude().isEmpty();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(mCompanyName);
parcel.writeString(mLineName);
parcel.writeString(mStationName);
parcel.writeString(mShortStationName);
parcel.writeString(mLatitude);
parcel.writeString(mLongitude);
parcel.writeString(mLanguage);
}
}
| [
"buixuanthe11t2bk@gmail.com"
] | buixuanthe11t2bk@gmail.com |
e7b31bd6063436cd53ddce419ed8f30527bfad0e | 2f8264af5cb8f89a3c48f25a5724f036a8af5976 | /Android/Day1(21.05.28)/CalcculationLayout/app/src/androidTest/java/com/aoslec/calcculationlayout/ExampleInstrumentedTest.java | 68652627102a746980f8e53d3e931680e5bc3659 | [] | no_license | ReplaceMyBrain/Class | 731c9988cf226a2f971412a84e3ddb205188f09b | b214e0c456ca3665f116903fa75e7fbe5fe85abd | refs/heads/main | 2023-07-12T21:04:04.401420 | 2021-08-27T18:53:48 | 2021-08-27T18:53:48 | 352,622,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package com.aoslec.calcculationlayout;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.aoslec.calcculationlayout", appContext.getPackageName());
}
} | [
"80452660+ReplaceMyBrain@users.noreply.github.com"
] | 80452660+ReplaceMyBrain@users.noreply.github.com |
6bbdb65bf9e04c83465bdfaa8a939bb6ee579761 | b38ebf4de362aeb74a5ce8a2e0f9fa0f94208147 | /src/java/com/proyectoCFIP/entities/Profesiograma.java | 02d7a5dd61d151419e341da5d0b18c45d947f2d9 | [] | no_license | juanCodoba/ultima | 7c14815ef3961cff30ead6fc81b197808ede680a | 3bb7eda388bbef9aa777649ffd7da72195355f52 | refs/heads/master | 2020-04-01T03:11:04.715528 | 2019-09-09T22:14:11 | 2019-09-09T22:14:11 | 152,812,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,226 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.proyectoCFIP.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Luis Carlos Cabal
*/
@Entity
@Table(name = "profesiograma")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Profesiograma.findAll", query = "SELECT p FROM Profesiograma p"),
@NamedQuery(name = "Profesiograma.findByIdProfesiograma", query = "SELECT p FROM Profesiograma p WHERE p.idProfesiograma = :idProfesiograma"),
@NamedQuery(name = "Profesiograma.findByDescripcion", query = "SELECT p FROM Profesiograma p WHERE p.descripcion = :descripcion")
})
public class Profesiograma implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_profesiograma")
private Integer idProfesiograma;
@Size(max = 255)
@Column(name = "descripcion")
private String descripcion;
@JoinColumn(name = "id_tipo_profesiograma", referencedColumnName = "id_tipo_profesiograma")
@ManyToOne(optional = true)
private TipoProfesiograma idTipoProfesiograma;
@Size(max = 1000000)
@Column(name = "url_profesiograma")
private String urlProfesiograma;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idProfesiograma")
private List<Cargos> cargosList;
public Profesiograma() {
}
public Profesiograma(Integer idProfesiograma) {
this.idProfesiograma = idProfesiograma;
}
public Profesiograma(Integer idProfesiograma, TipoProfesiograma idTipoProfesiograma) {
this.idProfesiograma = idProfesiograma;
this.idTipoProfesiograma = idTipoProfesiograma;
}
public Integer getIdProfesiograma() {
return idProfesiograma;
}
public void setIdProfesiograma(Integer idProfesiograma) {
this.idProfesiograma = idProfesiograma;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public TipoProfesiograma getIdTipoProfesiograma() {
return idTipoProfesiograma;
}
public void setIdTipoProfesiograma(TipoProfesiograma idTipoProfesiograma) {
this.idTipoProfesiograma = idTipoProfesiograma;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idProfesiograma != null ? idProfesiograma.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Profesiograma)) {
return false;
}
Profesiograma other = (Profesiograma) object;
if ((this.idProfesiograma == null && other.idProfesiograma != null) || (this.idProfesiograma != null && !this.idProfesiograma.equals(other.idProfesiograma))) {
return false;
}
return true;
}
@Override
public String toString() {
return getDescripcion();
}
public List<Cargos> getCargosList() {
return cargosList;
}
public void setCargosList(List<Cargos> cargosList) {
this.cargosList = cargosList;
}
public String getUrlProfesiograma() {
return urlProfesiograma;
}
public void setUrlProfesiograma(String urlProfesiograma) {
this.urlProfesiograma = urlProfesiograma;
}
}
| [
"Luis Carlos Cabal"
] | Luis Carlos Cabal |
ced8f2060050a4eac387b3b19be68c0c6cf4c8e7 | cc53f7685325c016cc07ca2d1997a0fd302a146a | /src/test/java/AlbumTest.java | 4af8e79d9321625559f70e05a16312de5971e12d | [] | no_license | slbrtg/rotten-peaches-spark | 107bc6f3da5a3f1fc0bf6b70e22f990ff51adaff | 0a47e95c0f36cccd9c993465e61f383e37106a0f | refs/heads/master | 2020-06-27T13:15:45.379911 | 2017-07-13T23:44:47 | 2017-07-13T23:44:47 | 97,059,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,297 | java | import org.sql2o.*;
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class AlbumTest {
@Rule
public DatabaseRule database = new DatabaseRule();
@Test
public void Album_instantiatesCorrectly_true() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
assertEquals(true, testAlbum instanceof Album);
}
@Test
public void getName_retrievesAlbumName_OKComputer() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
assertEquals("OK Computer", testAlbum.getName());
}
@Test
public void getId_instantiatesWithAnId_true() {
Album testAlbum = new Album("OK Computer", 1997, "indie rock", 1);
testAlbum.save();
assertTrue(testAlbum.getId() > 0);
}
@Test
public void all_retrievesAllInstancesOfAlbum_true() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
assertEquals(true, Album.all().get(0).equals(testAlbum));
assertEquals(true, Album.all().get(1).equals(testAlbum2));
}
@Test
public void find_returnAlbumWIthSameId_testAlbum2() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
assertEquals(Album.find(testAlbum2.getId()), testAlbum2);
}
@Test
public void updateName_updatesAlbumName_PabloHoney() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
testAlbum.updateName("Pablo Honey");
assertEquals("Pablo Honey", Album.find(testAlbum.getId()).getName());
}
@Test
public void updateReleaseYear_updatesAlbumReleaseYear_1993() {
Album testAlbum = new Album("King Of Limbs", 1997, "indie rock", 1);
testAlbum.save();
testAlbum.updateReleaseYear(1993);
assertEquals(1993, Album.find(testAlbum.getId()).getReleaseYear());
}
@Test
public void delete_deletesAnAlbum_true() {
Album testAlbum2 = new Album("In Rainbows", 1997, "indie rock", 2);
testAlbum2.save();
int testAlbumId = testAlbum2.getId();
testAlbum2.delete();
assertEquals(null, Album.find(testAlbumId));
}
}
| [
"sowmya@"
] | sowmya@ |
6083313d85e8933ff11d4916e0a65b571edcdf6f | fc420ee4f989de2b6cf112670a52c298aee4d202 | /CifradoRino/src/cifradorino/Crypto.java | f77e7b5921b2aaaa2c75424308dafad0df312607 | [] | no_license | NeoTRAN001/Crypto | e74b8b10673b84049dee2136e2e3211e0f269903 | 2ac817f1bfaa7e4574e9af9ded9291b53543bebc | refs/heads/master | 2020-04-08T22:01:51.168585 | 2019-05-16T19:54:51 | 2019-05-16T19:54:51 | 159,768,437 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,332 | java | package cifradorino;
/**
*
* @author Neo
*/
import java.util.StringTokenizer;
public class Crypto {
public String create(String word) {
char[] arrayWord = word.toCharArray();
char auxWord;
int total = 0;
String index = "", result = "";
for(int i = 0; i < arrayWord.length; i++) {
auxWord = arrayWord[i];
System.out.println(auxWord);
if(auxWord != '1') {
for(int j = 0; j < arrayWord.length; j++) {
if(auxWord == arrayWord[j])
{
if(j == (arrayWord.length - 1)) {
arrayWord[j] = '1';
index += j; total++;
} else {
arrayWord[j] = '1';
index += j + "$"; total++;
}
}
}
} else continue;
result += auxWord + "%" + total + "╚" + index + "^";
index = ""; total = 0;
}
return word.length() + "(/>♂<)/" + result;
}
public String killRino(String word) {
StringTokenizer tokenSize = new StringTokenizer(word,"(/>♂<)/");
int size = Integer.parseInt(tokenSize.nextToken());
char[] arrayWord = new char[size];
String result = "";
char wordC;
int index, rep;
StringTokenizer tokenWord = new StringTokenizer(tokenSize.nextToken(), "^");
while(tokenWord.hasMoreElements()) {
StringTokenizer tokenChar = new StringTokenizer(tokenWord.nextToken(), "%╚$");
while(tokenChar.hasMoreElements()) {
wordC = tokenChar.nextToken().charAt(0);
rep = Integer.parseInt(tokenChar.nextToken());
for(int i = 0; i < rep; i++) {
index = Integer.parseInt(tokenChar.nextToken());
arrayWord[index] = wordC;
}
}
}
for(int i =0; i < arrayWord.length; i++) {
result += arrayWord[i];
}
return result;
}
}
| [
"neo_tran@outlook.com"
] | neo_tran@outlook.com |
32d6e6d96cffb9022200b963100d3bf9697caf9a | 20cf48c45546b3a4ffd201079b0189c137cb8e0f | /war/src/main/java-user/com/omdasoft/orderonline/gwt/order/client/userView/presenter/UserViewPresenterImpl.java | 3dac9baee63a778c9e836a244e62cc95051d1bab | [] | no_license | winglight/orderonline | 6a1f4b5833cb77da344c3f405e8c5546bc8110db | 2cd108e85ec702e7eb49a5a44174b9d926fd498a | refs/heads/master | 2021-01-15T16:56:42.166403 | 2013-09-28T09:00:03 | 2013-09-28T09:00:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,442 | java | package com.omdasoft.orderonline.gwt.order.client.userView.presenter;
import net.customware.gwt.dispatch.client.DispatchAsync;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.omdasoft.orderonline.gwt.order.client.breadCrumbs.presenter.BreadCrumbsPresenter;
import com.omdasoft.orderonline.gwt.order.client.core.Platform;
import com.omdasoft.orderonline.gwt.order.client.mvp.BasePresenter;
import com.omdasoft.orderonline.gwt.order.client.mvp.ErrorHandler;
import com.omdasoft.orderonline.gwt.order.client.mvp.EventBus;
import com.omdasoft.orderonline.gwt.order.client.userAdd.dataprovider.UserWinAdapter;
import com.omdasoft.orderonline.gwt.order.client.userAdd.plugin.UserAddConstants;
import com.omdasoft.orderonline.gwt.order.client.userView.model.UserWinClient;
import com.omdasoft.orderonline.gwt.order.client.userView.request.UserViewRequest;
import com.omdasoft.orderonline.gwt.order.client.userView.request.UserViewResponse;
import com.omdasoft.orderonline.gwt.order.client.view.constant.CssStyleConstants;
import com.omdasoft.orderonline.gwt.order.client.widget.EltNewPager;
import com.omdasoft.orderonline.gwt.order.client.widget.ListCellTable;
import com.omdasoft.orderonline.gwt.order.client.win.Win;
import com.omdasoft.orderonline.gwt.order.model.user.UserRoleVo;
import com.omdasoft.orderonline.gwt.order.util.StringUtil;
public class UserViewPresenterImpl extends
BasePresenter<UserViewPresenter.UserViewDisplay> implements
UserViewPresenter {
private final DispatchAsync dispatch;
//private final SessionManager sessionManager;
private final Win win;
final ErrorHandler errorHandler;
private final BreadCrumbsPresenter breadCrumbs;
String staffId;
boolean colleague=false;
EltNewPager pager;
ListCellTable<UserWinClient> cellTable;
UserWinAdapter listViewAdapter;
@Inject
public UserViewPresenterImpl(EventBus eventBus, UserViewDisplay display,
DispatchAsync dispatch, Win win,
BreadCrumbsPresenter breadCrumbs, ErrorHandler errorHandler) {
super(eventBus, display);
this.dispatch = dispatch;
// this.sessionManager = sessionManager;
this.errorHandler = errorHandler;
this.win = win;
this.breadCrumbs = breadCrumbs;
}
@Override
public void bind() {
breadCrumbs.loadChildPage("用户详细信息");
display.setBreadCrumbs(breadCrumbs.getDisplay().asWidget());
init();
registerHandler(display.getupadateBtnClickHandlers().addClickHandler(
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Platform.getInstance()
.getEditorRegistry()
.openEditor(
UserAddConstants.EDITOR_STAFFADD_SEARCH,
"EDITOR_STAFFADD_SEARCH_DO_ID", staffId);
}
}));
}
void init() {
if(colleague==true)
{
display.displayUpdateBtn(colleague);
}
dispatch.execute(new UserViewRequest(staffId),
new AsyncCallback<UserViewResponse>() {
@Override
public void onFailure(Throwable t) {
win.alert(t.getMessage());
}
@Override
public void onSuccess(UserViewResponse resp) {
display.setStaffNo(resp.getStaffNo());
display.setStaffName(resp.getStaffName());
display.setPhone(resp.getPhone());
if(resp.getUserRoleVos()!=null && resp.getUserRoleVos().size()>0)
{
String roleString="";
for (UserRoleVo role:resp.getUserRoleVos()) {
if(role==UserRoleVo.CORP_ADMIN)
roleString+="管理员;";
if(role==UserRoleVo.DEPT_MGR)
roleString+="分店管理员;";
}
if(!StringUtil.isEmpty(roleString))
display.getStaffRoles().setText(roleString);
else
display.getStaffRoles().getElement().getParentElement().getParentElement().addClassName(CssStyleConstants.hidden);
}
else
{
display.getStaffRoles().getElement().getParentElement().getParentElement().addClassName(CssStyleConstants.hidden);
}
}
});
}
@Override
public void initUserView(String staffId) {
this.staffId = staffId;
}
@Override
public void initUserView_Colleague(String staffId,boolean colleague) {
this.staffId = staffId;
this.colleague=colleague;
}
}
| [
"wing_light@hotmail.com"
] | wing_light@hotmail.com |
186307cb1c3a4b7c0348fabed0946004695d747e | 6e4cdb5b2aa1307cb25fb2581acb520caedfc029 | /Exercises_Threads_1_Fall_2015/src/main/java/Exercise_2/evenClass.java | fc9a61046bf8d8825a2caf0c4d6e4adf64efda17 | [] | no_license | PhilipWestChristiansen/sp2 | b35d005789e6dd834d7341d5b8cf4f68f4cbe82c | d4ae296d901e788425ce35ea29b5af6c2b671393 | refs/heads/master | 2020-05-20T23:50:36.405201 | 2016-09-02T12:13:11 | 2016-09-02T12:13:11 | 67,219,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 175 | java | package Exercise_2;
public class evenClass {
private static int n = 0;
public synchronized static int next() {
n++;
n++;
return n;
}
}
| [
"PWC@10.50.130.35"
] | PWC@10.50.130.35 |
e3981a5c3e006489a0702331ca4c7382b2b3ff3d | 72fe9dba584370367771facbfddaa62bd2d855c6 | /WordChainsProd/src/com/strumsoft/wordchainsfree/helper/WordGameProvider.java | 416bcdb9123147133581b01f99ebb6d127d8e128 | [] | no_license | eshaanb/Word-Chains | 2333f3b1101e4399eda91a3a1e7129c37b4565bc | d8b078feccea7dd108a52ec9f64abec4b70d24d3 | refs/heads/master | 2021-01-18T13:55:56.446203 | 2014-12-09T08:03:51 | 2014-12-09T08:03:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,315 | java | package com.strumsoft.wordchainsfree.helper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.google.gson.Gson;
import com.strumsoft.wordchainsfree.model.Artists;
import com.strumsoft.wordchainsfree.model.FBMessage;
import com.strumsoft.wordchainsfree.model.Game;
import com.strumsoft.wordchainsfree.model.Games;
import com.strumsoft.wordchainsfree.model.Movies;
import com.strumsoft.wordchainsfree.model.TVShows;
public class WordGameProvider extends ContentProvider {
private DBHelper dbHelper;
public static final String GAMES_TABLE_NAME = "games";
private static final String DATABASE_NAME = "wordgames.db";
public static final String WORDS_TABLE_NAME = "words";
public static final String TEMP_WORDS_TABLE_NAME = "tempwords";
public static final String BOTWORDS_TABLE_NAME = "botwords";
public static final String FRIENDS_TABLE_NAME = "friends";
public static final String REGISTERED_FRIENDS_TABLE_NAME = "regfriends";
public static final String USERS_TABLE_NAME = "users";
public static final String MESSAGES_TABLE_NAME = "messages";
public static final String SCORE_TABLE_NAME = "score";
public static final String AUTHORITY = "com.strumsoft.wordgamefree.provider.WordGameProvider";
public static final Uri GAMES_URI = Uri.parse("content://"+AUTHORITY+"/"+GAMES_TABLE_NAME);
public static final Uri USERS_URI = Uri.parse("content://"+AUTHORITY+"/"+USERS_TABLE_NAME);
public static final Uri WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+WORDS_TABLE_NAME);
public static final Uri TEMP_WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+TEMP_WORDS_TABLE_NAME);
public static final Uri BOT_WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+BOTWORDS_TABLE_NAME);
public static final Uri FRIENDS_URI = Uri.parse("content://"+AUTHORITY+"/"+FRIENDS_TABLE_NAME);
public static final Uri REGISTERED_FRIENDS_URI = Uri.parse("content://"+AUTHORITY+"/"+REGISTERED_FRIENDS_TABLE_NAME);
public static final Uri ALL_URI = Uri.parse("content://"+AUTHORITY+"/all");
public static final Uri ALL_GAMES_URI = Uri.parse("content://"+AUTHORITY+"/allgames");
public static final Uri MESSAGES_URI = Uri.parse("content://"+AUTHORITY+"/messages");
public static final Uri SCORE_URI = Uri.parse("content://"+AUTHORITY+"/score");
private static final UriMatcher uriMatcher;
// Mapped to content://wordgame/games
private static final int GAMES = 1;
// Mapped to content://wordgame/messages
private static final int MESSAGES = 12;
// Mapped to content://wordgame/player
private static final int PLAYERS = 2;
// Mapped to content://wordgame/words
private static final int WORDS = 3;
private static final int BOT_WORDS = 9;
// Mapped to content://wordgame/games/*
private static final int GAME_ITEM = 4;
// Mapped to content://wordgame/users/*
private static final int PLAYER_ITEM = 5;
// Mapped to content://wordgame/words/*
private static final int WORD_ITEM = 6;
// Mapped to content://wordgame/botwords/*
private static final int BOT_WORD_ITEM = 11;
// Mapped to content://wordgame/messages/*
private static final int MESSAGE_ITEM = 13;
// Mapped to content://wordgame/all
private static final int ALL = 7;
private static final int REGISTERED_FRIENDS = 14;
private static final int SCORE_ITEM = 15;
private static final int SCORES = 16;
private static final int TEMP_WORDS = 17;
private static final int TEMP_WORD_ITEM = 18;
private static final HashMap<String, String> gamesProjection;
private static final HashMap<String, String> playersProjection;
private static final HashMap<String, String> wordsProjection;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, GAMES_TABLE_NAME, GAMES);
uriMatcher.addURI(AUTHORITY, USERS_TABLE_NAME, PLAYERS);
uriMatcher.addURI(AUTHORITY, WORDS_TABLE_NAME, WORDS);
uriMatcher.addURI(AUTHORITY, BOTWORDS_TABLE_NAME, BOT_WORDS);
uriMatcher.addURI(AUTHORITY, GAMES_TABLE_NAME+"/*", GAME_ITEM);
uriMatcher.addURI(AUTHORITY, USERS_TABLE_NAME+"/*", PLAYER_ITEM);
uriMatcher.addURI(AUTHORITY, WORDS_TABLE_NAME+"/*", WORD_ITEM);
uriMatcher.addURI(AUTHORITY, BOTWORDS_TABLE_NAME+"/*", BOT_WORD_ITEM);
uriMatcher.addURI(AUTHORITY, "all", ALL);
uriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME, MESSAGES);
uriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME+"/*", MESSAGE_ITEM);
uriMatcher.addURI(AUTHORITY, REGISTERED_FRIENDS_TABLE_NAME, REGISTERED_FRIENDS);
uriMatcher.addURI(AUTHORITY, SCORE_TABLE_NAME, SCORES);
uriMatcher.addURI(AUTHORITY, SCORE_TABLE_NAME+"/*", SCORE_ITEM);
uriMatcher.addURI(AUTHORITY, TEMP_WORDS_TABLE_NAME, TEMP_WORDS);
uriMatcher.addURI(AUTHORITY, TEMP_WORDS_TABLE_NAME+"/*", TEMP_WORD_ITEM);
gamesProjection = new HashMap<String, String>();
gamesProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
gamesProjection.put(DBHelper.CREATOR, DBHelper.CREATOR);
gamesProjection.put(DBHelper.TURNCOUNT, DBHelper.TURNCOUNT);
gamesProjection.put(DBHelper.TYPE, DBHelper.TYPE);
playersProjection = new HashMap<String, String>();
playersProjection.put(DBHelper.USER_USERNAME, DBHelper.USER_USERNAME);
playersProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection = new HashMap<String, String>();
wordsProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection.put(DBHelper.MY_ORDER, DBHelper.MY_ORDER);
wordsProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection.put(DBHelper.WORD_USERNAME, DBHelper.WORD_USERNAME);
wordsProjection.put(DBHelper.WORD, DBHelper.WORD);
}
public static ContentValues gameToContentValues(Game g) {
ContentValues gameTableCv = new ContentValues();
gameTableCv.put(DBHelper.GAME_ID, g.getStrId());
gameTableCv.put(DBHelper.TYPE, g.getType());
gameTableCv.put(DBHelper.PIC_URL, g.getPicUrl());
gameTableCv.put(DBHelper.CURRENT_PLAYER, g.getCurrPlayer());
gameTableCv.put(DBHelper.CREATOR, g.getGameCreator());
gameTableCv.put(DBHelper.MODE, g.getMode());
return gameTableCv;
}
public static FBMessage messageCurToMessage(Cursor c) {
if (c.getCount() < 1) {
return null;
}
return new FBMessage(c.getString(c.getColumnIndex(DBHelper.BODY)),
c.getInt(c.getColumnIndex(DBHelper.MY_ORDER)),
c.getString(c.getColumnIndex(DBHelper.USERID)),
c.getString(c.getColumnIndex(DBHelper.PIC_URL)));
}
public static Game gameCurToGame(Cursor c) {
if (c.getCount() < 1) {
return null;
}
if (c.getColumnIndex(DBHelper.CURRENT_PLAYER) != -1) {
String id = c.getString(c.getColumnIndex(DBHelper.GAME_ID));
String type = c.getString(c.getColumnIndex(DBHelper.TYPE));
String currPlayer = c.getString(c.getColumnIndex(DBHelper.CURRENT_PLAYER));
String creator = c.getString(c.getColumnIndex(DBHelper.CREATOR));
String picUrl = c.getString(c.getColumnIndex(DBHelper.PIC_URL));
String mode = c.getString(c.getColumnIndex(DBHelper.MODE));
int index;
ArrayList<String> ids = null;
ArrayList<String> names = null;
if ((index = c.getColumnIndex(DBHelper.USERLIST)) != -1) {
String userids = c.getString(c.getColumnIndex(DBHelper.USERIDS));
String userList = c.getString(index);
if (userList != null) {
names = new ArrayList<String>(Arrays.asList(userList.split(",")));
}
if (userids != null) {
ids = new ArrayList<String>(Arrays.asList(userids.split(",")));
}
}
return new Game(ids, names, creator, id, null, currPlayer, type, picUrl, mode);
}
else {
String id = c.getString(c.getColumnIndex(DBHelper.GAME_ID));
String type = c.getString(c.getColumnIndex(DBHelper.TYPE));
return new Game(null, null, null, id, null, null, type, null, null);
}
}
public static String getUserName(Context c, String userid) {
Cursor myCur = c.getContentResolver().query(USERS_URI,
new String[] {DBHelper.USER_USERNAME},
DBHelper.USERID+"=?",
new String[] {userid},
null);
myCur.moveToFirst();
if (myCur.getCount() > 0) {
String retString = myCur.getString(myCur.getColumnIndex(DBHelper.USER_USERNAME));
myCur.close();
return retString;
}
else {
return userid;
}
}
public static LinkedHashMap<String, HashMap<String, String>> wordCurToWordList(Context con, Cursor c) {
c.moveToFirst();
LinkedHashMap<String, HashMap<String, String>> wordList = new LinkedHashMap<String, HashMap<String, String>>();
while (!c.isAfterLast()) {
String word = c.getString(c.getColumnIndex(DBHelper.WORD));
String name = c.getString(c.getColumnIndex(DBHelper.WORD_USERNAME));
int order = c.getInt(c.getColumnIndex(DBHelper.MY_ORDER));
HashMap<String, String> wordToPlayer = new HashMap<String, String>();
wordToPlayer.put(word, name);
wordList.put(""+order, wordToPlayer);
c.moveToNext();
}
return wordList;
}
public static Games jsonStringToGamesList(String json) {
Gson gson2 = new Gson();
Games games = gson2.fromJson(json, Games.class);
return games;
}
public static Artists jsonStringToArtists(String json) {
Gson gson2 = new Gson();
Artists artists = gson2.fromJson(json, Artists.class);
return artists;
}
public static Movies jsonStringToMovies(String json) {
Gson gson2 = new Gson();
Movies movies = gson2.fromJson(json, Movies.class);
return movies;
}
public static TVShows jsonStringToTVShows(String json) {
Gson gson2 = new Gson();
TVShows shows = gson2.fromJson(json, TVShows.class);
return shows;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
Uri gameUri = null;
switch (uriMatcher.match(uri)) {
case GAME_ITEM:
gameUri = Uri.withAppendedPath(GAMES_URI, whereArgs[0]);
count = db.delete(GAMES_TABLE_NAME, where, whereArgs);
break;
case PLAYER_ITEM:
gameUri = Uri.withAppendedPath(USERS_URI, whereArgs[0]);
count = db.delete(USERS_TABLE_NAME, where, whereArgs);
break;
case WORD_ITEM:
gameUri = Uri.withAppendedPath(WORDS_URI, whereArgs[0]);
count = db.delete(WORDS_TABLE_NAME, where, whereArgs);
break;
case BOT_WORD_ITEM:
gameUri = Uri.withAppendedPath(BOT_WORDS_URI, whereArgs[0]);
count = db.delete(BOTWORDS_TABLE_NAME, where, whereArgs);
break;
case MESSAGE_ITEM:
gameUri = Uri.withAppendedPath(MESSAGES_URI, whereArgs[0]);
count = db.delete(MESSAGES_TABLE_NAME, where, whereArgs);
break;
case REGISTERED_FRIENDS:
count = db.delete(REGISTERED_FRIENDS_TABLE_NAME, where, whereArgs);
break;
case SCORE_ITEM:
gameUri = Uri.withAppendedPath(SCORE_URI, whereArgs[0]);
count = db.delete(SCORE_TABLE_NAME, where, whereArgs);
break;
case TEMP_WORD_ITEM:
count = db.delete(TEMP_WORDS_TABLE_NAME, where, whereArgs);
break;
case ALL:
count += db.delete(GAMES_TABLE_NAME, where, whereArgs);
count += db.delete(USERS_TABLE_NAME, null, null);
count += db.delete(WORDS_TABLE_NAME, null, null);
count += db.delete(SCORE_TABLE_NAME, null, null);
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
if (null != gameUri) {
getContext().getContentResolver().notifyChange(gameUri, null);
}
return count;
}
@Override
public String getType(Uri arg0) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long row = 0L;
Uri notifyUri = null;
switch (uriMatcher.match(uri)) {
// games/*
case GAME_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(GAMES_URI, values.getAsString("gameid"));
}
row = db.insert(GAMES_TABLE_NAME, "", values);
break;
// users/*
case PLAYER_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(USERS_URI, values.getAsString("gameid"));
}
row = db.insert(USERS_TABLE_NAME, "", values);
break;
// words/*
case WORD_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(WORDS_URI, values.getAsString("gameid"));
}
row = db.insert(WORDS_TABLE_NAME, "", values);
break;
case BOT_WORD_ITEM:
row = db.insert(BOTWORDS_TABLE_NAME, "", values);
break;
case REGISTERED_FRIENDS:
row = db.insert(REGISTERED_FRIENDS_TABLE_NAME, "", values);
break;
case SCORE_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(SCORE_URI, values.getAsString("gameid"));
}
row = db.insert(SCORE_TABLE_NAME, "", values);
break;
case TEMP_WORD_ITEM:
row = db.insert(TEMP_WORDS_TABLE_NAME, "", values);
break;
case MESSAGE_ITEM:
if (values.containsKey(DBHelper.THREAD_ID)) {
notifyUri = Uri.withAppendedPath(MESSAGES_URI, values.getAsString(DBHelper.THREAD_ID));
}
row = db.insert(MESSAGES_TABLE_NAME, "", values);
Cursor q = db.query(MESSAGES_TABLE_NAME, null, DBHelper.THREAD_ID+"=?", new String[] {values.getAsString(DBHelper.THREAD_ID)}, null, null, null);
if (q.getCount() > 19) {
db.delete(MESSAGES_TABLE_NAME, DBHelper.MY_ORDER+"=?", new String[] {String.valueOf(values.getAsInteger(DBHelper.MY_ORDER)-20)});
}
q.close();
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
// if successful
if (row > 0) {
getContext().getContentResolver().notifyChange(uri, null);
if (null != notifyUri) {
getContext().getContentResolver().notifyChange(notifyUri, null);
}
return uri;
}
return null;
}
@Override
public boolean onCreate() {
dbHelper = DBHelper.getInstance(getContext(), DATABASE_NAME);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case GAMES:
cursor = db.query(GAMES_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case PLAYERS:
cursor = db.query(USERS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case WORDS:
cursor = db.query(WORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOT_WORDS:
cursor = db.query(BOTWORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case MESSAGES:
cursor = db.query(MESSAGES_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case REGISTERED_FRIENDS:
cursor = db.query(REGISTERED_FRIENDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case SCORES:
cursor = db.query(SCORE_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case TEMP_WORDS:
cursor = db.query(TEMP_WORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count;
switch (uriMatcher.match(uri)) {
case GAME_ITEM:
count = db.update(GAMES_TABLE_NAME, values, where, whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
| [
"ebhalla@fan.tv"
] | ebhalla@fan.tv |
bfd56f800e9e01f8b898cefe8dbefa863d078447 | 7fa9c6b0fa1d0726ae1cda0199716c811a1ea01b | /Crawler/data/BillAction.java | fb6c3939f83e2e11b2dd60c398424fd3fd6e612a | [] | no_license | NayrozD/DD2476-Project | b0ca75799793d8ced8d4d3ba3c43c79bb84a72c0 | 94dfb3c0a470527b069e2e0fd9ee375787ee5532 | refs/heads/master | 2023-03-18T04:04:59.111664 | 2021-03-10T15:03:07 | 2021-03-10T15:03:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,470 | java | 12
https://raw.githubusercontent.com/Pingvin235/bgerp/master/src/ru/bgcrm/plugin/bgbilling/proto/struts/action/BillAction.java
package ru.bgcrm.plugin.bgbilling.proto.struts.action;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ru.bgcrm.model.BGException;
import ru.bgcrm.model.SearchResult;
import ru.bgcrm.plugin.bgbilling.proto.dao.BillDAO;
import ru.bgcrm.plugin.bgbilling.proto.model.bill.Bill;
import ru.bgcrm.plugin.bgbilling.proto.model.bill.Invoice;
import ru.bgcrm.plugin.bgbilling.struts.action.BaseAction;
import ru.bgcrm.struts.form.DynActionForm;
import ru.bgcrm.util.Utils;
import ru.bgcrm.util.sql.ConnectionSet;
public class BillAction
extends BaseAction
{
public ActionForward attributeList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
form.getResponse().setData( "list", new BillDAO( form.getUser(), billingId, moduleId ).getAttributeList( contractId ) );
return processUserTypedForward( conSet, mapping, form, response, "attributeList" );
}
public ActionForward docTypeList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
form.getResponse().setData( "billTypeList", billDao.getContractDocTypeList( contractId, "bill" ) );
form.getResponse().setData( "invoiceTypeList", billDao.getContractDocTypeList( contractId, "invoice" ) );
return processUserTypedForward( conSet, mapping, form, response, "docTypeList" );
}
public ActionForward docTypeAdd( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
new BillDAO( form.getUser(), billingId, moduleId ).contractDocTypeAdd( contractId, form.getParam( "typeIds" ) );
return processJsonForward( conSet, form, response );
}
public ActionForward docTypeDelete( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
new BillDAO( form.getUser(), billingId, moduleId ).contractDocTypeDelete( contractId, form.getParam( "typeIds" ) );
return processJsonForward( conSet, form, response );
}
public ActionForward documentList( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int contractId = form.getParamInt( "contractId" );
int moduleId = form.getParamInt( "moduleId" );
String mode = form.getParam( "mode", "bill" );
form.setParam( "mode", mode );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
if( "bill".equals( mode ) )
{
billDao.searchBillList( contractId, new SearchResult<Bill>( form ) );
}
else
{
billDao.searchInvoiceList( contractId, new SearchResult<Invoice>( form ) );
}
return processUserTypedForward( conSet, mapping, form, response, "documentList" );
}
public ActionForward getDocument( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int moduleId = form.getParamInt( "moduleId" );
String type = form.getParam( "type" );
String ids = form.getParam( "ids" );
try
{
OutputStream out = response.getOutputStream();
Utils.setFileNameHeades( response, type + ".pdf" );
out.write( new BillDAO( form.getUser(), billingId, moduleId ).getDocumentsPdf( ids, type ) );
}
catch( Exception ex )
{
throw new BGException( ex );
}
return null;
}
public ActionForward setPayed( ActionMapping mapping,
DynActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ConnectionSet conSet )
throws BGException
{
String billingId = form.getParam( "billingId" );
int moduleId = form.getParamInt( "moduleId" );
String ids = form.getParam( "ids" );
Date date = form.getParamDate( "date" );
BigDecimal summa = Utils.parseBigDecimal( form.getParam( "summa" ) );
String comment = form.getParam( "comment" );
BillDAO billDao = new BillDAO( form.getUser(), billingId, moduleId );
if( date != null )
{
billDao.setPayed( ids, true, date, summa, comment );
}
else
{
billDao.setPayed( ids, false, null, null, null );
}
return processJsonForward( conSet, form, response );
}
} | [
"veronika.cucorova@gmail.com"
] | veronika.cucorova@gmail.com |
b7ff8a9b8acd3a0abda0cc6e97ad9d353d8a7e44 | 99c03face59ec13af5da080568d793e8aad8af81 | /hom_classifier/2om_classifier/scratch/AOIS90AOIS9/Pawn.java | 0eaaa9bf50b6b060b92da2ca1cdcb7656e14cf5a | [] | no_license | fouticus/HOMClassifier | 62e5628e4179e83e5df6ef350a907dbf69f85d4b | 13b9b432e98acd32ae962cbc45d2f28be9711a68 | refs/heads/master | 2021-01-23T11:33:48.114621 | 2020-05-13T18:46:44 | 2020-05-13T18:46:44 | 93,126,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,761 | java | // This is a mutant program.
// Author : ysma
import java.util.ArrayList;
public class Pawn extends ChessPiece
{
public Pawn( ChessBoard board, ChessPiece.Color color )
{
super( board, color );
}
public java.lang.String toString()
{
if (color == ChessPiece.Color.WHITE) {
return "♙";
} else {
return "♟";
}
}
public java.util.ArrayList<String> legalMoves()
{
java.util.ArrayList<String> returnList = new java.util.ArrayList<String>();
if (this.getColor().equals( ChessPiece.Color.WHITE )) {
int currentCol = this.getColumn();
int nextRow = this.getRow() + 1;
if (nextRow <= 7) {
if (board.getPiece( onePossibleMove( nextRow, ++currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 1) {
int nextNextRow = this.getRow() + 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
} else {
int currentCol = this.getColumn();
int nextRow = this.getRow() - 1;
if (nextRow >= 0) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow--, currentCol ) );
}
}
if (this.getRow() == 6) {
int nextNextRow = this.getRow() - 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
}
return returnList;
}
} | [
"fout.alex@gmail.com"
] | fout.alex@gmail.com |
fb64b815d5766bb477bdb7c395b966464176326b | 51e0883ba6ba3faed7dad80fb7c8826051b2b251 | /src/main/java/org/example/simplehttpserver/config/Configuration.java | 886c06abbf57edc6465f69826f72dee981431e0e | [] | no_license | samyum918/simplehttpserver | f480325b983da44d8f9ef298f60526606c6673c4 | d2bbb5f24437d3196f4862c7024614fa1687e671 | refs/heads/master | 2023-01-19T12:55:52.110420 | 2020-11-29T15:20:22 | 2020-11-29T15:20:22 | 316,453,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 192 | java | package org.example.simplehttpserver.config;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Configuration {
private Integer port;
private String webroot;
}
| [
"sam.yum@worldline.com"
] | sam.yum@worldline.com |
9e633f2684b6043a9483ed6894f897a99b218a0a | 94e10d222730dbc7925fe44c38d2eba8f1f19eea | /app/src/main/java/com/txunda/construction_worker/utils/ShareForApp.java | a6838e9c09318b1ce5a84b99bbd0dfe18f58919f | [] | no_license | Qsrx/construction_worker | 3293cfb6322e3052c941b0d2411ac7c17f69d796 | 7f2103cbc35bec551f87f7dc5266d46dc7991f5a | refs/heads/master | 2020-04-29T01:36:26.626064 | 2019-03-26T03:27:34 | 2019-03-26T03:27:34 | 175,736,253 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,247 | java | package com.txunda.construction_worker.utils;
import android.graphics.Bitmap;
import android.util.Log;
import com.zhy.http.okhttp.utils.L;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
/**
* ===============Txunda===============
* 作者:DUKE_HwangZj
* 日期:2017/6/30 0030
* 时间:下午 4:49
* 描述:分享
* ===============Txunda===============
*/
public class ShareForApp implements PlatformActionListener {
// /**
// * 分享平台
// */
// public enum PlatformForShare {
// QQ, Qzon, Sine, Wechat, WechatMoments, FACEBOOK, WHATSAPP, INSRAGRAM, SinaWeibo
// }
//
// /**
// * 分享之后的状态
// */
// public enum StatusForShare {
// Success, Error, Cancel
// }
//
// /**
// * 分享平台的名称
// */
// private String platFormName;
// /**
// * 分享的图片
// */
// private Bitmap bitmap;
// /**
// * 图片链接
// */
// private String picUrl;
//
// /**
// * 标题
// */
// private String title;
// /**
// * 分享文本
// */
// private String text;
// /**
// * 标题链接
// */
// private String titleUrl;
//
// private ShareBeBackListener shareBeBackListener;
//
// /**
// * 够造函数
// *
// * @param platFormName 平台名称
// * @param bitmap 分享的图片
// * @param title 标题
// * @param text 文本
// * @param titleUrl 标题连接
// */
// public ShareForApp(String platFormName, Bitmap bitmap, String title, String text, String titleUrl,
// ShareBeBackListener shareBeBackListener) {
// this.platFormName = platFormName;
// this.bitmap = bitmap;
// this.title = title;
// this.text = text;
// this.titleUrl = titleUrl;
// this.shareBeBackListener = shareBeBackListener;
// }
//
// public ShareForApp(String platFormName, String picUrl, String title, String text, String titleUrl,
// ShareBeBackListener shareBeBackListener) {
// this.platFormName = platFormName;
// this.picUrl = picUrl;
// this.title = title;
// this.text = text;
// this.titleUrl = titleUrl;
// this.shareBeBackListener = shareBeBackListener;
// }
//
//
// public void toShare() {
// Platform.ShareParams sp = new Platform.ShareParams();
// sp.setTitle(title);
// sp.setText(text);// 分享文本
//
// if (platFormName.equals(Wechat.NAME)) {
// sp.setUrl(titleUrl);
// }
//// else if (platFormName.equals(SinaWeibo.NAME) || platFormName.equals(QQ.NAME)) {
//// sp.setTitleUrl(titleUrl);
//// }
// sp.setImageData(bitmap);
// // 3、非常重要:获取平台对象
// Platform wechathy = ShareSDK.getPlatform(platFormName);
// wechathy.setPlatformActionListener(this); // 设置分享事件回调
// // 执行分享
// wechathy.share(sp);
// Log.d("zdl", "toShare: 分享");
// }
//
// // SHARE_WEBPAGE 分享网页
//// SHARE_TEXT 分享文本
//// SHARE_IMAGE 分享图片
// public void toShareWithPicUrl() {
// Platform.ShareParams sp = new Platform.ShareParams();
// if (platFormName.equals(Wechat.NAME)) {// 微信
//// if (type == 1) {
//// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
//// sp.setImageUrl(picUrl);
//// sp.setUrl(titleUrl);
//// }else if (type == 3){
////
//// } else if (type == 4){
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImagePath(picUrl);
//// }
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// }
// else if (platFormName.equals(QQ.NAME)) {// QQ
//// if (type == 1) {
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// } else if (type == 3){
////
//// sp.setImageUrl(picUrl);
//// } else if (type == 4){
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImagePath(picUrl);
//// }
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// } else if (platFormName.equals(WechatMoments.NAME)) {//朋友圈
// sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
// sp.setImageUrl(picUrl);
//// sp.setShareType(Platform.SHARE_IMAGE);//分享图片
//// sp.setImageData(bitmap);
// sp.setTitleUrl(titleUrl);
// }
// sp.setTitle(title);
// sp.setText(text);// 分享文本
// // 3、非常重要:获取平台对象
// Platform wechathy = ShareSDK.getPlatform(platFormName);
// wechathy.setPlatformActionListener(this); // 设置分享事件回调
// // 执行分享
// wechathy.share(sp);
// L.e("分享");
// }
//
// @Override
// public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
// Log.e("=====成功=====", hashMap.toString());
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Success, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Success, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Success, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Success, i);
// }
// }
//
// @Override
// public void onError(Platform platform, int i, Throwable throwable) {
// Log.e("=====失败====", String.valueOf(i) + "=====" + throwable.getMessage());
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Error, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Error, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Error, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Error, i);
// }
// }
//
// @Override
// public void onCancel(Platform platform, int i) {
// Log.e("=====取消====", String.valueOf(i));
//// if (platform.getName().equals(SinaWeibo.NAME)) {// 微博
//// shareBeBackListener.beBack(SinaWeibo, StatusForShare.Cancel, i);
//// } else
// if (platform.getName().equals(Wechat.NAME)) {// 微信
// shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Cancel, i);
// } else if (platform.getName().equals(QQ.NAME)) {// QQ
// shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Cancel, i);
// } else if (platform.getName().equals(WechatMoments.NAME)) {//微信朋友圈
// shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Cancel, i);
// }
// }
/**
* 分享平台
*/
public enum PlatformForShare {
QQ, Qzon, Sine, Wechat, WechatMoments, FACEBOOK, WHATSAPP, INSRAGRAM, SinaWeibo
}
/**
* 分享之后的状态
*/
public enum StatusForShare {
Success, Error, Cancel
}
/**
* 分享平台的名称
*/
private String platFormName;
/**
* 分享的图片
*/
private Bitmap bitmap;
/**
* 图片链接
*/
private String picUrl;
/**
* 标题
*/
private String title;
/**
* 分享文本
*/
private String text;
/**
* 标题链接
*/
private String titleUrl;
private ShareBeBackListener shareBeBackListener;
/**
* 够造函数
*
* @param platFormName 平台名称
* @param bitmap 分享的图片
* @param title 标题
* @param text 文本
* @param titleUrl 标题连接
*/
public ShareForApp(String platFormName, Bitmap bitmap, String title, String text, String titleUrl,
ShareBeBackListener shareBeBackListener) {
this.platFormName = platFormName;
this.bitmap = bitmap;
this.title = title;
this.text = text;
this.titleUrl = titleUrl;
this.shareBeBackListener = shareBeBackListener;
}
public ShareForApp(String platFormName, String picUrl, String title, String text, String titleUrl,
ShareBeBackListener shareBeBackListener) {
this.platFormName = platFormName;
this.picUrl = picUrl;
this.title = title;
this.text = text;
this.titleUrl = titleUrl;
this.shareBeBackListener = shareBeBackListener;
}
public void toShare() {
Platform.ShareParams sp = new Platform.ShareParams();
sp.setTitle(title);
sp.setText(text);// 分享文本
if (platFormName.equals(Wechat.NAME)) {
sp.setUrl(titleUrl);
} else if (platFormName.equals(QQ.NAME)) {
sp.setTitleUrl(titleUrl);
}
sp.setImageData(bitmap);
// 3、非常重要:获取平台对象
Platform wechathy = ShareSDK.getPlatform(platFormName);
wechathy.setPlatformActionListener(this); // 设置分享事件回调
// 执行分享
wechathy.share(sp);
Log.d("zdl", "toShare: 分享");
}
// SHARE_WEBPAGE 分享网页
// SHARE_TEXT 分享文本
// SHARE_IMAGE 分享图片
public void toShareWithPicUrl(int type) {
Platform.ShareParams sp = new Platform.ShareParams();
if (platFormName.equals(Wechat.NAME)) {// 微信
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
sp.setUrl(titleUrl);
}else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
} else if (platFormName.equals(QQ.NAME)) {// QQ
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
} else if (platFormName.equals(WechatMoments.NAME)) {//朋友圈
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
} else {
if (type == 1) {
sp.setShareType(Platform.SHARE_WEBPAGE);//分享网页
sp.setImageUrl(picUrl);
} else if (type == 3){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImageUrl(picUrl);
} else if (type == 4){
sp.setShareType(Platform.SHARE_IMAGE);//分享图片
sp.setImagePath(picUrl);
}
sp.setTitleUrl(titleUrl);
}
sp.setTitle(title);
sp.setText(text);// 分享文本
// 3、非常重要:获取平台对象
Platform wechathy = ShareSDK.getPlatform(platFormName);
wechathy.setPlatformActionListener(this); // 设置分享事件回调
// 执行分享
wechathy.share(sp);
L.e("分享");
}
@Override
public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
Log.e("=====成功=====", hashMap.toString());
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Success, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Success, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Success, i);
}
}
@Override
public void onError(Platform platform, int i, Throwable throwable) {
Log.e("=====失败====", String.valueOf(i) + "=====" + throwable.getMessage());
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Error, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Error, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Error, i);
}
}
@Override
public void onCancel(Platform platform, int i) {
Log.e("=====取消====", String.valueOf(i));
if (platform.getName().equals(Wechat.NAME)) {// 微信
shareBeBackListener.beBack(PlatformForShare.Wechat, StatusForShare.Cancel, i);
} else if (platform.getName().equals(QQ.NAME)) {// QQ
shareBeBackListener.beBack(PlatformForShare.QQ, StatusForShare.Cancel, i);
} else if (platform.getName().equals(WechatMoments.NAME)) {//微信朋友圈
shareBeBackListener.beBack(PlatformForShare.WechatMoments, StatusForShare.Cancel, i);
}
}
} | [
"””浮“1964348142@qq.com"
] | ””浮“1964348142@qq.com |
ddd620f10b0fd29370b7309a0374fe85fe1e4903 | 5db5f33faab148887324b1a01cdb6373b14d4ead | /app/src/main/java/com/zjzf/shoescircleandroid/model/GoodsListInfo.java | d2d6c4410e4097c1efa8123d9ee24b871fa2cca0 | [] | no_license | UserChenille/Android-ShoesCircle | 745ce70a23638d6dfa446e67342b091779a87833 | 66fa171227f6c28b75c95f03cd9d9699a7e159a1 | refs/heads/master | 2020-04-30T01:33:27.315683 | 2019-03-20T06:27:11 | 2019-03-20T06:27:11 | 176,531,765 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,727 | java | package com.zjzf.shoescircleandroid.model;
import com.zjzf.shoescircle.lib.base.baseadapter.MultiType;
import java.util.List;
/**
* Created by 陈志远 on 2018/8/5.
*/
public class GoodsListInfo {
/**
* offset : 0
* limit : 2147483647
* total : 8
* size : 1
* pages : 8
* current : 1
* searchCount : true
* openSort : true
* orderByField : id
* records : [{"id":1015889815853224000,"enable":1,"createTime":"2018-07-08 09:29:37","memId":1,"member":{"id":1,"enable":1,"createTime":"2018-07-08 08:46:54","account":"hehaoyang","phone":"15857193035","memName":"何昊阳","avatar":"","sex":0,"evaluate":5,"score":0,"level":1},"name":"乔丹6","photo":"tfhf23121312","freightNo":"AA223AA5","size":"41,42","price":111,"state":1}]
* condition : null
* asc : true
* offsetCurrent : 0
*/
private int offset;
private int limit;
private int total;
private int size;
private int pages;
private int current;
private boolean searchCount;
private boolean openSort;
private String orderByField;
private Object condition;
private boolean asc;
private int offsetCurrent;
private List<RecordsBean> records;
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
public boolean isSearchCount() {
return searchCount;
}
public void setSearchCount(boolean searchCount) {
this.searchCount = searchCount;
}
public boolean isOpenSort() {
return openSort;
}
public void setOpenSort(boolean openSort) {
this.openSort = openSort;
}
public String getOrderByField() {
return orderByField;
}
public void setOrderByField(String orderByField) {
this.orderByField = orderByField;
}
public Object getCondition() {
return condition;
}
public void setCondition(Object condition) {
this.condition = condition;
}
public boolean isAsc() {
return asc;
}
public void setAsc(boolean asc) {
this.asc = asc;
}
public int getOffsetCurrent() {
return offsetCurrent;
}
public void setOffsetCurrent(int offsetCurrent) {
this.offsetCurrent = offsetCurrent;
}
public List<RecordsBean> getRecords() {
return records;
}
public void setRecords(List<RecordsBean> records) {
this.records = records;
}
public static class RecordsBean implements MultiType {
/**
* id : 1015889815853224000
* enable : 1
* createTime : 2018-07-08 09:29:37
* memId : 1
* member : {"id":1,"enable":1,"createTime":"2018-07-08 08:46:54","account":"hehaoyang","phone":"15857193035","memName":"何昊阳","avatar":"","sex":0,"evaluate":5,"score":0,"level":1}
* name : 乔丹6
* photo : tfhf23121312
* freightNo : AA223AA5
* size : 41,42
* price : 111
* state : 1
*/
private long id;
private int enable;
private String createTime;
private int memId;
private MemberBean member;
private String name;
private String photo;
private String freightNo;
private String size;
private int price;
private int state;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getMemId() {
return memId;
}
public void setMemId(int memId) {
this.memId = memId;
}
public MemberBean getMember() {
return member;
}
public void setMember(MemberBean member) {
this.member = member;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getFreightNo() {
return freightNo;
}
public void setFreightNo(String freightNo) {
this.freightNo = freightNo;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public int getItemType() {
return 0;
}
public static class MemberBean {
/**
* id : 1
* enable : 1
* createTime : 2018-07-08 08:46:54
* account : hehaoyang
* phone : 15857193035
* memName : 何昊阳
* avatar :
* sex : 0
* evaluate : 5
* score : 0
* level : 1
*/
private int id;
private int enable;
private String createTime;
private String account;
private String phone;
private String memName;
private String avatar;
private int sex;
private int evaluate;
private int score;
private int level;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMemName() {
return memName;
}
public void setMemName(String memName) {
this.memName = memName;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getEvaluate() {
return evaluate;
}
public void setEvaluate(int evaluate) {
this.evaluate = evaluate;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
}
}
| [
"1520941160@qq.com"
] | 1520941160@qq.com |
a742ecf4ea58c5bca8930ab04591b7e0b212f81f | 5cb1f58740c658712b514696d9df284b3000ab8c | /src/main/java/com/mn/data/GifRepositoryImpl.java | e785ce3a5e13ac7f68fdbf2545486548f7b7b0d7 | [] | no_license | michaln889/DemotyApp | eb44163ec8df78e905fe75b8aef26281d8103b69 | 780bfd84a537a25443b2295ba8062a5ac2d23f89 | refs/heads/master | 2021-01-19T09:08:31.662506 | 2017-12-19T18:47:57 | 2017-12-19T18:47:57 | 87,725,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,176 | java | package com.mn.data;
import com.mn.model.Gif;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Repository
public class GifRepositoryImpl implements GifRepository
{
private List<Gif> allGifs = Arrays.asList(
new Gif(1, "gif1", "aaa", LocalDate.now(), false, 1),
new Gif(2, "gif2", "bbb", LocalDate.now(), true, 2),
new Gif(3, "gif3", "ccc", LocalDate.now(), true, 3),
new Gif(4, "gif4", "ddd", LocalDate.now(), false, 1),
new Gif(5, "gif5", "eee", LocalDate.now(), true, 2),
new Gif(6, "2841-1792494-StickSkok", "fff", LocalDate.now(), false, 2)
);
@Autowired
private UserRepository userRepository;
@Override
public List<Gif> findAll()
{
return allGifs;
}
@Override
public Gif findByName(String name)
{
for(Gif el : allGifs)
{
if(el.getName().equals(name))
{
return el;
}
}
return null;
}
@Override
public List<Gif> findFavorites()
{
List<Gif> gifs = new ArrayList<>();
for(Gif el : allGifs)
{
if(el.isFavorite())
{
gifs.add(el);
}
}
return gifs;
}
@Override
public List<Gif> findByCategoryId(int id)
{
List<Gif> gifs = new ArrayList<>();
for(Gif el : allGifs)
{
if(el.getCategoryId() == id)
{
gifs.add(el);
}
}
return gifs;
}
@Override
public Gif findById(int id) {
for(Gif el : allGifs)
{
if(el.getId() == id)
{
return el;
}
}
return null;
}
@Override
public void makeFavoriteOrUnfavorite(Gif gif) {
if(!gif.isFavorite())
{
gif.setFavorite(true);
}
else
{
gif.setFavorite(false);
}
}
}
| [
"michaln889@gmail.com"
] | michaln889@gmail.com |
bc1cd170315f1090182d952d663abad30fa0e7fc | 917372f7a06e20f694c8577d39ef3c552819d78d | /app/src/main/java/com/example/android/sunshine/data/SunshinePreferences.java | 9a88c5f17514d52481792e81dea0e8036a55bc4a | [] | no_license | augustmary/SunshineApp | cce610aa7fc5c361f697342ca906327decdb1a43 | ee1dd8aa9fc9961d3872290304ebb25f8bc79e80 | refs/heads/master | 2021-06-15T19:50:50.131981 | 2017-03-10T15:45:39 | 2017-03-10T15:45:39 | 81,199,350 | 0 | 0 | null | 2017-03-10T15:53:58 | 2017-02-07T11:07:58 | Java | UTF-8 | Java | false | false | 6,176 | java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;
import com.example.android.sunshine.R;
public class SunshinePreferences {
/*
* Human readable location string, provided by the API. Because for styling,
* "Mountain View" is more recognizable than 94043.
*/
public static final String PREF_CITY_NAME = "city_name";
/*
* In order to uniquely pinpoint the location on the map when we launch the
* map intent, we store the latitude and longitude.
*/
public static final String PREF_COORD_LAT = "coord_lat";
public static final String PREF_COORD_LONG = "coord_long";
/*
* Before you implement methods to return your REAL preference for location,
* we provide some default values to work with.
*/
private static final String DEFAULT_WEATHER_LOCATION = "94043,USA";
private static final double[] DEFAULT_WEATHER_COORDINATES = {37.4284, 122.0724};
private static final String DEFAULT_MAP_LOCATION =
"1600 Amphitheatre Parkway, Mountain View, CA 94043";
/**
* Helper method to handle setting location details in Preferences (City Name, Latitude,
* Longitude)
*
* @param c Context used to get the SharedPreferences
* @param cityName A human-readable city name, e.g "Mountain View"
* @param lat The latitude of the city
* @param lon The longitude of the city
*/
static public void setLocationDetails(Context c, String cityName, double lat, double lon) {
/** This will be implemented in a future lesson **/
}
/**
* Helper method to handle setting a new location in preferences. When this happens
* the database may need to be cleared.
*
* @param c Context used to get the SharedPreferences
* @param locationSetting The location string used to request updates from the server.
* @param lat The latitude of the city
* @param lon The longitude of the city
*/
static public void setLocation(Context c, String locationSetting, double lat, double lon) {
/** This will be implemented in a future lesson **/
}
/**
* Resets the stored location coordinates.
*
* @param c Context used to get the SharedPreferences
*/
static public void resetLocationCoordinates(Context c) {
/** This will be implemented in a future lesson **/
}
/**
* Returns the location currently set in Preferences. The default location this method
* will return is "94043,USA", which is Mountain View, California. Mountain View is the
* home of the headquarters of the Googleplex!
*
* @param context Context used to get the SharedPreferences
* @return Location The current user has set in SharedPreferences. Will default to
* "94043,USA" if SharedPreferences have not been implemented yet.
*/
public static String getPreferredWeatherLocation(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String keyForLocation = context.getString(R.string.pref_location_key);
String defaultLocation = context.getString(R.string.pref_location_default);
return prefs.getString(keyForLocation, defaultLocation);
}
/**
* Returns true if the user has selected metric temperature display.
*
* @param context Context used to get the SharedPreferences
* @return true If metric display should be used
*/
public static boolean isMetric(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String keyForUnits = context.getString(R.string.pref_units_key);
String defaultUnits = context.getString(R.string.pref_units_metric);
String preferredUnits = prefs.getString(keyForUnits, defaultUnits);
String metric = context.getString(R.string.pref_units_metric);
boolean userPrefersMetric;
userPrefersMetric = metric.equals(preferredUnits);
return userPrefersMetric;
}
/**
* Returns the location coordinates associated with the location. Note that these coordinates
* may not be set, which results in (0,0) being returned. (conveniently, 0,0 is in the middle
* of the ocean off the west coast of Africa)
*
* @param context Used to get the SharedPreferences
* @return An array containing the two coordinate values.
*/
public static double[] getLocationCoordinates(Context context) {
return getDefaultWeatherCoordinates();
}
/**
* Returns true if the latitude and longitude values are available. The latitude and
* longitude will not be available until the lesson where the PlacePicker API is taught.
*
* @param context used to get the SharedPreferences
* @return true if lat/long are set
*/
public static boolean isLocationLatLonAvailable(Context context) {
/** This will be implemented in a future lesson **/
return false;
}
private static String getDefaultWeatherLocation() {
/** This will be implemented in a future lesson **/
return DEFAULT_WEATHER_LOCATION;
}
public static double[] getDefaultWeatherCoordinates() {
/** This will be implemented in a future lesson **/
return DEFAULT_WEATHER_COORDINATES;
}
} | [
"shumeykoms@gmail.com"
] | shumeykoms@gmail.com |
a94a67b2223b07c2b730132a93f0a5869353712b | d785d788a3f4765ad998795a7dfb3607acbca81a | /ACSL_base/src/org/dalton/acsl3/abc15/ACSL3_ABC15_c16mn.java | de39bed478ee37504de8ad76be9675011348de7b | [] | no_license | daltonschool/ACSL_base | 6f77c6dd39e16061ee96b0abd50946206e1a7cbe | c021472f4cb4f0476652eb4e3f96039dd5150861 | refs/heads/master | 2021-05-04T11:18:51.860150 | 2017-01-03T03:42:14 | 2017-01-03T03:42:14 | 46,642,526 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,301 | java | package org.dalton.acsl3.abc15;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class ACSL3_ABC15_c16mn {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true){
String[][] grid = new String[6][6];
gridSetter(grid);
String[] input = scan.nextLine().split(", ");
for (int i = 0; i < 4; i++) {
//parsing double array values from grid position
grid[Integer.valueOf(input[i])/6][Integer.valueOf(input[i])%6 - 1] = "X";
}
//placing initial letters on grid
int counter = 0;
for (int i = 6; i < input.length; i+=2) {
if(Integer.valueOf(input[i]) < 7){
int row = 1;
if(grid[row][Integer.valueOf(input[i])-1].equals("X")) row++;
grid[row][Integer.valueOf(input[i])-1] = input[i-1];
}else if(Integer.valueOf(input[i])%6 == 1){
int column = 1;
if(grid[Integer.valueOf(input[i])/6][column].equals("X")) column++;
grid[Integer.valueOf(input[i])/6][column] = input[i-1];
}else if(Integer.valueOf(input[i])%6 == 0){
int column = 4;
if(grid[(Integer.valueOf(input[i])/6)-1][column].equals("X")) column--;
grid[Integer.valueOf(input[i])/6-1][column] = input[i-1];
}else if(Integer.valueOf(input[i]) > 30){
int row = 4;
if(grid[row][(Integer.valueOf(input[i])%6)-1].equals("X")) row--;
grid[row][(Integer.valueOf(input[i])%6)-1] = input[i-1];
}
}
// gridPrinter(gridConverter(grid));
// System.out.println();
grid = gridSolver(gridConverter(grid));
// gridPrinter(grid);
// System.out.println();
System.out.println(gridToString(grid));
}
}
public static String gridToString(String[][] grid){
String result = "";
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if(!grid[i][j].equals("X") && !grid[i][j].equals("0")) result += grid[i][j];
}
}
return result;
}
public static String[][] gridSolver(String[][] grid){
if(gridChecker(grid)) return grid;
for (int i = 0; i < grid.length; i++) {
grid[i] = missingChecker(grid[i]);
}
String[] column = new String[grid.length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < column.length; j++) {
column[j] = grid[j][i];
}
column = missingChecker(column);
for (int j = 0; j < column.length; j++) {
grid[j][i] = column[j];
}
}
// gridPrinter(grid);
// System.out.println();
grid = overlap(grid);
return gridSolver(grid);
}
public static String[][] overlap(String[][] grid){
String[][] columns = new String[grid.length][grid.length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
columns[i][j] = grid[j][i];
}
}
for (int i = 0; i < grid.length; i++) {
List<Integer> numzeros = new ArrayList<Integer>();
String letter = "";
for (int j = 0; j < grid[i].length; j++) {
if(grid[i][j] == "0"){
numzeros.add(j);
}
if(!grid[i][j].equals("X") && !grid[i][j].equals("0")) letter = grid[i][j];
}
if(numzeros.size() == 2){
for (int j = 0; j < numzeros.size(); j++) {
if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("A") && !Arrays.asList(columns[numzeros.get(j)]).contains("A") && !letter.equals("A")){
grid[i][numzeros.get(j)] = "A";
break;
}else if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("B") && !Arrays.asList(columns[numzeros.get(j)]).contains("B") && !letter.equals("B")){
grid[i][numzeros.get(j)] = "B";
break;
}else if(Arrays.asList(columns[numzeros.get((j+1)%2)]).contains("C") && !Arrays.asList(columns[numzeros.get(j)]).contains("C") && !letter.equals("C")){
grid[i][numzeros.get(j)] = "C";
break;
}
}
// System.out.println("row overlap");
// gridPrinter(grid);
// System.out.println();
}
}
for (int i = 0; i < grid.length; i++) {
List<Integer> numzeros = new ArrayList<Integer>();
String letter = "";
for (int j = 0; j < grid[i].length; j++) {
if(grid[j][i] == "0") numzeros.add(j);
letter = grid[j][i];
}
if(numzeros.size() == 2){
for (int j = 0; j < numzeros.size(); j++) {
if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("A") && !Arrays.asList(grid[numzeros.get(j)]).contains("A") && !letter.equals("A")){
grid[numzeros.get(j)][i] = "A";
break;
}else if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("B") && !Arrays.asList(grid[numzeros.get(j)]).contains("B") && !letter.equals("B")){
grid[numzeros.get(j)][i] = "B";
break;
}else if(Arrays.asList(grid[numzeros.get((j+1)%2)]).contains("C") && !Arrays.asList(grid[numzeros.get(j)]).contains("C") && !letter.equals("C")){
grid[numzeros.get(j)][i] = "C";
break;
}
}
// System.out.println("column overlap");
// gridPrinter(grid);
// System.out.println();
}
}
return grid;
}
public static String[] missingChecker(String[] input){
int letters = 'A' + 'B' + 'C' + 'X';
int zerocount = 0;
int place = 0;
for (int i = 0; i < input.length; i++) {
if(input[i] == "0"){
zerocount ++;
place = i;
}
else letters = letters - input[i].charAt(0);
}
if(zerocount == 1){
char letter = (char) letters;
input[place] = "" + letter;
return input;
}
else return input;
}
public static boolean gridChecker(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if(grid[i][j].equals("0")) return false;
}
}
return true;
}
public static String[][] gridConverter(String[][] grid){
String[][] result = new String[4][4];
int k = 0;
for (int i = 1; i < grid.length; i++) {
int l = 0;
if(i == grid.length - 1) break;
for (int j = 1; j < grid[i].length; j++) {
if(j == grid[i].length - 1) break;
result[k][l] = grid[i][j];
l++;
}
k++;
}
return result;
}
public static void gridSetter(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = "0";
}
}
}
public static void gridPrinter(String[][] grid){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(" " + grid[i][j] + " ");
}
System.out.println();
}
}
}
| [
"charlie@forsters.com"
] | charlie@forsters.com |
7674dd0c711fa9aedce42c32d7f59c933350214e | d179c3a428566e4dccf5f55bdd2d812f7d5bc833 | /src/main/java/org/sejda/sambox/rendering/RenderDestination.java | 9e6b63b691b79316d580d4535755bf8441f154c3 | [
"Apache-2.0",
"LicenseRef-scancode-apple-excl",
"BSD-3-Clause",
"APAFML"
] | permissive | torakiki/sambox | ea82fb22583f7e5f316c740a632d5c1891e5d067 | c8a6d26aa0b133130a90df104e3bb267ff13a19f | refs/heads/master | 2023-08-10T12:17:25.490810 | 2023-08-01T15:30:51 | 2023-08-01T15:30:51 | 30,909,947 | 48 | 16 | Apache-2.0 | 2023-08-01T15:08:27 | 2015-02-17T09:14:01 | Java | UTF-8 | Java | false | false | 1,053 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.rendering;
/**
* Optional content groups are visible depending on the render purpose.
*/
public enum RenderDestination
{
/** graphics export */
EXPORT,
/** viewing */
VIEW,
/** printing */
PRINT
}
| [
"andrea.vacondio@gmail.com"
] | andrea.vacondio@gmail.com |
9b419ac9e57cc461b10bde501edbdcf71c3a148a | faac256e67bdcb268054939c5f841d8b706f52e1 | /app/src/main/java/zw/co/vokers/zoledge/reader/camera/GraphicOverlay.java | c408e58373d69e2ac302d4f1d2a8aa1cec34316d | [] | no_license | VinceGee/ZOLEdge | 9b425e3f588277c344921bf13e81d6441c8f74ce | 6dd48be95b22ac20fce4e95ca04b054f6f2b3e68 | refs/heads/master | 2020-03-22T05:40:06.390930 | 2018-07-03T12:46:12 | 2018-07-03T12:46:12 | 139,582,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,141 | java | /*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package zw.co.vokers.zoledge.reader.camera;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
/**
* A view which renders a series of custom graphics to be overlayed on top of an associated preview
* (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove
* them, triggering the appropriate drawing and invalidation within the view.<p>
*
* Supports scaling and mirroring of the graphics relative the camera's preview properties. The
* idea is that detection items are expressed in terms of a preview size, but need to be scaled up
* to the full view size, and also mirrored in the case of the front-facing camera.<p>
*
* Associated {@link Graphic} items should use the following methods to convert to view coordinates
* for the graphics that are drawn:
* <ol>
* <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the
* supplied value from the preview scale to the view scale.</li>
* <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate
* from the preview's coordinate system to the view coordinate system.</li>
* </ol>
*/
public class GraphicOverlay<T extends GraphicOverlay.Graphic> extends View {
private final Object mLock = new Object();
private int mPreviewWidth;
private float mWidthScaleFactor = 1.0f;
private int mPreviewHeight;
private float mHeightScaleFactor = 1.0f;
private int mFacing = CameraSource.CAMERA_FACING_BACK;
private Set<T> mGraphics = new HashSet<>();
/**
* Base class for a custom graphics object to be rendered within the graphic overlay. Subclass
* this and implement the {@link Graphic#draw(Canvas)} method to define the
* graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}.
*/
public static abstract class Graphic {
private GraphicOverlay mOverlay;
public Graphic(GraphicOverlay overlay) {
mOverlay = overlay;
}
/**
* Draw the graphic on the supplied canvas. Drawing should use the following methods to
* convert to view coordinates for the graphics that are drawn:
* <ol>
* <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of
* the supplied value from the preview scale to the view scale.</li>
* <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the
* coordinate from the preview's coordinate system to the view coordinate system.</li>
* </ol>
*
* @param canvas drawing canvas
*/
public abstract void draw(Canvas canvas);
/**
* Adjusts a horizontal value of the supplied value from the preview scale to the view
* scale.
*/
public float scaleX(float horizontal) {
return horizontal * mOverlay.mWidthScaleFactor;
}
/**
* Adjusts a vertical value of the supplied value from the preview scale to the view scale.
*/
public float scaleY(float vertical) {
return vertical * mOverlay.mHeightScaleFactor;
}
/**
* Adjusts the x coordinate from the preview's coordinate system to the view coordinate
* system.
*/
public float translateX(float x) {
if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) {
return mOverlay.getWidth() - scaleX(x);
} else {
return scaleX(x);
}
}
/**
* Adjusts the y coordinate from the preview's coordinate system to the view coordinate
* system.
*/
public float translateY(float y) {
return scaleY(y);
}
public void postInvalidate() {
mOverlay.postInvalidate();
}
}
public GraphicOverlay(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Removes all graphics from the overlay.
*/
public void clear() {
synchronized (mLock) {
mGraphics.clear();
}
postInvalidate();
}
/**
* Adds a graphic to the overlay.
*/
public void add(T graphic) {
synchronized (mLock) {
mGraphics.add(graphic);
}
postInvalidate();
}
/**
* Removes a graphic from the overlay.
*/
public void remove(T graphic) {
synchronized (mLock) {
mGraphics.remove(graphic);
}
postInvalidate();
}
/**
* Returns a copy (as a list) of the set of all active graphics.
* @return list of all active graphics.
*/
public List<T> getGraphics() {
synchronized (mLock) {
return new Vector(mGraphics);
}
}
/**
* Returns the horizontal scale factor.
*/
public float getWidthScaleFactor() {
return mWidthScaleFactor;
}
/**
* Returns the vertical scale factor.
*/
public float getHeightScaleFactor() {
return mHeightScaleFactor;
}
/**
* Sets the camera attributes for size and facing direction, which informs how to transform
* image coordinates later.
*/
public void setCameraInfo(int previewWidth, int previewHeight, int facing) {
synchronized (mLock) {
mPreviewWidth = previewWidth;
mPreviewHeight = previewHeight;
mFacing = facing;
}
postInvalidate();
}
/**
* Draws the overlay with its associated graphic objects.
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
synchronized (mLock) {
if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) {
mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
}
for (Graphic graphic : mGraphics) {
graphic.draw(canvas);
}
}
}
}
| [
"vinceg@Vincents-MacBook-Pro.local"
] | vinceg@Vincents-MacBook-Pro.local |
465973d5e0e14b135b293e90611da2f1f927053a | 1f19aec2ecfd756934898cf0ad2758ee18d9eca2 | /u-1/u-1-f358.java | 49c23582263b09add8527098aa5a8f6b86b876e3 | [] | no_license | apertureatf/perftest | f6c6e69efad59265197f43af5072aa7af8393a34 | 584257a0c1ada22e5486052c11395858a87b20d5 | refs/heads/master | 2020-06-07T17:52:51.172890 | 2019-06-21T18:53:01 | 2019-06-21T18:53:01 | 193,039,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117
7304672759536 | [
"jenkins@khan.paloaltonetworks.local"
] | jenkins@khan.paloaltonetworks.local |
305820bc3039753328eb71f7846ae6608184f5b2 | 4bd2ddf7cd2b0e3e87c78d7d81d6df1c5bdc1cda | /xh5/x5-bpmx-root/modules/x5-bpmx-core/src/main/java/com/hotent/bpmx/core/defxml/entity/CallConversation.java | 132fccccde3f5a6d8a769dbbd96b7ea4d71ebd9c | [] | no_license | codingOnGithub/hx | 27a873a308528eb968632bbf97e6e25107f92a9f | c93d6c23032ff798d460ee9a0efaba214594a6b9 | refs/heads/master | 2021-05-27T14:40:05.776605 | 2014-10-22T16:52:34 | 2014-10-22T16:52:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,269 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.11 at 10:08:02 AM CST
//
package com.hotent.bpmx.core.defxml.entity;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
/**
* <p>Java class for tCallConversation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tCallConversation">
* <complexContent>
* <extension base="{http://www.omg.org/spec/BPMN/20100524/MODEL}tConversationNode">
* <sequence>
* <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}participantAssociation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="calledCollaborationRef" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tCallConversation", propOrder = {
"participantAssociation"
})
public class CallConversation
extends ConversationNode
{
protected List<ParticipantAssociation> participantAssociation;
@XmlAttribute(name = "calledCollaborationRef")
protected QName calledCollaborationRef;
/**
* Gets the value of the participantAssociation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the participantAssociation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParticipantAssociation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ParticipantAssociation }
*
*
*/
public List<ParticipantAssociation> getParticipantAssociation() {
if (participantAssociation == null) {
participantAssociation = new ArrayList<ParticipantAssociation>();
}
return this.participantAssociation;
}
/**
* Gets the value of the calledCollaborationRef property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getCalledCollaborationRef() {
return calledCollaborationRef;
}
/**
* Sets the value of the calledCollaborationRef property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setCalledCollaborationRef(QName value) {
this.calledCollaborationRef = value;
}
}
| [
"wang2009long@126.com"
] | wang2009long@126.com |
ea5c4eb86da0047497dbc77ee53c601138b960b9 | 300947e343fbe069ff64a49b4151b7fa81ab2c30 | /Timber-master/Timber-master/app/src/main/java/naman14/timber/StreamYoutubecrome.java | 95f441b1275fe97ca2180ed049c0df6fac215fcc | [] | no_license | Sripathm2/Timber | 342dadc81f2f8872e5d87cd145bc8dfef3fddda4 | ff1f79f08752b76307cb3957a40336577cdd39c3 | refs/heads/master | 2021-06-10T04:49:09.223490 | 2017-01-23T20:22:26 | 2017-01-23T20:22:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 883 | java | package naman14.timber;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import com.naman14.timber.R;
public class StreamYoutubecrome extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_youtubecrome);
Intent intent = getIntent();
String output=intent.getStringExtra("check");
output.replaceAll(" ","+");
String url="https://www.youtube.com/results?search_query=+"+output;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
}
}
| [
"sripathm2@gmail.com"
] | sripathm2@gmail.com |
697228fa9e44a5f204e0aa8b7118cba717a797e3 | 17f00d0aecce8af1979f787709c3313a082b384b | /fm-workbench/trusted-build/edu.umn.cs.crisys.smaccm.aadl2camkes/src/edu/umn/cs/crisys/smaccm/aadl2camkes/ast/IdType.java | ffbf4dc65ea34dbb32437c4ec30dc059bb7f2369 | [] | no_license | three-jeeps/smaccm | 490100fc55bc765ea06a08323622520d0457b58f | cfcd09ffb485683c7e59a6674df40e5bd0dcab0a | refs/heads/master | 2021-01-15T14:46:48.785880 | 2015-01-08T02:32:52 | 2015-01-08T02:32:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,985 | java | /*
Copyright (c) 2011,2013 Rockwell Collins and the University of Minnesota.
Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA).
Permission is hereby granted, free of charge, to any person obtaining a copy of this data,
including any software or models in source or binary form, as well as any drawings, specifications,
and documentation (collectively "the Data"), to deal in the Data without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Data.
THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
package edu.umn.cs.crisys.smaccm.aadl2camkes.ast;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.umn.cs.crisys.smaccm.aadl2camkes.Aadl2CamkesException;
import edu.umn.cs.crisys.smaccm.aadl2camkes.Aadl2CamkesFailure;
public class IdType extends Type {
private final String typeId;
private Type typeRef = null;
public IdType(String tid) {
typeId = tid;
}
public String getTypeId() {
return typeId;
}
// TODO: this may be problematic for type aliases.
// Type aliases are not supported in CORBA IDL.
public boolean isBaseType() { return false ; }
public Type getTypeRef() { return typeRef; }
private Type getRootTypeInt(Set<Type> visited) {
if (visited.contains(this)) {
throw new Aadl2CamkesException("Circular reference in ids for type " + typeId);
}
else if (typeRef instanceof IdType) {
visited.add(this);
return ((IdType)typeRef).getRootTypeInt(visited);
}
else {
return typeRef;
}
}
@Override
public Type getRootType() throws Aadl2CamkesFailure {
Set<Type> visited = new HashSet<Type>();
try {
return getRootTypeInt(visited);
} catch (Aadl2CamkesException e) {
Aadl2CamkesFailure f = new Aadl2CamkesFailure();
f.addMessage(e.toString());
f.addMessage("Circular reference in ids for type " + typeId);
throw f;
}
}
@Override
public void init(Map<String, Type> types) {
assert(types != null);
Type ty = types.get(typeId);
if (ty == null) {
throw new Aadl2CamkesException("Unable to find type " + typeId + " (last lookup: " + typeId + ")");
}
else {
typeRef = ty;
}
}
@Override
public String toString() {
return typeId;
}
}
| [
"andrew.gacek@gmail.com"
] | andrew.gacek@gmail.com |
61c455ea1cb69c5b2d8e3b54ea7c75e55cc70bc0 | fd55f9688db9e059f170bbd270df5f628feb9c4b | /app/src/main/java/com/example/sierzega/projectforclasses/MainActivity.java | d896ff644d13300772df60526c93d078c26f3d16 | [] | no_license | Swierscz/Projectforclasses | b7963b86d9ba2229e1ca169a88ee5dc664005014 | 7b3ba0bf906ba215f95da13ce99d7b8a0d64c73e | refs/heads/master | 2020-03-18T11:46:28.671498 | 2018-05-24T09:10:58 | 2018-05-24T09:10:58 | 134,690,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,115 | java | package com.example.sierzega.projectforclasses;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private NumberHolder numberHolder;
private ArrayAdapter<String> arrayAdapter;
public static final String BASE_URL = "http://192.168.42.229:8080/";
Retrofit retrofit;
MyApiEndpointInterface apiService;
EditText amountOfNumbersToGenerate, edtTxtAvgValue;
Button btnGenerateNumbers, btnCalculateAvgValue;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(MyApiEndpointInterface.class);
numberHolder = NumberHolder.getInstance();
initializeViewComponents();
btnGenerateNumbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
numberHolder.fillListWithData(getRandomNumbersFromServer());
updateListOfNumbersWithGeneratedValues();
}
});
thread.start();
}
});
btnCalculateAvgValue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
apiService.sendNumbersValues(numberHolder.getListOfIntegers()).enqueue(new Callback<List<Integer>>() {
@Override
public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) {
getAvgValueFromServerAndUpdateTextField();
}
@Override
public void onFailure(Call<List<Integer>> call, Throwable t) {
Log.i(TAG, "Sending numbers failed");
}
});
}
});
thread.start();
}
});
}
private void updateListOfNumbersWithGeneratedValues() {
arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, ListConversionUtils.convertIntegersToStringsInList(numberHolder.getListOfIntegers()));
runOnUiThread(new Runnable() {
@Override
public void run() {
listView.setAdapter(arrayAdapter);
}
});
}
private void initializeViewComponents() {
btnGenerateNumbers = (Button) findViewById(R.id.btnGenerateNumbers);
btnCalculateAvgValue = (Button) findViewById(R.id.btnCalculateAvgValue);
listView = (ListView) findViewById(R.id.lvListOfNumbers);
amountOfNumbersToGenerate = (EditText) findViewById(R.id.edtTxtAmountOfNumbersToGenerate);
edtTxtAvgValue = (EditText) findViewById(R.id.edtTxtAvgValue);
}
public List<Integer> getRandomNumbersFromServer() {
Call<List<Integer>> callWithListOfNumbers = apiService.getRandomNumbers(Integer.parseInt(amountOfNumbersToGenerate.getText().toString()));
List<Integer> tempList;
try {
tempList = callWithListOfNumbers.execute().body();
return tempList;
} catch (IOException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
public void getAvgValueFromServerAndUpdateTextField() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final Call<Integer> callValue = apiService.getAvgValue();
int i = 0;
try {
i = callValue.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
edtTxtAvgValue.setText("" + finalI);
}
});
}
});
thread.start();
}
}
| [
"jsierzega@student.wat.edu.pl"
] | jsierzega@student.wat.edu.pl |
6dc52096d920e5d26d895b2c54fbf6a815953e69 | 6bfc5a1efdbbe337dca4a71c3ed53054bf662a82 | /src/grimonium/set/GrimoniumSet.java | ac144c367c19765c2d291ce920b6c2003d67c4dc | [] | no_license | michaelforrest/grimonium | d99945779edbc08654eea97c687d8ffb0ecf21fd | 1f582d8f59e262ee84a28ddebf0e5741392fa78e | refs/heads/master | 2021-01-16T19:33:29.737744 | 2009-02-12T17:44:47 | 2009-02-12T17:44:47 | 97,209 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,191 | java | package grimonium.set;
import grimonium.Ableton;
import grimonium.GrimoniumOutput;
import grimonium.Ableton.MidiTrack;
import grimonium.gui.Colours;
import grimonium.gui.MixerSource;
import grimonium.maps.ElementFactory;
import grimonium.maps.EncoderMap;
import grimonium.maps.FaderMap;
import grimonium.maps.MapBase;
import java.util.ArrayList;
import microkontrol.MicroKontrol;
import microkontrol.controls.Button;
import microkontrol.controls.EncoderListener;
import processing.xml.XMLElement;
public class GrimoniumSet extends CollectionWithSingleSelectedItem implements EncoderListener, MixerSource{
public Song[] songs;
private MicroKontrol mk;
private MapBase[] commonElements;
private Song beforeShiftPressed;
public GrimoniumSet(XMLElement child) {
if(!child.getName().equals("set")) return;
mk = MicroKontrol.getInstance();
addCommon(child.getChild("common"));
addSongs(child.getChildren("songs/song"));
setCollection(songs);
activateSong(0);
mk.encoders[8].listen(this);
mk.buttons.get("HEX LOCK").listen(Button.PRESSED,this,"onShiftPressed" );
mk.buttons.get("HEX LOCK").listen(Button.RELEASED,this,"onShiftReleased" );
}
public void onShiftPressed(){
beforeShiftPressed = current();
select(songs[songs.length-1]);
GuiController.update();
}
public void onShiftReleased(){
select(beforeShiftPressed);
GuiController.update();
}
private void addCommon(XMLElement child) {
commonElements = new MapBase[child.getChildren().length];
for (int i = 0; i < child.getChildren().length; i++) {
XMLElement element = child.getChildren()[i];
MapBase control = ElementFactory.create(element);
control.activate();
commonElements[i] = control;
}
}
private void activateSong(int index) {
select(songs[index]);
}
@Override
public void select(Object object) {
if(current() != null) current().deactivate();
super.select(object);
current().activate();
GrimoniumOutput.visualsChanged(current().visuals);
}
public Song current() {
return (Song) super.current();
}
private void addSongs(XMLElement[] children) {
songs = new Song[children.length];
for (int i = 0; i < children.length; i++) {
XMLElement element = children[i];
Song song = new Song(element);
songs[i] = song;
}
}
public void moved(Integer delta) {
changeSelectionByOffset(delta);
}
public Song currentSong() {
return current();
}
public ArrayList<EncoderMap> getEncoders() {
return MapBase.collectEncoders(commonElements);
}
public ArrayList<FaderMap> getFaders() {
return MapBase.collectFaders(commonElements);
}
public int getColour() {
return 0x22000000 + Colours.get("blue");
}
public void previousSong() {
changeSelectionByOffset(-1);
}
public void nextSong() {
changeSelectionByOffset(1);
}
public int getAlpha() {
return 0xFF;
}
public float getTint() {
return 255;
}
public void stopClipsFromOtherSongs() {
for(MidiTrack track : Ableton.midiTracks){
stopTrackUnlessInGroup(track);
}
}
private void stopTrackUnlessInGroup(MidiTrack track) {
for(ClipGroup group : current().groups){
if(group.track == track.channel) return;
}
if(track.stop!=null) track.stop.trigger();
}
}
| [
"michael.forrest@gmail.com"
] | michael.forrest@gmail.com |
20a7fa62ab28dab7fe1434e3b9d4f28a1d815e4c | e2837676303164d27f42dbcfbcf8cbbf6659ed02 | /microservice-course-management/src/main/java/com/sha/microservicecoursemanagement/repository/CourseRepository.java | e7e946f69c34efeca12f21922ba49cab2b867850 | [] | no_license | erkan4534/microservices | 2860e135bfa9c37421536844cb58247a5e2fca92 | ad5d428f0f56b5e15ebe6e3f8a4d9d82cbd4a836 | refs/heads/main | 2023-04-24T10:10:06.697476 | 2021-05-16T18:57:20 | 2021-05-16T18:57:20 | 358,974,175 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 252 | java | package com.sha.microservicecoursemanagement.repository;
import com.sha.microservicecoursemanagement.model.Course;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<Course,Long> {
}
| [
"erkanyildirim28@gmail.com"
] | erkanyildirim28@gmail.com |
5c2b7cb0b131bde0090495a684bd0d9b49a79266 | 7dca9d068fe6d18803cb568f3792363d652c5570 | /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClient.java | 10defcf3829e116383c05b8c80a5cec467ecf29f | [] | no_license | biafra23/AmDroid | 2c0d68dc9bd559c5a811123681261ef10d9e5700 | 3aad88fff8a6d8c0eb9e3be22b23a60c25916285 | refs/heads/master | 2016-09-06T17:22:56.390353 | 2012-07-31T20:09:24 | 2012-07-31T20:09:24 | 2,485,574 | 16 | 2 | null | null | null | null | UTF-8 | Java | false | false | 39,008 | java | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.client.cache;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
/* LogFactory removed by HttpClient for Android script. */
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HeaderElement;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpHost;
import ch.boye.httpclientandroidlib.HttpMessage;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.HttpStatus;
import ch.boye.httpclientandroidlib.HttpVersion;
import ch.boye.httpclientandroidlib.ProtocolException;
import ch.boye.httpclientandroidlib.ProtocolVersion;
import ch.boye.httpclientandroidlib.RequestLine;
import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
import ch.boye.httpclientandroidlib.client.ClientProtocolException;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.ResponseHandler;
import ch.boye.httpclientandroidlib.client.cache.CacheResponseStatus;
import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
import ch.boye.httpclientandroidlib.impl.cookie.DateParseException;
import ch.boye.httpclientandroidlib.impl.cookie.DateUtils;
import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.EntityUtils;
import ch.boye.httpclientandroidlib.util.VersionInfo;
/**
* <p>The {@link CachingHttpClient} is meant to be a drop-in replacement for
* a {@link DefaultHttpClient} that transparently adds client-side caching.
* The current implementation is conditionally compliant with HTTP/1.1
* (meaning all the MUST and MUST NOTs are obeyed), although quite a lot,
* though not all, of the SHOULDs and SHOULD NOTs are obeyed too. Generally
* speaking, you construct a {@code CachingHttpClient} by providing a
* "backend" {@link HttpClient} used for making actual network requests and
* provide an {@link HttpCacheStorage} instance to use for holding onto
* cached responses. Additional configuration options can be provided by
* passing in a {@link CacheConfig}. Note that all of the usual client
* related configuration you want to do vis-a-vis timeouts and connection
* pools should be done on this backend client before constructing a {@code
* CachingHttpClient} from it.</p>
*
* <p>Generally speaking, the {@code CachingHttpClient} is implemented as a
* <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>
* of the backend client; for any incoming request it attempts to satisfy
* it from the cache, but if it can't, or if it needs to revalidate a stale
* cache entry, it will use the backend client to make an actual request.
* However, a proper HTTP/1.1 cache won't change the semantics of a request
* and response; in particular, if you issue an unconditional request you
* will get a full response (although it may be served to you from the cache,
* or the cache may make a conditional request on your behalf to the origin).
* This notion of "semantic transparency" means you should be able to drop
* a {@link CachingHttpClient} into an existing application without breaking
* anything.</p>
*
* <p>Folks that would like to experiment with alternative storage backends
* should look at the {@link HttpCacheStorage} interface and the related
* package documentation there. You may also be interested in the provided
* {@link ch.boye.httpclientandroidlib.impl.client.cache.ehcache.EhcacheHttpCacheStorage
* EhCache} and {@link
* ch.boye.httpclientandroidlib.impl.client.cache.memcached.MemcachedHttpCacheStorage
* memcached} storage backends.</p>
* </p>
* @since 4.1
*/
@ThreadSafe // So long as the responseCache implementation is threadsafe
public class CachingHttpClient implements HttpClient {
/**
* This is the name under which the {@link
* ch.boye.httpclientandroidlib.client.cache.CacheResponseStatus} of a request
* (for example, whether it resulted in a cache hit) will be recorded if an
* {@link HttpContext} is provided during execution.
*/
public static final String CACHE_RESPONSE_STATUS = "http.cache.response.status";
private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false;
private final AtomicLong cacheHits = new AtomicLong();
private final AtomicLong cacheMisses = new AtomicLong();
private final AtomicLong cacheUpdates = new AtomicLong();
private final HttpClient backend;
private final HttpCache responseCache;
private final CacheValidityPolicy validityPolicy;
private final ResponseCachingPolicy responseCachingPolicy;
private final CachedHttpResponseGenerator responseGenerator;
private final CacheableRequestPolicy cacheableRequestPolicy;
private final CachedResponseSuitabilityChecker suitabilityChecker;
private final ConditionalRequestBuilder conditionalRequestBuilder;
private final int maxObjectSizeBytes;
private final boolean sharedCache;
private final ResponseProtocolCompliance responseCompliance;
private final RequestProtocolCompliance requestCompliance;
private final AsynchronousValidator asynchRevalidator;
public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
CachingHttpClient(
HttpClient client,
HttpCache cache,
CacheConfig config) {
super();
if (client == null) {
throw new IllegalArgumentException("HttpClient may not be null");
}
if (cache == null) {
throw new IllegalArgumentException("HttpCache may not be null");
}
if (config == null) {
throw new IllegalArgumentException("CacheConfig may not be null");
}
this.maxObjectSizeBytes = config.getMaxObjectSizeBytes();
this.sharedCache = config.isSharedCache();
this.backend = client;
this.responseCache = cache;
this.validityPolicy = new CacheValidityPolicy();
this.responseCachingPolicy = new ResponseCachingPolicy(maxObjectSizeBytes, sharedCache);
this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy);
this.cacheableRequestPolicy = new CacheableRequestPolicy();
this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, config);
this.conditionalRequestBuilder = new ConditionalRequestBuilder();
this.responseCompliance = new ResponseProtocolCompliance();
this.requestCompliance = new RequestProtocolCompliance();
this.asynchRevalidator = makeAsynchronousValidator(config);
}
/**
* Constructs a {@code CachingHttpClient} with default caching settings that
* stores cache entries in memory and uses a vanilla {@link DefaultHttpClient}
* for backend requests.
*/
public CachingHttpClient() {
this(new DefaultHttpClient(),
new BasicHttpCache(),
new CacheConfig());
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options that
* stores cache entries in memory and uses a vanilla {@link DefaultHttpClient}
* for backend requests.
* @param config cache module options
*/
public CachingHttpClient(CacheConfig config) {
this(new DefaultHttpClient(),
new BasicHttpCache(config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with default caching settings that
* stores cache entries in memory and uses the given {@link HttpClient}
* for backend requests.
* @param client used to make origin requests
*/
public CachingHttpClient(HttpClient client) {
this(client,
new BasicHttpCache(),
new CacheConfig());
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options that
* stores cache entries in memory and uses the given {@link HttpClient}
* for backend requests.
* @param config cache module options
* @param client used to make origin requests
*/
public CachingHttpClient(HttpClient client, CacheConfig config) {
this(client,
new BasicHttpCache(config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options
* that stores cache entries in the provided storage backend and uses
* the given {@link HttpClient} for backend requests. However, cached
* response bodies are managed using the given {@link ResourceFactory}.
* @param client used to make origin requests
* @param resourceFactory how to manage cached response bodies
* @param storage where to store cache entries
* @param config cache module options
*/
public CachingHttpClient(
HttpClient client,
ResourceFactory resourceFactory,
HttpCacheStorage storage,
CacheConfig config) {
this(client,
new BasicHttpCache(resourceFactory, storage, config),
config);
}
/**
* Constructs a {@code CachingHttpClient} with the given caching options
* that stores cache entries in the provided storage backend and uses
* the given {@link HttpClient} for backend requests.
* @param client used to make origin requests
* @param storage where to store cache entries
* @param config cache module options
*/
public CachingHttpClient(
HttpClient client,
HttpCacheStorage storage,
CacheConfig config) {
this(client,
new BasicHttpCache(new HeapResourceFactory(), storage, config),
config);
}
CachingHttpClient(
HttpClient backend,
CacheValidityPolicy validityPolicy,
ResponseCachingPolicy responseCachingPolicy,
HttpCache responseCache,
CachedHttpResponseGenerator responseGenerator,
CacheableRequestPolicy cacheableRequestPolicy,
CachedResponseSuitabilityChecker suitabilityChecker,
ConditionalRequestBuilder conditionalRequestBuilder,
ResponseProtocolCompliance responseCompliance,
RequestProtocolCompliance requestCompliance) {
CacheConfig config = new CacheConfig();
this.maxObjectSizeBytes = config.getMaxObjectSizeBytes();
this.sharedCache = config.isSharedCache();
this.backend = backend;
this.validityPolicy = validityPolicy;
this.responseCachingPolicy = responseCachingPolicy;
this.responseCache = responseCache;
this.responseGenerator = responseGenerator;
this.cacheableRequestPolicy = cacheableRequestPolicy;
this.suitabilityChecker = suitabilityChecker;
this.conditionalRequestBuilder = conditionalRequestBuilder;
this.responseCompliance = responseCompliance;
this.requestCompliance = requestCompliance;
this.asynchRevalidator = makeAsynchronousValidator(config);
}
private AsynchronousValidator makeAsynchronousValidator(
CacheConfig config) {
if (config.getAsynchronousWorkersMax() > 0) {
return new AsynchronousValidator(this, config);
}
return null;
}
/**
* Reports the number of times that the cache successfully responded
* to an {@link HttpRequest} without contacting the origin server.
* @return the number of cache hits
*/
public long getCacheHits() {
return cacheHits.get();
}
/**
* Reports the number of times that the cache contacted the origin
* server because it had no appropriate response cached.
* @return the number of cache misses
*/
public long getCacheMisses() {
return cacheMisses.get();
}
/**
* Reports the number of times that the cache was able to satisfy
* a response by revalidating an existing but stale cache entry.
* @return the number of cache revalidations
*/
public long getCacheUpdates() {
return cacheUpdates.get();
}
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
HttpContext defaultContext = null;
return execute(target, request, defaultContext);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler) throws IOException {
return execute(target, request, responseHandler, null);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException {
HttpResponse resp = execute(target, request, context);
return handleAndConsume(responseHandler,resp);
}
public HttpResponse execute(HttpUriRequest request) throws IOException {
HttpContext context = null;
return execute(request, context);
}
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
URI uri = request.getURI();
HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
return execute(httpHost, request, context);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
throws IOException {
return execute(request, responseHandler, null);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
HttpResponse resp = execute(request, context);
return handleAndConsume(responseHandler, resp);
}
private <T> T handleAndConsume(
final ResponseHandler<? extends T> responseHandler,
HttpResponse response) throws Error, IOException {
T result;
try {
result = responseHandler.handleResponse(response);
} catch (Exception t) {
HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new UndeclaredThrowableException(t);
}
// Handling the response was successful. Ensure that the content has
// been fully consumed.
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
return result;
}
public ClientConnectionManager getConnectionManager() {
return backend.getConnectionManager();
}
public HttpParams getParams() {
return backend.getParams();
}
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
// default response context
setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
String via = generateViaHeader(request);
if (clientRequestsOurOptions(request)) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new OptionsHttp11Response();
}
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
request, context);
if (fatalErrorResponse != null) return fatalErrorResponse;
request = requestCompliance.makeRequestCompliant(request);
request.addHeader("Via",via);
flushEntriesInvalidatedByRequest(target, request);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
return callBackend(target, request, context);
}
HttpCacheEntry entry = satisfyFromCache(target, request);
if (entry == null) {
return handleCacheMiss(target, request, context);
}
return handleCacheHit(target, request, context, entry);
}
private HttpResponse handleCacheHit(HttpHost target, HttpRequest request,
HttpContext context, HttpCacheEntry entry)
throws ClientProtocolException, IOException {
recordCacheHit(target, request);
Date now = getCurrentDate();
if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
return generateCachedResponse(request, context, entry, now);
}
if (!mayCallBackend(request)) {
return generateGatewayTimeout(context);
}
if (validityPolicy.isRevalidatable(entry)) {
return revalidateCacheEntry(target, request, context, entry, now);
}
return callBackend(target, request, context);
}
private HttpResponse revalidateCacheEntry(HttpHost target,
HttpRequest request, HttpContext context, HttpCacheEntry entry,
Date now) throws ClientProtocolException {
log.trace("Revalidating the cache entry");
try {
if (asynchRevalidator != null
&& !staleResponseNotAllowed(request, entry, now)
&& validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
final HttpResponse resp = generateCachedResponse(request, context, entry, now);
asynchRevalidator.revalidateCacheEntry(target, request, context, entry);
return resp;
}
return revalidateCacheEntry(target, request, context, entry);
} catch (IOException ioex) {
return handleRevalidationFailure(request, context, entry, now);
} catch (ProtocolException e) {
throw new ClientProtocolException(e);
}
}
private HttpResponse handleCacheMiss(HttpHost target, HttpRequest request,
HttpContext context) throws IOException {
recordCacheMiss(target, request);
if (!mayCallBackend(request)) {
return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
}
Map<String, Variant> variants =
getExistingCacheVariants(target, request);
if (variants != null && variants.size() > 0) {
return negotiateResponseFromVariants(target, request, context, variants);
}
return callBackend(target, request, context);
}
private HttpCacheEntry satisfyFromCache(HttpHost target, HttpRequest request) {
HttpCacheEntry entry = null;
try {
entry = responseCache.getCacheEntry(target, request);
} catch (IOException ioe) {
log.warn("Unable to retrieve entries from cache", ioe);
}
return entry;
}
private HttpResponse getFatallyNoncompliantResponse(HttpRequest request,
HttpContext context) {
HttpResponse fatalErrorResponse = null;
List<RequestProtocolError> fatalError = requestCompliance.requestIsFatallyNonCompliant(request);
for (RequestProtocolError error : fatalError) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
fatalErrorResponse = requestCompliance.getErrorForRequest(error);
}
return fatalErrorResponse;
}
private Map<String, Variant> getExistingCacheVariants(HttpHost target,
HttpRequest request) {
Map<String,Variant> variants = null;
try {
variants = responseCache.getVariantCacheEntriesWithEtags(target, request);
} catch (IOException ioe) {
log.warn("Unable to retrieve variant entries from cache", ioe);
}
return variants;
}
private void recordCacheMiss(HttpHost target, HttpRequest request) {
cacheMisses.getAndIncrement();
if (log.isTraceEnabled()) {
RequestLine rl = request.getRequestLine();
log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]");
}
}
private void recordCacheHit(HttpHost target, HttpRequest request) {
cacheHits.getAndIncrement();
if (log.isTraceEnabled()) {
RequestLine rl = request.getRequestLine();
log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]");
}
}
private void recordCacheUpdate(HttpContext context) {
cacheUpdates.getAndIncrement();
setResponseStatus(context, CacheResponseStatus.VALIDATED);
}
private void flushEntriesInvalidatedByRequest(HttpHost target,
HttpRequest request) {
try {
responseCache.flushInvalidatedCacheEntriesFor(target, request);
} catch (IOException ioe) {
log.warn("Unable to flush invalidated entries from cache", ioe);
}
}
private HttpResponse generateCachedResponse(HttpRequest request,
HttpContext context, HttpCacheEntry entry, Date now) {
final HttpResponse cachedResponse;
if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
|| request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
cachedResponse = responseGenerator.generateNotModifiedResponse(entry);
} else {
cachedResponse = responseGenerator.generateResponse(entry);
}
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
if (validityPolicy.getStalenessSecs(entry, now) > 0L) {
cachedResponse.addHeader("Warning","110 localhost \"Response is stale\"");
}
return cachedResponse;
}
private HttpResponse handleRevalidationFailure(HttpRequest request,
HttpContext context, HttpCacheEntry entry, Date now) {
if (staleResponseNotAllowed(request, entry, now)) {
return generateGatewayTimeout(context);
} else {
return unvalidatedCacheHit(context, entry);
}
}
private HttpResponse generateGatewayTimeout(HttpContext context) {
setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
return new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout");
}
private HttpResponse unvalidatedCacheHit(HttpContext context,
HttpCacheEntry entry) {
final HttpResponse cachedResponse = responseGenerator.generateResponse(entry);
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
return cachedResponse;
}
private boolean staleResponseNotAllowed(HttpRequest request,
HttpCacheEntry entry, Date now) {
return validityPolicy.mustRevalidate(entry)
|| (isSharedCache() && validityPolicy.proxyRevalidate(entry))
|| explicitFreshnessRequest(request, entry, now);
}
private boolean mayCallBackend(HttpRequest request) {
for (Header h: request.getHeaders("Cache-Control")) {
for (HeaderElement elt : h.getElements()) {
if ("only-if-cached".equals(elt.getName())) {
return false;
}
}
}
return true;
}
private boolean explicitFreshnessRequest(HttpRequest request, HttpCacheEntry entry, Date now) {
for(Header h : request.getHeaders("Cache-Control")) {
for(HeaderElement elt : h.getElements()) {
if ("max-stale".equals(elt.getName())) {
try {
int maxstale = Integer.parseInt(elt.getValue());
long age = validityPolicy.getCurrentAgeSecs(entry, now);
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
if (age - lifetime > maxstale) return true;
} catch (NumberFormatException nfe) {
return true;
}
} else if ("min-fresh".equals(elt.getName())
|| "max-age".equals(elt.getName())) {
return true;
}
}
}
return false;
}
private String generateViaHeader(HttpMessage msg) {
final VersionInfo vi = VersionInfo.loadVersionInfo("ch.boye.httpclientandroidlib.client", getClass().getClassLoader());
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
final ProtocolVersion pv = msg.getProtocolVersion();
if ("http".equalsIgnoreCase(pv.getProtocol())) {
return String.format("%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getMajor(), pv.getMinor(), release);
} else {
return String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getProtocol(), pv.getMajor(), pv.getMinor(), release);
}
}
private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) {
if (context != null) {
context.setAttribute(CACHE_RESPONSE_STATUS, value);
}
}
/**
* Reports whether this {@code CachingHttpClient} implementation
* supports byte-range requests as specified by the {@code Range}
* and {@code Content-Range} headers.
* @return {@code true} if byte-range requests are supported
*/
public boolean supportsRangeAndContentRangeHeaders() {
return SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS;
}
/**
* Reports whether this {@code CachingHttpClient} is configured as
* a shared (public) or non-shared (private) cache. See {@link
* CacheConfig#setSharedCache(boolean)}.
* @return {@code true} if we are behaving as a shared (public)
* cache
*/
public boolean isSharedCache() {
return sharedCache;
}
Date getCurrentDate() {
return new Date();
}
boolean clientRequestsOurOptions(HttpRequest request) {
RequestLine line = request.getRequestLine();
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod()))
return false;
if (!"*".equals(line.getUri()))
return false;
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue()))
return false;
return true;
}
HttpResponse callBackend(HttpHost target, HttpRequest request, HttpContext context)
throws IOException {
Date requestDate = getCurrentDate();
log.trace("Calling the backend");
HttpResponse backendResponse = backend.execute(target, request, context);
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
return handleBackendResponse(target, request, requestDate, getCurrentDate(),
backendResponse);
}
private boolean revalidationResponseIsTooOld(HttpResponse backendResponse,
HttpCacheEntry cacheEntry) {
final Header entryDateHeader = cacheEntry.getFirstHeader("Date");
final Header responseDateHeader = backendResponse.getFirstHeader("Date");
if (entryDateHeader != null && responseDateHeader != null) {
try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
if (respDate.before(entryDate)) return true;
} catch (DateParseException e) {
// either backend response or cached entry did not have a valid
// Date header, so we can't tell if they are out of order
// according to the origin clock; thus we can skip the
// unconditional retry recommended in 13.2.6 of RFC 2616.
}
}
return false;
}
HttpResponse negotiateResponseFromVariants(HttpHost target,
HttpRequest request, HttpContext context,
Map<String, Variant> variants) throws IOException {
HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequestFromVariants(request, variants);
Date requestDate = getCurrentDate();
HttpResponse backendResponse = backend.execute(target, conditionalRequest, context);
Date responseDate = getCurrentDate();
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
return handleBackendResponse(target, request, requestDate, responseDate, backendResponse);
}
Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
if (resultEtagHeader == null) {
log.warn("304 response did not contain ETag");
return callBackend(target, request, context);
}
String resultEtag = resultEtagHeader.getValue();
Variant matchingVariant = variants.get(resultEtag);
if (matchingVariant == null) {
log.debug("304 response did not contain ETag matching one sent in If-None-Match");
return callBackend(target, request, context);
}
HttpCacheEntry matchedEntry = matchingVariant.getEntry();
if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) {
return retryRequestUnconditionally(target, request, context,
matchedEntry);
}
recordCacheUpdate(context);
HttpCacheEntry responseEntry = getUpdatedVariantEntry(target,
conditionalRequest, requestDate, responseDate, backendResponse,
matchingVariant, matchedEntry);
HttpResponse resp = responseGenerator.generateResponse(responseEntry);
tryToUpdateVariantMap(target, request, matchingVariant);
if (shouldSendNotModifiedResponse(request, responseEntry)) {
return responseGenerator.generateNotModifiedResponse(responseEntry);
}
return resp;
}
private HttpResponse retryRequestUnconditionally(HttpHost target,
HttpRequest request, HttpContext context,
HttpCacheEntry matchedEntry) throws IOException {
HttpRequest unconditional = conditionalRequestBuilder
.buildUnconditionalRequest(request, matchedEntry);
return callBackend(target, unconditional, context);
}
private HttpCacheEntry getUpdatedVariantEntry(HttpHost target,
HttpRequest conditionalRequest, Date requestDate,
Date responseDate, HttpResponse backendResponse,
Variant matchingVariant, HttpCacheEntry matchedEntry) {
HttpCacheEntry responseEntry = matchedEntry;
try {
responseEntry = responseCache.updateVariantCacheEntry(target, conditionalRequest,
matchedEntry, backendResponse, requestDate, responseDate, matchingVariant.getCacheKey());
} catch (IOException ioe) {
log.warn("Could not update cache entry", ioe);
}
return responseEntry;
}
private void tryToUpdateVariantMap(HttpHost target, HttpRequest request,
Variant matchingVariant) {
try {
responseCache.reuseVariantEntryFor(target, request, matchingVariant);
} catch (IOException ioe) {
log.warn("Could not update cache entry to reuse variant", ioe);
}
}
private boolean shouldSendNotModifiedResponse(HttpRequest request,
HttpCacheEntry responseEntry) {
return (suitabilityChecker.isConditional(request)
&& suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date()));
}
HttpResponse revalidateCacheEntry(
HttpHost target,
HttpRequest request,
HttpContext context,
HttpCacheEntry cacheEntry) throws IOException, ProtocolException {
HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry);
Date requestDate = getCurrentDate();
HttpResponse backendResponse = backend.execute(target, conditionalRequest, context);
Date responseDate = getCurrentDate();
if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) {
HttpRequest unconditional = conditionalRequestBuilder
.buildUnconditionalRequest(request, cacheEntry);
requestDate = getCurrentDate();
backendResponse = backend.execute(target, unconditional, context);
responseDate = getCurrentDate();
}
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
int statusCode = backendResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) {
recordCacheUpdate(context);
}
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(target, request, cacheEntry,
backendResponse, requestDate, responseDate);
if (suitabilityChecker.isConditional(request)
&& suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) {
return responseGenerator.generateNotModifiedResponse(updatedEntry);
}
return responseGenerator.generateResponse(updatedEntry);
}
if (staleIfErrorAppliesTo(statusCode)
&& !staleResponseNotAllowed(request, cacheEntry, getCurrentDate())
&& validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) {
final HttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry);
cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
HttpEntity errorBody = backendResponse.getEntity();
if (errorBody != null) EntityUtils.consume(errorBody);
return cachedResponse;
}
return handleBackendResponse(target, conditionalRequest, requestDate, responseDate,
backendResponse);
}
private boolean staleIfErrorAppliesTo(int statusCode) {
return statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
|| statusCode == HttpStatus.SC_BAD_GATEWAY
|| statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
|| statusCode == HttpStatus.SC_GATEWAY_TIMEOUT;
}
HttpResponse handleBackendResponse(
HttpHost target,
HttpRequest request,
Date requestDate,
Date responseDate,
HttpResponse backendResponse) throws IOException {
log.trace("Handling Backend response");
responseCompliance.ensureProtocolCompliance(request, backendResponse);
boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse);
responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse);
if (cacheable &&
!alreadyHaveNewerCacheEntry(target, request, backendResponse)) {
try {
return responseCache.cacheAndReturnResponse(target, request, backendResponse, requestDate,
responseDate);
} catch (IOException ioe) {
log.warn("Unable to store entries in cache", ioe);
}
}
if (!cacheable) {
try {
responseCache.flushCacheEntriesFor(target, request);
} catch (IOException ioe) {
log.warn("Unable to flush invalid cache entries", ioe);
}
}
return backendResponse;
}
private boolean alreadyHaveNewerCacheEntry(HttpHost target, HttpRequest request,
HttpResponse backendResponse) {
HttpCacheEntry existing = null;
try {
existing = responseCache.getCacheEntry(target, request);
} catch (IOException ioe) {
// nop
}
if (existing == null) return false;
Header entryDateHeader = existing.getFirstHeader("Date");
if (entryDateHeader == null) return false;
Header responseDateHeader = backendResponse.getFirstHeader("Date");
if (responseDateHeader == null) return false;
try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
return responseDate.before(entryDate);
} catch (DateParseException e) {
}
return false;
}
}
| [
"github@dirk.jaeckel.name"
] | github@dirk.jaeckel.name |
5b4fa101454b89d1ddc5c8cf2238b5bb354ae832 | e3ccc2fef19be175120b8d5073858aef0dce4bd2 | /cs315/util/Iterator.java | dbf6a904ae214d8ea0649ba378b054b6b2ffb50f | [] | no_license | michaeltheitking/Alphametic | c334594325eaf533403ba64a58ad85f978bec6dc | 2ccb8b9204940ec39e718ce04bf6fcee76fbee29 | refs/heads/master | 2021-05-27T19:36:56.066440 | 2014-06-11T17:05:13 | 2014-06-11T17:05:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package cs315.util;
/**
* Interface for iterating through all the permutations of a character array.
*
* @author michael king and michael fradkin
* @version 1.0
*/
public interface Iterator
{
/**
* method to determine if loops can be incremented again. <BR>
* post: returns true if iterator can be incremented at least once; otherwise false <BR>
* Complexity: ?? <BR>
* Memory Usage: ?? <BR>
* @return true if iterator can be incremented at least once; otherwise false
*/
boolean hasNext();
/**
* method to increment through the object <BR>
* pre: this.hasNext() == true <BR>
* post: iterator is incremented once <BR>
* Complexity: ??<BR>
* Memory Usage: ??<BR>
* @return the next iteration Object
*/
Object next();
}
| [
"mk@michael-king.com"
] | mk@michael-king.com |
4746b6b544c6558cac029dac115bc3ae8ceb4253 | 717a2db8128c1a214a86de6acfcd51f64233c1b6 | /src/main/java/com/olympians/controllers/UserController.java | 4cade2d02df2c19f9ce82c75a8500e85c37d0132 | [] | no_license | java24july-ank-meh/Olympians | e300e1c8d32794d71b5ae82efdadd6535bef5161 | d561c04cef38db4c83889cced112e3d20bc7489f | refs/heads/master | 2021-01-22T14:21:02.671263 | 2017-09-12T19:09:54 | 2017-09-12T19:09:54 | 100,714,218 | 0 | 0 | null | 2017-08-25T19:20:10 | 2017-08-18T13:24:17 | HTML | UTF-8 | Java | false | false | 2,989 | java | package com.olympians.controllers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.olympians.Dao.DaoInterface;
import com.olympians.beans.Person;
import com.olympians.beans.PersonImpl;
@Controller
@RequestMapping("/usercontroller")
public class UserController {
@Autowired
Person loggedIn;
@Autowired
DaoInterface dao;
public UserController() {
super();
// TODO Auto-generated constructor stub
}
public UserController(Person loggedIn, DaoInterface dao) {
super();
this.loggedIn = loggedIn;
this.dao = dao;
}
public Person getLoggedIn() {
return loggedIn;
}
public void setLoggedIn(Person loggedIn) {
this.loggedIn = loggedIn;
}
public DaoInterface getDao() {
return dao;
}
public void setDao(DaoInterface dao) {
this.dao = dao;
}
@RequestMapping("/all")
public ResponseEntity<Object> allUserFields(HttpServletRequest req){
List<Person> result = new ArrayList<>();
Person toReturn = null;
try{toReturn = dao.GetPersonbyUserName(loggedIn.getUsername());}
catch(Exception e) {e.printStackTrace();}
System.out.println("In allUserFields: " + toReturn);
result.add(toReturn);
return ResponseEntity.ok(result);
}
@RequestMapping("/edit")
public String editUserFields(HttpServletRequest req){
Person person = null;
try{person = dao.GetPersonbyUserName(loggedIn.getUsername());}
catch(Exception e ) {e.printStackTrace();}
String fname = req.getParameter("fname");
String lname = req.getParameter("lname");
String username = req.getParameter("uname");
String opword = req.getParameter("opword");
String npword = req.getParameter("npword");
String email = req.getParameter("email");
if(!opword.equals(person.getPassword()) || !(opword.equals(npword))) {
}
else {
dao.EditAccount(person, fname, lname, username, npword, email);
}
return "redirect:homepage";
}
@RequestMapping("/new")
public String newUser(HttpServletRequest req) {
//forward:url lets you forward request from one controller to another
String fname = req.getParameter("fname");
String lname = req.getParameter("lname");
String username = req.getParameter("user1");
String email = req.getParameter("email");
String password = req.getParameter("pass1");
loggedIn.setFname(fname);
loggedIn.setLname(lname);
loggedIn.setUsername(username);
loggedIn.setEmail(email);
loggedIn.setPassword(password);
try {dao.CreateUser(fname, lname, username, password, email);}
catch(Exception e) {return "redirect:/";}
return "redirect:/homepage";
}
}
| [
"chpalmour@gmail"
] | chpalmour@gmail |
ef7753dcd8ada2ffe82f87e0e75ecd038cad0157 | df3da3c9dfec9dd15f7ee7159eb833e97c3cbf6a | /src/main/java/com/superapp/firstdemo/ServletInitializer.java | ac3ed64bc9e9e54e28cc4e29d0d675d1e5b550d2 | [] | no_license | alexjcm/vaccination-inventory | ccd4d948a59c68f218b92c7dd81b342976d708d6 | 6775d4b40023ca93299bcec100f8b4db50fac431 | refs/heads/main | 2023-08-28T00:21:42.163532 | 2021-10-13T02:41:37 | 2021-10-13T02:41:37 | 407,659,686 | 0 | 0 | null | 2021-10-13T02:41:37 | 2021-09-17T19:37:19 | Java | UTF-8 | Java | false | false | 429 | java | package com.superapp.firstdemo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SuperappApplication.class);
}
}
| [
"alexjhon@live.com"
] | alexjhon@live.com |
d6633bdaa2723b91b29e4cd81fd8f691905c240e | 7be4ab4e0dd5e26c17373bca27b8b811dc116b31 | /app/src/main/java/larryherb/weathernow/GSON/WindObject.java | 8a3c1b5ce4f49d00cb7757776067271d20d1e75a | [
"MIT"
] | permissive | lherb3/WeatherNow-AndroidApp | 1cc5a7ae86b77b9e5c1f589a096219d6c77dedfc | a471b5d0faa7b284b20dff5e14722a96a2999bb4 | refs/heads/master | 2021-08-19T12:19:41.213602 | 2017-11-26T07:23:51 | 2017-11-26T07:23:51 | 110,650,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 333 | java | package larryherb.weathernow.GSON;
import com.google.gson.annotations.SerializedName;
/**
* Created by lherb3 on 11/13/17.
*/
public class WindObject {
@SerializedName("speed")
public double speed;
@SerializedName("deg")
public double
degrees;
@SerializedName("gust")
public double gust;
}
| [
"larry.herb@wasapi.com"
] | larry.herb@wasapi.com |
eb6fa10f5235e4366e48c781160a1eb06e5e701c | 947edc58e161933b70d595242d4663a6d0e68623 | /pigx-upms/pigx-upms-biz/src/main/java/com/pig4cloud/pigx/admin/service/CtcdMantissaService.java | a56df4b12d388aa5d94897b207d7a97a2743c940 | [] | no_license | jieke360/pig6 | 5a5de28b0e4785ff8872e7259fc46d1f5286d4d9 | 8413feed8339fab804b11af8d3fbab406eb80b68 | refs/heads/master | 2023-02-04T12:39:34.279157 | 2020-12-31T03:57:43 | 2020-12-31T03:57:43 | 325,705,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | /*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.admin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.admin.entity.CtcdMantissa;
/**
* 进位类型
*
* @author gaoxiao
* @date 2020-08-12 11:37:07
*/
public interface CtcdMantissaService extends IService<CtcdMantissa> {
}
| [
"qdgaoxiao@163.com"
] | qdgaoxiao@163.com |
9b51c7df25e53508c790dbdd7fe2454d4647dcd6 | aba1234b5e243116bf5e7433c9e428ede1a0c924 | /src/main/java/com/brandongossen/bodg/clientmanager/controllers/UsersController.java | adef600177524828e119af5b3d8e30f1ade8b004 | [] | no_license | Brandon-Travis-BodG/bod-g-client-relationships | dbc3d7a039ee56ccefbf9e90373d271fe1819df9 | 1d9ec15202c642a3422d9ef4a6551c494f92cbc7 | refs/heads/master | 2021-09-15T08:13:39.758940 | 2018-05-22T06:18:13 | 2018-05-22T06:18:13 | 116,068,346 | 0 | 0 | null | 2018-05-29T00:41:02 | 2018-01-02T23:32:48 | Java | UTF-8 | Java | false | false | 3,150 | java | package com.brandongossen.bodg.clientmanager.controllers;
import com.brandongossen.bodg.clientmanager.models.Gender;
import com.brandongossen.bodg.clientmanager.models.GenderConverter;
import com.brandongossen.bodg.clientmanager.models.User;
import com.brandongossen.bodg.clientmanager.repositories.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
@Controller
public class UsersController {
private UsersRepository usersDao;
private PasswordEncoder passwordEncoder;
public UsersController(UsersRepository usersDao, PasswordEncoder passwordEncoder) {
this.usersDao = usersDao;this.passwordEncoder = passwordEncoder;
}
@GetMapping("/register")
public String showRegistrationForm(Model viewModel) {
viewModel.addAttribute("user", new User());
return "users/registration";
}
@PostMapping("/register")
public String registerUser(@Valid User user, Errors validation, Model viewModel) {
User existingUser = usersDao.findByUsername(user.getUsername());
User existingEmail = usersDao.findByEmail(user.getEmail());
User existingPhoneNumber = usersDao.findByPhoneNumber(user.getPhoneNumber());
if (existingUser != null) {
validation.rejectValue(
"username",
"user.username",
"Username already taken!"
);
}
if (existingEmail != null) {
validation.rejectValue(
"email",
"user.email",
"Email already taken!"
);
}
if (existingPhoneNumber != null) {
validation.rejectValue(
"user.phoneNumber",
"user.phoneNumber",
"Phone number is already taken!"
);
}
if (validation.hasErrors()) {
viewModel.addAttribute("errors", validation);
viewModel.addAttribute("user", user);
return "users/registration";
}
//user.setPassword(passwordEncoder.encode(user.getPassword()));
//place the hashing encoder to storing password in a variable
String hashPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(hashPassword);
usersDao.save(user);
return "redirect:/login";
}
@InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(Gender.class, new GenderConverter());
//Gender Converter is changing from a string to a gender object
}
}
| [
"brandongossen@yahoo.com"
] | brandongossen@yahoo.com |
46c39f350c077bdf38cf6736fe68fa12a71cd66c | 3f920aaa8826d1aabfe2ee12c3eb1fddda5b6591 | /src/com/pan/Concurrent/SynLockIn_1/Run1.java | 09c915b2026837edc1c2bce9335ca682dd734da4 | [] | no_license | Pan1206/commitMQ | fddf57b3ff8e6f2558b39a590f0b21d7b5c31088 | de45ac8837f345a761aa1b2cf0c0a2b7112dd895 | refs/heads/master | 2020-12-28T15:55:21.356559 | 2020-02-06T09:57:48 | 2020-02-06T09:57:48 | 238,395,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,046 | java | package com.pan.Concurrent.SynLockIn_1;
/**
* 1)当存在父子类继承关系时,子类是完全可以通过"可重入锁”调用父类的同步方法的;
* 2)虽然可以使用synchronized来定义方法,但synchronized并不属于方法定义的一部分,
* 因此,synchronized关键字不能被继承。如果在父类中的某个方法使用了synchronized关键字,
* 而在子类中覆盖了这个方法,在子类中的这个方法默认情况下并不是同步的,
* 而必须显式地在子类的这个方法中加上synchronized关键字才可以。
* 当然,还可以在子类方法中调用父类中相应的方法,这样虽然子类中的方法不是同步的,
* 但子类调用了父类的同步方法,因此,子类的方法也就相当于同步了。这两种方式的例子代码如下:
* 在子类方法中加上synchronized关键字
*/
public class Run1 {
public static void main(String[] args) {
MyThread1 myThread1=new MyThread1();
myThread1.start();
}
}
| [
"panzhijie1206@163.com"
] | panzhijie1206@163.com |
fc6973d79bbdb96d33753f38df9c5917a1e88a34 | 54d572858271c6ef357daebeabc4d0e0967a4163 | /src/LeetCode076.java | 2b7a2fa09d71939724222be885c2cfaf905af462 | [] | no_license | WHJ1101/leetcode | 6dba763d1467e3207b3749d723c5a871d1836e67 | feeed099e7104a497e0f6c4d4b8a11e32881d0e6 | refs/heads/master | 2022-11-20T10:08:56.253456 | 2020-07-19T18:39:45 | 2020-07-19T18:39:45 | 263,327,418 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,636 | java | import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
class LeetCode076 {
Map<Character, Integer> ori = new HashMap<Character, Integer>();
Map<Character, Integer> cnt = new HashMap<Character, Integer>();
public String minWindow(String s, String t) {
int tLen = t.length();
for (int i = 0; i < tLen; i++) {
char c = t.charAt(i);
ori.put(c, ori.getOrDefault(c, 0) + 1);
}
int l = 0, r = -1;
int len = Integer.MAX_VALUE, ansL = -1, ansR = -1;
int sLen = s.length();
while (r < sLen) {
++r;
if (r < sLen && ori.containsKey(s.charAt(r))) {
cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
}
while (check() && l <= r) {
if (r - l + 1 < len) {
len = r - l + 1;
ansL = l;
ansR = l + len;
}
if (ori.containsKey(s.charAt(l))) {
cnt.put(s.charAt(l), cnt.getOrDefault(s.charAt(l), 0) - 1);
}
++l;
}
}
return ansL == -1 ? "" : s.substring(ansL, ansR);
}
public boolean check() {
Iterator iter = ori.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Character key = (Character) entry.getKey();
Integer val = (Integer) entry.getValue();
if (cnt.getOrDefault(key, 0) < val) {
return false;
}
}
return true;
}
}
| [
"489519813@qq.com"
] | 489519813@qq.com |
e17e9a77c3fe45a9e4eea0a1936d735ac4b22731 | 887d067c15066ea7f1df98eeefe2c12ceeeec435 | /SpringNybatis/src/main/java/com/imooc/thrift/ThriftService.java | 35aa6bdb8589b617aca70172a19d158e118a8c38 | [] | no_license | liubo0501/myspring | d1734e33e391e10e0899006023c9e1f927816bbc | bb179171715fe137d3e92e04db57b40f358a0629 | refs/heads/master | 2020-03-21T19:57:58.031250 | 2018-06-28T07:08:01 | 2018-06-28T07:08:01 | 138,980,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 41,834 | java | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.imooc.thrift;
/********************************************************************************
** Copyright(c) 2014-2017 湖南万为智能机器人技术有限公司 All Rights Reserved.
** @author liubo@anbot.cn
** 日期: 2017/11/10
** 描述:Thrift
** 版本:v1.0
*********************************************************************************/
@SuppressWarnings({ "cast", "rawtypes", "serial", "unchecked", "unused" })
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-04-13")
public class ThriftService {
public interface Iface {
public java.lang.String httpRequest(java.lang.String data) throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void httpRequest(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {
}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot,
org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot) {
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public java.lang.String httpRequest(java.lang.String data) throws org.apache.thrift.TException {
send_httpRequest(data);
return recv_httpRequest();
}
public void send_httpRequest(java.lang.String data) throws org.apache.thrift.TException {
httpRequest_args args = new httpRequest_args();
args.setData(data);
sendBase("httpRequest", args);
}
public java.lang.String recv_httpRequest() throws org.apache.thrift.TException {
httpRequest_result result = new httpRequest_result();
receiveBase(result, "httpRequest");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT,
"httpRequest failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void httpRequest(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException {
checkReady();
httpRequest_call method_call = new httpRequest_call(data, resultHandler, this, ___protocolFactory,
___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class httpRequest_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.String> {
private java.lang.String data;
public httpRequest_call(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.data = data;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("httpRequest",
org.apache.thrift.protocol.TMessageType.CALL, 0));
httpRequest_args args = new httpRequest_args();
args.setData(data);
args.write(prot);
prot.writeMessageEnd();
}
public java.lang.String getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(
getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_httpRequest();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I>
implements org.apache.thrift.TProcessor {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(
new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface,
java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(
java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("httpRequest", new httpRequest());
return processMap;
}
public static class httpRequest<I extends Iface>
extends org.apache.thrift.ProcessFunction<I, httpRequest_args> {
public httpRequest() {
super("httpRequest");
}
public httpRequest_args getEmptyArgsInstance() {
return new httpRequest_args();
}
protected boolean isOneway() {
return false;
}
public httpRequest_result getResult(I iface, httpRequest_args args) throws org.apache.thrift.TException {
httpRequest_result result = new httpRequest_result();
result.success = iface.httpRequest(args.data);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory
.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(
new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface,
java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> getProcessMap(
java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("httpRequest", new httpRequest());
return processMap;
}
public static class httpRequest<I extends AsyncIface>
extends org.apache.thrift.AsyncProcessFunction<I, httpRequest_args, java.lang.String> {
public httpRequest() {
super("httpRequest");
}
public httpRequest_args getEmptyArgsInstance() {
return new httpRequest_args();
}
public org.apache.thrift.async.AsyncMethodCallback<java.lang.String> getResultHandler(
final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.String>() {
public void onComplete(java.lang.String o) {
httpRequest_result result = new httpRequest_result();
result.success = o;
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY, seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException) e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb, msg, msgType, seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, httpRequest_args args,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException {
iface.httpRequest(args.data, resultHandler);
}
}
}
public static class httpRequest_args implements org.apache.thrift.TBase<httpRequest_args, httpRequest_args._Fields>,
java.io.Serializable, Cloneable, Comparable<httpRequest_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"httpRequest_args");
private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField(
"data", org.apache.thrift.protocol.TType.STRING, (short) 1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new httpRequest_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new httpRequest_argsTupleSchemeFactory();
public java.lang.String data; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
DATA((short) 1, "data");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // DATA
return DATA;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(httpRequest_args.class, metaDataMap);
}
public httpRequest_args() {
}
public httpRequest_args(java.lang.String data) {
this();
this.data = data;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public httpRequest_args(httpRequest_args other) {
if (other.isSetData()) {
this.data = other.data;
}
}
public httpRequest_args deepCopy() {
return new httpRequest_args(this);
}
@Override
public void clear() {
this.data = null;
}
public java.lang.String getData() {
return this.data;
}
public httpRequest_args setData(java.lang.String data) {
this.data = data;
return this;
}
public void unsetData() {
this.data = null;
}
/**
* Returns true if field data is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetData() {
return this.data != null;
}
public void setDataIsSet(boolean value) {
if (!value) {
this.data = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case DATA:
if (value == null) {
unsetData();
} else {
setData((java.lang.String) value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case DATA:
return getData();
}
throw new java.lang.IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case DATA:
return isSetData();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof httpRequest_args)
return this.equals((httpRequest_args) that);
return false;
}
public boolean equals(httpRequest_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_data = true && this.isSetData();
boolean that_present_data = true && that.isSetData();
if (this_present_data || that_present_data) {
if (!(this_present_data && that_present_data))
return false;
if (!this.data.equals(that.data))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetData()) ? 131071 : 524287);
if (isSetData())
hashCode = hashCode * 8191 + data.hashCode();
return hashCode;
}
@Override
public int compareTo(httpRequest_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetData()).compareTo(other.isSetData());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetData()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("httpRequest_args(");
boolean first = true;
sb.append("data:");
if (this.data == null) {
sb.append("null");
} else {
sb.append(this.data);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class httpRequest_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_argsStandardScheme getScheme() {
return new httpRequest_argsStandardScheme();
}
}
private static class httpRequest_argsStandardScheme
extends org.apache.thrift.scheme.StandardScheme<httpRequest_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // DATA
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.data = iprot.readString();
struct.setDataIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, httpRequest_args struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.data != null) {
oprot.writeFieldBegin(DATA_FIELD_DESC);
oprot.writeString(struct.data);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class httpRequest_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_argsTupleScheme getScheme() {
return new httpRequest_argsTupleScheme();
}
}
private static class httpRequest_argsTupleScheme
extends org.apache.thrift.scheme.TupleScheme<httpRequest_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetData()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetData()) {
oprot.writeString(struct.data);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.data = iprot.readString();
struct.setDataIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(
org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY
: TUPLE_SCHEME_FACTORY).getScheme();
}
}
public static class httpRequest_result
implements org.apache.thrift.TBase<httpRequest_result, httpRequest_result._Fields>, java.io.Serializable,
Cloneable, Comparable<httpRequest_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"httpRequest_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(
"success", org.apache.thrift.protocol.TType.STRING, (short) 0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new httpRequest_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new httpRequest_resultTupleSchemeFactory();
public java.lang.String success; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short) 0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(httpRequest_result.class, metaDataMap);
}
public httpRequest_result() {
}
public httpRequest_result(java.lang.String success) {
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public httpRequest_result(httpRequest_result other) {
if (other.isSetSuccess()) {
this.success = other.success;
}
}
public httpRequest_result deepCopy() {
return new httpRequest_result(this);
}
@Override
public void clear() {
this.success = null;
}
public java.lang.String getSuccess() {
return this.success;
}
public httpRequest_result setSuccess(java.lang.String success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/**
* Returns true if field success is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.String) value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new java.lang.IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof httpRequest_result)
return this.equals((httpRequest_result) that);
return false;
}
public boolean equals(httpRequest_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
if (isSetSuccess())
hashCode = hashCode * 8191 + success.hashCode();
return hashCode;
}
@Override
public int compareTo(httpRequest_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("httpRequest_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class httpRequest_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_resultStandardScheme getScheme() {
return new httpRequest_resultStandardScheme();
}
}
private static class httpRequest_resultStandardScheme
extends org.apache.thrift.scheme.StandardScheme<httpRequest_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.success = iprot.readString();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, httpRequest_result struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeString(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class httpRequest_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_resultTupleScheme getScheme() {
return new httpRequest_resultTupleScheme();
}
}
private static class httpRequest_resultTupleScheme
extends org.apache.thrift.scheme.TupleScheme<httpRequest_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeString(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readString();
struct.setSuccessIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(
org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY
: TUPLE_SCHEME_FACTORY).getScheme();
}
}
}
| [
"1187448504@qq.com"
] | 1187448504@qq.com |
0fa7cf821791298b2e9b73b63cffe62701d56bdb | 304afb759a91f00809ff49cfc2fbf7606a78d80f | /project_game/src/br/com/casadocodigo/bis/game/scenes/TitleScreen.java | 80b314527722a1f23a2cbf4491338a88890c0780 | [] | no_license | edmatamoros/ProjectGame | 8c1c065733ed532eccef43b37afc60c9d06999ec | 0ae0da2c02d4a652253558a851bcac391e3f07cd | refs/heads/master | 2021-01-19T14:34:34.426315 | 2014-04-05T19:19:47 | 2014-04-05T19:19:47 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,381 | java | package br.com.casadocodigo.bis.game.scenes;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenHeight;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenResolution;
import static br.com.casadocodigo.bis.config.DeviceSettings.screenWidth;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import br.com.casadocodigo.bis.config.Assets;
import br.com.casadocodigo.bis.game.control.MenuButtons;
import br.com.casadocodigo.bis.screens.ScreenBackground;
public class TitleScreen extends CCLayer {
private ScreenBackground background;
public CCScene scene() {
CCScene scene = CCScene.node();
scene.addChild(this);
return scene;
}
public TitleScreen() {
// background
//Adiciona a imagem Background.png que está
//no diretório assets
this.background = new ScreenBackground(Assets.BACKGROUND);
this.background.setPosition(screenResolution(CGPoint.ccp(screenWidth() / 2.0f, screenHeight() / 2.0f)));
this.addChild(this.background);
// logo
CCSprite title = CCSprite.sprite(Assets.LOGO);
title.setPosition(screenResolution(CGPoint.ccp( screenWidth() /2 , screenHeight() - 130 ))) ;
this.addChild(title);
// Adiciona os botões de opção
MenuButtons menuLayer = new MenuButtons();
this.addChild(menuLayer);
}
}
| [
"ed_matamoros@hotmail.com"
] | ed_matamoros@hotmail.com |
09c83816c924837db9326db80308815bf73ad378 | 8fc81eec28b4f41984c78a5474f8925d2921f8d8 | /algorithms/src/main/java/exigentech/codility/practice/foresee/Problem.java | d8590038e7dae06dd94addf0fa1ce31d70f96ead | [] | no_license | anecula/cracking-the-coding-interview | 63db00bb85448522b5582dc427b166c68b1d8d40 | 9b1a72073448a92663488b8f71c9f9d6006bcc0b | refs/heads/master | 2020-03-29T23:43:17.754532 | 2018-06-18T13:20:29 | 2018-06-18T13:20:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,268 | java | package exigentech.codility.practice.foresee;
import java.util.Random;
enum RandomValueGenerator {
SOLUTION;
private static Random RANDOM = new Random();
/**
* @return Randomized integer such that {@code lowerBound < n < upperBound}
*/
int betweenBounds(int lowerBound, int upperBound) {
return RANDOM.nextInt(upperBound - lowerBound) + lowerBound;
}
}
final class Solution {
private static int UPPER_BOUND = Double.valueOf(Math.pow(10, 9)).intValue();
private static int MULTIPLE_OF = 10;
/**
* @return Randomized multiple of 10 (x) such that {@code n < x < 10^9}.
*/
int solution(int n) {
if (n == UPPER_BOUND - 1) {
// Since the return value must be greater than n and a multiple of 10,
// UPPER_BOUND is the only valid value.
return UPPER_BOUND;
}
if (n >= UPPER_BOUND) {
throw new IllegalArgumentException("Input n must be strictly < " + UPPER_BOUND);
}
final int boundedRandom = RandomValueGenerator.SOLUTION.betweenBounds(n + 1, UPPER_BOUND);
final int mod = boundedRandom % MULTIPLE_OF;
if (mod == 0) {
return boundedRandom;
}
if (boundedRandom - mod == n) {
return boundedRandom + (MULTIPLE_OF - mod);
}
return boundedRandom - mod;
}
}
| [
"myers.adam.k@gmail.com"
] | myers.adam.k@gmail.com |
93d7485f2b76ff488691c8804e3aa647cb2d6e4d | 05835a7bcf0446786d5ae2d1d8402666bbd62798 | /hermes-monitor/src/main/java/com/ctrip/hermes/monitor/service/KafkaMonitor.java | 9266b1d14cb2de43dc64e9b33b8f1b695b46a66f | [
"Apache-2.0"
] | permissive | richarwu/hermes | 10f4b56d03b2d5974dd98a58d542c06586079ad7 | 80ca70a7067114f4d22d4336cf0032aaaaaf695d | refs/heads/master | 2021-01-18T00:11:30.688586 | 2015-11-04T03:34:59 | 2015-11-04T03:34:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,539 | java | package com.ctrip.hermes.monitor.service;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.index.IndexResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ctrip.hermes.monitor.Bootstrap;
import com.ctrip.hermes.monitor.config.MonitorConfig;
import com.ctrip.hermes.monitor.domain.MonitorItem;
import com.ctrip.hermes.monitor.stat.StatResult;
import com.ctrip.hermes.monitor.zabbix.ZabbixApiGateway;
import com.ctrip.hermes.monitor.zabbix.ZabbixConst;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.history.HistoryObject.HISOTRY_OBJECT_TYPE;
import com.zabbix4j.host.HostObject;
import com.zabbix4j.item.ItemObject;
@Service
public class KafkaMonitor implements IZabbixMonitor {
private static final Logger logger = LoggerFactory.getLogger(KafkaMonitor.class);
public static void main(String[] args) throws Throwable {
ConfigurableApplicationContext context = SpringApplication.run(Bootstrap.class);
KafkaMonitor monitor = context.getBean(KafkaMonitor.class);
monitor.monitorPastHours(24 * 2, 5);
context.close();
}
@Autowired
private ESMonitorService service;
@Autowired
private ZabbixApiGateway zabbixApi;
@Autowired
private MonitorConfig config;
@Scheduled(cron = "0 5 * * * *")
public void monitorHourly() throws Throwable {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date timeTill = cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, -1);
Date timeFrom = cal.getTime();
monitorKafka(timeFrom, timeTill);
}
private void monitorKafka(Date timeFrom, Date timeTill) throws Throwable {
Map<Integer, HostObject> kafkaHosts = zabbixApi.searchHostsByName(config.getZabbixKafkaBrokerHosts());
Map<Integer, StatResult> messageInStat = statMessageIn(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> byteInStat = statByteIn(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> byteOutStat = statByteOut(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> failedProduceRequestsStat = statFailedProduceRequests(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> failedFetchRequestsStat = statFailedFetchRequests(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestQueueSizeStat = statRequestQueueSize(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestRateProduceStat = statRequestRateProduce(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestRateFetchConsumerStat = statRequestRateFetchConsumer(timeFrom, timeTill,
kafkaHosts);
Map<Integer, StatResult> requestRateFetchFollowerStat = statRequestRateFetchFollower(timeFrom, timeTill,
kafkaHosts);
int MINUTE_IN_SECONDS = (int) ((timeTill.getTime() - timeFrom.getTime()) / 1000 / 60);
for (Integer hostid : kafkaHosts.keySet()) {
Map<String, Object> stat = new HashMap<String, Object>();
stat.put("kafka.messagein.sumbymin", messageInStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.messagein.meanbysec", messageInStat.get(hostid).getMean());
stat.put("kafka.bytein.sumbymin", byteInStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.bytein.meanbysec", byteInStat.get(hostid).getMean());
stat.put("kafka.byteout.sumbymin", byteOutStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.byteout.meanbysec", byteOutStat.get(hostid).getMean());
stat.put("kafka.failedproducerequest.sumbymin", failedProduceRequestsStat.get(hostid).getSum()
* MINUTE_IN_SECONDS);
stat.put("kafka.failedproducerequest.meanbysec", failedProduceRequestsStat.get(hostid).getMean());
stat.put("kafka.failedfetchrequest.sumbymin", failedFetchRequestsStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.failedfetchrequest.meanbysec", failedFetchRequestsStat.get(hostid).getMean());
stat.put("kafka.requestqueuesize.meanbysec", requestQueueSizeStat.get(hostid).getMean());
stat.put("kafka.produce.sumbymin", requestRateProduceStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.produce.meanbysec", requestRateProduceStat.get(hostid).getMean());
stat.put("kafka.fetchconsumer.sumbymin", requestRateFetchConsumerStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.fetchconsumer.meanbysec", requestRateFetchConsumerStat.get(hostid).getMean());
stat.put("kafka.fetchfollower.sumbymin", requestRateFetchFollowerStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.fetchfollower.meanbysec", requestRateFetchFollowerStat.get(hostid).getMean());
MonitorItem item = new MonitorItem();
item.setCategory(ZabbixConst.CATEGORY_KAFKA);
item.setSource(ZabbixConst.SOURCE_ZABBIX);
item.setStartDate(timeFrom);
item.setEndDate(timeTill);
item.setHost(kafkaHosts.get(hostid).getHost());
item.setGroup(ZabbixConst.GROUP_KAFKA_BROKER);
item.setValue(stat);
try {
IndexResponse response = service.prepareIndex(item);
logger.info(response.getId());
} catch (IOException e) {
logger.warn("Save item failed", e);
}
}
}
public void monitorPastHours(int hours, int requestIntervalSecond) throws Throwable {
for (int i = hours - 1; i >= 0; i--) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.HOUR_OF_DAY, -i);
Date timeTill = cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, -1);
Date timeFrom = cal.getTime();
monitorKafka(timeFrom, timeTill);
try {
Thread.sleep(requestIntervalSecond * 1000);
} catch (InterruptedException e) {
}
}
}
private Map<Integer, StatResult> statByteIn(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(), ZabbixConst.KAFKA_BYTE_IN_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Bytes In(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Bytes In(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statByteOut(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(), ZabbixConst.KAFKA_BYTE_OUT_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Bytes Out(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Bytes Out(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statFailedFetchRequests(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_FAILED_FETCH_REQUESTS);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += validResult.getSum() * 60;
logger.info(String.format(
"%14s Failed Fetch Request(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts.get(hostid)
.getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Failed Fetch Request(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statFailedProduceRequests(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_FAILED_PRODUCE_REQUESTS);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format(
"%14s Failed Produce Request(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Failed Produce Request(%s - %s) %,12d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statMessageIn(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_MESSAGE_IN_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Message In(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Message In(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestQueueSize(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_QUEUE_SIZE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getMean() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += validResult.getMean();
logger.info(String.format("%14s Request Queue Size(%s - %s) %,9.0f(By Second) ", hosts.get(hostid).getHost(),
timeFrom, timeTill, validResult.getMean()));
}
logger.info(String.format("%14s Request Queue Size(%s - %s) %,12d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateFetchConsumer(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_FETCHCONSUMER);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Fetch Consumer(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Fetch Consumer(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateFetchFollower(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_FETCHFOLLOWER);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Fetch Follower(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Fetch Follower(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateProduce(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_PRODUCE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Produce(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Produce(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
}
| [
"liuyiming.vip@gmail.com"
] | liuyiming.vip@gmail.com |
167aa72e7119a3c3eb83753131e75db87c94ab16 | 07fafdaf3ac44da373434ddda2fb96859247cf4f | /Actividad2Musico.java/src/excepciones/ito/poo/Solicitante.java | 109fd2c6edc4a6304824897c7a5122694931264a | [] | no_license | GerardoGutierrezFeria/PracticaComplementaria | 38311501b67d051cb78238670af8d4681bda2328 | 787543b24d181f4b05fe9a532f7e3b7d59ad618d | refs/heads/master | 2023-06-08T21:40:21.933869 | 2021-06-14T22:25:50 | 2021-06-14T22:25:50 | 376,970,839 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 174 | java | package excepciones.ito.poo;
@SuppressWarnings("serial")
public class Solicitante extends Exception {
public Solicitante(String message) {
super(message);
}
} | [
"Gelexis@LAPTOP-7BJ6TSE7"
] | Gelexis@LAPTOP-7BJ6TSE7 |
cb9c6d40a2144442aba4ed4a6b22dc421ada380d | 98c049efdfebfafc5373897d491271b4370ab9b4 | /src/main/java/lapr/project/data/PharmacyDB.java | 13e4ba5a59d1a42e2a7a219fb038b76bfd504b30 | [] | no_license | antoniodanielbf-isep/LAPR3-2020 | 3a4f4cc608804f70cc87a3ccb29cbc05f5edf0f3 | 7ee16e8c995aea31c30c858f93e8ebdf1de7617f | refs/heads/main | 2023-05-27T14:42:05.442427 | 2021-06-20T18:09:59 | 2021-06-20T18:09:59 | 378,709,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,568 | java | package lapr.project.data;
import lapr.project.model.*;
import oracle.jdbc.OracleTypes;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* The type Pharmacy db.
*/
public class PharmacyDB extends DataHandler {
/**
* Gets all pharmacies.
*
* @return the all pharmacies
*/
public List<Pharmacy> getAllPharmacies() {
List<Pharmacy> pharmacys = new ArrayList<>();
try (CallableStatement callStmt =
getConnection().prepareCall("{ ? = call getAllPharmacys() }")) {
callStmt.registerOutParameter(1, OracleTypes.CURSOR);
callStmt.execute();
ResultSet rSet = (ResultSet) callStmt.getObject(1);
while (rSet.next()) {
int id = rSet.getInt(1);
String designation = rSet.getString(2);
String address = rSet.getString(3);
String pharmacyOwner = rSet.getString(4);
pharmacys.add(new Pharmacy(id, designation, address, pharmacyOwner));
}
return pharmacys;
} catch (SQLException e) {
e.printStackTrace();
}
throw new IllegalArgumentException("No Data Found");
}
/**
* Create pharmacy int.
*
* @param pharmacyOwner the pharmacy owner
* @param designation the designation
* @param address the address
* @return the int
*/
public int createPharmacy(String pharmacyOwner, String designation, Address address) {
Integer pharmacyID;
CallableStatement callStmt = null;
if (!pharmacyOwner.isEmpty() && !designation.isEmpty() && address != null) {
try {
callStmt = getConnection().prepareCall("{ ? = call createPharmacy(?,?,?) }");
callStmt.registerOutParameter(1, OracleTypes.INTEGER);
callStmt.setString(2, pharmacyOwner);
callStmt.setString(3, address.getCoordinates());
callStmt.setString(4, designation);
callStmt.execute();
pharmacyID = (Integer) callStmt.getObject(1);
return pharmacyID;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
assert callStmt != null;
callStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return -1;
}
/**
* Update boolean.
*
* @param pharmacyOwner the pharmacy owner
* @param designation the designation
* @param address the address
* @return the boolean
*/
public boolean update(String pharmacyOwner, String designation, Address address) {
boolean isUpdated = false;
if (!pharmacyOwner.isEmpty() && !designation.isEmpty() && address != null) {
try (CallableStatement callStmt = getConnection().prepareCall("{ call updatePharmacy(?,?,?) }")) {
callStmt.setString(1, pharmacyOwner);
callStmt.setString(2, address.getCoordinates());
callStmt.setString(3, designation);
callStmt.execute();
isUpdated = true;
} catch (SQLException e) {
e.printStackTrace();
}
}
return isUpdated;
}
/**
* Gets pharmacy by user email.
*
* @param email the email
* @return the pharmacy by user email
*/
public Pharmacy getPharmacyByUserEmail(String email) {
CallableStatement callStmt;
Pharmacy pharmacy = null;
try {
callStmt = getConnection().prepareCall("{ ? = call getPharmacyByUserEmail(?) }");
callStmt.registerOutParameter(1, OracleTypes.CURSOR);
callStmt.setString(2, email);
callStmt.execute();
ResultSet rSet = (ResultSet) callStmt.getObject(1);
if (rSet.next()) {
int id = rSet.getInt(1);
String designation = rSet.getString(2);
String adress = rSet.getString(3);
String pharmacyOwner = rSet.getString(4);
closeAll();
pharmacy = new Pharmacy(id, designation, adress, pharmacyOwner);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pharmacy;
}
}
| [
"1190402@isep.ipp.pt"
] | 1190402@isep.ipp.pt |
78092c6b080afb3e1d796f9fa72075780c6528ca | 11e613c4598c21e9e212413e6fc1fef59d6f2742 | /rxeasyhttp/src/main/java/com/zhouyou/http/cache/converter/GsonDiskConverter.java | f169e864dd8b358860e339da3c438b4e0f181521 | [
"Apache-2.0"
] | permissive | SunnyLy/RxEasyHttp | ed666d91487f90c2f60be1f66669ff34154138d0 | 613e9580a054a5979a6b5c8c7cc48953cb555cff | refs/heads/master | 2020-06-01T15:43:41.051183 | 2017-06-12T08:48:41 | 2017-06-12T08:48:41 | 94,078,502 | 1 | 0 | null | 2017-06-12T09:26:32 | 2017-06-12T09:26:32 | null | UTF-8 | Java | false | false | 3,278 | java | /*
* Copyright (C) 2017 zhouyou(478319399@qq.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhouyou.http.cache.converter;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.zhouyou.http.utils.HttpLog;
import com.zhouyou.http.utils.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
/**
* <p>描述:GSON-数据转换器</p>
* 1.GSON-数据转换器其实就是存储字符串的操作<br>
* 2.如果你的Gson有特殊处理,可以自己创建一个,否则用默认。<br>
* <p>
* 优点:<br>
* 相对于SerializableDiskConverter转换器,存储的对象不需要进行序列化(Serializable),<br>
* 特别是一个对象中又包含很多其它对象,每个对象都需要Serializable,比较麻烦<br>
* </p>
* <p>
* <p>
* 缺点:<br>
* 就是存储和读取都要使用Gson进行转换,object->String->Object的给一个过程,相对来说<br>
* 每次都要转换性能略低,但是以现在的手机性能可以忽略不计了。<br>
* </p>
* <p>
* 《-------骚年,自己根据实际需求选择吧!!!------------》<br>
* 《--看到这里,顺便提下知道IDiskConverter的好处了吧,面向接口编程是不是很灵活(*^_^*)----------》<br>
* <p>
* 作者: zhouyou<br>
* 日期: 2016/12/24 17:35<br>
* 版本: v2.0<br>
*/
public class GsonDiskConverter implements IDiskConverter {
private Gson gson;
public GsonDiskConverter() {
this.gson = new Gson();
}
public GsonDiskConverter(Gson gson) {
this.gson = gson;
}
@Override
public <T> T load(InputStream source, Type type) {
T value = null;
try {
if (gson != null) gson = new Gson();
value = gson.fromJson(new InputStreamReader(source), type);
} catch (JsonIOException e) {
HttpLog.e(e.getMessage());
} catch (JsonSyntaxException e) {
HttpLog.e(e.getMessage());
} finally {
Utils.close(source);
}
return value;
}
@Override
public boolean writer(OutputStream sink, Object data) {
try {
String json = gson.toJson(data);
byte[] bytes = json.getBytes();
sink.write(bytes, 0, bytes.length);
sink.flush();
return true;
} catch (JsonIOException e) {
HttpLog.e(e.getMessage());
} catch (JsonSyntaxException e) {
HttpLog.e(e.getMessage());
} catch (IOException e) {
HttpLog.e(e.getMessage());
}
return false;
}
}
| [
"zhouyou1989123@gmail.com"
] | zhouyou1989123@gmail.com |
d9ab219428c327d63c0ffa1063dbb4ed504bdd06 | 0d8f6066839539aceaa2e0e01b666b37b8288ee6 | /src/main/java/com/stardust/easyassess/track/services/FormService.java | feb75dc1ee2e08341271845727cbfa5617bfc087 | [
"MIT"
] | permissive | EasyAssessSystem/track | 4d4dcdf37696b09082e8538ad4bf0fad5771780c | 3c3a6b358e5fb7531695ad7140a56b1ad6d36e7d | refs/heads/master | 2020-09-15T09:21:46.391690 | 2018-03-29T07:37:13 | 2018-03-29T07:37:13 | 66,845,229 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 196 | java | package com.stardust.easyassess.track.services;
import com.stardust.easyassess.track.models.form.Form;
public interface FormService extends EntityService<Form> {
Form submit(Form form);
}
| [
"chengli@thoughtworks.com"
] | chengli@thoughtworks.com |
f0c71db39a7497ee09f0e8e38f5df9dca8783d06 | 4aabb2b37e6a9d8248d59139db9e4b9a2e8213ea | /app/src/main/java/com/technextit/emergency/ContactListFragment.java | 90242f27289c8c4258b19e48a971b8924def60f7 | [] | no_license | Nebir/EmergencyBD | a2a835b0fb9b5d6702a5c5fa3255455d82806843 | 6693eac35f76e8be844b8281e8b3be3e76ee91ef | refs/heads/master | 2020-03-30T19:14:18.524232 | 2018-10-04T07:30:32 | 2018-10-04T07:30:32 | 151,528,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,051 | java | package com.technextit.emergency;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.technextit.emergency.adapter.ContactListAdapter;
import com.technextit.emergency.app.AppController;
import com.technextit.emergency.http.Client;
import com.technextit.emergency.listener.VolleyResponseHandler;
import com.technextit.emergency.model.Contact;
import com.technextit.emergency.model.Contacts;
import com.technextit.emergency.model.Division;
import com.technextit.emergency.model.Service;
import com.technextit.emergency.utils.URLUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class ContactListFragment extends Fragment implements ActionBar.TabListener{
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String SELECTED_SERVICE_POS = "selected_service_pos";
public ContactListAdapter contactListAdapter;
public List<Contact> contacts;
public ListView listView;
public static ContactListFragment newInstance(int selectedDivision, int selectedService) {
ContactListFragment fragment = new ContactListFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, selectedDivision);
args.putInt(SELECTED_SERVICE_POS, selectedService);
fragment.setArguments(args);
return fragment;
}
public ContactListFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
// int servicePos = savedInstanceState.getInt(SELECTED_SERVICE_POS);
// int divisionPos = savedInstanceState.getInt(ARG_SECTION_NUMBER);
listView = (ListView) view.findViewById(R.id.contactListView);
contacts = new ArrayList<Contact>();
contactListAdapter = new ContactListAdapter(getActivity(), contacts);
listView.setAdapter(contactListAdapter);
HashMap<String, String> params = new HashMap<String, String>();
// Service service = AppController.getInstance().getServices().get(servicePos);
// Division division = AppController.getInstance().getDivisions().get(divisionPos);
//
// params.put("serviceId", ""+service.getId());
// params.put("divisionId", ""+division.getId());
Client.post(URLUtils.URL_CONTACTS, params, Contacts.class, null, new VolleyResponseHandler<Contacts>() {
@Override
public void onSuccess(Contacts response) {
if (response.contacts != null) {
contactListAdapter.setContacts(response.contacts);
}
Log.e("Key", "SIze of divisions-- " + response.contacts.size());
Toast.makeText(getActivity(), "Test--> " + response.contacts.size(), Toast.LENGTH_SHORT).show();
contactListAdapter.notifyDataSetChanged();
}
@Override
public void onError(VolleyError error) {
Toast.makeText(getActivity(), "Test--> " + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Key", "error-- " + error.getMessage());
}
});
return view;
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
| [
"nebir1993@gmail.com"
] | nebir1993@gmail.com |
2799826ef897ecc63d675b861ed277e69b7523ed | fcf485b7d02986bb294d5add269269276b773d62 | /src/main/java/com/hitesh/test/leetcode/array/AvoidFloodInTheCity.java | 1aa1e406e37ac81addfeab8c538e304fc3a38035 | [] | no_license | hiteshsethiya/codeshadow | 0e38cadb5abcfdb714a308796e1e7f0ab0f5eebb | b67a8177cff6614fff6e69014a0b42ac904af4fc | refs/heads/master | 2022-05-31T08:48:47.035099 | 2020-11-06T10:58:48 | 2020-11-06T10:58:48 | 244,311,764 | 1 | 0 | null | 2022-05-20T21:32:03 | 2020-03-02T07:54:17 | Java | UTF-8 | Java | false | false | 5,424 | java | package com.hitesh.test.leetcode.array;
import java.util.*;
public class AvoidFloodInTheCity {
/*
* Your country has an infinite number of lakes. Initially, all the lakes are empty,
* but when it rains over the nth lake, the nth lake becomes full of water.
* If it rains over a lake which is full of water, there will be a flood.
* Your goal is to avoid the flood in any lake.
*
* Given an integer array rains where:
*
* rains[i] > 0 means there will be rains over the rains[i] lake.
* rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
* Return an array ans where:
*
* ans.length == rains.length
* ans[i] == -1 if rains[i] > 0.
* ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
* If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
*
* Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake,
* nothing changes. (see example 4)
*
*
*
* Example 1:
*
* Input: rains = [1,2,3,4]
* Output: [-1,-1,-1,-1]
* Explanation: After the first day full lakes are [1]
* After the second day full lakes are [1,2]
* After the third day full lakes are [1,2,3]
* After the fourth day full lakes are [1,2,3,4]
* There's no day to dry any lake and there is no flood in any lake.
* Example 2:
*
* Input: rains = [1,2,0,0,2,1]
* Output: [-1,-1,2,1,-1,-1]
* Explanation: After the first day full lakes are [1]
* After the second day full lakes are [1,2]
* After the third day, we dry lake 2. Full lakes are [1]
* After the fourth day, we dry lake 1. There is no full lakes.
* After the fifth day, full lakes are [2].
* After the sixth day, full lakes are [1,2].
* It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
* Example 3:
*
* Input: rains = [1,2,0,1,2]
* Output: []
* Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
* After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose
* to dry in the 3rd day, the other one will flood.
* Example 4:
*
* Input: rains = [69,0,0,0,69]
* Output: [-1,69,1,1,-1]
* Explanation: Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1]
* is acceptable where 1 <= x,y <= 10^9
* Example 5:
*
* Input: rains = [10,20,20]
* Output: []
* Explanation: It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
*
*
* Constraints:
*
* 1 <= rains.length <= 10^5
* 0 <= rains[i] <= 10^9
*/
private static final int[] EMPTY = new int[0];
public int[] avoidFloodBF(int[] rains) {
int[] ans = new int[rains.length];
Set<Integer> full = new HashSet<>();
int n = rains.length;
for (int i = 0; i < n; ++i) {
int j = i + 1;
if (j < n && rains[i] > 0 && rains[i] == rains[j]) return EMPTY;
if (full.contains(rains[i])) return EMPTY;
if (rains[i] > 0) {
ans[i] = -1;
full.add(rains[i]);
} else if (rains[i] == 0) {
while (j < n && (rains[j] == 0 || !full.contains(rains[j]))) {
j++;
}
if (j < n) {
ans[i] = full.contains(rains[j]) ? rains[j] : 1;
full.remove(ans[i]);
} else {
ans[i] = 1;
}
}
}
return ans;
}
public int[] avoidFlood(int[] rains) {
int[] ans = new int[rains.length];
int n = rains.length;
Map<Integer, Integer> fullLakes = new HashMap<>();
TreeSet<Integer> noRains = new TreeSet<>();
for (int i = 0; i < n; ++i) {
if (rains[i] == 0) {
noRains.add(i);
ans[i] = 1;
} else if (rains[i] > 0) {
if (fullLakes.containsKey(rains[i])) {
Integer canDry = noRains.ceiling(fullLakes.get(rains[i]));
if (canDry == null) return EMPTY;
ans[canDry] = rains[i];
noRains.remove(canDry);
}
fullLakes.put(rains[i], i);
ans[i] = -1;
}
}
return ans;
}
public static void execute(int[] input, int[] ans) {
int[] o = new AvoidFloodInTheCity().avoidFlood(input);
System.out.println(Arrays.toString(o));
System.out.println(Arrays.equals(o, ans));
}
public static void main(String[] args) {
execute(new int[]{1, 2, 0, 2, 3, 0, 1}, new int[]{-1, -1, 2, -1, -1, 1, -1});
execute(new int[]{1, 0, 2, 0, 2, 1}, new int[]{-1, 1, -1, 2, -1, -1});
execute(new int[]{1, 2, 3, 4}, new int[]{-1, -1, -1, -1});
execute(new int[]{1, 2, 0, 0, 2, 1}, new int[]{-1, -1, 2, 1, -1, -1});
execute(new int[]{1, 2, 0, 1, 2}, new int[]{});
execute(new int[]{69, 0, 0, 0, 69}, new int[]{-1, 69, 1, 1, -1});
execute(new int[]{10, 20, 20}, new int[]{});
}
}
| [
"hiteshsethiya@gmail.com"
] | hiteshsethiya@gmail.com |
44492187b46fba284ebf3d8cf4a75f9fb5886002 | f9f4b3244b60cf5107edafaaf1f225cbafc63cb4 | /Assignment_PM/src/com/bcj/corejava/operators/lab2/MoonWeight.java | 32913216b5d8eee3d78425865c60cdb620fea029 | [] | no_license | padmaja0922/corejava | eb10b18a4602edcb580a6618fd1569b2e4e1df6c | 5c428c170487132835afb46be35b7308b9a01d9e | refs/heads/master | 2021-07-16T22:18:28.484709 | 2017-10-23T15:47:44 | 2017-10-23T15:47:44 | 108,002,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package com.bcj.corejava.operators.lab2;
import java.util.Scanner;
/* calculating weight on moon */
public class MoonWeight {
public double weightOnMoon(double w) {
double p = w * 0.17;
w = w - p;
return w;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the weight on earth :");
double d = scan.nextDouble();
MoonWeight m = new MoonWeight();
d = m.weightOnMoon(d);
System.out.println("Weight on moon is : " + d);
scan.close();
}
}
| [
"pmutthoju.bcj@gmail.com"
] | pmutthoju.bcj@gmail.com |
446730cf20197d5b9a4a0227c4ed55148a840a05 | 9276f9c42a4feb5e5e89bce9dd99511d7f029f6b | /src/main/java/com/evacipated/cardcrawl/mod/stslib/fields/cards/AbstractCard/SneckoField.java | 299facfbfb92c75b2a24b6d51d80ae1fa987aa4b | [
"MIT"
] | permissive | kiooeht/StSLib | b520d67aeb11bc40de391f3f806134b911d36b2c | 6d9b5e020ff7b608308ad1abb8f1f6b1682afecf | refs/heads/master | 2023-08-17T05:04:50.315903 | 2023-08-15T21:26:33 | 2023-08-15T21:26:33 | 140,659,888 | 84 | 52 | MIT | 2023-09-13T06:00:52 | 2018-07-12T04:13:35 | Java | UTF-8 | Java | false | false | 977 | java | package com.evacipated.cardcrawl.mod.stslib.fields.cards.AbstractCard;
import com.evacipated.cardcrawl.modthespire.lib.SpireField;
import com.evacipated.cardcrawl.modthespire.lib.SpirePatch;
import com.megacrit.cardcrawl.cards.AbstractCard;
@SpirePatch(
cls="com.megacrit.cardcrawl.cards.AbstractCard",
method=SpirePatch.CLASS
)
public class SneckoField
{
public static SpireField<Boolean> snecko = new SneckoFieldType(() -> false);
// This is done so card cost is automatically set to -1
private static class SneckoFieldType extends SpireField<Boolean>
{
SneckoFieldType(DefaultValue<Boolean> defaultValue)
{
super(defaultValue);
}
@Override
public void set(Object __intance, Boolean value)
{
super.set(__intance, value);
if (value && __intance instanceof AbstractCard) {
((AbstractCard)__intance).cost = -1;
}
}
}
} | [
"kiooeht@gmail.com"
] | kiooeht@gmail.com |
ac314f805506a3413e897d2324c98f875d776490 | ff0e2cd24bc598f2d40a1aef179f107c0b5986aa | /src/main/java/com/geekerstar/job/configure/ScheduleConfigure.java | 1d0c878d7b2752a0b9827084b84c86c5c6e39231 | [] | no_license | geekerstar/geek-fast | 8ecc7eabae4e3c35e9619d9f02876fb9d2484511 | 212ff294aaf5c04ac2cc2f6f0e5446db1932282a | refs/heads/master | 2022-09-17T09:59:59.340773 | 2020-08-06T08:37:14 | 2020-08-06T08:37:14 | 226,278,168 | 1 | 0 | null | 2022-09-01T23:17:27 | 2019-12-06T08:11:18 | Java | UTF-8 | Java | false | false | 2,268 | java | package com.geekerstar.job.configure;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
/**
* @author geekerstar
* @date 2020/2/2 12:39
* @description
*/
@Configuration
@RequiredArgsConstructor
public class ScheduleConfigure {
private final DynamicRoutingDataSource dynamicRoutingDataSource;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// 手动从多数据源中获取 quartz数据源
DataSource quartz = dynamicRoutingDataSource.getDataSource("quartz");
factory.setDataSource(quartz);
// quartz参数
Properties prop = new Properties();
prop.put("org.quartz.scheduler.instanceName", "MyScheduler");
prop.put("org.quartz.scheduler.instanceId", "AUTO");
// 线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
// JobStore配置
prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
// 集群配置
prop.put("org.quartz.jobStore.isClustered", "true");
prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
prop.put("org.quartz.jobStore.misfireThreshold", "12000");
prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
factory.setQuartzProperties(prop);
factory.setSchedulerName("Geek_Scheduler");
// 延时启动
factory.setStartupDelay(1);
factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// 启动时更新己存在的 Job
factory.setOverwriteExistingJobs(true);
// 设置自动启动,默认为 true
factory.setAutoStartup(true);
return factory;
}
}
| [
"247507792@qq.com"
] | 247507792@qq.com |
cefc0542b22443e91915396f310ad2f081a9346a | 666f226474bbf225646c1e4d56d52612c8b50aab | /app/src/main/java/com/aou/cheba/Activity/HuaTi_Activity.java | 044c7ffa4bd27e3220fdbf37da05c686570e295a | [] | no_license | Single-Shadow/CheBa_new | cbea8900b0b1bf1f9321f398e6426250a08be585 | aad5afa6f225af5be0741270f3482cff4fcde7a6 | refs/heads/master | 2021-05-05T03:56:38.274045 | 2018-01-23T02:26:26 | 2018-01-23T02:26:26 | 118,542,195 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72,234 | java | package com.aou.cheba.Activity;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.aou.cheba.Fragment.Me_Fragment;
import com.aou.cheba.Fragment_new.CheYouQuan_Fragment;
import com.aou.cheba.Fragment_new.ShaiChe_Fragment;
import com.aou.cheba.Fragment_new.WenDa_Fragment;
import com.aou.cheba.Fragment_new.ZiXun_Fragment;
import com.aou.cheba.R;
import com.aou.cheba.bean.MyCode1;
import com.aou.cheba.bean.MyCodeInfo;
import com.aou.cheba.bean.MyCode_data;
import com.aou.cheba.bean.MyCode_pinglun;
import com.aou.cheba.bean.MyCode_uplist;
import com.aou.cheba.utils.Data_Util;
import com.aou.cheba.utils.SPUtils;
import com.aou.cheba.utils.SerializeUtils;
import com.aou.cheba.utils.TimeUtil;
import com.aou.cheba.utils.Utils;
import com.aou.cheba.view.LoadMoreListView;
import com.aou.cheba.view.MyListView;
import com.aou.cheba.view.MyToast;
import com.aou.cheba.view.RefreshAndLoadMoreView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import net.qiujuer.genius.blur.StackBlur;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by Administrator on 2016/11/29.
*/
public class HuaTi_Activity extends SwipeBackActivity implements View.OnClickListener {
private ImageView finish;
private Button fabiao;
private EditText et;
private String biaoti;
private LoadMoreListView mLoadMoreListView;
private RefreshAndLoadMoreView mRefreshAndLoadMoreView;
private MyListView lv;
private int position_cheka;
private ImageView iv_beijing;
private TextView tv_nickname;
private TextView tv_time;
private CircleImageView iv_head;
private TextView tv_titlfe;
private TextView tv_conftent;
private LinearLayout ll_love;
private ImageView iv_1;
private ImageView iv_2;
private ImageView iv_3;
private ImageView iv_4;
private ImageView iv_5;
private ImageView iv_6;
private ImageView iv_7;
private List<MyCode_uplist.ObjBean> obj = new ArrayList<>();
private List<MyCode_pinglun.ObjBean> comment_list = new ArrayList<>();
private int page = 1;
private Long isson = null;
private RelativeLayout rl_wai;
private LinearLayout rl_xia;
private EditText tv_huitie2;
private String s;
private ImageView iv_xin;
private ImageView iv_shoucang;
private ImageView iv_fenxiang;
private MyCode_data.ObjBean ser = new MyCode_data.ObjBean();
private ImageView iv_gender;
private boolean isclickson;
private LinearLayout ll_hide;
private WebView web;
private TextView btn_guanzhu;
private TextView tv_dizhi;
private LinearLayout ll_suiyi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.huati_activity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ser = (MyCode_data.ObjBean) getIntent().getSerializableExtra("ser");
position_cheka = getIntent().getIntExtra("position", 0);
findViewById();
getHead();
inithttp_getpinglun_list(1);
}
private void initData() {
adapter = new MyAdapter();
mLoadMoreListView.setAdapter(adapter);
mRefreshAndLoadMoreView.setLoadMoreListView(mLoadMoreListView);
mLoadMoreListView.setRefreshAndLoadMoreView(mRefreshAndLoadMoreView);
mRefreshAndLoadMoreView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
page = 1;
inithttp_getpinglun_list(page);
}
});
mLoadMoreListView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
@Override
public void onLoadMore() {
page += 1;
inithttp_getpinglun_list(page);
}
});
mLoadMoreListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("test", "键盘");
if (position != 0) {
isclickson = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isclickson = false;
}
}, 500);
//打开软键盘
InputMethodManager imm = (InputMethodManager) HuaTi_Activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
// 获取编辑框焦点
tv_huitie2.setFocusable(true);
tv_huitie2.setFocusableInTouchMode(true);
tv_huitie2.requestFocus();
/* InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(tv_huitie2, InputMethodManager.SHOW_FORCED);*/
// ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(tv_huitie2,InputMethodManager.SHOW_FORCED);
isson = comment_list.get(position - 1).getId();
s = "回复" + comment_list.get(position - 1).getNickname();
}
}
});
}
private boolean isenter = false;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_finish:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
finish();
}
break;
case R.id.tv_zan:
int tag = (int) v.getTag();
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (comment_list.get(tag).getUped() == null || !(comment_list.get(tag).getUped() == Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")))) {
inithttp_pl_up(tag);
}
}
break;
case R.id.btn_guanzhu:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isFollowed()) {
MyToast.showToast(HuaTi_Activity.this, "已关注");
} else {
inithttp_guanzhu(ser.getUid(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
}
}
}
break;
case R.id.iv_head:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
Intent intent = new Intent(HuaTi_Activity.this, Other_Activity.class);
intent.putExtra("uid", ser.getUid());
startActivity(intent);
}
break;
case R.id.ll_love:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
Intent intent1 = new Intent(HuaTi_Activity.this, Love_Activity.class);
intent1.putExtra("id", ser.getId());
startActivity(intent1);
}
break;
case R.id.tv_huitie2:
break;
case R.id.iv_xin:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isUped()) {
MyToast.showToast(HuaTi_Activity.this, "您已经赞过了");
} else {
inithttp_up(position_cheka);
}
}
}
break;
case R.id.iv_shoucang:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
if (ser.isCollected()) {
inithttp_delshoucang(ser.getId(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
} else {
inithttp_shoucang(ser.getId(), SPUtils.getString(HuaTi_Activity.this, "token"), position_cheka);
}
}
}
break;
case R.id.iv_fenxiang:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(ser.getTitle());
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// text是分享文本,所有平台都需要这个字段
if (ser.getContent() != null && ser.getContent().length() > 33) {
oks.setText(ser.getContent().substring(33, ser.getContent().length()));
} else {
oks.setText("");
}
// 分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
if (ser.getPictrue() != null && !TextUtils.isEmpty(ser.getPictrue())) {
oks.setImageUrl(Data_Util.IMG+ser.getPictrue().split(",")[0]);
} else {
oks.setImageUrl("http://www.szcheba.com/CarbarFileServer/download/41fd795ddb0a38421f0269371c516b08");
}
// Log.i("test",list_tucao.get(position).getPictrue().split(",")[0]);
// oks.setImageUrl("http://b248.photo.store.qq.com/psb?/2c280a19-7f4f-4e7d-a168-20d7fd2f70cc/pUL9tktoc3SHsXcU8hba08Tt5pRL2r.6SaZN4imCsls!/b/dCJ805PTDQAA&bo=ngL2AQAAAAABCUU!&rf=viewer_4" + "");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("文章的评论");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("分享内容的地址");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://www.anou.net.cn/web/share/cbshare.jsp");
// 启动分享GUI
oks.show(HuaTi_Activity.this);
}
break;
case R.id.tv_publish:
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
if (TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
finish();
startActivity(new Intent(HuaTi_Activity.this, Login_Activity.class));
MyToast.showToast(HuaTi_Activity.this, "请先登录");
} else {
String trim = tv_huitie2.getText().toString().trim();
String s = readStream(getResources().openRawResource(R.raw.mingan));
String[] split = s.split(",");
for (int i = 0; i < split.length; i++) {
String x = split[i]; //x为敏感词汇
if (trim.contains(x)) {
trim = trim.replaceAll(x, getXing(x));
}
}
if (TextUtils.isEmpty(trim)) {
} else {
if (isson == null) {
inithttp_tjpl(trim, null);
} else {
inithttp_tjpl(trim, isson);
isson = null;
}
}
}
}
break;
}
}
private String getXing(String f) {
String a = "";
for (int i = 0; i < f.length(); i++) {
a = a + "*";
}
return a;
}
private String readStream(InputStream is) {
// 资源流(GBK汉字码)变为串
String res;
try {
byte[] buf = new byte[is.available()];
is.read(buf);
res = new String(buf, "GBK"); // 必须将GBK码制转成Unicode
is.close();
} catch (Exception e) {
res = "";
}
return res; // 把资源文本文件送到String串中
}
private void inithttp_guanzhu(final long uid, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"uid\": " + uid + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!FollowUser.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("已关注");
btn_guanzhu.setTextColor(Color.parseColor("#d9d9d9"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_hui);
btn_guanzhu.setEnabled(false);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setFollowed(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setFollowed(true);
}
}
MyCodeInfo me_mycodes = new Me_Fragment().mycodes;
if (me_mycodes != null&&me_mycodes.getObj()!=null) {
me_mycodes.getObj().setFollowCount(me_mycodes.getObj().getFollowCount() + 1);
}
SPUtils.put(HuaTi_Activity.this, "islogin", true);
MyToast.showToast(HuaTi_Activity.this, "关注成功");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_up(final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\",\"obj\":{\"id\":\"" + ser.getId() + "\"}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!Like.action";
break;
case 6:
urls = "/Carbar/Traffic!Like.action";
break;
case 7:
urls = "/Carbar/ShaiChe!Like.action";
break;
case 9:
urls = "/Carbar/WenDa!Like.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setUpCount(new ZiXun_Fragment().list_data.get(position).getUpCount() + 1);
new ZiXun_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setUpCount(new CheYouQuan_Fragment().list_data.get(position).getUpCount() + 1);
new CheYouQuan_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setUpCount(new ShaiChe_Fragment().list_data.get(position).getUpCount() + 1);
new ShaiChe_Fragment().list_data.get(position).setUped(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setUpCount(new WenDa_Fragment().list_data.get(position).getUpCount() + 1);
new WenDa_Fragment().list_data.get(position).setUped(true);
}
}
ser.setUped(true);
iv_xin.setImageResource(R.mipmap.x_hong);
setResult(55);
/*MyCode_uplist.ObjBean objBean = new MyCode_uplist.ObjBean();
objBean.setHeadImg(SPUtils.getString(HuaTi_Activity.this, "headImage"));
obj.add(0, objBean);
data_up(obj);*/
MyToast.showToast(HuaTi_Activity.this, "赞");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_shoucang(long did, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"did\": " + did + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!Collection.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
ser.setCollected(true);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setCollected(true);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setCollected(true);
}
}
iv_shoucang.setImageResource(R.mipmap.sc_hong);
setResult(55);
MyToast.showToast(HuaTi_Activity.this, "收藏");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_delshoucang(long did, String token, final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"obj\": {\"did\": " + did + "},\"token\": \"" + token + "\"}");
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + "/Carbar/User!DelCollection.action")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (0 == mycode.getCode()) {
ser.setCollected(false);
if (position >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position).setCollected(false);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position).setCollected(false);
}
}
iv_shoucang.setImageResource(R.mipmap.sc);
setResult(55);
MyToast.showToast(HuaTi_Activity.this, "取消收藏");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
ArrayList<ImageView> list_iv = new ArrayList<>();
boolean isup = false;
private void findViewById() {
rl_wai = (RelativeLayout) findViewById(R.id.rl_wai);
rl_xia = (LinearLayout) findViewById(R.id.rl_xia);
ll_suiyi = (LinearLayout) findViewById(R.id.ll_suiyi);
finish = (ImageView) findViewById(R.id.iv_finish);
iv_xin = (ImageView) findViewById(R.id.iv_xin);
iv_shoucang = (ImageView) findViewById(R.id.iv_shoucang);
iv_fenxiang = (ImageView) findViewById(R.id.iv_fenxiang);
tv_huitie2 = (EditText) findViewById(R.id.tv_huitie2);
fabiao = (Button) findViewById(R.id.tv_publish);
mLoadMoreListView = (LoadMoreListView) findViewById(R.id.load_more_list);
mRefreshAndLoadMoreView = (RefreshAndLoadMoreView) findViewById(R.id.refresh_and_load_more);
finish.setOnClickListener(this);
fabiao.setOnClickListener(this);
// tv_huitie2.setOnClickListener(this);
iv_xin.setOnClickListener(this);
iv_shoucang.setOnClickListener(this);
iv_fenxiang.setOnClickListener(this);
if (ser.isUped()) {
iv_xin.setImageResource(R.mipmap.x_hong);
} else {
iv_xin.setImageResource(R.mipmap.x);
}
if (ser.isCollected()) {
iv_shoucang.setImageResource(R.mipmap.sc_hong);
} else {
iv_shoucang.setImageResource(R.mipmap.sc);
}
//软键盘的弹出监听
controlKeyboardLayout(rl_wai, rl_xia);
rl_wai.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rl_wai.getWindowVisibleDisplayFrame(r);
int screenHeight = rl_wai.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (heightDifference > 200) {
fabiao.setVisibility(View.VISIBLE);
ll_suiyi.setVisibility(View.GONE);
isup = true;
Log.i("test", "弹出键盘");
tv_huitie2.setHint(s);
} else {
if (isup) {
fabiao.setVisibility(View.GONE);
ll_suiyi.setVisibility(View.VISIBLE);
Log.i("test", "键盘收回");
isup = false;
isson = null;
s = "";
tv_huitie2.setText("");
tv_huitie2.setHint("说几句...");
}
}
}
});
}
private int size = 0;
private void controlKeyboardLayout(final View root, final View needToScrollView) {
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private Rect r = new Rect();
@Override
public void onGlobalLayout() {
HuaTi_Activity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int screenHeight = HuaTi_Activity.this.getWindow().getDecorView().getRootView().getHeight();
int heightDifference = screenHeight - r.bottom;
if (Math.abs(heightDifference - size) != 0) {
final ObjectAnimator animator = ObjectAnimator.ofFloat(needToScrollView, "translationY", 0, -heightDifference);
size = heightDifference;
animator.setDuration(0);
animator.start();
}
}
});
}
private void getHead() {
View inflate = View.inflate(HuaTi_Activity.this, R.layout.huati_head, null);
mLoadMoreListView.addHeaderView(inflate);
lv = (MyListView) inflate.findViewById(R.id.lv);
iv_beijing = (ImageView) inflate.findViewById(R.id.iv_beijing);
iv_gender = (ImageView) inflate.findViewById(R.id.iv_gender);
iv_head = (CircleImageView) inflate.findViewById(R.id.iv_head);
tv_nickname = (TextView) inflate.findViewById(R.id.tv_nickname);
tv_time = (TextView) inflate.findViewById(R.id.tv_time);
btn_guanzhu = (TextView) inflate.findViewById(R.id.btn_guanzhu);
tv_dizhi = (TextView) inflate.findViewById(R.id.tv_dizhi);
tv_conftent = (TextView) inflate.findViewById(R.id.tv_content);
tv_titlfe = (TextView) inflate.findViewById(R.id.tv_title);
ll_love = (LinearLayout) inflate.findViewById(R.id.ll_love);
ll_hide = (LinearLayout) inflate.findViewById(R.id.ll_hide);
web = (WebView) inflate.findViewById(R.id.web);
iv_1 = (ImageView) inflate.findViewById(R.id.iv_1);
iv_2 = (ImageView) inflate.findViewById(R.id.iv_2);
iv_3 = (ImageView) inflate.findViewById(R.id.iv_3);
iv_4 = (ImageView) inflate.findViewById(R.id.iv_4);
iv_5 = (ImageView) inflate.findViewById(R.id.iv_5);
iv_6 = (ImageView) inflate.findViewById(R.id.iv_6);
iv_7 = (ImageView) inflate.findViewById(R.id.iv_7);
list_iv.add(iv_1);
list_iv.add(iv_2);
list_iv.add(iv_3);
list_iv.add(iv_4);
list_iv.add(iv_5);
list_iv.add(iv_6);
list_iv.add(iv_7);
ll_love.setOnClickListener(this);
iv_head.setOnClickListener(this);
btn_guanzhu.setOnClickListener(this);
initData();
// inithttp_getup_list(1, ser.getId());
if (ser.getPictrue() != null && ser.getPictrue().length() != 0) {
String[] split = ser.getPictrue().split(",");
final List<String> list_image = Arrays.asList(split);
// Glide.with(HuaTi_Activity.this).load(Data_Util.IMG+list_image.get(0)).into(iv_beijing);
if (list_image == null || list_image.size() == 0) {
} else {
mohu(Data_Util.IMG + list_image.get(0), iv_beijing);
}
}
if (ser.getGender() == 1) {
iv_gender.setImageResource(R.mipmap.nan);
} else {
iv_gender.setImageResource(R.mipmap.nv);
}
if (TextUtils.isEmpty(ser.getLocation())) {
tv_dizhi.setVisibility(View.INVISIBLE);
} else {
tv_dizhi.setVisibility(View.VISIBLE);
tv_dizhi.setText(ser.getLocation());
}
if (SPUtils.getString(HuaTi_Activity.this, "uid").equals(ser.getUid() + "")) {
btn_guanzhu.setVisibility(View.GONE);
} else {
if (ser.isFollowed() && !TextUtils.isEmpty(SPUtils.getString(HuaTi_Activity.this, "token"))) {
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("已关注");
btn_guanzhu.setTextColor(Color.parseColor("#d9d9d9"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_hui);
btn_guanzhu.setEnabled(false);
} else {
btn_guanzhu.setEnabled(true);
btn_guanzhu.setVisibility(View.VISIBLE);
btn_guanzhu.setText("+ 关注");
btn_guanzhu.setTextColor(Color.parseColor("#ffffff"));
btn_guanzhu.setBackgroundResource(R.drawable.custom_lv);
}
}
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + ser.getHeadImg()).into(iv_head);
tv_nickname.setText(ser.getNickname());
tv_time.setText(TimeUtil.getDateTimeFromMillisecond2(ser.getAddtime()));
ll_hide.setVisibility(View.GONE);
web.setVisibility(View.VISIBLE);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setBlockNetworkImage(false);
web.setInitialScale(100);
web.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
String web_url;
if (ser.getContent().contains(",")) {
web_url = ser.getContent().split(",")[0];
} else {
web_url = ser.getContent();
}
loadWebView(Data_Util.HTML + web_url, web);
/* if (ser.getContent() != null && !Utils.isContainChinese(ser.getContent().substring(0,33))) {
// web.loadUrl(Data_Util.HTML+web_url);
// web.setWebViewClient(new HelloWebViewClient());
} else {
ll_hide.setVisibility(View.VISIBLE);
web.setVisibility(View.GONE);
tv_conftent.setText(ser.getContent());
tv_titlfe.setText(ser.getTitle());
lv.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return list_image.size() - 1;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.item_layout, null);
}
ImageView image = (ImageView) convertView.findViewById(R.id.iv_image);
ViewGroup.LayoutParams vParams = image.getLayoutParams();
vParams.height = (int) (DisplayUtil.getMobileHeight(HuaTi_Activity.this) * 0.37);
image.setLayoutParams(vParams);
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG+list_image.get(position + 1)).into(image);
return convertView;
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isenter) {
isenter = true;
h.postDelayed(new Runnable() {
@Override
public void run() {
isenter = false;
}
}, 500);
String[] split1 = ser.getPictrue().split(",");
String sp = "";
for (int i = 0; i < split1.length; i++) {
if (i != 0) {
if (i == 1) {
sp = sp + split1[i];
} else {
sp = sp + "," + split1[i];
}
}
}
Intent i = new Intent(HuaTi_Activity.this, LiuLan_Activity.class);
i.putExtra("split", sp);
i.putExtra("item", position);
startActivity(i);
}
}
});
}*/
}
public void loadWebView(final String url2, final WebView web) {
new Thread(new Runnable() {
@Override
public void run() {
Connection connection = null;
connection = Jsoup.connect(url2);
System.out.println("网页:");
try {
Document document = connection.get();
String s = document.html();
System.out.println("网页:" + s);
String[] src = Utils.substringsBetween(s, "src=\"", "\"");
Set<String> src_set = new HashSet<>();
//去重
if (src != null && src.length != 0) {
Collections.addAll(src_set, src);
for (String src_str : src_set) {
s = s.replace(src_str, Data_Util.IMG + src_str);
}
}
String[] src2 = Utils.substringsBetween(s, "src=\'", "\'");
if (src2 != null && src2.length != 0) {
src_set = new HashSet<>();
Collections.addAll(src_set, src2);
for (String src_str : src_set) {
s = s.replace(src_str, Data_Util.IMG + src_str);
}
}
String s1 = Utils.substringBetween(s, "img{", "}");
if (s1 == null || s1.length() == 0) {
s = s.replace("img{}", "img{width: 100%;max-width: 100%;height: auto;margin: 10px auto;display: block;}");
} else {
s = s.replace(s1, "width: 100%;max-width: 100%;height: auto; margin: 10px auto ;display: block;");
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
String[] src3 = Utils.substringsBetween(s, "font-size:", "}");
String pix = "22px";
if (widthPixels <= 540) {
pix = "13px";
} else if (widthPixels > 540 && widthPixels < 640) {
pix = "14px";
} else if (widthPixels >= 640 && widthPixels < 720) {
pix = "15px";
} else if (widthPixels >= 720 && widthPixels < 750) {
pix = "16px";
} else if (widthPixels >= 750 && widthPixels < 800) {
pix = "17px";
} else if (widthPixels >= 800 && widthPixels < 960) {
pix = "18px";
} else if (widthPixels >= 960 && widthPixels < 1080) {
pix = "19px";
} else {
pix = "22px";
}
Utils.i("手机像素宽度:" + widthPixels);
for (String sp : src3) {
s = s.replace(sp, pix); //字体大小统一调整
}
String[] src4 = Utils.substringsBetween(s, "<div", ">");
if (src4!=null){
for (String style : src4) {
s = s.replace("<div"+style+">", ""); //统一去掉div 删掉样式
}
}
s=s.replace("</div>","");
String body = Utils.substringBetween(s, "<body>", "</body>");
String body1=body.replace("width","");
body1=body1.replace("height","");
body1=body1.replace("margin","");
body1=body1.replace("padding","");
s=s.replace(body,body1);
// MyDebug.showLargeLog(s);
final String finalS = s;
h.post(new Runnable() {
@Override
public void run() {
web.loadDataWithBaseURL(null, finalS, "text/html", "utf-8", null);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// view.loadUrl(url);
return true;
}
}
private void inithttp_pl_up(final int position) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\",\"obj\":{\"id\":" + comment_list.get(position).getId() + "}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!CommentLike.action";
break;
case 6:
urls = "/Carbar/Server!CommentLike.action";
break;
case 7:
urls = "/Carbar/ShaiChe!CommentLike.action";
break;
case 9:
urls = "/Carbar/WenDa!CommentLike.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
comment_list.get(position).setUped(Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")));
comment_list.get(position).setUpCount(comment_list.get(position).getUpCount() + 1);
adapter.notifyDataSetChanged();
MyToast.showToast(HuaTi_Activity.this, "赞");
} else if (mycode.getCode() == 4) {
SPUtils.put(HuaTi_Activity.this, "token", "");
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
}
});
}
});
}
private void inithttp_getpinglun_list(final int page) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"page\":{\"page\":" + page + "},\"obj\":{\"did\":" + ser.getId() + "},\"token\":\"" + SPUtils.getString(HuaTi_Activity.this, "token") + "\"}");
Utils.i("ID评论:" + ser.getId() + " " + page);
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!LoadComment.action";
break;
case 6:
urls = "/Carbar/Traffic!LoadComment.action";
break;
case 7:
urls = "/Carbar/ShaiChe!LoadComment.action";
break;
case 9:
urls = "/Carbar/WenDa!LoadComment.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Utils.i("评论列表:" + res);
Gson gson = new Gson();
final MyCode_pinglun mycode = gson.fromJson(res, MyCode_pinglun.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
if (page == 1) {
h.postDelayed(new Runnable() {
@Override
public void run() {
comment_list = mycode.getObj();
if (adapter != null) {
adapter.notifyDataSetChanged();
} else {
initData();
}
if (comment_list.size() < 10) {
mLoadMoreListView.setHaveMoreData(false);
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
} else {
mLoadMoreListView.setHaveMoreData(true);
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
}
}
}, 300);
} else {
h.postDelayed(new Runnable() {
@Override
public void run() {
List<MyCode_pinglun.ObjBean> obj = mycode.getObj();
if (obj.size() == 0) {
mLoadMoreListView.setHaveMoreData(false);
} else {
mLoadMoreListView.setHaveMoreData(true);
comment_list.addAll(obj);
}
adapter.notifyDataSetChanged();
//当加载完成之后设置此时不在刷新状态
mRefreshAndLoadMoreView.setRefreshing(false);
mLoadMoreListView.onLoadComplete();
}
}, 300);
}
}
}
});
}
});
}
private void inithttp_getup_list(final int page, long l) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, "{\"page\":{\"page\":" + page + "},\"obj\":{\"id\":" + l + "}}");
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!LoadUp.action";
break;
case 6:
urls = "/Carbar/Traffic!LoadUp.action";
break;
case 7:
urls = "/Carbar/ShaiChe!LoadUp.action";
break;
case 9:
urls = "/Carbar/WenDa!LoadUp.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Utils.i(res);
Gson gson = new Gson();
final MyCode_uplist mycode = gson.fromJson(res, MyCode_uplist.class);
h.post(new Runnable() {
@Override
public void run() {
if (mycode.getCode() == 0) {
obj = mycode.getObj();
//初始化点赞列表
data_up(obj);
}
}
});
}
});
}
private void data_up(List<MyCode_uplist.ObjBean> obj) {
if (obj == null || obj.size() == 0) {
ll_love.setVisibility(View.GONE);
} else {
ll_love.setVisibility(View.VISIBLE);
if (obj.size() >= 6) {
for (int i = 0; i < 7; i++) {
list_iv.get(i).setVisibility(View.VISIBLE);
if (i == 6) {
list_iv.get(i).setImageResource(R.mipmap.shenlue);
} else {
try {
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + obj.get(i).getHeadImg()).into(list_iv.get(i));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else {
for (int i = 0; i < 7; i++) {
if (i < obj.size()) {
list_iv.get(i).setVisibility(View.VISIBLE);
try {
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + obj.get(i).getHeadImg()).into(list_iv.get(i));
} catch (Exception e) {
e.printStackTrace();
}
} else if (i == obj.size()) {
list_iv.get(i).setVisibility(View.VISIBLE);
list_iv.get(i).setImageResource(R.mipmap.shenlue);
} else {
list_iv.get(i).setVisibility(View.INVISIBLE);
}
}
}
}
}
Handler h = new Handler();
private void mohu(final String s, final ImageView iv) {
new Thread(new Runnable() {
@Override
public void run() {
// final Bitmap bitmap_s = BitmapFactory.decodeFile(s);
Bitmap bitmap_s = getBitMBitmap(s);
final Bitmap newBitmap;
try {
if (bitmap_s != null) {
newBitmap = StackBlur.blurNatively(bitmap_s, 20, false);
} else {
return;
}
h.post(new Runnable() {
@Override
public void run() {
iv.setImageBitmap(newBitmap);
}
});
} catch (Exception e) {
}
}
}).start();
}
//高斯模糊 保留
public static Bitmap getBitMBitmap(String urlpath) {
Bitmap map = null;
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
private MyAdapter adapter;
public class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return comment_list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.pinglun_item, null);
viewHolder = new ViewHolder();
viewHolder.headima = (CircleImageView) convertView.findViewById(R.id.iv_headima);
viewHolder.nickname = (TextView) convertView.findViewById(R.id.tv_nickname);
viewHolder.tv_zan = (TextView) convertView.findViewById(R.id.tv_zan);
viewHolder.content = (TextView) convertView.findViewById(R.id.tv_content);
viewHolder.lv = (MyListView) convertView.findViewById(R.id.lv_pinglun);
convertView.setTag(viewHolder);
}
viewHolder = (ViewHolder) convertView.getTag();
Glide.with(HuaTi_Activity.this).load(Data_Util.IMG + comment_list.get(position).getHeadImg()).into(viewHolder.headima);
viewHolder.nickname.setText(comment_list.get(position).getNickname());
Log.i("test", comment_list.get(position).getUped() + "");
if (comment_list.get(position).getUped() != null && (comment_list.get(position).getUped() == Integer.parseInt(SPUtils.getString(HuaTi_Activity.this, "uid")))) {
viewHolder.tv_zan.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(HuaTi_Activity.this, R.mipmap.zan_hong), null, null, null);
} else {
viewHolder.tv_zan.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(HuaTi_Activity.this, R.mipmap.zan2), null, null, null);
}
if (comment_list.get(position).getUpCount() == 0) {
viewHolder.tv_zan.setText("");
} else {
viewHolder.tv_zan.setText(comment_list.get(position).getUpCount() + "");
}
viewHolder.content.setText(comment_list.get(position).getContent());
viewHolder.headima.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HuaTi_Activity.this, Other_Activity.class);
intent.putExtra("uid", comment_list.get(position).getUid());
startActivity(intent);
}
});
viewHolder.tv_zan.setTag(position);
viewHolder.tv_zan.setOnClickListener(HuaTi_Activity.this);
if (comment_list.get(position).getSubList() == null || comment_list.get(position).getSubList().size() == 0) {
viewHolder.lv.setVisibility(View.GONE);
} else {
viewHolder.lv.setVisibility(View.VISIBLE);
viewHolder.lv.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return comment_list.get(position).getSubList().size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
ViewHolder2 viewHolder2 = null;
if (convertView == null) {
convertView = View.inflate(HuaTi_Activity.this, R.layout.pinglun_item_son, null);
viewHolder2 = new ViewHolder2();
viewHolder2.tv_content_son = (TextView) convertView.findViewById(R.id.tv_content_son);
viewHolder2.tv_nickname_son = (TextView) convertView.findViewById(R.id.tv_nickname_son);
convertView.setTag(viewHolder2);
}
viewHolder2 = (ViewHolder2) convertView.getTag();
viewHolder2.tv_content_son.setText(":" + comment_list.get(position).getSubList().get(i).getContent());
viewHolder2.tv_nickname_son.setText(comment_list.get(position).getSubList().get(i).getNickname());
return convertView;
}
});
}
return convertView;
}
}
private void inithttp_tjpl(String s, final Long pid) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.SECONDS)//设置连接超时时间
.build();
MediaType JSON = MediaType.parse("application/json; Charset=utf-8");
Map<String, Object> reqData = new HashMap<>();
Map<String, Object> reqDataObj = new HashMap<>();
reqDataObj.put("content", s);
reqDataObj.put("did", ser.getId());
reqDataObj.put("pid", pid);
reqData.put("obj", reqDataObj);
reqData.put("token", SPUtils.getString(HuaTi_Activity.this, "token"));
String s1 = "";
try {
s1 = SerializeUtils.object2Json(reqData);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(JSON, s1);
String urls = "";
switch (ser.getType()) {
case 5:
urls = "/Carbar/Server!Comment.action";
break;
case 6:
urls = "/Carbar/Traffic!Comment.action";
break;
case 7:
urls = "/Carbar/ShaiChe!Comment.action";
break;
case 9:
urls = "/Carbar/WenDa!Comment.action";
break;
}
//创建一个请求对象
Request request = new Request.Builder()
.url(Data_Util.HttPHEAD + urls)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "连接服务器失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String res = response.body().string();
Gson gson = new Gson();
final MyCode1 mycode = gson.fromJson(res, MyCode1.class);
if (mycode.getCode() == 0) {
h.post(new Runnable() {
@Override
public void run() {
// myAdapter.notifyDataSetChanged();
if (pid == null) {
if (position_cheka >= 0) {
if (ser.getType() == 5) {
new ZiXun_Fragment().list_data.get(position_cheka).setCommentNum(new ZiXun_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 6) {
new CheYouQuan_Fragment().list_data.get(position_cheka).setCommentNum(new CheYouQuan_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 7) {
new ShaiChe_Fragment().list_data.get(position_cheka).setCommentNum(new ShaiChe_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
} else if (ser.getType() == 9) {
new WenDa_Fragment().list_data.get(position_cheka).setCommentNum(new WenDa_Fragment().list_data.get(position_cheka).getCommentNum() + 1);
}
}
}
tv_huitie2.setText(null);
tv_huitie2.setHint("说几句...");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
imm.hideSoftInputFromWindow(tv_huitie2.getWindowToken(), 0);
page = 1;
inithttp_getpinglun_list(page);
setResult(55);
}
});
}
if (mycode.getCode() == 4) {
h.post(new Runnable() {
@Override
public void run() {
MyToast.showToast(HuaTi_Activity.this, "请先登录");
}
});
}
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev) && isShouldHideInput(fabiao, ev)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null) {
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
web.destroy();
}
static class ViewHolder {
MyListView lv;
CircleImageView headima;
TextView nickname;
TextView tv_zan;
TextView content;
}
static class ViewHolder2 {
TextView tv_content_son;
TextView tv_nickname_son;
}
}
| [
"1195700031@qq.com"
] | 1195700031@qq.com |
adf875c74ce9337df923d37f915e073a3c4272e4 | 2855a6068ec8af1c39895d12cb12e13ce2ffc2df | /rxandroidjmdns/src/main/java/com/hoanglm/rxandroidjmdns/dagger/ServiceConnectorScope.java | a7befd09c5f66fe546eefe01bf47076fc4b37990 | [] | no_license | inpyokim/RxAndroidJmDNS | b3af6228d4cbf68398bb2425ce4f0d1d578463fe | 3651bb553541407e9f080c690fc2dec75c325d17 | refs/heads/master | 2020-07-07T08:14:47.012771 | 2018-05-30T04:32:15 | 2018-05-30T04:32:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 244 | java | package com.hoanglm.rxandroidjmdns.dagger;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceConnectorScope {
} | [
"minhhoangtoday@gmail.com"
] | minhhoangtoday@gmail.com |
fc08882c742365447769cb55976b71cc16ab490f | e2dc52555383dbf17b8a9f6f0a2f5280fed0298b | /fcgs/PidsCore/src/main/java/com/pids/core/creator/RandomDatasCreator.java | db89e02ff77472cd3a3a93a885927fc6a27b8d7e | [] | no_license | jiangbinboy/fcgs | 2f1e7d58f5a5923ca7003628ecd4a0c7b8b484cb | 6073f820553ac9af8cdc4d6e9a65475618a342d6 | refs/heads/master | 2022-11-17T00:17:22.836784 | 2020-07-10T03:26:11 | 2020-07-10T03:26:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,888 | java | package com.pids.core.creator;
/**
* 随机字符串创建器
* @author WUHAOTIAN
* @email nghsky@foxmail.com
* @date 2019年4月15日上午11:15:52
*/
public class RandomDatasCreator {
public static final char BIG[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
public static final char SMALL[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static final char NUM[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static final char ALL[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
/**
* 获取指定长度字符串,包含大写、小写字母、数字
* @author WUHAOTIAN
* @param len 字符串长度
* @return
* @date 2019年4月15日上午11:20:14
*/
public static String getStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (ALL.length));
sb.append(ALL[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度大写字母
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getUppercaseStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (BIG.length));
sb.append(BIG[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度小写字母
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getLowercaseStr(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (SMALL.length));
sb.append(SMALL[index] + "");
}
return sb.toString();
}
/**
* 获取指定长度数字
* @author WUHAOTIAN
* @param len
* @return
* @date 2019年4月15日上午11:21:18
*/
public static String getNum(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = (int) (Math.random() * (NUM.length));
sb.append(NUM[index] + "");
}
return sb.toString();
}
}
| [
"nghsky@foxmail.com"
] | nghsky@foxmail.com |
9208433b3d7110553c3ddee77e110d193b218051 | 79595075622ded0bf43023f716389f61d8e96e94 | /app/src/main/java/org/apache/http/impl/client/DefaultRedirectHandler.java | 5818bd1865daeb29d2dafedcb4b273281bbd912c | [] | no_license | dstmath/OppoR15 | 96f1f7bb4d9cfad47609316debc55095edcd6b56 | b9a4da845af251213d7b4c1b35db3e2415290c96 | refs/heads/master | 2020-03-24T16:52:14.198588 | 2019-05-27T02:24:53 | 2019-05-27T02:24:53 | 142,840,716 | 7 | 4 | null | null | null | null | UTF-8 | Java | false | false | 4,493 | java | package org.apache.http.impl.client;
import android.net.http.Headers;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.client.CircularRedirectException;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
@Deprecated
public class DefaultRedirectHandler implements RedirectHandler {
private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
private final Log log = LogFactory.getLog(getClass());
public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_MOVED_PERMANENTLY /*301*/:
case HttpStatus.SC_MOVED_TEMPORARILY /*302*/:
case HttpStatus.SC_SEE_OTHER /*303*/:
case HttpStatus.SC_TEMPORARY_REDIRECT /*307*/:
return true;
default:
return false;
}
}
public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
Header locationHeader = response.getFirstHeader(Headers.LOCATION);
if (locationHeader == null) {
throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header");
}
String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
try {
URI uri = new URI(location);
HttpParams params = response.getParams();
if (!uri.isAbsolute()) {
if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
}
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
throw new IllegalStateException("Target host not available in the HTTP context");
}
try {
uri = URIUtils.resolve(URIUtils.rewriteURI(new URI(((HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST)).getRequestLine().getUri()), target, true), uri);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
URI redirectURI;
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
}
if (uri.getFragment() != null) {
try {
redirectURI = URIUtils.rewriteURI(uri, new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), true);
} catch (URISyntaxException ex2) {
throw new ProtocolException(ex2.getMessage(), ex2);
}
}
redirectURI = uri;
if (redirectLocations.contains(redirectURI)) {
throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
}
redirectLocations.add(redirectURI);
}
return uri;
} catch (URISyntaxException ex22) {
throw new ProtocolException("Invalid redirect URI: " + location, ex22);
}
}
}
| [
"toor@debian.toor"
] | toor@debian.toor |
025e28aa2e5f368d3204a494bdc035995d75dbc4 | f1cc4a923edea421e39b78cc3b6111b719bf4ca0 | /src/main/java/com/wangsocial/app/service/PaymentService.java | c594f6c816d33595ad01ee8a3f4baf2e91cb4b38 | [] | no_license | wangzejie1993/xu | e413f0f7f7c3632b241f5f98585b57ffb9f8241c | 1a9111c8752b2445f448986779b397e9773c4734 | refs/heads/master | 2021-05-02T08:07:47.145931 | 2018-09-25T06:13:58 | 2018-09-25T06:13:58 | 120,845,346 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 276 | java | package com.wangsocial.app.service;
import com.wangsocial.app.entity.Payment;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 支付表 服务类
* </p>
*
* @author
* @since 2017-06-21
*/
public interface PaymentService extends IService<Payment> {
}
| [
"504887284@qq.com"
] | 504887284@qq.com |
253106d3a5d28c3c7b47fe286c2344f1fd401a2e | c893e4f191f02e853732cc8ea82d820b98234b5e | /ShellAddScriptTool/src/com/tomagoyaky/apkeditor/utils/Charsets.java | 65ddebebfb9f40e1a67fb3d2fa23b0b25bceba9f | [] | no_license | tomagoyaky/tomagoyakyShell | 726e267fce82e56089c3b1011f1332852e3df80a | 6be018144fb943ae1ff86a8301ec2b047f7cff22 | refs/heads/master | 2021-01-10T02:39:04.223793 | 2016-03-12T09:54:49 | 2016-03-12T09:54:49 | 53,195,492 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,035 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tomagoyaky.apkeditor.utils;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Charsets required of every implementation of the Java platform.
*
* From the Java documentation <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">
* Standard charsets</a>:
* <p>
* <cite>Every implementation of the Java platform is required to support the following character encodings. Consult
* the release documentation for your implementation to see if any other encodings are supported. Consult the release
* documentation for your implementation to see if any other encodings are supported. </cite>
* </p>
*
* <ul>
* <li><code>US-ASCII</code><br>
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.</li>
* <li><code>ISO-8859-1</code><br>
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.</li>
* <li><code>UTF-8</code><br>
* Eight-bit Unicode Transformation Format.</li>
* <li><code>UTF-16BE</code><br>
* Sixteen-bit Unicode Transformation Format, big-endian byte order.</li>
* <li><code>UTF-16LE</code><br>
* Sixteen-bit Unicode Transformation Format, little-endian byte order.</li>
* <li><code>UTF-16</code><br>
* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
* accepted on input, big-endian used on output.)</li>
* </ul>
*
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @since 2.3
* @version $Id$
*/
public class Charsets {
//
// This class should only contain Charset instances for required encodings. This guarantees that it will load
// correctly and without delay on all Java platforms.
//
/**
* Returns the given Charset or the default Charset if the given Charset is null.
*
* @param charset
* A charset or null.
* @return the given Charset or the default Charset if the given Charset is null
*/
public static Charset toCharset(final Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
}
/**
* Returns a Charset for the named charset. If the name is null, return the default Charset.
*
* @param charset
* The name of the requested charset, may be null.
* @return a Charset for the named charset
* @throws java.nio.charset.UnsupportedCharsetException
* If the named charset is unavailable
*/
public static Charset toCharset(final String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
}
/**
* <p>
* Eight-bit Unicode Transformation Format.
* </p>
* <p>
* Every implementation of the Java platform is required to support this character encoding.
* </p>
*
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
*/
@Deprecated
public static final Charset UTF_8 = Charset.forName("UTF-8");
} | [
"765175458@qq.com"
] | 765175458@qq.com |
0f581a6099a77221bcc3d52262b780ff518af9fc | f857e7ef3d3d4da42e9e683820fcc122ecb5d798 | /app/src/test/java/com/abdallah/weathery/ExampleUnitTest.java | f3a628ae0c5c0c1f268430ddf1b48d17c9b292ee | [] | no_license | Abd-Allah-muhammed-muhammed/Weathery | f21138c5942715f43a4fbbfca020190265b9ae4b | be1b579a2fde93e7de065864b42a6b5f96236962 | refs/heads/master | 2022-11-15T21:04:50.403731 | 2020-07-11T15:37:22 | 2020-07-11T15:37:22 | 278,223,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.abdallah.weathery;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect( ) {
assertEquals(4, 2 + 2);
}
} | [
"abdallahkshaf151@gmail.com"
] | abdallahkshaf151@gmail.com |
1b8bcc08417ed5cdea9186ba34879a354f045989 | 2a515fecd1bfa95d4d8b8571a597d430a37d16db | /src/main/java/com/pwc/assignment/controller/DepartmentController.java | 8fdcc65409c4ed6ae2ed842adc2c1232c96ac508 | [] | no_license | mabulhaija/cms | 90edc60aedcfd209d8b0a5c86a053cf2c01e15f1 | 801216957e6120601fb704c04a3ad4dc6f275fa4 | refs/heads/master | 2023-07-16T17:07:48.118783 | 2021-09-01T18:55:32 | 2021-09-01T18:55:32 | 401,834,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,088 | java | package com.pwc.assignment.controller;
import com.pwc.assignment.authentication.JwtTokenProvider;
import com.pwc.assignment.model.Department;
import com.pwc.assignment.service.DepartmentService;
import com.pwc.assignment.service.response.Response;
import com.pwc.assignment.service.response.success.CreatedResponse;
import com.pwc.assignment.service.response.success.NoContentResponse;
import com.pwc.assignment.service.response.success.OkResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@Autowired
DepartmentService departmentService;
@Autowired
private HttpServletRequest request;
@GetMapping
public Response getDepartments(@RequestParam(value = "size", required = false, defaultValue = "5") @Min(value = 5) @Max(value = 25) int size,
@RequestParam(value = "offset", required = false, defaultValue = "0") @Min(value = 0) int offset,
@RequestParam(value = "name", required = false) String name) {
return new OkResponse("Success!", departmentService.getEntities(size, offset, name));
}
@GetMapping("/{id}")
public Response getDepartmentById(@PathVariable("id") Integer id) {
return new OkResponse("Success!", departmentService.getEntityById(id));
}
@GetMapping("/{id}/users")
public Response getDepartmentUsers(@PathVariable("id") Integer id,
@RequestParam(value = "size", required = false, defaultValue = "5") @Min(value = 5) @Max(value = 25) int size,
@RequestParam(value = "offset", required = false, defaultValue = "0") @Min(value = 0) int offset) {
return new OkResponse("Success!", departmentService.getDepartmentUsers(id, size, offset));
}
@PostMapping
public Response addNewDepartment(@NotNull(message = "Request body cannot be null") @Valid @RequestBody Department department) {
Integer userId = JwtTokenProvider.extractUserData(request).getId();
department.setAddedBy(userId);
return new CreatedResponse("Department added successfully!", departmentService.insertEntity(department));
}
@PutMapping("/{id}")
public Response updateDepartment(@PathVariable("id") Integer id,
@NotNull(message = "Request body cannot be null") @Valid @RequestBody Department department) {
departmentService.updateEntity(id, department);
return new OkResponse("Department updated successfully!", department);
}
@DeleteMapping("/{id}")
public Response deleteDepartment(@PathVariable("id") Integer id) {
departmentService.deleteEntity(id);
return new NoContentResponse();
}
}
| [
"m.abdallah@arabot.io"
] | m.abdallah@arabot.io |
c6fa8ec576f42d4bbe96d03e25599ef0ad74ff1d | b39d7e1122ebe92759e86421bbcd0ad009eed1db | /sources/android/media/-$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I.java | 80ac29402da64f56fc8956fd7ed41f1af551b663 | [] | no_license | AndSource/miuiframework | ac7185dedbabd5f619a4f8fc39bfe634d101dcef | cd456214274c046663aefce4d282bea0151f1f89 | refs/heads/master | 2022-03-31T11:09:50.399520 | 2020-01-02T09:49:07 | 2020-01-02T09:49:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 688 | java | package android.media;
import java.util.ArrayList;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I implements Runnable {
private final /* synthetic */ AudioRecordingCallbackInfo f$0;
private final /* synthetic */ ArrayList f$1;
public /* synthetic */ -$$Lambda$AudioRecordingMonitorImpl$2$cn04v8rie0OYr-_fiLO_SMYka7I(AudioRecordingCallbackInfo audioRecordingCallbackInfo, ArrayList arrayList) {
this.f$0 = audioRecordingCallbackInfo;
this.f$1 = arrayList;
}
public final void run() {
this.f$0.mCb.onRecordingConfigChanged(this.f$1);
}
}
| [
"shivatejapeddi@gmail.com"
] | shivatejapeddi@gmail.com |
cfe0908eea167caed8e052dc5b005b18915948e1 | 3c875e49e161ad3b692eb3a80d95b26bc51ee941 | /mall/mall-mbg/src/main/java/com/xzj/mall/mapper/UmsMemberLoginLogMapper.java | e1b5436216a75692032788fb2a6fa2ca273c6deb | [] | no_license | Xuezaijing/doc | 2cc4d4bb368152b9f727c8bd209a16e9bb58d2b7 | 53c9bfc7b3b2b7bd4b781c6e1e51702904a47020 | refs/heads/master | 2022-07-07T07:41:15.865165 | 2020-09-03T11:59:48 | 2020-09-03T11:59:48 | 192,318,423 | 0 | 1 | null | 2022-06-21T01:17:49 | 2019-06-17T09:40:29 | Java | UTF-8 | Java | false | false | 992 | java | package com.xzj.mall.mapper;
import com.xzj.mall.model.UmsMemberLoginLog;
import com.xzj.mall.model.UmsMemberLoginLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UmsMemberLoginLogMapper {
int countByExample(UmsMemberLoginLogExample example);
int deleteByExample(UmsMemberLoginLogExample example);
int deleteByPrimaryKey(Long id);
int insert(UmsMemberLoginLog record);
int insertSelective(UmsMemberLoginLog record);
List<UmsMemberLoginLog> selectByExample(UmsMemberLoginLogExample example);
UmsMemberLoginLog selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UmsMemberLoginLog record, @Param("example") UmsMemberLoginLogExample example);
int updateByExample(@Param("record") UmsMemberLoginLog record, @Param("example") UmsMemberLoginLogExample example);
int updateByPrimaryKeySelective(UmsMemberLoginLog record);
int updateByPrimaryKey(UmsMemberLoginLog record);
} | [
"1062147007@qq.com"
] | 1062147007@qq.com |
d265670591721c88563da3df8c4ad7c0458fb82e | c65f507f37797de753482e3bf3a19ab36d84ec56 | /ScFrame/src/main/java/com/caihan/scframe/utils/MetaDataUtils.java | ceeeb9d9c8a8c8d8f0f71414601385cc648c84f4 | [] | no_license | tieruni/MyScFrame | 4d7a91b42af982a0f752a802d73b2d2e3ecfbee5 | 9a16c71760827f41d8a013b6fe7fe4393a53884e | refs/heads/master | 2022-02-16T01:06:15.620230 | 2019-09-15T02:16:36 | 2019-09-15T02:16:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,865 | java | package com.caihan.scframe.utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
/**
* meta-data标签工具类
*
* @author caihan
* @date 2018/6/26
* @e-mail 93234929@qq.com
* 维护者
*/
public class MetaDataUtils {
/**
* 获取value
* <meta-data android:name="meta_app" android:value="value from meta_app" />
*
* @param context 上下文
* @param metaStringKey meta_app
* @return value from meta_app
*/
public static String getMetaDataFromApp(Context context, String metaStringKey) {
String value = "";
try {
ApplicationInfo appInfo = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
value = appInfo.metaData.getString(metaStringKey);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return value;
}
/**
* 获取resource id
* <p>
* <meta-data android:name="meta_act" android:resource="@string/app_name" />
*
* @param context 上下文
* @param metaStringKey meta_act
* @return
*/
public static int getMetaDataIdFromAct(Context context, String metaStringKey) {
int resId = 0;
try {
ActivityInfo activityInfo = context.getPackageManager()
.getActivityInfo(((Activity) context).getComponentName(),
PackageManager.GET_META_DATA);
resId = activityInfo.metaData.getInt(metaStringKey);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return resId;
}
}
| [
"93234929@qq.com"
] | 93234929@qq.com |
46c6359be0c0f9b167d5c8a3d2d4657349fabb35 | 5291f4b848fe0c4391616cec25806f9e015f23a6 | /src/todo/utils/DBUtils.java | 43e8f1e7bfb750e4d229a1ff7ba2868a1ff6b557 | [] | no_license | sudoy/todo_suzuki | 28b207beb39c7fb4640d780315eef1629a85c6dc | d4b6ad7acc48768e4ffa7a361a053c1a5aeb363c | refs/heads/master | 2020-06-10T11:11:27.178638 | 2019-07-09T05:34:56 | 2019-07-09T05:34:56 | 193,638,865 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,640 | java | package todo.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBUtils {
//DB接続
public static Connection getConnection() throws NamingException, SQLException {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("asms");
return ds.getConnection();
}
//DB閉じる
public static void close(Connection c,PreparedStatement p,ResultSet r){
try {
if(r != null){
r.close();
}
if(p != null){
p.close();
}
if(c != null){
c.close();
}
} catch (Exception e) {}
}
public static void close(Connection c,PreparedStatement p){
try {
if(p != null){
p.close();
}
if(c != null){
c.close();
}
} catch (Exception e) {}
}
public static void close(PreparedStatement p,ResultSet r){
try {
if(p != null){
p.close();
}
if(r != null){
r.close();
}
} catch (Exception e) {}
}
public static void colse(Connection c){
try{
if(c != null){ c.close(); }
}catch(Exception e) {}
}
public static void close(PreparedStatement... ps){
for(PreparedStatement p : ps) {
try{
if(p != null){ p.close(); }
}catch(Exception e) {}
}
}
public static void close(ResultSet r){
try{
if(r != null){ r.close(); }
}catch(Exception e) {}
}
}
| [
"鈴木@TSD-SUZUKI"
] | 鈴木@TSD-SUZUKI |
2087ea21ce95685d05ab635e4344d3cc6e3aa433 | 129f58086770fc74c171e9c1edfd63b4257210f3 | /src/testcases/CWE470_Unsafe_Reflection/CWE470_Unsafe_Reflection__listen_tcp_54b.java | 75fccc2cab795bff5b42cff86fb0d441341365ed | [] | no_license | glopezGitHub/Android23 | 1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba | 6215d0684c4fbdc7217ccfbedfccfca69824cc5e | refs/heads/master | 2023-03-07T15:14:59.447795 | 2023-02-06T13:59:49 | 2023-02-06T13:59:49 | 6,856,387 | 0 | 3 | null | 2023-02-06T18:38:17 | 2012-11-25T22:04:23 | Java | UTF-8 | Java | false | false | 1,170 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE470_Unsafe_Reflection__listen_tcp_54b.java
Label Definition File: CWE470_Unsafe_Reflection.label.xml
Template File: sources-sink-54b.tmpl.java
*/
/*
* @description
* CWE: 470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
* BadSource: listen_tcp Read data using a listening tcp connection
* GoodSource: Set data to a hardcoded class name
* Sinks:
* BadSink : Instantiate class named in data
* Flow Variant: 54 Data flow: data passed as an argument from one method through three others to a fifth; all five functions are in different classes in the same package
*
* */
package testcases.CWE470_Unsafe_Reflection;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE470_Unsafe_Reflection__listen_tcp_54b
{
public void bad_sink(String data ) throws Throwable
{
(new CWE470_Unsafe_Reflection__listen_tcp_54c()).bad_sink(data );
}
/* goodG2B() - use goodsource and badsink */
public void goodG2B_sink(String data ) throws Throwable
{
(new CWE470_Unsafe_Reflection__listen_tcp_54c()).goodG2B_sink(data );
}
}
| [
"guillermo.pando@gmail.com"
] | guillermo.pando@gmail.com |
9ac11fef1620ced044058e61cc5ece0764608236 | 8fe809808931203aa6913d130afb2f41ac58ef2c | /src/com/ai/aris/server/webservice/service/impl/AisServiceSVImpl.java | 00f271df13c5482f7fc627e95c40a42aba5610c9 | [] | no_license | yangsense/bpris | 08332632f39fa33584bdcb95f07e5d61b635a347 | 77bed9caebc4fd1a4b5a90e5de884ffc414fc5cc | refs/heads/master | 2020-06-05T16:54:31.536441 | 2019-06-18T09:49:47 | 2019-06-18T09:49:47 | 192,486,051 | 0 | 0 | null | 2019-06-18T07:46:34 | 2019-06-18T07:12:00 | null | UTF-8 | Java | false | false | 112,089 | java | package com.ai.aris.server.webservice.service.impl;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
import com.ai.appframe2.bo.DataContainerFactory;
import com.ai.appframe2.bo.SysdateManager;
import com.ai.appframe2.common.AIConfigManager;
import com.ai.appframe2.common.DataContainerInterface;
import com.ai.appframe2.common.ServiceManager;
import com.ai.appframe2.service.ServiceFactory;
import com.ai.aris.server.basecode.bean.AisPatientInfoHisBean;
import com.ai.aris.server.basecode.bean.AisPatientInfoHisEngine;
import com.ai.aris.server.basecode.bean.AisPixInfoBean;
import com.ai.aris.server.basecode.bean.AisPixInfoEngine;
import com.ai.aris.server.basecode.bean.AisServiceLogBean;
import com.ai.aris.server.basecode.bean.AisServiceLogEngine;
import com.ai.aris.server.basecode.bean.AiscBodyPart2ItemBean;
import com.ai.aris.server.basecode.bean.AiscBodyPart2ItemEngine;
import com.ai.aris.server.basecode.bean.AiscBodyPartBean;
import com.ai.aris.server.basecode.bean.AiscBodyPartEngine;
import com.ai.aris.server.basecode.bean.AiscCareProvBean;
import com.ai.aris.server.basecode.bean.AiscCareProvEngine;
import com.ai.aris.server.basecode.bean.AiscConorganizationBean;
import com.ai.aris.server.basecode.bean.AiscEquipmentBean;
import com.ai.aris.server.basecode.bean.AiscEquipmentEngine;
import com.ai.aris.server.basecode.bean.AiscItemMastBean;
import com.ai.aris.server.basecode.bean.AiscItemMastEngine;
import com.ai.aris.server.basecode.bean.AiscLocBean;
import com.ai.aris.server.basecode.bean.AiscLocEngine;
import com.ai.aris.server.basecode.bean.AiscLoginLocBean;
import com.ai.aris.server.basecode.bean.AiscOrdCat2LocBean;
import com.ai.aris.server.basecode.bean.AiscOrdCat2LocEngine;
import com.ai.aris.server.basecode.bean.AiscOrdCategoryBean;
import com.ai.aris.server.basecode.bean.AiscOrdCategoryEngine;
import com.ai.aris.server.basecode.bean.AiscOrdSubCategoryBean;
import com.ai.aris.server.basecode.bean.AiscRoomBean;
import com.ai.aris.server.basecode.bean.AiscRoomEngine;
import com.ai.aris.server.basecode.bean.AiscServerInfoBean;
import com.ai.aris.server.basecode.bean.AiscServerInfoEngine;
import com.ai.aris.server.basecode.bean.AiscUser2CareProvBean;
import com.ai.aris.server.common.bean.CommonEngine;
import com.ai.aris.server.common.service.interfaces.ICommonSV;
import com.ai.aris.server.common.util.DBUtil;
import com.ai.aris.server.interfacereal.bean.AisPatientRealBean;
import com.ai.aris.server.interfacereal.bean.AisPatientRealEngine;
import com.ai.aris.server.interfacereal.bean.AisStudyinfoRealBean;
import com.ai.aris.server.interfacereal.bean.AisStudyinfoRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscBodyPart2ItemRealBean;
import com.ai.aris.server.interfacereal.bean.AiscBodypartRealBean;
import com.ai.aris.server.interfacereal.bean.AiscBodypartRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscCareprovRealBean;
import com.ai.aris.server.interfacereal.bean.AiscCareprovRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscEquipmentRealBean;
import com.ai.aris.server.interfacereal.bean.AiscEquipmentRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscItemmastRealBean;
import com.ai.aris.server.interfacereal.bean.AiscItemmastRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscLocRealBean;
import com.ai.aris.server.interfacereal.bean.AiscLocRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscOrdCat2LocRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdcategoryRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdcategoryRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscOrdsubcategoryRealBean;
import com.ai.aris.server.interfacereal.bean.AiscOrdsubcategoryRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscRoomRealBean;
import com.ai.aris.server.interfacereal.bean.AiscRoomRealEngine;
import com.ai.aris.server.interfacereal.bean.AiscSeverinfoRealBean;
import com.ai.aris.server.interfacereal.bean.AiscSeverinfoRealEngine;
import com.ai.aris.server.interfacereal.bean.QryStudyItemInterfaceBean;
import com.ai.aris.server.interfacereal.bean.QryordsubcateINFBean;
import com.ai.aris.server.interfacereal.bean.QryordsubcateINFEngine;
import com.ai.aris.server.webservice.BusiDataEnum;
import com.ai.aris.server.webservice.DataEnum;
import com.ai.aris.server.webservice.bean.AisPatientInfoData;
import com.ai.aris.server.webservice.bean.AisStudyReportData;
import com.ai.aris.server.webservice.service.interfaces.IAisServiceSV;
import com.ai.aris.server.workstation.bean.AisFilesInfoBean;
import com.ai.aris.server.workstation.bean.AisFilesInfoEngine;
import com.ai.aris.server.workstation.bean.AisPatientInfoBean;
import com.ai.aris.server.workstation.bean.AisPatientInfoEngine;
import com.ai.aris.server.workstation.bean.AisReportFilesBean;
import com.ai.aris.server.workstation.bean.AisReportFilesEngine;
import com.ai.aris.server.workstation.bean.AisStudyInfoBean;
import com.ai.aris.server.workstation.bean.AisStudyInfoEngine;
import com.ai.aris.server.workstation.bean.AisStudyItemInfoBean;
import com.ai.aris.server.workstation.bean.AisStudyItemInfoEngine;
import com.ai.aris.server.workstation.bean.AisStudyReportBean;
import com.ai.aris.server.workstation.bean.AisStudyReportEngine;
import com.ai.aris.server.workstation.bean.QryReportHBean;
import com.ai.aris.server.workstation.bean.QryReportHEngine;
import com.ai.aris.server.workstation.bean.QryServerMediumBean;
import com.ai.aris.server.workstation.bean.QryServerMediumEngine;
import com.ai.aris.server.workstation.model.AisFilesInfoModel;
import com.ai.aris.server.workstation.service.interfaces.IPatientRegSV;
import com.ai.common.json.TimestampMorpher;
import com.ai.common.util.DateUtils;
import com.ai.common.util.ServiceUtil;
public class AisServiceSVImpl implements IAisServiceSV {
IPatientRegSV patientSv = (IPatientRegSV) ServiceFactory.getService(IPatientRegSV.class);
ICommonSV commonSV = (ICommonSV) ServiceFactory.getService(ICommonSV.class);
public <T extends DataContainerInterface> void save(T aBean) throws Exception{
CommonEngine.save(aBean);
}
public void updateSynMark(List<AisStudyReportData> list)throws Exception{
if(list!=null&&list.size()>0){
for(AisStudyReportData bean :list){
try {
String delSql2 = "update ais_studyreport set REPORT_TOARCHIVE=1 where report_id="+bean.getReportId()+" and studyinfo_id="+bean.getStudyinfoId()+"";
commonSV.execute(delSql2,null);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
@Override
public AisPixInfoBean[] getAisPixInfoBean(String patientId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(patientId)) {
condition.append(" AND PATIENT_ID = '" + patientId+"'" );
}
if (isNotBlank(orgId)) {
condition.append(" AND ORG_ID = '" + orgId+"'" );
}
AisPixInfoBean[] pixBean = AisPixInfoEngine.getBeans(condition.toString(), null);
if(pixBean.length > 0){
return pixBean;
}else{
return null;
}
}
@Override
public AisPatientInfoBean[] getAisPatientBean(String idNumber) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(idNumber)) {
condition.append(" AND PATIENT_IDNUMBER = '" + idNumber+"'" );
}
AisPatientInfoBean[] patientBean = AisPatientInfoEngine.getBeans(condition.toString(), null);
if(patientBean.length > 0){
return patientBean;
}else{
return null;
}
}
@Override
public boolean insertPatientBean(long id,String patientId,Map map) throws Exception{
try {
String patientDob = map.get("Patient_DOB").toString().equals("")?"":map.get("Patient_DOB").toString();
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientGlobalid(id);
bean.setPatientId(patientId);
bean.setPatientName(map.get("Patient_Name").toString());
bean.setPatientNamepy(map.get("Patient_NamePy").toString());
bean.setPatientDob(Timestamp.valueOf(patientDob));
bean.setPatientAge(map.get("Patient_Age").toString());
bean.setPatientSex(map.get("Patient_Sex").toString());
bean.setPatientIdnumber(map.get("Patient_IDNumber").toString());
bean.setPatientCardid(map.get("Patient_CardID").toString());
bean.setPatientMedicareid(map.get("Patient_MedicareID").toString());
bean.setPatientMobile(map.get("Patient_Mobile").toString());
bean.setPatientPhone(map.get("Patient_Phone").toString());
bean.setPatientVocation(map.get("Patient_Vocation").toString());
bean.setPatientNation(map.get("Patient_Nation").toString());
bean.setPatientStation(map.get("Patient_Station").toString());
bean.setPatientRemark(map.get("Patient _Remark").toString());
bean.setPatientStatus(map.get("Patient_Status").toString());
bean.setPatientAddress(map.get("Patient_Address").toString());
AisPatientInfoEngine.save(bean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean insertPixBean(long id,Map map) throws Exception{
try {
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(map.get("Org_Id").toString());
zbean.setPatientId(map.get("Patient_HID").toString());
AisPixInfoEngine.save(zbean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean updatePatient(long id,Map map) throws Exception{
try {
String patientDob = map.get("Patient_DOB").toString().equals("")?"":map.get("Patient_DOB").toString();
//修改前保存原始记录
AisPatientInfoBean oldBean = AisPatientInfoEngine.getBean(id);
AisPatientInfoHisBean hisBean = new AisPatientInfoHisBean();
DataContainerFactory.copyNoClearData(oldBean, hisBean);
AisPatientInfoHisEngine.save(hisBean);
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientGlobalid(id);
bean.setStsToOld();
bean.setPatientName(map.get("Patient_Name").toString());
bean.setPatientNamepy(map.get("Patient_NamePy").toString());
bean.setPatientDob(Timestamp.valueOf(patientDob));
bean.setPatientAge(map.get("Patient_Age").toString());
bean.setPatientSex(map.get("Patient_Sex").toString());
bean.setPatientIdnumber(map.get("Patient_IDNumber").toString());
bean.setPatientCardid(map.get("Patient_CardID").toString());
bean.setPatientMedicareid(map.get("Patient_MedicareID").toString());
bean.setPatientMobile(map.get("Patient_Mobile").toString());
bean.setPatientPhone(map.get("Patient_Phone").toString());
bean.setPatientVocation(map.get("Patient_Vocation").toString());
bean.setPatientNation(map.get("Patient_Nation").toString());
bean.setPatientStation(map.get("Patient_Station").toString());
bean.setPatientRemark(map.get("Patient _Remark").toString());
bean.setPatientStatus(map.get("Patient_Status").toString());
bean.setPatientAddress(map.get("Patient_Address").toString());
AisPatientInfoEngine.save(bean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean deleteBusiData(String orgId) throws Exception{
Statement stmt = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = "delete from ais_studyreport where studyinfo_id in (select studyinfo_id from ais_studyinfo where org_id='"+orgId+"' and studystatus_code='VERIFY')";
String sql1 = "delete from ais_studyiteminfo where studyinfo_id in (select studyinfo_id from ais_studyinfo where org_id='"+orgId+"' and studystatus_code='VERIFY')";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}finally{
com.ai.aris.server.common.util.DBUtil.release(null, stmt, null);
}
}
@Override
public void deleteStudyinfoReal(String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(orgId)) {
condition.append(" AND org_id = '" + orgId+"'" );
}
AisStudyinfoRealBean[] realBeans = AisStudyinfoRealEngine.getBeans(condition.toString(), null);
if(realBeans.length > 0){
for(AisStudyinfoRealBean bean :realBeans){
bean.delete();
AisStudyinfoRealEngine.save(bean);
}
}
}
@Override
public boolean insertStudyInfo(Map map) throws Exception{
Statement stmt = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
long studyId = ServiceUtil.getSequence("SEQSTUDYINFOID");
String cloumn = "STUDYINFO_ID,ORG_ID,LOC_ID,PATIENT_OUTPATIENTID,PATIENT_INPATIENTID,STUDY_EPSODEID,PATIENTTYPE_CODE,"
+ "STUDY_APPLOCID,STUDY_APPDOC,STUDY_WARD,STUDY_BEDNO,STUDY_AIM,STUDY_CLINIC,STUDY_ITEMDESC,STUDY_APPDATE,STUDY_ACCNUMBER,STUDYSTATUS_CODE,PATIENT_GLOBALID";
String studyapptime = map.get("Study_AppDateTime").toString().equals("")?"":map.get("Study_AppDateTime").toString();
String cloumnValue = ""+studyId+",'"+map.get("ORG_ID")+"','"+map.get("Loc_code")+"','"+map.get("Patient_OutpatientID")+"'," +
"'"+map.get("Patient_InpatientID")+"','"+map.get("Study_EpsodeID")+"','"+map.get("PatientType_Code")+"','"+map.get("Study_AppLoc")+"','"+map.get("Study_AppDoc")+"'," +
"'"+map.get("Study_Ward")+"','"+map.get("Study_bedNo")+"','"+map.get("Study_Aim")+"','"+map.get("Study_Clinic")+"','"+map.get("Study_ItemDesc")+"' "
+ "to_date('"+studyapptime+"','yyyy-MM-dd hh24:mi:ss'),'"+map.get("Study_Accnumber")+"','"+map.get("StudyStatus_Code")+"',"+map.get("PATIENT_GLOBALID")+" ";
//
String sql = "insert into ais_studyinfo ("+cloumn+") values ("+cloumnValue+")";
stmt.executeUpdate(sql);
// Timestamp dateTime=new Timestamp(new Date().getTime());
String reportTime = map.get("Report_ReportDateTime").toString().equals("")?"":map.get("Report_ReportDateTime").toString();
long newReportId = ServiceUtil.getSequence("SEQREPORTID");
AisStudyReportBean reportBean = new AisStudyReportBean();
reportBean.setReportId(newReportId);
reportBean.setStudyinfoId(studyId);
reportBean.setReportDatetime(Timestamp.valueOf(reportTime));
reportBean.setReportDoctorid(map.get("Study_ReportDoctorCode").toString());
reportBean.setReportVerifydoctorid(map.get("Report_ReportDoctor").toString());
reportBean.setReportExammethod(map.get("Report_ExamMethod").toString());
reportBean.setReportIspositive(Integer.parseInt(map.get("Report_IsPositive").toString()));
reportBean.setReportRemark(map.get("Study_Remark").toString());
reportBean.setReportExam(map.get("Report_Exam").toString());
reportBean.setReportResult(map.get("Report_Result").toString());
AisStudyReportEngine.save(reportBean);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}finally{
com.ai.aris.server.common.util.DBUtil.release(null, stmt, null);
}
}
@Override
public String insertPatientBean(String orgId,AisPatientInfoData model) throws Exception{
Map seqs = patientSv.getSeq(orgId,"-999");
long id = Long.parseLong(seqs.get("patientGlobalid").toString());
String pacsPatientId = seqs.get("patientId").toString();
//pix保存医院的病人ID
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(orgId);
zbean.setPatientId(model.getPatientId());
AisPixInfoEngine.save(zbean);
//
AisPatientRealBean real = new AisPatientRealBean();
real.setPatientRealId(ServiceUtil.getSequence("SEQPATIENT_REAL"));
real.setGlobalId(id);
real.setOldGlobalId(model.getPatientGlobalid());
real.setOrgId(orgId);
AisPatientRealEngine.save(real);
//中心病人ID保存为中心规则病人ID
AisPatientInfoBean bean = new AisPatientInfoBean();
bean.setPatientId(pacsPatientId);
bean.setPatientGlobalid(id);
bean.setPatientName(model.getPatientName());
bean.setPatientNamepy(model.getPatientNamepy());
bean.setPatientDob(model.getPatientDob());
bean.setPatientAge(model.getPatientAge());
bean.setPatientSex(model.getPatientSex());
bean.setPatientIdnumber(model.getPatientIdnumber());
bean.setPatientCardid(model.getPatientCardid());
bean.setPatientMedicareid(model.getPatientMedicareid());
bean.setPatientMobile(model.getPatientMobile());
bean.setPatientPhone(model.getPatientPhone());
bean.setPatientVocation(model.getPatientVocation());
bean.setPatientNation(model.getPatientNation());
bean.setPatientStation(model.getPatientStation());
bean.setPatientStatus(model.getPatientStatus());
bean.setPatientRemark(model.getPatientRemark());
bean.setPatientAddress(model.getPatientAddress());
bean.setOrgId(orgId);
AisPatientInfoEngine.save(bean);
return String.valueOf(id);
}
@Override
public void insertPixBean(long id,String orgId,AisPatientInfoData model) throws Exception{
try {
//pix保存医院的病人ID
AisPixInfoBean zbean = new AisPixInfoBean();
zbean.setPatientGlobalid(id);
zbean.setOrgId(orgId);
zbean.setPatientId(model.getPatientId());
AisPixInfoEngine.save(zbean);
//
AisPatientRealBean real = new AisPatientRealBean();
real.setPatientRealId(ServiceUtil.getSequence("SEQPATIENT_REAL"));
real.setGlobalId(id);
real.setOldGlobalId(model.getPatientGlobalid());
real.setOrgId(orgId);
AisPatientRealEngine.save(real);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void updatePatient(long id,AisPatientInfoData model) throws Exception{
AisPatientInfoBean oldBean = AisPatientInfoEngine.getBean(id);
oldBean.setStsToOld();
oldBean.setPatientName(model.getPatientName());
oldBean.setPatientNamepy(model.getPatientNamepy());
oldBean.setPatientDob(model.getPatientDob());
oldBean.setPatientAge(model.getPatientAge());
oldBean.setPatientSex(model.getPatientSex());
oldBean.setPatientIdnumber(model.getPatientIdnumber());
oldBean.setPatientCardid(model.getPatientCardid());
oldBean.setPatientMedicareid(model.getPatientMedicareid());
oldBean.setPatientMobile(model.getPatientMobile());
oldBean.setPatientPhone(model.getPatientPhone());
oldBean.setPatientAddress(model.getPatientAddress());
AisPatientInfoEngine.save(oldBean);
}
@Override
public AiscLocRealBean getLocRealBean(long locId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and old_loc_id="+locId );
AiscLocRealBean[] realBean = AiscLocRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AisStudyItemInfoBean[] getStudyItem(long studyinfoId) throws Exception{
String sql = "SELECT * FROM AIS_STUDYITEMINFO WHERE STUDYINFO_ID = " + studyinfoId;
AisStudyItemInfoBean[] studyItemInfoBeans = AisStudyItemInfoEngine.getBeansFromSql(sql, null);
if(studyItemInfoBeans.length > 0){
return studyItemInfoBeans;
}else{
return null;
}
}
@Override
public AisPatientRealBean getRealGlobalId(long globalId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_GLOBAL_ID ="+globalId );
AisPatientRealBean[] realBean = AisPatientRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscItemmastRealBean getStudyItemRealBean(long oldmastId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_ITEMMAST_ID ="+oldmastId );
AiscItemmastRealBean[] realBean = AiscItemmastRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscBodypartRealBean getBodypartRealBean(long oldmastId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_BODYPART_CODE ="+oldmastId );
AiscBodypartRealBean[] realBean = AiscBodypartRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AisStudyinfoRealBean getStudyinfoRealBean(long studyinfoId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_STUDYINFO_ID ="+studyinfoId );
AisStudyinfoRealBean[] realBean = AisStudyinfoRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscCareprovRealBean getCareBean(long careId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_CAREPROV_ID ="+careId );
AiscCareprovRealBean[] realBean = AiscCareprovRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscEquipmentRealBean getEquipmentBean(long equipId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_EQUIPMENT_ID ="+equipId );
AiscEquipmentRealBean[] realBean = AiscEquipmentRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public AiscRoomRealBean getRoomReal(long roomId,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and OLD_ROOM_ID ="+roomId );
AiscRoomRealBean[] realBean = AiscRoomRealEngine.getBeans(condition.toString(), null);
if(realBean.length > 0){
return realBean[0];
}else{
return null;
}
}
@Override
public void insertStudyItem(QryStudyItemInterfaceBean bean)throws Exception{
AisStudyItemInfoBean sbean = new AisStudyItemInfoBean();
sbean.setStudyinfoId(bean.getStudyinfoId());
sbean.setStudyitemId(ServiceUtil.getSequence("SEQSTUDYITEMID"));
sbean.setStudyitemHisid(bean.getStudyitemHisid());
sbean.setStudyitemCode(bean.getStudyitemCode());
sbean.setStudyitemDesc(bean.getStudyitemDesc());
sbean.setStudyitemEndesc(bean.getStudyitemEndesc());
sbean.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
sbean.setStudyitemPrice(bean.getStudyitemPrice());
sbean.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
sbean.setStudyitemStatus(bean.getStudyitemStatus());
sbean.setStudyitemItemno(bean.getStudyitemItemno());
sbean.setStudyitemBodypart(bean.getStudyitemBodypart());
AisStudyItemInfoEngine.save(sbean);
}
@Override
public void insertStudyinfoReal(long newStudyInfoId,AisStudyInfoBean bean)throws Exception{
AisStudyinfoRealBean realbean = new AisStudyinfoRealBean();
realbean.setStudyinfoRealId(ServiceUtil.getSequence("SEQSTUDYTEMPID"));
realbean.setStudyinfoId(newStudyInfoId);
realbean.setOldStudyinfoId(bean.getStudyinfoId());
realbean.setOrgId(bean.getOrgId());
AisStudyinfoRealEngine.save(realbean);
}
@Override
public AiscServerInfoBean getServerInfo(AiscServerInfoBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and server_ip='"+bean.getServerIp()+"'");
condition.append(" and server_type = '"+bean.getServerType()+"' ");
AiscServerInfoBean[] oldBean = AiscServerInfoEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
@Override
public AiscLocBean getLocInfo(AiscLocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and loc_code='"+bean.getLocCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscLocBean[] oldBean = AiscLocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscRoomBean getRoomInfo(AiscRoomBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_loc_id="+bean.getLocId(),null,AiscLocRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and loc_id="+realBeen[0].getLocId()+"");
}else{
condition.append(" and loc_id="+bean.getLocId()+"");
}
condition.append(" and room_desc='"+bean.getRoomDesc()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscRoomBean[] oldBean = AiscRoomEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscEquipmentBean getEquipment(AiscEquipmentBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and equipment_code='"+bean.getEquipmentCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscEquipmentBean[] oldBean = AiscEquipmentEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscOrdCategoryBean getCategory(AiscOrdCategoryBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and ordcategory_code='"+bean.getOrdcategoryCode()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscOrdCategoryBean[] oldBean = AiscOrdCategoryEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public QryordsubcateINFBean getAiscOrdSubCategory(AiscOrdSubCategoryBean bean,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and ordsubcategory_code='"+bean.getOrdsubcategoryCode()+"'");
condition.append(" and org_id='"+orgId+"'");
QryordsubcateINFBean[] oldBean = QryordsubcateINFEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public long getRealOrdcategoryId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_ordcategory_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscOrdcategoryRealBean[] oldBean = AiscOrdcategoryRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getOrdcategoryId();
}else{
return id;
}
}
public long getItemmastId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_itemmast_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscItemmastRealBean[] oldBean = AiscItemmastRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getItemmastId();
}else{
return id;
}
}
public long getLocId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_loc_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscLocRealBean[] oldBean = AiscLocRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getLocId();
}else{
return id;
}
}
public long getRoomId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_room_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscRoomRealBean[] oldBean = AiscRoomRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getRoomId();
}else{
return id;
}
}
public long getServerId(long id) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_server_id="+id);
AiscSeverinfoRealBean[] oldBean = AiscSeverinfoRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getServerId();
}else{
return id;
}
}
public long getBodyCode(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_bodypart_code="+id);
condition.append(" and org_id='"+orgId+"'");
AiscBodypartRealBean[] oldBean = AiscBodypartRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getBodypartCode();
}else{
return id;
}
}
public long getRealOrdSubcategoryId(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and old_subcate_id="+id);
condition.append(" and org_id='"+orgId+"'");
AiscOrdsubcategoryRealBean[] oldBean = AiscOrdsubcategoryRealEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0].getSubcateId();
}else{
return id;
}
}
public AiscItemMastBean getAiscItemMast(AiscItemMastBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and itemmast_code='"+bean.getItemmastCode()+"'");
condition.append(" and itemmast_desc='"+bean.getItemmastDesc()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscItemMastBean[] oldBean = AiscItemMastEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscBodyPartBean getAiscBodyPart(AiscBodyPartBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and bodypart_desc='"+bean.getBodypartDesc()+"'");
condition.append(" and org_id='"+bean.getOrgId()+"'");
condition.append(" and bodypart_type='"+bean.getBodypartType()+"'");
AiscBodyPartBean[] oldBean = AiscBodyPartEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscBodyPart2ItemBean getAiscBodyPartItem(AiscBodyPart2ItemBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscItemmastRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_itemmast_id="+bean.getItemmastId(),null,AiscItemmastRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and itemmast_id="+realBeen[0].getItemmastId()+"");
}else{
condition.append(" and itemmast_id="+bean.getItemmastId()+"");
}
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscBodypartRealBean[] partBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_bodypart_code="+bean.getBodypartCode(),null,AiscBodypartRealBean.class);
if(partBeen!=null&&partBeen.length>0){
condition.append(" and bodypart_code="+partBeen[0].getBodypartCode()+"");
}else{
condition.append(" and bodypart_code="+bean.getBodypartCode()+"");
}
condition.append(" and org_id='"+bean.getOrgId()+"'");
AiscBodyPart2ItemBean[] oldBean = AiscBodyPart2ItemEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscOrdCat2LocBean getAiscOrdcat2loc(AiscOrdCat2LocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
AiscOrdcategoryRealBean[] ordcat = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_ordcategory_id="+bean.getOrdcatId(),null,AiscOrdcategoryRealBean.class);
if(ordcat!=null&&ordcat.length>0){
condition.append(" and ordcat_id="+ordcat[0].getOrdcategoryId()+"");
}else{
condition.append(" and ordcat_id="+bean.getOrdcatId()+"");
}
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+bean.getOrgId()+" and old_loc_id="+bean.getLocId(),null,AiscLocRealBean.class);
if(realBeen!=null&&realBeen.length>0){
condition.append(" and loc_id="+realBeen[0].getLocId()+"");
}else{
condition.append(" and loc_id="+bean.getLocId()+"");
}
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscOrdCat2LocBean[] oldBean = AiscOrdCat2LocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public AiscCareProvBean getAiscCareprov(AiscCareProvBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and careprov_code='"+bean.getCareprovCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
AiscCareProvBean[] oldBean = AiscCareProvEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public String sendData(String body,String orgId) throws Exception{
Date currentTime = SysdateManager.getSysDate();
JSONObject jsonbody = JSONObject.fromObject(body);
String result = "success";
// try{
for (DataEnum c : DataEnum.values()) {
if("SEVERINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("SEVERINFO"));
List<AiscServerInfoBean> list = (List<AiscServerInfoBean>) JSONArray.toCollection(jsonArray,AiscServerInfoBean.class);
for(AiscServerInfoBean serverBean :list){
AiscServerInfoBean yBean = getServerInfo(serverBean);
if(yBean==null){
AiscSeverinfoRealBean newBean =new AiscSeverinfoRealBean();
//插入新服务器ID与源服务器ID对应关系
newBean.setServerRealId(commonSV.getSequence("SEQ_AISC_SEVERINFO_REAL"));
newBean.setOldServerId(serverBean.getServerId());
newBean.setOrgId(orgId);
serverBean.setServerId(commonSV.getSequence("SEQSERVERINFOID"));
newBean.setServerId(serverBean.getServerId());
commonSV.save(serverBean);
commonSV.save(newBean);
}else{
AiscSeverinfoRealBean qryBean = commonSV.getBean(" OLD_SERVER_ID = "+serverBean.getServerId()+" and org_id='"+orgId+"'",null,AiscSeverinfoRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_SEVERINFO_REAL t set SERVER_ID= "+yBean.getServerId()+",CREATE_TIME =to_date( '"+currentTime+"', 'yyyy-mm-dd hh24:mi:ss')\n" +
" where t.OLD_SERVER_ID = "+serverBean.getServerId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscSeverinfoRealBean realBean = new AiscSeverinfoRealBean();
realBean.setServerRealId(commonSV.getSequence("SEQ_AISC_SEVERINFO_REAL"));
realBean.setOldServerId(serverBean.getServerId());
realBean.setOrgId(orgId);
realBean.setServerId(yBean.getServerId());
commonSV.save(realBean);
}
}
}
}
if("ROOM".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ROOM"));
List<AiscRoomBean> list = (List<AiscRoomBean>) JSONArray.toCollection(jsonArray,AiscRoomBean.class);
for(AiscRoomBean roomBean :list){
//判断房间是否存在
AiscRoomBean ybean = getRoomInfo(roomBean);
if(ybean==null){
AiscRoomRealBean realBean =new AiscRoomRealBean();
realBean.setRoomRealId(commonSV.getSequence("SEQ_AISC_ROOM_REAL"));
realBean.setOldRoomId(roomBean.getRoomId());
realBean.setOrgId(String.valueOf(roomBean.getOrgId()));
roomBean.setRoomId(commonSV.getSequence("SEQROOMID"));
long locId = getLocId(roomBean.getLocId(),orgId);
roomBean.setLocId(locId);
realBean.setRoomId(roomBean.getRoomId());
commonSV.save(roomBean);
commonSV.save(realBean);
}else{
AiscRoomRealBean qryBean = commonSV.getBean(" OLD_ROOM_ID = "+roomBean.getRoomId()+" and org_id='"+ybean.getOrgId()+"'",null,AiscRoomRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ROOM_REAL t set ROOM_ID= "+ybean.getRoomId()+",CREATE_TIME =sysdate" +
" where t.OLD_ROOM_ID = "+roomBean.getRoomId()+" and t.org_id= "+ybean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscRoomRealBean realBean =new AiscRoomRealBean();
realBean.setRoomRealId(commonSV.getSequence("SEQ_AISC_ROOM_REAL"));
realBean.setOldRoomId(roomBean.getRoomId());
realBean.setOrgId(String.valueOf(roomBean.getOrgId()));
realBean.setRoomId(ybean.getRoomId());
commonSV.save(realBean);
}
}
}
}
if("LOC".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("LOC"));
List<AiscLocBean> list = (List<AiscLocBean>) JSONArray.toCollection(jsonArray,AiscLocBean.class);
for(AiscLocBean locBeen :list){
AiscLocBean oldBean = getLocInfo(locBeen);
if(oldBean==null){
//插入新科室及关系对应
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(locBeen.getOrgId());
realBean.setOldLocId(locBeen.getLocId());
locBeen.setLocId(commonSV.getSequence("SEQLOCID"));
long serverId = getServerId(locBeen.getServerId());
locBeen.setServerId(serverId);
realBean.setLocId(locBeen.getLocId());
commonSV.save(locBeen);
commonSV.save(realBean);
}else{
AiscLocRealBean qryBean = commonSV.getBean(" OLD_LOC_ID = "+locBeen.getLocId()+" and org_id='"+oldBean.getOrgId()+"'",null,AiscLocRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_loc_real t set loc_id= "+oldBean.getLocId()+",CREATE_TIME =sysdate" +
" where t.OLD_LOC_ID = "+locBeen.getLocId()+" and t.org_id= "+oldBean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(locBeen.getOrgId());
realBean.setOldLocId(locBeen.getLocId());
realBean.setLocId(oldBean.getLocId());
commonSV.save(realBean);
}
}
}
}
if("EQUIPMENT".equals(c.getInterfaceName())){
JsonConfig jsonConfig = new JsonConfig();
String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("EQUIPMENT"),jsonConfig);
List<AiscEquipmentBean> list = (List<AiscEquipmentBean>) JSONArray.toCollection(jsonArray,AiscEquipmentBean.class);
for(AiscEquipmentBean equipmentBeen:list){
AiscEquipmentBean oldBean = getEquipment(equipmentBeen);
if(oldBean==null){
AiscEquipmentRealBean realBean =new AiscEquipmentRealBean();
realBean.setEquipmentRealId(commonSV.getSequence("SEQ_AISC_EQUIPMENT_REAL"));
realBean.setOrgId(equipmentBeen.getOrgId());
realBean.setOldEquipmentId(equipmentBeen.getEquipmentId());
equipmentBeen.setEquipmentId(commonSV.getSequence("SEQEQUIPMENTID"));
long locId = getLocId(equipmentBeen.getLocId(),orgId);
equipmentBeen.setLocId(locId);
long roomId = getRoomId(equipmentBeen.getRoomId(),orgId);
equipmentBeen.setRoomId(roomId);
realBean.setEquipmentId(equipmentBeen.getEquipmentId());
// long ordsubcategoryId = getRealOrdSubcategoryId(equipmentBeen.getOrdsubcategoryId(),orgId);
// equipmentBeen.setOrdsubcategoryId(ordsubcategoryId);
commonSV.save(equipmentBeen);
commonSV.save(realBean);
}else{
AiscEquipmentRealBean qryBean = commonSV.getBean(" OLD_EQUIPMENT_ID = "+equipmentBeen.getEquipmentId()+" and org_id='"+oldBean.getOrgId()+"'",null,AiscEquipmentRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_equipment_real t set EQUIPMENT_ID= "+oldBean.getEquipmentId()+",CREATE_TIME =sysdate" +
" where t.OLD_EQUIPMENT_ID = "+equipmentBeen.getEquipmentId()+" and t.org_id= "+oldBean.getOrgId() ;
commonSV.execute(upSql,null);
}else{
AiscEquipmentRealBean realBean = new AiscEquipmentRealBean();
realBean.setEquipmentRealId(commonSV.getSequence("SEQ_AISC_EQUIPMENT_REAL"));
realBean.setOrgId(equipmentBeen.getOrgId());
realBean.setOldEquipmentId(equipmentBeen.getEquipmentId());
realBean.setEquipmentId(oldBean.getEquipmentId());
commonSV.save(realBean);
}
}
}
}
if("ORDCATEGORY".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDCATEGORY"));
List<AiscOrdCategoryBean> list = (List<AiscOrdCategoryBean>) JSONArray.toCollection(jsonArray,AiscOrdCategoryBean.class);
for (AiscOrdCategoryBean ordCategoryBeen:list){
AiscOrdCategoryBean oldBean = getCategory(ordCategoryBeen);
if(oldBean==null){
AiscOrdcategoryRealBean realBean =new AiscOrdcategoryRealBean();
realBean.setOrdcategoryRealId(commonSV.getSequence("SEQ_AISC_ORDCATEGORY_REAL"));
realBean.setOldOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
realBean.setOrgId(orgId);
ordCategoryBeen.setOrdcategoryId(commonSV.getSequence("SEQ_ORDCATEGORY"));
realBean.setOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
commonSV.save(ordCategoryBeen);
commonSV.save(realBean);
}else{
AiscOrdcategoryRealBean qryBean = commonSV.getBean(" OLD_ORDCATEGORY_ID = "+ordCategoryBeen.getOrdcategoryId()+" and org_id='"+orgId+"'",null,AiscOrdcategoryRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ORDCATEGORY_REAL t set ORDCATEGORY_ID= "+oldBean.getOrdcategoryId()+",CREATE_TIME =sysdate" +
" where t.OLD_ORDCATEGORY_ID = "+ordCategoryBeen.getOrdcategoryId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdcategoryRealBean realBean =new AiscOrdcategoryRealBean();
realBean.setOrdcategoryRealId(commonSV.getSequence("SEQ_AISC_ORDCATEGORY_REAL"));
realBean.setOldOrdcategoryId(ordCategoryBeen.getOrdcategoryId());
realBean.setOrgId(orgId);
realBean.setOrdcategoryId(oldBean.getOrdcategoryId());
commonSV.save(realBean);
}
}
}
}
if("ORDSUBCATEGORY".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDSUBCATEGORY"));
List<AiscOrdSubCategoryBean> list = (List<AiscOrdSubCategoryBean>) JSONArray.toCollection(jsonArray,AiscOrdSubCategoryBean.class);
for (AiscOrdSubCategoryBean ordSubCategoryBeen:list){
QryordsubcateINFBean oldBean = getAiscOrdSubCategory(ordSubCategoryBeen,orgId);
if(oldBean==null){
AiscOrdsubcategoryRealBean realBean =new AiscOrdsubcategoryRealBean();
realBean.setSubcateRealId(commonSV.getSequence("SEQ_aisc_ordsubcategory_real"));
realBean.setOldSubcateId (ordSubCategoryBeen.getOrdsubcategoryId());
realBean.setOrgId(orgId);
ordSubCategoryBeen.setOrdsubcategoryId(commonSV.getSequence("SEQ_ORDSUBCATEGORY"));
realBean.setSubcateId(ordSubCategoryBeen.getOrdsubcategoryId());
long id = getRealOrdcategoryId(ordSubCategoryBeen.getOrdcategoryId(),orgId);
ordSubCategoryBeen.setOrdcategoryId(id);
commonSV.save(ordSubCategoryBeen);
commonSV.save(realBean);
}else{
AiscOrdsubcategoryRealBean qryBean = commonSV.getBean(" old_subcate_id = "+ordSubCategoryBeen.getOrdsubcategoryId()+" and org_id='"+orgId+"'",null,AiscOrdsubcategoryRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_ordsubcategory_real t set subcate_id= "+oldBean.getOrdsubcategoryId()+",CREATE_TIME =sysdate" +
" where t.old_subcate_id = "+ordSubCategoryBeen.getOrdsubcategoryId()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdsubcategoryRealBean realBean =new AiscOrdsubcategoryRealBean();
realBean.setSubcateRealId(commonSV.getSequence("SEQ_aisc_ordsubcategory_real"));
realBean.setOldSubcateId (ordSubCategoryBeen.getOrdsubcategoryId());
realBean.setOrgId(orgId);
realBean.setSubcateId(oldBean.getOrdsubcategoryId());
commonSV.save(realBean);
}
}
}
}
if("ITEMMAST".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ITEMMAST"));
List<AiscItemMastBean> list = (List<AiscItemMastBean>) JSONArray.toCollection(jsonArray,AiscItemMastBean.class);
for (AiscItemMastBean itemMastBeen:list){
AiscItemMastBean oldBean = getAiscItemMast(itemMastBeen);
if(oldBean==null){
AiscItemmastRealBean newBean =new AiscItemmastRealBean();
newBean.setItemmastRealId(commonSV.getSequence("SEQ_AISC_ITEMMAST_REAL"));
newBean.setOldItemmastId(itemMastBeen.getItemmastId());
newBean.setOrgId(orgId);
itemMastBeen.setItemmastId(commonSV.getSequence("SEQ_ITEMMAST"));
newBean.setItemmastId(itemMastBeen.getItemmastId());
long id = getRealOrdcategoryId(itemMastBeen.getOrdcategoryId(),orgId);
itemMastBeen.setOrdcategoryId(id);
long subid = getRealOrdSubcategoryId(itemMastBeen.getOrdsubcategoryId(),orgId);
itemMastBeen.setOrdsubcategoryId(subid);
commonSV.save(itemMastBeen);
commonSV.save(newBean);
}else{
AiscItemmastRealBean qryBean = commonSV.getBean(" OLD_ITEMMAST_ID = "+itemMastBeen.getItemmastId()+" and org_id='"+orgId+"'",null,AiscItemmastRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_itemmast_real t set ITEMMAST_ID= "+oldBean.getItemmastId()+",CREATE_TIME =sysdate" +
" where t.OLD_ITEMMAST_ID = "+itemMastBeen.getItemmastId()+" and t.org_id= '"+orgId+"'";
commonSV.execute(upSql,null);
}else{
AiscItemmastRealBean newBean =new AiscItemmastRealBean();
newBean.setItemmastRealId(commonSV.getSequence("SEQ_AISC_ITEMMAST_REAL"));
newBean.setOldItemmastId(itemMastBeen.getItemmastId());
newBean.setOrgId(orgId);
newBean.setItemmastId(oldBean.getItemmastId());
commonSV.save(newBean);
}
}
}
}
if("BODYPART".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("BODYPART"));
List<AiscBodyPartBean> list = (List<AiscBodyPartBean>) JSONArray.toCollection(jsonArray,AiscBodyPartBean.class);
for (AiscBodyPartBean bodyPartBeen:list){
AiscBodyPartBean oldBean = getAiscBodyPart(bodyPartBeen);
if(oldBean==null){
AiscBodypartRealBean newBean =new AiscBodypartRealBean();
newBean.setBodypartRealId(commonSV.getSequence("SEQ_AISC_BODYPART_REAL"));
newBean.setOldBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
newBean.setOrgId(orgId);
bodyPartBeen.setBodypartCode(String.valueOf(commonSV.getSequence("SEQBODYPARTID")));
if(bodyPartBeen.getBodypartPid()!=-1){
long id = getBodyCode(bodyPartBeen.getBodypartPid(),orgId);
bodyPartBeen.setBodypartPid(id);
}
newBean.setBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
commonSV.save(bodyPartBeen);
commonSV.save(newBean);
}else{
AiscBodypartRealBean qryBean = commonSV.getBean(" OLD_BODYPART_CODE = "+bodyPartBeen.getBodypartCode()+" and org_id='"+orgId+"'",null,AiscBodypartRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_BODYPART_REAL t set BODYPART_CODE= "+oldBean.getBodypartCode()+",CREATE_TIME =sysdate" +
" where t.OLD_BODYPART_CODE = "+bodyPartBeen.getBodypartCode()+" and t.org_id= '"+orgId+"'" ;
commonSV.execute(upSql,null);
}else{
AiscBodypartRealBean newBean =new AiscBodypartRealBean();
newBean.setBodypartRealId(commonSV.getSequence("SEQ_AISC_BODYPART_REAL"));
newBean.setOldBodypartCode(Long.parseLong(bodyPartBeen.getBodypartCode()));
newBean.setOrgId(orgId);
newBean.setBodypartCode(Long.parseLong(oldBean.getBodypartCode()));
commonSV.save(newBean);
}
}
}
}
if("BODYPART2ITEM".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("BODYPART2ITEM"));
List<AiscBodyPart2ItemBean> list = (List<AiscBodyPart2ItemBean>) JSONArray.toCollection(jsonArray,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bodyPart2ItemBeen:list){
AiscBodyPart2ItemBean oldBean = getAiscBodyPartItem(bodyPart2ItemBeen);
if(oldBean==null){
AiscBodyPart2ItemRealBean realBean =new AiscBodyPart2ItemRealBean();
realBean.setItemRealId(commonSV.getSequence("SEQ_AISC_BODYPART2ITEM_REAL"));
realBean.setOldItemId(bodyPart2ItemBeen.getBodypart2Id());
realBean.setOrgId(String.valueOf(bodyPart2ItemBeen.getOrgId()));
bodyPart2ItemBeen.setBodypart2Id(commonSV.getSequence("SEQBODYPARTITEMID"));
realBean.setItemId(bodyPart2ItemBeen.getBodypart2Id());
long mastid = getItemmastId(bodyPart2ItemBeen.getItemmastId(),orgId);
bodyPart2ItemBeen.setItemmastId(mastid);
long bodyCode = getBodyCode(Long.parseLong(bodyPart2ItemBeen.getBodypartCode()),orgId);
bodyPart2ItemBeen.setBodypartCode(String.valueOf(bodyCode));
commonSV.save(bodyPart2ItemBeen);
commonSV.save(realBean);
}else{
AiscBodyPart2ItemRealBean qryBean = commonSV.getBean(" OLD_ITEM_ID = "+bodyPart2ItemBeen.getBodypart2Id()+" and org_id='"+String.valueOf(bodyPart2ItemBeen.getOrgId())+"'",null,AiscBodyPart2ItemRealBean.class);
if (qryBean!=null){
String upSql= " update aisc_bodypart2item_real t set ITEM_ID= "+oldBean.getBodypart2Id()+",CREATE_TIME =sysdate" +
" where t.OLD_ITEM_ID = "+bodyPart2ItemBeen.getBodypart2Id()+" and t.org_id= '"+String.valueOf(bodyPart2ItemBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscBodyPart2ItemRealBean realBean =new AiscBodyPart2ItemRealBean();
realBean.setItemRealId(commonSV.getSequence("SEQ_AISC_BODYPART2ITEM_REAL"));
realBean.setOldItemId(bodyPart2ItemBeen.getBodypart2Id());
realBean.setOrgId(String.valueOf(bodyPart2ItemBeen.getOrgId()));
realBean.setItemId(oldBean.getBodypart2Id());
commonSV.save(realBean);
}
}
}
}
if("ORDCAT2LOC".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("ORDCAT2LOC"));
List<AiscOrdCat2LocBean> list = (List<AiscOrdCat2LocBean>) JSONArray.toCollection(jsonArray,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean ordCat2LocBeen:list){
AiscOrdCat2LocBean oldBean = getAiscOrdcat2loc(ordCat2LocBeen);
if(oldBean==null){
AiscOrdCat2LocRealBean realBean = new AiscOrdCat2LocRealBean();
realBean.setOrdcat2locRealId(commonSV.getSequence("SEQ_AISC_ORDCAT2LOC_REAL"));
realBean.setOldOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
realBean.setOrgId(String.valueOf(ordCat2LocBeen.getOrgId()));
ordCat2LocBeen.setOrdcat2locId(commonSV.getSequence("SEQORDCAT2LOC"));
long locId = getLocId(ordCat2LocBeen.getLocId(),orgId);
ordCat2LocBeen.setLocId(locId);
long id = getRealOrdcategoryId(ordCat2LocBeen.getOrdcatId(),orgId);
ordCat2LocBeen.setOrdcatId(id);;
realBean.setOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
commonSV.save(ordCat2LocBeen);
commonSV.save(realBean);
}else{
AiscOrdCat2LocRealBean qryBean = commonSV.getBean(" old_ORDCAT2LOC_id = "+ordCat2LocBeen.getOrdcat2locId()+" and org_id='"+String.valueOf(ordCat2LocBeen.getOrgId())+"'",null,AiscOrdCat2LocRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_ORDCAT2LOC_REAL t set ORDCAT2LOC_id= "+oldBean.getOrdcat2locId()+",CREATE_TIME =sysdate" +
" where t.old_ORDCAT2LOC_id = "+ordCat2LocBeen.getOrdcat2locId()+" and t.org_id= '"+String.valueOf(ordCat2LocBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscOrdCat2LocRealBean realBean = new AiscOrdCat2LocRealBean();
realBean.setOrdcat2locRealId(commonSV.getSequence("SEQ_AISC_ORDCAT2LOC_REAL"));
realBean.setOldOrdcat2locId(ordCat2LocBeen.getOrdcat2locId());
realBean.setOrgId(String.valueOf(ordCat2LocBeen.getOrgId()));
realBean.setOrdcat2locId(oldBean.getOrdcat2locId());
commonSV.save(realBean);
}
}
}
}
if("CAREPROV".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("CAREPROV"));
List<AiscCareProvBean> list = (List<AiscCareProvBean>) JSONArray.toCollection(jsonArray,AiscCareProvBean.class);
for (AiscCareProvBean careProvBeen:list){
AiscCareProvBean oldBean = getAiscCareprov(careProvBeen);
if(oldBean==null){
AiscCareprovRealBean realBean =new AiscCareprovRealBean();
realBean.setCareprovRealId(commonSV.getSequence("SEQ_AISC_CAREPROV_REAL"));
realBean.setOldCareprovId(careProvBeen.getCareprovId());
realBean.setOrgId(String.valueOf(careProvBeen.getOrgId()));
careProvBeen.setCareprovId(commonSV.getSequence("SEQ_AISC_CAREPROV"));
realBean.setCareprovId(careProvBeen.getCareprovId());
long locId = getLocId(careProvBeen.getLocId(),orgId);
careProvBeen.setLocId(locId);
commonSV.save(careProvBeen);
commonSV.save(realBean);
}else{
AiscCareprovRealBean qryBean = commonSV.getBean(" OLD_CAREPROV_ID = "+careProvBeen.getCareprovId()+" and org_id='"+String.valueOf(careProvBeen.getOrgId())+"'",null,AiscCareprovRealBean.class);
if (qryBean!=null){
String upSql= " update AISC_CAREPROV_REAL t set CAREPROV_ID= "+oldBean.getCareprovId()+",CREATE_TIME =sysdate" +
" where t.OLD_CAREPROV_ID = "+careProvBeen.getCareprovId()+" and t.org_id= '"+String.valueOf(careProvBeen.getOrgId())+"'" ;
commonSV.execute(upSql,null);
}else{
AiscCareprovRealBean realBean =new AiscCareprovRealBean();
realBean.setCareprovRealId(commonSV.getSequence("SEQ_AISC_CAREPROV_REAL"));
realBean.setOldCareprovId(careProvBeen.getCareprovId());
realBean.setOrgId(String.valueOf(careProvBeen.getOrgId()));
realBean.setCareprovId(oldBean.getCareprovId());
commonSV.save(realBean);
}
}
}
}
}
translateBatch(orgId);
// }catch(Exception e){
// result = "faild";
// e.printStackTrace();
// }
return result;
}
public String sendBusiData(String body,String orgId) throws Exception{
Date currentTime = SysdateManager.getSysDate();
JSONObject jsonbody = JSONObject.fromObject(body);
String result = "success";
for (BusiDataEnum c : BusiDataEnum.values()) {
if("PATIENTINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("PATIENTINFO"));
List<AisPatientInfoData> list = (List<AisPatientInfoData>) JSONArray.toCollection(jsonArray,AisPatientInfoData.class);
//首先根据身份证号判断
for(AisPatientInfoData model:list){
AisPatientInfoBean[] patientBean = null;
if(isNotBlank(model.getPatientIdnumber())){
patientBean = getAisPatientBean(model.getPatientIdnumber());
}
//查询ais_pixinfo表中是否有记录
AisPixInfoBean[] pixBean = getAisPixInfoBean(model.getPatientId(),orgId);
//该情况只有人为修改数据的时候才会出现
if(pixBean!=null&&patientBean==null){
//pixBean 更新
//patient 插入
}else if(pixBean==null&&patientBean==null){
//patient 插入&pixBean 插入
insertPatientBean(orgId,model);
}else if(pixBean==null&&patientBean!=null){
//查询pacs已有病人信息
if(patientBean!=null&&patientBean.length>0){
for(int hh=0;hh<patientBean.length;hh++){
//插入pixBean
if(isFlag(patientBean[0].getPatientGlobalid(),orgId)){
insertPixBean(patientBean[hh].getPatientGlobalid(),orgId,model);
}
//更新中心pacs已有病人信息
updatePatient(patientBean[hh].getPatientGlobalid(),model);
}
}
}else{
//若pix和中心patient都有信息,则只更新病人信息
if(pixBean!=null&&pixBean.length>0){
for(int hh=0;hh<pixBean.length;hh++){
//更新中心pacs已有病人信息
updatePatient(pixBean[hh].getPatientGlobalid(),model);
}
}
}
}
}
if("STUDYINFO".equals(c.getInterfaceName())){
JsonConfig jsonConfig = new JsonConfig();
String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYINFO"),jsonConfig);
List<AisStudyInfoBean> list = (List<AisStudyInfoBean>) JSONArray.toCollection(jsonArray,AisStudyInfoBean.class);
for (AisStudyInfoBean bean : list){
long studyinfoId= Long.parseLong(orgId+bean.getStudyinfoId());
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(studyinfoId,bean.getOrgId());
if(oldBean==null){
AisStudyinfoRealBean realBean =new AisStudyinfoRealBean();
realBean.setStudyinfoRealId(commonSV.getSequence("SEQSTUDYTEMPID"));
realBean.setOldStudyinfoId(studyinfoId);
realBean.setOrgId(String.valueOf(bean.getOrgId()));
bean.setStudyinfoId(Long.parseLong(orgId+commonSV.getSequence("SEQSTUDYINFOID")));
realBean.setStudyinfoId(bean.getStudyinfoId());
//转义
translateStudyinfo(bean);
//插入关系表及的登记记录
commonSV.save(bean);
commonSV.save(realBean);
}else{
//修改登记信息
AisStudyInfoBean oldstudyInfoBean = new AisStudyInfoBean();
oldstudyInfoBean.setStudyinfoId(oldBean.getStudyinfoId());
oldstudyInfoBean.setStsToOld();
bean.setStudyinfoId(oldBean.getStudyinfoId());
DataContainerFactory.copyNoClearData(bean, oldstudyInfoBean);
translateStudyinfo(oldstudyInfoBean);
AisStudyInfoEngine.save(oldstudyInfoBean);
}
}
}
if("STUDYITEMINFO".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYITEMINFO"));
List<AisStudyItemInfoBean> list = (List<AisStudyItemInfoBean>) JSONArray.toCollection(jsonArray,AisStudyItemInfoBean.class);
for (AisStudyItemInfoBean bean : list){
AisStudyItemInfoBean studyitemBeen = new AisStudyItemInfoBean();
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
//studyinfoId转义
if(oldBean!=null){
deleteStudyIteminfo(oldBean.getStudyinfoId(),orgId);
studyitemBeen.setStudyinfoId(oldBean.getStudyinfoId());
}
//检查项目code转义
AiscItemmastRealBean studyitem = getStudyItemRealBean(Long.parseLong(bean.getStudyitemCode()),orgId);
if(studyitem!=null){
studyitemBeen.setStudyitemCode(String.valueOf(studyitem.getItemmastId()));
}
studyitemBeen.setStudyitemId(commonSV.getSequence("SEQSTUDYITEMID"));
studyitemBeen.setStudyitemHisid(bean.getStudyitemHisid());
studyitemBeen.setStudyitemCode(bean.getStudyitemCode());
studyitemBeen.setStudyitemDesc(bean.getStudyitemDesc());
studyitemBeen.setStudyitemEndesc(bean.getStudyitemEndesc());
studyitemBeen.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
studyitemBeen.setStudyitemPrice(bean.getStudyitemPrice());
studyitemBeen.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
studyitemBeen.setStudyitemStatus(bean.getStudyitemStatus());
studyitemBeen.setStudyitemItemno(bean.getStudyitemItemno());
if(bean.getStudyitemBodypart()!=null&&!"".equals(bean.getStudyitemBodypart())){
String arr[] = bean.getStudyitemBodypart().split(",");
String parts = "";
boolean task = false;
for(int i=0;i<arr.length;i++){
AiscBodypartRealBean partBean = getBodypartRealBean(Long.parseLong(arr[i]),orgId);
if(partBean!=null){
parts+=partBean.getBodypartCode()+",";
}else{
parts = bean.getStudyitemBodypart();
task = true;
}
}
if(task){
studyitemBeen.setStudyitemBodypart(parts);
}else{
studyitemBeen.setStudyitemBodypart(parts.substring(0,parts.length()-1));
}
}
commonSV.save(studyitemBeen);
}
}
if("STUDYREPORT".equals(c.getInterfaceName())){
JSONArray jsonArray = JSONArray.fromObject(jsonbody.getString("STUDYREPORT"));
List<AisStudyReportBean> list = (List<AisStudyReportBean>) JSONArray.toCollection(jsonArray,AisStudyReportBean.class);
for (AisStudyReportBean bean : list){
AisStudyReportBean studyreport = new AisStudyReportBean();
//studyinfoId转义
AisStudyinfoRealBean realbean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
if(realbean!=null){
deleteStudyReport(realbean.getStudyinfoId(),orgId);
studyreport.setStudyinfoId(realbean.getStudyinfoId());
}else{
studyreport.setStudyinfoId(Long.parseLong(orgId+bean.getStudyinfoId()));
}
studyreport.setReportId(commonSV.getSequence("SEQREPORTID"));
studyreport.setReportDatetime(bean.getReportDatetime());
if (isNotBlank(bean.getReportDoctorid())) {
AiscCareprovRealBean reportdoc = getCareBean(Long.parseLong(bean.getReportDoctorid()),orgId);
if(reportdoc!=null){
studyreport.setReportDoctorid(String.valueOf(reportdoc.getCareprovId()));
}else{
studyreport.setReportDoctorid(bean.getReportDoctorid());
}
}
studyreport.setReportVerifydatetime(bean.getReportVerifydatetime());
if (isNotBlank(bean.getReportVerifydoctorid())) {
AiscCareprovRealBean verifydoc = getCareBean(Long.parseLong(bean.getReportVerifydoctorid()),orgId);
if(verifydoc!=null){
studyreport.setReportVerifydoctorid(String.valueOf(verifydoc.getCareprovId()));
}else{
studyreport.setReportVerifydoctorid(bean.getReportVerifydoctorid());
}
}
studyreport.setReportFinaldatetime(bean.getReportFinaldatetime());
if (isNotBlank(bean.getReportFinaldoctorid())) {
AiscCareprovRealBean finaldoc = getCareBean(Long.parseLong(bean.getReportFinaldoctorid()),orgId);
if(finaldoc!=null){
studyreport.setReportFinaldoctorid(String.valueOf(finaldoc.getCareprovId()));
}else{
studyreport.setReportFinaldoctorid(bean.getReportFinaldoctorid());
}
}
if (isNotBlank(bean.getReportRecord())) {
AiscCareprovRealBean writedoc = getCareBean(Long.parseLong(bean.getReportRecord()),orgId);
if(writedoc!=null){
studyreport.setReportRecord(String.valueOf(writedoc.getCareprovId()));
}else{
studyreport.setReportRecord(bean.getReportRecord());
}
}
studyreport.setReportIscompleted(Integer.parseInt(String.valueOf(bean.getReportIscompleted())));
studyreport.setReportIspositive(Integer.parseInt(String.valueOf(bean.getReportIspositive())));
studyreport.setReportIsprinted(Integer.parseInt(String.valueOf(bean.getReportIsprinted())));
studyreport.setReportIssent(Integer.parseInt(String.valueOf(bean.getReportIssent())));
studyreport.setReportPrintcareprovid(bean.getReportPrintcareprovid());
studyreport.setReportPrintdatetime(bean.getReportPrintdatetime());
studyreport.setReportUncompletedreason(bean.getReportUncompletedreason());
studyreport.setReportExam(bean.getReportExam());
studyreport.setReportExammethod(bean.getReportExammethod());
studyreport.setReportResult(bean.getReportResult());
studyreport.setReportIcd10(bean.getReportIcd10());
studyreport.setReportAcrcode(bean.getReportAcrcode());
studyreport.setReportRemark(bean.getReportRemark());
studyreport.setReportLock(Integer.parseInt(String.valueOf(bean.getReportLock())));
commonSV.save(studyreport);
}
}
}
return result;
}
public void deleteStudyReport(long studyinfoId,String orgId){
try {
String delSql2 = "delete from ais_studyreport where report_id=(select "
+ " report_id from ais_studyreport a,ais_studyinfo b where a.studyinfo_id=b.studyinfo_id "
+ " and b.org_id=:ORG_ID and a.studyinfo_id=:studyinfoId and b.studystatus_code = 'VERIFY')";
Map delMap2 = new HashMap();
delMap2.put("ORG_ID",orgId);
delMap2.put("studyinfoId",studyinfoId);
commonSV.execute(delSql2,delMap2);
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteStudyIteminfo(long studyinfoId,String orgId){
try {
String delSql2 = "delete from ais_studyiteminfo where studyitem_id=(select "
+ " studyitem_id from ais_studyiteminfo a,ais_studyinfo b where a.studyinfo_id=b.studyinfo_id "
+ " and b.org_id=:ORG_ID and a.studyinfo_id=:studyinfoId and b.studystatus_code='VERIFY') ";
Map delMap2 = new HashMap();
delMap2.put("ORG_ID",orgId);
delMap2.put("studyinfoId",studyinfoId);
commonSV.execute(delSql2,delMap2);
}catch (Exception e){
e.printStackTrace();
}
}
private AisStudyInfoBean translateStudyinfo(AisStudyInfoBean bean) throws Exception{
AiscLocRealBean realbean = getLocRealBean(bean.getLocId(),bean.getOrgId());
if(realbean!=null){
bean.setLocId(realbean.getLocId());
}
//申请科室转义
if (bean.getStudyApplocid()!=-1&&isNotBlank(String.valueOf(bean.getStudyApplocid()))) {
AiscLocRealBean applocbean = getLocRealBean(bean.getStudyApplocid(),bean.getOrgId());
if(applocbean!=null){
bean.setStudyApplocid(applocbean.getLocId());
}
}
//房间转义
if (bean.getRoomId()!=-1&&isNotBlank(String.valueOf(bean.getRoomId()))) {
AiscRoomRealBean roomreal = getRoomReal(bean.getRoomId(),bean.getOrgId());
if(roomreal!=null){
bean.setRoomId(roomreal.getRoomId());
}
}
//申请医生转义
if (isNotBlank(bean.getStudyAppdoc())) {
AiscCareprovRealBean carebean = getCareBean(Long.parseLong(bean.getStudyAppdoc()),bean.getOrgId());
if(carebean!=null){
bean.setStudyAppdoc(String.valueOf(carebean.getCareprovId()));
}
}
//设备转义
if (bean.getEquipmentId()!=-1&&isNotBlank(String.valueOf(bean.getEquipmentId()))) {
AiscEquipmentRealBean equipreal = getEquipmentBean(bean.getEquipmentId(),bean.getOrgId());
if(equipreal!=null){
bean.setEquipmentId(equipreal.getEquipmentId());
}
}
//操作员转义
if (isNotBlank(bean.getStudyOperationid())) {
// AiscCareprovRealBean operbean = getCareBean(Long.parseLong(bean.getStudyOperationid()),bean.getOrgId());
// bean.setStudyOperationid(String.valueOf(operbean.get));
}
//检查医生转义
if (isNotBlank(bean.getStudyDoctorid())) {
AiscCareprovRealBean docbean = getCareBean(Long.parseLong(bean.getStudyDoctorid()),bean.getOrgId());
if(docbean!=null){
bean.setStudyDoctorid(String.valueOf(docbean.getCareprovId()));
}
}
//辅助技师转义
if (isNotBlank(bean.getAidDoctorid())) {
AiscCareprovRealBean jsbean = getCareBean(Long.parseLong(bean.getAidDoctorid()),bean.getOrgId());
if(jsbean!=null){
bean.setStudyDoctorid(String.valueOf(jsbean.getCareprovId()));
}
}
//病人ID转义
AisPatientRealBean paBean = getRealGlobalId(bean.getPatientGlobalid(),bean.getOrgId());
if(paBean!=null){
bean.setPatientGlobalid(paBean.getGlobalId());
}
return bean;
}
private Boolean translateBatch(String orgId){
Boolean flag =false ;
try {
//---------科室关系表-----------------
AiscLocRealBean[] realBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscLocRealBean.class);
for (AiscLocRealBean realBean:realBeen){
//设备信息中科室转义
AiscEquipmentBean[] equipmentBeens = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscEquipmentBean.class);
for (AiscEquipmentBean bean:equipmentBeens) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//房间信息中科室转义
AiscRoomBean[] roomBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscRoomBean.class);
for (AiscRoomBean bean:roomBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//检查大类与科室关联中科室ID转义
AiscOrdCat2LocBean[] ordCat2LocBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean bean:ordCat2LocBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//医护人员维护中科室ID转义
AiscCareProvBean[] careProvBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscCareProvBean.class);
for (AiscCareProvBean bean:careProvBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
//操作员与登录科室登录中科室ID转义
AiscLoginLocBean[] loginLocBeen = commonSV.getBeans(" LOC_ID = "+realBean.getOldLocId()+" and ORG_ID = "+orgId,null,AiscLoginLocBean.class);
for (AiscLoginLocBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setLocId(realBean.getLocId());
commonSV.save(bean);
}
}
//---------服务器关系表-----------------
AiscSeverinfoRealBean[] severinfoRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscSeverinfoRealBean.class);
for (AiscSeverinfoRealBean realBean :severinfoRealBeen){
//科室表中服务器ID转义
AiscLocBean[] loginLocBeen = commonSV.getBeans(" SERVER_ID = "+realBean.getOldServerId(),null,AiscLocBean.class);
for (AiscLocBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setServerId(realBean.getServerId());
commonSV.save(bean);
}
}
//---------房间关系表-----------------
AiscRoomRealBean[] roomRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscRoomRealBean.class);
for (AiscRoomRealBean realBean :roomRealBeen){
//设备信息中房间转义
AiscEquipmentBean[] equipmentBeen = commonSV.getBeans(" ROOM_ID = "+realBean.getOldRoomId()+" and ORG_ID = "+orgId,null,AiscEquipmentBean.class);
for (AiscEquipmentBean bean:equipmentBeen) {
bean.setStsToOld();
bean.setRoomId(realBean.getRoomId());
commonSV.save(bean);
}
}
//---------检查项目关系表-----------------
AiscItemmastRealBean[] itemMastBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscItemmastRealBean.class);
for (AiscItemmastRealBean realBean :itemMastBeen){
//检查项目与部位关系中itemmast_id转义
AiscBodyPart2ItemBean[] bodypart2itemBeen = commonSV.getBeans(" ITEMMAST_ID = "+realBean.getOldItemmastId()+" and ORG_ID = "+orgId,null,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bean:bodypart2itemBeen) {
bean.setStsToOld();
bean.setItemmastId(realBean.getItemmastId());
commonSV.save(bean);
}
}
//---------检查部位关系表-----------------
AiscBodypartRealBean[] bodyPartBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscBodypartRealBean.class);
for (AiscBodypartRealBean realBean :bodyPartBeen){
//检查项目与部位关系中bodypart_code转义
AiscBodyPart2ItemBean[] loginLocBeen = commonSV.getBeans(" BODYPART_CODE = "+realBean.getOldBodypartCode()+" and ORG_ID = "+orgId,null,AiscBodyPart2ItemBean.class);
for (AiscBodyPart2ItemBean bean:loginLocBeen) {
bean.setStsToOld();
bean.setBodypartCode(String.valueOf(realBean.getBodypartCode()));
commonSV.save(bean);
}
}
//---------检查大类关系表-----------------
AiscOrdcategoryRealBean[] ordcategoryRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscOrdcategoryRealBean.class);
for (AiscOrdcategoryRealBean realBean :ordcategoryRealBeen){
//检查大类与科室关联中检查大类转义
AiscOrdCat2LocBean[] ordCat2LocBeen = commonSV.getBeans(" ORDCAT_ID = "+realBean.getOldOrdcategoryId(),null,AiscOrdCat2LocBean.class);
for (AiscOrdCat2LocBean bean:ordCat2LocBeen) {
bean.setStsToOld();
bean.setOrdcatId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
//检查子类中检查大类转义
AiscOrdSubCategoryBean[] ordSubCategoryBeen = commonSV.getBeans(" ORDCATEGORY_ID = "+realBean.getOldOrdcategoryId(),null,AiscOrdSubCategoryBean.class);
for (AiscOrdSubCategoryBean bean:ordSubCategoryBeen) {
bean.setStsToOld();
bean.setOrdcategoryId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
//检查项目中检查大类转义
AiscItemMastBean[] itemmstBeen = commonSV.getBeans(" ORDCATEGORY_ID = "+realBean.getOldOrdcategoryId()+" and ORG_ID = "+orgId,null,AiscItemMastBean.class);
for (AiscItemMastBean bean:itemmstBeen) {
bean.setStsToOld();
bean.setOrdcategoryId(realBean.getOrdcategoryId());
commonSV.save(bean);
}
}
//---------检查子类关系表-----------------
AiscOrdsubcategoryRealBean[] ordsubcateRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscOrdsubcategoryRealBean.class);
for (AiscOrdsubcategoryRealBean realBean :ordsubcateRealBeen){
//设备中检查子类转义
AiscEquipmentBean[] equipBeen = commonSV.getBeans(" ordsubcategory_id = "+realBean.getOldSubcateId(),null,AiscEquipmentBean.class);
for(AiscEquipmentBean bean:equipBeen){
bean.setStsToOld();
bean.setOrdsubcategoryId(realBean.getSubcateId());
commonSV.save(bean);
}
}
//---------医护人员关系表-----------------
AiscCareprovRealBean[] careprovRealBeen = commonSV.getBeans(" ORG_ID = "+orgId,null,AiscCareprovRealBean.class);
for (AiscCareprovRealBean realBean :careprovRealBeen){
//操作员与医护人员关联中医护人员ID转义
AiscUser2CareProvBean[] user2CareProvBeen = commonSV.getBeans(" CAREPROV_ID = "+realBean.getOldCareprovId(),null,AiscUser2CareProvBean.class);
for (AiscUser2CareProvBean bean:user2CareProvBeen) {
bean.setStsToOld();
bean.setCareprovId(realBean.getCareprovId());
commonSV.save(bean);
}
}
} catch (Exception e) {
e.printStackTrace();
return flag ;
}
return flag ;
}
/**
* 写入接口日志表
* @param bean
* @return
* @throws Exception
*/
public void writeServiceLog(AisServiceLogBean bean) throws Exception{
long id =ServiceUtil.getSequence("SEQ_AIS_SERVICE_LOG");
bean.setServiceId(id);
AisServiceLogEngine.save(bean);
}
public String upPatientInfo(AisPatientInfoData patient,String orgId) throws Exception{
AisPatientInfoBean[] patientBean = null;
if(isNotBlank(patient.getPatientIdnumber())){
patientBean = getAisPatientBean(patient.getPatientIdnumber());
}
//查询ais_pixinfo表中是否有记录
AisPixInfoBean[] pixBean = getAisPixInfoBean(patient.getPatientId(),orgId);
//该情况只有人为修改数据的时候才会出现
if(pixBean!=null&&patientBean==null){
//pixBean 更新
return String.valueOf(pixBean[0].getPatientGlobalid());
//patient 插入
}else if(pixBean==null&&patientBean==null){
//patient 插入&pixBean 插入
return insertPatientBean(orgId,patient);
}else if(pixBean==null&&patientBean!=null){
//查询pacs已有病人信息
if(patientBean!=null&&patientBean.length>0){
//插入pixBean
if(isFlag(patientBean[0].getPatientGlobalid(),orgId)){
insertPixBean(patientBean[0].getPatientGlobalid(),orgId,patient);
}
//更新中心pacs已有病人信息
updatePatient(patientBean[0].getPatientGlobalid(),patient);
return String.valueOf(patientBean[0].getPatientGlobalid());
}
}else{
//若pix和中心patient都有信息,则只更新病人信息
if(pixBean!=null&&pixBean.length>0){
//更新中心pacs已有病人信息
updatePatient(pixBean[0].getPatientGlobalid(),patient);
return String.valueOf(pixBean[0].getPatientGlobalid());
}
}
return "";
}
public String upStudyInfo(AisStudyInfoBean bean,String orgId) throws Exception{
long studyinfoId= Long.parseLong(orgId+bean.getStudyinfoId());
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(studyinfoId,bean.getOrgId());
if(oldBean==null){
long id = Long.parseLong(orgId+commonSV.getSequence("SEQSTUDYINFOID"));
AisStudyinfoRealBean realBean =new AisStudyinfoRealBean();
realBean.setStudyinfoRealId(commonSV.getSequence("SEQSTUDYTEMPID"));
realBean.setOldStudyinfoId(studyinfoId);
realBean.setOrgId(String.valueOf(bean.getOrgId()));
bean.setStudyinfoId(id);
realBean.setStudyinfoId(id);
//转义
translateStudyinfo(bean);
//插入关系表及的登记记录
commonSV.save(bean);
commonSV.save(realBean);
return String.valueOf(id);
}else{
//修改登记信息
AisStudyInfoBean oldstudyInfoBean = new AisStudyInfoBean();
oldstudyInfoBean.setStudyinfoId(oldBean.getStudyinfoId());
oldstudyInfoBean.setStsToOld();
bean.setStudyinfoId(oldBean.getStudyinfoId());
DataContainerFactory.copyNoClearData(bean, oldstudyInfoBean);
translateStudyinfo(oldstudyInfoBean);
AisStudyInfoEngine.save(oldstudyInfoBean);
return String.valueOf(oldstudyInfoBean.getStudyinfoId());
}
}
public void upStudyItemInfo(AisStudyItemInfoBean bean,String orgId) throws Exception{
AisStudyItemInfoBean studyitemBeen = new AisStudyItemInfoBean();
AisStudyinfoRealBean oldBean = getStudyinfoRealBean(Long.parseLong(orgId+bean.getStudyinfoId()),orgId);
//studyinfoId转义
if(oldBean!=null){
deleteStudyIteminfo(oldBean.getStudyinfoId(),orgId);
studyitemBeen.setStudyinfoId(oldBean.getStudyinfoId());
}
//检查项目code转义
AiscItemmastRealBean studyitem = getStudyItemRealBean(Long.parseLong(bean.getStudyitemCode()),orgId);
if(studyitem!=null){
studyitemBeen.setStudyitemCode(String.valueOf(studyitem.getItemmastId()));
}
studyitemBeen.setStudyitemId(commonSV.getSequence("SEQSTUDYITEMID"));
studyitemBeen.setStudyitemHisid(bean.getStudyitemHisid());
studyitemBeen.setStudyitemCode(bean.getStudyitemCode());
studyitemBeen.setStudyitemDesc(bean.getStudyitemDesc());
studyitemBeen.setStudyitemEndesc(bean.getStudyitemEndesc());
studyitemBeen.setStudyitemBodyinfo(bean.getStudyitemBodyinfo());
studyitemBeen.setStudyitemPrice(bean.getStudyitemPrice());
studyitemBeen.setStudyitemNumber(Integer.parseInt(String.valueOf(bean.getStudyitemNumber())));
studyitemBeen.setStudyitemStatus(bean.getStudyitemStatus());
studyitemBeen.setStudyitemItemno(bean.getStudyitemItemno());
if(bean.getStudyitemBodypart()!=null&&!"".equals(bean.getStudyitemBodypart())){
String arr[] = bean.getStudyitemBodypart().split(",");
String parts = "";
boolean task = false;
for(int i=0;i<arr.length;i++){
AiscBodypartRealBean partBean = getBodypartRealBean(Long.parseLong(arr[i]),orgId);
if(partBean!=null){
parts+=partBean.getBodypartCode()+",";
}else{
parts = bean.getStudyitemBodypart();
task = true;
}
}
if(task){
studyitemBeen.setStudyitemBodypart(parts);
}else{
studyitemBeen.setStudyitemBodypart(parts.substring(0,parts.length()-1));
}
}
commonSV.save(studyitemBeen);
}
public AiscLocBean getHzLocInfo(AiscLocBean bean) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
condition.append(" and loc_code='"+bean.getLocCode()+"'");
condition.append(" and org_id = '"+bean.getOrgId()+"' ");
condition.append(" and loc_type = 'C' ");
AiscLocBean[] oldBean = AiscLocEngine.getBeans(condition.toString(), null);
if(oldBean!=null&&oldBean.length>0){
return oldBean[0];
}else{
return null;
}
}
public String upHzloc(String studyinfoId,String orgId,String conlocId,String conorgId,String locId,AiscLocBean aiscloc) throws Exception{
AiscLocBean oldBean = getHzLocInfo(aiscloc);
long newlocId = commonSV.getSequence("SEQLOCID");
if(oldBean==null){
//插入新会诊科室及关系对应
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(aiscloc.getOrgId());
realBean.setOldLocId(aiscloc.getLocId());
aiscloc.setLocId(newlocId);
long serverId = getServerId(aiscloc.getServerId());
aiscloc.setServerId(serverId);
realBean.setLocId(aiscloc.getLocId());
commonSV.save(aiscloc);
commonSV.save(realBean);
}else{
AiscLocRealBean qryBean = commonSV.getBean(" OLD_LOC_ID = "+conlocId+" and org_id='"+oldBean.getOrgId()+"'",null,AiscLocRealBean.class);
if (qryBean==null){
AiscLocRealBean realBean = new AiscLocRealBean();
realBean.setLocRealId(commonSV.getSequence("SEQ_AISC_LOC_REAL"));
realBean.setOrgId(oldBean.getOrgId());
realBean.setOldLocId(Long.parseLong(conlocId));
realBean.setLocId(oldBean.getLocId());
commonSV.save(realBean);
}
}
//查询中心申请科室ID
AiscLocRealBean sqBean = commonSV.getBean(" OLD_LOC_ID = "+locId+" and org_id='"+orgId+"'",null,AiscLocRealBean.class);
//查询中心会诊科室ID
AiscLocRealBean hzBean = commonSV.getBean(" OLD_LOC_ID = "+conlocId+" and org_id='"+conorgId+"'",null,AiscLocRealBean.class);
AiscConorganizationBean conorgBean = commonSV.getBean(" conloc_id='"+hzBean.getLocId()+"' and org_id='"+sqBean.getOrgId()+"' and loc_id="+sqBean.getLocId()+" and conorg_id='"+hzBean.getOrgId()+"'",null,AiscConorganizationBean.class);
if(conorgBean==null){
//插入登录科室与会诊科室关联
AiscConorganizationBean newconorg = new AiscConorganizationBean();
newconorg.setConorganizatId(ServiceUtil.getSequence("SEQ_Conorganization"));
newconorg.setConlocId(String.valueOf(hzBean.getLocId()));
newconorg.setConorgId(hzBean.getOrgId());
newconorg.setOrgId(sqBean.getOrgId());
newconorg.setLocId(sqBean.getLocId());
commonSV.save(newconorg);
updateConLoc(studyinfoId,hzBean.getLocId());
}else{
updateConLoc(studyinfoId,Long.parseLong(conorgBean.getConlocId()));
}
return "0";
}
public void updateConLoc(String studyinfoId,long locId) throws Exception{
AisStudyInfoBean bean = AisStudyInfoEngine.getBean(Long.parseLong(studyinfoId));
bean.setStsToOld();
bean.setStudyConsultloc(locId);
bean.setStudystatusCode("APPConsult");
AisStudyInfoEngine.save(bean);
}
public String saveFilePDFUrl(AisFilesInfoModel filemodel) throws Exception{
AisFilesInfoBean fileBean = new AisFilesInfoBean();
long fileId = ServiceUtil.getSequence("SEQFILEID");
fileBean.setFileId(fileId);
fileBean.setStudyinfoId(filemodel.getStudyinfoId());
fileBean.setFileType(filemodel.getFileType());
fileBean.setFilePath(filemodel.getFilePath());
fileBean.setMiId(-1);
AisFilesInfoEngine.save(fileBean);
return "0";
}
public boolean isFlag(long id,String orgId) throws Exception{
StringBuffer condition = new StringBuffer();
condition.append(" ORG_ID = '" + orgId+"' and patient_globalid="+id );
AisPixInfoBean[] pixBean = AisPixInfoEngine.getBeans(condition.toString(), null);
if(pixBean!=null&&pixBean.length > 0){
return true;
}else{
return false;
}
}
public AisStudyInfoBean getStudyInfoByAccnumber(String studyAccnumber) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(studyAccnumber)) {
condition.append(" AND study_accnumber = '" + studyAccnumber + "'");
}
AisStudyInfoBean[] studyBean = AisStudyInfoEngine.getBeans(condition.toString(), null);
if (studyBean.length > 0) {
return studyBean[0];
} else {
return null;
}
}
public Map reportBack(String hzOrgId,String studyAccnumber,String hzReportExam,String hzReportResult,String ipport,String reportDoc,String verifyDoc,String studyTime) throws Exception{
Statement stmt = null;
ResultSet rs = null;
Map result = new HashMap();
String code = "0";
String message = "回传报告成功";
Timestamp dateTime = new Timestamp(new Date().getTime());
AisStudyInfoBean sbean = getStudyInfoByAccnumber(studyAccnumber);
sbean.setStudystatusCode("Consulted");
sbean.setStudyHavereport(1);
AisStudyInfoEngine.save(sbean);
AisStudyReportBean reportBean = getOldReport(sbean.getStudyinfoId());
if(reportBean ==null){
reportBean = new AisStudyReportBean();
long newReportId = ServiceUtil.getSequence("SEQREPORTID");
reportBean.setReportId(newReportId);
reportBean.setReportDatetime(dateTime);
reportBean.setReportVerifydatetime(dateTime);
reportBean.setStudyinfoId(sbean.getStudyinfoId());
// reportBean.setReportDoctorid(user.getCareProvId());
// reportBean.setReportRecord(user.getCareProvId());
reportBean.setReportExam(hzReportExam);
reportBean.setReportResult(hzReportExam);
reportBean.setReportIsprinted(0);//未打印
reportBean.setReportIscompleted(1);
AisStudyReportEngine.save(reportBean);
}else{
reportBean.setStsToOld();
reportBean.setReportExam(hzReportExam);
reportBean.setReportResult(hzReportExam);
AisStudyReportEngine.save(reportBean);
}
//3.生成html文件上传服务器
//3.1首先取到设备类型ID
String template = "";
//按设备大类查模板现在不用
AiscEquipmentBean eBean = AiscEquipmentEngine.getBean(sbean.getEquipmentId());
//3.2查html模板 //模板应该取当前登录所用的组织机构及科室标识查,还是直接用检查单中的组织机构和科室查
try{
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = " SELECT A.REPORT_FORMAT, B.ORG_ID, B.LOC_ID, B.MODALITY_ID "
+ " FROM AISC_REPORTFORMAT A, AISC_REPORTFORMAT2LOC B "
+ " WHERE A.FORMAT_ID = B.FORMAT_ID ";
sql += " AND ORG_ID = " + sbean.getOrgId() + " ";
sql += " AND LOC_ID = " + sbean.getLocId()+""
+ " AND B.MODEL_TYPE = 3 ";
rs = stmt.executeQuery(sql);
if (rs.next()) {
Clob reportFormat = rs.getClob("REPORT_FORMAT");
if (reportFormat != null) {
template = reportFormat.getSubString(1, (int) reportFormat.length());
}
}
if ("".equals(template)) {
code = "-1";
message = "回传报告失败:打印模板文件不存在,请确认!";
throw new Exception("上传报告失败:打印模板文件不存在,请确认!");
}
}catch (Exception e) {
// TODO: handle exception
}
finally {
DBUtil.release(rs, stmt, null);
ServiceManager.getSession().getConnection().close();
}
//3.3组装html文件
//3.3.1获取填充数据
Map map = getTemplateFilling(String.valueOf(reportBean.getStudyinfoId()));
//剔除strike中的记录 留痕处理 -- 正则表达式
String reportExam = String.valueOf(map.get("REPORT_EXAM"));
String reportResult = String.valueOf(map.get("REPORT_RESULT"));
Pattern p = Pattern.compile("<strike>.*</strike>");
Matcher m1 = p.matcher(reportExam);
Matcher m2 = p.matcher(reportResult);
//去除删除标签
String newReportExam = m1.replaceAll("");
String newReportResult = m2.replaceAll("");
//图片内容填充
// String patientImg = "";
// if (!"".equals(imgAddrArray)) {
// String[] imgArray = imgAddrArray.split("\\|");
// String html = "<tr>";
// for (int i = 0; i < imgArray.length; i++) {
// html += "<td align='center' height='1' valign='bottom' width='33%'><img border='0' height='172' src='" + imgArray[i] + "' width='230' /><p align='center'> </p></td>";
// if (i != 0 && (i + 1) % 2 == 0) {
// html += "</tr><tr>";
// }
// }
// html += "</tr>";
// patientImg = html;
// } else {
// patientImg = "无";
// }
String id = "";
String cardId = "";
String cardNo = "";
if ("INP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "住院号";
} else if ("HP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "体检号";
cardId = "身份证号:";
cardNo = String.valueOf(map.get("PATIENT_IDNUMBER"));
} else if ("OP".equals(String.valueOf(map.get("PATIENTTYPE_CODE")))) {
id = "门诊号";
} else {
id = "住院号";
}
//内容填充
String studyReprotMsg = template.replaceAll("#ORG_NAME#", String.valueOf(map.get("ORG_NAME")))
.replaceAll("#ORG_NAME#", String.valueOf(map.get("ORG_NAME")))
.replaceAll("#TEMP#", "")
.replaceAll("#姓名#", String.valueOf(map.get("PATIENT_NAME")))
.replaceAll("#性别#", String.valueOf(map.get("PATIENT_SEX")))
.replaceAll("#年龄#", String.valueOf(map.get("PATIENT_AGE")))
.replaceAll("#检查号#", String.valueOf(map.get("STUDY_ACCNUMBER")))
.replaceAll("#仪器型号#", String.valueOf(map.get("EQUIPMENT_ID")))
.replaceAll("#来源#", String.valueOf(map.get("PATIENTTYPE")))
.replaceAll("#PATIENT_TYPEID#", id)
.replaceAll("#AUDITORFINAL_DOC#", "审核医师")
.replaceAll("#住院号#", String.valueOf(map.get("PATIENT_INPATIENTID")))
.replaceAll("#检查项目#", String.valueOf(map.get("STUDY_ITEMDESC")))
.replaceAll("#检查部位#", String.valueOf(map.get("STUDYITEM_BODYINFO")))
// .replaceAll("#图像#", String.valueOf(patientImg))
.replaceAll("#审核日期#", String.valueOf(map.get("REPORT_VERIFYDATETIME")))
.replaceAll("#终审医生#", String.valueOf(map.get("REPORT_FINALDOCTORNAME")))
.replaceAll("#终审核期#", String.valueOf(map.get("REPORT_FINALDATETIME")))
.replaceAll("#报告医生#", URLDecoder.decode(reportDoc, "UTF-8"))
.replaceAll("#报告时间#", String.valueOf(map.get("REPORT_DATETIME")))
.replaceAll("#报告日期#", String.valueOf(map.get("REPORT_DATE")))
.replaceAll("#患者ID#", String.valueOf(map.get("PATIENT_ID")))
.replaceAll("#申请科室#", String.valueOf(map.get("STUDY_APPLOCNAME")))
.replaceAll("#检查日期#", studyTime)
.replaceAll("#门诊号#", String.valueOf(map.get("PATIENT_OUTPATIENTID")))
.replaceAll("#病区#", String.valueOf(map.get("STUDY_WARDNAME")))
.replaceAll("#床号#", String.valueOf(map.get("STUDY_BEDNO")))
.replaceAll("#房间#", String.valueOf(map.get("ROOM_ID")))
.replaceAll("#CARD_ID#", cardId)
.replaceAll("#身份证号#", cardNo)
.replaceAll("#检查所见#", newReportExam)
.replaceAll("#诊断意见#", newReportResult);
studyReprotMsg = studyReprotMsg.replaceAll("#审核医生#", URLDecoder.decode(verifyDoc, "UTF-8"));
//3.3.2生成文件上传服务器-保存文件表路径
String fileAddr = "";
long miId = 0l;
// 生成html文件
String htmlHead = "<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
String htmlFoot = "</html>";
String script = "<link type='text/css' rel='stylesheet' href='"+ipport+"/aris/statics/pages/css/index/css/print.css'/><script type='text/javascript' src='"+ipport+"/aris/statics/common/js/jquery-1.11.2.js'></script><script type='text/javascript' language='javascript'>"
+ " function logout(){ "
+ " var browserName=navigator.appName; "
+ " if (browserName=='Netscape'){ "
+ " window.open('', '_self', ''); "
+ " window.close(); "
+ " } "
+ " if (browserName=='Microsoft Internet Explorer') { "
+ " window.parent.opener = 'whocares'; "
+ " window.close(); "
+ " } "
+ "} "
+ " function goBack(){ "
+ " window.location.href = '"+ipport+"/workList/init.html'; "
+ "if(!$('#menuTree',parent.document).is(':hidden')){ "
+ " parent.switchBarl(); "
+ " } "
+ " } "
+ "function print(){ "
+ " window.opener.document.getElementById('workbtnback').click();"
+ "WebBrowser.ExecWB(6, 6); "
//记录打印次数及打印状态
+ "$.ajax({ "
+ " type: 'POST', "
+ " async: true, "
+ " url: '"+ipport+"/studyReport/setReportPrintInfo.ajax?reportId=" + reportBean.getReportId() + "',"
+ " success: function (data) {setTimeout(function(){WebBrowser.execwb(45,1);},5000); "
+ " "
+ " }"
+ " });"
+ " } "
+ " </script><style media=print>.page-content{display:none;}</style><OBJECT classid='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2' height='0' id='WebBrowser' width='0'></OBJECT><div class='page-content' style='text-align:right'> "
+ "<button type='button' class='btn btn-primary' onclick='print()'>打 印</button><button type='button' class='btn btn-pink' onclick='logout()'>关 闭</button></div>";
String footBtn = "<div class='page-content' style='text-align:right'><button type='button' class='btn btn-primary' onclick='print()'>打 印</button><button type='button' class='btn btn-pink' onclick='logout()'>关 闭</button></div>";
studyReprotMsg = htmlHead + script + studyReprotMsg + footBtn + htmlFoot;
if (studyReprotMsg != null && !"".equals(studyReprotMsg)) {
Timestamp t = SysdateManager.getSysTimestamp();
String date = DateUtils.getDateyyyymm(t);
String day = getDateday(t);
String time = DateUtils.getDateddmmmiss(t);
//按设备类型标识分目录存放
String mtype = eBean.getModalityId() + "";
// 生成一个随机数
Random rand = new Random();
String part2 = "";
for (int i = 0; i < 3; i++) {
part2 += rand.nextInt(10);
}
//文件存放服务器及路径处理
//1. 保存在哪个服务器,哪个介质下,根据科室取存储服务器IP及介质信息
QryServerMediumBean serverMedium = new QryServerMediumBean();
QryServerMediumBean[] serverMediums= null;
serverMediums = getServerMedium(String.valueOf(sbean.getLocId()));
if (serverMediums.length > 0) {
for (QryServerMediumBean bean : serverMediums) {
if (bean.getMediumIsfull() == 0 || bean.getMediumIsonline() == 1) {
serverMedium = bean;
break;
}
}
} else {
code = "-2";
message = "回传报告失败:存储介质异常!";
}
if ("".equals(serverMedium.getServerIp()) || "".equals(serverMedium.getMediumPath())) {
code = "-2";
message = "回传报告失败:存储介质异常!";
}
//介质标识
miId = serverMedium.getMediumId();
//组织文件名
String fileName = date + "_" + time + "_" + part2;
//将本地文件写至fileServer服务器
String reportUpPath = AIConfigManager.getConfigItem("ReportUpPath");
File targetFile = new File(reportUpPath + fileName + ".html");
if (!copy(studyReprotMsg, targetFile, reportUpPath)) {
throw new Exception("上传报告失败:存储介质异常,写HTML文件失败!!");
}
fileAddr = fileName + ".html";
//记录文件地址到库表中 ----删除临时报告文件记录
AisReportFilesBean[] fileBeans = getfileBeans(reportBean.getReportId(), "0");
if (fileBeans != null && fileBeans.length > 0) {
for (int i = 0; i < fileBeans.length; i++) {
AisReportFilesBean realBean = AisReportFilesEngine.getBean(fileBeans[i].getReportfileId());
realBean.setStsToOld();
realBean.delete();
AisReportFilesEngine.save(realBean);
AisFilesInfoBean oldFileBean = AisFilesInfoEngine.getBean(fileBeans[i].getFileId());
oldFileBean.setStsToOld();
oldFileBean.delete();
AisFilesInfoEngine.save(oldFileBean);
}
}
AisFilesInfoBean fileBean = new AisFilesInfoBean();
long fileId = ServiceUtil.getSequence("SEQFILEID");
fileBean.setFileId(fileId);
fileBean.setStudyinfoId(reportBean.getStudyinfoId());
fileBean.setFileType("html");
fileBean.setFilePath(fileAddr);
fileBean.setMiId(miId);
AisFilesInfoEngine.save(fileBean);
AisReportFilesBean reportFileBeqn = new AisReportFilesBean();
reportFileBeqn.setReportfileId(ServiceUtil.getSequence("SEQREPORTFILEID"));
reportFileBeqn.setFileId(fileId);
reportFileBeqn.setReportId(reportBean.getReportId());
reportFileBeqn.setStatus("0");
AisReportFilesEngine.save(reportFileBeqn);
}
result.put("code", code);
result.put("message", message);
return result;
}
public AisReportFilesBean[] getfileBeans(long reportId, String status) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (reportId != 0) {
condition.append(" AND report_Id = " + reportId);
}
if (isNotBlank(status)) {
condition.append(" AND status = '" + status + "' ");
}
AisReportFilesBean[] reportFile = AisReportFilesEngine.getBeans(condition.toString(), null);
if (reportFile.length > 0) {
return reportFile;
} else {
return null;
}
}
//将模板内容copy到对应目录文件中
public static boolean copy(String src, File dest, String filePath) {
try {
FileOutputStream out = null;
try {
File fileDir = new File(filePath);
if (!fileDir.isDirectory()) {
//fileDir.mkdirs();
}
out = new FileOutputStream(dest);
out.write(src.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (out != null) {
out.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
public Map getTemplateFilling(String studyinfoId) throws Exception {
Map map = new HashMap();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = ServiceManager.getSession().getConnection().createStatement();
String sql = " SELECT B.STUDYINFO_ID, "
+ " B.ORG_ID, "
+ " B.LOC_ID, "
+ " A.patient_idnumber, "
+ " (SELECT SO.ORG_NAME FROM SYS_ORG SO WHERE SO.ORG_ID = B.ORG_ID) AS ORG_NAME, "
+ " B.STUDY_ACCNUMBER, "
+ " B.PATIENT_GLOBALID, "
+ " A.PATIENT_NAME, "
+ " DECODE(A.PATIENT_SEX, '1', '男', '2', '女', '未知') PATIENT_SEX, "
+ " B.PATIENT_AGE, "
+ " B.STUDY_WARD, "
+ " B.STUDY_BEDNO, "
+ " B.STUDY_ITEMDESC STUDY_ITEMDESC, "
+ " (SELECT WM_CONCAT(C.STUDYITEM_BODYINFO) "
+ " FROM AIS_STUDYITEMINFO C "
+ " WHERE B.STUDYINFO_ID = C.STUDYINFO_ID) STUDYITEM_BODYINFO, "
+ " B.STUDY_REMARK, "
+ " B.STUDY_CLINIC, "
+ " B.PATIENT_INPATIENTID, "
+ " B.STUDY_DOCTORID, "
+ " B.AID_DOCTORID, "
+ " B.STUDY_EXPOSURECOUNT, "
+ " B.STUDY_FILMCOUNT, "
+ " B.STUDY_HAVEREPORT, "
+ " B.STUDY_HAVEIMAGE, "
+ " TO_CHAR(B.STUDY_STARTTIME, 'YYYY-MM-DD hh24:mi:ss') STUDY_TIME, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = B.STUDY_DOCTORID) STUDY_DOCTORNAME, "
+ " B.EQUIPMENT_ID, "
+ " (SELECT SD.ITEM_NAME FROM SYS_DICTITEM SD WHERE SD.ITEM_NO = B.PATIENTTYPE_CODE AND DICT_NAME='PATIENT_TYPE') PATIENTTYPE, "
+ " B.PATIENTTYPE_CODE, "
+ " C.REPORT_EXAM, "
+ " C.REPORT_RESULT, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_DOCTORID) REPORT_DOCTORNAME, "
+ " TO_CHAR(C.REPORT_DATETIME, 'YYYY-MM-DD hh24:mi:ss') REPORT_DATETIME, "
+ " TO_CHAR(C.REPORT_DATETIME, 'YYYY-MM-DD hh24:mi:ss') REPORT_DATE, "
+ " B.STUDY_ITEMDESC, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_VERIFYDOCTORID) REPORT_VERIFYDOCTORNAME, "
+ " TO_CHAR(C.REPORT_VERIFYDATETIME, 'YYYY-MM-DD') REPORT_VERIFYDATETIME, "
+ " (SELECT CAREPROV_NAME FROM AISC_CAREPROV AC WHERE AC.CAREPROV_ID = C.REPORT_FINALDOCTORID) REPORT_FINALDOCTORNAME, "
+ " TO_CHAR(C.REPORT_FINALDATETIME, 'YYYY-MM-DD') REPORT_FINALDATETIME, "
+ " A.PATIENT_ID , "
+ " (SELECT AL.LOC_DESC FROM AISC_LOC AL WHERE AL.LOC_ID = B.STUDY_APPLOCID AND AL.ORG_ID = B.ORG_ID AND LOC_TYPE='A') STUDY_APPLOCNAME , "
+ " (SELECT AL.LOC_DESC FROM AISC_LOC AL WHERE AL.LOC_ID = B.STUDY_WARD AND AL.ORG_ID = B.ORG_ID AND LOC_TYPE='B') STUDY_WARDNAME , "
+ " B.PATIENT_OUTPATIENTID , "
+ " B.STUDY_BEDNO , "
+ " B.ROOM_ID "
+ " FROM AIS_PATIENTINFO A, "
+ " AIS_STUDYINFO B, "
+ " AIS_STUDYREPORT C "
+ " WHERE A.PATIENT_GLOBALID = B.PATIENT_GLOBALID "
+ " AND B.STUDYINFO_ID = C.STUDYINFO_ID "
+ " AND B.STUDYINFO_ID = " + studyinfoId + " ";
rs = stmt.executeQuery(sql);
if (rs.next()) {
map.put("ORG_NAME", rs.getString("ORG_NAME") == null ? "" : rs.getString("ORG_NAME"));
map.put("PATIENT_NAME", rs.getString("PATIENT_NAME") == null ? "" : rs.getString("PATIENT_NAME"));
map.put("PATIENT_SEX", rs.getString("PATIENT_SEX") == null ? "" : rs.getString("PATIENT_SEX"));
map.put("PATIENT_AGE", rs.getString("PATIENT_AGE") == null ? "" : rs.getString("PATIENT_AGE"));
map.put("STUDY_ACCNUMBER", rs.getString("STUDY_ACCNUMBER") == null ? "" : rs.getString("STUDY_ACCNUMBER"));
map.put("EQUIPMENT_ID", rs.getString("EQUIPMENT_ID") == null ? "" : rs.getString("EQUIPMENT_ID"));
map.put("PATIENTTYPE", rs.getString("PATIENTTYPE") == null ? "" : rs.getString("PATIENTTYPE"));
map.put("PATIENT_INPATIENTID", rs.getString("PATIENT_INPATIENTID") == null ? "" : rs.getString("PATIENT_INPATIENTID"));
map.put("STUDYITEM_BODYINFO", rs.getString("STUDYITEM_BODYINFO") == null ? "" : rs.getString("STUDYITEM_BODYINFO"));
map.put("STUDY_TIME", rs.getString("STUDY_TIME") == null ? "" : rs.getString("STUDY_TIME"));
map.put("STUDY_DOCTORNAME", rs.getString("STUDY_DOCTORNAME") == null ? "" : rs.getString("STUDY_DOCTORNAME"));
map.put("REPORT_DOCTORNAME", rs.getString("REPORT_DOCTORNAME") == null ? "" : rs.getString("REPORT_DOCTORNAME"));
map.put("REPORT_DATETIME", rs.getString("REPORT_DATETIME") == null ? "" : rs.getString("REPORT_DATETIME"));
map.put("REPORT_DATE", rs.getString("REPORT_DATE") == null ? "" : rs.getString("REPORT_DATE"));
map.put("STUDY_ITEMDESC", rs.getString("STUDY_ITEMDESC") == null ? "" : rs.getString("STUDY_ITEMDESC"));
map.put("REPORT_VERIFYDOCTORNAME", rs.getString("REPORT_VERIFYDOCTORNAME") == null ? "" : rs.getString("REPORT_VERIFYDOCTORNAME"));
map.put("REPORT_VERIFYDATETIME", rs.getString("REPORT_VERIFYDATETIME") == null ? "" : rs.getString("REPORT_VERIFYDATETIME"));
map.put("REPORT_FINALDOCTORNAME", rs.getString("REPORT_FINALDOCTORNAME") == null ? "" : rs.getString("REPORT_FINALDOCTORNAME"));
map.put("REPORT_FINALDATETIME", rs.getString("REPORT_FINALDATETIME") == null ? "" : rs.getString("REPORT_FINALDATETIME"));
map.put("PATIENT_ID", rs.getString("PATIENT_ID") == null ? "" : rs.getString("PATIENT_ID"));
map.put("STUDY_APPLOCNAME", rs.getString("STUDY_APPLOCNAME") == null ? "" : rs.getString("STUDY_APPLOCNAME"));
map.put("PATIENTTYPE_CODE", rs.getString("PATIENTTYPE_CODE") == null ? "" : rs.getString("PATIENTTYPE_CODE"));
map.put("STUDY_WARDNAME", rs.getString("STUDY_WARDNAME") == null ? "" : rs.getString("STUDY_WARDNAME"));
map.put("PATIENT_OUTPATIENTID", rs.getString("PATIENT_OUTPATIENTID") == null ? "" : rs.getString("PATIENT_OUTPATIENTID"));
map.put("STUDY_BEDNO", rs.getString("STUDY_BEDNO") == null ? "" : rs.getString("STUDY_BEDNO"));
map.put("ROOM_ID", rs.getString("ROOM_ID") == null ? "" : rs.getString("ROOM_ID"));
map.put("PATIENT_IDNUMBER", rs.getString("PATIENT_IDNUMBER") == null ? "" : rs.getString("PATIENT_IDNUMBER"));
Clob exam = rs.getClob("REPORT_EXAM");//检查所见
Clob result = rs.getClob("REPORT_RESULT");//诊断结果
if (exam != null) {
map.put("REPORT_EXAM", exam.getSubString(1, (int) exam.length()) == null ? "" : exam.getSubString(1, (int) exam.length()));
}
if (result != null) {
map.put("REPORT_RESULT", result.getSubString(1, (int) result.length()) == null ? "" : result.getSubString(1, (int) result.length()));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.release(rs, stmt, null);
ServiceManager.getSession().getConnection().close();
}
return map;
}
//根据科室标识,查询存储服务介质
public QryServerMediumBean[] getServerMedium(String locId) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (isNotBlank(locId)) {
condition.append(" AND LOC_ID = " + locId);
}
condition.append(" AND SERVER_ENABLED = 1"); //状态有效
condition.append(" AND MEDIUM_ENABLED = 1"); //状态有效
condition.append(" ORDER BY MEDIUM_ID ASC");
QryServerMediumBean[] serverMediums = QryServerMediumEngine.getBeans(condition.toString(), null);
return serverMediums;
}
public static String getDateday(Timestamp t) {
String str = t.toString();
str = str.replace("-", "");
String date = str.substring(6, 8);
return date;
}
public AisStudyReportBean getOldReport(long studyinfoId) throws Exception {
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (studyinfoId!=0) {
condition.append(" AND studyinfo_id = " + studyinfoId);
}
AisStudyReportBean[] reportBean = AisStudyReportEngine.getBeans(condition.toString(), null);
if (reportBean!=null&&reportBean.length > 0) {
return reportBean[0];
} else {
return null;
}
}
}
| [
"mr_yang_sen@163.com"
] | mr_yang_sen@163.com |
209b8dbe48389caa610c56ceface04f598889f30 | b586df5309b2c9e86a22f5fb19beff83dca57fc3 | /src/main/java/com/example/hike/rabbitmq/Consumer.java | 2bb3865822944c56527dfdba3828bf35bc4fe6d3 | [] | no_license | Vikuolia/HikeService | ad1afb3d9de10bb6180c542173359dca344bdc26 | 48ff0eeec361ce13f3a0172883bb871a9e53ed28 | refs/heads/master | 2023-02-04T17:29:26.098247 | 2020-12-23T00:12:00 | 2020-12-23T00:12:00 | 313,717,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 585 | java | package com.example.hike.rabbitmq;
import com.example.hike.model.Hike;
import com.example.hike.service.HikeService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static com.example.hike.rabbitmq.Config.QUEUE;
@Component
public class Consumer {
@Autowired
HikeService hikeService;
@RabbitListener(queues = QUEUE)
public void consumeMessageFromQueue(Hike hike){
System.out.println(hikeService.addHike(hike));
}
}
| [
"iv.vik.19.07@gmail.com"
] | iv.vik.19.07@gmail.com |
ff98d444a76c9ed4adc51d22e5ffd2d31ae36c78 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_8b9964737428c70f8d86878f19a66348aa0e4bd5/OptionFrameV2/2_8b9964737428c70f8d86878f19a66348aa0e4bd5_OptionFrameV2_t.java | f6d0e7075e4a390727a9bdaa95fb5bb35ac2a70e | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 25,981 | java | /* OpenLogViewer
*
* Copyright 2011
*
* This file is part of the OpenLogViewer project.
*
* OpenLogViewer software is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenLogViewer software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with any OpenLogViewer software. If not, see http://www.gnu.org/licenses/
*
* I ask that if you make any changes to this file you fork the code on github.com!
*
*/
package org.diyefi.openlogviewer.optionpanel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.*;
import org.diyefi.openlogviewer.OpenLogViewerApp;
import org.diyefi.openlogviewer.genericlog.GenericDataElement;
import org.diyefi.openlogviewer.genericlog.GenericLog;
import org.diyefi.openlogviewer.propertypanel.SingleProperty;
/**
*
* @author Bryan Harris
*/
public class OptionFrameV2 extends JFrame {
private JFrame thisRef;
private JPanel inactiveHeaders;
private ModifyGraphPane infoPanel;
private JButton addDivisionButton;
private JButton remDivisionButton;
private JLayeredPane layeredPane;
private ArrayList<JPanel> activePanelList;
private static final int COMP_HEIGHT = 20;// every thing except panels are 20 px high; default 20
private static final int COMP_WIDTH = 200; // used for buttons and such that are in; default 200
private static final int PANEL_WIDTH = 140;// panels are 120 px wide buttons and labels are also; default 120
private static final int PANEL_HEIGHT = 120;// panels are 120 px high;default 120
@SuppressWarnings("LeakingThisInConstructor")
public OptionFrameV2() {
super("Graphing Option Pane");
this.setSize(1280, 480);
this.setPreferredSize(this.getSize());
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
thisRef = this;
activePanelList = new ArrayList<JPanel>();
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(1280, 420));
JScrollPane scroll = new JScrollPane(layeredPane);
inactiveHeaders = initHeaderPanel();
layeredPane.add(inactiveHeaders);
infoPanel = new ModifyGraphPane();
this.add(infoPanel);
this.add(scroll);
addActiveHeaderPanel();
}
private JInternalFrame initInfoPanel() {
JInternalFrame ip = new JInternalFrame();
return ip;
}
private JPanel initHeaderPanel() {
JPanel ih = new JPanel();
ih.setLayout(null);
ih.setName("Drop InactiveHeaderPanel");
this.addDivisionButton = new JButton("Add Division");
addDivisionButton.setBounds(0, 0, PANEL_WIDTH, COMP_HEIGHT);
addDivisionButton.addActionListener(addDivisionListener);
ih.add(addDivisionButton);
ih.setBounds(0, 0, 1280, 180);
return ih;
}
private ActionListener addDivisionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addActiveHeaderPanel();
}
};
private ActionListener remDivisionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
remActiveHeaderPanel(e);
}
};
private ContainerListener addRemoveListener = new ContainerListener() {
@Override
public void componentAdded(ContainerEvent e) {
if (e.getChild() != null) {
if (e.getChild() instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) e.getChild()).setEnabled(true);
((ActiveHeaderLabel) e.getChild()).setSelected(true);
((ActiveHeaderLabel) e.getChild()).getGDE().setSplitNumber(
activePanelList.indexOf(
e.getChild().getParent()) + 1);
}
}
}
@Override
public void componentRemoved(ContainerEvent e) {
if (e.getChild() != null) {
if (e.getChild() instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) e.getChild()).setEnabled(false);
((ActiveHeaderLabel) e.getChild()).setSelected(false);
}
for (int i = 0; i < e.getContainer().getComponentCount(); i++) {
if (e.getContainer().getComponent(i) instanceof ActiveHeaderLabel) {
e.getContainer().getComponent(i).setLocation(0, i * COMP_HEIGHT);
}
}
}
}
};
private void addActiveHeaderPanel() {
if (activePanelList.size() < 8) {
int row = activePanelList.size() / 4;
int col = activePanelList.size() % 4;
JPanel activePanel = new JPanel();
activePanelList.add(activePanel);
if (OpenLogViewerApp.getInstance() != null) {
OpenLogViewerApp.getInstance().getLayeredGraph().setTotalSplits(activePanelList.size());
}
activePanel.setLayout(null);
activePanel.setName("Drop ActivePanel " + (activePanelList.indexOf(activePanel) + 1));
activePanel.addContainerListener(addRemoveListener);
activePanel.setBounds((col * PANEL_WIDTH), inactiveHeaders.getHeight() + PANEL_HEIGHT * row, PANEL_WIDTH, PANEL_HEIGHT);
activePanel.setBackground(Color.DARK_GRAY);
JButton removeButton = new JButton("Remove");
removeButton.setToolTipText("Click Here to remove this division and associated Graphs");
removeButton.setBounds(0, 0, PANEL_WIDTH, COMP_HEIGHT);
removeButton.addActionListener(remDivisionListener);
activePanel.add(removeButton);
layeredPane.add(activePanel);
if (activePanelList.size() == 8) {
addDivisionButton.setEnabled(false);
}
}
}
private void remActiveHeaderPanel(ActionEvent e) {
JPanel panel = (JPanel) ((JButton) e.getSource()).getParent();
activePanelList.remove(panel);
OpenLogViewerApp.getInstance().getLayeredGraph().setTotalSplits(activePanelList.size());
for (int i = 0; i < panel.getComponentCount();) {
if (panel.getComponent(i) instanceof ActiveHeaderLabel) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) panel.getComponent(i);
GCB.getInactivePanel().add(GCB);
GCB.setLocation(GCB.getInactiveLocation());
GCB.setSelected(false);
} else if (panel.getComponent(i) instanceof JButton) {
panel.remove(panel.getComponent(i));//removes the button
} else {
i++;
}
}
panel.getParent().remove(panel);
for (int i = 0; i < activePanelList.size(); i++) {
int row = i / 4;
int col = i % 4;
activePanelList.get(i).setLocation((col * PANEL_HEIGHT), inactiveHeaders.getHeight() + PANEL_WIDTH * row);
}
if (!addDivisionButton.isEnabled()) {
addDivisionButton.setEnabled(true);
}
////////////////////////////////////////////////////////////////////Move this to events eventually,
if (activePanelList.size() > 1) {
for (int i = 0; i < activePanelList.size(); i++) {
JPanel active = activePanelList.get(i);
if (active.getComponentCount() > 1) {
for (int j = 0; j < active.getComponentCount(); j++) {
if (active.getComponent(j) instanceof ActiveHeaderLabel) {
((ActiveHeaderLabel) active.getComponent(j)).getGDE().setSplitNumber(i + 1);
}
}
}
}
}
this.repaint();
}
private MouseMotionAdapter labelAdapter = new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
Component c = e.getComponent();
ActiveHeaderLabel GCB = (ActiveHeaderLabel) c;
GCB.setDragging(true);
if (c.getParent() != null && layeredPane.getMousePosition() != null && (e.getModifiers() == 16)) {// 4 == right mouse button
if (!c.getParent().contains(layeredPane.getMousePosition().x - c.getParent().getX(), layeredPane.getMousePosition().y - c.getParent().getY())) {
Component cn = c.getParent().getParent().getComponentAt(layeredPane.getMousePosition());
if (cn instanceof JPanel) {
JPanel j = (JPanel) cn;
if (j.getName().contains("Drop")) { // implement a better way to do this later
j.add(c);// components cannot share parents so it is automatically removed
c.setLocation( // reset the location to where the mouse is, otherwise first pixel when moving to the new jpanel
// will cause a location issue reflecting where the panel was in the PREVIOUS panel
layeredPane.getMousePosition().x - c.getParent().getX() - (c.getWidth() / 2),
layeredPane.getMousePosition().y - c.getParent().getY() - (c.getHeight() / 2));
}
}
} else {
c.setLocation(c.getX() + e.getX() - (c.getWidth() / 2), c.getY() + e.getY() - (c.getHeight() / 2));
}
thisRef.repaint();
}
}
};
private boolean place(ActiveHeaderLabel GCB) {
int x = 0;
int y = COMP_HEIGHT;
while (y < GCB.getParent().getHeight()) {
if (GCB.getParent().getComponentAt(x, y) == GCB.getParent() || GCB.getParent().getComponentAt(x, y) == GCB) {
GCB.setLocation(x, y);
return true;
}
y = y + COMP_HEIGHT;
}
return false;
}
public void updateFromLog(GenericLog gl) {
while (activePanelList.size() > 0) {
activePanelList.get(0).removeAll();
layeredPane.remove(activePanelList.get(0));
activePanelList.remove(activePanelList.get(0)); // only did it this way incase things are out of order at any point
}
addDivisionButton.setEnabled(true);
if (inactiveHeaders.getComponentCount() > 1) {
inactiveHeaders.removeAll();
inactiveHeaders.add(this.addDivisionButton);
}
this.addActiveHeaderPanel(); // will be based on highest number of divisions found when properties are applied
ArrayList<ActiveHeaderLabel> tmpList = new ArrayList<ActiveHeaderLabel>();
Iterator i = gl.keySet().iterator();
String head = "";
ActiveHeaderLabel toBeAdded = null;
while (i.hasNext()) {
head = (String) i.next();
GenericDataElement GDE = gl.get(head);
toBeAdded = new ActiveHeaderLabel();
toBeAdded.setName(head);
toBeAdded.setText(head);
toBeAdded.setRef(GDE);
toBeAdded.setEnabled(false);//you are unable to activate a graph in the inacivelist
toBeAdded.addMouseMotionListener(labelAdapter);
if (checkForProperties(toBeAdded, GDE)) {
toBeAdded.setBackground(GDE.getColor());
}
tmpList.add(toBeAdded);
}
Collections.sort(tmpList);
int j = 0;
int leftSide = 0;
for (int it = 0; it < tmpList.size(); it++) {
if (COMP_HEIGHT + (COMP_HEIGHT * (j + 1)) > inactiveHeaders.getHeight()) {
j = 0;
leftSide += PANEL_WIDTH;
}
tmpList.get(it).setBounds(leftSide, (COMP_HEIGHT + (COMP_HEIGHT * j)),
PANEL_WIDTH//(((COMP_HEIGHT + (head.length() * 8)) < 120) ? (32 + (head.length() * 7)) : 120)// this keeps the select boxes at a max of 120
, COMP_HEIGHT);
inactiveHeaders.add(tmpList.get(it));
j++;
}
this.repaint();
this.setDefaultCloseOperation(JFrame.ICONIFIED);
this.setVisible(true);
}
private boolean checkForProperties(ActiveHeaderLabel GCB, GenericDataElement GDE) {
for (int i = 0; i < OpenLogViewerApp.getInstance().getProperties().size(); i++) {
if (OpenLogViewerApp.getInstance().getProperties().get(i).getHeader().equals(GDE.getName())) {
GDE.setColor(OpenLogViewerApp.getInstance().getProperties().get(i).getColor());
GDE.setMaxValue(OpenLogViewerApp.getInstance().getProperties().get(i).getMax());
GDE.setMinValue(OpenLogViewerApp.getInstance().getProperties().get(i).getMin());
GDE.setSplitNumber(OpenLogViewerApp.getInstance().getProperties().get(i).getSplit());
if (OpenLogViewerApp.getInstance().getProperties().get(i).isActive()) {
//GCB.setSelected(true);
return true;
}
}
}
return false;
}
private class ModifyGraphPane extends JInternalFrame {
GenericDataElement GDE;
ActiveHeaderLabel AHL;
private JLabel minLabel;
private JLabel maxLabel;
private JTextField minField;
private JTextField maxField;
private JButton resetButton;
private JButton applyButton;
private JButton saveButton;
private JButton colorButton;
private ActionListener resetButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
GDE.reset();
minField.setText(Double.toString(GDE.getMinValue()));
maxField.setText(Double.toString(GDE.getMaxValue()));
}
}
};
private ActionListener applyButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
changeGDEValues();
}
}
};
private ActionListener saveButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GDE != null) {
changeGDEValues();
OpenLogViewerApp.getInstance().getPropertyPane().addPropertyAndSave(new SingleProperty(GDE));
}
}
};
private ActionListener colorButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(
new JFrame(),
"Choose Background Color",
colorButton.getForeground());
if (c != null) {
colorButton.setForeground(c);
}
}
};
public ModifyGraphPane() {
this.setName("InfoPanel");
minLabel = new JLabel("Min:");
maxLabel = new JLabel("Max:");
minField = new JTextField(10);
maxField = new JTextField(10);
resetButton = new JButton("Reset Min/Max");
resetButton.addActionListener(resetButtonListener);
applyButton = new JButton("Apply");
applyButton.addActionListener(applyButtonListener);
saveButton = new JButton("Save");
saveButton.addActionListener(saveButtonListener);
colorButton = new JButton("Color");
colorButton.addActionListener(colorButtonListener);
//X Y width height
minLabel.setBounds(0, 0, COMP_WIDTH/2, COMP_HEIGHT);
minField.setBounds(100, 0, COMP_WIDTH/2, COMP_HEIGHT);
maxLabel.setBounds(0, 20, COMP_WIDTH/2, COMP_HEIGHT);
maxField.setBounds(100, 20, COMP_WIDTH/2, COMP_HEIGHT);
colorButton.setBounds(0, 40, COMP_WIDTH, COMP_HEIGHT);
applyButton.setBounds(0, 60, COMP_WIDTH/2, COMP_HEIGHT);
saveButton.setBounds(100, 60, COMP_WIDTH/2, COMP_HEIGHT);
resetButton.setBounds(0, 80, COMP_WIDTH, COMP_HEIGHT);
this.setLayout(null);
///ip.add(headerLabel);
this.add(minLabel);
this.add(minField);
this.add(maxLabel);
this.add(maxField);
this.add(colorButton);
this.add(applyButton);
this.add(saveButton);
this.add(resetButton);
this.setBounds(500, 180, 210, 133);
this.setMaximizable(false);
this.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
this.setClosable(true);
}
public void setGDE(GenericDataElement gde, ActiveHeaderLabel ahl) {
this.GDE = gde;
this.AHL = ahl;
this.setTitle(GDE.getName());
minField.setText(GDE.getMinValue().toString());
maxField.setText(GDE.getMaxValue().toString());
colorButton.setForeground(GDE.getColor());
}
private void changeGDEValues() {
try {
GDE.setMaxValue(Double.parseDouble(maxField.getText()));
} catch (Exception ex) {
//TO-DO: do something with Auto field
}
try {
GDE.setMinValue(Double.parseDouble(minField.getText()));
} catch (Exception ex) {
//TO-DO: do something with Auto field
}
if (!GDE.getColor().equals(colorButton.getForeground())) {
GDE.setColor(colorButton.getForeground());
AHL.setForeground(colorButton.getForeground());
}
}
}
private class ActiveHeaderLabel extends JLabel implements Comparable {
private GenericDataElement GDE;
private Point previousLocation;
private Point inactiveLocation;
private JPanel previousPanel;
private JPanel inactivePanel;
private boolean dragging;
private boolean selected;
private MouseListener selectedListener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == 16) {
setSelected(!selected);
} else if (e.getModifiers() == 18) {
infoPanel.setGDE(GDE,(ActiveHeaderLabel)e.getSource());
if (!infoPanel.isVisible()) {
infoPanel.setVisible(true);
}
}
// System.out.println(e.getModifiers());
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) e.getSource();
GCB.setPreviousLocation(GCB.getLocation());
GCB.setPreviousPanel((JPanel) GCB.getParent());
}
@Override
public void mouseReleased(MouseEvent e) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) e.getSource();
if (GCB.isDragging()) {
if (GCB.getParent() == inactiveHeaders) { // moving back to inactive
GCB.setLocation(GCB.getInactiveLocation());
GCB.setSelected(false);
GCB.setEnabled(false);
} else { // moving to
if (!place(GCB)) {
if (GCB.getPreviousPanel() != GCB.getParent()) { // if it moved
GCB.getPreviousPanel().add(GCB);
place(GCB);
}
if (GCB.getPreviousPanel() == GCB.getInactivePanel()) {
GCB.setLocation(GCB.getInactiveLocation());
GCB.setEnabled(false);
GCB.setSelected(false);
} else {
place(GCB);
}
thisRef.repaint();
}
}
GCB.setDragging(false);
}
}
};
private ItemListener enabledListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
public ActiveHeaderLabel() {
super();
addMouseListener(selectedListener);
super.setOpaque(false);
inactivePanel = inactiveHeaders;
dragging = false;
selected = false;
super.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.white));
}
@Override
public void setBounds(int x, int y, int widht, int height) {
super.setBounds(x, y, widht, height);
if (inactiveLocation == null) {
inactiveLocation = new Point(x, y);
}
}
public void setRef(GenericDataElement GDE) {
this.GDE = GDE;
// this line is here because if the tool tip is never set no mouse events
// will ever be created for tool tips
this.setToolTipText();
}
@Override
public String getToolTipText(MouseEvent e) {
this.setToolTipText();
return getToolTipText();
}
public void setToolTipText() {
this.setToolTipText("<HTML>Min Value: <b>" + GDE.getMinValue()
+ "</b><br>Max Value: <b>" + GDE.getMaxValue()
+ "</b><br>Total Length: <b>" + GDE.size() + "</b> data points"
+ "<br>To modify Min and Max values for scaling purposes Ctrl+LeftClick</HTML>");
}
public GenericDataElement getGDE() {
return GDE;
}
public Point getPreviousLocation() {
return previousLocation;
}
public void setPreviousLocation(Point previousLocation) {
this.previousLocation = previousLocation;
}
public JPanel getPreviousPanel() {
return previousPanel;
}
public void setPreviousPanel(JPanel previousPanel) {
this.previousPanel = previousPanel;
}
public Point getInactiveLocation() {
return inactiveLocation;
}
public JPanel getInactivePanel() {
return inactivePanel;
}
public boolean isDragging() {
return dragging;
}
public void setDragging(boolean dragging) {
this.dragging = dragging;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
if (this.isEnabled()) {
this.selected = selected;
} else {
this.selected = false;
}
addRemGraph();
}
private void addRemGraph() {
if (selected) {
this.setForeground(GDE.getColor());
this.repaint();
OpenLogViewerApp.getInstance().getLayeredGraph().addGraph(this.getName());
} else {
this.setForeground(GDE.getColor().darker().darker());
if (OpenLogViewerApp.getInstance().getLayeredGraph().removeGraph(this.getName())) {
OpenLogViewerApp.getInstance().getLayeredGraph().repaint();
}
}
}
@Override
public int compareTo(Object o) {
if (o instanceof ActiveHeaderLabel) {
ActiveHeaderLabel GCB = (ActiveHeaderLabel) o;
return this.GDE.compareTo(GCB.getGDE());
} else {
return -1;
}
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
aef7e4f677bd35405ab553bdc4c20381ef23cf9b | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/10/10_075d9a966c5814e55323bcab0de14ccc53b498d7/Autoboxer/10_075d9a966c5814e55323bcab0de14ccc53b498d7_Autoboxer_t.java | d9813581942a872acce5e5659a5b01fc914d972a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 19,249 | java | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.translate;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.NodeCopier;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.ASTUtil;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.ErrorReportingASTVisitor;
import com.google.devtools.j2objc.util.NameTable;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.ConditionalExpression;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.SwitchStatement;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.WhileStatement;
import java.util.List;
/**
* Adds support for boxing and unboxing numeric primitive values.
*
* @author Tom Ball
*/
public class Autoboxer extends ErrorReportingASTVisitor {
private final AST ast;
private static final String VALUE_METHOD = "Value";
private static final String VALUEOF_METHOD = "valueOf";
public Autoboxer(AST ast) {
this.ast = ast;
}
/**
* Convert a primitive type expression into a wrapped instance. Each
* wrapper class has a static valueOf factory method, so "expr" gets
* translated to "Wrapper.valueOf(expr)".
*/
private Expression box(Expression expr) {
ITypeBinding wrapperBinding = Types.getWrapperType(Types.getTypeBinding(expr));
if (wrapperBinding != null) {
return newBoxExpression(expr, wrapperBinding);
} else {
return NodeCopier.copySubtree(ast, expr);
}
}
private Expression boxWithType(Expression expr, ITypeBinding wrapperType) {
if (Types.isBoxedPrimitive(wrapperType)) {
return newBoxExpression(expr, wrapperType);
}
return box(expr);
}
private Expression newBoxExpression(Expression expr, ITypeBinding wrapperType) {
ITypeBinding primitiveType = Types.getPrimitiveType(wrapperType);
assert primitiveType != null;
IMethodBinding wrapperMethod = BindingUtil.findDeclaredMethod(
wrapperType, VALUEOF_METHOD, primitiveType.getName());
assert wrapperMethod != null : "could not find valueOf method for " + wrapperType;
MethodInvocation invocation = ASTFactory.newMethodInvocation(
ast, wrapperMethod, ASTFactory.newSimpleName(ast, wrapperType));
ASTUtil.getArguments(invocation).add(NodeCopier.copySubtree(ast, expr));
return invocation;
}
/**
* Convert a wrapper class instance to its primitive equivalent. Each
* wrapper class has a "classValue()" method, such as intValue() or
* booleanValue(). This method therefore converts "expr" to
* "expr.classValue()".
*/
private Expression unbox(Expression expr) {
ITypeBinding binding = Types.getTypeBinding(expr);
ITypeBinding primitiveType = Types.getPrimitiveType(binding);
if (primitiveType != null) {
IMethodBinding valueMethod = BindingUtil.findDeclaredMethod(
binding, primitiveType.getName() + VALUE_METHOD);
assert valueMethod != null : "could not find value method for " + binding;
return ASTFactory.newMethodInvocation(ast, valueMethod, NodeCopier.copySubtree(ast, expr));
} else {
return NodeCopier.copySubtree(ast, expr);
}
}
@Override
public void endVisit(Assignment node) {
Expression lhs = node.getLeftHandSide();
ITypeBinding lhType = Types.getTypeBinding(lhs);
Expression rhs = node.getRightHandSide();
ITypeBinding rhType = Types.getTypeBinding(rhs);
Assignment.Operator op = node.getOperator();
if (op != Assignment.Operator.ASSIGN && !lhType.isPrimitive() &&
!lhType.equals(node.getAST().resolveWellKnownType("java.lang.String"))) {
// Not a simple assignment; need to break the <operation>-WITH_ASSIGN
// assignment apart.
node.setOperator(Assignment.Operator.ASSIGN);
node.setRightHandSide(box(newInfixExpression(lhs, rhs, op, lhType)));
} else {
if (lhType.isPrimitive() && !rhType.isPrimitive()) {
node.setRightHandSide(unbox(rhs));
} else if (!lhType.isPrimitive() && rhType.isPrimitive()) {
node.setRightHandSide(boxWithType(rhs, lhType));
}
}
}
private InfixExpression newInfixExpression(
Expression lhs, Expression rhs, Assignment.Operator op, ITypeBinding lhType) {
InfixExpression newRhs = ast.newInfixExpression();
newRhs.setLeftOperand(unbox(lhs));
newRhs.setRightOperand(unbox(rhs));
InfixExpression.Operator infixOp;
// op isn't an enum, so this can't be a switch.
if (op == Assignment.Operator.PLUS_ASSIGN) {
infixOp = InfixExpression.Operator.PLUS;
} else if (op == Assignment.Operator.MINUS_ASSIGN) {
infixOp = InfixExpression.Operator.MINUS;
} else if (op == Assignment.Operator.TIMES_ASSIGN) {
infixOp = InfixExpression.Operator.TIMES;
} else if (op == Assignment.Operator.DIVIDE_ASSIGN) {
infixOp = InfixExpression.Operator.DIVIDE;
} else if (op == Assignment.Operator.BIT_AND_ASSIGN) {
infixOp = InfixExpression.Operator.AND;
} else if (op == Assignment.Operator.BIT_OR_ASSIGN) {
infixOp = InfixExpression.Operator.OR;
} else if (op == Assignment.Operator.BIT_XOR_ASSIGN) {
infixOp = InfixExpression.Operator.XOR;
} else if (op == Assignment.Operator.REMAINDER_ASSIGN) {
infixOp = InfixExpression.Operator.REMAINDER;
} else if (op == Assignment.Operator.LEFT_SHIFT_ASSIGN) {
infixOp = InfixExpression.Operator.LEFT_SHIFT;
} else if (op == Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN) {
infixOp = InfixExpression.Operator.RIGHT_SHIFT_SIGNED;
} else if (op == Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) {
infixOp = InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED;
} else {
throw new IllegalArgumentException();
}
newRhs.setOperator(infixOp);
Types.addBinding(newRhs, Types.getPrimitiveType(lhType));
return newRhs;
}
@Override
public void endVisit(ArrayAccess node) {
Expression index = node.getIndex();
if (!Types.getTypeBinding(index).isPrimitive()) {
node.setIndex(unbox(index));
}
}
@Override
public void endVisit(ArrayInitializer node) {
ITypeBinding type = Types.getTypeBinding(node).getElementType();
List<Expression> expressions = ASTUtil.getExpressions(node);
for (int i = 0; i < expressions.size(); i++) {
Expression expr = expressions.get(i);
Expression result = boxOrUnboxExpression(expr, type);
if (expr != result) {
expressions.set(i, result);
}
}
}
@Override
public void endVisit(CastExpression node) {
Expression expr = boxOrUnboxExpression(node.getExpression(), Types.getTypeBinding(node));
if (expr != node.getExpression()) {
ASTNode parent = node.getParent();
if (parent instanceof Expression) {
// Check if this cast is an argument or the invocation's expression.
if (parent instanceof MethodInvocation) {
List<Expression> args = ASTUtil.getArguments((MethodInvocation) parent);
for (int i = 0; i < args.size(); i++) {
if (node.equals(args.get(i))) {
args.set(i, expr);
return;
}
}
}
ASTUtil.setProperty(node.getParent(), expr);
}
}
}
@Override
public void endVisit(ClassInstanceCreation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(ConditionalExpression node) {
ITypeBinding nodeType = Types.getTypeBinding(node);
Expression thenExpr = node.getThenExpression();
ITypeBinding thenType = Types.getTypeBinding(thenExpr);
Expression elseExpr = node.getElseExpression();
ITypeBinding elseType = Types.getTypeBinding(elseExpr);
if (thenType.isPrimitive() && !nodeType.isPrimitive()) {
node.setThenExpression(box(thenExpr));
} else if (!thenType.isPrimitive() && nodeType.isPrimitive()) {
node.setThenExpression(unbox(thenExpr));
}
if (elseType.isPrimitive() && !nodeType.isPrimitive()) {
node.setElseExpression(box(elseExpr));
} else if (!elseType.isPrimitive() && nodeType.isPrimitive()) {
node.setElseExpression(unbox(elseExpr));
}
}
@Override
public void endVisit(ConstructorInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(DoStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
@Override
public void endVisit(EnumConstantDeclaration node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(IfStatement node) {
Expression expr = node.getExpression();
ITypeBinding binding = Types.getTypeBinding(expr);
if (!binding.isPrimitive()) {
node.setExpression(unbox(expr));
}
}
@Override
public void endVisit(InfixExpression node) {
ITypeBinding type = Types.getTypeBinding(node);
Expression lhs = node.getLeftOperand();
ITypeBinding lhBinding = Types.getTypeBinding(lhs);
Expression rhs = node.getRightOperand();
ITypeBinding rhBinding = Types.getTypeBinding(rhs);
InfixExpression.Operator op = node.getOperator();
// Don't unbox for equality tests where both operands are boxed types.
if ((op == InfixExpression.Operator.EQUALS || op == InfixExpression.Operator.NOT_EQUALS)
&& !lhBinding.isPrimitive() && !rhBinding.isPrimitive()) {
return;
}
// Don't unbox for string concatenation.
if (op == InfixExpression.Operator.PLUS && Types.isJavaStringType(type)) {
return;
}
if (!lhBinding.isPrimitive()) {
node.setLeftOperand(unbox(lhs));
}
if (!rhBinding.isPrimitive()) {
node.setRightOperand(unbox(rhs));
}
List<Expression> extendedOperands = ASTUtil.getExtendedOperands(node);
for (int i = 0; i < extendedOperands.size(); i++) {
Expression expr = extendedOperands.get(i);
if (!Types.getTypeBinding(expr).isPrimitive()) {
extendedOperands.set(i, unbox(expr));
}
}
}
@Override
public void endVisit(MethodInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(PrefixExpression node) {
PrefixExpression.Operator op = node.getOperator();
Expression operand = node.getOperand();
if (op == PrefixExpression.Operator.INCREMENT) {
rewriteBoxedPrefixOrPostfix(node, operand, "PreIncr");
} else if (op == PrefixExpression.Operator.DECREMENT) {
rewriteBoxedPrefixOrPostfix(node, operand, "PreDecr");
} else if (!Types.getTypeBinding(operand).isPrimitive()) {
node.setOperand(unbox(operand));
}
}
@Override
public void endVisit(PostfixExpression node) {
PostfixExpression.Operator op = node.getOperator();
if (op == PostfixExpression.Operator.INCREMENT) {
rewriteBoxedPrefixOrPostfix(node, node.getOperand(), "PostIncr");
} else if (op == PostfixExpression.Operator.DECREMENT) {
rewriteBoxedPrefixOrPostfix(node, node.getOperand(), "PostDecr");
}
}
private void rewriteBoxedPrefixOrPostfix(
ASTNode node, Expression operand, String methodPrefix) {
ITypeBinding type = Types.getTypeBinding(operand);
if (!Types.isBoxedPrimitive(type)) {
return;
}
AST ast = node.getAST();
String methodName = methodPrefix + NameTable.capitalize(Types.getPrimitiveType(type).getName());
IOSMethodBinding methodBinding = IOSMethodBinding.newFunction(methodName, type, type, type);
MethodInvocation invocation = ASTFactory.newMethodInvocation(ast, methodBinding, null);
ASTUtil.getArguments(invocation).add(
ASTFactory.newAddressOf(ast, NodeCopier.copySubtree(ast, operand)));
ASTUtil.setProperty(node, invocation);
}
@Override
public void endVisit(ReturnStatement node) {
Expression expr = node.getExpression();
if (expr != null) {
ASTNode n = node.getParent();
while (!(n instanceof MethodDeclaration)) {
n = n.getParent();
}
ITypeBinding returnType = Types.getMethodBinding(n).getReturnType();
ITypeBinding exprType = Types.getTypeBinding(expr);
if (returnType.isPrimitive() && !exprType.isPrimitive()) {
node.setExpression(unbox(expr));
}
if (!returnType.isPrimitive() && exprType.isPrimitive()) {
node.setExpression(box(expr));
}
}
}
@Override
public void endVisit(SuperConstructorInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(SuperMethodInvocation node) {
convertArguments(Types.getMethodBinding(node), ASTUtil.getArguments(node));
}
@Override
public void endVisit(VariableDeclarationFragment node) {
Expression initializer = node.getInitializer();
if (initializer != null) {
ITypeBinding nodeType = Types.getTypeBinding(node);
ITypeBinding initType = Types.getTypeBinding(initializer);
if (nodeType.isPrimitive() && !initType.isPrimitive()) {
node.setInitializer(unbox(initializer));
} else if (!nodeType.isPrimitive() && initType.isPrimitive()) {
node.setInitializer(boxWithType(initializer, nodeType));
}
}
}
@Override
public void endVisit(WhileStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
@Override
public void endVisit(SwitchStatement node) {
Expression expression = node.getExpression();
ITypeBinding exprType = Types.getTypeBinding(expression);
if (!exprType.isPrimitive()) {
node.setExpression(unbox(expression));
}
}
private void convertArguments(IMethodBinding methodBinding, List<Expression> args) {
if (methodBinding instanceof IOSMethodBinding) {
return; // already converted
}
if (Types.isJavaStringType(methodBinding.getDeclaringClass()) &&
methodBinding.getName().equals("format")) {
// The String.format methods are mapped directly to NSString methods,
// but arguments referred to as objects by the format string need to
// be boxed.
if (!args.isEmpty()) {
Expression first = args.get(0);
int firstArg = 1;
ITypeBinding typeBinding = Types.getTypeBinding(first);
if (typeBinding.getQualifiedName().equals("java.util.Locale")) {
first = args.get(1);
firstArg = 2;
typeBinding = Types.getTypeBinding(first);
}
if (first instanceof StringLiteral) {
List<Boolean> formatSpecifiers =
getFormatSpecifiers(((StringLiteral) first).getLiteralValue());
for (int i = 0; i < formatSpecifiers.size(); i++) {
if (formatSpecifiers.get(i)) {
int iArg = i + firstArg;
Expression arg = args.get(iArg);
if (Types.getTypeBinding(arg).isPrimitive()) {
args.set(iArg, box(arg));
}
}
}
}
}
return;
}
ITypeBinding[] paramTypes = methodBinding.getParameterTypes();
for (int i = 0; i < args.size(); i++) {
ITypeBinding paramType;
if (methodBinding.isVarargs() && i >= paramTypes.length - 1) {
paramType = paramTypes[paramTypes.length - 1].getComponentType();
} else {
paramType = paramTypes[i];
}
Expression arg = args.get(i);
Expression replacementArg = boxOrUnboxExpression(arg, paramType);
if (replacementArg != arg) {
args.set(i, replacementArg);
}
}
}
// Returns a list of booleans indicating whether the format specifier
// refers to an object argument or not.
private List<Boolean> getFormatSpecifiers(String format) {
List<Boolean> specifiers = Lists.newArrayList();
int i = 0;
while ((i = format.indexOf('%', i)) != -1) {
if (format.charAt(++i) == '%') {
// Skip %% sequences, since they don't have associated args.
++i;
continue;
}
specifiers.add(format.charAt(i) == '@');
}
return specifiers;
}
private Expression boxOrUnboxExpression(Expression arg, ITypeBinding argType) {
ITypeBinding argBinding;
IBinding binding = Types.getBinding(arg);
if (binding instanceof IMethodBinding) {
argBinding = ((IMethodBinding) binding).getReturnType();
} else {
argBinding = Types.getTypeBinding(arg);
}
if (argType.isPrimitive() && !argBinding.isPrimitive()) {
return unbox(arg);
} else if (!argType.isPrimitive() && argBinding.isPrimitive()) {
return box(arg);
} else {
return arg;
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
0f00d18d404b1a203e3b6e6eb8023e41c78a1246 | 58f63a6147b3c6a61b8b3c54f635c54bff4275d8 | /src/main/java/org/tsaap/lti/tp/dataconnector/None.java | 6b4d786e65dee396a1e17d789f7d22571457b76c | [] | no_license | TSaaP/tsaap-lti | 32fa51c83eb2b12d7a603b3008aad7023ed316fe | c6865d310d5dd6d6b2b0c924136b6c8721340e98 | refs/heads/master | 2021-01-20T18:04:05.694148 | 2017-09-08T10:27:18 | 2017-09-08T10:27:18 | 60,834,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,352 | java | /*
* LTIToolProvider - Classes to handle connections with an LTI 1 compliant tool consumer
* Copyright (C) 2013 Stephen P Vickers
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this program; if not, see <http://www.gnu.org/licences/>
*
* Contact: stephen@spvsoftwareproducts.com
*/
package org.tsaap.lti.tp.dataconnector;
import org.tsaap.lti.tp.*;
import java.util.*;
/**
* Class which implements a dummy data connector with no database persistence.
*
* @author Stephen P Vickers
* @version 1.1.01 (18-Jun-13)
*/
public class None extends DataConnector {
/**
* Constructs a dummy data connector object which implements simulated methods
* without persisting any data.
*/
public None() {
}
///
/// ToolConsumer methods
///
/**
* Load tool consumer object with a default secret of <code>secret</code> and enabled.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully loaded
*/
@Override
public boolean loadToolConsumer(ToolConsumer consumer) {
consumer.setSecret("secret");
consumer.setEnabled(true);
Calendar now = Calendar.getInstance();
consumer.setCreated(now);
consumer.setUpdated(now);
return true;
}
/**
* Save tool consumer object.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully saved
*/
@Override
public boolean saveToolConsumer(ToolConsumer consumer) {
consumer.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete tool consumer object.
*
* @param consumer ToolConsumer object
* @return <code>true</code> if the tool consumer object was successfully deleted
*/
@Override
public boolean deleteToolConsumer(ToolConsumer consumer) {
consumer.initialise();
return true;
}
/**
* Load tool consumer objects.
*
* @return array of all defined ToolConsumer objects
*/
@Override
public List<ToolConsumer> getToolConsumers() {
return new ArrayList<ToolConsumer>();
}
///
/// ResourceLink methods
///
/**
* Load resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resource link object was successfully loaded
*/
@Override
public boolean loadResourceLink(ResourceLink resourceLink) {
Calendar now = Calendar.getInstance();
resourceLink.setCreated(now);
resourceLink.setUpdated(now);
return true;
}
/**
* Save resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resource link object was successfully saved
*/
@Override
public boolean saveResourceLink(ResourceLink resourceLink) {
resourceLink.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete resource link object.
*
* @param resourceLink ResourceLink object
* @return <code>true</code> if the resourceLink object was successfully deleted
*/
@Override
public boolean deleteResourceLink(ResourceLink resourceLink) {
resourceLink.initialise();
return true;
}
/**
* Get array of user objects.
*
* @param resourceLink ResourceLink object
* @param localOnly <code>true</code> if only users for the resource link are to be returned (excluding users sharing this resource link)
* @param scope Scope value to use for user IDs
* @return array of User objects
*/
@Override
public Map<String, User> getUserResultSourcedIDs(ResourceLink resourceLink, boolean localOnly, int scope) {
return new HashMap<String, User>();
}
/**
* Get shares defined for a resource link.
*
* @param resourceLink ResourceLink object
* @return array of resourceLinkShare objects
*/
@Override
public List<ResourceLinkShare> getShares(ResourceLink resourceLink) {
return new ArrayList<ResourceLinkShare>();
}
///
/// Nonce methods
///
/**
* Load nonce object.
*
* @param nonce Nonce object
* @return <code>true</code> if the nonce object was successfully loaded
*/
@Override
public boolean loadConsumerNonce(Nonce nonce) {
return false; // assume the nonce does not already exist
}
/**
* Save nonce object.
*
* @param nonce Nonce object
* @return <code>true</code> if the nonce object was successfully saved
*/
@Override
public boolean saveConsumerNonce(Nonce nonce) {
return true;
}
///
/// ResourceLinkShareKey methods
///
/**
* Load resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully loaded
*/
@Override
public boolean loadResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
/**
* Save resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully saved
*/
@Override
public boolean saveResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
/**
* Delete resource link share key object.
*
* @param shareKey Resource link share key object
* @return <code>true</code> if the resource link share key object was successfully deleted
*/
@Override
public boolean deleteResourceLinkShareKey(ResourceLinkShareKey shareKey) {
return true;
}
///
/// User methods
///
/**
* Load user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully loaded
*/
@Override
public boolean loadUser(User user) {
Calendar now = Calendar.getInstance();
user.setCreated(now);
user.setUpdated(now);
return true;
}
/**
* Save user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully saved
*/
@Override
public boolean saveUser(User user) {
user.setUpdated(Calendar.getInstance());
return true;
}
/**
* Delete user object.
*
* @param user User object
* @return <code>true</code> if the user object was successfully deleted
*/
@Override
public boolean deleteUser(User user) {
user.initialise();
return true;
}
}
| [
"franck.silvestre@ticetime.com"
] | franck.silvestre@ticetime.com |
5e37718cc0462c2a669d025f85c69e86e48f1e7b | e665666b082fdd0304fc05cf26fac65676bc71e0 | /src/java/ca/savi/horse/model/hwunmarshaller/UnmarshalGenericOperationRequestParamsResponse.java | dd545d06555eef3de10506ee5b1c38c1185dbdbb | [] | no_license | savi-dev/horse | 827da67da56f87d3b85c1508eb69bc1847451c93 | d71a80d066ada52f8d0c4a8b6e047923cd1e8e4a | refs/heads/master | 2021-01-25T12:09:23.870319 | 2012-08-20T15:32:38 | 2012-08-20T15:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,238 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB)
// Reference Implementation, vhudson-jaxb-ri-2.2-147
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source
// schema.
// Generated on: 2012.03.19 at 01:54:32 PM EDT
//
package ca.savi.horse.model.hwunmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="setRegisterValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
* <element name="uuid" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "setRegisterValue", "uuid" })
@XmlRootElement(name = "UnmarshalGenericOperationRequestParams-Response")
public class UnmarshalGenericOperationRequestParamsResponse {
protected byte[] setRegisterValue;
protected String uuid;
/**
* Gets the value of the setRegisterValue property.
* @return possible object is byte[]
*/
public byte[] getSetRegisterValue() {
return setRegisterValue;
}
/**
* Sets the value of the setRegisterValue property.
* @param value allowed object is byte[]
*/
public void setSetRegisterValue(byte[] value) {
this.setRegisterValue = ((byte[]) value);
}
/**
* Gets the value of the uuid property.
* @return possible object is {@link String }
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
* @param value allowed object is {@link String }
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| [
"hes.rahimi@savinetwork.ca"
] | hes.rahimi@savinetwork.ca |
36f4e873994547d1e0a7575545426a5b4fea2fc9 | 70b5aa0bcc271af9f9483492ab9beef4975db296 | /mall-tiny-01/src/main/java/com/macro/mall/tiny/controller/TestController.java | a2a478a43adade2952206cf7b761276db69dcd75 | [] | no_license | qiusu/mallLearning | 1b22162d8f856fbdc942700579db2350aefdbca5 | 135706ba21178e4129d43b2d4829981a339bb70c | refs/heads/master | 2022-08-18T12:22:28.904830 | 2019-08-10T15:49:36 | 2019-08-10T15:49:36 | 201,069,452 | 0 | 0 | null | 2022-06-21T01:38:23 | 2019-08-07T14:42:21 | Java | UTF-8 | Java | false | false | 300 | java | package com.macro.mall.tiny.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/hi")
public String getInfo(){
return "hi";
}
}
| [
"1430908463@qq.com"
] | 1430908463@qq.com |
ca06be891702d0f30542a9c88a5d1cd23f055d2f | d6c36b52b7f32819f0f7db1a2d8ba118a700a41b | /src/Course2/w2/StringsFirstAssignments/Part4.java | 5ea239bb3f4644d01236fcd1c9ea4e34f96efb5a | [] | no_license | leonardloh/Duke-University-Java-Programming-and-Software-Engineering-Fundamentals-Specialization | d0620f55609a3f45de03bb757ba058a9d19cbdd3 | 355e282b0be578efcf97ecc592d3f61ca8f6f7d1 | refs/heads/master | 2022-08-18T19:18:48.298605 | 2020-05-18T14:59:12 | 2020-05-18T14:59:12 | 262,826,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 839 | java | package Course2.w2.StringsFirstAssignments;
import edu.duke.URLResource;
public class Part4 {
public static String pattern = "youtube.com";
public static String quote = "\"";
public void findOccurence()
{
URLResource ur = new URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
for(String word: ur.words())
{
int patternIndex = word.indexOf(pattern);
if (patternIndex != -1 )
{
int indexQuote1 = word.indexOf(quote);
int indexQuote2 = word.indexOf(quote, word.indexOf(quote)+1);
System.out.println(word.substring(indexQuote1, indexQuote2+1));
}
}
}
public static void main(String[] args) {
Part4 p4 = new Part4();
p4.findOccurence();
}
}
| [
"jingzhi.loh@skymind.my"
] | jingzhi.loh@skymind.my |
578b9bd97443c1c261e3158d331fbbbf706ec845 | 6abe807945f29c887484f9ac4221f45ab4dd8768 | /android/app/src/main/java/com/catgallery/MainActivity.java | 967dd825c8b1b9fa070adb660e6190f04d2bc382 | [] | no_license | jinhe2305/CatGallery | aab3cf08d60928f9261eabaaf79a99dec894678c | fd863437050ddbfb5d8cc1a2886383a96473ee49 | refs/heads/master | 2020-04-27T09:14:11.796997 | 2019-03-06T19:23:52 | 2019-03-06T19:23:52 | 174,206,305 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 365 | java | package com.catgallery;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "CatGallery";
}
}
| [
"jinhe2305@gmail.com"
] | jinhe2305@gmail.com |
76b4b054fc7d303a02bdeba0260c8595627ec8dd | 42b5f055f8a3ffb64f4e27d0b0fa1fa515d2fa47 | /weka/classifiers/functions/MultilayerPerceptron.java | 3c18d154327ff2ed7fa02810b4858fe6ce91892e | [] | no_license | sinamalakouti/DeepTreeNetwork | 4de4be524b062435e1d083d0d8792f4955a47007 | 0eab518f99b00e8b6bf0e3b5771ff71c84e525f1 | refs/heads/master | 2022-01-11T08:58:59.855122 | 2019-07-24T19:02:38 | 2019-07-24T19:02:38 | 145,144,372 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87,133 | java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* MultilayerPerceptron.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.functions;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.IterativeClassifier;
import weka.classifiers.functions.neural.LinearUnit;
import weka.classifiers.functions.neural.NeuralConnection;
import weka.classifiers.functions.neural.NeuralNode;
import weka.classifiers.functions.neural.SigmoidUnit;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
/**
* <!-- globalinfo-start --> A Classifier that uses backpropagation to classify
* instances.<br/>
* This network can be built by hand, created by an algorithm or both. The
* network can also be monitored and modified during training time. The nodes in
* this network are all sigmoid (except for when the class is numeric in which
* case the the output nodes become unthresholded linear units).
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -L <learning rate>
* Learning Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.3).
* </pre>
*
* <pre>
* -M <momentum>
* Momentum Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.2).
* </pre>
*
* <pre>
* -N <number of epochs>
* Number of epochs to train through.
* (Default = 500).
* </pre>
*
* <pre>
* -V <percentage size of validation set>
* Percentage size of validation set to use to terminate
* training (if this is non zero it can pre-empt num of epochs.
* (Value should be between 0 - 100, Default = 0).
* </pre>
*
* <pre>
* -S <seed>
* The value used to seed the random number generator
* (Value should be >= 0 and and a long, Default = 0).
* </pre>
*
* <pre>
* -E <threshold for number of consequetive errors>
* The consequetive number of errors allowed for validation
* testing before the netwrok terminates.
* (Value should be > 0, Default = 20).
* </pre>
*
* <pre>
* -G
* GUI will be opened.
* (Use this to bring up a GUI).
* </pre>
*
* <pre>
* -A
* Autocreation of the network connections will NOT be done.
* (This will be ignored if -G is NOT set)
* </pre>
*
* <pre>
* -B
* A NominalToBinary filter will NOT automatically be used.
* (Set this to not use a NominalToBinary filter).
* </pre>
*
* <pre>
* -H <comma seperated numbers for nodes on each layer>
* The hidden layers to be created for the network.
* (Value should be a list of comma separated Natural
* numbers or the letters 'a' = (attribs + classes) / 2,
* 'i' = attribs, 'o' = classes, 't' = attribs .+ classes)
* for wildcard values, Default = a).
* </pre>
*
* <pre>
* -C
* Normalizing a numeric class will NOT be done.
* (Set this to not normalize the class if it's numeric).
* </pre>
*
* <pre>
* -I
* Normalizing the attributes will NOT be done.
* (Set this to not normalize the attributes).
* </pre>
*
* <pre>
* -R
* Reseting the network will NOT be allowed.
* (Set this to not allow the network to reset).
* </pre>
*
* <pre>
* -D
* Learning rate decay will occur.
* (Set this to cause the learning rate to decay).
* </pre>
*
* <!-- options-end -->
*
* @author Malcolm Ware (mfw4@cs.waikato.ac.nz)
* @version $Revision: 14497 $
*/
public class MultilayerPerceptron extends AbstractClassifier implements
OptionHandler, WeightedInstancesHandler, Randomizable, IterativeClassifier {
/** for serialization */
private static final long serialVersionUID = -5990607817048210779L;
/**
* Main method for testing this class.
*
* @param argv should contain command line options (see setOptions)
*/
public static void main(String[] argv) {
runClassifier(new MultilayerPerceptron(), argv);
}
/**
* This inner class is used to connect the nodes in the network up to the data
* that they are classifying, Note that objects of this class are only
* suitable to go on the attribute side or class side of the network and not
* both.
*/
protected class NeuralEnd extends NeuralConnection {
/** for serialization */
static final long serialVersionUID = 7305185603191183338L;
/**
* the value that represents the instance value this node represents. For an
* input it is the attribute number, for an output, if nominal it is the
* class value.
*/
private int m_link;
/** True if node is an input, False if it's an output. */
private boolean m_input;
/**
* Constructor
*/
public NeuralEnd(String id) {
super(id);
m_link = 0;
m_input = true;
}
/**
* Call this function to determine if the point at x,y is on the unit.
*
* @param g The graphics context for font size info.
* @param x The x coord.
* @param y The y coord.
* @param w The width of the display.
* @param h The height of the display.
* @return True if the point is on the unit, false otherwise.
*/
@Override
public boolean onUnit(Graphics g, int x, int y, int w, int h) {
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
if (x < l || x > l + fm.stringWidth(m_id) + 4 || y < t
|| y > t + fm.getHeight() + fm.getDescent() + 4) {
return false;
}
return true;
}
/**
* This will draw the node id to the graphics context.
*
* @param g The graphics context.
* @param w The width of the drawing area.
* @param h The height of the drawing area.
*/
@Override
public void drawNode(Graphics g, int w, int h) {
if ((m_type & PURE_INPUT) == PURE_INPUT) {
g.setColor(Color.green);
} else {
g.setColor(Color.orange);
}
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
g.fill3DRect(l, t, fm.stringWidth(m_id) + 4,
fm.getHeight() + fm.getDescent() + 4, true);
g.setColor(Color.black);
g.drawString(m_id, l + 2, t + fm.getHeight() + 2);
}
/**
* Call this function to draw the node highlighted.
*
* @param g The graphics context.
* @param w The width of the drawing area.
* @param h The height of the drawing area.
*/
@Override
public void drawHighlight(Graphics g, int w, int h) {
g.setColor(Color.black);
FontMetrics fm = g.getFontMetrics();
int l = (int) (m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int) (m_y * h) - fm.getHeight() / 2;
g.fillRect(l - 2, t - 2, fm.stringWidth(m_id) + 8,
fm.getHeight() + fm.getDescent() + 8);
drawNode(g, w, h);
}
/**
* Call this to get the output value of this unit.
*
* @param calculate True if the value should be calculated if it hasn't been
* already.
* @return The output value, or NaN, if the value has not been calculated.
*/
@Override
public double outputValue(boolean calculate) {
if (Double.isNaN(m_unitValue) && calculate) {
if (m_input) {
if (m_currentInstance.isMissing(m_link)) {
m_unitValue = 0;
} else {
m_unitValue = m_currentInstance.value(m_link);
}
} else {
// node is an output.
m_unitValue = 0;
for (int noa = 0; noa < m_numInputs; noa++) {
m_unitValue += m_inputList[noa].outputValue(true);
}
if (m_numeric && m_normalizeClass) {
// then scale the value;
// this scales linearly from between -1 and 1
m_unitValue = m_unitValue
* m_attributeRanges[m_instances.classIndex()]
+ m_attributeBases[m_instances.classIndex()];
}
}
}
return m_unitValue;
}
/**
* Call this to get the error value of this unit, which in this case is the
* difference between the predicted class, and the actual class.
*
* @param calculate True if the value should be calculated if it hasn't been
* already.
* @return The error value, or NaN, if the value has not been calculated.
*/
@Override
public double errorValue(boolean calculate) {
if (!Double.isNaN(m_unitValue) && Double.isNaN(m_unitError) && calculate) {
if (m_input) {
m_unitError = 0;
for (int noa = 0; noa < m_numOutputs; noa++) {
m_unitError += m_outputList[noa].errorValue(true);
}
} else {
if (m_currentInstance.classIsMissing()) {
m_unitError = .1;
} else if (m_instances.classAttribute().isNominal()) {
if (m_currentInstance.classValue() == m_link) {
m_unitError = 1 - m_unitValue;
} else {
m_unitError = 0 - m_unitValue;
}
} else if (m_numeric) {
if (m_normalizeClass) {
if (m_attributeRanges[m_instances.classIndex()] == 0) {
m_unitError = 0;
} else {
m_unitError = (m_currentInstance.classValue() - m_unitValue)
/ m_attributeRanges[m_instances.classIndex()];
// m_numericRange;
}
} else {
m_unitError = m_currentInstance.classValue() - m_unitValue;
}
}
}
}
return m_unitError;
}
/**
* Call this to reset the value and error for this unit, ready for the next
* run. This will also call the reset function of all units that are
* connected as inputs to this one. This is also the time that the update
* for the listeners will be performed.
*/
@Override
public void reset() {
if (!Double.isNaN(m_unitValue) || !Double.isNaN(m_unitError)) {
m_unitValue = Double.NaN;
m_unitError = Double.NaN;
m_weightsUpdated = false;
for (int noa = 0; noa < m_numInputs; noa++) {
m_inputList[noa].reset();
}
}
}
/**
* Call this to have the connection save the current weights.
*/
@Override
public void saveWeights() {
for (int i = 0; i < m_numInputs; i++) {
m_inputList[i].saveWeights();
}
}
/**
* Call this to have the connection restore from the saved weights.
*/
@Override
public void restoreWeights() {
for (int i = 0; i < m_numInputs; i++) {
m_inputList[i].restoreWeights();
}
}
/**
* Call this function to set What this end unit represents.
*
* @param input True if this unit is used for entering an attribute, False
* if it's used for determining a class value.
* @param val The attribute number or class type that this unit represents.
* (for nominal attributes).
*/
public void setLink(boolean input, int val) throws Exception {
m_input = input;
if (input) {
m_type = PURE_INPUT;
} else {
m_type = PURE_OUTPUT;
}
if (val < 0
|| (input && val > m_instances.numAttributes())
|| (!input && m_instances.classAttribute().isNominal() && val > m_instances
.classAttribute().numValues())) {
m_link = 0;
} else {
m_link = val;
}
}
/**
* @return link for this node.
*/
public int getLink() {
return m_link;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* Inner class used to draw the nodes onto.(uses the node lists!!) This will
* also handle the user input.
*/
private class NodePanel extends JPanel implements RevisionHandler {
/** for serialization */
static final long serialVersionUID = -3067621833388149984L;
/**
* The constructor.
*/
public NodePanel() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (!m_stopped) {
return;
}
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK
&& !e.isAltDown()) {
Graphics g = NodePanel.this.getGraphics();
int x = e.getX();
int y = e.getY();
int w = NodePanel.this.getWidth();
int h = NodePanel.this.getHeight();
ArrayList<NeuralConnection> tmp = new ArrayList<NeuralConnection>(4);
for (int noa = 0; noa < m_numAttributes; noa++) {
if (m_inputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_inputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_outputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_outputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if (m_neuralNode.onUnit(g, x, y, w, h)) {
tmp.add(m_neuralNode);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
return;
}
}
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId),
m_random, m_sigmoidUnit);
m_nextId++;
temp.setX((double) e.getX() / w);
temp.setY((double) e.getY() / h);
tmp.add(temp);
addNode(temp);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
true);
} else {
// then right click
Graphics g = NodePanel.this.getGraphics();
int x = e.getX();
int y = e.getY();
int w = NodePanel.this.getWidth();
int h = NodePanel.this.getHeight();
ArrayList<NeuralConnection> tmp = new ArrayList<NeuralConnection>(4);
for (int noa = 0; noa < m_numAttributes; noa++) {
if (m_inputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_inputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_outputs[noa].onUnit(g, x, y, w, h)) {
tmp.add(m_outputs[noa]);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if (m_neuralNode.onUnit(g, x, y, w, h)) {
tmp.add(m_neuralNode);
selection(
tmp,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
return;
}
}
selection(
null,
(e.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK,
false);
}
}
});
}
/**
* This function gets called when the user has clicked something It will
* amend the current selection or connect the current selection to the new
* selection. Or if nothing was selected and the right button was used it
* will delete the node.
*
* @param v The units that were selected.
* @param ctrl True if ctrl was held down.
* @param left True if it was the left mouse button.
*/
private void selection(ArrayList<NeuralConnection> v, boolean ctrl,
boolean left) {
if (v == null) {
// then unselect all.
m_selected.clear();
repaint();
return;
}
// then exclusive or the new selection with the current one.
if ((ctrl || m_selected.size() == 0) && left) {
boolean removed = false;
for (int noa = 0; noa < v.size(); noa++) {
removed = false;
for (int nob = 0; nob < m_selected.size(); nob++) {
if (v.get(noa) == m_selected.get(nob)) {
// then remove that element
m_selected.remove(nob);
removed = true;
break;
}
}
if (!removed) {
m_selected.add(v.get(noa));
}
}
repaint();
return;
}
if (left) {
// then connect the current selection to the new one.
for (int noa = 0; noa < m_selected.size(); noa++) {
for (int nob = 0; nob < v.size(); nob++) {
NeuralConnection.connect(m_selected.get(noa), v.get(nob));
}
}
} else if (m_selected.size() > 0) {
// then disconnect the current selection from the new one.
for (int noa = 0; noa < m_selected.size(); noa++) {
for (int nob = 0; nob < v.size(); nob++) {
NeuralConnection.disconnect(m_selected.get(noa), v.get(nob));
NeuralConnection.disconnect(v.get(nob), m_selected.get(noa));
}
}
} else {
// then remove the selected node. (it was right clicked while
// no other units were selected
for (int noa = 0; noa < v.size(); noa++) {
v.get(noa).removeAllInputs();
v.get(noa).removeAllOutputs();
removeNode(v.get(noa));
}
}
repaint();
}
/**
* This will paint the nodes ontot the panel.
*
* @param g The graphics context.
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = getWidth();
int y = getHeight();
if (25 * m_numAttributes > 25 * m_numClasses && 25 * m_numAttributes > y) {
setSize(x, 25 * m_numAttributes);
} else if (25 * m_numClasses > y) {
setSize(x, 25 * m_numClasses);
} else {
setSize(x, y);
}
y = getHeight();
for (int noa = 0; noa < m_numAttributes; noa++) {
m_inputs[noa].drawInputLines(g, x, y);
}
for (int noa = 0; noa < m_numClasses; noa++) {
m_outputs[noa].drawInputLines(g, x, y);
m_outputs[noa].drawOutputLines(g, x, y);
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
m_neuralNode.drawInputLines(g, x, y);
}
for (int noa = 0; noa < m_numAttributes; noa++) {
m_inputs[noa].drawNode(g, x, y);
}
for (int noa = 0; noa < m_numClasses; noa++) {
m_outputs[noa].drawNode(g, x, y);
}
for (NeuralConnection m_neuralNode : m_neuralNodes) {
m_neuralNode.drawNode(g, x, y);
}
for (int noa = 0; noa < m_selected.size(); noa++) {
m_selected.get(noa).drawHighlight(g, x, y);
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* This provides the basic controls for working with the neuralnetwork
*
* @author Malcolm Ware (mfw4@cs.waikato.ac.nz)
* @version $Revision: 14497 $
*/
class ControlPanel extends JPanel implements RevisionHandler {
/** for serialization */
static final long serialVersionUID = 7393543302294142271L;
/** The start stop button. */
public JButton m_startStop;
/** The button to accept the network (even if it hasn't done all epochs. */
public JButton m_acceptButton;
/** A label to state the number of epochs processed so far. */
public JPanel m_epochsLabel;
/** A label to state the total number of epochs to be processed. */
public JLabel m_totalEpochsLabel;
/** A text field to allow the changing of the total number of epochs. */
public JTextField m_changeEpochs;
/** A label to state the learning rate. */
public JLabel m_learningLabel;
/** A label to state the momentum. */
public JLabel m_momentumLabel;
/** A text field to allow the changing of the learning rate. */
public JTextField m_changeLearning;
/** A text field to allow the changing of the momentum. */
public JTextField m_changeMomentum;
/**
* A label to state roughly the accuracy of the network.(because the
* accuracy is calculated per epoch, but the network is changing throughout
* each epoch train).
*/
public JPanel m_errorLabel;
/** The constructor. */
public ControlPanel() {
setBorder(BorderFactory.createTitledBorder("Controls"));
m_totalEpochsLabel = new JLabel("Num Of Epochs ");
m_epochsLabel = new JPanel() {
/** for serialization */
private static final long serialVersionUID = 2562773937093221399L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(m_controlPanel.m_totalEpochsLabel.getForeground());
g.drawString("Epoch " + m_epoch, 0, 10);
}
};
m_epochsLabel.setFont(m_totalEpochsLabel.getFont());
m_changeEpochs = new JTextField();
m_changeEpochs.setText("" + m_numEpochs);
m_errorLabel = new JPanel() {
/** for serialization */
private static final long serialVersionUID = 4390239056336679189L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(m_controlPanel.m_totalEpochsLabel.getForeground());
if (m_valSize == 0) {
g.drawString(
"Error per Epoch = " + Utils.doubleToString(m_error, 7), 0, 10);
} else {
g.drawString(
"Validation Error per Epoch = "
+ Utils.doubleToString(m_error, 7), 0, 10);
}
}
};
m_errorLabel.setFont(m_epochsLabel.getFont());
m_learningLabel = new JLabel("Learning Rate = ");
m_momentumLabel = new JLabel("Momentum = ");
m_changeLearning = new JTextField();
m_changeMomentum = new JTextField();
m_changeLearning.setText("" + m_learningRate);
m_changeMomentum.setText("" + m_momentum);
setLayout(new BorderLayout(15, 10));
m_stopIt = true;
m_accepted = false;
m_startStop = new JButton("Start");
m_startStop.setActionCommand("Start");
m_acceptButton = new JButton("Accept");
m_acceptButton.setActionCommand("Accept");
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
buttons.add(m_startStop);
buttons.add(m_acceptButton);
add(buttons, BorderLayout.WEST);
JPanel data = new JPanel();
data.setLayout(new BoxLayout(data, BoxLayout.Y_AXIS));
Box ab = new Box(BoxLayout.X_AXIS);
ab.add(m_epochsLabel);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
Component b = Box.createGlue();
ab.add(m_totalEpochsLabel);
ab.add(m_changeEpochs);
m_changeEpochs.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
ab.add(m_errorLabel);
data.add(ab);
add(data, BorderLayout.CENTER);
data = new JPanel();
data.setLayout(new BoxLayout(data, BoxLayout.Y_AXIS));
ab = new Box(BoxLayout.X_AXIS);
b = Box.createGlue();
ab.add(m_learningLabel);
ab.add(m_changeLearning);
m_changeLearning.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
ab = new Box(BoxLayout.X_AXIS);
b = Box.createGlue();
ab.add(m_momentumLabel);
ab.add(m_changeMomentum);
m_changeMomentum.setMaximumSize(new Dimension(200, 20));
ab.add(b);
data.add(ab);
add(data, BorderLayout.EAST);
m_startStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Start")) {
m_stopIt = false;
m_startStop.setText("Stop");
m_startStop.setActionCommand("Stop");
int n = Integer.valueOf(m_changeEpochs.getText()).intValue();
m_numEpochs = n;
m_changeEpochs.setText("" + m_numEpochs);
double m = Double.valueOf(m_changeLearning.getText()).doubleValue();
setLearningRate(m);
m_changeLearning.setText("" + m_learningRate);
m = Double.valueOf(m_changeMomentum.getText()).doubleValue();
setMomentum(m);
m_changeMomentum.setText("" + m_momentum);
blocker(false);
} else if (e.getActionCommand().equals("Stop")) {
m_stopIt = true;
m_startStop.setText("Start");
m_startStop.setActionCommand("Start");
}
}
});
m_acceptButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_accepted = true;
blocker(false);
}
});
m_changeEpochs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n = Integer.valueOf(m_changeEpochs.getText()).intValue();
if (n > 0) {
m_numEpochs = n;
blocker(false);
}
}
});
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
/**
* a ZeroR model in case no model can be built from the data or the network
* predicts all zeros for the classes
*/
private Classifier m_ZeroR;
/** Whether to use the default ZeroR model */
private boolean m_useDefaultModel = false;
/** The training instances. */
private Instances m_instances;
/** The current instance running through the network. */
private Instance m_currentInstance;
/** A flag to say that it's a numeric class. */
private boolean m_numeric;
/** The ranges for all the attributes. */
private double[] m_attributeRanges;
/** The base values for all the attributes. */
private double[] m_attributeBases;
/** The output units.(only feeds the errors, does no calcs) */
private NeuralEnd[] m_outputs;
/** The input units.(only feeds the inputs does no calcs) */
private NeuralEnd[] m_inputs;
/** All the nodes that actually comprise the logical neural net. */
private NeuralConnection[] m_neuralNodes;
/** The number of classes. */
private int m_numClasses = 0;
/** The number of attributes. */
private int m_numAttributes = 0; // note the number doesn't include the class.
/** The panel the nodes are displayed on. */
private NodePanel m_nodePanel;
/** The control panel. */
private ControlPanel m_controlPanel;
/** The next id number available for default naming. */
private int m_nextId;
/** A Vector list of the units currently selected. */
private ArrayList<NeuralConnection> m_selected;
/** The number of epochs to train through. */
private int m_numEpochs;
/** a flag to state if the network should be running, or stopped. */
private boolean m_stopIt;
/** a flag to state that the network has in fact stopped. */
private boolean m_stopped;
/** a flag to state that the network should be accepted the way it is. */
private boolean m_accepted;
/** The window for the network. */
private JFrame m_win;
/**
* A flag to tell the build classifier to automatically build a neural net.
*/
private boolean m_autoBuild;
/**
* A flag to state that the gui for the network should be brought up. To allow
* interaction while training.
*/
private boolean m_gui;
/** An int to say how big the validation set should be. */
private int m_valSize;
/** The number to to use to quit on validation testing. */
private int m_driftThreshold;
/** The number used to seed the random number generator. */
private int m_randomSeed;
/** The actual random number generator. */
private Random m_random;
/** A flag to state that a nominal to binary filter should be used. */
private boolean m_useNomToBin;
/** The actual filter. */
private NominalToBinary m_nominalToBinaryFilter;
/** The string that defines the hidden layers */
private String m_hiddenLayers;
/** This flag states that the user wants the input values normalized. */
private boolean m_normalizeAttributes;
/** This flag states that the user wants the learning rate to decay. */
private boolean m_decay;
/** This is the learning rate for the network. */
private double m_learningRate;
/** This is the momentum for the network. */
private double m_momentum;
/** Shows the number of the epoch that the network just finished. */
private int m_epoch;
/** Shows the error of the epoch that the network just finished. */
private double m_error;
/**
* This flag states that the user wants the network to restart if it is found
* to be generating infinity or NaN for the error value. This would restart
* the network with the current options except that the learning rate would be
* smaller than before, (perhaps half of its current value). This option will
* not be available if the gui is chosen (if the gui is open the user can fix
* the network themselves, it is an architectural minefield for the network to
* be reset with the gui open).
*/
private boolean m_reset;
/**
* This flag states that the user wants the class to be normalized while
* processing in the network is done. (the final answer will be in the
* original range regardless). This option will only be used when the class is
* numeric.
*/
private boolean m_normalizeClass;
/**
* this is a sigmoid unit.
*/
private final SigmoidUnit m_sigmoidUnit;
/**
* This is a linear unit.
*/
private final LinearUnit m_linearUnit;
/**
* The constructor.
*/
public MultilayerPerceptron() {
m_instances = null;
m_currentInstance = null;
m_controlPanel = null;
m_nodePanel = null;
m_epoch = 0;
m_error = 0;
m_outputs = new NeuralEnd[0];
m_inputs = new NeuralEnd[0];
m_numAttributes = 0;
m_numClasses = 0;
m_neuralNodes = new NeuralConnection[0];
m_selected = new ArrayList<NeuralConnection>(4);
m_nextId = 0;
m_stopIt = true;
m_stopped = true;
m_accepted = false;
m_numeric = false;
m_random = null;
m_nominalToBinaryFilter = new NominalToBinary();
m_sigmoidUnit = new SigmoidUnit();
m_linearUnit = new LinearUnit();
// setting all the options to their defaults. To completely change these
// defaults they will also need to be changed down the bottom in the
// setoptions function (the text info in the accompanying functions should
// also be changed to reflect the new defaults
m_normalizeClass = true;
m_normalizeAttributes = true;
m_autoBuild = true;
m_gui = false;
m_useNomToBin = true;
m_driftThreshold = 20;
m_numEpochs = 500;
m_valSize = 0;
m_randomSeed = 0;
m_hiddenLayers = "a";
m_learningRate = .3;
m_momentum = .2;
m_reset = true;
m_decay = false;
}
/**
* @param d True if the learning rate should decay.
*/
public void setDecay(boolean d) {
m_decay = d;
}
/**
* @return the flag for having the learning rate decay.
*/
public boolean getDecay() {
return m_decay;
}
/**
* This sets the network up to be able to reset itself with the current
* settings and the learning rate at half of what it is currently. This will
* only happen if the network creates NaN or infinite errors. Also this will
* continue to happen until the network is trained properly. The learning rate
* will also get set back to it's original value at the end of this. This can
* only be set to true if the GUI is not brought up.
*
* @param r True if the network should restart with it's current options and
* set the learning rate to half what it currently is.
*/
public void setReset(boolean r) {
if (m_gui) {
r = false;
}
m_reset = r;
}
/**
* @return The flag for reseting the network.
*/
public boolean getReset() {
return m_reset;
}
/**
* @param c True if the class should be normalized (the class will only ever
* be normalized if it is numeric). (Normalization puts the range
* between -1 - 1).
*/
public void setNormalizeNumericClass(boolean c) {
m_normalizeClass = c;
}
/**
* @return The flag for normalizing a numeric class.
*/
public boolean getNormalizeNumericClass() {
return m_normalizeClass;
}
/**
* @param a True if the attributes should be normalized (even nominal
* attributes will get normalized here) (range goes between -1 - 1).
*/
public void setNormalizeAttributes(boolean a) {
m_normalizeAttributes = a;
}
/**
* @return The flag for normalizing attributes.
*/
public boolean getNormalizeAttributes() {
return m_normalizeAttributes;
}
/**
* @param f True if a nominalToBinary filter should be used on the data.
*/
public void setNominalToBinaryFilter(boolean f) {
m_useNomToBin = f;
}
/**
* @return The flag for nominal to binary filter use.
*/
public boolean getNominalToBinaryFilter() {
return m_useNomToBin;
}
/**
* This seeds the random number generator, that is used when a random number
* is needed for the network.
*
* @param l The seed.
*/
@Override
public void setSeed(int l) {
if (l >= 0) {
m_randomSeed = l;
}
}
/**
* @return The seed for the random number generator.
*/
@Override
public int getSeed() {
return m_randomSeed;
}
/**
* This sets the threshold to use for when validation testing is being done.
* It works by ending testing once the error on the validation set has
* consecutively increased a certain number of times.
*
* @param t The threshold to use for this.
*/
public void setValidationThreshold(int t) {
if (t > 0) {
m_driftThreshold = t;
}
}
/**
* @return The threshold used for validation testing.
*/
public int getValidationThreshold() {
return m_driftThreshold;
}
/**
* The learning rate can be set using this command. NOTE That this is a static
* variable so it affect all networks that are running. Must be greater than 0
* and no more than 1.
*
* @param l The New learning rate.
*/
public void setLearningRate(double l) {
if (l > 0 && l <= 1) {
m_learningRate = l;
if (m_controlPanel != null) {
m_controlPanel.m_changeLearning.setText("" + l);
}
}
}
/**
* @return The learning rate for the nodes.
*/
public double getLearningRate() {
return m_learningRate;
}
/**
* The momentum can be set using this command. THE same conditions apply to
* this as to the learning rate.
*
* @param m The new Momentum.
*/
public void setMomentum(double m) {
if (m >= 0 && m <= 1) {
m_momentum = m;
if (m_controlPanel != null) {
m_controlPanel.m_changeMomentum.setText("" + m);
}
}
}
/**
* @return The momentum for the nodes.
*/
public double getMomentum() {
return m_momentum;
}
/**
* This will set whether the network is automatically built or if it is left
* up to the user. (there is nothing to stop a user from altering an autobuilt
* network however).
*
* @param a True if the network should be auto built.
*/
public void setAutoBuild(boolean a) {
if (!m_gui) {
a = true;
}
m_autoBuild = a;
}
/**
* @return The auto build state.
*/
public boolean getAutoBuild() {
return m_autoBuild;
}
/**
* This will set what the hidden layers are made up of when auto build is
* enabled. Note to have no hidden units, just put a single 0, Any more 0's
* will indicate that the string is badly formed and make it unaccepted.
* Negative numbers, and floats will do the same. There are also some
* wildcards. These are 'a' = (number of attributes + number of classes) / 2,
* 'i' = number of attributes, 'o' = number of classes, and 't' = number of
* attributes + number of classes.
*
* @param h A string with a comma seperated list of numbers. Each number is
* the number of nodes to be on a hidden layer.
*/
public void setHiddenLayers(String h) {
String tmp = "";
StringTokenizer tok = new StringTokenizer(h, ",");
if (tok.countTokens() == 0) {
return;
}
double dval;
int val;
String c;
boolean first = true;
while (tok.hasMoreTokens()) {
c = tok.nextToken().trim();
if (c.equals("a") || c.equals("i") || c.equals("o") || c.equals("t")) {
tmp += c;
} else {
dval = Double.valueOf(c).doubleValue();
val = (int) dval;
if ((val == dval && (val != 0 || (tok.countTokens() == 0 && first)) && val >= 0)) {
tmp += val;
} else {
return;
}
}
first = false;
if (tok.hasMoreTokens()) {
tmp += ", ";
}
}
m_hiddenLayers = tmp;
}
/**
* @return A string representing the hidden layers, each number is the number
* of nodes on a hidden layer.
*/
public String getHiddenLayers() {
return m_hiddenLayers;
}
/**
* This will set whether A GUI is brought up to allow interaction by the user
* with the neural network during training.
*
* @param a True if gui should be created.
*/
public void setGUI(boolean a) {
m_gui = a;
if (!a) {
setAutoBuild(true);
} else {
setReset(false);
}
}
/**
* @return The true if should show gui.
*/
public boolean getGUI() {
return m_gui;
}
/**
* This will set the size of the validation set.
*
* @param a The size of the validation set, as a percentage of the whole.
*/
public void setValidationSetSize(int a) {
if (a < 0 || a > 99) {
return;
}
m_valSize = a;
}
/**
* @return The percentage size of the validation set.
*/
public int getValidationSetSize() {
return m_valSize;
}
/**
* Set the number of training epochs to perform. Must be greater than 0.
*
* @param n The number of epochs to train through.
*/
public void setTrainingTime(int n) {
if (n > 0) {
m_numEpochs = n;
}
}
/**
* @return The number of epochs to train through.
*/
public int getTrainingTime() {
return m_numEpochs;
}
/**
* Call this function to place a node into the network list.
*
* @param n The node to place in the list.
*/
private void addNode(NeuralConnection n) {
NeuralConnection[] temp1 = new NeuralConnection[m_neuralNodes.length + 1];
for (int noa = 0; noa < m_neuralNodes.length; noa++) {
temp1[noa] = m_neuralNodes[noa];
}
temp1[temp1.length - 1] = n;
m_neuralNodes = temp1;
}
/**
* Call this function to remove the passed node from the list. This will only
* remove the node if it is in the neuralnodes list.
*
* @param n The neuralConnection to remove.
* @return True if removed false if not (because it wasn't there).
*/
private boolean removeNode(NeuralConnection n) {
NeuralConnection[] temp1 = new NeuralConnection[m_neuralNodes.length - 1];
int skip = 0;
for (int noa = 0; noa < m_neuralNodes.length; noa++) {
if (n == m_neuralNodes[noa]) {
skip++;
} else if (!((noa - skip) >= temp1.length)) {
temp1[noa - skip] = m_neuralNodes[noa];
} else {
return false;
}
}
m_neuralNodes = temp1;
return true;
}
/**
* This function sets what the m_numeric flag to represent the passed class it
* also performs the normalization of the attributes if applicable and sets up
* the info to normalize the class. (note that regardless of the options it
* will fill an array with the range and base, set to normalize all attributes
* and the class to be between -1 and 1)
*
* @param inst the instances.
* @return The modified instances. This needs to be done. If the attributes
* are normalized then deep copies will be made of all the instances
* which will need to be passed back out.
*/
private Instances setClassType(Instances inst) throws Exception {
if (inst != null) {
// x bounds
m_attributeRanges = new double[inst.numAttributes()];
m_attributeBases = new double[inst.numAttributes()];
for (int noa = 0; noa < inst.numAttributes(); noa++) {
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < inst.numInstances(); i++) {
if (!inst.instance(i).isMissing(noa)) {
double value = inst.instance(i).value(noa);
if (value < min) {
min = value;
}
if (value > max) {
max = value;
}
}
}
m_attributeRanges[noa] = (max - min) / 2;
m_attributeBases[noa] = (max + min) / 2;
}
if (m_normalizeAttributes) {
for (int i = 0; i < inst.numInstances(); i++) {
Instance currentInstance = inst.instance(i);
double[] instance = new double[inst.numAttributes()];
for (int noa = 0; noa < inst.numAttributes(); noa++) {
if (noa != inst.classIndex()) {
if (m_attributeRanges[noa] != 0) {
instance[noa] = (currentInstance.value(noa) - m_attributeBases[noa]) / m_attributeRanges[noa];
} else {
instance[noa] = currentInstance.value(noa) - m_attributeBases[noa];
}
} else {
instance[noa] = currentInstance.value(noa);
}
}
inst.set(i, new DenseInstance(currentInstance.weight(), instance));
}
}
if (inst.classAttribute().isNumeric()) {
m_numeric = true;
} else {
m_numeric = false;
}
}
return inst;
}
/**
* A function used to stop the code that called buildclassifier from
* continuing on before the user has finished the decision tree.
*
* @param tf True to stop the thread, False to release the thread that is
* waiting there (if one).
*/
public synchronized void blocker(boolean tf) {
if (tf) {
try {
wait();
} catch (InterruptedException e) {
}
} else {
notifyAll();
}
}
/**
* Call this function to update the control panel for the gui.
*/
private void updateDisplay() {
if (m_gui) {
m_controlPanel.m_errorLabel.repaint();
m_controlPanel.m_epochsLabel.repaint();
}
}
/**
* this will reset all the nodes in the network.
*/
private void resetNetwork() {
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].reset();
}
}
/**
* This will cause the output values of all the nodes to be calculated. Note
* that the m_currentInstance is used to calculate these values.
*/
private void calculateOutputs() {
for (int noc = 0; noc < m_numClasses; noc++) {
// get the values.
m_outputs[noc].outputValue(true);
}
}
/**
* This will cause the error values to be calculated for all nodes. Note that
* the m_currentInstance is used to calculate these values. Also the output
* values should have been calculated first.
*
* @return The squared error.
*/
private double calculateErrors() throws Exception {
double ret = 0, temp = 0;
for (int noc = 0; noc < m_numAttributes; noc++) {
// get the errors.
m_inputs[noc].errorValue(true);
}
for (int noc = 0; noc < m_numClasses; noc++) {
temp = m_outputs[noc].errorValue(false);
ret += temp * temp;
}
return ret;
}
/**
* This will cause the weight values to be updated based on the learning rate,
* momentum and the errors that have been calculated for each node.
*
* @param l The learning rate to update with.
* @param m The momentum to update with.
*/
private void updateNetworkWeights(double l, double m) {
for (int noc = 0; noc < m_numClasses; noc++) {
// update weights
m_outputs[noc].updateWeights(l, m);
}
}
/**
* This creates the required input units.
*/
private void setupInputs() throws Exception {
m_inputs = new NeuralEnd[m_numAttributes];
int now = 0;
for (int noa = 0; noa < m_numAttributes + 1; noa++) {
if (m_instances.classIndex() != noa) {
m_inputs[noa - now] = new NeuralEnd(m_instances.attribute(noa).name());
m_inputs[noa - now].setX(.1);
m_inputs[noa - now].setY((noa - now + 1.0) / (m_numAttributes + 1));
m_inputs[noa - now].setLink(true, noa);
} else {
now = 1;
}
}
}
/**
* This creates the required output units.
*/
private void setupOutputs() throws Exception {
m_outputs = new NeuralEnd[m_numClasses];
for (int noa = 0; noa < m_numClasses; noa++) {
if (m_numeric) {
m_outputs[noa] = new NeuralEnd(m_instances.classAttribute().name());
} else {
m_outputs[noa] = new NeuralEnd(m_instances.classAttribute().value(noa));
}
m_outputs[noa].setX(.9);
m_outputs[noa].setY((noa + 1.0) / (m_numClasses + 1));
m_outputs[noa].setLink(false, noa);
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId), m_random,
m_sigmoidUnit);
m_nextId++;
temp.setX(.75);
temp.setY((noa + 1.0) / (m_numClasses + 1));
addNode(temp);
NeuralConnection.connect(temp, m_outputs[noa]);
}
}
/**
* Call this function to automatically generate the hidden units
*/
private void setupHiddenLayer() {
StringTokenizer tok = new StringTokenizer(m_hiddenLayers, ",");
int val = 0; // num of nodes in a layer
int prev = 0; // used to remember the previous layer
int num = tok.countTokens(); // number of layers
String c;
for (int noa = 0; noa < num; noa++) {
// note that I am using the Double to get the value rather than the
// Integer class, because for some reason the Double implementation can
// handle leading white space and the integer version can't!?!
c = tok.nextToken().trim();
if (c.equals("a")) {
val = (m_numAttributes + m_numClasses) / 2;
} else if (c.equals("i")) {
val = m_numAttributes;
} else if (c.equals("o")) {
val = m_numClasses;
} else if (c.equals("t")) {
val = m_numAttributes + m_numClasses;
} else {
val = Double.valueOf(c).intValue();
}
for (int nob = 0; nob < val; nob++) {
NeuralNode temp = new NeuralNode(String.valueOf(m_nextId), m_random,
m_sigmoidUnit);
m_nextId++;
temp.setX(.5 / (num) * noa + .25);
temp.setY((nob + 1.0) / (val + 1));
addNode(temp);
if (noa > 0) {
// then do connections
for (int noc = m_neuralNodes.length - nob - 1 - prev; noc < m_neuralNodes.length
- nob - 1; noc++) {
NeuralConnection.connect(m_neuralNodes[noc], temp);
}
}
}
prev = val;
}
tok = new StringTokenizer(m_hiddenLayers, ",");
c = tok.nextToken();
if (c.equals("a")) {
val = (m_numAttributes + m_numClasses) / 2;
} else if (c.equals("i")) {
val = m_numAttributes;
} else if (c.equals("o")) {
val = m_numClasses;
} else if (c.equals("t")) {
val = m_numAttributes + m_numClasses;
} else {
val = Double.valueOf(c).intValue();
}
if (val == 0) {
for (int noa = 0; noa < m_numAttributes; noa++) {
for (int nob = 0; nob < m_numClasses; nob++) {
NeuralConnection.connect(m_inputs[noa], m_neuralNodes[nob]);
}
}
} else {
for (int noa = 0; noa < m_numAttributes; noa++) {
for (int nob = m_numClasses; nob < m_numClasses + val; nob++) {
NeuralConnection.connect(m_inputs[noa], m_neuralNodes[nob]);
}
}
for (int noa = m_neuralNodes.length - prev; noa < m_neuralNodes.length; noa++) {
for (int nob = 0; nob < m_numClasses; nob++) {
NeuralConnection.connect(m_neuralNodes[noa], m_neuralNodes[nob]);
}
}
}
}
/**
* This will go through all the nodes and check if they are connected to a
* pure output unit. If so they will be set to be linear units. If not they
* will be set to be sigmoid units.
*/
private void setEndsToLinear() {
for (NeuralConnection m_neuralNode : m_neuralNodes) {
if ((m_neuralNode.getType() & NeuralConnection.OUTPUT) == NeuralConnection.OUTPUT) {
((NeuralNode) m_neuralNode).setMethod(m_linearUnit);
} else {
((NeuralNode) m_neuralNode).setMethod(m_sigmoidUnit);
}
}
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/** The instances in the validation set (if any) */
protected transient Instances valSet = null;
/** The number of instances in the validation set (if any) */
protected transient int numInVal = 0;
/** Total weight of the instances in the training set */
protected transient double totalWeight = 0;
/** Total weight of the instances in the validation set (if any) */
protected transient double totalValWeight = 0;
/** Drift off counter */
protected transient double driftOff = 0;
/** To keep track of error */
protected transient double lastRight = Double.POSITIVE_INFINITY;
protected transient double bestError = Double.POSITIVE_INFINITY;
/** Data in original format (in case learning rate gets reset */
protected transient Instances originalFormatData = null;
/**
* Initializes an iterative classifier.
*
* @param data the instances to be used in induction
* @exception Exception if the model cannot be initialized
*/
public void initializeClassifier(Instances data) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
data = new Instances(data);
data.deleteWithMissingClass();
originalFormatData = data;
m_ZeroR = new weka.classifiers.rules.ZeroR();
m_ZeroR.buildClassifier(data);
// only class? -> use ZeroR model
if (data.numAttributes() == 1) {
System.err.println("Cannot build model (only class attribute present in data!), "
+ "using ZeroR model instead!");
m_useDefaultModel = true;
return;
} else {
m_useDefaultModel = false;
}
m_epoch = 0;
m_error = 0;
m_instances = null;
m_currentInstance = null;
m_controlPanel = null;
m_nodePanel = null;
m_outputs = new NeuralEnd[0];
m_inputs = new NeuralEnd[0];
m_numAttributes = 0;
m_numClasses = 0;
m_neuralNodes = new NeuralConnection[0];
m_selected = new ArrayList<NeuralConnection>(4);
m_nextId = 0;
m_stopIt = true;
m_stopped = true;
m_accepted = false;
m_instances = new Instances(data);
m_random = new Random(m_randomSeed);
m_instances.randomize(m_random);
if (m_useNomToBin) {
m_nominalToBinaryFilter = new NominalToBinary();
m_nominalToBinaryFilter.setInputFormat(m_instances);
m_instances = Filter.useFilter(m_instances, m_nominalToBinaryFilter);
}
m_numAttributes = m_instances.numAttributes() - 1;
m_numClasses = m_instances.numClasses();
setClassType(m_instances);
// this sets up the validation set.
// numinval is needed later
numInVal = (int) (m_valSize / 100.0 * m_instances.numInstances());
if (m_valSize > 0) {
if (numInVal == 0) {
numInVal = 1;
}
valSet = new Instances(m_instances, 0, numInVal);
}
// /////////
setupInputs();
setupOutputs();
if (m_autoBuild) {
setupHiddenLayer();
}
// ///////////////////////////
// this sets up the gui for usage
if (m_gui) {
m_win = Utils.getWekaJFrame("Neural Network", null);
m_win.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
boolean k = m_stopIt;
m_stopIt = true;
int well = JOptionPane.showConfirmDialog(m_win, "Are You Sure...\n"
+ "Click Yes To Accept" + " The Neural Network"
+ "\n Click No To Return", "Accept Neural Network",
JOptionPane.YES_NO_OPTION);
if (well == 0) {
m_win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_accepted = true;
blocker(false);
} else {
m_win.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
m_stopIt = k;
}
});
m_win.getContentPane().setLayout(new BorderLayout());
m_nodePanel = new NodePanel();
// without the following two lines, the
// NodePanel.paintComponents(Graphics)
// method will go berserk if the network doesn't fit completely: it will
// get called on a constant basis, using 100% of the CPU
// see the following forum thread:
// http://forum.java.sun.com/thread.jspa?threadID=580929&messageID=2945011
m_nodePanel.setPreferredSize(new Dimension(640, 480));
m_nodePanel.revalidate();
JScrollPane sp = new JScrollPane(m_nodePanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
m_controlPanel = new ControlPanel();
m_win.getContentPane().add(sp, BorderLayout.CENTER);
m_win.getContentPane().add(m_controlPanel, BorderLayout.SOUTH);
m_win.setSize(640, 480);
m_win.setVisible(true);
}
// This sets up the initial state of the gui
if (m_gui) {
blocker(true);
m_controlPanel.m_changeEpochs.setEnabled(false);
m_controlPanel.m_changeLearning.setEnabled(false);
m_controlPanel.m_changeMomentum.setEnabled(false);
}
// For silly situations in which the network gets accepted before training
// commenses
if (m_numeric) {
setEndsToLinear();
}
if (m_accepted) {
return;
}
// connections done.
totalWeight = 0;
totalValWeight = 0;
driftOff = 0;
lastRight = Double.POSITIVE_INFINITY;
bestError = Double.POSITIVE_INFINITY;
// ensure that at least 1 instance is trained through.
if (numInVal == m_instances.numInstances()) {
numInVal--;
}
if (numInVal < 0) {
numInVal = 0;
}
for (int noa = numInVal; noa < m_instances.numInstances(); noa++) {
if (!m_instances.instance(noa).classIsMissing()) {
totalWeight += m_instances.instance(noa).weight();
}
}
if (m_valSize != 0) {
for (int noa = 0; noa < valSet.numInstances(); noa++) {
if (!valSet.instance(noa).classIsMissing()) {
totalValWeight += valSet.instance(noa).weight();
}
}
}
m_stopped = false;
}
/**
* Performs one iteration.
*
* @return false if no further iterations could be performed, true otherwise
* @exception Exception if this iteration fails for unexpected reasons
*/
public boolean next() throws Exception {
if (m_accepted || m_useDefaultModel) { // Has user accepted the network already or do we need to use default model?
return false;
}
m_epoch++;
double right = 0;
for (int nob = numInVal; nob < m_instances.numInstances(); nob++) {
m_currentInstance = m_instances.instance(nob);
if (!m_currentInstance.classIsMissing()) {
// this is where the network updating (and training occurs, for the
// training set
resetNetwork();
calculateOutputs();
double tempRate = m_learningRate * m_currentInstance.weight();
if (m_decay) {
tempRate /= m_epoch;
}
right += (calculateErrors() / m_instances.numClasses())
* m_currentInstance.weight();
updateNetworkWeights(tempRate, m_momentum);
}
}
right /= totalWeight;
if (Double.isInfinite(right) || Double.isNaN(right)) {
if ((!m_reset) || (originalFormatData == null)){
m_instances = null;
throw new Exception("Network cannot train. Try restarting with a smaller learning rate.");
} else {
// reset the network if possible
if (m_learningRate <= Utils.SMALL) {
throw new IllegalStateException("Learning rate got too small ("
+ m_learningRate + " <= " + Utils.SMALL + ")!");
}
double origRate = m_learningRate; // only used for when reset
m_learningRate /= 2;
buildClassifier(originalFormatData);
m_learningRate = origRate;
return false;
}
}
// //////////////////////do validation testing if applicable
if (m_valSize != 0) {
right = 0;
if (valSet == null) {
throw new IllegalArgumentException("Trying to use validation set but validation set is null.");
}
for (int nob = 0; nob < valSet.numInstances(); nob++) {
m_currentInstance = valSet.instance(nob);
if (!m_currentInstance.classIsMissing()) {
// this is where the network updating occurs, for the validation set
resetNetwork();
calculateOutputs();
right += (calculateErrors() / valSet.numClasses()) * m_currentInstance.weight();
// note 'right' could be calculated here just using
// the calculate output values. This would be faster.
// be less modular
}
}
if (right < lastRight) {
if (right < bestError) {
bestError = right;
// save the network weights at this point
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].saveWeights();
}
driftOff = 0;
}
} else {
driftOff++;
}
lastRight = right;
if (driftOff > m_driftThreshold || m_epoch + 1 >= m_numEpochs) {
for (int noc = 0; noc < m_numClasses; noc++) {
m_outputs[noc].restoreWeights();
}
m_accepted = true;
}
right /= totalValWeight;
}
m_error = right;
// shows what the neuralnet is upto if a gui exists.
updateDisplay();
// This junction controls what state the gui is in at the end of each
// epoch, Such as if it is paused, if it is resumable etc...
if (m_gui) {
while ((m_stopIt || (m_epoch >= m_numEpochs && m_valSize == 0)) && !m_accepted) {
m_stopIt = true;
m_stopped = true;
if (m_epoch >= m_numEpochs && m_valSize == 0) {
m_controlPanel.m_startStop.setEnabled(false);
} else {
m_controlPanel.m_startStop.setEnabled(true);
}
m_controlPanel.m_startStop.setText("Start");
m_controlPanel.m_startStop.setActionCommand("Start");
m_controlPanel.m_changeEpochs.setEnabled(true);
m_controlPanel.m_changeLearning.setEnabled(true);
m_controlPanel.m_changeMomentum.setEnabled(true);
blocker(true);
if (m_numeric) {
setEndsToLinear();
}
}
m_controlPanel.m_changeEpochs.setEnabled(false);
m_controlPanel.m_changeLearning.setEnabled(false);
m_controlPanel.m_changeMomentum.setEnabled(false);
m_stopped = false;
// if the network has been accepted stop the training loop
if (m_accepted) {
return false;
}
}
if (m_accepted) {
return false;
}
if (m_epoch < m_numEpochs) {
return true; // We can keep iterating
} else {
return false;
}
}
/**
* Signal end of iterating, useful for any house-keeping/cleanup
*
* @exception Exception if cleanup fails
*/
public void done() throws Exception {
if (m_gui) {
m_win.dispose();
m_controlPanel = null;
m_nodePanel = null;
}
if (!m_useDefaultModel) {
m_instances = new Instances(m_instances, 0);
}
m_currentInstance = null;
originalFormatData = null;
}
/**
* Call this function to build and train a neural network for the training
* data provided.
*
* @param i The training data.
* @throws Exception if can't build classification properly.
*/
@Override
public void buildClassifier(Instances i) throws Exception {
// Initialize classifier
initializeClassifier(i);
// For the given number of iterations
while (next()) {
}
// Clean up
done();
}
/**
* Call this function to predict the class of an instance once a
* classification model has been built with the buildClassifier call.
*
* @param i The instance to classify.
* @return A double array filled with the probabilities of each class type.
* @throws Exception if can't classify instance.
*/
@Override
public double[] distributionForInstance(Instance i) throws Exception {
// default model?
if (m_useDefaultModel) {
return m_ZeroR.distributionForInstance(i);
}
if (m_useNomToBin) {
m_nominalToBinaryFilter.input(i);
m_currentInstance = m_nominalToBinaryFilter.output();
} else {
m_currentInstance = i;
}
// Make a copy of the instance so that it isn't modified
m_currentInstance = (Instance) m_currentInstance.copy();
if (m_normalizeAttributes) {
double[] instance = new double[m_currentInstance.numAttributes()];
for (int noa = 0; noa < m_instances.numAttributes(); noa++) {
if (noa != m_instances.classIndex()) {
if (m_attributeRanges[noa] != 0) {
instance[noa] = (m_currentInstance.value(noa) - m_attributeBases[noa]) / m_attributeRanges[noa];
} else {
instance[noa] = m_currentInstance.value(noa) - m_attributeBases[noa];
}
} else {
instance[noa] = m_currentInstance.value(noa);
}
}
m_currentInstance = new DenseInstance(m_currentInstance.weight(), instance);
m_currentInstance.setDataset(m_instances);
}
resetNetwork();
// since all the output values are needed.
// They are calculated manually here and the values collected.
double[] theArray = new double[m_numClasses];
for (int noa = 0; noa < m_numClasses; noa++) {
theArray[noa] = m_outputs[noa].outputValue(true);
}
if (m_instances.classAttribute().isNumeric()) {
return theArray;
}
// now normalize the array
double count = 0;
for (int noa = 0; noa < m_numClasses; noa++) {
count += theArray[noa];
}
if (count <= 0) {
return m_ZeroR.distributionForInstance(i);
}
for (int noa = 0; noa < m_numClasses; noa++) {
theArray[noa] /= count;
}
return theArray;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(14);
newVector.addElement(new Option(
"\tLearning Rate for the backpropagation algorithm.\n"
+ "\t(Value should be between 0 - 1, Default = 0.3).", "L", 1,
"-L <learning rate>"));
newVector.addElement(new Option(
"\tMomentum Rate for the backpropagation algorithm.\n"
+ "\t(Value should be between 0 - 1, Default = 0.2).", "M", 1,
"-M <momentum>"));
newVector.addElement(new Option("\tNumber of epochs to train through.\n"
+ "\t(Default = 500).", "N", 1, "-N <number of epochs>"));
newVector.addElement(new Option(
"\tPercentage size of validation set to use to terminate\n"
+ "\ttraining (if this is non zero it can pre-empt num of epochs.\n"
+ "\t(Value should be between 0 - 100, Default = 0).", "V", 1,
"-V <percentage size of validation set>"));
newVector.addElement(new Option(
"\tThe value used to seed the random number generator\n"
+ "\t(Value should be >= 0 and and a long, Default = 0).", "S", 1,
"-S <seed>"));
newVector.addElement(new Option(
"\tThe consequetive number of errors allowed for validation\n"
+ "\ttesting before the netwrok terminates.\n"
+ "\t(Value should be > 0, Default = 20).", "E", 1,
"-E <threshold for number of consequetive errors>"));
newVector.addElement(new Option("\tGUI will be opened.\n"
+ "\t(Use this to bring up a GUI).", "G", 0, "-G"));
newVector.addElement(new Option(
"\tAutocreation of the network connections will NOT be done.\n"
+ "\t(This will be ignored if -G is NOT set)", "A", 0, "-A"));
newVector.addElement(new Option(
"\tA NominalToBinary filter will NOT automatically be used.\n"
+ "\t(Set this to not use a NominalToBinary filter).", "B", 0, "-B"));
newVector.addElement(new Option(
"\tThe hidden layers to be created for the network.\n"
+ "\t(Value should be a list of comma separated Natural \n"
+ "\tnumbers or the letters 'a' = (attribs + classes) / 2, \n"
+ "\t'i' = attribs, 'o' = classes, 't' = attribs .+ classes)\n"
+ "\tfor wildcard values, Default = a).", "H", 1,
"-H <comma seperated numbers for nodes on each layer>"));
newVector.addElement(new Option(
"\tNormalizing a numeric class will NOT be done.\n"
+ "\t(Set this to not normalize the class if it's numeric).", "C", 0,
"-C"));
newVector.addElement(new Option(
"\tNormalizing the attributes will NOT be done.\n"
+ "\t(Set this to not normalize the attributes).", "I", 0, "-I"));
newVector.addElement(new Option(
"\tReseting the network will NOT be allowed.\n"
+ "\t(Set this to not allow the network to reset).", "R", 0, "-R"));
newVector.addElement(new Option("\tLearning rate decay will occur.\n"
+ "\t(Set this to cause the learning rate to decay).", "D", 0, "-D"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -L <learning rate>
* Learning Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.3).
* </pre>
*
* <pre>
* -M <momentum>
* Momentum Rate for the backpropagation algorithm.
* (Value should be between 0 - 1, Default = 0.2).
* </pre>
*
* <pre>
* -N <number of epochs>
* Number of epochs to train through.
* (Default = 500).
* </pre>
*
* <pre>
* -V <percentage size of validation set>
* Percentage size of validation set to use to terminate
* training (if this is non zero it can pre-empt num of epochs.
* (Value should be between 0 - 100, Default = 0).
* </pre>
*
* <pre>
* -S <seed>
* The value used to seed the random number generator
* (Value should be >= 0 and and a long, Default = 0).
* </pre>
*
* <pre>
* -E <threshold for number of consequetive errors>
* The consequetive number of errors allowed for validation
* testing before the netwrok terminates.
* (Value should be > 0, Default = 20).
* </pre>
*
* <pre>
* -G
* GUI will be opened.
* (Use this to bring up a GUI).
* </pre>
*
* <pre>
* -A
* Autocreation of the network connections will NOT be done.
* (This will be ignored if -G is NOT set)
* </pre>
*
* <pre>
* -B
* A NominalToBinary filter will NOT automatically be used.
* (Set this to not use a NominalToBinary filter).
* </pre>
*
* <pre>
* -H <comma seperated numbers for nodes on each layer>
* The hidden layers to be created for the network.
* (Value should be a list of comma separated Natural
* numbers or the letters 'a' = (attribs + classes) / 2,
* 'i' = attribs, 'o' = classes, 't' = attribs .+ classes)
* for wildcard values, Default = a).
* </pre>
*
* <pre>
* -C
* Normalizing a numeric class will NOT be done.
* (Set this to not normalize the class if it's numeric).
* </pre>
*
* <pre>
* -I
* Normalizing the attributes will NOT be done.
* (Set this to not normalize the attributes).
* </pre>
*
* <pre>
* -R
* Reseting the network will NOT be allowed.
* (Set this to not allow the network to reset).
* </pre>
*
* <pre>
* -D
* Learning rate decay will occur.
* (Set this to cause the learning rate to decay).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
// the defaults can be found here!!!!
String learningString = Utils.getOption('L', options);
if (learningString.length() != 0) {
setLearningRate((new Double(learningString)).doubleValue());
} else {
setLearningRate(0.3);
}
String momentumString = Utils.getOption('M', options);
if (momentumString.length() != 0) {
setMomentum((new Double(momentumString)).doubleValue());
} else {
setMomentum(0.2);
}
String epochsString = Utils.getOption('N', options);
if (epochsString.length() != 0) {
setTrainingTime(Integer.parseInt(epochsString));
} else {
setTrainingTime(500);
}
String valSizeString = Utils.getOption('V', options);
if (valSizeString.length() != 0) {
setValidationSetSize(Integer.parseInt(valSizeString));
} else {
setValidationSetSize(0);
}
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
setSeed(Integer.parseInt(seedString));
} else {
setSeed(0);
}
String thresholdString = Utils.getOption('E', options);
if (thresholdString.length() != 0) {
setValidationThreshold(Integer.parseInt(thresholdString));
} else {
setValidationThreshold(20);
}
String hiddenLayers = Utils.getOption('H', options);
if (hiddenLayers.length() != 0) {
setHiddenLayers(hiddenLayers);
} else {
setHiddenLayers("a");
}
if (Utils.getFlag('G', options)) {
setGUI(true);
} else {
setGUI(false);
} // small note. since the gui is the only option that can change the other
// options this should be set first to allow the other options to set
// properly
if (Utils.getFlag('A', options)) {
setAutoBuild(false);
} else {
setAutoBuild(true);
}
if (Utils.getFlag('B', options)) {
setNominalToBinaryFilter(false);
} else {
setNominalToBinaryFilter(true);
}
if (Utils.getFlag('C', options)) {
setNormalizeNumericClass(false);
} else {
setNormalizeNumericClass(true);
}
if (Utils.getFlag('I', options)) {
setNormalizeAttributes(false);
} else {
setNormalizeAttributes(true);
}
if (Utils.getFlag('R', options)) {
setReset(false);
} else {
setReset(true);
}
if (Utils.getFlag('D', options)) {
setDecay(true);
} else {
setDecay(false);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of NeuralNet.
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-L");
options.add("" + getLearningRate());
options.add("-M");
options.add("" + getMomentum());
options.add("-N");
options.add("" + getTrainingTime());
options.add("-V");
options.add("" + getValidationSetSize());
options.add("-S");
options.add("" + getSeed());
options.add("-E");
options.add("" + getValidationThreshold());
options.add("-H");
options.add(getHiddenLayers());
if (getGUI()) {
options.add("-G");
}
if (!getAutoBuild()) {
options.add("-A");
}
if (!getNominalToBinaryFilter()) {
options.add("-B");
}
if (!getNormalizeNumericClass()) {
options.add("-C");
}
if (!getNormalizeAttributes()) {
options.add("-I");
}
if (!getReset()) {
options.add("-R");
}
if (getDecay()) {
options.add("-D");
}
Collections.addAll(options, super.getOptions());
return options.toArray(new String[0]);
}
/**
* @return string describing the model.
*/
@Override
public String toString() {
// only ZeroR model?
if (m_useDefaultModel) {
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
buf.append(this.getClass().getName().replaceAll(".*\\.", "")
.replaceAll(".", "=")
+ "\n\n");
buf
.append("Warning: No model could be built, hence ZeroR model is used:\n\n");
buf.append(m_ZeroR.toString());
return buf.toString();
}
StringBuffer model = new StringBuffer(m_neuralNodes.length * 100);
// just a rough size guess
NeuralNode con;
double[] weights;
NeuralConnection[] inputs;
for (NeuralConnection m_neuralNode : m_neuralNodes) {
con = (NeuralNode) m_neuralNode; // this would need a change
// for items other than nodes!!!
weights = con.getWeights();
inputs = con.getInputs();
if (con.getMethod() instanceof SigmoidUnit) {
model.append("Sigmoid ");
} else if (con.getMethod() instanceof LinearUnit) {
model.append("Linear ");
}
model.append("Node " + con.getId() + "\n Inputs Weights\n");
model.append(" Threshold " + weights[0] + "\n");
for (int nob = 1; nob < con.getNumInputs() + 1; nob++) {
if ((inputs[nob - 1].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) {
model.append(" Attrib "
+ m_instances.attribute(((NeuralEnd) inputs[nob - 1]).getLink())
.name() + " " + weights[nob] + "\n");
} else {
model.append(" Node " + inputs[nob - 1].getId() + " "
+ weights[nob] + "\n");
}
}
}
// now put in the ends
for (NeuralEnd m_output : m_outputs) {
inputs = m_output.getInputs();
model.append("Class "
+ m_instances.classAttribute().value(m_output.getLink())
+ "\n Input\n");
for (int nob = 0; nob < m_output.getNumInputs(); nob++) {
if ((inputs[nob].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) {
model.append(" Attrib "
+ m_instances.attribute(((NeuralEnd) inputs[nob]).getLink()).name()
+ "\n");
} else {
model.append(" Node " + inputs[nob].getId() + "\n");
}
}
}
return model.toString();
}
/**
* This will return a string describing the classifier.
*
* @return The string.
*/
public String globalInfo() {
return "A Classifier that uses backpropagation to classify instances.\n"
+ "This network can be built by hand, created by an algorithm or both. "
+ "The network can also be monitored and modified during training time. "
+ "The nodes in this network are all sigmoid (except for when the class "
+ "is numeric in which case the the output nodes become unthresholded "
+ "linear units).";
}
/**
* @return a string to describe the learning rate option.
*/
public String learningRateTipText() {
return "The amount the" + " weights are updated.";
}
/**
* @return a string to describe the momentum option.
*/
public String momentumTipText() {
return "Momentum applied to the weights during updating.";
}
/**
* @return a string to describe the AutoBuild option.
*/
public String autoBuildTipText() {
return "Adds and connects up hidden layers in the network.";
}
/**
* @return a string to describe the random seed option.
*/
public String seedTipText() {
return "Seed used to initialise the random number generator."
+ "Random numbers are used for setting the initial weights of the"
+ " connections betweem nodes, and also for shuffling the training data.";
}
/**
* @return a string to describe the validation threshold option.
*/
public String validationThresholdTipText() {
return "Used to terminate validation testing."
+ "The value here dictates how many times in a row the validation set"
+ " error can get worse before training is terminated.";
}
/**
* @return a string to describe the GUI option.
*/
public String GUITipText() {
return "Brings up a gui interface."
+ " This will allow the pausing and altering of the nueral network"
+ " during training.\n\n"
+ "* To add a node left click (this node will be automatically selected,"
+ " ensure no other nodes were selected).\n"
+ "* To select a node left click on it either while no other node is"
+ " selected or while holding down the control key (this toggles that"
+ " node as being selected and not selected.\n"
+ "* To connect a node, first have the start node(s) selected, then click"
+ " either the end node or on an empty space (this will create a new node"
+ " that is connected with the selected nodes). The selection status of"
+ " nodes will stay the same after the connection. (Note these are"
+ " directed connections, also a connection between two nodes will not"
+ " be established more than once and certain connections that are"
+ " deemed to be invalid will not be made).\n"
+ "* To remove a connection select one of the connected node(s) in the"
+ " connection and then right click the other node (it does not matter"
+ " whether the node is the start or end the connection will be removed"
+ ").\n"
+ "* To remove a node right click it while no other nodes (including it)"
+ " are selected. (This will also remove all connections to it)\n."
+ "* To deselect a node either left click it while holding down control,"
+ " or right click on empty space.\n"
+ "* The raw inputs are provided from the labels on the left.\n"
+ "* The red nodes are hidden layers.\n"
+ "* The orange nodes are the output nodes.\n"
+ "* The labels on the right show the class the output node represents."
+ " Note that with a numeric class the output node will automatically be"
+ " made into an unthresholded linear unit.\n\n"
+ "Alterations to the neural network can only be done while the network"
+ " is not running, This also applies to the learning rate and other"
+ " fields on the control panel.\n\n"
+ "* You can accept the network as being finished at any time.\n"
+ "* The network is automatically paused at the beginning.\n"
+ "* There is a running indication of what epoch the network is up to"
+ " and what the (rough) error for that epoch was (or for"
+ " the validation if that is being used). Note that this error value"
+ " is based on a network that changes as the value is computed."
+ " (also depending on whether"
+ " the class is normalized will effect the error reported for numeric"
+ " classes.\n"
+ "* Once the network is done it will pause again and either wait to be"
+ " accepted or trained more.\n\n"
+ "Note that if the gui is not set the network will not require any"
+ " interaction.\n";
}
/**
* @return a string to describe the validation size option.
*/
public String validationSetSizeTipText() {
return "The percentage size of the validation set."
+ "(The training will continue until it is observed that"
+ " the error on the validation set has been consistently getting"
+ " worse, or if the training time is reached).\n"
+ "If This is set to zero no validation set will be used and instead"
+ " the network will train for the specified number of epochs.";
}
/**
* @return a string to describe the learning rate option.
*/
public String trainingTimeTipText() {
return "The number of epochs to train through."
+ " If the validation set is non-zero then it can terminate the network"
+ " early";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String nominalToBinaryFilterTipText() {
return "This will preprocess the instances with the filter."
+ " This could help improve performance if there are nominal attributes"
+ " in the data.";
}
/**
* @return a string to describe the hidden layers in the network.
*/
public String hiddenLayersTipText() {
return "This defines the hidden layers of the neural network."
+ " This is a list of positive whole numbers. 1 for each hidden layer."
+ " Comma seperated. To have no hidden layers put a single 0 here."
+ " This will only be used if autobuild is set. There are also wildcard"
+ " values 'a' = (attribs + classes) / 2, 'i' = attribs, 'o' = classes"
+ " , 't' = attribs + classes.";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String normalizeNumericClassTipText() {
return "This will normalize the class if it's numeric."
+ " This could help improve performance of the network, It normalizes"
+ " the class to be between -1 and 1. Note that this is only internally"
+ ", the output will be scaled back to the original range.";
}
/**
* @return a string to describe the nominal to binary option.
*/
public String normalizeAttributesTipText() {
return "This will normalize the attributes."
+ " This could help improve performance of the network."
+ " This is not reliant on the class being numeric. This will also"
+ " normalize nominal attributes as well (after they have been run"
+ " through the nominal to binary filter if that is in use) so that the"
+ " nominal values are between -1 and 1";
}
/**
* @return a string to describe the Reset option.
*/
public String resetTipText() {
return "This will allow the network to reset with a lower learning rate."
+ " If the network diverges from the answer this will automatically"
+ " reset the network with a lower learning rate and begin training"
+ " again. This option is only available if the gui is not set. Note"
+ " that if the network diverges but isn't allowed to reset it will"
+ " fail the training process and return an error message.";
}
/**
* @return a string to describe the Decay option.
*/
public String decayTipText() {
return "This will cause the learning rate to decrease."
+ " This will divide the starting learning rate by the epoch number, to"
+ " determine what the current learning rate should be. This may help"
+ " to stop the network from diverging from the target output, as well"
+ " as improve general performance. Note that the decaying learning"
+ " rate will not be shown in the gui, only the original learning rate"
+ ". If the learning rate is changed in the gui, this is treated as the"
+ " starting learning rate.";
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14497 $");
}
}
| [
"siinamalakouti@gmail.com"
] | siinamalakouti@gmail.com |
bd622e13b39bf8b37efd65b9248fe31d666abd55 | bc6ab85b295e6f6a50452037f79bcf492557d3b5 | /src/main/java/com/nel/chan/dsalgo/array/rearrange/MultiArrayReverse.java | 1809f88925e73c96d2c371fb849f538e819b9d08 | [] | no_license | chandrakanth-nelge/dsalgo | 23ce2c91031667736190fb9b09e386967e65076b | 83b479b66988d788c941f4e6763f10100568cc20 | refs/heads/master | 2022-05-01T20:10:17.551085 | 2022-03-16T07:24:34 | 2022-03-16T07:24:34 | 232,068,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,336 | java | package com.nel.chan.dsalgo.array.rearrange;
import java.util.Arrays;
import java.util.Scanner;
public class MultiArrayReverse {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int rowCount = getRowCount();
int colCount = getColCount();
int[][] mulDimenArr = readMultiDimensionalArray(rowCount, colCount);
System.out.println();
printMultiDimensionalArray(mulDimenArr, rowCount, colCount);
System.out.println();
reverseMultiDimensionalArray(mulDimenArr, rowCount, colCount);
System.out.println();
in.close();
}
private static int[][] readMultiDimensionalArray(int rowCount, int colCount) {
System.out.println("Enter multi dimensional array elements");
int[][] mulDimenArr = new int[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
mulDimenArr[i][j] = in.nextInt();
}
}
return mulDimenArr;
}
private static void printMultiDimensionalArray(int[][] mulDimenArr, int rowCount, int colCount) {
System.out.println("Printing multi dimensional array elements");
for (int i = 0; i < rowCount; i++) {
System.out.print("[");
for (int j = 0; j < colCount; j++) {
if (j == colCount - 1) {
System.out.print(mulDimenArr[i][j]);
} else {
System.out.print(mulDimenArr[i][j] + ", ");
}
}
System.out.print("]");
System.out.println();
}
}
private static void reverseMultiDimensionalArray(int[][] mulDimenArr, int rowCount, int colCount) {
System.out.println("Reversing multi dimensional array");
for (int i = 0; i < colCount; i++) {
System.out.print("[");
for (int j = 0; j < rowCount; j++) {
if (j == rowCount - 1) {
System.out.print(mulDimenArr[j][i]);
} else {
System.out.print(mulDimenArr[j][i] + ", ");
}
}
System.out.print("]");
System.out.println();
}
}
@SuppressWarnings("unused")
private static void printMultiDimensionalArray(int[][] mulDimenArr) {
System.out.println("Printing multi dimensional array elements");
for (int[] rowArr : mulDimenArr) {
System.out.println(Arrays.toString(rowArr));
}
}
private static int getRowCount() {
System.out.println("Enetr row count");
return in.nextInt();
}
private static int getColCount() {
System.out.println("Enetr column count");
return in.nextInt();
}
} | [
"chandrakanth@techmojo.in"
] | chandrakanth@techmojo.in |
4320f9fbf5069b34d30aa2c81a2885bbf1f2ca08 | 4523f35d6264b007b85853b4e95b6e890b6e60f5 | /src/main/java/top/wsure/bot/utils/DynamicEnumUtils.java | 2156aa55821136eb4a72b1ee22af58c6a17e5fdd | [] | no_license | WsureWarframe/ws-jcq | 7fd751eb9db37a110311a94af6841ec22d7a64fc | 46bd364e88519d00f08104e4132ba12318ad7f05 | refs/heads/master | 2023-03-05T12:51:51.205940 | 2021-02-15T18:03:50 | 2021-02-15T18:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,393 | java | package top.wsure.bot.utils;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
import top.wsure.bot.common.cache.CacheManagerImpl;
import top.wsure.bot.common.cache.EntityCache;
import top.wsure.bot.common.enums.CacheEnum;
public class DynamicEnumUtils {
private static final ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException,
IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException,
IllegalAccessException {
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException {
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException {
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes,
Object[] additionalValues) throws Exception {
Object[] params = new Object[additionalValues.length + 2];
params[0] = value;
params[1] = ordinal;
System.arraycopy(additionalValues, 0, params, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(params));
}
/**
* Add an enum instance to the enum class given as argument
*
* @param <T> the type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName,Class<?>[] classes,Object[] args) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(),
classes, // could be used to pass values to the enum constuctor if needed
args); // could be used to pass values to the enum constuctor if needed
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* TestEnum And Test Main
*/
@AllArgsConstructor
@Getter
@ToString
private static enum TestEnum {
a("aa"),
b("bb"),
c("cc");
private String test;
};
public static void main(String[] args) {
// Dynamically add 3 new enum instances d, e, f to TestEnum
addEnum(TestEnum.class, "d",new Class[]{String.class},new Object[]{"dd"});
addEnum(TestEnum.class, "e",new Class[]{String.class},new Object[]{"ee"});
addEnum(TestEnum.class, "f",new Class[]{String.class},new Object[]{"ff"});
addEnum(CacheEnum.class,"TestCache",
new Class[]{String.class},
new Object[]{"test"});
CacheManagerImpl cache = CacheEnum.getManager("test");
cache.putCache("11","22",100L);
System.out.println(cache.getCacheDataByKey("11").toString());
// Run a few tests just to show it works OK.
System.out.println(Arrays.deepToString(TestEnum.values()));
// Shows : [a, b, c, d, e, f]
}
}
| [
"root@wsure.top"
] | root@wsure.top |
400839822eaee8ff33858b2fc5d72039be8a5f80 | 5ecc519431b0ccfd9895306c79dab89288d75ec9 | /JAVA/basicAlgrithms/ShellSort.java | 647c07bd5c47542b0942c4ac56cc4596f1dc09a7 | [] | no_license | changlongG/Algorithms | d07b3e0eccbf015a543d96ae0d777dfcbd144543 | 89316f5260996d4cacba0d42182026387add1ef9 | refs/heads/master | 2020-04-17T10:47:02.810092 | 2019-03-13T02:47:08 | 2019-03-13T02:47:08 | 166,513,811 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package algorithm;
public class ShellSort {
public static int[] shellSort(int[] array) {
int increment = array.length / 3;
while (true) {
// System.out.println(increment);
int index = 0;
while (index < array.length - increment) {
for (int i = index; i >= 0 && i + increment < array.length; i--) {
if (array[i] > array[i + increment]) {
int temp = array[i];
array[i] = array[i + increment];
array[i + increment] = temp;
}
}
index++;
}
if (increment == 1) {
break;
}
increment = increment / 3;
}
return array;
}
public static void main(String[] args) {
int[] array = { 4, 5, 3, 7, 9, 5, 8, 11, -1, 9, 2, 5, 11, 29, 4 };
array = shellSort(array);
for (int i : array) {
System.out.print(i + ", ");
}
}
}
| [
"changlongloveu@gmail.com"
] | changlongloveu@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.