text
stringlengths 10
2.72M
|
|---|
package firstAssignment;
public abstract class Employee {
public int grossSalary;
public int incomeTax;
public int netSalary;
abstract void calculateNetSalary();
abstract void displayNetSalary();
}
class Manager extends Employee{
public Manager(int grossSalary,int incomeTax) {
this.grossSalary=grossSalary;
this.incomeTax=incomeTax;
}
void calculateNetSalary() {
netSalary=grossSalary-incomeTax;
}
void displayNetSalary() {
System.out.println("The total net salary of the manager is:"+netSalary);
}
}
class Clerk extends Employee{
public Clerk(int grossSalary,int incomeTax) {
this.grossSalary=grossSalary;
this.incomeTax=incomeTax;
}
void calculateNetSalary() {
netSalary=grossSalary-incomeTax;
}
void displayNetSalary() {
System.out.println("The total net salary of the clerk is:"+netSalary);
}
}
class TestAbstraction{
public static void main(String args[]){
Employee m=new Manager(20000,2000);
Employee c=new Clerk(15000,1000);
m.calculateNetSalary();
m.displayNetSalary();
c.calculateNetSalary();
c.displayNetSalary();
}
}
|
package com.zaiou.common.db;
import com.zaiou.common.db.annotation.Column;
import com.zaiou.common.db.annotation.Table;
import com.zaiou.common.mybatis.po.Po;
import com.zaiou.common.utils.CamelCaseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import java.lang.reflect.Field;
import java.util.*;
/**
* @Description: 拼接sql
* @auther: LB 2018/9/19 16:24
* @modify: LB 2018/9/19 16:24
*/
@Slf4j
public class DBProvider {
/**
* 插入数据PO对象不为空的属性
* @param po
* @return
*/
public String insertNotNull(Po po) {
// 获取表名
String tableName = tableName(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName || notNullfieldMap.isEmpty()) {
throw new RuntimeException("PO属性中未定义表名或属性字段!");
}
// 拼接查询的字段
Set<String> keySet = notNullfieldMap.keySet();
StringBuilder columns = new StringBuilder();
StringBuilder values = new StringBuilder();
for (String key : keySet) {
if (columns.length() > 0) {
columns.append(",");
values.append(",");
}
columns.append(notNullfieldMap.get(key));
if ("create_time".equals(notNullfieldMap.get(key))) {
values.append("CURRENT_TIMESTAMP");
} else {
values.append("#{").append(key).append("}");
}
}
SQL sql = new SQL();
sql.INSERT_INTO(tableName);
sql.VALUES(columns.toString(), values.toString());
return sql.toString();
}
/**
* PO中属性不为null的进行AND条件查询
* @param po
* @return
*/
public String selectNotNullAnd(Po po) {
return selectNotNullAndOrder(po, null);
}
/**
* PO中属性不为null的进行AND条件查询,并排序
* @param po
* @param orderSql
* @return
*/
public String selectNotNullAndOrder(Po po, String orderSql) {
// 获取表名
String tableName = tableName(po);
// 获取所有字段与PO属性对应Map
Map<String, String> allFieldMap = allFieldMap(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName) {
throw new RuntimeException("PO属性中未定义表名或属性字段!");
}
StringBuilder columns = new StringBuilder();
StringBuilder where = new StringBuilder();
// 拼接查询的字段
Set<String> keySet = allFieldMap.keySet();
for (String key : keySet) {
if (columns.length() > 0) {
columns.append(",");
}
columns.append(allFieldMap.get(key)).append(" as ").append(key.toUpperCase());
}
// 根据PO属性不为空拼接过滤条件
Set<String> keySet2 = notNullfieldMap.keySet();
for (String key : keySet2) {
if (where.length() > 0) {
where.append(" and ");
}
where.append(notNullfieldMap.get(key)).append(" = #{").append(key).append("}");
}
SQL sql = new SQL();
sql.SELECT(columns.toString());
sql.FROM(tableName);
if (where.length() > 0) {
sql.WHERE(where.toString());
}
if (orderSql != null && orderSql.length() > 0) {
sql.ORDER_BY(orderSql);
}
return sql.toString();
}
/**
* PO中属性不为null的进行AND条件查询
* @param param
* @return
*/
public String selectPageNotNull(Map<String, Object> param) {
Po po = (Po) param.get("po");
// 获取表名
String tableName = tableName(po);
// 获取所有字段与PO属性对应Map
Map<String, String> allFieldMap = allFieldMap(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName) {
throw new RuntimeException("PO属性中未定义表名或属性字段!");
}
StringBuilder columns = new StringBuilder();
StringBuilder where = new StringBuilder();
// 拼接查询的字段
Set<String> keySet = allFieldMap.keySet();
for (String key : keySet) {
if (columns.length() > 0) {
columns.append(",");
}
columns.append(allFieldMap.get(key)).append(" as ").append(key);
}
// 根据PO属性不为空拼接过滤条件
Set<String> keySet2 = notNullfieldMap.keySet();
try {
for (String key : keySet2) {
if (where.length() > 0) {
where.append(" and ");
}
where.append(notNullfieldMap.get(key)).append(" = #{").append(key).append("}");
Field field = po.getClass().getDeclaredField(key);
field.setAccessible(true);
Object value = field.get(po);
param.put(key, value);
}
} catch (Exception e) {
log.error("无法获取Po属性值", e);
}
// 删除po
param.remove("po");
SQL sql = new SQL();
sql.SELECT(columns.toString());
sql.FROM(tableName);
if (where.length() > 0) {
sql.WHERE(where.toString());
}
return sql.toString() + " LIMIT #{limit} OFFSET #{offset} ";
}
/**
* 插入数据PO对象不为空的属性
* @param po
* @return
*/
public String deleteNotNull(Po po) {
// 获取表名
String tableName = tableName(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName || notNullfieldMap.isEmpty()) {
throw new RuntimeException("PO属性中未定义表名或属性字段!");
}
StringBuilder where = new StringBuilder();
// 根据PO属性不为空拼接过滤条件
Set<String> keySet = notNullfieldMap.keySet();
for (String key : keySet) {
if (where.length() > 0) {
where.append(" and ");
}
where.append(notNullfieldMap.get(key)).append(" = #{").append(key).append("}");
}
SQL sql = new SQL();
sql.DELETE_FROM(tableName);
sql.WHERE(where.toString());
return sql.toString();
}
/**
* 根据PO对象的ID属性更新操作
* @param po
* @return
*/
public String updateByIdNotNull(Po po) {
// 获取表名
String tableName = tableName(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName || notNullfieldMap.size() < 1) {
throw new RuntimeException("PO属性中未定义表名或更新的属性字段!");
}
if (!notNullfieldMap.containsKey("id")) {
throw new RuntimeException("update操作必须存在id属性!");
}
String where = "id=#{id}";
StringBuilder sets = new StringBuilder();
// 根据PO属性不为空拼接过滤条件
Set<String> keySet = notNullfieldMap.keySet();
for (String key : keySet) {
if (!key.equals("id")) {
if (sets.length() > 0) {
sets.append(",");
}
sets.append(notNullfieldMap.get(key)).append("=#{").append(key).append("}");
}
}
if (sets.length() < 1) {
sets.append("id=#{id}");
}
SQL sql = new SQL();
sql.UPDATE(tableName);
sql.SET(sets.toString());
sql.WHERE(where);
return sql.toString();
}
/**
* PO中属性不为null的进行AND条件进行count数据
* @param po
* @return
*/
public String countNotNullAnd(Po po) {
// 获取表名
String tableName = tableName(po);
// 获取所有不为空的PO属性对应字段名的Map
Map<String, String> notNullfieldMap = notNullFieldMap(po);
if (null == tableName) {
throw new RuntimeException("PO属性中未定义表名或属性字段!");
}
StringBuilder columns = new StringBuilder("count(1)");
StringBuilder where = new StringBuilder();
// 根据PO属性不为空拼接过滤条件
Set<String> keySet2 = notNullfieldMap.keySet();
for (String key : keySet2) {
if (where.length() > 0) {
where.append(" and ");
}
where.append(notNullfieldMap.get(key)).append(" = #{").append(key).append("}");
}
SQL sql = new SQL();
sql.SELECT(columns.toString());
sql.FROM(tableName);
if (where.length() > 0) {
sql.WHERE(where.toString());
}
return sql.toString();
}
/**
* 根据po取表名
* @param po
* @return
*/
private String tableName(Po po) {
Table annotation = po.getClass().getAnnotation(Table.class);
if (null == annotation) {
// 如果不包含Table注解,直接取PO类名,转换成下划线命名
String className = po.getClass().getSimpleName();
if (className.endsWith("Po")) {
// 如果Po结尾,去掉Po
className = className.substring(0, className.length() - 2);
}
String tableName = CamelCaseUtils.toUnderlineName(className);
if (tableName.endsWith("_po")) {
return tableName.substring(0, tableName.indexOf("_po"));
}
return tableName;
} else {
// 如果包含Table注解,取注解名称
return annotation.value();
}
}
/**
* 根据PO获取所有属性和表字段映射关系
* @param po
* @return
*/
private Map<String, String> allFieldMap(Po po) {
Map<String, String> fieldMap = new HashMap<String, String>();
Field[] fields = po.getClass().getDeclaredFields();
for (Field f : fields) {
if (!f.getName().equals("serialVersionUID")) {
fieldMap.put(f.getName(), getFieldName(f));
}
}
return fieldMap;
}
/**
* 根据PO获取所有不为空的属性和表字段映射关系
* @param po
* @return
*/
private Map<String, String> notNullFieldMap(Po po) {
Map<String, String> notNullfieldMap = new HashMap<String, String>();
Field[] fields = getDeclaredField(po);
boolean fieldIsNotNull;
for (Field f : fields) {
try {
f.setAccessible(true);
if (f.getName().equals("serialVersionUID")) {
continue;
}
fieldIsNotNull = (null != f.get(po));
if (fieldIsNotNull) {
notNullfieldMap.put(f.getName(), getFieldName(f));
}
} catch (IllegalArgumentException e) {
log.error("获取po对象值失败", e);
} catch (IllegalAccessException e) {
log.error("无法po获取对象值", e);
}
}
return notNullfieldMap;
}
/**
* 获取Po中所有字段
* @param po
* @return
*/
public Field[] getDeclaredField(Po po) {
Class<?> clazz = po.getClass();
List<Field> fieldList = new ArrayList<Field>();
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
fieldList.add(f);
}
if (clazz.getSuperclass() != Object.class) {
Field[] superFields = clazz.getSuperclass().getDeclaredFields();
for (Field sf : superFields) {
boolean isExist = false;
for (Field f : fieldList) {
if (f.getName().equals(sf.getName())) {
isExist = true;
break;
}
}
if (isExist == false) {
fieldList.add(sf);
} else {
isExist = false;
}
}
}
return fieldList.toArray(new Field[fieldList.size()]);
}
/**
* 取字段对应数据表字段的名字
* @param field
* @return
*/
private String getFieldName(Field field) {
Column column = field.getAnnotation(Column.class);
if (null != column) {
// 字段包含Column注解的处理
return column.value();
} else {
// 没有注解,直接取字段名转换成下划线命名字段
return CamelCaseUtils.toUnderlineName(field.getName());
}
}
}
|
package edu.caltech.cs2.textgenerator;
import edu.caltech.cs2.datastructures.LinkedDeque;
import edu.caltech.cs2.interfaces.IDeque;
import edu.caltech.cs2.interfaces.IQueue;
import java.util.Iterator;
public class NGram implements Iterable<String>, Comparable<NGram> {
public static final String NO_SPACE_BEFORE = ",?!.-,:'";
public static final String NO_SPACE_AFTER = "-'><=";
public static final String REGEX_TO_FILTER = "”|\"|“|\\(|\\)|\\*";
public static final String DELIMITER = "\\s+|\\s*\\b\\s*";
private IDeque<String> data;
public static String normalize(String s) {
return s.replaceAll(REGEX_TO_FILTER, "").strip();
}
public NGram(IDeque<String> x) {
this.data = new LinkedDeque<>();
for (int i = 0; i < x.size(); i++) {
this.data.addBack(x.peekFront());
x.addBack(x.removeFront());
}
}
public NGram(String data) {
this(normalize(data).split(DELIMITER));
}
public NGram(String[] data) {
this.data = new LinkedDeque<>();
for (String s : data) {
s = normalize(s);
if (!s.isEmpty()) {
this.data.addBack(s);
}
}
}
public NGram next(String word) {
String[] data = new String[this.data.size()];
for (int i = 0; i < data.length - 1; i++) {
this.data.addBack(this.data.removeFront());
data[i] = this.data.peekFront();
}
this.data.addBack(this.data.removeFront());
data[data.length - 1] = word;
return new NGram(data);
}
@Override
public String toString() {
String result = "";
String prev = "";
for (String s : this.data) {
result += ((NO_SPACE_AFTER.contains(prev) || NO_SPACE_BEFORE.contains(s) || result.isEmpty()) ? "" : " ") + s;
prev = s;
}
return result.strip();
}
@Override
public Iterator<String> iterator() {
return this.data.iterator();
}
@Override
public int compareTo(NGram other) {
if(other == null) throw new NullPointerException();
if(this.data.size() != other.data.size()) return this.data.size() >= other.data.size() ? 1 : -1;
Iterator<String> yeet = this.iterator();
Iterator<String> yoink = other.iterator();
while(yeet.hasNext() && yoink.hasNext()){
String str1 = yeet.next();
String str2 = yoink.next();
if(!(str1.equals(str2))){
return str1.compareTo(str2);
}
}
return 0;
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null) return false;
if(!(o instanceof NGram)) return false;
NGram yuh = (NGram) o;
if(yuh.data.size() != this.data.size()) return false;
Iterator<String> yeet = this.iterator();
Iterator<String> yoink = yuh.iterator();
while(yeet.hasNext() && yoink.hasNext()){
String item1 = yeet.next();
String item2 = yoink.next();
if(! item1.equals(item2)) return false;
}
return !(yeet.hasNext() || yoink.hasNext());
}
@Override
public int hashCode() {
int toret = 0;
int i = 0;
for(String s : data){
toret += hashString(s, i);
i += s.length();
}
return toret;
}
private int hashString(String s, int ct ){
int toret = 0;
int j = ct;
for(int i = 0; i < s.length(); i++){
toret += Math.pow(37, j) * s.charAt(i);
j++;
}
return toret;
}
}
|
package choo.edeline.foodrng;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
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.ImageView;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
private static final String CHOSEN_ITEM = "item";
DatabaseHelper mDatabaseHelper;
private ImageView RNGenerator;
private TextView item;
private Button mViewList;
private String selectedItem = "";
private String username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = getIntent().getExtras().getString("username");
getSupportActionBar().setTitle("Food RNG");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mViewList = (Button)findViewById(R.id.btnViewList);
mViewList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, ItemListActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
item = (TextView)findViewById(R.id.tvRNG);
mDatabaseHelper = new DatabaseHelper(this);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.soundeffect);
RNGenerator = (ImageView)findViewById(R.id.ivRNG);
RNGenerator.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ObjectAnimator rotateAnimation = ObjectAnimator.ofFloat
(RNGenerator, "rotation", 0f, 360f);
rotateAnimation.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(rotateAnimation);
animatorSet.start();
mediaPlayer.start();
Cursor data = mDatabaseHelper.getItemData(username);
ArrayList<String> itemList = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//then add it to the ArrayList
itemList.add(data.getString(0));
}
if (itemList.isEmpty() == true) {
selectedItem = "Oops! Your list is empty.";
item.setText(selectedItem);
}
else {
Collections.shuffle(itemList);
selectedItem = "Today's pick is: " + itemList.get(0);
item.setText(selectedItem);
}
}
});
if (savedInstanceState != null) {
selectedItem = savedInstanceState.getString(CHOSEN_ITEM, "");
item.setText(selectedItem);
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(CHOSEN_ITEM, selectedItem);
}
}
|
package zad1;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
public class HeadServer {
//initialize socket and input stream
private Socket socket = null;
private Socket socketSend = null;
private ServerSocket server = null;
private DataInputStream inServer = null;
private DataInputStream inputClient = null;
private DataOutputStream outputClient = null;
public static Map<String, Integer> mapServer = Map.of("RUS", 5001, "FR", 5002, "ANG", 5003);
public void server(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
inServer = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
System.out.println("Client accepted");
String line = "";
while (!line.equals("Over")) {
line = inServer.readUTF();
System.out.println(line);
String[] splitLine = line.split(";");
System.out.println();
try {
socketSend = new Socket("localhost", mapServer.get(splitLine[0]));
inputClient = new DataInputStream(System.in);
outputClient = new DataOutputStream(socketSend.getOutputStream());
outputClient.writeUTF(splitLine[1] + ";" + splitLine[2]);
}catch (NullPointerException a){
System.out.println("Closing connection");
}
}
socket.close();
inServer.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
int headServerPort = 5000;
HeadServer headServer = new HeadServer();
headServer.server(headServerPort);
}
}
|
package br.com.fiap.dao;
import java.util.Calendar;
import java.util.List;
import br.com.fiap.entity.Pacote;
import br.com.fiap.entity.Transporte;
public interface PacoteDAO extends DAO<Pacote,Integer>{
List<Pacote> buscarPorTransporte(Transporte transporte);
List<Pacote> getPacotes(Calendar inicio, Calendar fim);
}
|
package org.point85.domain.dto;
import org.point85.domain.email.EmailSource;
public class EmailSourceDto extends CollectorDataSourceDto {
private String receiveSecurityPolicy;
private String emailProtocol;
private String sendHost;
private Integer sendPort;
private String sendSecurityPolicy;
public EmailSourceDto(EmailSource source) {
super(source);
this.setReceiveSecurityPolicy(
source.getReceiveSecurityPolicy() != null ? source.getReceiveSecurityPolicy().name() : null);
this.setSendSecurityPolicy(
source.getSendSecurityPolicy() != null ? source.getSendSecurityPolicy().name() : null);
this.setEmailProtocol(source.getProtocol() != null ? source.getProtocol().name() : null);
this.setSendHost(source.getSendHost());
this.setSendPort(source.getSendPort());
}
public String getReceiveSecurityPolicy() {
return receiveSecurityPolicy;
}
public void setReceiveSecurityPolicy(String receiveSecurityPolicy) {
this.receiveSecurityPolicy = receiveSecurityPolicy;
}
public String getEmailProtocol() {
return emailProtocol;
}
public void setEmailProtocol(String emailProtocol) {
this.emailProtocol = emailProtocol;
}
public String getSendHost() {
return sendHost;
}
public void setSendHost(String sendHost) {
this.sendHost = sendHost;
}
public Integer getSendPort() {
return sendPort;
}
public void setSendPort(Integer sendPort) {
this.sendPort = sendPort;
}
public String getSendSecurityPolicy() {
return sendSecurityPolicy;
}
public void setSendSecurityPolicy(String sendSecurityPolicy) {
this.sendSecurityPolicy = sendSecurityPolicy;
}
}
|
package com.pbadun.fragment.interfaces;
/**
* Отвечает за обработку фрагментов в зависимости от размера экрана
* @author jb
*
*/
public interface IFragmentSize {
/**
* Вывести стараницу с новастью...
* @param urlSite
*/
public void urlView(String urlSite);
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.translation.in.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.exceptions.IllegalAttributeValueException;
import pl.edu.icm.unity.exceptions.InternalException;
import pl.edu.icm.unity.server.api.AttributesManagement;
import pl.edu.icm.unity.server.authn.remote.RemoteAttribute;
import pl.edu.icm.unity.server.authn.remote.RemotelyAuthenticatedInput;
import pl.edu.icm.unity.server.translation.in.AttributeEffectMode;
import pl.edu.icm.unity.server.translation.in.InputTranslationAction;
import pl.edu.icm.unity.server.translation.in.MappedAttribute;
import pl.edu.icm.unity.server.translation.in.MappingResult;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.basic.AttributeVisibility;
import pl.edu.icm.unity.types.translation.ActionParameterDefinition;
import pl.edu.icm.unity.types.translation.ActionParameterDefinition.Type;
import pl.edu.icm.unity.types.translation.TranslationActionType;
/**
* Maps multiple attributes only by providing new names, values are unchanged.
*
* @author K. Benedyczak
*/
@Component
public class MultiMapAttributeActionFactory extends AbstractInputTranslationActionFactory
{
public static final String NAME = "multiMapAttribute";
private AttributesManagement attrsMan;
@Autowired
public MultiMapAttributeActionFactory(@Qualifier("insecure") AttributesManagement attrsMan)
{
super(NAME, new ActionParameterDefinition[] {
new ActionParameterDefinition(
"mapping",
"TranslationAction.multiMapAttribute.paramDesc.mapping",
Type.LARGE_TEXT),
new ActionParameterDefinition(
"visibility",
"TranslationAction.mapAttribute.paramDesc.visibility",
AttributeVisibility.class),
new ActionParameterDefinition(
"effect",
"TranslationAction.mapAttribute.paramDesc.effect",
AttributeEffectMode.class)});
this.attrsMan = attrsMan;
}
@Override
public InputTranslationAction getInstance(String... parameters)
{
return new MultiMapAttributeAction(parameters, getActionType(), attrsMan);
}
public static class MultiMapAttributeAction extends InputTranslationAction
{
private static final Logger log = Log.getLogger(Log.U_SERVER_TRANSLATION, MultiMapAttributeAction.class);
private final AttributesManagement attrMan;
private String mapping;
private AttributeVisibility visibility;
private AttributeEffectMode mode;
private List<Mapping> mappings;
public MultiMapAttributeAction(String[] params, TranslationActionType desc, AttributesManagement attrsMan)
{
super(desc, params);
setParameters(params);
attrMan = attrsMan;
parseMapping();
}
@Override
protected MappingResult invokeWrapped(RemotelyAuthenticatedInput input, Object mvelCtx,
String currentProfile)
{
MappingResult ret = new MappingResult();
Map<String, RemoteAttribute> remoteAttrs = input.getAttributes();
for (Mapping mapping: mappings)
{
RemoteAttribute ra = remoteAttrs.get(mapping.external);
if (ra != null)
mapSingle(ret, ra, mapping, input.getIdpName(), currentProfile);
}
return ret;
}
private void mapSingle(MappingResult ret, RemoteAttribute ra, Mapping mapping, String idp, String profile)
{
AttributeType at = mapping.local;
List<Object> typedValues;
try
{
typedValues = MapAttributeActionFactory.MapAttributeAction.convertValues(
ra.getValues(), at.getValueType());
} catch (IllegalAttributeValueException e)
{
log.debug("Can't convert attribute values returned by the action's expression "
+ "to the type of attribute " + at.getName() + " , skipping it", e);
return;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
Attribute<?> attribute = new Attribute(at.getName(), at.getValueType(), mapping.group,
visibility, typedValues, idp, profile);
MappedAttribute ma = new MappedAttribute(mode, attribute);
log.debug("Mapped attribute: " + attribute);
ret.addAttribute(ma);
}
private void parseMapping()
{
mappings = new ArrayList<MultiMapAttributeAction.Mapping>();
Map<String, AttributeType> attributeTypes;
try
{
attributeTypes = attrMan.getAttributeTypesAsMap();
} catch (EngineException e)
{
throw new InternalException("Can't get attribute types", e);
}
String lines[] = mapping.split("\n");
int num = 0;
for (String line: lines)
{
num++;
line = line.trim();
String tokens[] = line.split("[ ]+");
if (tokens.length != 3)
throw new IllegalArgumentException("Line " + num + " is invalid: must have 3 tokens");
AttributeType at = attributeTypes.get(tokens[1]);
if (at == null)
throw new IllegalArgumentException("Attribute type " + tokens[1] + " is not known");
Mapping map = new Mapping(tokens[0], at, tokens[2]);
mappings.add(map);
}
}
private void setParameters(String[] parameters)
{
if (parameters.length != 3)
throw new IllegalArgumentException("Action requires exactly 3 parameters");
mapping = parameters[0];
visibility = AttributeVisibility.valueOf(parameters[1]);
mode = AttributeEffectMode.valueOf(parameters[2]);
}
private static class Mapping
{
private String external;
private AttributeType local;
private String group;
public Mapping(String external, AttributeType local, String group)
{
this.external = external;
this.local = local;
this.group = group;
}
}
}
}
|
package com.example.mvvmnotesapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.Session2Command;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
public class AddEditNoteActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.mvvmnotesapp.EXTRA_ID";
public static final String EXTRA_TITLE = "com.example.mvvmnotesapp.EXTRA_TITLE";
public static final String EXTRA_DESCRIPTION = "com.example.mvvmnotesapp.EXTRA_DESCRIPTION";
public static final String EXTRA_PRIORITY = "com.example.mvvmnotesapp.EXTRA_PRIORITY";
/* Data members to hold the values of the Views in layout */
private EditText titleEditText;
private EditText contentEditText;
private NumberPicker priorityNumberPicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
// Associating data members with correct Views.
titleEditText = findViewById(R.id.title_edit_text);
contentEditText = findViewById(R.id.content_edit_text);
priorityNumberPicker = findViewById(R.id.priority_number_picker);
// Setting the min and max values of NumberPicker, which cannot be done in XML
priorityNumberPicker.setMinValue(1);
priorityNumberPicker.setMaxValue(25);
Intent callingIntent = getIntent();
//To get the close button in top-left corner (ic_close icon)
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
if (callingIntent.hasExtra(EXTRA_ID)) {
setTitle("Edit Note");
String currentTitle = callingIntent.getStringExtra(EXTRA_TITLE);
String currentDescription = callingIntent.getStringExtra(EXTRA_DESCRIPTION);
int currentPriority = callingIntent.getIntExtra(EXTRA_PRIORITY, 1);
titleEditText.setText(currentTitle);
contentEditText.setText(currentDescription);
priorityNumberPicker.setValue(currentPriority);
}
else
setTitle("Add Note");
}
/* To get the Save icon in the top-right corner of the action bar */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return true;
}
/* To ensure that when the ic_save icon is clicked, we are redirected to a piece of code
* that does exactly that */
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.save_note_menu:
saveNote();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveNote() {
// Get the input entered by the user
String noteTitle = String.valueOf(titleEditText.getText());
String noteContent = String.valueOf(contentEditText.getText());
int notePriority = priorityNumberPicker.getValue();
// To ensure that EditText Views hold valid inputs
if (noteTitle.trim().isEmpty() || noteContent.trim().isEmpty()) {
Toast.makeText(this, "Please insert a title and description",
Toast.LENGTH_SHORT).show();
return;
}
// Sending information to the calling Activity through Intent extras
Intent inputData = new Intent();
inputData.putExtra(EXTRA_TITLE, noteTitle);
inputData.putExtra(EXTRA_DESCRIPTION, noteContent);
inputData.putExtra(EXTRA_PRIORITY, notePriority);
int currentId = getIntent().getIntExtra(EXTRA_ID, -1);
if(currentId != -1) {
inputData.putExtra(EXTRA_ID, currentId);
}
setResult(RESULT_OK, inputData); // RESULT_OK signifies that we were able to successfully
// retrieve input data
finish(); // Close this Activity
}
}
|
package com.tpg.brks.ms.expenses.service.clients;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@ConfigurationProperties(prefix = "user.details.service.client")
public class UserDetailsServiceClientProperties implements UserDetailsServiceClientConfiguration {
@NotNull
private String rootUri;
@Min(value = 1000)
private int connectionTimeout;
@Min(value = 1000)
private int readTimeout;
}
|
package com.needii.dashboard.model.form;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import com.needii.dashboard.model.Product;
import com.needii.dashboard.model.ProductCityMap;
import com.needii.dashboard.model.ProductTagMap;
public class ProductForm {
private String rejectReason;
private String image;
private boolean approve;
private String price;
private String lastPrice;
private String quantity;
private String cashbackAmount;
private float cashbackDefault;
private String cashbackDefaultLabel;
private String discountPercent;
private String supplierId;
private Integer status;
private boolean isReject;
private boolean isNew;
private boolean isHot;
private boolean isBestSeller;
private boolean isShowHome;
private boolean isPromotion;
private boolean isTodayDeal;
private boolean isCommingDeal;
private boolean availableForSale;
private String cityId;
private String tag;
private String width;
private String height;
private String depth;
private String weight;
private ProductDataForm productDataForm;
private SkuForm skuForm;
public ProductForm() {}
public ProductForm(Product entity) {
this.approve = entity.getApprove();
this.price = String.valueOf(entity.getPrice());
this.rejectReason = entity.getRejectReason();
this.status = entity.getStatus();
this.lastPrice = String.valueOf(entity.getLastPrice());
this.quantity = String.valueOf(entity.getQuantity());
this.cashbackAmount = String.valueOf(entity.getCashbackAmount());
this.cashbackDefault = entity.getCategory().getCashbackPercent();
this.discountPercent = String.valueOf(entity.getDiscountPercent());
this.isReject = entity.getIsReject();
this.isNew = entity.getIsNew();
this.isHot = entity.getIsHot();
this.isBestSeller = entity.getIsBestSeller();
this.isShowHome = entity.getIsShowHome();
this.isPromotion = entity.getIsPromotion();
this.isTodayDeal = entity.getIsTodayDeal();
this.isCommingDeal = entity.getIsCommingDeal();
this.availableForSale = entity.getAvailableForSale();
if (entity.getCategory().getCategoryParentListId().size() > 1){
this.categoryId = entity.getCategory().getCategoryParentListId().get(0);
}
this.tag = StringUtils.join(entity.getProductTags().stream().map(ProductTagMap::getTagId).collect(Collectors.toList()),",");
this.cityId = StringUtils.join(entity.getProductCities().stream().map(ProductCityMap::getCityId).collect(Collectors.toList()),",");
this.supplierId = String.valueOf(entity.getSupplier().getId());
this.image = entity.getImage();
this.weight = String.valueOf(entity.getWeight());
this.width = String.valueOf(entity.getWidth());
this.height = String.valueOf(entity.getHeight());
this.depth = String.valueOf(entity.getDepth());
this.productDataForm = new ProductDataForm(entity.getData());
}
private String categoryId;
/**
* @return the rejectReason
*/
public String getRejectReason() {
return rejectReason;
}
/**
* @param rejectReason the rejectReason to set
*/
public void setRejectReason(String rejectReason) {
this.rejectReason = rejectReason;
}
/**
* @return the approve
*/
public boolean getApprove() {
return approve;
}
/**
* @param approve the approve to set
*/
public void setApprove(boolean approve) {
this.approve = approve;
}
/**
* @return the price
*/
public String getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(String price) {
this.price = price;
}
/**
* @return the lastPrice
*/
public String getLastPrice() {
return lastPrice;
}
/**
* @param lastPrice the lastPrice to set
*/
public void setLastPrice(String lastPrice) {
this.lastPrice = lastPrice;
}
/**
* @return the quantity
*/
public String getQuantity() {
return quantity;
}
/**
* @param quantity the quantity to set
*/
public void setQuantity(String quantity) {
this.quantity = quantity;
}
/**
* @return the cashbackAmount
*/
public String getCashbackAmount() {
return cashbackAmount;
}
/**
* @param cashbackAmount the cashbackAmount to set
*/
public void setCashbackAmount(String cashbackAmount) {
this.cashbackAmount = cashbackAmount;
}
public float getCashbackDefault() {
return cashbackDefault;
}
public void setCashbackDefault(float cashbackDefault) {
this.cashbackDefault = cashbackDefault;
}
public String getCashbackDefaultLabel() {
return cashbackDefaultLabel;
}
public void setCashbackDefaultLabel(String cashbackDefaultLabel) {
this.cashbackDefaultLabel = cashbackDefaultLabel;
}
/**
* @return the disountPercent
*/
public String getDiscountPercent() {
return discountPercent;
}
/**
* @param discountPercent the disountPercent to set
*/
public void setDiscountPercent(String discountPercent) {
this.discountPercent = discountPercent;
}
/**
* @return the status
*/
public Integer getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* @return the isReject
*/
public boolean getIsReject() {
return isReject;
}
/**
* @param isReject the isReject to set
*/
public void setIsReject(boolean isReject) {
this.isReject = isReject;
}
/**
* @return the isRew
*/
public boolean getIsNew() {
return isNew;
}
/**
* @param isNew the isNew to set
*/
public void setIsNew(boolean isNew) {
this.isNew = isNew;
}
/**
* @return the isHot
*/
public boolean getIsHot() {
return isHot;
}
/**
* @param isHot the isHot to set
*/
public void setIsHot(boolean isHot) {
this.isHot = isHot;
}
/**
* @return the isBestSeller
*/
public boolean getIsBestSeller() {
return isBestSeller;
}
/**
* @param isBestSeller the isBestSeller to set
*/
public void setIsBestSeller(boolean isBestSeller) {
this.isBestSeller = isBestSeller;
}
/**
* @return the isShowHome
*/
public boolean getIsShowHome() {
return isShowHome;
}
/**
* @param isShowHome the isShowHome to set
*/
public void setIsShowHome(boolean isShowHome) {
this.isShowHome = isShowHome;
}
/**
* @return the isPromotion
*/
public boolean getIsPromotion() {
return isPromotion;
}
/**
* @param isPromotion the isPromotion to set
*/
public void setIsPromotion(boolean isPromotion) {
this.isPromotion = isPromotion;
}
/**
* @return the isTodayDeal
*/
public boolean getIsTodayDeal() {
return isTodayDeal;
}
/**
* @param isTodayDeal the isTodayDeal to set
*/
public void setIsTodayDeal(boolean isTodayDeal) {
this.isTodayDeal = isTodayDeal;
}
/**
* @return the isCommingDeal
*/
public boolean getIsCommingDeal() {
return isCommingDeal;
}
/**
* @param isCommingDeal the isCommingDeal to set
*/
public void setIsCommingDeal(boolean isCommingDeal) {
this.isCommingDeal = isCommingDeal;
}
/**
* @return the availableForSale
*/
public boolean getAvailableForSale() {
return availableForSale;
}
/**
* @param availableForSale the availableForSale to set
*/
public void setAvailableForSale(boolean availableForSale) {
this.availableForSale = availableForSale;
}
/**
* @return the categoryId
*/
public String getCategoryId() {
return categoryId;
}
/**
* @param categoryId the categoryId to set
*/
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
/**
* @return the image
*/
public String getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
public ProductDataForm getProductDataForm() {
return productDataForm;
}
public void setProductDataForm(ProductDataForm productDataForm) {
this.productDataForm = productDataForm;
}
public String getSupplierId() {
return supplierId;
}
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
public SkuForm getSkuForm() {
return skuForm;
}
public void setSkuForm(SkuForm skuForm) {
this.skuForm = skuForm;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getDepth() {
return depth;
}
public void setDepth(String depth) {
this.depth = depth;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
|
import edu.princeton.cs.algs4.StdRandom;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] arr;
private int capacity;
private int n;
public RandomizedQueue() {
n = 0;
capacity = 10;
arr = (Item[]) new Object[capacity];
}
private void resize(int size) {
assert size >= n;
arr = Arrays.copyOf(arr, size);
this.capacity = size;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
public void enqueue(Item item) {
if (item == null) throw new IllegalArgumentException();
if (n == capacity)
resize(capacity * 2);
arr[n] = item;
n++;
}
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException();
int random = StdRandom.uniform(n);
Item item = arr[random];
arr[random] = arr[n - 1];
arr[n - 1] = null;
if (n > 0 && n == capacity / 4)
resize(capacity / 2);
n--;
return item;
}
public Item sample() {
if (isEmpty()) throw new NoSuchElementException();
int random = StdRandom.uniform(n);
return arr[random];
}
public Iterator<Item> iterator() {
return new RandomizedQueueIterator();
}
private class RandomizedQueueIterator implements Iterator<Item> {
private Item[] array = Arrays.copyOf(arr, arr.length);
private int num = n;
@Override
public boolean hasNext() {
return num > 0;
}
@Override
public Item next() {
if (num == 0) throw new NoSuchElementException();
int random = StdRandom.uniform(num);
Item item = array[random];
array[random] = array[num - 1];
array[num - 1] = null;
num--;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] args) {
}
}
|
package exercicio04;
import java.util.Scanner;
public class DVD extends Midia
{
private int faixas;
DVD()
{
}
DVD(int codigo, double preco, String nome, int f){
super(codigo, preco, nome);
this.setFaixas(f);
}
public int getFaixas() {
return faixas;
}
public void setFaixas(int faixas) {
this.faixas = faixas;
}
@Override
public void insereDados()
{
super.insereDados();
Scanner entrada = new Scanner (System.in);
System.out.println("Digite o numero de faixas\n");
int faixas = entrada.nextInt();
this.setFaixas(faixas);
}
@Override
public String getDetalhes() {
System.out.println("A capa do dvd esta sendo exibida\n");
String x =super.getDetalhes();
return (x + "Faixas: " +this.getFaixas());
}
@Override
public void printDados()
{
System.out.println(getDetalhes());
}
public String getTipo()
{
return super.getTipo("DVD");
}
public void inserirDados()
{
}
}
|
class Solution {
public int maxDepth(String s) {
int max=0;
int open=0;
for(char c:s.toCharArray()){
if(c=='('){
open++;
max=Math.max(max,open);
}
else if(c==')'){
open--;
}
}
return max;
}
}
|
package BrazilCenter.DaoUtils.Utils;
import org.apache.log4j.Logger;
public class LogUtils {
public static Logger logger = Logger.getLogger("BrazilCenterUtils");
}
|
package com.ruenzuo.sabisukatto.sabisukattokit;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Url;
/**
* Created by ruenzuo on 19/03/2017.
*/
public interface MediaDownloadService {
@GET
Call<ResponseBody> downloadMedia(@Url String fileUrl);
}
|
package factories;
import domain.MainCourse;
import java.util.Map;
/**
* Created by rodrique on 4/20/2018.
*/
public class MainCourseFactory
{
public static MainCourse getMainCourse(Map<String,String> values)// , List<Chef> chefs)
{
MainCourse mainCourse = new MainCourse
.Builder()
.mainID(values.get("main ID"))
.foodItem(values.get("food Item"))
.build();
return mainCourse;
}
}
|
package prosjektoppgave.models;
/**
* An interface for objects that can be part by a Contract
*/
public interface ContractAsset {
public void addContract(Contract contract);
public boolean isContracted();
}
|
package com.git.cloud.reports.model.po;
import com.git.cloud.common.model.base.BaseBO;
public class SqlParamPo extends BaseBO implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -8581296369465496282L;
//报表SQL实体类
private String id;//ID
private String sqlKey;//sqlKEY
private String sqlValue;//sqlVALUE
private String reportId;//表示这个sql从属于哪个报表
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSqlKey() {
return sqlKey;
}
public void setSqlKey(String sqlKey) {
this.sqlKey = sqlKey;
}
public String getSqlValue() {
return sqlValue;
}
public void setSqlValue(String sqlValue) {
this.sqlValue = sqlValue;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package service;
public interface ConfidentialTokenStore extends TokenStore {
}
|
package Servlets;
import Logica.Controladora;
import Logica.Entrada;
import Logica.FormatoFechas;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "EditarEntrada", urlPatterns = {"/EditarEntrada"})
public class EditarEntrada extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Controladora control = new Controladora();
int idEditar = Integer.parseInt(request.getParameter("idEditar"));
Entrada EntradaAEditar = control.buscarEntradaPorId(idEditar);
HttpSession miSession = request.getSession();
miSession.setAttribute("editarEntrada", EntradaAEditar);
response.sendRedirect("editarEntrada.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.rengu.operationsmanagementsuitev3.Utils;
import org.apache.commons.io.FileUtils;
import java.io.File;
/**
* @program: OperationsManagementSuiteV3
* @author: hanchangming
* @create: 2018-08-22 16:59
**/
public class ApplicationConfig {
// 默认角色
public static final String DEFAULT_ADMIN_ROLE_NAME = "admin";
public static final String DEFAULT_USER_ROLE_NAME = "user";
// 默认管理员用户
public static final String DEFAULT_ADMIN_USERNAME = "admin";
public static final String DEFAULT_ADMIN_PASSWORD = "admin";
// 服务器连接地址、端口
public static final int TCP_RECEIVE_PORT = 6005;
public static final int UDP_RECEIVE_PORT = 6004;
public static final int UDP_SEND_PORT = 3087;
public static final int TCP_DEPLOY_PORT = 3088;
public static final String SERVER_CAST_ADDRESS = "224.10.10.15";
public static final int SERVER_BROAD_CAST_PORT = 3086;
public static final int SERVER_MULTI_CAST_PORT = 3086;
// 文件块保存路径
public static final String CHUNKS_SAVE_PATH = FormatUtils.formatPath(FileUtils.getTempDirectoryPath() + File.separator + "OMS" + File.separator + "CHUNKS");
// 文件保存路径
public static final String FILES_SAVE_PATH = FormatUtils.formatPath(FileUtils.getUserDirectoryPath() + File.separator + "OMS" + File.separator + "FILES");
// 扫描超时时间
public static final long SCAN_TIME_OUT = 1000 * 10;
// 部署回复超时时间
public static final long REPLY_TIME_OUT = 1000 * 10;
}
|
package seedu.project.testutil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.project.model.ProjectList;
import seedu.project.model.project.Project;
/**
* A utility class to help with building ProjectList objects. Example usage:
* <br>
* {@code Project ab = new ProjectListBuilder().withProject("CS2101 Project").build();}
*/
public class ProjectListBuilder {
private List<Project> projects;
public ProjectListBuilder() {
projects = new ArrayList<>();
}
public ProjectListBuilder(ProjectList projectListToCopy) {
projects = projectListToCopy.getProjectList();
}
/**
* Adds a new {@code Task} to the {@code Project} that we are building.
*/
public ProjectListBuilder withProject(Project project) {
this.projects = new ArrayList<>(Arrays.asList(project));
return this;
}
public ProjectList build() {
return new ProjectList(projects);
}
}
|
package oo.composicao.desafio;
public class ClienteTeste {
public static void main(String[] args) {
Produtos p1 = new Produtos (4.78 ,"Desodorante");
Produtos p2 = new Produtos (5.78 ,"Kinder Ovo");
Item i1 = new Item(5);
Item i2 = new Item(4);
Cliente c1 = new Cliente("Joćo");
Cliente c2 = new Cliente("Carlos");
Compra compra1 = new Compra();
//Adicionando itens nas compras
compra1.itens.add(i1);
compra1.itens.add(i2);
//Adicionando compras nos clientes
c1.compras.add(compra1);
c2.compras.add(compra1);
System.out.println(c1.nome + " Comprou um " + p1.nome + " E gastou " + c1.obterValorCompleto(p1.preco, i1.quantidade));
System.out.println(c2.nome + " Comprou um " + p2.nome + " E gastou " + c2.obterValorCompleto(p2.preco, i2.quantidade));
}
}
|
package br.com.porquesim.eventmanager;
public class Main {
public Main() {
EventManager.get().registerListener("teste", new EventListener() {
@Override
public void on(String evt) {
System.out.println("Received event: " + evt);
}
});
EventManager.get().fire("teste");
//manager.fire(new TesteEvent(this));
}
@ListenTo(event = TesteEvent.class)
public void faz(TesteEvent ev) {
System.out.println("Fazendo");
}
public static void main(String[] args) {
new Main();
}
}
|
package com.corejava.collection;
public class Employee {
private int empid;
private String employeeName;
public Employee(int empid, String employeeName) {
super();
this.empid = empid;
this.employeeName = employeeName;
}
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
/*
* @Override public boolean equals(Object obj) {
* System.out.println("equals() method called..");
* System.out.println("Generated equals() method result::"+super.equals(obj));
* //return super.equals(obj);
*
* //downcasting Employee employee=(Employee)obj;
* if(this.getEmpid()==employee.getEmpid() &&
* this.getEmployeeName().equals(employee.getEmployeeName())){ return true;
* //duplicate object } return false; //unique object }
*/
@Override
public int hashCode() {
System.out.println("hashCode() method called..");
System.out.println("Generated HashCode::"+super.hashCode());
System.out.println("Overridden HashCode::"+empid);
return empid;
}
@Override
public String toString() {
return "Employee [empid=" + empid + ", employeeName=" + employeeName + "]";
}
}
|
package com.sirma.itt.javacourse.reflectionAnotationRegex.task5.emailValidator;
import com.sirma.itt.javacourse.InputUtils;
import com.sirma.itt.javacourse.StringUtil;
/**
* Class that asks a user to enter an email adres an validate it.
*
* @author simeon
*/
public class RunEmailValidator {
/**
* Main method.
*
* @param args
* for the main method.
*/
public static void main(String[] args) {
InputUtils.printConsoleMessage("Please enter you're email address.");
String email = InputUtils.readValidatedLine(StringUtil.REGEX_VALIDATOR_EMAIL_ADDRESS);
InputUtils.printConsoleMessage("Thank you for entering you're email address : " + email);
}
}
|
/*
* Why hashset is called hash? it uses hash code to determine which bucket
* the object should be allocated.
* Hashset used equals() to determine the uniqueness.
* Hashset internally is implemented by a HashMap, key-value pairs. Object hashcode
* is stored as the key of the value(object), for a fast retreiving.
*/
package CollectionFun.SetFun;
import CollectionFun.Person;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @author YNZ
*/
public class SetHashBuket {
public static void main(String[] args) {
//HashSet use equals() to determine uniqueness.
Set<String> mySet = new HashSet<>(5, 0.8f);
mySet.add("aa");
mySet.add("aa");
mySet.add(new String("aa"));
System.out.println(mySet);
//
Set<Person> persons = new HashSet<>(5, 0.8f);
persons.add(new Person("ynz"));
persons.add(new Person("ynz"));
persons.add(new Person("OCK"));
persons.add(new Person("aaa"));
System.out.println(persons);
System.out.println("hashcode OCK " + "OCK".hashCode());
System.out.println("hashcode ynz" + "ynz".hashCode());
System.out.println("hashcode aaa" + "aaa".hashCode());
//let's see how hashcode determins object's bucket
Set<String> buckets = new HashSet<>(5, 0.8f);
buckets.add("OCK");
buckets.add("ynz");
buckets.add("aaa");
System.out.println(buckets);
//lineked hashset is ordered
Set<String> linkBuckets = new LinkedHashSet<>(5, 0.8f);
linkBuckets.add("OCK");
linkBuckets.add("ynz");
linkBuckets.add("aaa");
System.out.println(linkBuckets);
//treeSet is ordered
Set<String> treeSet = new TreeSet<>();
treeSet.add("OCK");
treeSet.add("ynz");
treeSet.add("aaa");
System.out.println(treeSet);
}
}
|
package com.techm.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.techm.models.User;
public class BillDetailsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
session.setMaxInactiveInterval(1000);
String billedCellNo=request.getParameter("billedCellNo");
double minutes=Double.parseDouble(request.getParameter("minutes"));
double billAmount=calculateBill(minutes);
session.setAttribute("billedCellNo", billedCellNo);
session.setAttribute("minutes", minutes);
session.setAttribute("billAmount", billAmount);
RequestDispatcher rd=request.getRequestDispatcher("/displaybilldetails.jsp");
rd.forward(request, response);
}
public double calculateBill(double minutes){
return minutes * 2.5;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
package in.omerjerk.processing.video.android.callbacks;
import android.graphics.SurfaceTexture;
public interface CameraHandlerCallback {
public void handleSetSurfaceTexture(SurfaceTexture texture);
public void startCamera(Integer cameraId);
public void startPreview();
public void stopCamera();
}
|
package com.vaiha.LemmeShowU;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.display.VirtualDisplay;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.vaiha.LemmeShowU.MainActivity4.temp2;
/**
* Created by vaiha on 6/10/16.
*/
public class StopReceiver extends BroadcastReceiver {
NotificationManager mNotificationManager;
Notification notification;
Context context;
SharedPreferences sharedPreferences;
private MediaProjectionManager mProjectionManager;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
String action = (String) intent.getExtras().get("DO");
if (action.equals("stop")) {
if (SupportClass.g_flag) {
SupportClass.g_flag = false;
SupportClass.close = false;
start_Notification();
}
if (SupportClass.stopvid) {
SupportClass.g_flag = false;
SupportClass.close = false;
SupportClass.movie=false;
temp2=false;
try {
if (SupportClass.mediaRecorder != null) {
Log.e("MMM", "" + SupportClass.mediaRecorder);
SupportClass.mediaRecorder.stop();
SupportClass.mediaRecorder.reset();
SupportClass.mediaRecorder.release();
}
} catch (NullPointerException e) {
e.getStackTrace();
}
SupportClass.stopvid = false;
SupportClass.check_recorder_create = true;
start_Notification();
}
} else if (action.equals("exit")) {
SupportClass.g_notificationManager.cancelAll();
SupportClass.close = true;
}
}
private void start_Notification() {
mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.icon;
//int icon = R.drawable.animationfile;
long when = System.currentTimeMillis();
notification = new Notification(icon, "LemmeShowU", when);
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.start_notification);
contentView.setImageViewResource(R.id.image11, R.drawable.icon);
contentView.setImageViewResource(R.id.image21, R.mipmap.play);
contentView.setImageViewResource(R.id.image, R.mipmap.movie);
contentView.setImageViewResource(R.id.image31, R.mipmap.frames);
contentView.setImageViewResource(R.id.image41, R.mipmap.exit);
contentView.setTextViewText(R.id.stop, "Start");
// contentView.setTextViewText(R.id.movie, "Movie");
contentView.setTextViewText(R.id.fps, "FPS");
contentView.setTextViewText(R.id.exit, "Exit");
setListeners(contentView);
sharedPreferences = context.getSharedPreferences("MyPref", MODE_PRIVATE);
String mode = sharedPreferences.getString("capture_mode", "Video");
if (mode.equals("Video")) {
contentView.setViewVisibility(R.id.fpsLayout, View.GONE);
contentView.setViewVisibility(R.id.mpLayout, View.VISIBLE);
} else {
contentView.setViewVisibility(R.id.fpsLayout, View.VISIBLE);
contentView.setViewVisibility(R.id.mpLayout, View.GONE);
}
notification.contentView = contentView;
SupportClass.g_notificationManager = mNotificationManager;
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the framerate
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
//notification.defaults |= Notification.DEFAULT_SOUND; // Sound
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
mNotificationManager.notify(0, notification);
SupportClass.g_flag = false;
}
public void setListeners(RemoteViews view) {
//listener 1
Intent start = new Intent(context, StartReceiver.class);
start.putExtra("DO", "start");
start.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent btn1 = PendingIntent.getBroadcast(context, 0, start, 0);
notification.contentIntent = btn1;
view.setOnClickPendingIntent(R.id.startLayout, btn1);
//listener 2
Intent rate1 = new Intent(context, StartReceiver.class);
rate1.putExtra("DO", "movie");
rate1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
rate1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent btn2 = PendingIntent.getBroadcast(context, 1, rate1, 0);
notification.contentIntent = btn2;
view.setOnClickPendingIntent(R.id.movieLayout, btn2);
//listener 2
Intent rate = new Intent(context, FrameRate.class);
rate.putExtra("DO", "rate");
rate.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
rate.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent btn3 = PendingIntent.getActivity(context, 1, rate, 0);
notification.contentIntent = btn3;
view.setOnClickPendingIntent(R.id.fpsLayout, btn3);
Intent bit_rate = new Intent(context, BitRate.class);
bit_rate.putExtra("DO", "brate");
PendingIntent btn5 = PendingIntent.getActivity(context, 1, bit_rate, 0);
notification.contentIntent = btn5;
view.setOnClickPendingIntent(R.id.mpLayout, btn5);
//listener 3
Intent exit = new Intent(context, StopReceiver.class);
exit.putExtra("DO", "exit");
PendingIntent btn4 = PendingIntent.getBroadcast(context, 1, exit, 0);
notification.contentIntent = btn4;
view.setOnClickPendingIntent(R.id.exitLayout, btn4);
}
}
|
package com.example.appuel.fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.appuel.R;
import com.example.appuel.adapter.LichthiAdapter;
import com.example.appuel.databinding.FragmentLichthiBinding;
import com.example.appuel.databinding.FragmentThoikhoabieuBinding;
import com.example.appuel.modal.LichThi;
import com.example.appuel.modal.SinhVien;
import com.example.appuel.util.CheckConnection;
import com.example.appuel.util.Server;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class LichThi_Fragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
Context context;
ArrayList<LichThi> listLichthi = new ArrayList<>();
LichthiAdapter lichthiAdapter;
public LichThi_Fragment() {
// Required empty public constructor
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
context = getActivity();
binding = FragmentLichthiBinding.inflate(inflater, container, false);
ActionToolbar();
addControl();
GetDataLichThi();
return binding.root;
}
private void GetDataLichThi() {
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Server.linkLichthi, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
int id = jsonObject.getInt("Id");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String ngaythi = jsonObject.getString("Ngaythi");
Date date=sdf.parse(ngaythi);
String giothi = jsonObject.getString("Giothi");
String mamonhoc = jsonObject.getString("Mamonhoc");
String tenmonhoc = jsonObject.getString("Tenmonhoc");
String phongthi = jsonObject.getString("Phongthi");
listLichthi.add(new LichThi(id,date,giothi,mamonhoc,tenmonhoc,phongthi));
lichthiAdapter.notifyDataSetChanged();
} catch (Exception ex) {
Log.d("TAG", "LOI: " + ex);
}
}
Log.d("TAG", "lichthi: "+listLichthi);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
CheckConnection.showToast(context, error.toString());
}
});
requestQueue.add(jsonArrayRequest);
}
private void addControl() {
lichthiAdapter=new LichthiAdapter(listLichthi,context);
binding.lvLichThi.setAdapter(lichthiAdapter);
}
public static LichThi_Fragment newInstance(String param1, String param2) {
LichThi_Fragment fragment = new LichThi_Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
FragmentLichthiBinding binding;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
super.onCreate(savedInstanceState);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.notification, menu);
super.onCreateOptionsMenu(menu, inflater);
}
private void ActionToolbar() {
((AppCompatActivity) context).setSupportActionBar(binding.toolbarLichThi);
}
}
|
package com.itheima.bos.test;
import net.sf.json.JSONObject;
import cn.itcast.crm.domain.Customer;
public class JsonLibTest {
public static void main(String[] args) {
Customer c = null;
String json = JSONObject.fromObject(c).toString();
System.out.println(json);
}
}
|
package cn.sau.one.po;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class PictureExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public PictureExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andPictureIdIsNull() {
addCriterion("picture_id is null");
return (Criteria) this;
}
public Criteria andPictureIdIsNotNull() {
addCriterion("picture_id is not null");
return (Criteria) this;
}
public Criteria andPictureIdEqualTo(Integer value) {
addCriterion("picture_id =", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdNotEqualTo(Integer value) {
addCriterion("picture_id <>", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdGreaterThan(Integer value) {
addCriterion("picture_id >", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdGreaterThanOrEqualTo(Integer value) {
addCriterion("picture_id >=", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdLessThan(Integer value) {
addCriterion("picture_id <", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdLessThanOrEqualTo(Integer value) {
addCriterion("picture_id <=", value, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdIn(List<Integer> values) {
addCriterion("picture_id in", values, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdNotIn(List<Integer> values) {
addCriterion("picture_id not in", values, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdBetween(Integer value1, Integer value2) {
addCriterion("picture_id between", value1, value2, "pictureId");
return (Criteria) this;
}
public Criteria andPictureIdNotBetween(Integer value1, Integer value2) {
addCriterion("picture_id not between", value1, value2, "pictureId");
return (Criteria) this;
}
public Criteria andPictureUrlIsNull() {
addCriterion("picture_url is null");
return (Criteria) this;
}
public Criteria andPictureUrlIsNotNull() {
addCriterion("picture_url is not null");
return (Criteria) this;
}
public Criteria andPictureUrlEqualTo(String value) {
addCriterion("picture_url =", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlNotEqualTo(String value) {
addCriterion("picture_url <>", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlGreaterThan(String value) {
addCriterion("picture_url >", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlGreaterThanOrEqualTo(String value) {
addCriterion("picture_url >=", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlLessThan(String value) {
addCriterion("picture_url <", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlLessThanOrEqualTo(String value) {
addCriterion("picture_url <=", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlLike(String value) {
addCriterion("picture_url like", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlNotLike(String value) {
addCriterion("picture_url not like", value, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlIn(List<String> values) {
addCriterion("picture_url in", values, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlNotIn(List<String> values) {
addCriterion("picture_url not in", values, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlBetween(String value1, String value2) {
addCriterion("picture_url between", value1, value2, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureUrlNotBetween(String value1, String value2) {
addCriterion("picture_url not between", value1, value2, "pictureUrl");
return (Criteria) this;
}
public Criteria andPictureTypeIsNull() {
addCriterion("picture_type is null");
return (Criteria) this;
}
public Criteria andPictureTypeIsNotNull() {
addCriterion("picture_type is not null");
return (Criteria) this;
}
public Criteria andPictureTypeEqualTo(String value) {
addCriterion("picture_type =", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeNotEqualTo(String value) {
addCriterion("picture_type <>", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeGreaterThan(String value) {
addCriterion("picture_type >", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeGreaterThanOrEqualTo(String value) {
addCriterion("picture_type >=", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeLessThan(String value) {
addCriterion("picture_type <", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeLessThanOrEqualTo(String value) {
addCriterion("picture_type <=", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeLike(String value) {
addCriterion("picture_type like", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeNotLike(String value) {
addCriterion("picture_type not like", value, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeIn(List<String> values) {
addCriterion("picture_type in", values, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeNotIn(List<String> values) {
addCriterion("picture_type not in", values, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeBetween(String value1, String value2) {
addCriterion("picture_type between", value1, value2, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTypeNotBetween(String value1, String value2) {
addCriterion("picture_type not between", value1, value2, "pictureType");
return (Criteria) this;
}
public Criteria andPictureTimeIsNull() {
addCriterion("picture_time is null");
return (Criteria) this;
}
public Criteria andPictureTimeIsNotNull() {
addCriterion("picture_time is not null");
return (Criteria) this;
}
public Criteria andPictureTimeEqualTo(Date value) {
addCriterion("picture_time =", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeNotEqualTo(Date value) {
addCriterion("picture_time <>", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeGreaterThan(Date value) {
addCriterion("picture_time >", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeGreaterThanOrEqualTo(Date value) {
addCriterion("picture_time >=", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeLessThan(Date value) {
addCriterion("picture_time <", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeLessThanOrEqualTo(Date value) {
addCriterion("picture_time <=", value, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeIn(List<Date> values) {
addCriterion("picture_time in", values, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeNotIn(List<Date> values) {
addCriterion("picture_time not in", values, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeBetween(Date value1, Date value2) {
addCriterion("picture_time between", value1, value2, "pictureTime");
return (Criteria) this;
}
public Criteria andPictureTimeNotBetween(Date value1, Date value2) {
addCriterion("picture_time not between", value1, value2, "pictureTime");
return (Criteria) this;
}
public Criteria andUserIdIsNull() {
addCriterion("user_id is null");
return (Criteria) this;
}
public Criteria andUserIdIsNotNull() {
addCriterion("user_id is not null");
return (Criteria) this;
}
public Criteria andUserIdEqualTo(Integer value) {
addCriterion("user_id =", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotEqualTo(Integer value) {
addCriterion("user_id <>", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThan(Integer value) {
addCriterion("user_id >", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {
addCriterion("user_id >=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThan(Integer value) {
addCriterion("user_id <", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThanOrEqualTo(Integer value) {
addCriterion("user_id <=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdIn(List<Integer> values) {
addCriterion("user_id in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotIn(List<Integer> values) {
addCriterion("user_id not in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdBetween(Integer value1, Integer value2) {
addCriterion("user_id between", value1, value2, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotBetween(Integer value1, Integer value2) {
addCriterion("user_id not between", value1, value2, "userId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
package com.yecoo.dao;
import java.util.List;
import com.yecoo.model.CodeTableForm;
import com.yecoo.util.DbUtils;
import com.yecoo.util.Md5;
import com.yecoo.util.StrUtils;
/**
* 用户管理
* @author zhoujd
*/
public class UserDaoImpl extends BaseDaoImpl {
private DbUtils dbUtils = new DbUtils();
/**
* 用户数量
* @param form
* @return
*/
public int getUserCount(CodeTableForm form) {
String sql = "SELECT COUNT(t.userid) FROM suser t WHERE 1 = 1";
String cond = getUserListCondition(form);
sql += cond;
int count = dbUtils.getIntBySql(sql);
return count;
}
/**
* 用户列表
* @param form
* @param pageNum
* @param numPerPage
* @return
*/
public List<CodeTableForm> getUserList(CodeTableForm form) {
String sql = "SELECT * FROM suser t WHERE 1 = 1";
String cond = getUserListCondition(form);
sql += cond;
sql += " LIMIT " + (pageNum-1)*numPerPage + "," + numPerPage;
List<CodeTableForm> list = dbUtils.getListBySql(sql);
return list;
}
/**
* 用户列表-条件
* @param form
* @return
*/
public String getUserListCondition(CodeTableForm form) {
StringBuffer cond = new StringBuffer("");
String username = StrUtils.nullToStr(form.getValue("username"));
if(!username.equals("")) {
cond.append(" AND t.username like '%").append(username).append("%'");
}
return cond.toString();
}
/**
* 获取用户信息
* @param userid
* @return
*/
public CodeTableForm getUserById(String userid) {
String sql = "SELECT a.* FROM suser a WHERE a.userid = upper('" + userid + "')";
CodeTableForm codeTableForm = dbUtils.getFormBySql(sql);
return codeTableForm;
}
/**
* 新增用户
* @param form
* @return
*/
public int addUser(CodeTableForm form) {
//密码加密
String passwd = StrUtils.nullToStr(form.getValue("passwd"));
if(!passwd.equals("")) {
Md5 md5 = new Md5();
form.setValue("passwd", md5.md5(passwd));
}
int iReturn = dbUtils.setInsert(form, "suser", "");
return iReturn;
}
/**
* 修改用户
* @param form
* @return
*/
public int ediUser(CodeTableForm form) {
//密码加密
String passwd = StrUtils.nullToStr(form.getValue("passwd"));
if(!passwd.equals("")) {
Md5 md5 = new Md5();
form.setValue("passwd", md5.md5(passwd));
}
int iReturn = dbUtils.setUpdate(form, "", "suser", "userid", "");
return iReturn;
}
/**
* 删除用户
* @param userids
* @return
*/
public int deleteUsers(String userids) {
String sql = "DELETE FROM suser WHERE userid IN (" + userids + ")";
return dbUtils.executeSQL(sql);
}
public int changePassword(CodeTableForm form) {
//密码加密
String passwd = StrUtils.nullToStr(form.getValue("passwd"));
if(!passwd.equals("")) {
Md5 md5 = new Md5();
form.setValue("passwd", md5.md5(passwd));
}
int iReturn = dbUtils.setUpdate(form, "suser", "userid");
return iReturn;
}
}
|
package codingBat.recursion2;
public class Exe7SplitOdd10 {
/*
Given an array of ints, is it possible to divide the ints into two groups, so that the sum of one group is a multiple of 10,
and the sum of the other group is odd. Every int must be in one group or the other. Write a recursive helper method
that takes whatever arguments you like, and make the initial call to your recursive helper from splitOdd10(). (No loops needed.)
splitOdd10([5, 5, 5]) → true
splitOdd10([5, 5, 6]) → false
splitOdd10([5, 5, 6, 1]) → true
*/
public boolean splitOdd10(int[] nums) {
return helper(0,nums,0,0);
}
private boolean helper(int start, int[] nums, int mult10, int odd) {
if (start>= nums.length) return (mult10%10==0 && odd%2==1);
return helper(start+1,nums, mult10+nums[start], odd) ||
helper(start+1,nums, mult10, odd+nums[start]);
}
}
|
package ObserverDesignPattern;
/**
* Created by Frank Fang on 8/25/18.
*/
public class IStateWatcherA implements IStateObserver{
public IStateWatcherA(){
System.out.println("This is StateWatcherA");
}
@Override
public void onStateChange(){
System.out.println("StateWatchA watches StateChange");
System.out.println("StateWatchA sell the stock");
}
}
|
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.io.PrintStream;
public class House {
private int temperature = 20;
private ArrayList<Appliance> houseAppliance = new ArrayList<Appliance>();
private ArrayList<Person> housePersons = new ArrayList<Person>();
private Meter waterMeter;
private Meter gasMeter;
private Meter electricMeter;
private boolean isWaterMeter = false;
private boolean isGasMeter = false;
private boolean isElectricMeter = false;
private PrintStream printer = new PrintStream("Register.txt");
public House() throws FileNotFoundException {
}
protected Meter getWaterMeter() {
return waterMeter;
}
protected Meter getElectricMeter() {
return electricMeter;
}
protected Meter getGasMeter() {
return gasMeter;
}
/**
* Add a meter to the house if there is no meter of the same type
*/
protected void addMeter(Meter meter) {
if (meter.getType().equals("electric") && !isElectricMeter) {
electricMeter = new ElectricMeter(meter.getConsumed(), meter.canGenerate());
isElectricMeter = true;
} else if (meter.getType().equals("gas") && !isGasMeter) {
gasMeter = new GasMeter(meter.getConsumed(), meter.canGenerate());
isGasMeter = true;
} else if (meter.getType().equals("water") && !isWaterMeter) {
waterMeter = new WaterMeter(meter.getConsumed(), meter.canGenerate());
isWaterMeter = true;
} else System.out.println("There is already one " + meter.getType() + " meter in the house");
}
protected ArrayList<Appliance> getHouseApplianceList() {
return houseAppliance;
}
/**
* This method adds a new appliance to the house
* It won't allow more than 25 appliances
*/
protected void addAppliance(Appliance appliance) {
if (houseAppliance.size() < 25) {
houseAppliance.add(appliance);
} else System.out.println("The house has 25 appliances already");
}
protected void removeAppliance(Appliance appliance) {
houseAppliance.remove(appliance);
}
protected int numAppliances() {
return houseAppliance.size();
}
protected ArrayList<Person> getHousePersons() {
return housePersons;
}
protected void addPerson(Person person) {
housePersons.add(person);
}
protected Person getLastPerson() {
return housePersons.get(housePersons.size() - 1);
}
protected int getTemperature() {
return temperature;
}
protected void increaseTempereture() {
temperature++;
}
/**
* First it calls timePasses() on every person in the house
* After that, some appliances are turned on, some not depending on tasks and appliance type
* Then it iterates over the appliance list and calls timePasses() on every appliance
*/
private void timePasses() {
for (Person person : housePersons)
person.timePasses();
for (Appliance appliance : houseAppliance)
appliance.timePasses();
}
private void printResults() {
int quantity; // in this integer the generated amount of energy will be substracted from the consumed one
if (electricMeter != null) {
quantity = electricMeter.getConsumed() - electricMeter.getGenerated();
System.out.println("The electricity consumed by this house in a day was " + quantity);
printer.println(("The electricity consumed by this house in a day was " + quantity));
}
if (gasMeter != null) {
System.out.println("The gas consumed by this house in a day was " + gasMeter.getConsumed());
printer.println(("The electricity consumed by this house in a day was " + gasMeter.getConsumed()));
}
if (waterMeter != null) {
System.out.println("The water consumed by this house in a day was " + waterMeter.getConsumed());
printer.println(("The electricity consumed by this house in a day was " + waterMeter.getConsumed()));
}
}
/**
* Calls timePasses() in the house for 96 times wich is the equivalent of one day
* Prints the results using the printResults() method
* The temperature drops once every 2 hours
* Considering that the first part of the day is during night, the teperature will drop by 2 degrees
* Otherwise, if it is not the middle of the day, it drops by 1 degree
*/
protected void go() {
for (int i = 1; i < 97; i++) {
if (i % 8 == 0 && i < 25) {
temperature = temperature - 2;
} else if (i % 8 == 0 && i < 49)
temperature--;
else if (i % 8 == 0 && i > 72)
temperature--;
this.timePasses();
}
this.printResults();
}
/**
* Run the program by simply creating a new Simulator
*/
public static void main(String[] args) {
try {
Simulator simulator = new Simulator();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
package sortingalgorithmstutor.SortingAlgorithmsPainters;
import java.awt.Color;
/**This class is mostly used in animation of algorithms, represents one element in
* array to sort with some aditional information
*
* @author Petr
*/
public class Element
{
public String stringNumber;
public int xNumberCoordinate;
public int yNumberCoordinate;
public int actualNumber;
public boolean isVisible = true;
public int collumnWidth;
public int collumnHeight;
public int xCollumnCoordinate;
public int yCollumnCoordinate;
//for drawing in countingSort purposes only...
public int tmpxNumberCoordinate;
public int tmpyNumberCoordinate;
public int tmpxCollumnCoordinate;
public int tmpyCollumnCoordinate;
public boolean isPulledDown = false;
public boolean aboveBucket = false;
public Color c = Color.BLUE;
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.translation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import pl.edu.icm.unity.exceptions.InternalException;
import pl.edu.icm.unity.server.registries.TypesRegistryBase;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.types.translation.ProfileType;
import pl.edu.icm.unity.types.translation.TranslationProfile;
import pl.edu.icm.unity.types.translation.TranslationRule;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* The translation profile instance is a {@link TranslationProfile}, enriched in that way that it can be executed,
* while {@link TranslationProfile} only stores a description of a profile. This class is an abstract root of all
* types of translation profile instances, implementing initialization of {@link TranslationRuleInstance}s.
*
* @author K. Benedyczak
*/
public abstract class TranslationProfileInstance<T extends TranslationActionInstance, R extends TranslationRuleInstance<T>>
extends TranslationProfile
{
private static final Logger log = Log.getLogger(Log.U_SERVER, TranslationActionInstance.class);
protected List<R> ruleInstances;
public TranslationProfileInstance(String name, String description, ProfileType profileType,
List<? extends TranslationRule> rules, TypesRegistryBase<? extends TranslationActionFactory> registry)
{
super(name, description, profileType, rules);
initInstance(registry);
}
public TranslationProfileInstance(ObjectNode json, TypesRegistryBase<? extends TranslationActionFactory> registry)
{
super(json);
initInstance(registry);
}
/**
* @return list of profile's rules
*/
public List<R> getRuleInstances()
{
return ruleInstances;
}
protected void initInstance(TypesRegistryBase<? extends TranslationActionFactory> registry)
{
ruleInstances = new ArrayList<>(getRules().size());
try
{
for (TranslationRule rule: getRules())
{
TranslationActionFactory fact = registry.getByName(rule.getAction().getName());
String[] parameters = rule.getAction().getParameters();
TranslationActionInstance actionInstance = loadAction(fact, parameters);
ruleInstances.add(createRule(actionInstance,
new TranslationCondition(rule.getCondition())));
}
} catch (Exception e)
{
throw new InternalException("Can't create runtime instance of a translation profile", e);
}
}
private TranslationActionInstance loadAction(TranslationActionFactory fact, String[] parameters)
{
try
{
return fact.getInstance(parameters);
} catch (Exception e)
{
log.error("Can not load action " + fact.getActionType().getName() + " with parameters: " +
Arrays.toString(parameters) +
". This action will be ignored during profile's execution. "
+ "Fix the action definition. This problem can occur after system "
+ "reconfiguration when action definition becomes obsolete "
+ "(e.g. using not existing attribute)", e);
return fact.getBlindInstance(parameters);
}
}
/**
* Must return a correct instance of a rule. Should check if the action is of proper type.
* @param action
* @param condition
* @return
*/
protected abstract R createRule(TranslationActionInstance action, TranslationCondition condition);
}
|
/*
* array is a reference type
*/
package Arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author YNZ
*/
public class ArrayIsObj {
public static void changeIt(Double[] d, Double n) {
ArrayList<Double> al = new ArrayList<>();
al.addAll(Arrays.asList(d));//allAll e1 e2 e3
al.add(n); //all {e1 e2 e3}
System.out.println(al.toArray(d) instanceof Double[]);//cannot casting object into its sub-type.
d = al.toArray(d);
System.out.println("in changeIt: " + Arrays.toString(d));
}
public static double[] appendArray(double[] d, double[] n) {
double[] tmp = new double[d.length + n.length - 1];
System.arraycopy(d, 0, tmp, 0, d.length);
System.arraycopy(n, 0, tmp, d.length - 1, n.length);
return tmp;
}
public static void changeReferenceType(List<Double> list) {
list.add(new Double(5998));
}
public static void appendString(String[] str) {
String[] tmp = new String[str.length + 1];
tmp[tmp.length - 1] = "or I am here";
str = tmp;
System.out.println("within change string[]" + Arrays.toString(str));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//array is considered something like a primitive type.
//it is passed by a copy; it doesn't change its mirror externally
Double[] d = new Double[]{12.3, 34.5};
System.out.println("before changeIt: " + Arrays.toString(d));
changeIt(d, new Double(456));
System.out.println("after changeIt: " + Arrays.toString(d));
double[] s = {12, 454.85, 8475.977};
double[] n = {123.98, 99.999};
double[] p = appendArray(s, n);
System.out.println(Arrays.toString(p));
List<Double> list = new ArrayList(Arrays.asList(d));
System.out.println("before changeIt: " + list);
changeReferenceType(list);
System.out.println("after changeIt" + list);
//it seems in java primitive type will be considered pass by copy.
//whatever you cannot change Array from a method. then you need to return it.
//however, this is not about the ArrayList, called reference type.
String[] str = new String[]{"dou dou", "wo wo"};
System.out.println("before change string[]" + Arrays.toString(str));
appendString(str);
System.out.println("after change string[]" + Arrays.toString(str));
String testStr = "am testing";
System.out.println("String is Object: " + (testStr instanceof String));
}
}
|
package org.qw3rtrun.aub.engine.property.transform;
import org.junit.Test;
import org.qw3rtrun.aub.engine.property.matrix.Matrix4fBinding;
import org.qw3rtrun.aub.engine.property.vector.Vector3fBinding;
import org.qw3rtrun.aub.engine.property.vector.Vector3fProperty;
import org.qw3rtrun.aub.engine.vectmath.Matrix4f;
import org.qw3rtrun.aub.engine.vectmath.Vector3f;
import org.qw3rtrun.aub.engine.vectmath.Vector4f;
import static org.junit.Assert.assertThat;
import static org.qw3rtrun.aub.engine.Matchers.nearTo;
import static org.qw3rtrun.aub.engine.property.vector.Vector3fConstant.CONST_X;
import static org.qw3rtrun.aub.engine.property.vector.Vector3fConstant.vect3fc;
import static org.qw3rtrun.aub.engine.vectmath.Vector3f.X;
import static org.qw3rtrun.aub.engine.vectmath.Vector3f.vect3f;
public class ScalingTest {
@Test
public void testScale() throws Exception {
Vector3fProperty a = new Vector3fProperty(vect3f(1, 2, 3));
Vector3fProperty b = new Vector3fProperty(Vector3f.XYZ);
Vector3fBinding scaling = new Scaling(a).apply(b);
assertThat(scaling, nearTo(vect3fc(1, 2, 3)));
a.setValue(-1, 0, 3);
assertThat(scaling, nearTo(vect3fc(-1, 0, 3)));
b.setValue(0, 1.5f, -1);
assertThat(scaling, nearTo(vect3fc(0, 0, -3)));
}
@Test
public void testInvertScale() throws Exception {
Vector3fProperty a = new Vector3fProperty(vect3f(1, 1f / 2, 1f / 3));
Vector3fProperty b = new Vector3fProperty(Vector3f.XYZ);
Vector3fBinding scaling = new Scaling(a).invert().apply(b);
assertThat(scaling, nearTo(vect3fc(1, 2, 3)));
a.setValue(-1, 1, 1f / 3);
assertThat(scaling, nearTo(vect3fc(-1, 1, 3)));
b.setValue(1, 1.5f, -1);
assertThat(scaling, nearTo(vect3fc(-1, 1.5f, -3)));
}
@Test
public void testMatrix() {
Scaling scaling = new Scaling(vect3fc(1, 2, 3));
Matrix4fBinding matrix = scaling.asMatrix();
assertThat(matrix.get(), nearTo(Matrix4f.cols(Vector4f.X.multiply(1), Vector4f.Y.multiply(2), Vector4f.Z.multiply(3), Vector4f.W.multiply(-1))));
assertThat(matrix.product(X), nearTo(scaling.apply(CONST_X)));
}
}
|
package mysqltest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Random;
public class InsertSQL {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/selenium_test";
String user = "root";
String pwd = "123456";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, pwd);
if (!conn.isClosed())
System.out.println("connect mysql successfully");
Statement state = conn.createStatement();
String createTable = "create table people(id int, name varchar(20), age int)";
state.executeLargeUpdate(createTable);
String[] arr = new String[]{"benchi", "kk", "mashaladi", "falali"};
for (int i = 0; i <= 10 ; i++) {
int n = new Random().nextInt(arr.length - 1);
String insertData = String.format("insert into people values(%s, '%s', 18)", i, arr[n]);
// System.out.println(insertData);
conn.prepareStatement(insertData).execute();
}
}
}
|
package ba.fit.rent_a_car.app;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Zrinko on 11.11.2014..
*/
public class Automobil {
String SikaURL;
String Boja;
String GodinaProizvodnje;
String automobilID;
String NazivProzvodjaca;
String NazivModela;
String Gorivo;
String Transmisija;
int CijenaPoDanu;
public String getGorivo() {
return Gorivo;
}
public void setGorivo(String gorivo) {
Gorivo = gorivo;
}
public String getTransmisija() {
return Transmisija;
}
public void setTransmisija(String transmisija) {
Transmisija = transmisija;
}
public int getCijenaPoDanu() {
return CijenaPoDanu;
}
public void setCijenaPoDanu(int cijenaPoDanu) {
CijenaPoDanu = cijenaPoDanu;
}
public String getNazivProzvodjaca() {
return NazivProzvodjaca;
}
public void setNazivProzvodjaca(String nazivProzvodjaca) {
NazivProzvodjaca = nazivProzvodjaca;
}
public String getNavizModela() {
return NazivModela;
}
public void setNavizModela(String nazivModela) {
NazivModela = nazivModela;
}
public String getSikaURL() {
return SikaURL;
}
public void setSikaURL(String slika) {
SikaURL = slika;
}
public String getBoja() {
return Boja;
}
public void setBoja(String boja) {
Boja = boja;
}
public String getGodinaProizvodnje() {
return GodinaProizvodnje;
}
public void setGodinaProizvodnje(String godinaProizvodnje) {
GodinaProizvodnje = godinaProizvodnje;
}
public String getAutomobilID() {
return automobilID;
}
public void setAutomobilID(String automobilID) {
this.automobilID = automobilID;
}
// Constructor to convert JSON object into a Java class instance
public Automobil(JSONObject object){
try {
this.Boja = object.getString("Boja");
this.SikaURL=object.getString("Slika");
this.automobilID=object.getString("autoID");
this.NazivProzvodjaca=object.getString("Naziv_proizvodjaca");
this.NazivModela=object.getString("Naziv_Modela");
this.GodinaProizvodnje=object.getString("Godina_proizvodnje");
this.Gorivo=object.getString("Gorivo");
this.Transmisija=object.getString("Transmisija");
this.CijenaPoDanu=object.getInt("cijenaPoDanu");
} catch (JSONException e) {
e.printStackTrace();
}
}
// Factory method to convert an array of JSON objects into a list of objects
// Narudzba.fromJson(jsonArray);
public static ArrayList<Automobil> fromJson(JSONArray jsonObjects) {
ArrayList<Automobil> automobili = new ArrayList<Automobil>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
automobili.add(new Automobil(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return automobili;
}
}
|
/*
* in absence of break, what happends?
* it will fall in following cases, until find a break.
*
*/
package Switch;
/**
*
* @author YNZ
*/
public class EJavaGuru3 {
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
byte foo = 120;
switch (foo) {
default:
System.out.println("ejavaguru");
break;
case 2:
System.out.println("e");
break;
case 120:
System.out.println("ejava");
case 121:
System.out.println("enum");
case 127:
System.out.println("guru");
break;
}
}
}
|
import java.util.Iterator;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
public class MyHashTable<K, V> implements HashTableAPI<K, V> {
private int size;
private double loadFactor;
private List<Entry> buckets;
private Set<K> keySet;
private int numBuckets;
private int hashFunc(K key, int numBuckets) {
return Math.floorMod(key.hashCode(), numBuckets);
}
public MyHashTable() {
size = 0;
loadFactor = 0.75;
buckets = new ArrayList<Entry>(16);
for (int i = 0 ; i < 16 ; i++) {
buckets.add(i, null);
}
keySet = new HashSet<K>();
numBuckets = 16;
}
public MyHashTable(int initialSize) {
size = 0;
loadFactor = 0.75;
buckets = new ArrayList<Entry>(initialSize);
for (int i = 0 ; i < initialSize ; i++) {
buckets.add(i, null);
}
keySet = new HashSet<K>();
numBuckets = initialSize;
}
public MyHashTable(int initialSize, double loadFactor) {
size = 0;
this.loadFactor = loadFactor;
buckets = new ArrayList<Entry>(initialSize);
for (int i = 0 ; i < initialSize ; i++) {
buckets.add(i, null);
}
keySet = new HashSet<K>();
numBuckets = initialSize;
}
private class Entry {
K key;
V val;
Entry next;
Entry(K k, V v, Entry n) {
key = k;
val = v;
next = n;
}
Entry get(K k) {
if (k != null && k.equals(key)) {
return this;
}
if (next == null) {
return null;
}
return next.get(k);
}
}
@Override
public void clear() {
size = 0;
buckets = new ArrayList<Entry>(16);
for (int i = 0 ; i < 16 ; i++) {
buckets.add(i, null);
}
keySet = new HashSet<K>();
numBuckets = 16;
}
@Override
public boolean containsKey(K key) {
return get(key) != null;
}
@Override
public V get(K key) {
int hc = hashFunc(key, numBuckets);
if (buckets.get(hc) == null) {
return null;
}
return buckets.get(hc).val;
}
@Override
public int size() {
return size;
}
private void resize(int newSize) {
List<Entry> newBuckets = new ArrayList<Entry>(newSize);
for (int i = 0 ; i < newSize ; i++) {
newBuckets.add(i, null);
}
for (K key : keySet) {
int hc = hashFunc(key, newSize);
V value = get(key);
Entry e = newBuckets.get(hc);
if (e == null) {
newBuckets.set(hc, new Entry(key, value, null));
} else {
newBuckets.set(hc, new Entry(key, value, e));
}
}
buckets = newBuckets;
numBuckets = newSize;
}
@Override
public void put(K key, V value) {
if ((double) size / (double) numBuckets > loadFactor) {
resize(numBuckets * 2);
}
int hc = hashFunc(key, numBuckets);
Entry e = buckets.get(hc);
if (e == null) {
Entry newEntry = new Entry(key, value, null);
buckets.set(hc, newEntry);
size++;
keySet.add(key);
} else {
if (e.get(key) == null) {
buckets.set(hc, new Entry(key, value, e));
size++;
keySet.add(key);
} else {
buckets.get(hc).get(key).val = value;
}
}
}
@Override
public Set keySet() {
return keySet;
}
@Override
public V remove(K key) {
throw new UnsupportedOperationException();
}
@Override
public V remove(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<K> iterator() {
return keySet.iterator();
}
}
|
package com.ider.ytb_tv.ui.activity;
import android.os.Bundle;
import com.ider.ytb_tv.R;
/**
* Created by ider-eric on 2016/8/17.
*/
public class SearchActivity extends ServiceActivity {
@Override
void serviceConnected() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
}
|
package demo.utility;
import demo.domain.Ad;
import demo.domain.AdRepository;
import net.spy.memcached.MemcachedClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class AdsSelector {
private static AdsSelector instance = null;
//private int EXP = 7200;
private AdRepository adRepository;
private MemcachedClient memcachedClient;
private AdsSelector(MemcachedClient memcachedClient, AdRepository adRepository) {
this.memcachedClient = memcachedClient;
this.adRepository = adRepository;
}
public static AdsSelector getInstance(MemcachedClient memcachedClient, AdRepository adRepository) {
if (instance == null) {
instance = new AdsSelector(memcachedClient, adRepository);
}
return instance;
}
public List<Ad> selectAds(List<String> queryTerms) {
List<Ad> adList = new ArrayList<Ad>();
//key: adID, value : count of adId which match current query
HashMap<Long, Integer> matchedAds = new HashMap<Long, Integer>();
try {
for (String queryTerm : queryTerms) {
System.out.println("selectAds queryTerm = " + queryTerm);
Set<Long> adIdList = (Set<Long>) this.memcachedClient.get(queryTerm);
if (adIdList != null && adIdList.size() > 0) {
for (Object adId : adIdList) {
Long key = (Long) adId;
if (matchedAds.containsKey(key)) {
int count = matchedAds.get(key) + 1;
matchedAds.put(key, count);
} else {
matchedAds.put(key, 1);
}
}
}
}
for (Long adId : matchedAds.keySet()) {
System.out.println("selectAds adId = " + adId);
Ad ad = adRepository.getAdByAdId(adId);
if (ad == null) continue;
//number of word match query / total number of words in key words
double relevanceScore = (matchedAds.get(adId) * 1.0 / ad.getKeyWords().split(",").length);
ad.setRelevanceScore(relevanceScore);
System.out.println("selectAds pClick = " + ad.getPClick());
System.out.println("selectAds relevanceScore = " + ad.getRelevanceScore());
adList.add(ad);
}
} catch (Exception e) {
e.printStackTrace();
}
return adList;
}
}
|
package player.Equipe2;
import pacman.Game;
import pacman.Location;
import pacman.State;
import java.util.Collection;
public class PacmanStateEvaluator {
public static int MAX_DOTS_COUNT = 245;
public static double evaluateState(State state){
if (Game.isLosing(state))
return -1000.0;
if (Game.isWinning(state))
return 1000.0;
double score = 0.0;
Location pacManLocation = state.getPacManLocation();
double dotsProportion = (double)1 / state.getDotLocations().size() * MAX_DOTS_COUNT;
score += Math.pow(dotsProportion, 16);
score += getMinDistance(pacManLocation, state.getDotLocations()) * Math.pow(dotsProportion, 16);
score += getMinDistance(pacManLocation, state.getGhostLocations());
return score;
}
private static double getMinDistance(Location sourceLocation, Collection<Location> targetLocations) {
double minDistance = Double.POSITIVE_INFINITY;
for (Location dotLocation : targetLocations) {
double distance = Location.manhattanDistance(sourceLocation, dotLocation);
if (distance < minDistance) {
minDistance = distance;
}
}
if (Double.isInfinite(minDistance))
throw new RuntimeException();
return minDistance;
}
}
|
package com.auro.scholr.teacher.presentation.view.fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.auro.scholr.R;
import com.auro.scholr.core.application.AuroApp;
import com.auro.scholr.core.application.base_component.BaseFragment;
import com.auro.scholr.core.application.di.component.ViewModelFactory;
import com.auro.scholr.core.common.AppConstant;
import com.auro.scholr.core.common.CommonCallBackListner;
import com.auro.scholr.core.common.CommonDataModel;
import com.auro.scholr.core.common.Status;
import com.auro.scholr.databinding.FragmentTeacherInfoBinding;
import com.auro.scholr.home.presentation.view.activity.HomeActivity;
import com.auro.scholr.teacher.data.model.response.MyClassRoomTeacherResModel;
import com.auro.scholr.teacher.data.model.response.TeacherProgressModel;
import com.auro.scholr.teacher.data.model.response.ZohoAppointmentListModel;
import com.auro.scholr.teacher.presentation.view.adapter.TeacherProgressAdapter;
import com.auro.scholr.teacher.presentation.viewmodel.TeacherInfoViewModel;
import com.auro.scholr.util.AppLogger;
import com.auro.scholr.util.AppUtil;
import com.auro.scholr.util.ViewUtil;
import com.auro.scholr.util.alert_dialog.CustomDialogModel;
import com.auro.scholr.util.alert_dialog.CustomProgressDialog;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Objects;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
public class TeacherInfoFragment extends BaseFragment implements CommonCallBackListner, View.OnClickListener {
@Inject
@Named("TeacherInfoFragment")
ViewModelFactory viewModelFactory;
FragmentTeacherInfoBinding binding;
TeacherInfoViewModel viewModel;
boolean isStateRestore;
CustomProgressDialog customProgressDialog;
Resources resources;
TeacherProgressAdapter mteacherProgressAdapter;
public TeacherInfoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (binding != null) {
isStateRestore = true;
return binding.getRoot();
}
binding = DataBindingUtil.inflate(inflater, getLayout(), container, false);
AuroApp.getAppComponent().doInjection(this);
AuroApp.getAppContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
viewModel = ViewModelProviders.of(this, viewModelFactory).get(TeacherInfoViewModel.class);
binding.setLifecycleOwner(this);
binding.setTeacherInfoViewModel(viewModel);
setRetainInstance(true);
return binding.getRoot();
}
@Override
protected void init() {
binding.headerTopParent.cambridgeHeading.setVisibility(View.GONE);
setListener();
viewModel.getTeacherDashboardData(AuroApp.getAuroScholarModel().getMobileNumber());
viewModel.getTeacherProgressData(AuroApp.getAuroScholarModel().getMobileNumber());
}
@Override
protected void setToolbar() {
}
@Override
protected void setListener() {
if (viewModel != null && viewModel.serviceLiveData().hasObservers()) {
viewModel.serviceLiveData().removeObservers(this);
} else {
observeServiceResponse();
}
binding.button.setOnClickListener(this);
}
private void openProgressDialog() {
CustomDialogModel customDialogModel = new CustomDialogModel();
customDialogModel.setContext(getActivity());
customDialogModel.setTitle(AuroApp.getAppContext().getResources().getString(R.string.getting_webinar_slots));
// customDialogModel.setContent(getActivity().getResources().getString(R.string.bullted_list));
customDialogModel.setTwoButtonRequired(false);
customProgressDialog = new CustomProgressDialog(customDialogModel);
Objects.requireNonNull(customProgressDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customProgressDialog.setCancelable(false);
customProgressDialog.show();
customProgressDialog.setProgressDialogText(AuroApp.getAppContext().getResources().getString(R.string.getting_webinar_slots));
// customProgressDialog.updateDataUi(0);
}
private void observeServiceResponse() {
viewModel.serviceLiveData().observeForever(responseApi -> {
switch (responseApi.status) {
case LOADING:
if (responseApi.apiTypeStatus == Status.GET_ZOHO_APPOINTMENT) {
openProgressDialog();
}
break;
case SUCCESS:
if (responseApi.apiTypeStatus == Status.GET_TEACHER_PROGRESS_API) {
binding.parentLayoutTwo.setVisibility(View.VISIBLE);
TeacherProgressModel teacherProgressModel = (TeacherProgressModel) responseApi.data;
binding.rvDoucumentUpload.setLayoutManager(new LinearLayoutManager(getActivity()));
binding.rvDoucumentUpload.setHasFixedSize(true);
binding.rvDoucumentUpload.setNestedScrollingEnabled(false);
mteacherProgressAdapter = new TeacherProgressAdapter(teacherProgressModel.teacherProgressStatusModels, this);
binding.rvDoucumentUpload.setAdapter(mteacherProgressAdapter);
}
if (responseApi.apiTypeStatus == Status.GET_ZOHO_APPOINTMENT) {
if (responseApi.apiTypeStatus == Status.GET_ZOHO_APPOINTMENT) {
if (customProgressDialog != null) {
customProgressDialog.dismiss();
}
}
ZohoAppointmentListModel zohoAppointmentListModel = (ZohoAppointmentListModel) responseApi.data;
Bundle bundle = new Bundle();
bundle.putParcelable(AppConstant.SENDING_DATA.APPOINTMENT_DATA, zohoAppointmentListModel);
SelectYourAppointmentDialogFragment fragment = new SelectYourAppointmentDialogFragment(); //where MyFragment is my fragment I want to show
fragment.setCancelable(true);
fragment.setArguments(bundle);
fragment.show(getActivity().getSupportFragmentManager(), TeacherInfoFragment.class.getSimpleName());
}
if (responseApi.apiTypeStatus == Status.GET_TEACHER_DASHBOARD_API) {
AppUtil.myClassRoomResModel = (MyClassRoomTeacherResModel) responseApi.data;
}
break;
case FAIL:
case NO_INTERNET:
if (responseApi.apiTypeStatus == Status.GET_TEACHER_PROGRESS_API) {
handleProgress(1);
showSnackbarError((String) responseApi.data);
}
if (responseApi.apiTypeStatus == Status.GET_ZOHO_APPOINTMENT) {
if (customProgressDialog != null) {
customProgressDialog.dismiss();
}
showSnackbarError((String) responseApi.data);
}
break;
default:
if (responseApi.apiTypeStatus == Status.GET_ZOHO_APPOINTMENT) {
if (customProgressDialog != null) {
customProgressDialog.dismiss();
}
}
handleProgress(1);
showSnackbarError(getString(R.string.default_error));
break;
}
});
}
public void handleProgress(int status) {
switch (status) {
case 0:
binding.button.setVisibility(View.GONE);
binding.progressBar.setVisibility(View.VISIBLE);
break;
case 1:
binding.button.setVisibility(View.VISIBLE);
binding.progressBar.setVisibility(View.GONE);
break;
}
}
@Override
public void onResume() {
super.onResume();
HomeActivity.setListingActiveFragment(HomeActivity.TEACHER_INFO_FRAGMENT);
resources = ViewUtil.getCustomResource(getActivity());
init();
}
@Override
protected int getLayout() {
return R.layout.fragment_teacher_info;
}
@Override
public void commonEventListner(CommonDataModel commonDataModel) {
switch (commonDataModel.getClickType()) {
case WEBINAR_CLICK:
// viewModel.getZohoAppointment();
break;
}
}
private void showSnackbarError(String message) {
ViewUtil.showSnackBar(binding.getRoot(), message);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AppLogger.e("chhonker", "fragment requestCode=" + requestCode);
}
@Override
public void onClick(View v) {
}
}
|
package pl.lukabrasi.weatheronline.dtos;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class CloudsDto {
private int all;
}
|
package com.qfc.yft.entity.offline;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.qfc.yft.utils.JackUtils;
public class OffShopInfo extends JsonOffline {
OffImage shopBannerPic;
JSONArray shopCertArray;
JSONArray shopPicsArray;
OffImage shopLogoPic;
int status ;
String updateTime;
int shopId;
public OffShopInfo(){
this(0);
}
public OffShopInfo(int shopId) {
super();
this.shopId = shopId;
this.shopBannerPic = new OffImage();
this.shopCertArray = new JSONArray();
this.shopPicsArray = new JSONArray();
this.shopLogoPic = new OffImage();
this.status = -1;
this.updateTime = JackUtils.getDate();
}
public OffShopInfo(JSONObject job){
super(job);
}
public int getSize() {
if(!countMe(status)) return 0;
int size = 0;
if(countMe(shopBannerPic.status)) size++;
if(countMe(shopLogoPic.status)) size++;
size+=getArraySize(shopCertArray);
size+=getArraySize(shopPicsArray);
return size;
}
@Override
public JSONObject toJsonObj() {
JSONObject job = new JSONObject();
try {
job.put(OFF_SHOPBANNERPIC, shopBannerPic.toJsonObj());
job.put(OFF_SHOPCERTARRAY, shopCertArray);
job.put(OFF_SHOPPICSARRAY, shopPicsArray);
job.put(OFF_SHOPLOGOPIC, shopLogoPic.toJsonObj());
job.put(OFF_SHOPID, shopId+"");//1209
job.put(OFF_STATUS, status+"");//1209
job.put(OFF_UPDATETIME, updateTime);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return job;
}
@Override
public void initJackJson(JSONObject job) {
if(job==null) return;
shopBannerPic=new OffImage(job.optJSONObject(OFF_SHOPBANNERPIC ));
shopCertArray=job.optJSONArray(OFF_SHOPCERTARRAY );
shopPicsArray=job.optJSONArray(OFF_SHOPPICSARRAY );
shopLogoPic=new OffImage(job.optJSONObject(OFF_SHOPLOGOPIC ));
shopId=job.optInt(OFF_SHOPID );
status=job.optInt(OFF_STATUS );
updateTime=job.optString(OFF_UPDATETIME );
}
public OffImage getShopBannerPic() {
return shopBannerPic;
}
public void setShopBannerPic(OffImage shopBannerPic) {
this.shopBannerPic = shopBannerPic;
}
public JSONArray getShopCertArray() {
return shopCertArray;
}
public void setShopCertArray(JSONArray shopCertArray) {
this.shopCertArray = shopCertArray;
}
public JSONArray getShopPicsArray() {
return shopPicsArray;
}
public void setShopPicsArray(JSONArray shopPicsArray) {
this.shopPicsArray = shopPicsArray;
}
public OffImage getShopLogoPic() {
return shopLogoPic;
}
public void setShopLogoPic(OffImage shopLogoPic) {
this.shopLogoPic = shopLogoPic;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public int getShopId() {
return shopId;
}
public void setShopId(int shopId) {
this.shopId = shopId;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow 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 any later version. *
* *
* Data Crow 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 net.datacrow.console.windows.drivemanager;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.Layout;
import net.datacrow.console.components.DcLongTextField;
import net.datacrow.core.resources.DcResources;
import net.datacrow.drivemanager.IDriveManagerListener;
import net.datacrow.drivemanager.JobAlreadyRunningException;
public abstract class DriveManagerPanel extends JPanel implements IDriveManagerListener {
private final DcLongTextField textHelp = ComponentFactory.getHelpTextField();
private final JobStatusPanel statusPanel;
public DriveManagerPanel() {
statusPanel = new JobStatusPanel(this);
build();
}
protected abstract ImageIcon getIcon();
protected abstract String getTitle();
protected abstract String getHelpText();
protected abstract void saveSettings();
protected abstract void start() throws JobAlreadyRunningException;
protected abstract void stop();
@Override
public void notify(String msg) {
statusPanel.setMessage(msg);
}
@Override
public void notifyJobStarted() {
notify(DcResources.getText("msgJobStartedAtX", new Date().toString()));
statusPanel.isRunning(true);
allowActions(false);
}
@Override
public void notifyJobStopped() {
notify(DcResources.getText("msgJobStoppedAtX", new Date().toString()));
statusPanel.isRunning(false);
allowActions(true);
}
protected void allowActions(boolean b) {}
@Override
public void setFont(Font font) {
super.setFont(font);
if (textHelp != null) {
textHelp.setFont(ComponentFactory.getStandardFont());
statusPanel.setFont(ComponentFactory.getStandardFont());
}
}
protected void build() {
setLayout(Layout.getGBL());
JPanel panel = new JPanel();
panel.setLayout(Layout.getGBL());
textHelp.setText(getHelpText());
textHelp.setPreferredSize(new Dimension(100, 60));
textHelp.setMinimumSize(new Dimension(100, 60));
textHelp.setMaximumSize(new Dimension(800, 60));
panel.add(textHelp, Layout.getGBC(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
panel.add(statusPanel, Layout.getGBC(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
add(panel, Layout.getGBC(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0), 0, 0));
}
}
|
package com.spring.testable.mock.pojo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 商户表实体
* @author caijie
* @date 2021/07/06 11:18
*/
@Data
@TableName("merchant")
public class Merchant implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编号
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 账户名称
*/
@TableField("account")
private String account;
/**
* 备用账号名称
*/
@TableField("bak_account")
private String bakAccount;
/**
* 备用账号id
*/
@TableField("bak_account_id")
private String bakAccountId;
/**
* 商家昵称
*/
private String nickname;
/**
* 解冻时间
*/
@TableField("freeze_dead_time")
private Date freezeDeadTime;
/**
* 等级:默认=0,1=商户V1,2=商户V2,3=商户V3
*/
private Integer level;
/**
* 状态:0=默认,1=已激活,2=取消激活,3=冻结
*/
private Integer status;
/**
* 资金权限:0=默认,1=已开启,2=已关闭
*/
private Integer authority;
/**
* 备注
*/
private String remark;
/**
* 是否删除 0=未删除 1=删除
*/
@TableField("is_deleted")
private Integer isDeleted;
/**
* 创建时间
*/
@TableField("created_time")
private Date createdTime;
/**
* 更新时间
*/
@TableField("updated_time")
private Date updatedTime;
}
|
package com.tu.rocketmq.config;
import com.tu.rocketmq.action.RockerMqAction;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
/**
* @Auther: tuyongjian
* @Date: 2020/4/21 15:36
* @Description: 事务消息的监听器
*
* txProducerGroup 事务生产的监听组
*/
@Component
@RocketMQTransactionListener(txProducerGroup="txProducer")
public class TransProducerListener implements RocketMQLocalTransactionListener {
private static final Logger logger = LoggerFactory.getLogger(TransProducerListener.class);
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
logger.info("开始执行事务的本地方法---");
String jsonString = new String((byte[])message.getPayload());//转换成String
logger.info("事务的本地方法的消息为---"+jsonString);
try {
int i=1/0;
return RocketMQLocalTransactionState.COMMIT;
}catch (Exception e){
return RocketMQLocalTransactionState.UNKNOWN;
}
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
logger.info("开始执行事务的本地检查方法---");
String jsonString = new String((byte[])message.getPayload());//转换成String
logger.info("事务的本地检查的消息为---"+jsonString);
return RocketMQLocalTransactionState.COMMIT;
}
}
|
package com.ecjtu.hotel.service;
import java.util.List;
import com.ecjtu.hotel.pojo.Guest;
public interface IGuestService {
int addGuest(Guest guest);
int deleteGuestById(Integer id);
int updateGuest(Guest guest);
Guest getGuestByUserId(Integer id);
List<Guest> getAllGuest();
}
|
package myapp.com.callrecorder.Services;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.IBinder;
import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import myapp.com.callrecorder.AppPreferences;
import myapp.com.callrecorder.Database.CallDetails;
import myapp.com.callrecorder.Database.CallLog;
import myapp.com.callrecorder.Database.Customer;
import myapp.com.callrecorder.Database.Database;
import myapp.com.callrecorder.MainActivity;
/**
* The nitty gritty Service that handles actually recording the conversations
*/
public class RecordCallService extends Service {
InputStream inputStream = null;
String result = null;
String responceStatus;
int tempstatus, responseUserId;
public final static String ACTION_START_RECORDING = "com.jlcsoftware.ACTION_CLEAN_UP";
public final static String ACTION_STOP_RECORDING = "com.jlcsoftware.ACTION_STOP_RECORDING";
public final static String EXTRA_PHONE_CALL = "com.jlcsoftware.EXTRA_PHONE_CALL";
List<Customer> custcount;
int count, CustomerId;
Database db = new Database(this);
String CallDetailsMobNo, CallType, AudioFileUploadStatus;
Calendar StartTime, EndTime;
String CallDateTime;
String CallDuration;
String audiofilename;
String path;
String fileName;
final Handler handler = new Handler();
final int delay = 10000; //milliseconds
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static boolean HandlerStatus = false;
// boolean CurrentHandlerStatus;
int id;
//boolean status;
public RecordCallService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ContentValues parcelableExtra = intent.getParcelableExtra(EXTRA_PHONE_CALL);
startRecording(new CallLog(parcelableExtra));
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
stopRecording();
super.onDestroy();
}
private CallLog phoneCall;
boolean isRecording = false;
private void stopRecording() {
custcount = db.getAllCustomers();
count = 0;
for (Customer cn : custcount) {
count++;
}
if (count > 0) {
// new updateLocationDetails().execute();
Database db = new Database(getApplicationContext());
Customer user1 = db.getCustomerDetails();
CustomerId = user1.getCust_id();
}
if (isRecording) {
try {
phoneCall.setEndTime(Calendar.getInstance());
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
isRecording = false;
phoneCall.save(getBaseContext());
// displayNotification(phoneCall);
SendCallDetails(phoneCall);
} catch (Exception e) {
e.printStackTrace();
}
}
phoneCall = null;
}
MediaRecorder mediaRecorder;
private void startRecording(CallLog phoneCall) {
if (!isRecording) {
isRecording = true;
this.phoneCall = phoneCall;
File file = null;
try {
this.phoneCall.setSartTime(Calendar.getInstance());
File dir = AppPreferences.getInstance(getApplicationContext()).getFilesDirectory();
mediaRecorder = new MediaRecorder();
file = File.createTempFile("record", ".3gp", dir);
this.phoneCall.setPathToRecording(file.getAbsolutePath());
// mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setAudioSamplingRate(8000);
mediaRecorder.setAudioEncodingBitRate(12200);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(phoneCall.getPathToRecording());
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
isRecording = false;
if (file != null) file.delete();
this.phoneCall = null;
isRecording = false;
}
}
}
public void SendCallDetails(CallLog phoneCall) {
CallDetailsMobNo = phoneCall.getPhoneNumber();
if (phoneCall.isOutgoing()) {
CallType = "Outgoing";
} else {
CallType = "Incoming";
}
StartTime = phoneCall.getStartTime();
EndTime = phoneCall.getEndTime();
float time = EndTime.getTimeInMillis() - StartTime.getTimeInMillis();
CallDuration = (String.format("%.2f", ((time / 1000) / 60)));
DateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
CallDateTime = df.format(StartTime.getTime());//14/12/17 1:01 PM to 14-12-2017 1:01:00
File file = new File(phoneCall.getPathToRecording());
path = file.toString();
String[] parts = path.split("/");
fileName = parts[parts.length - 1];
AudioFileUploadStatus = "No";
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("CallDetailsMobNo", CallDetailsMobNo);
editor.apply();
long Id = db.addCallDetails(new CallDetails(path, CallDetailsMobNo, CallType, CallDuration, CallDateTime, AudioFileUploadStatus));
editor.putLong("Id", Id);
editor.apply();
Intent in = new Intent(RecordCallService.this, MainActivity.class);
startActivity(in);
}
public static void sartRecording(Context context, CallLog phoneCall) {
Intent intent = new Intent(context, RecordCallService.class);
intent.setAction(ACTION_START_RECORDING);
intent.putExtra(EXTRA_PHONE_CALL, phoneCall.getContent());
context.startService(intent);
}
public static void stopRecording(Context context) {
Intent intent = new Intent(context, RecordCallService.class);
intent.setAction(ACTION_STOP_RECORDING);
context.stopService(intent);
}
}
|
package com.stefanini.service;
import java.util.ArrayList;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import com.stefanini.model.Agente;
import com.stefanini.repository.AgenteRepository;
@Stateless
public class AgenteService {
@Inject
private AgenteRepository agenteRepository;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void incluir(Agente agente){
agenteRepository.incluir(agente);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public ArrayList<Agente> listar(){
return (ArrayList<Agente>) agenteRepository.lista();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Agente busca(int id){
return agenteRepository.busca(id);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void altera(Agente agente){
agenteRepository.altera(agente);;
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deleta(Agente agente){
agenteRepository.deleta(agente);;
}
}
|
/**
*
*/
package partieConsole;
import java.util.Date;
/**
* @author Mamadou bobo
*
*/
public class Inscription {
//private static int compteur=0;
private int idInscription;
private Date dateInscription;
private Etudiant etudiant;
private Groupe groupe;
private Paiement paiement;
private Session session;
/*public Inscription( Date dateInscription, int etudiant, int groupe, int paiement,
int session) {
super();
compteur++;
this.idInscription = compteur;
this.dateInscription = dateInscription;
this.etudiant = etudiant;
this.groupe = groupe;
this.paiement = paiement;
this.session = session;
}
*/
public Inscription(int idInscription, Date dateInscription, int etudiant, int groupe, int paiement,
int session) {
super();
this.idInscription = idInscription;
this.dateInscription = dateInscription;
/*this.etudiant = etudiant;
this.groupe = groupe;
this.paiement = paiement;
this.session = session;*/
}
public Inscription() {
// TODO Auto-generated constructor stub
}
/*public static int getCompteur() {
return compteur;
}
public static void setCompteur(int compteur) {
Inscription.compteur = compteur;
}*/
public int getIdInscription() {
return idInscription;
}
public void setIdInscription(int idInscription) {
this.idInscription = idInscription;
}
public Date getDateInscription() {
return dateInscription;
}
public void setDateInscription(Date dateInscription) {
this.dateInscription = dateInscription;
}
public Etudiant getEtudiant() {
return etudiant;
}
public void setEtudiant(Etudiant etudiant) {
this.etudiant = etudiant;
}
public Groupe getGroupe() {
return groupe;
}
public void setGroupe(Groupe groupe) {
this.groupe = groupe;
}
public Paiement getPaiement() {
return paiement;
}
public void setPaiement(Paiement paiement) {
this.paiement = paiement;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
@Override
public String toString() {
return "Inscription [idInscription=" + idInscription + ", dateInscription=" + dateInscription + ", etudiant="
+ etudiant + ", groupe=" + groupe + ", paiement=" + paiement + ", session=" + session + "]";
}
}
|
package algo;
import java.util.Comparator;
import abstracts.AbstractSorter;
import interfaces.Sortable;
import util.Utils;
/**
* 1. Find the minimum value in the list
2. Swap it with the value in the current position
3. Repeat this process for all the elements until the entire array is sorted
This algorithm is called SelectionSort since it repeatedly selects the smallest element
*/
public class SelectionSort extends AbstractSorter implements Sortable {
@Override
public <T extends Comparable<? super T>> void sort(T[] values, boolean isAscending) {
int idx;
for (int i = 0; i < values.length - 1; i++) {
idx = i;
for (int j = i + 1; j < values.length; j++) {
if (isAscending) {
if (values[j].compareTo(values[idx]) < 0)
idx = j;
} else {
if (values[j].compareTo(values[idx]) > 0)
idx = j;
}
}
swap(values, i, idx);
}
}
}
|
package com.BaseClass;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
public class BaseClass1 {
protected WebDriver driver;
@BeforeClass
public void beforeclass(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Arti\\workspace1\\walmart12\\Resources\\chromedriver.exe" );
driver= new ChromeDriver();
//driver.get("https://www.walmart.com/");
}
}
|
package server.sport.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import server.sport.model.Activity;
import java.util.List;
public interface ActivityRepository extends JpaRepository<Activity, Integer> {
List<Activity> findAllActivitiesByTeamTeamId(int teamId);
Page<Activity> findByActivityName(String activityName, Pageable paging);
Page<Activity> findByCapacity(int capacity, Pageable paging);
Page<Activity> findByActivityType(String activityType, Pageable paging);
//List<Activity> findAll(int size);
}
|
package com.beans;
import java.util.Date;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import com.classes.EverdoseEmail;
import com.classes.SupplierProduct;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
import javax.mail.*;
import javax.mail.internet.*;
/**
* Session Bean implementation class EmailService
*/
@Stateless
@LocalBean
public class EmailService implements EmailServiceRemote, EmailServiceLocal {
/**
* Default constructor.
*/
public EmailService() {
}
@Override
public boolean supplyProduct(String emailTo, String supplierName, List<SupplierProduct> products ) {
System.out.println("Servicio de enviar Email");
String template = EverdoseEmail.supplyProductsTemplate;
String text = template.replace("{{NAME}}", supplierName );
String productsEmailString = "";
for (SupplierProduct product : products) {
productsEmailString+="Cantidad: ";
productsEmailString+=product.getAmount();
productsEmailString+="\n";
productsEmailString+="Nombre: ";
productsEmailString+=product.getName();
productsEmailString+="\n";
productsEmailString+="\n";
}
text = text.replace("{{PRODUCTS}}", productsEmailString );
try {
Session session = EverdoseEmail.getSession();
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(EverdoseEmail.EMAIL_FROM));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailTo, false));
msg.setSubject("Suministro de productos");
msg.setText(text);
msg.setSentDate(new Date());
Transport.send(msg);
}
catch (MessagingException e) {
e.printStackTrace();
}
return false;
}
}
|
package exception;
public class MatchOverException extends RuntimeException {
public MatchOverException(String message) {
super(message);
}
}
|
package com.es.phoneshop.web.controller;
import com.es.core.dto.input.CartItemInputDto;
import com.es.core.dto.output.CartTotalsOutputDto;
import com.es.core.exception.OutOfStockException;
import com.es.core.service.CartService;
import com.es.phoneshop.web.exception.InvalidInputException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.validation.Valid;
@Controller
@RequestMapping(value = "/ajaxCart")
public class AjaxCartController {
@Resource
private CartService cartService;
@PostMapping
@ResponseBody
public CartTotalsOutputDto addPhone(final @RequestBody @Valid CartItemInputDto cartItemInputDto,
final BindingResult bindingResult ) {
if (bindingResult.hasErrors()) {
throw new InvalidInputException(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
try {
cartService.addPhone(cartItemInputDto.getPhoneId(), cartItemInputDto.getRequestedQuantity());
} catch (OutOfStockException e) {
throw new InvalidInputException(e.getMessage());
}
return cartService.getCartTotalsOutputDto();
}
}
|
package com.example.agendaconfragments;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class AddFragment extends Fragment {
private Datos datos;
private FloatingActionButton fab;
EditText nombre, apellido, correo, telefono;
onSelectedItemAdd listenerAdd;
RadioButton amigos, trabajo, familia;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_add, container, false);
datos = new Datos();
nombre = v.findViewById(R.id.eT_Nombre);
apellido = v.findViewById(R.id.eT_Apellido);
correo = v.findViewById(R.id.eT_email);
telefono = v.findViewById(R.id.eT_Telefono);
familia = v.findViewById(R.id.rB_Familia);
amigos = v.findViewById(R.id.rB_Amigos);
trabajo = v.findViewById(R.id.rB_Trabajo);
fab = v.findViewById(R.id.fab1);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
datos.setNombre(nombre.getText().toString());
datos.setApellidos(apellido.getText().toString());
datos.setTelefono(telefono.getText().toString());
datos.setCorreo(correo.getText().toString());
datos.setAmigos(amigos.isChecked());
datos.setFamilia(familia.isChecked());
datos.setTrabajo(trabajo.isChecked());
listenerAdd.onItemAddSelected(datos);
}
});
return v;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
listenerAdd = (onSelectedItemAdd) context;
}
}
|
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class GetStudInfo extends HttpServlet{
public void doGet(HttpServletRequest req , HttpServletResponse res) throws IOException{
PrintWriter out = res.getWriter();
String rollNumber = req.getParameter("rollNo");
StudInfo sInfo = new StudInfo(rollNumber);
String dept = sInfo.getDepartment();
out.println("<html><head></head><body>"+
"<h2> Your Department is" + dept +"</h2></body></html>");
}
}
|
package org.sigmacamp.ioionavigator;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.IOIO;
import ioio.lib.api.IOIO.VersionType;
import ioio.lib.api.PulseInput;
import ioio.lib.api.PwmOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
public class IOIOThread extends BaseIOIOLooper {
private DigitalOutput led0, ledleft, ledright;
private Motor rightMotor, leftMotor;
private Sonar leftSonar, rightSonar;
public MainActivity parent;
private Compass compass;
boolean heartBeat=false; //used for built-in LED, as heartbeat
int mode=0; //0: going straight; 1: turning right; 2: turning left
//constructor
IOIOThread(MainActivity p) {
super();
this.parent = p;
}
/**
* Called when the IOIO is disconnected.
*/
@Override
public void disconnected() {
parent.popup("IOIO disconnected");
}
/**
* Called when the IOIO is connected, but has an incompatible firmware version.
*/
@Override
public void incompatible() {
parent.popup("IOIO: Incompatible firmware version!");
}
/**
* Setup - called when the IOIO is connected
*/
@Override
protected void setup() throws ConnectionLostException {
//print connection information
parent.popup(String.format("IOIO connected\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
ioio_.getImplVersion(VersionType.IOIOLIB_VER),
ioio_.getImplVersion(VersionType.APP_FIRMWARE_VER),
ioio_.getImplVersion(VersionType.BOOTLOADER_VER),
ioio_.getImplVersion(VersionType.HARDWARE_VER)));
//set up various LEDs etc
led0 = ioio_.openDigitalOutput(0, true);
ledleft = ioio_.openDigitalOutput(40, true);
ledright = ioio_.openDigitalOutput(39, true);
rightMotor=new Motor(13,14);
leftMotor=new Motor(11,12);
leftSonar=new Sonar(7,6);//trigger pin=7, echo pin=6
rightSonar=new Sonar(9,10);//trigger pin=7, echo pin=6
compass=parent.compass;
}
/**
* Called repetitively while the IOIO is connected.
*/
@Override
public void loop() throws ConnectionLostException, InterruptedException {
float leftDistance, rightDistance, heading, error;
boolean obstacleleft, obstacleright;
//pulse the built in LED
led0.write(heartBeat);
heartBeat=!heartBeat;
//get heading
if (!parent.startButton.isChecked()) {
heading = compass.getAzimut();
error = heading - 180;
leftMotor.setPower(50 - error * 0.3f);
rightMotor.setPower(50 + error * 0.3f);
} else {
leftMotor.setPower(0f);
rightMotor.setPower(0f);
}
Thread.sleep(50);
}
private class Motor {
private PwmOutput pin1, pin2;
//constructor
//requires 2 arguments: pin numbers
public Motor( int n1, int n2) throws ConnectionLostException {
pin1 = ioio_.openPwmOutput(n1, 5000); //opens as PWM output, frequency =5Khz
pin2 = ioio_.openPwmOutput(n2, 5000);
}
public void setPower(float power) throws ConnectionLostException {
//make sure power is between -100 ... 100
if (power > 100) {
power = 100;
} else if (power < -100) {
power = -100;
}
if (power > 0) {
pin1.setDutyCycle(power / 100);
pin2.setDutyCycle(0);
} else {
pin1.setDutyCycle(0);
pin2.setDutyCycle(Math.abs(power) / 100);
}
}
public void stop() throws ConnectionLostException {
pin1.setDutyCycle(0);
pin2.setDutyCycle(0);
}
}
/*
Class sonar. Uses ultrasonic sensor to measure distance.
*/
private class Sonar {
private DigitalOutput triggerPin;
private PulseInput echoPin;
//constructor
//requires 2 arguments: trigger pin number, echo pin number (echo must be 5V tolerant)
public Sonar(int trigger, int echo) throws ConnectionLostException{
echoPin = ioio_.openPulseInput(echo, PulseInput.PulseMode.POSITIVE);
triggerPin = ioio_.openDigitalOutput(trigger);
}
//measure distance, in cm. Returns -1 if connection lost.
public float getDistance() throws ConnectionLostException, InterruptedException {
int echoMseconds;
triggerPin.write(false);
Thread.sleep(5);
// set trigger pin to HIGH for 1 ms
triggerPin.write(true);
Thread.sleep(1);
triggerPin.write(false);
//get response time in microseconds
echoMseconds = (int) (echoPin.getDuration() * 1000 * 1000);
//convert microseconds to cm
return ((float) echoMseconds / 58);
}
}
}
|
package com.prj.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.prj.pojo.CarBrand;
import com.prj.service.ICarBrandService;
@Controller
public class CarBrandController {
@Resource
private ICarBrandService brandService;
private CarBrand carBrand;
public CarBrand getCarBrand() {
return carBrand;
}
public void setCarBrand(CarBrand carBrand) {
this.carBrand = carBrand;
}
@RequestMapping("/findAll_carBrand")
public String findAll(HttpServletRequest request){
List<CarBrand> carBrands = brandService.findAll();
HttpSession session = request.getSession();
session.setAttribute("carBrands", carBrands);
return "carbrandlist";
}
@RequestMapping("/del_carBrand")//末尾删除超链接删除
public String del(int id){
brandService.del(id);
return "redirect:findAll_carBrand";
}
@RequestMapping("/add_carBrand")
public String add(CarBrand carBrand,HttpServletRequest request){
// 1.获取文件
MultipartFile picFile = carBrand.getPicFile();
// 2.获取文件名
String picName = picFile.getOriginalFilename();
//3.上传图片
String path = request.getSession().getServletContext().getRealPath("images/brand");
String pname = "\\" + picFile.getOriginalFilename();
path += pname;
try {
FileUtils.copyInputStreamToFile(picFile.getInputStream(),
new File(path));
} catch (IOException e) {
e.printStackTrace();
}
carBrand.setCarbrandPic(picName);
brandService.save(carBrand);
return "redirect:findAll_carBrand";
}
@RequestMapping("/delcarbrand")//复选删除
public String delmany(String delid){
String[] delId = delid.split(",");
for (String id : delId) {
brandService.del(Integer.parseInt(id));
}
return "redirect:findAll_carBrand";
}
}
|
package by.pvt.herzhot.pojos;
import java.io.Serializable;
/**
* @author Herzhot
* @version 1.0
* 08.05.2016
*/
public interface IEntity extends Serializable {}
|
/*
SQL Schema Migration Toolkit
Copyright (C) 2015 Cédric Tabin
This file is part of ssmt, a tool used to maintain database schemas up-to-date.
The author can be contacted on http://www.astorm.ch/blog/index.php?contact
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.astorm.ssmt.tools.sql;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Provides useful method to handle tokens issued from a {@code SQLLexer}.
*/
public class SQLAnalyzer implements Iterator<SQLToken> {
private final Iterator<SQLToken> tokens;
private SQLToken nextToken;
/**
* Represents a dot (.).
*/
public static final String DOT = ".";
/**
* Represents a semi colon (;).
*/
public static final String SEMICOLON = ";";
/**
* Represents a comma (,).
*/
public static final String COMMA = ",";
/**
* Represents a left parenthesis (().
*/
public static final String LPAREN = "(";
/**
* Represents a right parenthesis ()).
*/
public static final String RPAREN = ")";
/**
* Creates a new {@code SQLAnalyzer} with the specified {@code tokenIterator}.
*/
public SQLAnalyzer(Iterator<SQLToken> tokenIterator) {
this.tokens = tokenIterator;
}
/**
* Returns the next {@code SQLToken} without consuming it. If there is no more
* token, then this method returns null.
*/
public SQLToken peek() {
if(nextToken==null && tokens.hasNext()) {
nextToken = tokens.next();
}
return nextToken;
}
/**
* Returns true if there are more tokens to read.
*/
@Override
public boolean hasNext() {
return nextToken!=null || tokens.hasNext();
}
/**
* Consumes the next token and returns it. If there is no more token to consume,
* this method returns null.
*/
@Override
public SQLToken next() {
if(nextToken!=null) {
SQLToken tkn = nextToken;
nextToken = null;
return tkn;
}
return tokens.next();
}
/**
* Consumes the next token. If there is no more token to consume, then an exception
* will be thrown.
*/
public SQLToken accept() throws SQLAnalyzerException {
if(!hasNext()) { throw new SQLAnalyzerException("Unexpected end of token list", "<any>", null); }
return next();
}
/**
* Consumes the next token and check that it corresponds to the specified token.
* This method simply redirects to the {@link #acceptAll() } method.
*/
public SQLToken accept(String token) throws SQLAnalyzerException {
return acceptAll(token);
}
/**
* If the next token matches the specified {@code token}, then consumes and returns it.
* This method simply redirects to the {@link #acceptAnyIfPossible() } method.
*/
public boolean acceptIfPossible(String token) throws SQLAnalyzerException {
return acceptAnyIfPossible(token)!=null;
}
/**
* Consumes the next tokens and checks that it corresponds to the specified token
* list. This method then returns the next token. If one of the token doesn't match
* the expected value, an exception will be thrown.
*/
public SQLToken acceptAll(String... tokens) throws SQLAnalyzerException {
if(tokens.length==0) { throw new IllegalArgumentException("At least one token needed"); }
for(String token : tokens) {
SQLToken tkn = next();
if(tkn==null) { throw new SQLAnalyzerException("Unexpected end of token list", token, null); }
if(!tkn.equals(token)) { throw new SQLAnalyzerException("Unexpected token "+tkn.getToken()+" at ("+tkn.getLine()+","+tkn.getColumn()+")", token, tkn); }
}
return peek();
}
/**
* Consumes the specified token list if the first token matches the first specified one.
* If the list has been consumed, this method returns true.
*/
public boolean acceptAllIfPossible(String... tokens) throws SQLAnalyzerException {
if(tokens.length==0) { throw new IllegalArgumentException("At least one token needed"); }
SQLToken tkn = peek();
if(tkn==null) { return false; }
if(tkn.equals(tokens[0])) {
acceptAll(tokens);
return true;
}
return false;
}
/**
* Consumes one token from the specified list and returns it. If the token doesn't match any
* of the expected token, then an exception is thrown.
*/
public SQLToken acceptAny(String... tokens) throws SQLAnalyzerException {
if(tokens.length==0) { throw new IllegalArgumentException("At least one token needed"); }
SQLToken tkn = next();
if(tkn==null) { throw new SQLAnalyzerException("Unexpected end of token list", tokens, null); }
for(String token : tokens) {
if(tkn.equals(token)) {
return tkn;
}
}
throw new SQLAnalyzerException("Unexpected token "+tkn.getToken()+" at ("+tkn.getLine()+","+tkn.getColumn()+")", tokens, tkn);
}
/**
* Consumes one token of the specified list if possible and returns it. If no token could
* be consumed, this method returns null.
*/
public SQLToken acceptAnyIfPossible(String... tokens) {
if(tokens.length==0) { throw new IllegalArgumentException("At least one token needed"); }
SQLToken tkn = peek();
if(tkn!=null) {
for(String token : tokens) {
if(tkn.equals(token)) {
return next();
}
}
}
return null;
}
/**
* Consumes all the tokens until the specified token is reached. After this method
* returns, the next token will be the one coming just after the specified {@code token}.
* This method returns all the consumed token. The last token of the list will be the
* specified {@code token} if the end of the lexer has not been reached.
*/
public List<SQLToken> until(String token) {
List<SQLToken> read = new LinkedList<>();
SQLToken tkn = next();
while(tkn!=null && !tkn.equals(token)) {
read.add(tkn);
tkn = next();
}
if(tkn!=null) {
read.add(tkn);
}
return read;
}
/**
* Drops all the tokens until one of the specified token is reached. This method will
* let the latter available (it is not consumed). This method returns true if one of
* the tokens has been reached, false if there is no more token to read.
*/
public boolean reach(String... tokens) {
SQLToken current = peek();
while(hasNext()) {
for(String tkn : tokens) {
if(current.equals(tkn)) {
return true;
}
}
next();
current = peek();
}
return false;
}
}
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.ballerinalang.net.kafka.nativeimpl.functions.consumer;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.KafkaException;
import org.ballerinalang.bre.Context;
import org.ballerinalang.bre.bvm.BLangVMErrors;
import org.ballerinalang.model.types.TypeKind;
import org.ballerinalang.model.values.BMap;
import org.ballerinalang.model.values.BStruct;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.natives.AbstractNativeFunction;
import org.ballerinalang.natives.annotations.Argument;
import org.ballerinalang.natives.annotations.BallerinaFunction;
import org.ballerinalang.natives.annotations.Receiver;
import org.ballerinalang.natives.annotations.ReturnType;
import org.ballerinalang.net.kafka.Constants;
import org.ballerinalang.net.kafka.KafkaUtils;
import java.util.Properties;
/**
* Native function ballerina.net.kafka:connect which connects consumer to remote cluster.
*/
@BallerinaFunction(packageName = "ballerina.net.kafka",
functionName = "connect",
receiver = @Receiver(type = TypeKind.STRUCT, structType = "KafkaConsumer",
structPackage = "ballerina.net.kafka"),
args = {
@Argument(name = "c",
type = TypeKind.STRUCT, structType = "KafkaConsumer",
structPackage = "ballerina.net.kafka")
},
returnType = {@ReturnType(type = TypeKind.STRUCT)},
isPublic = true)
public class Connect extends AbstractNativeFunction {
@Override
public BValue[] execute(Context context) {
// Consumer initialization
BStruct consumerStruct = (BStruct) getRefArgument(context, 0);
BMap<String, BValue> consumerBalConfig = (BMap<String, BValue>) consumerStruct.getRefField(0);
Properties consumerProperties = KafkaUtils.processKafkaConsumerConfig(consumerBalConfig);
try {
KafkaConsumer<byte[], byte[]> kafkaConsumer = new KafkaConsumer<>(consumerProperties);
consumerStruct.addNativeData(Constants.NATIVE_CONSUMER, kafkaConsumer);
} catch (KafkaException e) {
return getBValues(BLangVMErrors.createError(context, 0, e.getMessage()));
}
return VOID_RETURN;
}
}
|
package Algorithm;
public class EditDistance {
int min(int x,int y,int z)
{
if (x <= y && x <= z) return x;
if (y <= x && y <= z) return y;
else return z;
}
public int editDistDP(String str1, String str2)
{
int m=str1.length();
int n=str2.length();
int dp[][] = new int[m+1][n+1];
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i==0)
dp[i][j] = j;
else if (j==0)
dp[i][j] = i;
else if (str1.charAt(i-1) == str2.charAt(j-1))
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = 1 + min(dp[i][j-1],
dp[i-1][j],
dp[i-1][j-1]);
}
}
return dp[m][n];
}
}
|
package com.ashishkaul.rest.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ashishkaul.rest.interfaces.*;
@Component
public class SlamBookService implements ISlamBook{
@Autowired
private IH2Repository h2RepositoryService;
@Override
public String AddPersonInfo(String data) {
return h2RepositoryService.Create(data);
}
@Override
public String EditPersonInfo(String id, String data) {
return h2RepositoryService.Update(id, data);
}
@Override
public String RemovePersonInfo(String id) {
return h2RepositoryService.Delete(id);
}
@Override
public String ViewPersonInfo(String id) {
return h2RepositoryService.ReadOne(id);
}
@Override
public List<String> ViewPersonsInfo() {
return h2RepositoryService.ReadAll();
}
}
|
package be.dpms.medwan.common.model.vo.occupationalmedicine;
import be.mxs.common.model.vo.IIdentifiable;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA.
* User: MichaŽl
* Date: 16-juin-2003
* Time: 10:42:09
*/
public class WorkplaceVO implements Serializable, IIdentifiable {
public Integer workplaceId;
public String messageKey;
public WorkplaceVO(Integer workplaceId, String messageKey) {
this.workplaceId = workplaceId;
this.messageKey = messageKey;
}
public Integer getWorkplaceId() {
return workplaceId;
}
public String getMessageKey() {
return messageKey;
}
public void setWorkplaceId(Integer workplaceId) {
this.workplaceId = workplaceId;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof WorkplaceVO)) return false;
final WorkplaceVO workplaceVO = (WorkplaceVO) o;
return workplaceId.equals(workplaceVO.workplaceId);
}
public int hashCode() {
return workplaceId.hashCode();
}
}
|
package leetCode;
/**
* Created by gengyu.bi on 2014/12/30.
*/
public class ExcelSheetColumnNumber {
public int titleToNumber(String s) {
if (s == null || s.equals(""))
return 0;
char[] chars = s.toCharArray();
int result = 0;
for (int i = 0; i < chars.length; i++) {
int c = chars[chars.length - 1 - i] - 64;
result += c * Math.pow(26, i);
}
return result;
}
public static void main(String[] args) {
ExcelSheetColumnNumber excelSheetColumnNumber = new ExcelSheetColumnNumber();
int r = excelSheetColumnNumber.titleToNumber("AB");
System.out.println(r);
}
}
|
package main.java.Pipelines;
import main.java.Pipelines.Basic.PipelineTester;
import main.java.Pipelines.Basic.PnPPipelineTester;
import main.java.Utils.BetterTowerGoalUtils;
import main.java.Utils.CvUtils;
import main.java.Utils.PnPUtils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class PipelineRunner {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) throws IOException {
PnPPipelineTester pipeline = new PnPPipelineTester();
Mat matchMat = CvUtils.bufferedImageToMat(ImageIO.read(new File("src/assets/input2/out10.png")));//238
Mat out = pipeline.processFrame(matchMat);
//System.out.println(pipeline.getPos().dump());
Imgproc.resize(out, out, new Size(1280, 720));
HighGui.imshow("Output", out);
HighGui.waitKey();
}
}
|
package teu.iface.oq12;
class Homework2 {
public static void main(String... args) {
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
System.out.println("Hello This is first Programme");
}
}
|
package com.xys.car.service.impl;
import com.xys.car.entity.Carphoto;
import com.xys.car.mapper.CarphotoMapper;
import com.xys.car.service.ICarphotoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author zxm
* @since 2020-12-04
*/
@Service
public class CarphotoServiceImpl extends ServiceImpl<CarphotoMapper, Carphoto> implements ICarphotoService {
}
|
package com.bofsoft.laio.common;
import android.content.Intent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class StringUtil {
/**
* 字符串转换成十六进制字符串
*
* @param String str 待转换的ASCII字符串
* @return String 每个Byte之间空格分隔,如: [61 6C 6B]
*/
public static String str2HexStr(String str) {
char[] chars = "0123456789abcdef".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
// sb.append(' ');
}
return sb.toString().trim();
}
/**
* 十六进制转换字符串
*
* @param String str Byte字符串(Byte之间无分隔符 如:[616C6B])
* @return String 对应的字符串
*/
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
public static byte[] file2Byte(String filepath) {
if (filepath == null || filepath.equals("")) {
return null;
}
return file2Byte(new File(filepath));
}
public static byte[] file2Byte(File file) {
if (file == null || !file.exists()) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = fis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
bos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return bos.toByteArray();
} finally {
try {
bos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bos.toByteArray();
}
/**
* bytes转换成十六进制字符串
*
* @param byte[] b byte数组
* @return String 每个Byte值之间空格分隔
*/
public static String byte2HexStr(byte[] b) {
String stmp = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
// sb.append(" ");
}
return sb.toString().toUpperCase(Locale.CHINA).trim();
}
/**
* 十六进制字符串转byte[]
*
* @param hexString
* @return
*/
public static byte[] hexStr2Bytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString.toUpperCase(Locale.CHINA);
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* 文件转16进制字符串
*
* @param file
* @return
*/
public static String file2HexString(File file) {
return byte2HexStr(file2Byte(file));
}
/**
* 文件转16进制字符串
*
* @param file
* @return
*/
public static String file2HexString(String filepath) {
return byte2HexStr(file2Byte(filepath));
}
/**
* Convert char to byte
*
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* String的字符串转换成unicode的String
*
* @param String strText 全角字符串
* @return String 每个unicode之间无分隔符
* @throws Exception
*/
public static String strToUnicode(String strText) throws Exception {
char c;
StringBuilder str = new StringBuilder();
int intAsc;
String strHex;
for (int i = 0; i < strText.length(); i++) {
c = strText.charAt(i);
intAsc = (int) c;
strHex = Integer.toHexString(intAsc);
if (intAsc > 128)
str.append("\\u" + strHex);
else
// 低位在前面补00
str.append("\\u00" + strHex);
}
return str.toString();
}
/**
* unicode的String转换成String的字符串
*
* @param String hex 16进制值字符串 (一个unicode为2byte)
* @return String 全角字符串
*/
public static String unicodeToString(String hex) {
int t = hex.length() / 6;
StringBuilder str = new StringBuilder();
for (int i = 0; i < t; i++) {
String s = hex.substring(i * 6, (i + 1) * 6);
// 高位需要补上00再转
String s1 = s.substring(2, 4) + "00";
// 低位直接转
String s2 = s.substring(4);
// 将16进制的string转为int
int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
// 将int转换为字符
char[] chars = Character.toChars(n);
str.append(new String(chars));
}
return str.toString();
}
public static String join(List<String> list, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append(separator);
}
}
return sb.toString();
}
public static String Inter2HourTime(Integer intTime) {
Integer hour = intTime / (60 * 60);
Integer minute = (intTime % (60 * 60)) / 60;
Integer second = intTime % 60 % 60;
return String.format("%02d:%02d:%02d", hour, minute, second);
}
public static String Inter2HourTime(long intTime) {
Integer integer = new Long(intTime).intValue(); ;
return Inter2HourTime(integer);
}
public static boolean isEmpty(String str) {
if (str == null)
return true;
return str.isEmpty();
}
}
|
package project4;
public class MyLinkedList<AnyType> {
public MyLinkedList() {
doClear();
}
private void clear() {
doClear();
}
public void doClear() {
beginMarker = new Node<>(null, null, null);
endMarker = new Node<>(null, beginMarker, null);
beginMarker.next = endMarker;
theSize = 0;
modCount++;
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
/**
* Adds an item to this collection, at the end.
*
* @param x
* any object.
* @return true.
*/
public boolean add(AnyType x) {
add(size(), x);
return true;
}
/**
* Adds an item to this collection, at specified position. Items at or after
* that position are slid one position higher.
*
* @param x
* any object.
* @param idx
* position to add at.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size(), inclusive.
*/
public void add(int idx, AnyType x) {
addBefore(getNode(idx, 0, size()), x);
}
/**
* Adds an item to this collection, at specified position p. Items at or
* after that position are slid one position higher.
*
* @param p
* Node to add before.
* @param x
* any object.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size(), inclusive.
*/
private void addBefore(Node<AnyType> p, AnyType x) {
Node<AnyType> newNode = new Node<>(x, p.prev, p);
newNode.prev.next = newNode;
p.prev = newNode;
theSize++;
modCount++;
}
/**
* Gets the Node at position idx, which must range from 0 to size( ) - 1.
*
* @param idx
* index to search at.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size( ) - 1, inclusive.
*/
private Node<AnyType> getNode(int idx) {
return getNode(idx, 0, size() - 1);
}
/**
* Gets the Node at position idx, which must range from lower to upper.
*
* @param idx
* index to search at.
* @param lower
* lowest valid index.
* @param upper
* highest valid index.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException
* if idx is not between lower and upper, inclusive.
*/
private Node<AnyType> getNode(int idx, int lower, int upper) {
Node<AnyType> p;
if (idx < lower || idx > upper)
throw new IndexOutOfBoundsException("getNode index: " + idx + "; size: " + size());
if (idx < size() / 2) {
p = beginMarker.next;
for (int i = 0; i < idx; i++)
p = p.next;
} else {
p = endMarker;
for (int i = size(); i > idx; i--)
p = p.prev;
}
return p;
}
/**
* This is the doubly-linked list node.
*/
private static class Node<AnyType> {
public Node(AnyType d, Node<AnyType> p, Node<AnyType> n) {
data = d;
prev = p;
next = n;
}
public AnyType data;
public Node<AnyType> prev;
public Node<AnyType> next;
}
private int theSize;
private int modCount = 0;
private Node<AnyType> beginMarker;
private Node<AnyType> endMarker;
}
|
package by.bytechs.ndcParser.response;
import by.bytechs.ndcParser.enums.DecoderAscii;
import by.bytechs.ndcParser.enums.PrintCommand;
import by.bytechs.ndcParser.interfaces.NdcParser;
import by.bytechs.ndcParser.response.commands.NumberCashToDispense;
import by.bytechs.ndcParser.response.commands.PrinterData;
import by.bytechs.ndcParser.response.commands.TransactionReplyCommand;
import by.bytechs.ndcParser.response.interfaces.HostParserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
/**
* @author Romanovich Andrei
*/
@Service
public class HostParserServiceImpl implements HostParserService {
@Autowired
private NdcParser ndcParser;
@Override
public Object parseCommand(byte[] command) {
try {
String[] strFormatCommand = ndcParser.asciiToUtf(command);
if (strFormatCommand != null) {
String messageType = strFormatCommand[0];
switch (messageType.substring(0, 1)) {
case "1":
return null;
case "3":
return null;
case "4":
return parseTransactionReplyCommand(strFormatCommand);
case "8":
return null;
default:
return null;
}
}
return null;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
@Override
public TransactionReplyCommand parseTransactionReplyCommand(String[] command) {
try {
TransactionReplyCommand replyCommand = new TransactionReplyCommand();
for (int index = 1; index < command.length; index++) {
if (command[index].length() > 0) {
switch (index) {
case 1: {
replyCommand.setTerminalId(command[index]);
break;
}
case 2: {
replyCommand.setMessageSequenceNumber(command[index]);
break;
}
case 3: {
replyCommand.setNextState(command[index]);
break;
}
case 4: {
String[] cashCommand = command[index].split(DecoderAscii.GROUP_SEPARATOR.name());
replyCommand.setDispenseCashNotes(new ArrayList<>());
int beginIndex = 0;
int cassetteNumber = 1;
for (int endIndex = 2; endIndex <= cashCommand[0].length(); endIndex += 2) {
replyCommand.getDispenseCashNotes().add(new NumberCashToDispense(cassetteNumber,
Integer.parseInt(cashCommand[0].substring(beginIndex, endIndex))));
beginIndex = endIndex;
cassetteNumber++;
}
if (cashCommand.length > 1 && cashCommand[1].length() != 0) {
replyCommand.setDispenseCashCoins(new ArrayList<>());
beginIndex = 0;
cassetteNumber = 1;
for (int endIndex = 2; endIndex <= cashCommand[0].length(); endIndex += 2) {
replyCommand.getDispenseCashCoins().add(new NumberCashToDispense(cassetteNumber,
Integer.parseInt(cashCommand[0].substring(beginIndex, endIndex))));
beginIndex = endIndex;
cassetteNumber++;
}
}
break;
}
case 5: {
replyCommand.setTransactionSerialNumber(command[index].substring(0, 4));
replyCommand.setFunctionId(command[index].substring(4, 5));
if (command[index].length() > 5) {
replyCommand.setScreenNumber(command[index].substring(5, 8));
}
if (command[index].length() > 8) {
replyCommand.setScreenDisplayUpdate(command[index].substring(8));
}
break;
}
case 6: {
String[] gsCommand = command[index].split(DecoderAscii.GROUP_SEPARATOR.name());
replyCommand.setMessageCoordinationNumber(Integer.parseInt(gsCommand[0].substring(0, 1)));
String returnCard = gsCommand[0].substring(1, 2);
if (returnCard.equals("0")) {
replyCommand.setReturnCard(true);
} else if (returnCard.equals("1")) {
replyCommand.setReturnCard(false);
}
replyCommand.setDataForPrint(new ArrayList<>());
PrinterData printerData = new PrinterData();
replyCommand.getDataForPrint().add(printerData);
printerData.setPrintCommand(PrintCommand.getObject(gsCommand[0].substring(2, 3)));
if (gsCommand[0].length() > 3) {
printerData.setData(gsCommand[0].substring(3));
}
if (gsCommand.length > 1) {
for (int i = 1; i < gsCommand.length; i++) {
if (gsCommand[i].length() != 0) {
printerData = new PrinterData();
replyCommand.getDataForPrint().add(printerData);
printerData.setPrintCommand(PrintCommand.getObject(gsCommand[i].substring(0, 1)));
if (gsCommand[i].length() > 1) {
printerData.setData(gsCommand[i].substring(1));
}
}
}
}
break;
}
default: {
if (command[index].length() > 1) {
switch (command[index].substring(0, 1)) {
case "4": {
replyCommand.setTrack3(command[index].substring(1));
break;
}
case "K": {
replyCommand.setTrack1(command[index].substring(1));
break;
}
case "L": {
replyCommand.setTrack2(command[index].substring(1));
break;
}
case "5": {
replyCommand.setEMVData(command[index].substring(1));
break;
}
}
}
}
break;
}
}
}
return replyCommand;
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
}
|
package com.midea.designmodel.princple;
/**
* 依赖倒置原则
* 依赖关系传递又三种实现方式
* 1.接口传递
* 2.构造方法传递
* 3.setter方法传递
*
* 小结:
* 1.底层模块尽量都要有抽象类或者接口
* 2.变量的声明类型尽量时抽象类或者接口,这样我们的对象引用就有一个缓冲层
*
*/
public class DependcyInversion {
public static void main(String[] args) {
Email email=new Email();
Wexin wexin=new Wexin();
Person p=new Person();
//接口多态实现
p.receive(email);
p.receive(wexin);
}
}
class Email implements IReceive{
@Override
public void receive() {
System.out.println("接受到短信");
}
}
class Wexin implements IReceive{
@Override
public void receive() {
System.out.println("接受到微信");
}
}
interface IReceive{
void receive();
}
class Person{
//跟接口发生依赖 传递接口
void receive(IReceive receive){
receive.receive();
}
}
|
package com.git.cloud.reports.action;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.git.cloud.common.action.BaseAction;
import com.git.cloud.reports.model.po.CreateReportParamPo;
import com.git.cloud.reports.service.IReportService;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import net.sf.json.JSONObject;
@SuppressWarnings("rawtypes")
public class ReportAction extends BaseAction {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
*
*/
private static final long serialVersionUID = 1058008856401096521L;
@Autowired
private IReportService reportService;
private String id;
private CreateReportParamPo crpo ;
public CreateReportParamPo getCrpo() {
return crpo;
}
public void setCrpo(CreateReportParamPo crpo) {
this.crpo = crpo;
}
//定义一个成员变量
private String message;
private CreateReportParamPo createReportParam;
public CreateReportParamPo getCreateReportParam() {
return createReportParam;
}
public void setCreateReportParam(CreateReportParamPo createReportParam) {
this.createReportParam = createReportParam;
}
//提供get/set方法
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@SuppressWarnings("unchecked")
public void save(){
String[] params = this.getRequest().getParameterValues("params[]");
String type = this.getRequest().getParameter("type");
String reportId = this.getRequest().getParameter("id");
String result = reportService.save(params,type,reportId);
}
public String showReport(){
if(id.contains("?")){
id = id.substring(0, id.indexOf("?"));
}
this.setCreateReportParam(reportService.showReport(id));
return SUCCESS;
}
@SuppressWarnings({ "unchecked", "deprecation" })
public void searchForHtml(){
Map parameters = new HashMap();
Map parameMap = JSONObject.fromObject(this.getRequest().getParameter("paramMap"));
Map reportMap = (Map) parameMap.get("reportMap");
Map conMap = (Map) parameMap.get("conMap");
Map sqlMap = (Map) parameMap.get("sqlMap");
String jasperPath = (String) parameMap.get("jasperPath");
parameters.put("jasperPath", jasperPath);
//报表编译之后生成的.jasper文件的存放位置
File reportFile = new File(this.getSession().getServletContext().getRealPath(jasperPath));
File outPutFile = new File(this.getSession().getServletContext().getRealPath("/pages/reports/common/showReport.jsp"));
if(!reportFile.exists()) {
throw new JRRuntimeException("报表文件 AppDevInfo.jasper 不存在!");
}
if(!outPutFile.exists()) {
throw new JRRuntimeException("报表文件 outPutFile 不存在!");
}
//读取数据库的配置文件
Properties prop = new Properties();
InputStream in = null;
String url="";
String userName = "";
String password = "";
try {
in = new BufferedInputStream (new FileInputStream(this.getSession().getServletContext().getRealPath("/WEB-INF/classes/config/jdbc.properties")));
prop.load(in);
url = prop.getProperty("jdbc.url");
userName = prop.getProperty("jdbc.username");
password = prop.getProperty("jdbc.password");
Class.forName("com.mysql.jdbc.Driver");
} catch (FileNotFoundException e) {
logger.error("异常exception",e);
} catch (IOException e1){
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
} finally{
try {
if(in != null){
in.close();
}
} catch (IOException e) {
logger.error("异常exception",e);
}
}
//jsper所需参数,利用迭代器,获取所有参数
Map.Entry<String, String> me = null;
Iterator<Map.Entry<String, String>> it = reportMap.entrySet().iterator();
while(it.hasNext()){
me = it.next();
parameters.put(me.getKey(),me.getValue());
}
//遍历sql语句
it = sqlMap.entrySet().iterator();
String sqlStr = "";
while(it.hasNext()){
me = it.next();
sqlStr = me.getValue();
//替换sql语句中参数 并 将条件信息写入parameters
Iterator<Map.Entry> conIt = conMap.entrySet().iterator();
while(conIt.hasNext()){
Map.Entry conMe = conIt.next();
//conMap中非sql所需条件
if( !(conMe.getKey().toString().startsWith("isSqlParam_")) && !(parameters.containsKey(conMe.getKey()))){ //避免在sql语句多条的情况下 , 条件信息被重复写入。
parameters.put(conMe.getKey(),conMe.getValue());
}
//conMap中的sql所需条件
if(conMe.getKey() != null && conMe.getValue() != null && conMe.getKey().toString().startsWith("isSqlParam_") && conMe.getValue().toString().equals("Y")){
String conKey4Sql = conMe.getKey().toString().substring(conMe.getKey().toString().indexOf('_')+1);
sqlStr = sqlStr.replace(conKey4Sql, conMap.get(conKey4Sql).toString());
}
}
parameters.put(me.getKey(),sqlStr);
}
parameters.put("SERVERNAME",this.getRequest().getServerName());
parameters.put("SERVERPORT",this.getRequest().getServerPort());
parameters.put("CONTEXTPATH",this.getRequest().getContextPath());
parameters.put("SUBREPORT_DIR",this.getSession().getServletContext().getRealPath("/"));
Connection conn = null;
try {
conn = DriverManager.getConnection(url,userName,password);
} catch (SQLException e1) {
e1.printStackTrace();
}
//获得Jasper输入流
InputStream inputStream = this.getSession().getServletContext().getResourceAsStream(jasperPath);
//设置格式
this.getResponse().setContentType("text/html;charset=UTF-8");
JasperPrint jasperPrint = new JasperPrint();
try{
jasperPrint = JasperFillManager.fillReport(inputStream, parameters, conn);
}catch(Exception e){
logger.error("异常exception",e);
}
//关闭数据库连接
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
logger.error("异常exception",e);
}
//设置格式
this.getResponse().setContentType("text/html;charset=UTF-8");
//获得输出流 ,这里不能这样response.getOutputStream()
PrintWriter printWriter = null;
try {
printWriter = this.getResponse().getWriter();
} catch (IOException e) {
logger.error("异常exception",e);
}
//创建JRHtmlExporter对象
JRHtmlExporter htmlExporter = new JRHtmlExporter();
//把jasperPrint到Session里面(net.sf.jasperreports.j2ee.jasper_print)
this.getRequest().getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
//设值jasperPrint
htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
//设置输出
htmlExporter.setParameter(JRExporterParameter.OUTPUT_WRITER,printWriter);
//设置图片生成的Servlet(生成图片就用这个ImageServlet,并且要在XML文件里面配置 image?image=这个是Servlet的url-pattern)
//flush随机数用于重新获取图片(更新图片地址),否则条件改变后图片不会随之发生改变
htmlExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,this.getRequest().getContextPath()+"/servlets/image?image=");
//解决生成HTML报表缩小问题
//htmlExporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, "pt");
htmlExporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, JRHtmlExporterParameter.SIZE_UNIT_POINT);
//导出
try {
htmlExporter.exportReport();
} catch (JRException e) {
logger.error("异常exception",e);
}finally{
try {
if(printWriter!=null){
printWriter.close(); //关闭输出流
}
if(inputStream!=null){
inputStream.close(); //关闭输入流
}
} catch (IOException e) {
logger.error("异常exception",e);
}
}
}
@SuppressWarnings("unchecked")
public void toPdf(){
String reportName = this.getRequest().getParameter("reportName");
//报表编译之后生成的.jasper文件的存放位置
File reportFile = new File(this.getRequest().getSession().getServletContext().getRealPath("/pages/reports/appDevInfo/AppDevInfo.jasper"));
if(!reportFile.exists()) {
throw new JRRuntimeException("报表文件 AppDevInfo.jasper 不存在!");
}
Map parameters = new HashMap();
//读取数据库的配置文件
Properties prop = new Properties();
InputStream in = null;
String url="";
String userName = "";
String password = "";
try {
in = new BufferedInputStream (new FileInputStream(this.getRequest().getSession().getServletContext().getRealPath("/WEB-INF/classes/config/jdbc.properties")));
prop.load(in);
url = prop.getProperty("jdbc.url");
userName = prop.getProperty("jdbc.username");
password = prop.getProperty("jdbc.password");
} catch (Exception e) {
logger.error("异常exception",e);
}finally{
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
logger.error("异常exception",e);
}
}
String selectConKeySql = "SELECT c.CONKEY FROM report r LEFT JOIN REPORT_CONDITION c ON c.REPORT_ID = r.ID WHERE r.REPORTNAMEVALUE = ? AND r.IS_ACTIVE = 'Y'";
String selectSqlKeySql = "SELECT s.SQLKEY,s.SQLVALUE FROM report r LEFT JOIN report_sql s ON s.REPORT_ID = r.ID"+
"WHERE r.REPORTNAMEVALUE = ? AND r.IS_ACTIVE = 'Y'";
Connection conn;
//查询条件KEY
try {
conn = DriverManager.getConnection(url, userName, password);
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sb.toString());
PreparedStatement stmt = conn.prepareStatement(selectConKeySql);
stmt.setString(1, reportName);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
rs.getString("SQLKEY");
parameters.put(rs.getString("SQLKEY"), this.getRequest().getParameter(rs.getString("SQLVALUE")));
}
stmt.close();
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
//查询sql
try {
conn = DriverManager.getConnection(url, userName, password);
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(selectSqlKeySql);
PreparedStatement stmt = conn.prepareStatement(selectSqlKeySql);
stmt.setString(1, reportName);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
rs.getString("CONKEY");
parameters.put(rs.getString("CONKEY"), this.getRequest().getParameter(rs.getString("CONKEY")));
}
stmt.close();
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
try{
parameters.put("SERVERNAME",this.getRequest().getServerName());
parameters.put("SERVERPORT",this.getRequest().getServerPort());
parameters.put("CONTEXTPATH",this.getRequest().getContextPath());
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,userName, password);
byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),parameters,con);
this.getResponse().setContentType("application/pdf");
this.getResponse().setContentLength(bytes.length);
ServletOutputStream outStream = this.getResponse().getOutputStream();
outStream.write(bytes,0,bytes.length);
outStream.flush();
outStream.close();
}catch(Exception e){
logger.error("异常exception",e);
}
}
/**
* 查询所有的设备信息,分页展示到前台
*
* @throws Exception
*/
public void getReportList() throws Exception {
this.jsonOut(reportService.getReportPagination(this.getPaginationParam()));
}
/**
* 删除选中的报表
* @throws Exception
*/
public void deleteReportList() throws Exception {
reportService.deleteReportList(crpo.getId());
}
/**
* 查询报表信息,包括四个表的数据
* @throws Exception
*/
public void getReport() throws Exception{
jsonOut(reportService.selectReport(id));
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* 根据报表名查询报表信息,查重
* @throws Exception
*/
public void getReportForName() throws Exception{
String reportName = this.getRequest().getParameter("reportName");
CreateReportParamPo createReportParamPo = new CreateReportParamPo();
createReportParamPo = reportService.selectReportByName(reportName);
try {
jsonOut(createReportParamPo);
} catch (Exception e) {
logger.error("异常exception",e);
}
}
}
|
package util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.Properties;
/**
* Class <code>DatabaseProperties</code> can load properties from a database for
* quick access.
*
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
* @see Properties
*/
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
public class DatabaseProperties extends Properties {
public static final String DEFAULT_NAME_COLUMN = "name";
public static final String DEFAULT_VALUE_COLUMN = "value";
public static final String SEPARATOR = ":##:";
/**
* Creates a new <code>DatabaseProperties</code> instance with no properties.
*/
public DatabaseProperties() {
super();
}
/**
* Creates a new <code>DatabaseProperties</code> instance loading in the properties from the database.
*
* If the load fails (i.e. load throws an SQLException), than a stack trace is printed out but the
* exception is not thrown.
*
* @param dr a <code>DatabaseReader</code> value
* @param table a <code>String</code> value
* @param idColumns a <code>String[]</code> value
* @param nameColumn a <code>String</code> value
* @param valueColumn a <code>String</code> value
* @see #load(DatabaseReader,String,String[],String,String)
*/
public DatabaseProperties(DatabaseReader dr, String table, String[] idColumns, String nameColumn, String valueColumn) {
try {
load(dr,table,idColumns,nameColumn,valueColumn);
}
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method <code>load</code> loads in the properties.
*
* @param dr a <code>DatabaseReader</code> value of the DatabaseReader to use to acquire a connection to the database
* @param table a <code>String</code> value of the name of the properties table
* @param idColumns a <code>String[]</code> value of the name of the id columns
* @param nameColumn a <code>String</code> value of the name of the name column or the default 'name' if null
* @param valueColumn a <code>String</code> value of the name of the value column or the default value of 'value' if null
* @exception SQLException if an error occurs
*/
// WMN 1/10/12 This method is drastically overcomplicated but the dotplot applet code uses it.
public void load(DatabaseReader dr, String table, String[] idColumns, String nameColumn, String valueColumn) throws SQLException {
if (nameColumn == null) nameColumn = DEFAULT_NAME_COLUMN;
if (valueColumn == null) valueColumn = DEFAULT_VALUE_COLUMN;
StringBuffer query = new StringBuffer("SELECT ");
for (int i = 0; i < idColumns.length; i++) query.append(idColumns[i]).append(",");
query.append(nameColumn).append(",").append(valueColumn);
query.append(" FROM ").append(table);
Object[] ids = new Object[idColumns.length];
Connection con = null;
Statement stat = null;
ResultSet rs = null;
try {
con = dr.getConnection();
stat = con.createStatement();
rs = stat.executeQuery(query.toString());
while (rs.next()) {
for (int i = 0; i < idColumns.length; i++) ids[i] = rs.getObject(idColumns[i]);
setProperty(ids,rs.getString(nameColumn),rs.getString(valueColumn));
}
}
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) { }
rs = null;
}
if (stat != null) {
try {
stat.close();
} catch (Exception e) { }
stat = null;
}
con = null;
}
}
/**
* Method <code>store</code> attempts to store the data into the database.
* The DatabaseReader must have insert and delete privledges. Also,
* id columns are treated as integers if they can successfully be parsed.
* Otherwise they are treated as strings.
*
* @param dr a <code>DatabaseReader</code> value
* @param table a <code>String</code> value
* @param idColumns a <code>String[]</code> value
* @param nameColumn a <code>String</code> value, default 'name' used if null
* @param valueColumn a <code>String</code> value, default 'value' used if null
* @exception SQLException if an error occurs
*/
public void store(DatabaseReader dr, String table, String[] idColumns, String nameColumn, String valueColumn) throws SQLException {
java.util.Enumeration enumNames = propertyNames(); // mdb changed 3/23/07 #109
if (!enumNames.hasMoreElements()) return ; // mdb changed 3/23/07 #109
if (nameColumn == null) nameColumn = DEFAULT_NAME_COLUMN;
if (valueColumn == null) valueColumn = DEFAULT_VALUE_COLUMN;
Connection con = null;
PreparedStatement stat = null;
ResultSet rs = null;
String query = "REPLACE "+table+" (";
if (idColumns.length > 0) {
query += idColumns[0];
for (int i = 1; i < idColumns.length; ++i) query += ","+idColumns[i];
query += ",";
}
query += nameColumn+","+valueColumn+") VALUES (";
if (idColumns.length > 0) {
query += "?";
for (int i = 1; i < idColumns.length; ++i) query += ",?";
query += ",";
}
query += "?,?)";
try {
con = dr.getConnection();
stat = con.prepareStatement(query);
while (enumNames.hasMoreElements()) { // mdb changed 3/23/07 #109
String key = (String)enumNames.nextElement(); // mdb changed 3/23/07 #109
String[] vals = key.split(SEPARATOR);
for (int i = 0; i < vals.length-1; i++) {
try {
int j = Integer.parseInt(vals[i]);
stat.setInt(i+1,j);
}
catch (NumberFormatException n) {
stat.setString(i+1,vals[i]);
}
}
stat.setString(vals.length,vals[vals.length-1]);
stat.setString(vals.length+1,getProperty(key));
stat.addBatch();
}
stat.executeBatch();
}
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) { }
rs = null;
}
if (stat != null) {
try {
stat.close();
} catch (Exception e) { }
stat = null;
}
con = null;
}
}
/**
* Method <code>setProperty</code> sets the property
*
* @param ids an <code>Object[]</code> value
* @param name a <code>String</code> value
* @param value a <code>String</code> value
* @return an <code>Object</code> value of the previous value of the resultant key or null if it didn't exist
* @see #getKey(Object[],String)
* @see Properties#setProperty(String,String)
*/
public Object setProperty(Object[] ids, String name, String value) {
return setProperty(getKey(ids,name),value);
}
/**
* Method <code>setProperty</code> is a convenience method for single id property tables
*
* Will call setProperty(Object[],String,String) if id is an instance of an Object[]
*
* @param id an <code>Object</code> value
* @param name a <code>String</code> value
* @param value a <code>Strin</code> value
* @return an <code>Object</code> value
*/
public Object setProperty(Object id, String name, String value) {
if (id instanceof Object[]) return setProperty((Object[])id,name,value);
return setProperty(new Object[] {id},name,value);
}
/**
* Method <code>getProperty</code> returns the property or null if it doesn't exist
*
* @param ids an <code>Object[]</code> value of the ids given in the same order as on loading
* @param name a <code>String</code> value of the name
* @return a <code>String</code> value
* @see #getKey(Object[],String)
* @see Properties#getProperty(String)
*/
public String getProperty(Object[] ids, String name) {
return getProperty(getKey(ids,name));
}
/**
* Method <code>getProperty</code>
*
* @param ids an <code>Object[]</code> value
* @param name a <code>String</code> value
* @param defaultValue a <code>String</code> value
* @return a <code>String</code> value
* @see #getKey(Object[],String)
* @see Properties#getProperty(String,String)
*/
public String getProperty(Object[] ids, String name, String defaultValue) {
return getProperty(getKey(ids,name),defaultValue);
}
/**
* Method <code>getIntProperty</code> is a convenience method for converting
* a property into an integer. If the property doesn't exist or can't be
* converted to an integer, <code>defaultValue</code> is used.
*
* @param ids an <code>Object[]</code> value
* @param name a <code>String</code> value
* @param defaultValue an <code>int</code> value
* @return an <code>int</code> value
* @see #getProperty(Object[],String)
* @see Integer#parseInt(String)
*/
public int getIntProperty(Object[] ids, String name, int defaultValue) {
String prop = getProperty(ids,name);
if (prop != null && prop.trim().length() > 0) {
try {
defaultValue = Integer.parseInt(prop);
} catch (Exception e) { }
}
return defaultValue;
}
/**
* Method <code>getProperty</code> is a convenience method for a single id properties table
*
* @param id an <code>Object</code> value
* @param name a <code>String</code> value
* @param defaultValue a <code>String</code> value
* @return a <code>String</code> value
* @see #getKey(Object,String)
* @see Properties#getProperty(String,String)
*/
public String getProperty(Object id, String name, String defaultValue) {
return getProperty(getKey(id,name),defaultValue);
}
/**
* Method <code>getIntProperty</code> is a convenience method for a single id properties table
*
* @param id an <code>Object</code> value
* @param name a <code>String</code> value
* @param defaultValue an <code>int</code> value
* @return an <code>int</code> value
* @see #getKey(Object,String)
* @see Properties#getProperty(java.lang.String)
* @see Integer#parseInt(java.lang.String)
*/
public int getIntProperty(Object id, String name, int defaultValue) {
String prop = getProperty(getKey(id,name));
if (prop != null && prop.trim().length() > 0) {
try {
defaultValue = Integer.parseInt(prop);
} catch (Exception e) { }
}
return defaultValue;
}
/**
* Method <code>getBooleanProperty</code> is a convenience method for a single id properties table.
*
* First sees if it's an integer by attempting to parse it. If successfull, any non-zero value is
* determined to be true. Otherwise, returns true if the value is equal to "true" ignoring case.
*
* @param id an <code>Object</code> value
* @param name a <code>String</code> value
* @param defaultValue an <code>boolean</code> value
* @return an <code>boolean</code> value
* @see #getKey(Object,String)
* @see Properties#getProperty(java.lang.String)
* @see Boolean#valueOf(java.lang.String)
*/
public boolean getBooleanProperty(Object id, String name, boolean defaultValue) {
String prop = getProperty(getKey(id,name));
if (prop != null && prop.trim().length() > 0) {
try {
int i = Integer.parseInt(prop);
defaultValue = i != 0;
} catch (Exception e) {
defaultValue = Boolean.valueOf(prop).booleanValue();
}
}
return defaultValue;
}
/**
* Method <code>getBooleanProperty</code> is a convenience method for converting
* a property into an boolean. If the property doesn't exist or can't be
* converted to an integer, <code>defaultValue</code> is used.
*
* First sees if it's an integer by attempting to parse it. If successfull, any non-zero value is
* determined to be true. Otherwise, returns true if the value is equal to "true" ignoring case.
*
* @param ids an <code>Object[]</code> value
* @param name a <code>String</code> value
* @param defaultValue an <code>boolean</code> value
* @return an <code>boolean</code> value
* @see #getProperty(Object[],String)
* @see Integer#parseInt(String)
* @see Boolean#valueOf(java.lang.String)
*/
public boolean getBooleanProperty(Object[] ids, String name, boolean defaultValue) {
String prop = getProperty(ids,name);
if (prop != null && prop.trim().length() > 0) {
try {
int i = Integer.parseInt(prop);
defaultValue = i != 0;
} catch (Exception e) {
defaultValue = Boolean.valueOf(prop).booleanValue();
}
}
return defaultValue;
}
public Number getNumberProperty(Object[] ids, String name, Number defaultValue) {
String prop = getProperty(ids,name);
if (prop != null && prop.trim().length() > 0) {
try {
Class c = defaultValue.getClass();
java.lang.reflect.Constructor con = c.getConstructor(new Class[] {String.class});
Number n = (Number)con.newInstance(new Object[] {prop});
defaultValue = n;
} catch (Exception e) { }
}
return defaultValue;
}
public Number getNumberProperty(Object id, String name, Number defaultValue) {
return getNumberProperty(new Object[] {id},name,defaultValue);
}
/**
* Method <code>getKey</code> returns the key used that corrisponds to ids and name
*
* @param ids an <code>Object[]</code> value
* @param name a <code>String</code> value
* @return a <code>String</code> value
*/
public static String getKey(Object[] ids, String name) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < ids.length; i++) buf.append(ids[i]).append(SEPARATOR);
buf.append(name);
return buf.toString();
}
/**
* Method <code>getKey</code> is a convenience method for single id column properties tables.
*
* @param id an <code>Object</code> value
* @param name a <code>String</code> value
* @return a <code>String</code> value
*/
public static String getKey(Object id, String name) {
return new StringBuffer().append(id).append(SEPARATOR).append(name).toString();
}
}
|
package buyAndSell;
public class WishlistMessage extends Message {
public WishlistMessage(Item item, String time, String date, int messageId, int sellerId, int buyerId) {
super(item,time,date, messageId, sellerId, buyerId);
this.item = item;
this.title = "Someone is interested in your "+ item.getName();
this.msg = StoreDatabase.getUserProfileByID(buyerId).getUsername() + " added your " + item.getName()
+ " to their Wishlist!";
}
}
|
package devinfosys.dao;
import java.util.List;
import devinfosys.model.DeveloperType;
public interface IDeveloperTypeDAO {
public abstract List<DeveloperType> getDeveloperTypes();
}
|
package com.csp.util;
import java.util.Properties;
/**
* Class having Constants and methods to load properties from file.
*
*/
public class CommonPortletProperties {
/** The properties. */
private static Properties properties = com.csp.common.properties.CommonProperties.loadPropertiesFile("common.properties");;
/** The portlet name. */
public static String PORTLET_NAME = properties.getProperty("portlet.name");
/** The portlet id. */
public static String PORTLET_ID = properties.getProperty("portlet.id");
/** The TA b1. */
public static String TAB1 = properties.getProperty("tab1");
/** The TA b2. */
public static String TAB2 = properties.getProperty("tab2");
/** The TA b3. */
public static String TAB3 = properties.getProperty("tab3");
/** The Configure Base Price Tab */
public static String CONFIGURE_BASE_PRICE_TAB = properties.getProperty("configure-base-price-tab");
/** The Configure Base Price Tab */
public static String PRICING_CALCULATOR_TAB = properties.getProperty("pricing-calculator-tab");
/** The active tab. */
public static String ACTIVE_TAB = properties.getProperty("active.tab");
/** The page error permission. */
public static String PAGE_ERROR_PERMISSION = properties.getProperty("page.error.permission");
/** The PERMISSIO n_ ta b1_ view. */
public static String PERMISSION_TAB1_VIEW = properties.getProperty("permission.tab1-view");
/** The PERMISSIO n_ ta b2_ view. */
public static String PERMISSION_TAB2_VIEW = properties.getProperty("permission.tab2-view");
/** The PERMISSIO n_ ta b3_ view. */
public static String PERMISSION_TAB3_VIEW = properties.getProperty("permission.tab3-view");
/** The PERMISSIO configure base price tab_ view. */
public static String CONFIGURE_BASE_PRICE_TAB_VIEW = properties.getProperty("permission.configure-base-price-tab");
/** The PERMISSIO configure pricing calculator tab_ view. */
public static String PRICING_CALCULATOR_TAB_VIEW = properties.getProperty("permission.pricing-calculatore-tab");
/** The permission add contact. */
public static String PERMISSION_ADD_CONTACT = properties.getProperty("permission.add-contact");
/** The permission view contact. */
public static String PERMISSION_VIEW_CONTACT = properties.getProperty("permission.view-contact");
/** The permission delete contact. */
public static String PERMISSION_DELETE_CONTACT = properties.getProperty("permission.delete-contact");
/** The PERMISSIO n_ ta b2_ actio n1. */
public static String PERMISSION_TAB2_ACTION1 = properties.getProperty("permission.tab2-action1");
/** The PERMISSIO n_ ta b2_ actio n2. */
public static String PERMISSION_TAB2_ACTION2 = properties.getProperty("permission.tab2-action2");
/** The role service proevider admin. */
public static String ROLE_SERVICE_PROEVIDER_ADMIN = properties.getProperty("role.service.proevider.admin");
/** The role service proevider user. */
public static String ROLE_SERVICE_PROEVIDER_USER = properties.getProperty("role.service.proevider.user");
/** The role customer admin. */
public static String ROLE_CUSTOMER_ADMIN = properties.getProperty("role.customer.admin");
/** The role customer user. */
public static String ROLE_CUSTOMER_USER = properties.getProperty("role.customer.user");
/** The role type service proevider admin. */
public static String ROLE_TYPE_SERVICE_PROEVIDER_ADMIN = properties.getProperty("role.type.service.proevider.admin");
/** The role type service proevider user. */
public static String ROLE_TYPE_SERVICE_PROEVIDER_USER = properties.getProperty("role.type.service.proevider.user");
/** The role type customer admin. */
public static String ROLE_TYPE_CUSTOMER_ADMIN = properties.getProperty("role.type.customer.admin");
/** The role type customer user. */
public static String ROLE_TYPE_CUSTOMER_USER = properties.getProperty("role.type.customer.user");
/** The user admin email. */
public static String USER_ADMIN_EMAIL = properties.getProperty("user.admin.email");
/** The service provider admin role. */
public static String TYPE_SERVICE_PROVIDER_ADMIN = properties.getProperty("type.service.provider.admin");
/** The service provider user role. */
public static String TYPE_SERVICE_PROVIDER_USER = properties.getProperty("type.service.provider.user");
/** The context url. */
public static String CONTEXT_URL = properties.getProperty("context.url");
/** The PERMISSIO n_ preview_ view. */
public static String PERMISSION_PREVIEW_VIEW = properties.getProperty("permission.preview-view");
/** The TA b1. */
public static String PREVIEW_TAB = properties.getProperty("previewTab");
/** The active tab. */
public static String PRICING_ACTIVE_TAB = properties.getProperty("pricing.active.tab");
public static String CONFIGURE_COEFF_TAB_VIEW = properties.getProperty("permission.CONFIGURE_COEFF_TAB_VIEW");
public static String CONFIGURE_COEFF_DURATION_TAB_VIEW = properties.getProperty("permission.CONFIGURE_COEFF_DURATION_TAB_VIEW");
public static String CONFIGURE_COEFF_LATENCY_TAB_VIEW = properties.getProperty("permission.CONFIGURE_COEFF_LATENCY_TAB_VIEW");
public static String ACCESS_DENIED_MESSAGE = properties.getProperty("access.denied.msg");
public static String FIELD_REQUIRED_MESSAGE = properties.getProperty("msg.error.required");
public static String FIELD_INVALID_MESSAGE = properties.getProperty("msg.error.invalid.field");
public static String SI_CONFIGURATION_UPDATE_SUCCESS_MSG = properties.getProperty("si.update.successful.msg");
public static String SI_CONFIGURATION_UPDATE_FAILURE_MSG = properties.getProperty("si.update.failure.msg");
public static String SI_HOST_API = properties.getProperty("si.host.api");
public static String SI_HOST_APP = properties.getProperty("si.host.app");
public static String CONTROLLER_CONFIG_UPDATE_SUCCESS_MSG = properties.getProperty("controller.config.update.successful.msg");
public static String API_CONTROLLER_URL = properties.getProperty("api.controller.url");
public static String ACCESS_DENIED_MSG = properties.getProperty("access.denied.msg");
public static String API_CONTROLLER_CONNECTIVITY_FAIL_MSG = properties.getProperty("api.connectivity.fail.msg");
public static String API_CONTROLLER_CONNECTIVITY_SUCCESS_MSG = properties.getProperty("api.connectivity.success.msg");
public static String API_SUCCESS_CODE_PREFIX = properties.getProperty("api.success.prefix.code");
public static String API_METHOD_NOT_ALLOWED_CODE = properties.getProperty("api.method.not.allowed.code");
public static String API_URL_INVALID_PROP = properties.getProperty("api.url.invalid");
public static String STATUS_ACTIVE_CODE = properties.getProperty("status.active");
public static String STATUS_INACTUVE_CODE = properties.getProperty("status.inactive");
public static String CONTROLLER_CONFIG_UPDATE_FAIL_MSG = properties.getProperty("controller.config.update.fail.msg");
public static String SIMULATION_MODE_NORMAL = properties.getProperty("simulation.mode.normal");
public static String SIMULATION_MODE_NORMAL_CODE = properties.getProperty("simulation.mode.normal.code");
public static String SIMULATION_MODE_SIMULATION = properties.getProperty("simulation.mode.simulation");
public static String SIMULATION_MODE_CODE = properties.getProperty("simulation.mode.code");
public static String CSP_CORE_SETTING_PROP = properties.getProperty("csp.core.setting");
public static String SIMULATION_SETTING_PROP = properties.getProperty("setting.simulation");
public static String CONTROLLER_USERNAME_MAX_LENGTH_PROP = properties.getProperty("validation.username.max.length");
public static String CONTROLLER_API_MAX_LENGTH_PROP = properties.getProperty("validation.api.url.max.length");
public static String CONTROLLER_PASSWORD_MAX_LENGTH_PROP = properties.getProperty("validation.password.max.length");
public static String ERROR_MSG_INVALID_USERNAME_PROP = properties.getProperty("msg.error.invalid.username");
public static String ERROR_MSG_INVALID_PASSWORD_PROP = properties.getProperty("msg.error.invalid.password");
public static String ERROR_MSG_INVALID_API_URL = properties.getProperty("msg.error.invalid.url");
public static String UNASSIGN_SERVICE_CUSTOMER = properties.getProperty("UNASSIGN_SERVICE_CUSTOMER");
public static String DEACTIVATE_SERVICE_BILLING_ACCOUNT = properties.getProperty("DEACTIVATE_SERVICE_BILLING_ACCOUNT");
public static String DEACTIVATE_SERVICE = properties.getProperty("DEACTIVATE_SERVICE");
/**
* CALLBACK BWOD SCOPES
*/
public static String SCOPE_BWOD_CALLBACK_UNASSIGN_CUSTOMER = properties.getProperty("SCOPE_BWOD_CALLBACK_UNASSIGN_CUSTOMER");
public static String SCOPE_BWOD_CALLBACK_DEACTIVATE_BILLINGACCOUNT = properties.getProperty("SCOPE_BWOD_CALLBACK_DEACTIVATE_BILLINGACCOUNT");
public static String SCOPE_BWOD_CALLBACK_DEACTIVATE = properties.getProperty("SCOPE_BWOD_CALLBACK_DEACTIVATE");
}
|
package edu.neu.ccs.cs5010;
import sun.plugin.dom.exception.WrongDocumentException;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* created by xwenfei on 11/16/2017
*/
public class ReadCSVFile {
private String givenFileName;
private final int resort = 0;
private final int day = 1;
private final int skierID = 2;
private final int liftID = 3;
private final int timeStamp = 4;
public ReadCSVFile(String fileName){
this.givenFileName = fileName;
}
/**
*
* @param csvFile the file contains all the information we needed
* @return a hashmap, K is skier's ID, V is a list of lift which that skiers ride
* @throws IOException
*/
public List<HashMap> readInfoFromFile(String csvFile) throws IOException {
List<HashMap> mapList = new ArrayList<>();
HashMap<String,String> IDPairMap = new HashMap<>();
HashMap<String, List<String>> skierInfoMap = new HashMap<>();
HashMap<Integer,Integer> liftHourMap = new HashMap<>();
InputStream inputStream = new FileInputStream(csvFile);
Reader rder = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(rder);
String[] info;
String line = null;
if(csvFile == null){
throw new IllegalArgumentException("Template file should not be null");
}
try{
while((line= reader.readLine())!=null && line.length() > 0){
String[] rowInfo = line.split(",");
info = new String[4];
if(!skierInfoMap.containsKey(rowInfo[skierID])) {
List<String> liftIDList = new ArrayList<>();
liftIDList.add(rowInfo[liftID]);
skierInfoMap.put(rowInfo[skierID], liftIDList);
IDPairMap.put(rowInfo[skierID], rowInfo[liftID]);
liftHourMap.put(getHour(rowInfo[4]),Integer.parseInt(rowInfo[liftID]));
}
else{
skierInfoMap.get(rowInfo[skierID]).add(rowInfo[liftID]);
}
}
reader.close();
}catch (Exception e) {
e.printStackTrace();
}
mapList.add(skierInfoMap);
mapList.add(getTotalVerticalforEachID(skierInfoMap));
mapList.add(IDPairMap);
mapList.add(liftHourMap);
//System.out.println(testCount);
return mapList;
}
public int getHour(String timeInFile) throws IOException{
int hour;
double time = Double.parseDouble(timeInFile);
if(time < 1 || time > 360) throw new IllegalArgumentException(
"time wrong in file"
);
if (time <= 60) hour = 1;
else if (time > 60 && time <= 120) hour = 2;
else if (time > 120 && time <= 180) hour = 3;
else if (time > 180 && time <= 240) hour = 4;
else if (time > 240 && time <= 300) hour = 5;
else hour = 6;
return hour;
}
/**
*
* @param
* @return a map, K is the skier's ID,which is unique. V is the total vertical number he/she ride the lift
*/
public HashMap<String,Integer> getTotalVerticalforEachID(HashMap<String,List<String>> skierInfoMap) {
HashMap<String, Integer> verticalSumMap = new HashMap<>();
int liftIDRange = 0;
//double verticalNum = 0;
for (HashMap.Entry entry : skierInfoMap.entrySet()) {
int verticalSum = 0;
String skierID = (String) entry.getKey();
//System.out.println(skierID);
for (int i = 0; i < skierInfoMap.get(skierID).size(); i++) {
int verticalNum = 0;
try {
int liftType = Integer.parseInt(skierInfoMap.get(skierID).get(i));
if(liftType >= 1 && liftType <= 10) verticalNum = 200;
else if(liftType >= 11 && liftType <= 20) verticalNum = 300;
else if(liftType >= 21 && liftType <= 30) verticalNum = 400;
else if(liftType >= 31 && liftType <= 40) verticalNum = 500;}
catch (NumberFormatException e) {
System.out.println("not a number");
}
verticalSum = verticalSum + verticalNum;
}
verticalSumMap.put(skierID, verticalSum);
}
return verticalSumMap;
}
public List<Map.Entry<String, Integer>> sortByValue(Map<String, Integer> map) {
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
return list;
}
}
|
package com.htffund.yangcheng.elasticsearch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.transport.TransportClient;
public class TestMain {
private static Logger logger = LogManager.getLogger(TestMain.class);
public static void main(String[] args) {
ESClient esClient=new ESClient();
esClient.startup();
Document document = new Document();
//document.getIndex();
/*document.getGetResponse("us","user","1000");
document.getDeleteResponse();*/
}
}
|
package me.lordall.lordrp.event;
import me.lordall.lordrp.mysql.PlayerMysql;
import me.lordall.lordrp.scoreboard.CustomScoreBoardManager;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
/**
* Created by Lord_All on 03/03/2018
*/
public class PlayerJoin implements Listener{
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
// Util for All
player.teleport(new Location(player.getWorld(), -251.5, 64, 213.5));
e.setJoinMessage("§eWelcome §c" + player.getDisplayName() + "§e in LordRP server!");
// Scoreboard
CustomScoreBoardManager scoreBoardManager = new CustomScoreBoardManager(player);
scoreBoardManager.sendLine();
scoreBoardManager.setScoreboard();
}
}
|
/*
* Copyright (C) 2018 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.android.class2greylist;
import java.util.Locale;
public class Status {
// Highlight "Error:" in red.
private static final String ERROR = "\u001B[31mError: \u001B[0m";
private final boolean mDebug;
private boolean mHasErrors;
public Status(boolean debug) {
mDebug = debug;
}
public void debug(String msg, Object... args) {
if (mDebug) {
System.err.println(String.format(Locale.US, msg, args));
}
}
public void error(Throwable t) {
System.err.print(ERROR);
t.printStackTrace(System.err);
mHasErrors = true;
}
public void error(String message, Object... args) {
System.err.print(ERROR);
System.err.println(String.format(Locale.US, message, args));
mHasErrors = true;
}
public boolean ok() {
return !mHasErrors;
}
}
|
package com.git.cloud.appmgt.model.vo;
/**
* 应用系统返回结果VO
* @author qiupj
* @date 2014-12-17 上午11:18:04
* @version v1.0
*
*/
public class AppSysErrorVo {
private String resultFlag;//0-失败;1-成功
private String errormsg;
private String appId;
private String remark;
public AppSysErrorVo() {
}
public AppSysErrorVo(String resultFlag, String errormsg, String appId,
String remark) {
super();
this.resultFlag = resultFlag;
this.errormsg = errormsg;
this.appId = appId;
this.remark = remark;
}
public String getResultFlag() {
return resultFlag;
}
public void setResultFlag(String resultFlag) {
this.resultFlag = resultFlag;
}
public String getErrormsg() {
return errormsg;
}
public void setErrormsg(String errormsg) {
this.errormsg = errormsg;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
|
package edu.zc.oj.controller;
import edu.zc.oj.configuration.JudgeConfiguration;
import edu.zc.oj.entity.*;
import edu.zc.oj.entity.request.Compile;
import edu.zc.oj.entity.request.JudgeParameter;
import edu.zc.oj.entity.request.Run;
import edu.zc.oj.entity.request.TestCase;
import edu.zc.oj.judge.JudgeClient;
import edu.zc.oj.judge.JudgeResource;
import edu.zc.oj.judge.PlanFileResource;
import edu.zc.oj.utils.CommandUtils;
import edu.zc.oj.utils.StringUtils;
import edu.zc.oj.utils.UuidUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author <a href="mailTo:5239604@qq.com">coderPlus-tr</a>
* @date 2021/3/6
*/
@Slf4j
@RestController
@RequiredArgsConstructor
public class JudgeController {
private final JudgeConfiguration judgeConfiguration;
private final JudgeClient judgeClient;
/**
* <ol>
* <li>通过languageConfig对源代码进行编译</li>
* <li>循环测试用例</li>
* <li>生成临时输入输出文件</li>
* <li>如果result.result == 0 进行下一步,否则直接返回</li>
* <li>比对临时输出文件和测试用例的输出去掉尾部空格的MD5值是否一致</li>
* <li>不一致更改result.result = 4</li>
* </ol>
*
* @param judgeParameter 包含源代码,测试用例,语言配置
* @return 所有测试用例的测试结果
*/
@PostMapping("/judge")
public List<Result> judge(@RequestBody @Valid JudgeParameter judgeParameter) throws Exception {
final Compile compile = judgeParameter.getLanguageConfig().getCompile();
final Run run = judgeParameter.getLanguageConfig().getRun();
final String src = judgeParameter.getSrc();
final String judgeLogPath = judgeConfiguration.getJudgeLogPath();
final Integer userId = judgeConfiguration.getUserId();
final Integer groupId = judgeConfiguration.getGroupId();
final List<Result> results = new ArrayList<>();
try (final JudgeResource judgeResource = new JudgeResource(UuidUtils.uuid32(), judgeConfiguration)) {
final String workDir = judgeResource.getJudgeDir();
// compile
String compileCommandFormat = compile.getCompileCommand();
final String exePath = workDir + File.separator + compile.getExeName();
final String srcPath = workDir + File.separator + compile.getSrcName();
// generate src file
if (compileCommandFormat.contains("{src_path}")) {
compileCommandFormat = compileCommandFormat.replace("{src_path}", srcPath);
}
if (compileCommandFormat.contains("{exe_dir}")) {
compileCommandFormat = compileCommandFormat.replace("{exe_dir}", workDir);
}
if (compileCommandFormat.contains("{exe_path}")) {
compileCommandFormat = compileCommandFormat.replace("{exe_path}", exePath);
}
try (final PlanFileResource planFileResource = new PlanFileResource(judgeConfiguration, srcPath, src)) {
// compile src file
CommandUtils.exec(compileCommandFormat);
String commandFormat = run.getCommand();
if (commandFormat.contains("{exe_path}")) {
commandFormat = commandFormat.replace("{exe_path}", exePath);
}
if (commandFormat.contains("{exe_dir}")) {
commandFormat = commandFormat.replace("{exe_dir}", workDir);
}
if (commandFormat.contains("{max_memory}")) {
commandFormat = commandFormat.replace("{max_memory}", String.valueOf(compile.getMaxMemory() / 1024));
}
final String[] commands = commandFormat.split(" ");
final String command = commands[0];
String[] args;
if (commands.length > 1) {
args = new String[commands.length - 1];
System.arraycopy(commands, 1, args, 0, args.length );
} else {
args = null;
}
final List<TestCase> testCases = judgeParameter.getTestCases();
for (int i = 0; i < testCases.size(); i++) {
final String inFilePath = workDir + File.separator + i + ".in";
final String outFilePath = workDir + File.separator + i + ".out";
final String in = testCases.get(i).getIn();
final String out = testCases.get(i).getOut();
Config config = new Config();
config.setLogPath(judgeLogPath);
config.setGid(groupId);
config.setUid(userId);
config.setStack(128 * 1024 * 1024);
config.setMemory(judgeParameter.getMaxMemory() == null ? compile.getMaxMemory() : judgeParameter.getMaxMemory());
config.setSeccompRuleName(run.getSeccompRule());
config.setExePath(commands[0]);
config.setCpuTime(judgeParameter.getMaxCpuTime() == null ? compile.getMaxCpuTime() : judgeParameter.getMaxCpuTime());
config.setRealTime(compile.getMaxRealTime());
// TODO: 获取环境变量的ENV
config.setEnv(run.getEnv());
config.setArgs(args);
config.setInputPath(inFilePath);
config.setOutputPath(outFilePath);
config.setProcessNumber(JudgeClient.UNLIMITED);
config.setOutputSize(1024 * 1024 * 16);
config.setMemoryLimitCheckOnly(run.getMemoryLimitCheckOnly() == null ? 0 : run.getMemoryLimitCheckOnly());
try (final PlanFileResource inFileResource = new PlanFileResource(judgeConfiguration, inFilePath, in);
final PlanFileResource outFileResource = new PlanFileResource(judgeConfiguration, outFilePath)
) {
final Result result = judgeClient.run(config);
results.add(result);
if (result.getResult() == ResultCode.SUCCESS) {
String userOut = DigestUtils.md5DigestAsHex(StringUtils.trimEnd(new String(Files.readAllBytes(Paths.get(outFilePath))).toCharArray()).getBytes());
String realOut = DigestUtils.md5DigestAsHex(StringUtils.trimEnd(out.toCharArray()).getBytes());
if (!userOut.equals(realOut)) {
result.setResult(ResultCode.WRONG_ANSWER);
}
}
}
}
try{
Files.delete(Paths.get(exePath+".class"));
}catch (IOException ignore){
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw e;
}
return results;
}
}
|
package com.kubox.alayaspa;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
// final WebView myWebView = (WebView) findViewById(R.id.webview);
// myWebView.getSettings().setJavaScriptEnabled(true);
// myWebView.getSettings().setAppCacheEnabled(true);
// myWebView.loadUrl("http://192.168.100.67/website/alaya-mobile/");
// myWebView.setWebViewClient(new WebViewClient());
final WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.loadUrl("http://192.168.0.7/website/alaya-mobile/");
myWebView.setWebViewClient(new WebViewClient(){
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
myWebView.loadUrl("file:///android_asset/error.html");
}
});
}
}
|
/*
* tools4j-validator - Framework for Validation
* Copyright (c) 2014, David A. Bauer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tools4j.validator;
import java.awt.Window;
import java.io.StringReader;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
import javax.swing.JOptionPane;
public abstract class Validator<T> {
private static String violationMessageLanguage = Locale.getDefault().getLanguage();
protected static ResourceBundle violationMessageResource = ResourceBundle.getBundle("tools4j.resources/Validator", new Locale(violationMessageLanguage));
protected static final String[] OPENED = {"(", "["};
protected static final String[] CLOSED = {")", "]"};
protected static final String[] SMALLER = {"<", "<=", "\u2264"};
protected static final String[] LARGER = {">", ">=", "\u2265"};
protected String violationMessage;
protected String violationConstraint;
protected TransformationListener transformationListener;
protected ValidationListener validationListener;
protected BusinessRuleListener businessRuleListener;
protected boolean notNull; // NotNull
protected boolean Null; // Null
protected String businessRuleID;
protected T transformedValue;
protected String constraints;
public static String getViolationMessageLanguage() {
return violationMessageLanguage;
}
public static void setViolationMessageLanguage(String violationMessageLanguage) {
Validator.violationMessageLanguage = violationMessageLanguage;
violationMessageResource = ResourceBundle.getBundle("tools4j.resources/Validator", new Locale(violationMessageLanguage));
}
public String getViolationMessage() {
return violationMessage;
}
public String getViolationConstraint() {
return violationConstraint;
}
public TransformationListener getTransformationListener() {
return transformationListener;
}
public void setTransformationListener(TransformationListener transformationListener) {
this.transformationListener = transformationListener;
}
public ValidationListener getValidationListener() {
return validationListener;
}
public void setValidationListener(ValidationListener validationListener) {
this.validationListener = validationListener;
}
public BusinessRuleListener getBusinessRuleListener() {
return businessRuleListener;
}
public void setBusinessRuleListener(BusinessRuleListener businessRuleListener) {
this.businessRuleListener = businessRuleListener;
}
public boolean isNotNull() {
return notNull;
}
public void setNotNull(boolean value) {
notNull = value;
}
public boolean isNull() {
return Null;
}
public void setNull(boolean value) {
Null = value;
}
public String getBusinessRuleID() {
return businessRuleID;
}
public void setBusinessRuleID(String value) {
businessRuleID = value;
}
protected abstract boolean transform(Window window, String value);
public boolean validateString(String value) {
return validateString(null, value);
}
public boolean validateString(Window window, String value) {
boolean result = true;
if (transformationListener!=null) transformationListener.before(this, value);
if (value==null) {
if (notNull) {
violationConstraint = "NotNull";
violationMessage = String.format(violationMessageResource.getString("STR_NOTNULL"));
showViolationDialog(window);
result = false;
}
}
else {
if (Null) {
violationConstraint = "Null";
violationMessage = String.format(violationMessageResource.getString("STR_NULL"));
showViolationDialog(window);
result = false;
}
}
if (result && value!=null)
result = transform(window, value);
if (transformationListener!=null) transformationListener.after(this, value, result);
if (result)
return validate(window, transformedValue);
else
return false;
}
protected abstract boolean validation(Window window, T value);
public boolean validate(T value) {
return validate(null, value);
}
public boolean validate(Window window, T value) {
this.transformedValue = value;
boolean result = true;
violationMessage = null;
violationConstraint = null;
if (validationListener!=null) validationListener.before(this);
if (value==null) {
if (notNull) {
violationConstraint = "NotNull";
violationMessage = String.format(violationMessageResource.getString("STR_NOTNULL"));
showViolationDialog(window);
result = false;
}
}
else {
if (Null) {
violationConstraint = "Null";
violationMessage = String.format(violationMessageResource.getString("STR_NULL"));
showViolationDialog(window);
result = false;
}
}
if (result && value!=null)
result = validation(window, value);
if (result)
if (businessRuleListener!=null) {
result = businessRuleListener.checkBusinessRule(this);
if (!result) {
violationConstraint = "Rule";
if (businessRuleID!=null) {
String businessRuleName = null;
if (businessRuleListener instanceof DefaultBusinessRuleListener)
businessRuleName = ((DefaultBusinessRuleListener)businessRuleListener).getBusinessRuleName(this);
violationMessage = String.format(violationMessageResource.getString("STR_RULE2"), businessRuleName!=null ? businessRuleName : businessRuleID);
}
else
violationMessage = String.format(violationMessageResource.getString("STR_RULE"));
showViolationDialog(window);
}
}
if (validationListener!=null) validationListener.after(this, result);
return result;
}
public T getValue() {
return transformedValue;
}
protected void showViolationDialog(Window window) {
if (window!=null)
JOptionPane.showMessageDialog(window,
violationMessage,
violationMessageResource.getString("STR_TITLE"),
JOptionPane.ERROR_MESSAGE);
}
public String getConstraints() {
return constraints;
}
protected abstract void interpretConstraints(String constraints);
public void setConstraints(String constraints) {
this.constraints = constraints;
notNull = false;
Null = false;
businessRuleID = null;
JsonParser parser = Json.createParser(new StringReader(constraints));
while (parser.hasNext()) {
Event e = parser.next();
if (e == Event.KEY_NAME)
if (parser.getString().equalsIgnoreCase("constraint")) {
parser.next();
if (parser.getString().equalsIgnoreCase("NotNull")) {
setNotNull(true);
} else if (parser.getString().equalsIgnoreCase("Null")) {
setNull(true);
} else if (parser.getString().equalsIgnoreCase("Rule")) {
parser.next();
parser.next();
setBusinessRuleID(parser.getString());
}
}
}
parser.close();
interpretConstraints(constraints);
}
public void setConstraints(JsonObject model) {
setConstraints(model.toString());
}
protected abstract void buildConstraints(JsonArrayBuilder jsonArrayBuilder);
public JsonObject getConstraintsAsJsonObject() {
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
if (isNotNull())
jsonArrayBuilder.add(Json.createObjectBuilder().add("constraint", "NotNull"));
if (isNull())
jsonArrayBuilder.add(Json.createObjectBuilder().add("constraint", "Null"));
if (businessRuleID!=null)
jsonArrayBuilder.add(Json.createObjectBuilder()
.add("constraint", "Rule")
.add("id", businessRuleID));
buildConstraints(jsonArrayBuilder);
JsonObject result = Json.createObjectBuilder()
.add("type", getClass().getSimpleName().replace("Validator", ""))
.add("constraints", jsonArrayBuilder).build();
return result;
}
}
|
package com.example.ecommerce;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ecommerce.Model.Products;
import com.example.ecommerce.ViewHolder.ProductViewHolder;
import com.example.ecommerce.databinding.ActivityDisplaySubCategoriesProductsBinding;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class DisplaySubCategoriesProductsActivity extends AppCompatActivity {
ActivityDisplaySubCategoriesProductsBinding activityDisplaySubCategoriesBinding;
private ClickHandler clickHandler;
RecyclerView.LayoutManager layoutManager;
public String dbName;
public String category;
public String subCategory;
DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityDisplaySubCategoriesBinding = DataBindingUtil.setContentView(this,R.layout.activity_display_sub_categories_products);
clickHandler = new ClickHandler(this);
activityDisplaySubCategoriesBinding.setClickHandler(clickHandler);
dbName = getIntent().getStringExtra("dbName");
reference = FirebaseDatabase.getInstance().getReference().child("Products");
activityDisplaySubCategoriesBinding.recyclerCategorySubCategoriesProductsProductsDisplay.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
activityDisplaySubCategoriesBinding.recyclerCategorySubCategoriesProductsProductsDisplay.setLayoutManager(layoutManager);
category = getIntent().getStringExtra("category");
subCategory = getIntent().getStringExtra("subCategory");
}
public class ClickHandler {
private Context context;
public String category = getIntent().getStringExtra("category") + "/" + getIntent().getStringExtra("subCategory");
public ClickHandler(Context context) {
this.context = context;
}
}
@Override
protected void onStart() {
super.onStart();
dbName = getIntent().getStringExtra("dbName");
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(reference.orderByChild("subCategory").equalTo(subCategory), Products.class)
.build();
FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
String stringPriceHome = "Price: " + model.getPrice();
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText(stringPriceHome);
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.imageView.setOnClickListener(v -> {
if (dbName.equals("Admins")) {
Intent intent = new Intent(DisplaySubCategoriesProductsActivity.this, AdminMaintainProductsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
} else {
Intent intent = new Intent(DisplaySubCategoriesProductsActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
});
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_item_layout, parent, false);
return new ProductViewHolder(view);
}
};
activityDisplaySubCategoriesBinding.recyclerCategorySubCategoriesProductsProductsDisplay.setAdapter(adapter);
adapter.startListening();
}
}
|
package pl.edu.wszib.springhelloworld.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/Header")
public class Header {
@GetMapping
public String test () {
throw new RuntimeException();
// return "index";
}
@ExceptionHandler(RuntimeException.class)
public String exception() {
return "ERROR!!!";
}
}
|
package pro.likada.service;
import pro.likada.model.OrderPaymentType;
import java.util.List;
/**
* Created by Yusupov on 3/20/2017.
*/
public interface OrderPaymentTypeService {
List<OrderPaymentType> getAllOrderPaymentTypes();
OrderPaymentType getOrderTypeByName(String name);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.