text stringlengths 10 2.72M |
|---|
package thsst.calvis.configuration.model.errorlogging;
/**
* Created by Ivan on 1/29/2016.
*/
public enum InstructionInvalid{
invalidFilePath,
invalidFileParamterCount,
invalidFileNegativeCount,
invalidDuplicateFileRegisterDestinationParameter,
invalidFileNoSuchAddressingVariable,
invalidFileExceededParameterCount,
invalidFileLackingParameterCount,
invalidParameterFormat
}
|
/*
* All rights Reserved, Copyright (C) Aisino LIMITED 2018
* FileName: CreateOrder.java
* Version: $Revision$
* Modify record:
* NO. | Date | Name | Content
* 1 | 2018年12月6日 | Aisino)JackWei | original version
*/
package com.aisino.receipt.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.aisino.receipt.bean.Order;
import com.aisino.receipt.bean.OrderItem;
/**
* class name:CreateOrder <BR>
* class description: 根据限额生成订单 <BR>
* Remark: <BR>
* @version 1.00 2018年12月6日
* @author Aisino)weihaohao
*/
public class CreateOrder {
private CreateOrder() {
throw new IllegalStateException("Utility class");
}
//生成订单集合
private static List<Order> orders = new ArrayList<>();
/**
* Method name: createOrder <BR>
* Description: 生成订单工具方法, <BR>
* Remark: <BR>
* @param orderItems 订单商品列表
* @param limit 限额
* @return List<Order><BR>
*/
public static List<Order> createOrder(List<OrderItem> orderItems, double limit){
Logger logger = Logger.getLogger("lavasoft");
logger.setLevel(Level.INFO);
//如果商品为空
if(null==orderItems) {
logger.log(Level.INFO,"订单里面的商品为空!");
return Collections.emptyList();
}
//如果限额小于等于0
if(0>=limit) {
logger.log(Level.INFO,"限额出错,小于等于0!");
return Collections.emptyList();
}
//从大到小排序
OrderItemSort.orderItemSortByValue(orderItems, "DESC");
int i = 0;//下标
int len = orderItems.size();//所有商品数量
//如果商品不含税价格大于限额,生成订单
while(i<len) {
double value = orderItems.get(i).getValue();
if(value >= limit) {
//处理大于限额
opMax(orderItems, limit, i);
i++;
}else {
break;
}
//如果在处理中移除了,一定要i--
if(len!=orderItems.size()) {
len = orderItems.size();
i--;
}
}
//如果商品不含税价格小于限额,生成订单
while(!orderItems.isEmpty()) {
//从大到小排序
OrderItemSort.orderItemSortByValue(orderItems, "DESC");
//处理小于限额
opMin(orderItems, limit, 0);
}
return orders;
}
/**
* Method name: opMax <BR>
* Description: 处理大于限额的情况 <BR>
* Remark: <BR>
* @param orderItems
* @param limit
* @param i
* @return List<OrderItem><BR>
*/
public static void opMax(List<OrderItem> orderItems, double limit, int i) {
//获取第一个值
double value = orderItems.get(i).getValue();
//如果商品不含税价格大于限额
while(value >= limit) {
//生成一个订单
Order order = new Order();
//订单下面的商品列表
List<OrderItem> items = new ArrayList<>();
//获取当前商品
OrderItem item = (OrderItem) orderItems.get(i).clone();//要用克隆,不然赋值的是引用类型会出错!
//设置当前商品为订单最大值
item.setValue(limit);
//设置订单商品,且价格不为0
if(item.getValue() > 0.000001) {
items.add(item);
}
order.setItems(items);
//放到订单列表中
orders.add(order);
//修改当前商品不含税值为减去限额
orderItems.get(i).setValue(DoubleScale2.doubleRound(value - limit,2));
value -= limit;
value = DoubleScale2.doubleRound(value,2);
//如果不含税值减去后为0则要把这条记录移除掉
if(value < 0.000001) {
orderItems.remove(i);
}
}
}
/**
* Method name: opMin <BR>
* Description: 处理小于限额情况 <BR>
* Remark: <BR>
* @param orderItems
* @param limit
* @param i void<BR>
*/
public static void opMin(List<OrderItem> orderItems, double limit, int i) {
int len = orderItems.size();//记录长度
double value = orderItems.get(i).getValue();//获取记录第一个值
double addValue = 0;//中间值,用于记录大于限额的值
Order order = new Order();//创建空订单
List<OrderItem> items = new ArrayList<>();
//如果商品不含税价格小于限额
while(value <= limit && i<len-1) {
//加上下一个金额
i++;
value += orderItems.get(i).getValue();//依次相加记录里面的值
value = DoubleScale2.doubleRound(value, 2);//保留2位小数
//获取当前商品
OrderItem item = (OrderItem) orderItems.get(i-1).clone();//要用克隆,不然赋值的是引用类型会出错!
//设置订单商品,且价格不为0
if(item.getValue() > 0.000001) {
items.add(item);
}
orderItems.remove(i-1);//移除小于限额的。
len = orderItems.size();//重新计算长度
i=0;//从第一个开始
}
addValue = value;
//如果相加的大于限定的
if(addValue>limit) {
OrderItem item = (OrderItem) orderItems.get(0).clone();//要用克隆,不然赋值的是引用类型会出错!
item.setValue(DoubleScale2.doubleRound(limit-(DoubleScale2.doubleRound(addValue-item.getValue(),2)),2));
//设置订单商品,且价格不为0
if(item.getValue() > 0.000001) {
items.add(item);
}
}
//没有找到最末尾
if(len!=1) {
//设置第一个值
orderItems.get(0).setValue(DoubleScale2.doubleRound(value-limit,2));
}else {//找到最末尾
OrderItem item = (OrderItem) orderItems.get(0).clone();//要用克隆,不然赋值的是引用类型会出错!
if(item.getValue() > 0.000001) {//不能为0,为零就不用加进去
items.add(item);
}
orderItems.remove(0);//移除最后一个
}
//设置订单商品
order.setItems(items);
orders.add(order);
}
} |
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TcpClient {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: <host> <port>");
}
int port = Integer.valueOf(args[1]);
Scanner scanner = new Scanner(System.in);
String file;
int size;
System.out.print("Enter <filename> <N>: ");
file = scanner.next();
size = scanner.nextInt();
try{
Socket client = new Socket(args[0], port);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeUTF(file+" "+Integer.toString(size));
DataInputStream in =new DataInputStream(client.getInputStream());
// System.out.println("Server: "+in.readUTF());
byte[] msg = new byte[6];
int rsize = in.read(msg,0,6);
String str = new String(msg, 0, rsize);
if (rsize == 6 && str.equals("SORRY!")) {
System.out.println("Server says that the file does not exist.");
} else {
FileOutputStream fs = new FileOutputStream("./"+file+"1");
fs.write(msg, 0, rsize);
while (in.available() != 0) {
fs.write(in.read());
}
fs.close();
}
in.close();
out.close();
client.close();
} catch(Exception e) {
System.out.println(e.toString());
}
}
} |
package com.jim.multipos.ui.reports.debts;
import android.support.v4.app.Fragment;
import com.jim.multipos.config.scope.PerFragment;
import dagger.Binds;
import dagger.Module;
/**
* Created by Sirojiddin on 20.01.2018.
*/
@Module(
includes = DebtsReportPresenterModule.class
)
public abstract class DebtsReportFragmentModule {
@Binds
@PerFragment
abstract Fragment provideFragment(DebtsReportFragment debtsReportFragment);
@Binds
@PerFragment
abstract DebtsReportView provideDebtsReportView(DebtsReportFragment debtsReportFragment);
}
|
package programmers.level3;
import java.util.*;
class Network {
static int cnt;
public int solution(int n, int[][] computers) {
int answer = 0;
boolean[] visited = new boolean[n];
for (int[] target : computers)
System.out.println(Arrays.toString(target));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (computers[i][j] == 1) {
System.out.println("computers[" + i + "][" + j + "] = " + computers[i][j]);
cnt++;
dfs(computers, visited, i, n);
}
}
}
System.out.println(cnt);
return answer;
}
static void dfs(int[][] adj, boolean[] visited, int node, int n) {
if (visited[node])
return;
visited[node] = true;
System.out.println("visit : " + node);
for (int i = 0; i < n; i++) {
if (adj[node][i] == 1 && !visited[i]) {
dfs(adj, visited, node, n);
}
}
}
} |
package com.example.flutter_module.host;
import android.content.Context;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
public class HJPlatformFactory extends PlatformViewFactory {
/**
* @param createArgsCodec the codec used to decode the args parameter of {@link #create}.
*/
public HJPlatformFactory(MessageCodec<Object> createArgsCodec) {
super(createArgsCodec);
}
@Override
public PlatformView create(Context context, int viewId, Object args) {
return new HJActivity(context);
}
}
|
package com.myapp.exception;
public class TargetAlreadyAttackedException extends RuntimeException {
public TargetAlreadyAttackedException(String message) {
super(message);
}
}
|
package cn.izouxiang.dao;
import cn.izouxiang.domain.CFProject;
import cn.izouxiang.dao.base.BaseMongoDao;
public interface CFProjectDao extends BaseMongoDao<CFProject>{
void addCFProjectRealAmount(String proId, int amount);
void setProjectStatus(String proId, int status);
}
|
package com.top.top.utils.timer;
import java.util.Timer;
import java.util.TimerTask;
/**
* 作者:ProZoom
* 时间:2018/5/2
* 描述:
*/
public class BaseTimerTask extends TimerTask {
private ITimerListener mITimerListener=null;
public BaseTimerTask(ITimerListener mITimerListener) {
this.mITimerListener = mITimerListener;
}
@Override
public void run() {
if(mITimerListener!=null){
mITimerListener.onTimer();
}
}
}
|
package me.themgrf.skooblock.island.permissions;
public class IslandVisitorPermissionSet {
private final boolean ALLOW_BLOCK_PLACING;
private final boolean ALLOW_BLOCK_BREAKING;
private final boolean ALLOW_CONTAINER_ACCESS;
private final boolean ALLOW_WORKBENCH_ACCESS;
private final boolean ALLOW_FURNACE_ACCESS;
private final boolean ALLOW_ENCHANTING;
private final boolean ALLOW_ANVIL_USE;
private final boolean ALLOW_ARMOUR_STAND_USE;
private final boolean ALLOW_BEACON_USE;
private final boolean ALLOW_JUKEBOX_USE;
private final boolean ALLOW_BED_USE;
private final boolean ALLOW_POTION_BREWING;
private final boolean ALLOW_ANIMAL_BREADING;
private final boolean ALLOW_BUCKET_USE;
private final boolean ALLOW_DOOR_USE;
private final boolean ALLOW_GATE_USE;
private final boolean ALLOW_CROP_TRAMPLE;
private final boolean ALLOW_THROWING_EGGS;
private final boolean ALLOW_THROWING_EPEARLS;
private final boolean ALLOW_VEHICLE_USE;
private final boolean ALLOW_HURT_PEACEFUL;
private final boolean ALLOW_HURT_HOSTILE;
private final boolean ALLOW_LEASHING;
private final boolean ALLOW_BUTTON_USE;
private final boolean ALLOW_LEVER_USE;
private final boolean ALLOW_PRESSUREPLATE_USE;
private final boolean ALLOW_PVP;
private final boolean ALLOW_COW_MILKING;
private final boolean ALLOW_SHEEP_SHEARING;
private final boolean ALLOW_VILLAGER_TRADING;
private final boolean ALLOW_ITEM_DROPPING;
private final boolean ALLOW_ITEM_PICKUP;
private final boolean ALLOW_KEEP_EXP_ON_DEATH;
private final boolean ALLOW_KEEP_ITEMS_ON_DEATH;
public IslandVisitorPermissionSet(boolean ALLOW_BLOCK_PLACING,
boolean ALLOW_BLOCK_BREAKING,
boolean ALLOW_CONTAINER_ACCESS,
boolean ALLOW_WORKBENCH_ACCESS,
boolean ALLOW_FURNACE_ACCESS,
boolean ALLOW_ENCHANTING,
boolean ALLOW_ANVIL_USE,
boolean ALLOW_ARMOUR_STAND_USE,
boolean ALLOW_BEACON_USE,
boolean ALLOW_JUKEBOX_USE,
boolean ALLOW_BED_USE,
boolean ALLOW_POTION_BREWING,
boolean ALLOW_ANIMAL_BREADING,
boolean ALLOW_BUCKET_USE,
boolean ALLOW_DOOR_USE,
boolean ALLOW_GATE_USE,
boolean ALLOW_CROP_TRAMPLE,
boolean ALLOW_THROWING_EGGS,
boolean ALLOW_THROWING_EPEARLS,
boolean ALLOW_VEHICLE_USE,
boolean ALLOW_HURT_PEACEFUL,
boolean ALLOW_HURT_HOSTILE,
boolean ALLOW_LEASHING,
boolean ALLOW_BUTTON_USE,
boolean ALLOW_LEVER_USE,
boolean ALLOW_PRESSUREPLATE_USE,
boolean ALLOW_PVP,
boolean ALLOW_COW_MILKING,
boolean ALLOW_SHEEP_SHEARING,
boolean ALLOW_VILLAGER_TRADING,
boolean ALLOW_ITEM_DROPPING,
boolean ALLOW_ITEM_PICKUP,
boolean ALLOW_KEEP_EXP_ON_DEATH,
boolean ALLOW_KEEP_ITEMS_ON_DEATH) {
this.ALLOW_BLOCK_PLACING = ALLOW_BLOCK_PLACING;
this.ALLOW_BLOCK_BREAKING = ALLOW_BLOCK_BREAKING;
this.ALLOW_CONTAINER_ACCESS = ALLOW_CONTAINER_ACCESS;
this.ALLOW_WORKBENCH_ACCESS = ALLOW_WORKBENCH_ACCESS;
this.ALLOW_FURNACE_ACCESS = ALLOW_FURNACE_ACCESS;
this.ALLOW_ENCHANTING = ALLOW_ENCHANTING;
this.ALLOW_ANVIL_USE = ALLOW_ANVIL_USE;
this.ALLOW_ARMOUR_STAND_USE = ALLOW_ARMOUR_STAND_USE;
this.ALLOW_BEACON_USE = ALLOW_BEACON_USE;
this.ALLOW_JUKEBOX_USE = ALLOW_JUKEBOX_USE;
this.ALLOW_BED_USE = ALLOW_BED_USE;
this.ALLOW_POTION_BREWING = ALLOW_POTION_BREWING;
this.ALLOW_ANIMAL_BREADING = ALLOW_ANIMAL_BREADING;
this.ALLOW_BUCKET_USE = ALLOW_BUCKET_USE;
this.ALLOW_DOOR_USE = ALLOW_DOOR_USE;
this.ALLOW_GATE_USE = ALLOW_GATE_USE;
this.ALLOW_CROP_TRAMPLE = ALLOW_CROP_TRAMPLE;
this.ALLOW_THROWING_EGGS = ALLOW_THROWING_EGGS;
this.ALLOW_THROWING_EPEARLS = ALLOW_THROWING_EPEARLS;
this.ALLOW_VEHICLE_USE = ALLOW_VEHICLE_USE;
this.ALLOW_HURT_PEACEFUL = ALLOW_HURT_PEACEFUL;
this.ALLOW_HURT_HOSTILE = ALLOW_HURT_HOSTILE;
this.ALLOW_LEASHING = ALLOW_LEASHING;
this.ALLOW_BUTTON_USE = ALLOW_BUTTON_USE;
this.ALLOW_LEVER_USE = ALLOW_LEVER_USE;
this.ALLOW_PRESSUREPLATE_USE = ALLOW_PRESSUREPLATE_USE;
this.ALLOW_PVP = ALLOW_PVP;
this.ALLOW_COW_MILKING = ALLOW_COW_MILKING;
this.ALLOW_SHEEP_SHEARING = ALLOW_SHEEP_SHEARING;
this.ALLOW_VILLAGER_TRADING = ALLOW_VILLAGER_TRADING;
this.ALLOW_ITEM_DROPPING = ALLOW_ITEM_DROPPING;
this.ALLOW_ITEM_PICKUP = ALLOW_ITEM_PICKUP;
this.ALLOW_KEEP_EXP_ON_DEATH = ALLOW_KEEP_EXP_ON_DEATH;
this.ALLOW_KEEP_ITEMS_ON_DEATH = ALLOW_KEEP_ITEMS_ON_DEATH;
}
public boolean isALLOW_BLOCK_PLACING() {
return ALLOW_BLOCK_PLACING;
}
public boolean isALLOW_BLOCK_BREAKING() {
return ALLOW_BLOCK_BREAKING;
}
public boolean isALLOW_CONTAINER_ACCESS() {
return ALLOW_CONTAINER_ACCESS;
}
public boolean isALLOW_WORKBENCH_ACCESS() {
return ALLOW_WORKBENCH_ACCESS;
}
public boolean isALLOW_FURNACE_ACCESS() {
return ALLOW_FURNACE_ACCESS;
}
public boolean isALLOW_ENCHANTING() {
return ALLOW_ENCHANTING;
}
public boolean isALLOW_ANVIL_USE() {
return ALLOW_ANVIL_USE;
}
public boolean isALLOW_ARMOUR_STAND_USE() {
return ALLOW_ARMOUR_STAND_USE;
}
public boolean isALLOW_BEACON_USE() {
return ALLOW_BEACON_USE;
}
public boolean isALLOW_JUKEBOX_USE() {
return ALLOW_JUKEBOX_USE;
}
public boolean isALLOW_BED_USE() {
return ALLOW_BED_USE;
}
public boolean isALLOW_POTION_BREWING() {
return ALLOW_POTION_BREWING;
}
public boolean isALLOW_ANIMAL_BREADING() {
return ALLOW_ANIMAL_BREADING;
}
public boolean isALLOW_BUCKET_USE() {
return ALLOW_BUCKET_USE;
}
public boolean isALLOW_DOOR_USE() {
return ALLOW_DOOR_USE;
}
public boolean isALLOW_GATE_USE() {
return ALLOW_GATE_USE;
}
public boolean isALLOW_CROP_TRAMPLE() {
return ALLOW_CROP_TRAMPLE;
}
public boolean isALLOW_THROWING_EGGS() {
return ALLOW_THROWING_EGGS;
}
public boolean isALLOW_THROWING_EPEARLS() {
return ALLOW_THROWING_EPEARLS;
}
public boolean isALLOW_VEHICLE_USE() {
return ALLOW_VEHICLE_USE;
}
public boolean isALLOW_HURT_PEACEFUL() {
return ALLOW_HURT_PEACEFUL;
}
public boolean isALLOW_HURT_HOSTILE() {
return ALLOW_HURT_HOSTILE;
}
public boolean isALLOW_LEASHING() {
return ALLOW_LEASHING;
}
public boolean isALLOW_BUTTON_USE() {
return ALLOW_BUTTON_USE;
}
public boolean isALLOW_LEVER_USE() {
return ALLOW_LEVER_USE;
}
public boolean isALLOW_PRESSUREPLATE_USE() {
return ALLOW_PRESSUREPLATE_USE;
}
public boolean isALLOW_PVP() {
return ALLOW_PVP;
}
public boolean isALLOW_COW_MILKING() {
return ALLOW_COW_MILKING;
}
public boolean isALLOW_SHEEP_SHEARING() {
return ALLOW_SHEEP_SHEARING;
}
public boolean isALLOW_VILLAGER_TRADING() {
return ALLOW_VILLAGER_TRADING;
}
public boolean isALLOW_ITEM_DROPPING() {
return ALLOW_ITEM_DROPPING;
}
public boolean isALLOW_ITEM_PICKUP() {
return ALLOW_ITEM_PICKUP;
}
public boolean isALLOW_KEEP_EXP_ON_DEATH() {
return ALLOW_KEEP_EXP_ON_DEATH;
}
public boolean isALLOW_KEEP_ITEMS_ON_DEATH() {
return ALLOW_KEEP_ITEMS_ON_DEATH;
}
}
|
package kr.or.ddit.basic;
import javax.swing.*;
/*
* 컴퓨터와 가위 바위 보를 진행하는 프로그램을 작성하시오.
*
* 컴퓨터의 가위 바위 보는 난수를 이용하여 구하고
* 사용자의 가위 바위 보는 showInputDialog()메서드를 이용하여 입력받는다.
*
* 입력시간은 5초로 제한하고 카운트다운을 진행한다.
* 5초동안 입력이 없으면 진 것으로 처리한다.
*
* 5초 안에 입력이 완료되면 승패를 출력한다.
*
* 예시)
* == 결과 ==
* 컴퓨터 : 가위
* 당 신 : 바위
* 결 과 : 당신이 이겼습니다.
*
*/
public class T07_ThreadGame {
public static boolean inputCheck = false;
public static void main(String[] args) {
Thread th1 = new gameDataInput();
Thread th2 = new gameCountDown();
th1.start();
th2.start();
}
}
/**
* 데이터 입력을 위한 메서드
*/
class gameDataInput extends Thread {
@Override
public void run() {
String str = JOptionPane.showInputDialog("당신의 선택은?");
//입력이 완료되면 inputCheck변수를 true로 변경한다.
T07_ThreadGame.inputCheck = true;
int user = 0;
switch (str) {
case "가위":
user = 1;
break;
case "바위":
user = 2;
break;
case "보":
user = 3;
break;
}
int num = (int)(Math.random()*3 +1);
String com = null;
switch (num) {
case 1:
com = "가위";
break;
case 2:
com = "바위";
break;
case 3:
com = "보";
break;
}
System.out.println("== 결과 ==");
System.out.println("컴퓨터 : "+ com);
System.out.println("당 신 : "+ str);
if((user - num) == 1 || (user - num) == -2) {
System.out.println("당신이 이겼습니다.");
} else if ((user - num) == -1 || (user - num) == 2) {
System.out.println("당신이 졌습니다.");
} else {
System.out.println("비겼습니다.");
}
}
}
class gameCountDown extends Thread {
@Override
public void run() {
for (int i = 5; i >= 1; i--) {
//입력이 완료되었는지 여부를 검사하고 입력이 완료되면 run()메서드를 종료시킨다. 즉 현재 쓰레드를 종료시킨다.
if(T07_ThreadGame.inputCheck) {
return;
}
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//10초가 경과되었는데도 입력이 없으면 프로그램을 종료한다.
System.out.println("5초가 지났습니다.\r\n당신의 패배입니다.");
System.exit(0);
}
}
|
package com.tencent.mm.plugin.offline.ui;
import com.tencent.mm.g.a.ks;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
class WalletOfflineCoinPurseUI$35 extends c<ks> {
final /* synthetic */ WalletOfflineCoinPurseUI lMe;
WalletOfflineCoinPurseUI$35(WalletOfflineCoinPurseUI walletOfflineCoinPurseUI) {
this.lMe = walletOfflineCoinPurseUI;
this.sFo = ks.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
if (((ks) bVar).bVf.aeo != hashCode()) {
x.i("MicroMsg.WalletOfflineCoinPurseUI", "has create a new ui, finish self");
this.lMe.finish();
}
return false;
}
}
|
package com.tencent.mm.plugin.backup.backupmoveui;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.R;
import com.tencent.mm.bg.d;
import com.tencent.mm.sdk.platformtools.w;
class BackupUI$2 implements OnClickListener {
final /* synthetic */ BackupUI gVH;
BackupUI$2(BackupUI backupUI) {
this.gVH = backupUI;
}
public final void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("title", this.gVH.getString(R.l.backup_pc_doc_title));
intent.putExtra("rawUrl", this.gVH.getString(R.l.backup_pc_tip_doc, new Object[]{w.chP()}));
intent.putExtra("showShare", false);
intent.putExtra("neverGetA8Key", true);
d.b(this.gVH, "webview", ".ui.tools.WebViewUI", intent);
}
}
|
package com.lec.ex09lib;
//new Book("890ㄱ-102나","자바","홍길동")
public class Book implements ILendable {
private String bookNo; // 책청구번호ex. 890 ㄱ-102나
private String bookTitle; // 책제목 ex.자바
private String writer; // 저자
private String borrower; // 대출인 (입력)
private String checkOutDate; // 대출일(입력)
private byte state;
public Book() {
} // 디폴트 생성자
public Book(String bookNo, String bookTitle, String writer) {
this.bookNo = bookNo;
this.bookTitle = bookTitle;
this.writer = writer;
// borrower = null; checkOutDate = null;
state = STATE_NORMAL; // ILendable2꺼 (implements ILendable2에서가져온것)
}
// Book b = new Book("890ㄱ-102나","자바","홍길동")
// b.checkOut("신길동","201209");
@Override
public void checkOut(String borrower, String checkOutDate) {
if (state != STATE_NORMAL) {
System.out.println("대출중인 도서입니다");
return; // 아무값없이 그냥 나를 호출한 곳으로 감; return 0은 안됨 왜냐하면 지금은 void //!throw
}
// 대출처리 로직
this.borrower = borrower;
this.checkOutDate = checkOutDate;
state = STATE_BORROWED;
// "자바" 도서가 대출되었습니다
System.out.println(" \" " + bookTitle + "도서가 대출되었습니다"); // \"는 쌍따움표를 string으로 인식
}
// b.checkIn()
@Override
public void checkIn() { // !throw 추가
if (state != STATE_BORROWED) {
System.out.println("대출 중인 도서가 아닙니다.이상합니다."); // !throw 예외발생
return;
}
// 반납 처리 로직
borrower = null;
checkOutDate = null; // !날짜 비교 14일 지나면 연체료 (어제 예제), 1일 100씩 연체료 , Y를 눌러야 연체료 됨//Y를 눌러야 반납처리됨.
// scanner변수 필요
state = STATE_NORMAL;
// "자바"도서가 반납처리 되었습니다.
System.out.println("\"" + bookTitle + "\"도서가 반납되었습니다");
}
// b.printState() -> 자바 , 홍길동저 - 대출가능(대출중)
@Override
public void printState() {
if (state == STATE_NORMAL) {
System.out.printf("%s, %s저 - 대출가능\n", bookTitle, writer);
} else if (state == STATE_BORROWED) {
System.out.printf("%s,%s저 - 대출중 \n", bookTitle, writer);
} else {
System.out.printf("%s,%s - 유령상태입니다\n", bookTitle, writer);
}
// String msg = bookTitle + ","+writer+ "-";
// msg += state == STATE_NORMAL? "대출가능":"대출중";
// System.out.println(msg);
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
public String getWriter() {
return writer;
}
public String getBorrower() {
return borrower;
}
public String getCheckOutDate() {
return checkOutDate;
}
public byte getState() {
return state;
}
public String getBookNo() {
return bookNo;
}
public void setBookNo(String bookNo) {
this.bookNo = bookNo;
}
}
|
package es.utils.mapper.utils;
import es.utils.mapper.Mapper;
import es.utils.mapper.annotation.AliasNames;
import es.utils.mapper.converter.AbstractConverter;
import es.utils.mapper.holder.FieldHolder;
import es.utils.mapper.impl.object.DirectMapper;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.regex.Pattern;
/**
* This class contains a set of method used in the mapping creation.
* @author eschoysman
*/
@Slf4j
public class MapperUtil {
private static final Pattern PATTERN = Pattern.compile(".+? extends ");
/**
* This method returns the specific field of input class. If no field is found,
* an attempt to get the field through the {@code AliasNames} annotation is done.
* @param <T> type of the class
* @param type The class you're searching the field into.
* @param fieldName The field you're searching for.
* @return The Field found. If no result is found, null is returned.
* @see AliasNames
*/
public static <T> Field getField(Class<T> type, String fieldName) {
Objects.requireNonNull(type);
Objects.requireNonNull(fieldName);
Field result = getDeclaredField(type,fieldName);
if(result==null) result = getFieldOfClass(type,fieldName);
return result;
}
/**
* This method returns the specific field of input class. If no field is found,
* an attempt to get the field through the {@code AliasNames} annotation is done.
* @param <T> type of the class
* @param type The class you're searching the field into.
* @param fieldName The field you're searching for.
* @param mapper the Mapper instance used to find the field with the fieldName as annotation
* @return The Field found. If no result is found, null is returned.
* @see AliasNames
*/
public static <T> Field getField(Class<T> type, String fieldName, Mapper mapper) {
Field field = getField(type,fieldName);
if(field==null && mapper!=null) {
field = mapper.getFieldsHolderFromCache(type).values().stream()
.filter(fieldHolder->fieldHolder.getAllNames().contains(fieldName))
.map(FieldHolder::getField)
.findFirst().orElse(null);
}
return field;
}
/**
* This method returns all fields from given class, private and public ones.
* @param type The class you should inspect.
* @return A Set of Fields of the given class.
*/
public static Set<Field> getAllFields(Class<?> type) {
Field[] fields1 = type.getFields();
Field[] fields2 = type.getDeclaredFields();
Set<Field> fields = new LinkedHashSet<>(fields1.length+fields2.length);
for(Field f : fields1) fields.add(f);
for(Field f : fields2) fields.add(f);
return fields;
}
/**
* This method returns the generic class of an input Type with generic. In case of extension,
* the superclass Type is returned.
* @param <TYPE> generic type returned
* @param input The type you're trying to get the class of.
* @return the Class of the given Type. If no generic type is defined, null is returned.
*/
public static <TYPE> Class<TYPE> getGenericType(Type input) {
if(input!=null && input instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType)input;
Type[] argTypes = paramType.getActualTypeArguments();
if(argTypes.length==1) {
String typeName = argTypes[0].getTypeName();
if(PATTERN.matcher(typeName).find()) {
int startIndex = typeName.indexOf("extends")+8;
int endIndex = typeName.indexOf("<");
typeName = typeName.substring(startIndex,endIndex==-1? typeName.length() : endIndex);
}
try {
@SuppressWarnings("unchecked")
Class<TYPE> resultClass = (Class<TYPE>)Class.forName(typeName);
return resultClass;
} catch (Exception e) {}
}
}
return null;
}
/**
* Create a mapping using the implementation present in the sub-class of the given {@link AbstractConverter} and {@code mapper} instance.
* @param converter the type of the custom {@code AbstractConverter} to use
* @param mapper the {@code mapper} instance needed for instantiate the {@code AbstractConverter}
* @param <FROM> the type of the origin object
* @param <TO> the type of the destination object
* @return the newly created mapping if successfully instantiate, otherwise prints a warning and returns {@code null}.
*/
public static <FROM,TO> DirectMapper<FROM,TO> createFromConverter(Class<? extends AbstractConverter<FROM,TO>> converter, Mapper mapper) {
DirectMapper<FROM,TO> result = null;
try {
result = (DirectMapper<FROM,TO>)converter.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
try {
result = (DirectMapper<FROM,TO>)converter.getConstructor(Mapper.class).newInstance(mapper);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) {
log.warn("WARNING - The converter for "+converter+" does not have a empty public contructor or a constructor accepting a Mapper instance; the converter is ignored.");
}
}
return result;
}
private static Map<Class<?>,Class<?>> wrapConvert = new HashMap<Class<?>,Class<?>>() {{
put(byte.class,Byte.class);
put(short.class,Short.class);
put(int.class,Integer.class);
put(long.class,Long.class);
put(float.class,Float.class);
put(double.class,Double.class);
put(boolean.class,Boolean.class);
put(char.class,Character.class);
}};
public static <T> Class<T> getWrapType(Class<T> type) {
@SuppressWarnings("unchecked")
Class<T> wrapType = (Class<T>) wrapConvert.getOrDefault(type,type);
return wrapType;
}
private static <T> Field getDeclaredField(Class<T> type, String fieldName) {
try {
return type.getDeclaredField(fieldName);
} catch (NoSuchFieldException | SecurityException e) {
return null;
}
}
private static <T> Field getFieldOfClass(Class<T> type, String fieldName) {
try {
return type.getField(fieldName);
} catch (NoSuchFieldException | SecurityException e) {
return null;
}
}
}
|
package com.noteshare.common.filter;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final class RequestWrapper extends HttpServletRequestWrapper {
@SuppressWarnings("unused")
private String apostrophe = "'";
/** 可能存在风险,会过滤掉一些特殊字符 */
@Override
public Object getAttribute(String name) {
Object obj = super.getAttribute(name);
if (null != obj && obj instanceof String) {
obj = cleanXSS((String) obj);
}
return obj;
}
public RequestWrapper(HttpServletRequest paramHttpServletRequest) {
super(paramHttpServletRequest);
}
public RequestWrapper(HttpServletRequest paramHttpServletRequest,
String paramString) {
super(paramHttpServletRequest);
this.apostrophe = paramString;
}
public String[] getParameterValues(String paramString) {
String[] arrayOfString1 = super.getParameterValues(paramString);
if (arrayOfString1 == null)
return null;
int i = arrayOfString1.length;
String[] arrayOfString2 = new String[i];
for (int j = 0; j < i; j++)
arrayOfString2[j] = cleanXSS(arrayOfString1[j]);
return arrayOfString2;
}
public String getParameter(String paramString) {
String str = super.getParameter(paramString);
if (str == null)
return null;
return cleanXSS(str);
}
public String getHeader(String paramString) {
String str = super.getHeader(paramString);
if (str == null)
return null;
return cleanXSS(str);
}
private String cleanXSS(String paramString) {
if (paramString == null){
return "";
//解决因为替换<导致pageoffice展示问题
}else if(paramString.contains("object") && paramString.contains("OCX-Version")){
return paramString;
}else{
String str = paramString;
str = str.replaceAll("", "");
Pattern localPattern = Pattern.compile("<script>(.*?)</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\'(.*?)\\'", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("<script(.*?)>", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("eval\\((.*?)\\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("expression\\((.*?)\\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("javascript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("vbscript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("onload(.*?)=", 42);
str = localPattern.matcher(str).replaceAll("");
str = str.replaceAll("alert\\(", "(");
// str = str.replaceAll("\\(", "(").replaceAll("\\)", ")");
//这个分号暂时不要加,视频会商的菜单文件中包含‘替换掉会出问题
//str = str.replaceAll("'", this.apostrophe);
//会引起页面报错,先注释。/pages/hjyj/common/bg/ajax.jsp
//str = str.replaceAll("\"", "1");
str = str.replaceAll("<", "<").replaceAll(">", ">");
return str;
}
}
} |
package medicalcentermanagement;
import com.mahadihasan.mc.gui.LogIn;
import javax.swing.UIManager;
/**
*
* @author MAHADI HASAN NAHID
*/
public class MedicalCenterManagement {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}catch(Exception exception) {
}
LogIn logIn = new LogIn();
}
}
|
package com.xworkz.rental.utility.response;
import org.springframework.http.HttpStatus;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Response {
private String statusCode; // create status integer for user response
private String message; // create message in String for give the user message
private Object object;
private HttpStatus status;
// private Object data;
public Response(String message, String statusCode) {
this.statusCode = statusCode;
this.message = message;
}
public Response(String message, HttpStatus status) {
this.status = status;
this.message = message;
}
public Response(String message, String statusCode, Object object) {
this.statusCode = statusCode;
this.message = message;
this.object = object;
}
}
|
package org.springframework.fom;
/**
*
* @author shanhm1991@163.com
*
*/
public enum State {
/**
* 初始化
*/
INITED("images/inited.png", "inited"),
/**
* 正在运行
*/
RUNNING("images/running.png", "running"),
/**
* 等待定时周期
*/
SLEEPING("images/sleeping.png", "waiting for next time"),
/**
* 正在停止
*/
STOPPING("images/stopping.png", "stopping"),
/**
* 已经停止
*/
STOPPED("images/stopped.png", "stopped");
private String src;
private String title;
State(String src, String title){
this.src = src;
this.title = title;
}
public String src(){
return src;
}
public String title(){
return title;
}
}
|
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
//package Homework_Day3;
//import Homework_Day3.IntUtil;
public class LetterThruSubRoutine {
private static final IntUtil u = new IntUtil();
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Length.java");
testbed() ;
testbed1() ;
}
private static int length_easy(int [] s, int x) {
int l = 0 ;
int gx = x ;
while (true) {
if (s[x] == gx) {
return l ;
}
x = s[x] ;
++l ;
}
}
/*
* With subroutine
*/
private static int length(int [] s, int x) {
return subLength(s,x,x);
}
private static int subLength(int[] s,int n,int a){
if(s[a]==n){
return 0;
}
return subLength(s,n,s[a])+1;
}
public static void testbed() {
int s[] = {5,1,0,4,2,3} ;
int y = length_easy(s,3) ;
System.out.println("length_easy y = " + y);
u.myassert(y == 4) ;
int b[] = {5,1,0,4,2,3} ;
int x = length(s,3) ;
System.out.println("length x = " + x);
u.myassert(x == y) ;
for (int i = 0; i < s.length; ++i) {
u.myassert(s[i] == b[i]);
}
System.out.println("Assert passed");
}
public static void testbed1() {
int s[] = {5,1,0,4,2,3} ;
int b[] = {5,1,0,4,2,3} ;
int l = s.length ;
for (int j = 0; j < l ; ++j) {
int y = length_easy(s,j) ;
System.out.println("length_easy y = " + y);
int x = length(s,j) ;
System.out.println("length x = " + x);
u.myassert(x == y) ;
for (int i = 0; i < s.length; ++i) {
u.myassert(s[i] == b[i]);
}
System.out.println("Assert passed");
}
}
}
|
package com.dvilson.gadsleaderboard;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import com.dvilson.gadsleaderboard.models.User;
public class LearningHoursRecyclerAdapter extends RecyclerView.Adapter <LearningHoursRecyclerAdapter.LearningHoursViewHolder> {
ArrayList<User> mUsers;
Context mContext;
public LearningHoursRecyclerAdapter(Context context,ArrayList<User> users) {
mUsers = users;
mContext = context;
}
@NonNull
@Override
public LearningHoursViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_hours,parent,false);
return new LearningHoursViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull LearningHoursViewHolder holder, int position) {
holder.name.setText(mUsers.get(position).getName());
holder.hoursCountry.setText(mUsers.get(position).getHours()+" learning hours"+", "+mUsers.get(position).getCountry());
}
@Override
public int getItemCount() {
return mUsers.size();
}
public class LearningHoursViewHolder extends RecyclerView.ViewHolder{
ImageView mImageBadge;
TextView name ;
TextView hoursCountry;
public LearningHoursViewHolder(@NonNull View itemView) {
super(itemView);
mImageBadge = itemView.findViewById(R.id.image_badge);
name = itemView.findViewById(R.id.tv_name_hours);
hoursCountry = itemView.findViewById(R.id.tv_hours_country);
}
}
}
|
package com.xiaodao.system.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.xiaodao.system.mapper.SysMenuMapper;
import com.xiaodao.system.service.ISysMenuService;
import com.xiaodao.admin.entity.SysMenu;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
/**
* @description ISysMenu Service层
* @author xiaodao
* @since jdk1.8
*/
@Service
public class SysMenuServiceImpl implements ISysMenuService{
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
public int insert(SysMenu sysMenu) {
return sysMenuMapper.insert(sysMenu);
}
@Override
public int insertSelective(SysMenu sysMenu) {
return sysMenuMapper.insertSelective(sysMenu);
}
@Override
public int batchInsert(List<SysMenu> list) {
return sysMenuMapper.batchInsert(list);
}
@Override
public int batchInsertSelective(List<SysMenu> list) {
return sysMenuMapper.batchInsertSelective(list);
}
@Override
public int updateByPrimaryKey(SysMenu sysMenu) {
return sysMenuMapper.updateByPrimaryKey(sysMenu);
}
@Override
public int updateSelectiveByPrimaryKey(SysMenu sysMenu) {
return sysMenuMapper.updateSelectiveByPrimaryKey(sysMenu);
}
@Override
public int batchUpdate(List<SysMenu> list) {
return sysMenuMapper.batchUpdate(list);
}
@Override
public int batchUpdateSelective(List<SysMenu> list) {
return sysMenuMapper.batchUpdateSelective(list);
}
@Override
public int upsert(SysMenu sysMenu) {
return sysMenuMapper.upsert(sysMenu);
}
@Override
public int upsertSelective(SysMenu sysMenu) {
return sysMenuMapper.upsertSelective(sysMenu);
}
@Override
public int batchUpsert(List<SysMenu> list) {
return sysMenuMapper.batchUpsert(list);
}
@Override
public int batchUpsertSelective(List<SysMenu> list) {
return sysMenuMapper.batchUpsertSelective(list);
}
@Override
public int deleteByPrimaryKey(Long menuId) {
return sysMenuMapper.deleteByPrimaryKey(menuId);
}
@Override
public int deleteBatchByPrimaryKeys(List<Long> list) {
return sysMenuMapper.deleteBatchByPrimaryKeys(list);
}
@Override
public int delete(SysMenu sysMenu) {
return sysMenuMapper.delete(sysMenu);
}
@Override
public SysMenu queryByPrimaryKey(Long menuId) {
return sysMenuMapper.queryByPrimaryKey(menuId);
}
@Override
public List<SysMenu> queryBatchPrimaryKeys(List<Long> list) {
return sysMenuMapper.queryBatchPrimaryKeys(list);
}
@Override
public SysMenu queryOne(SysMenu sysMenu) {
return sysMenuMapper.queryOne(sysMenu);
}
@Override
public List<SysMenu> queryByCondition(SysMenu sysMenu) {
return sysMenuMapper.queryByCondition(sysMenu);
}
@Override
public List<SysMenu> queryFuzzy(SysMenu sysMenu) {
return sysMenuMapper.queryFuzzy(sysMenu);
}
@Override
public List<SysMenu> queryByLikeCondition(SysMenu sysMenu) {
return sysMenuMapper.queryByLikeCondition(sysMenu);
}
@Override
public int queryCount(SysMenu sysMenu) {
return sysMenuMapper.queryCount(sysMenu);
}
@Override
public List<Map<String, Object>> statisticsGroup(SysMenu sysMenu) {
return sysMenuMapper.statisticsGroup(sysMenu);
}
@Override
public List<Map<String, Object>> statisticsGroupByDay(SysMenu sysMenu) {
return sysMenuMapper.statisticsGroupByDay(sysMenu);
}
@Override
public List<Map<String, Object>> statisticsGroupByMonth(SysMenu sysMenu) {
return sysMenuMapper.statisticsGroupByMonth(sysMenu);
}
@Override
public List<Map<String, Object>> statisticsGroupByYear(SysMenu sysMenu) {
return sysMenuMapper.statisticsGroupByYear(sysMenu);
}
@Override
public List<SysMenu> selectMenuAll() {
return sysMenuMapper.selectMenuAll();
}
@Override
public List<SysMenu> selectMenuNormalAll() {
return sysMenuMapper.selectMenuNormalAll();
}
@Override
public List<SysMenu> selectMenusByUserId(Long userId) {
return sysMenuMapper.selectMenusByUserId(userId);
}
@Override
public List<String> selectPermsByUserId(Long userId) {
return sysMenuMapper.selectPermsByUserId(userId);
}
@Override
public List<Long> selectMenuIdsByRoleId(Long roleId) {
return sysMenuMapper.selectMenuIdsByRoleId(roleId);
}
@Override
public List<String> selectMenuTree(Long roleId) {
return sysMenuMapper.selectMenuTree(roleId);
}
} |
package com.supconit.kqfx.web.fxzf.msg.entities;
import java.util.Date;
import hc.base.domains.OrderPart;
/**
* 告警信息实体类
* @author gaoshuo
*
*/
public class Msg extends hc.base.domains.StringId implements hc.base.domains.Orderable {
/**
*
*/
private static final long serialVersionUID = 698242157940644050L;
@Override
public OrderPart[] getOrderParts() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setOrderParts(OrderPart[] orderParts) {
// TODO Auto-generated method stub
}
/**
* 用户ID
*/
private String userId;
/**
* 公告或告警信息关联ID
*/
private String pid;
/**
* 公告或告警标志 flag:0告警 1公告
*/
private String flag;
/**
* 公告或告警有效期
*/
private Date usefuldateTime;
/**
* 公告或告警内容
*/
private String content;
/**
* 机构ID用于获取回应的用户信息
*/
private String jgid;
/**
* 告警或公告时间
*/
private Date updateTime;
/**
* 是否显示信息
*/
private String msgflag;
public String getMsgflag() {
return msgflag;
}
public void setMsgflag(String msgflag) {
this.msgflag = msgflag;
}
public Date getUsefuldateTime() {
return usefuldateTime;
}
public void setUsefuldateTime(Date usefuldateTime) {
this.usefuldateTime = usefuldateTime;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getJgid() {
return jgid;
}
public void setJgid(String jgid) {
this.jgid = jgid;
}
}
|
package com.sample.school.app;
import java.util.List;
import com.sample.school.service.SchoolService;
import com.sample.school.util.KeyboardUtil;
import com.sample.school.vo.Course;
import com.sample.school.vo.Dept;
import com.sample.school.vo.Prof;
import com.sample.school.vo.Reg;
import com.sample.school.vo.Student;
import com.sample.school.vo.Subject;
public class SchoolApp {
public static void main(String[] args) throws Exception {
SchoolService service = new SchoolService();
while(true) {
System.out.println("학사관리 프로그램");
System.out.println("----------------------------------------");
System.out.println("1.교수 2.학생");
System.out.println("----------------------------------------");
System.out.print("사용자를 선택하세요: ");
int menuNo = KeyboardUtil.nextInt();
if (menuNo == 0) {
System.out.println("### 프로그램 종료");
KeyboardUtil.close();
break;
} else if (menuNo == 1) {
System.out.println("학사관리 프로그램(교수용)");
System.out.println("----------------------------------------");
System.out.println("1.과목조회 2.과목등록");
System.out.println("3.과정목록조회 4.과정상세조회 5.과정등록");
System.out.println("----------------------------------------");
System.out.print("메뉴를 선택하세요: ");
int profMenuNo = KeyboardUtil.nextInt();
if (profMenuNo == 1) {
System.out.println("과목 목록 조회");
List<Subject> allSubjects = service.getAllSubjects();
if (allSubjects.isEmpty()) {
System.out.println("!!! 과목 목록 조회 과정에서 오류가 발생했습니다.");
} else {
System.out.println("### 과목 목록 조회");
System.out.println("과목번호\t과목명\t학과번호\t학과명\t등록일");
System.out.println("----------------------------------------");
for (Subject subject : allSubjects) {
System.out.print(subject.getNo() + "\t");
System.out.print(subject.getTitle() + "\t");
System.out.print(subject.getDept().getNo() + "\t");
System.out.print(subject.getDept().getName() + "\t");
System.out.print(subject.getRegisteredDate() + "\n");
}
System.out.println("----------------------------------------");
}
} else if (profMenuNo == 2) {
System.out.println("과목등록");
System.out.print("과목명을 입력하세요: ");
String title = KeyboardUtil.nextString();
System.out.print("학과번호를 입력하세요: ");
int deptNo = KeyboardUtil.nextInt();
Subject subject = new Subject();
Dept dept = new Dept();
dept.setNo(deptNo);
subject.setTitle(title);
subject.setDept(dept);
boolean isSuccess = service.addSubject(subject);
if (isSuccess) {
System.out.println("### 과목등록이 완료되었습니다.");
} else {
System.out.println("!!! 과목등록 과정에서 오류가 발생했습니다.");
}
System.out.println("----------------------------------------");
} else if (profMenuNo == 3) {
System.out.println("과정목록조회");
List<Course> allCourses = service.getAllCourses();
if (allCourses.isEmpty()) {
System.out.println("!!! 과정목록조회 과정에서 오류가 발생했습니다.");
} else {
System.out.println("### 과정목록조회");
System.out.println("과정번호\t과정명\t학과명\t담당교수\t마감여부");
System.out.println("----------------------------------------");
for (Course course : allCourses) {
String registerable = "마감전";
if (!course.isRegisterable()) {
registerable = "마감완료";
}
System.out.print(course.getNo() + "\t");
System.out.print(course.getTitle() + "\t");
System.out.print(course.getDept().getName() + "\t");
System.out.print(course.getProf().getName() + "\t");
System.out.print(registerable + "\n");
}
}
System.out.println("----------------------------------------");
} else if (profMenuNo == 4) {
System.out.println("과정상세조회");
System.out.print("과정번호를 입력하세요: ");
int courseNo = KeyboardUtil.nextInt();
Course course = service.getCourseByNo(courseNo);
if (course == null) {
System.out.println("!!! 과정상세조회 과정에서 오류가 발생했습니다.");
} else {
System.out.println("### 과정상세조회");
String registerable = "마감전";
if (!course.isRegisterable()) {
registerable = "마감완료";
}
System.out.println("----------------------------------------");
System.out.println("과정번호: " + course.getNo());
System.out.println("과정명 : " + course.getTitle());
System.out.println("과목명 : " + course.getSubject().getTitle());
System.out.println("개설학과: " + course.getDept().getName());
System.out.println("담당교수: " + course.getProf().getName());
System.out.println("마감여부:" + registerable);
System.out.println("잔여인원:" + course.getStudentCount());
System.out.println("등록일자: " + course.getRegisteredDate());
}
System.out.println("----------------------------------------");
} else if (profMenuNo == 5) {
System.out.println("과정등록");
System.out.print("과정명을 입력하세요: ");
String title = KeyboardUtil.nextString();
System.out.print("학과번호를 입력하세요: ");
int deptNo = KeyboardUtil.nextInt();
System.out.print("교수번호를 입력하세요: ");
int profNo = KeyboardUtil.nextInt();
System.out.print("과목번호를 입력하세요: ");
int subjectNo = KeyboardUtil.nextInt();
Dept dept = new Dept();
dept.setNo(deptNo);
Prof prof = new Prof();
prof.setNo(profNo);
Subject subject = new Subject();
subject.setNo(subjectNo);
Course course = new Course();
course.setTitle(title);
course.setDept(dept);
course.setProf(prof);
course.setSubject(subject);
boolean isSuccess = service.addCourse(course);
if (isSuccess) {
System.out.println("### 과정등록이 성공적으로 완료되었습니다.");
} else {
System.out.println("!!! 과정등록과정에서 오류가 발생했습니다.");
}
}
System.out.println("----------------------------------------");
} else if (menuNo == 2) {
System.out.println("학사관리 프로그램(학생용)");
System.out.println("----------------------------------------");
System.out.println("1.학과과정조회 2.수강신청");
System.out.println("3.신청내역조회 4.신청취소");
System.out.println("----------------------------------------");
System.out.print("메뉴를 선택하세요: ");
int studentMenuNo = KeyboardUtil.nextInt();
if (studentMenuNo == 1) {
System.out.println("학과과정조회");
System.out.print("학과번호를 입력하세요: ");
int deptNo = KeyboardUtil.nextInt();
List<Course> deptCourses = service.getCoursesByDeptNo(deptNo);
if (deptCourses.isEmpty()) {
System.out.println("!!! 학과과정 조회 과정에서 오류가 발생했습니다.");
} else {
System.out.println("### 학과과정 조회 결과");
System.out.println("과정번호\t과정명\t담당교수\t잔여인원\t마감여부");
for (Course course : deptCourses) {
String registerable = "마감전";
if (!course.isRegisterable()) {
registerable = "마감완료";
}
System.out.print(course.getNo() + "\t");
System.out.print(course.getTitle() + "\t");
System.out.print(course.getProf().getName() + "\t");
System.out.print(course.getStudentCount() + "\t");
System.out.print(registerable + "\n");
}
}
System.out.println("----------------------------------------");
} else if (studentMenuNo == 2) {
System.out.println("수강신청");
System.out.print("과정번호를 입력하세요: ");
int courseNo = KeyboardUtil.nextInt();
System.out.print("학번을 입력하세요: ");
int studentNo = KeyboardUtil.nextInt();
Course course = new Course();
course.setNo(courseNo);
Student student = new Student();
student.setNo(studentNo);
Reg reg = new Reg();
reg.setCourse(course);
reg.setStudent(student);
boolean isSuccess = service.addReg(reg);
if (isSuccess) {
System.out.println("### 수강신청이 정상적으로 완료되었습니다.");
} else {
System.out.println("!!! 수강신청 과정에서 오류가 발생했습니다.");
}
System.out.println("----------------------------------------");
} else if (studentMenuNo == 3) {
System.out.println("신청내역조회");
System.out.print("학번을 입력하세요: ");
int studentNo = KeyboardUtil.nextInt();
List<Reg> myRegs = service.getMyRegs(studentNo);
if (myRegs.isEmpty()) {
System.out.println("!!! 신청내역 조회 중 오류가 발생했습니다.");
} else {
System.out.println("### 신청내역 조회 결과");
System.out.println("신청번호\t과정명\t담당교수명\t신청상태\t수료여부\t점수\t신청일");
for (Reg reg : myRegs) {
String cancel = "신청됨";
String complete = "미수료";
if (reg.isCanceled()) {
cancel = "취소됨";
}
if (reg.isCompleted()) {
complete = "수료";
}
System.out.print(reg.getNo() + "\t");
System.out.print(reg.getCourse().getTitle() + "\t");
System.out.print(reg.getCourse().getProf().getName() + "\t");
System.out.print(cancel + "\t");
System.out.print(complete + "\t");
System.out.print(reg.getGrade() + "\t");
System.out.print(reg.getRegisteredDate() + "\n");
}
}
System.out.println("----------------------------------------");
} else if (studentMenuNo == 4) {
System.out.println("신청취소");
System.out.print("수강신청번호를 입력하세요: ");
int regNo = KeyboardUtil.nextInt();
boolean isSuccess = service.cancelReg(regNo);
if (isSuccess) {
System.out.println("### 수강 취소가 완료되었습니다.");
} else {
System.out.println("!!! 수강 취소 과정에서 오류가 발생했습니다.");
}
}
System.out.println("----------------------------------------");
}
} // while end
} // main end
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.database;
import java.util.ArrayList;
import java.util.List;
/**
* A relation between two tables.
*
* @author Miquel Sas
*/
public class Relation extends ForeignKey {
/**
* A relation type describes the type of a relation. There are only four possible types of relations, listed below.
* <ol>
* <li><code><b>LookUp</b></code>: in a lookup relation, the list of local fields from the relation segments does
* not match the local entity key fields, and the foreign fields from the segments exactly match the foreign entity
* key fields. It is a many-to-one relation. A lookup relation can not be reversed because a relation must have
* convenient keys for the foreign entity.</li>
* <li><code><b>Unique</b></code>: in an unique relation, the list of fields from the segments exactly match both
* the local and foreign key fields. It is a one-to-one relation.</li>
* <li><code><b>LocalDetail</b></code>: it is a header-detail relation where the local entity is the detail entity.
* The fields from the segments match partly the local key fields and exactly the foreign key fields. It is a
* many-to-one relation.</li>
* <li><code><b>ForeignDetail</b></code>: it is a header-detail relation where the foreign entity is the detail
* entity. The fields from the segments match partly the foreign key fields and exactly the local key fields. It is
* a one-to-many relation.</li>
* </ol>
*
* A <code>LocalDetail</code> relation if reversed becomes a <code>ForeignDetail</code> relation and viceversa.
*/
public enum Type {
Invalid, Lookup, Unique, LocalDetail, ForeignDetail;
/**
* Returns he category of the relation type.
*
* @return The relation category.
*/
public Category getCategory() {
switch (this) {
case Lookup:
return Category.OneToOne;
case Unique:
return Category.OneToOne;
case LocalDetail:
return Category.ManyToOne;
case ForeignDetail:
return Category.OneToMany;
case Invalid:
return Category.Unknown;
default:
return Category.Unknown;
}
}
}
/**
* Relation categories are ONE_TO_ONE, ONE_TO_MANY, MANY_TO_ONE
*/
public enum Category {
Unknown, OneToOne, OneToMany, ManyToOne;
}
/**
* The outer property.
*/
private boolean outer = false;
/**
* Local table alias. <i>Relation</i>'s are an extension of <i>ForeignKey</i>, but when building a complex relation
* layout some names can be repeated, requiring a different alias.
*/
private String localTableAlias;
/**
* Foreign table alias. <i>Relation</i>'s are an extension of <i>ForeignKey</i>'s, so when building a complex
* relation layout some names can be repeated, requiring a different alias.
*/
private String foreignTableAlias;
/**
* Default constructor.
*/
public Relation() {
super();
}
/**
* Check if this relation is outer.
*
* @return A boolean.
*/
public boolean isOuter() {
return outer;
}
/**
* Sets the outer property.
*
* @param outer A boolean.
*/
public void setOuter(boolean outer) {
this.outer = outer;
}
/**
* Returns the local table alias.
*
* @return The local table alias.
*/
public String getLocalTableAlias() {
return localTableAlias;
}
/**
* Sets the local table alias.
*
* @param localTableAlias The local table alias.
*/
public void setLocalTableAlias(String localTableAlias) {
this.localTableAlias = localTableAlias;
}
/**
* Returns the foreign table alias.
*
* @return The foreign table alias.
*/
public String getForeignTableAlias() {
return foreignTableAlias;
}
/**
* Sets the foreign table alias.
*
* @param foreignTableAlias The foreign table alias.
*/
public void setForeignTableAlias(String foreignTableAlias) {
this.foreignTableAlias = foreignTableAlias;
}
/**
* Returns this relation type.
*
* @return The type of the relation.
*/
public Relation.Type getType() {
Type type = null;
boolean check = true;
if (check && getLocalTable() == null) {
check = false;
}
if (check && getForeignTable() == null) {
check = false;
}
if (check
&&
(getForeignTable().getPrimaryKeyFields() == null || getForeignTable().getPrimaryKeyFields().isEmpty())) {
check = false;
}
if (check && size() == 0) {
check = false;
}
if (check
&&
(getLocalTable().getPrimaryKeyFields() == null || getLocalTable().getPrimaryKeyFields().isEmpty())) {
check = false;
}
if (check) {
// Get local-foreign key-segment fields
List<Field> localPrimaryKeyFields = getLocalTable().getPrimaryKeyFields();
List<Field> foreignPrimaryKeyFields = getForeignTable().getPrimaryKeyFields();
List<Field> localSegmentFields = new ArrayList<>(size());
List<Field> foreignSegmentFields = new ArrayList<>(size());
for (Segment segment : this) {
localSegmentFields.add(segment.getLocalField());
foreignSegmentFields.add(segment.getForeignField());
}
// Define values for matches
int NO_MATCH = 1; // Key and segment fields do not match
int PARTIAL_MATCH_KEY = 2; // Match, key shorter
int PARTIAL_MATCH_SEG = 3; // Match, segments shorter
int TOTAL_MATCH = 4; // Exact match
int count = 0;
int localMatch = TOTAL_MATCH;
int foreignMatch = TOTAL_MATCH;
// Check matches on local fields
count = Math.max(localPrimaryKeyFields.size(), localSegmentFields.size());
for (int i = 0; i < count; i++) {
if (i >= localPrimaryKeyFields.size() && i < localSegmentFields.size()) {
localMatch = PARTIAL_MATCH_KEY;
break;
}
if (i < localPrimaryKeyFields.size() && i >= localSegmentFields.size()) {
localMatch = PARTIAL_MATCH_SEG;
break;
}
if (!localPrimaryKeyFields.get(i).equals(localSegmentFields.get(i))) {
localMatch = NO_MATCH;
break;
}
}
// Check matches on foreign fields
count = Math.max(foreignPrimaryKeyFields.size(), foreignSegmentFields.size());
for (int i = 0; i < count; i++) {
if (i >= foreignPrimaryKeyFields.size() && i < foreignSegmentFields.size()) {
foreignMatch = PARTIAL_MATCH_KEY;
break;
}
if (i < foreignPrimaryKeyFields.size() && i >= foreignSegmentFields.size()) {
foreignMatch = PARTIAL_MATCH_SEG;
break;
}
if (!foreignPrimaryKeyFields.get(i).equals(foreignSegmentFields.get(i))) {
foreignMatch = NO_MATCH;
break;
}
}
// Check type
if (localMatch == TOTAL_MATCH && foreignMatch == TOTAL_MATCH) {
type = Type.Unique;
} else if (localMatch == TOTAL_MATCH && foreignMatch == PARTIAL_MATCH_SEG) {
type = Type.ForeignDetail;
} else if (localMatch == PARTIAL_MATCH_KEY && foreignMatch == TOTAL_MATCH) {
type = Type.LocalDetail;
} else if (localMatch == PARTIAL_MATCH_SEG && foreignMatch == TOTAL_MATCH) {
type = Type.LocalDetail;
} else if (localMatch == NO_MATCH && foreignMatch == TOTAL_MATCH) {
type = Type.Lookup;
}
// If the type has not been set it may be the one-to-one / unique
if (type == null && size() == localPrimaryKeyFields.size() && size() == foreignPrimaryKeyFields.size()) {
type = Type.Unique;
}
}
if (type == null) {
type = Type.Invalid;
}
return type;
}
/**
* Gets a string representation of this relation.
*
* @return A string representation of this column spec.
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder(64);
b.append(getLocalTable().getName());
b.append(" -> ");
b.append(getForeignTable().getName());
if (isOuter()) {
b.append(" (+)");
}
b.append(" (");
for (int i = 0; i < size(); i++) {
if (i > 0) {
b.append(", ");
}
b.append(get(i));
}
b.append(")");
return b.toString();
}
}
|
package Menu;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Logo extends JPanel{
public void paintComponent(Graphics g) {
try {
Image img = ImageIO.read(new File("Risk_logo.jpg"));
g.drawImage(img, 0, 0, this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
import java.io.File;
import java.io.IOException;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.collection.CollectionReader_ImplBase;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.FileUtils;
import org.apache.uima.util.Progress;
/**
*
* This is a collection reader that takes an input file to be processed as a parameter.
*
* @author mtydykov
*
*/
public class CollectionReader extends CollectionReader_ImplBase {
private File myFile;
private int myCurrentIndex;
public static final String PARAM_INPUTDIR = "InputDirectory";
public void initialize() {
myFile = new File(((String) getConfigParameterValue(PARAM_INPUTDIR)).trim());
myCurrentIndex = 0;
}
@Override
public void getNext(CAS arg0) throws IOException, CollectionException {
myCurrentIndex++;
JCas myCas = null;
try {
myCas = arg0.getJCas();
} catch (CASException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = FileUtils.file2String(myFile);
myCas.setDocumentText(text);
String[] sentences = text.split("\n");
for (String sent : sentences) {
SentenceData data = new SentenceData(myCas);
String id = sent.substring(0, sent.indexOf(" "));
String sentText = sent.substring(sent.indexOf(" "));
data.setSentenceText(sentText.trim());
data.setSentenceId(id);
data.addToIndexes();
}
}
@Override
public void close() throws IOException {
// TODO Auto-generated method stub
}
@Override
public Progress[] getProgress() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasNext() throws IOException, CollectionException {
return myCurrentIndex < 1;
}
}
|
package com.spark.source;
import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
/**
* @fileName: HDFSSourceHandler.java
* @description: 读取hdfs数据
* @author: by echo huang
* @date: 2020-04-25 15:20
*/
public class HDFSSourceHandler {
public static void main(String[] args) throws Exception {
SparkConf sparkConf = new SparkConf().setMaster("local[1]").setAppName("hdfsSource");
JavaStreamingContext javaStreamingContext = new JavaStreamingContext(sparkConf, Duration.apply(5000));
JavaDStream<String> stringJavaDStream = javaStreamingContext.textFileStream("hdfs://hadoop:8020/cache");
stringJavaDStream.print();
javaStreamingContext.start();
javaStreamingContext.awaitTermination();
}
}
|
package com.example.comprale;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class FragmentPerfil extends Fragment {
Button btnClave;
EditText Nombre, Email, Clave, Direccion;
Variables variables = new Variables();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View vista = inflater.inflate(R.layout.fragment_perfil, container, false);
btnClave=(Button)vista.findViewById(R.id.btnCambiarClave);
Nombre=(EditText)vista.findViewById(R.id.Nombre);
Email=(EditText)vista.findViewById(R.id.Email);
Clave=(EditText)vista.findViewById(R.id.Clave);
Direccion=(EditText)vista.findViewById(R.id.Dirección);
Direccion.setText("Las Margaritas. Calle 1567, psj J, Casa #1, Soyapango, San Salvador");
Nombre.setText(variables.getLoginUser());
Clave.setText(variables.getLoginPass());
Email.setText("estudiante@udb.com.edu.sv");
btnClave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Contraseña cambiada", Toast.LENGTH_SHORT).show();
variables.setLoginPass(Clave.getText().toString());
variables.setLoginUser(Nombre.getText().toString());
}
});
return vista;
}
} |
package com.hb.rssai.presenter;
import com.hb.rssai.constants.Constant;
import com.hb.rssai.view.iView.IOfficeView;
import java.util.HashMap;
import java.util.Map;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Administrator on 2017/10/3 0003.
*/
public class OfflinePresenter extends BasePresenter<IOfficeView> {
private IOfficeView iOfficeView;
public OfflinePresenter(IOfficeView iOfficeView) {
this.iOfficeView = iOfficeView;
}
public void getChannels() {
dataGroupApi.getDataGroupList(getParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resDataGroup -> {
iOfficeView.setDataGroupResult(resDataGroup);
}, iOfficeView::loadError);
}
public Map<String, String> getParams() {
//参数可以不要
HashMap<String, String> map = new HashMap<>();
String jsonParams = "{\"page\":\"" + 1 + "\",\"size\":\"" + Constant.PAGE_SIZE + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
return map;
}
}
|
package com.example.tutorialconexion;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new NetTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return false;
}
private class NetTask extends AsyncTask<Object, Object, Object> {
String nubes = "Sin definir";
@Override
protected Object doInBackground(Object... params) {
fillData();
return null;
}
@Override
protected void onPostExecute(Object result) {
TextView textView = (TextView)findViewById(R.id.texto1);
textView.setText(nubes);
};
public void fillData() {
URL url = null;
try {
url = new URL("http://api.openweathermap.org/data/2.5/weather?q=Madrid,es&units=metric&lang=sp");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer stringBuffer = new StringBuffer();
try {
InputStream is = urlConnection.getInputStream();
BufferedInputStream buffStream = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
while (buffStream.read(buffer) != -1) {
stringBuffer.append(new String(buffer));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject jobj = new JSONObject(stringBuffer.toString());
nubes = jobj.getJSONArray("weather").getJSONObject(0).getString("description");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package fr.badblock.badkeys;
import java.sql.ResultSet;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import fr.badblock.badkeys.Request.RequestType;
import net.md_5.bungee.api.ChatColor;
public class BadKeyCommand implements CommandExecutor
{
@Override
public boolean onCommand(CommandSender arg0, Command arg1, String arg2, String[] arg3) {
if (!arg0.hasPermission("badkeys.give"))
{
arg0.sendMessage("§cVous n'avez pas la permission d'exécuter cette commande.");
return false;
}
if (arg3.length < 1)
{
arg0.sendMessage("§eUtilisation: /badkey <pseudo> [id]");
return true;
}
String playerName = arg3[0];
if (arg3.length < 2)
{
BadblockDatabase.getInstance().addRequest(new Request("SELECT * FROM `keys` WHERE player = '" +
BadblockDatabase.getInstance().mysql_real_escape_string(playerName) + "' && server = '" + BadKeys.instance.server + "'", RequestType.GETTER)
{
@Override
public void done(ResultSet resultSet)
{
try
{
arg0.sendMessage("§eClés non utilisées de " + playerName + " :");
boolean f = false;
while (resultSet.next())
{
f = true;
int keyId = resultSet.getInt("key");
String name = BadKeys.instance.names.containsKey(keyId) ? ChatColor.translateAlternateColorCodes('&', BadKeys.instance.names.get(keyId)) : "Inconnu";
arg0.sendMessage("§aClé " + keyId +" (" + name+ "§a)");
}
if (!f)
{
arg0.sendMessage("§cAucune clé non utilisée.");
}
}
catch (Exception error)
{
arg0.sendMessage("§cUne erreur est survenue.");
}
}
});
return true;
}
String rawId = arg3[1];
try
{
int id = Integer.parseInt(rawId);
BadblockDatabase.getInstance().addRequest(new Request("INSERT INTO `keys`(player, server, `key`) VALUES('" +
BadblockDatabase.getInstance().mysql_real_escape_string(playerName) + "', '" + BadKeys.instance.server + "', '" + id + "')", RequestType.SETTER));
System.out.println("[BadKeys] Added key for " + playerName + " (key id " + id + ") -> added by " + arg0.getName());
arg0.sendMessage("§aClé '" + id + "' donnée à " + playerName + ".");
return true;
}
catch (Exception error)
{
arg0.sendMessage("§cL'ID doit être un nombre.");
}
return false;
}
}
|
class Solution {
public boolean canPermutePalindrome(String s) {
/*
map to store the frequency
if there are greater than 1 odd frequency characters, return false;
else return true;
**/
if (s == null || s.length() == 0) return true;
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
int count_odd = 0;
for (char c : map.keySet()) {
if (map.get(c) % 2 == 1) count_odd++;
if (count_odd > 1) return false;
}
return true;
}
} |
package com.anibal.educational.rest_service.comps.config;
import com.odhoman.api.utilities.config.AppConfig;
/**
* Configurador General de la aplicacion
*
* @author Jonatan Flores
*
*/
public class RestServiceConfig extends AppConfig {
/**
* Autogenerated UID
*/
private static final long serialVersionUID = 1684706179604287726L;
/**
* Instancia singleton
*/
private static RestServiceConfig actConfig = null;
/**
* Constructor privado para forzar singleton;
*/
protected RestServiceConfig() {
}
/**
* @see AppConfig#getInstance()
*/
public static RestServiceConfig getInstance() {
if (actConfig == null) {
synchronized (RestServiceConfig.class) {
actConfig = new RestServiceConfig();
}
}
return actConfig;
}
}
|
package com.szcinda.express.dto;
import com.szcinda.express.RoleType;
import lombok.Data;
import java.io.Serializable;
@Data
public class UserCreateDto implements Serializable {
private String account;
private String password;
private String name;
private String email;
private RoleType role;
}
|
package com.lupan.HeadFirstDesignMode.chapter9_iteratorAndComposite.iterator;
/**
* TODO
*
* @author lupan
* @version 2016/3/24 0024
*/
public interface IteratorInterface<T> {
boolean hasNext();
T next();
}
|
package com.github.ezauton.core.pathplanning.purepursuit;
import com.github.ezauton.core.localization.sensors.VelocityEstimator;
/**
* Easy lookahead implementation given a speed. Takes in min speed, max speed, min lookahead, max lookahead and
* performs a linear interpolation.
*/
public class LookaheadBounds implements Lookahead {
private final double minDistance;
private final double maxDistance;
private final double minSpeed;
private final double dDistance;
private final double dSpeed;
private final VelocityEstimator velocityEstimator;
/**
* Create some lookahead bounds
*
* @param minDistance Minimum lookahead
* @param maxDistance Maximum lookahead
* @param minSpeed Minimum speed where lookahead is allowed to be dynamic
* @param maxSpeed Maximum speed where lookahead is allowed to be dynamic
* @param velocityEstimator Estimator of the robot's velocity. Used to calculate lookahead based on current speed.
*/
public LookaheadBounds(double minDistance, double maxDistance, double minSpeed, double maxSpeed, VelocityEstimator velocityEstimator) {
this.minDistance = minDistance;
this.maxDistance = maxDistance;
dDistance = maxDistance - minDistance;
this.minSpeed = minSpeed;
dSpeed = maxSpeed - minSpeed;
this.velocityEstimator = velocityEstimator;
}
/**
* Based on the current spead as described by this.velocityEstimator, calculate a lookahead
*
* @return The lookahead to use
*/
@Override
public double getLookahead() {
double speed = Math.abs(velocityEstimator.getTranslationalVelocity());
double lookahead = dDistance * (speed - minSpeed) / dSpeed + minDistance;
return Double.isNaN(lookahead) ? minDistance : Math.max(minDistance, Math.min(maxDistance, lookahead));
}
}
|
package com.hqhcn.android.service.impl;
import com.hqh.android.dao.LogMapper;
import com.hqh.android.entity.Log;
import com.hqh.android.entity.LogExample;
import com.hqh.android.service.LogService;
import com.hqh.android.tool.LogType;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class LogServiceImpl implements LogService {
@Autowired
private LogMapper logDao;
/**
* 日志信息插入
*/
@Override
public void add(Log entity) {
String jyw = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// TODO: 2018/1/22 0022 没有序列化
md.update(entity.toString().getBytes());
jyw = new BigInteger(1, md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
entity.setJmw(jyw);
logDao.insert(entity);
}
/**
* 查询日志信息列表
*/
@Override
public List<Log> query(LogExample example) {
List<Log> list_data = logDao.selectByExampleToPage(example);
return list_data;
}
@Override
public void info(LogType cz, String czip, String jmw, String logtype, String program, String usercode, String xxsm) {
info(cz, czip, jmw, logtype, program, usercode, xxsm, "1");
}
@Override
public void info(LogType cz, String czip, String jmw, String logtype, String program, String usercode, String xxsm, String resultCode) {
Log record = new Log();
record.setId(UUID.randomUUID().toString());
record.setCz(cz.toString());
record.setCzip(czip);
record.setCzsj(new Date());
record.setJmw(jmw);
record.setLogtype(logtype);
record.setProgram(program);
record.setUserCode(usercode == null ? "" : usercode);
record.setXxsm(xxsm);
record.setF1(resultCode);
try {
// TODO: 2018/2/28 0028 以后要统一
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(record.toString().getBytes());
jmw = new BigInteger(1, md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
record.setJmw(jmw);
add(record);
}
@Override
public List<Log> queryToday(LogExample example) {
// TODO: 2017/12/14 0014 待测试
Date tomorrow = DateUtils.addDays(new Date(), 1);
List<LogExample.Criteria> criteriaList = example.getOredCriteria();
criteriaList.get(0).andCzsjBetween(
DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH),
DateUtils.truncate(tomorrow, Calendar.DAY_OF_MONTH));
return logDao.selectByExample(example);
}
}
|
package de.rwth.i9.palm.persistence;
import java.util.List;
import java.util.Map;
import de.rwth.i9.palm.model.InterestProfile;
import de.rwth.i9.palm.model.InterestProfileType;
public interface InterestProfileDAO extends GenericDAO<InterestProfile>, InstantiableDAO
{
public List<InterestProfile> getAllInterestProfiles();
public List<InterestProfile> getAllActiveInterestProfile();
public List<InterestProfile> getAllActiveInterestProfile( InterestProfileType interestProfileType );
public Map<String, InterestProfile> getInterestProfileMap();
}
|
package Networking.LowLevelAPIS.TCPIP.EchoServer;
import java.io.*;
import java.net.Socket;
public class Echoer extends Thread {
private final Socket socket;
public Echoer(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String echoString = reader.readLine();
System.out.println("Recieved client input: " + echoString);
if (echoString.equalsIgnoreCase("exit")) {
break;
}
writer.println(echoString);
}
} catch (IOException e) {
System.out.println("Oops. " + e.getMessage());
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package com.stackroute.muzix.service;
import com.stackroute.muzix.model.Track;
import com.stackroute.muzix.repository.TrackRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class TrackServiceImpl implements TrackService {
TrackRepository trackRepository;
@Autowired
public TrackServiceImpl(TrackRepository trackRepository) {
this.trackRepository = trackRepository;
}
// method for getting all the tracks from database
@Override
public List<Track> getAllTracks() {
List<Track> trackList = trackRepository.findAll();
return trackList;
}
// method for creating a new track in DB
@Override
public Track saveTrack(Track track) {
return trackRepository.save(track);
}
// method for delete a track from DB using id
@Override
public Track deleteTrack(int id) {
Optional<Track> track =null;
if(trackRepository.existsById(id) == true) {
trackRepository.deleteById(id);
track= trackRepository.findById(id);
}
return track.get();
}
// method for update an existing track in DB
@Override
public Track updateTrack(int id, Track track) {
if(trackRepository.existsById(id) == true){
return trackRepository.save(track);
}
else
return null;
}
}
|
package com.duanxr.yith.midium;
import java.util.Stack;
import javafx.util.Pair;
/**
* @author 段然 2021/3/10
*/
public class DailyTemperatures {
/**
* Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
*
* For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
*
* Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
*
* 请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
*
* 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
*
* 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
*
*/
class Solution {
public int[] dailyTemperatures1(int[] T) {
int[] result = new int[T.length];
Stack<Pair<Integer, Integer>> stack = new Stack<>();
for (int i = 0; i < T.length; i++) {
while (!stack.isEmpty() && stack.peek().getKey() < T[i]) {
Pair<Integer, Integer> pop = stack.pop();
result[pop.getValue()] = i - pop.getValue();
}
stack.push(new Pair<>(T[i], i));
}
return result;
}
}
}
|
package com.example.user.myapplication.lockscreen.receiver;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import com.example.user.myapplication.lockscreen.LockMainActivity;
/**
* Created by Junho on 2016-02-26.
*/
public class LockScreenReceiver extends BroadcastReceiver {
//This is deprecated, but it is a simple way to disable the lockscreen in code
private KeyguardManager km = null;
private KeyguardManager.KeyguardLock keyLock = null;
//전화상태 체크
private TelephonyManager telephonyManager = null;
private boolean isPhoneIdle = true;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//If the screen was just turned on or it just booted up, start your Lock Activity
if(action.equals(Intent.ACTION_SCREEN_OFF))
{
//기본 잠금화면 없애기
if(km == null){
km = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
}
if(keyLock == null){
keyLock = km.newKeyguardLock(Context.KEYGUARD_SERVICE);
}
//전화상태에서 잠금화면 없애기
if(telephonyManager == null){
telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
}
if(isPhoneIdle) {
disableKeyguard();
Intent i = new Intent(context, LockMainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
public void disableKeyguard() {
keyLock.disableKeyguard();
}
public void reenableKeyguard(){
keyLock.reenableKeyguard();
}
//전화 상태 체크!
private PhoneStateListener phoneListener = new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
isPhoneIdle = true;
break;
case TelephonyManager.CALL_STATE_RINGING:
isPhoneIdle = false;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
isPhoneIdle = false;
break;
}
}
};
}
|
package com.moon.moon_thread.moonThread.threadSync;
/**
* @ClassName PushOrderProcess
* @Description: TODO
* @Author zyl
* @Date 2020/12/30
* @Version V1.0
**/
public class PushOrderProcess {
// 10个订单一起派发, 有100个司机,、
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
// 给100个司机派发
}
}
}
// 100个司机接单,接单成功改变订单状态和自己状态 |
package com.codecow.common.vo.resp;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author codecow
* @version 1.0 UPMS
* @date 2021/6/17 16:49
**/
@Data
public class HomeRespVO {
@ApiModelProperty(value = "用户信息")
private UserInfoRespVO userInfoRespVO;
@ApiModelProperty(value = "首页菜单导航数据")
private List<PermissionRespNodeVO>menus;
}
|
package no.hiof.larseknu.javafx.model;
import java.time.LocalDate;
public class Dyr {
private String navn, art;
private LocalDate fodselsDato;
private final int ID;
private static int idTeller = 100;
public Dyr(String navn, String art, LocalDate fodselsDato) {
this.navn = navn;
this.art = art;
this.fodselsDato = fodselsDato;
this.ID = Dyr.idTeller++;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
public String getArt() {
return art;
}
public void setArt(String art) {
this.art = art;
}
public LocalDate getFodselsDato() {
return fodselsDato;
}
public void setFodselsDato(LocalDate fodselsDato) {
this.fodselsDato = fodselsDato;
}
public int getID() {
return ID;
}
@Override
public String toString() {
return art + " - " + navn;
}
}
|
package interfaceTest;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyWindow2 implements ActionListener {
JLabel result;
public MyWindow2() {
JFrame f = new JFrame("이벤트 처리 화면");
f.setSize(300, 300);
FlowLayout flow = new FlowLayout();
f.setLayout(flow);
JButton b1 = new JButton("나를 눌러라");
f.add(b1);
JButton b2 = new JButton("클릭!!");
f.add(b2);
JButton b3 = new JButton("나 클릭!!=================");
f.add(b3);
//ClickClass click = new ClickClass();
b1.addActionListener(this);
b2.addActionListener(this);
//b2.addActionListener(new Click2Class());
result = new JLabel("결과");
result.setFont(new Font("궁서", Font.BOLD, 20));
result.setForeground(Color.BLUE);
f.add(result);
f.setVisible(true);
}
public static void main(String[] args) {
new MyWindow2();
}
@Override
public void actionPerformed(ActionEvent e) {
result.setText("버튼을 누름");
}
}
|
package shopify.app.shopifyme.domain.entities;
import java.util.List;
public class WishList {
private List<Wish> items;
public List<Wish> getItems() {
return items;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WishList{");
sb.append("items=").append(items);
sb.append('}');
return sb.toString();
}
public void add(final Wish wish) {
items.add(wish);
}
}
|
package issearchtree;
public class Solution {
public boolean isBST(TreeNode root) {
// Write your solution here.
return decide( root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean decide(TreeNode root, int min, int max){
if (root == null){
return true;
}
if (root.key < min || root.key > max){
return false;
}
else {
return decide(root.left, min, root.key-1) && decide( root.right , max, root.key + 1);
}
}
} |
package by.dt.boaopromtorg.repository;
import by.dt.boaopromtorg.entity.Shop;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ShopRepository extends MongoRepository<Shop,String>{
Shop findShopByAddress(String address);
}
|
package quiz12;
public class Computer {
//키보드, 마우스, 모니터 클래스를 저장하는 변수를 선언하세요
private KeyBoard k ;
private Mouse m ;
private Monitor mo ;
//기본생성자를 생성하고, 변수를 클래스로 초기화 하세요
public Computer(){
this.k =new KeyBoard();
this.m = new Mouse();
this.mo = new Monitor();
}
//모든 멤버변수를 받는 생성자
public Computer(KeyBoard k, Mouse m, Monitor mo){
this.k = k;
this.m = m;
this.mo = mo;
}
//키보드, 모니터, 마우스 정보를 출력하는 computerInfo() 메서드를 생성하세요
public void computerInfo(){
System.out.println("==============시스템 정보 =============");
k.info();
m.info();
mo.info();
}
//키보드, 모니터, 마우스에 대한 getter/setter도 생성하세요
public KeyBoard getK() {
return k;
}
public void setK(KeyBoard k) {
this.k = k;
}
public Mouse getM() {
return m;
}
public void setM(Mouse m) {
this.m = m;
}
public Monitor getMo() {
return mo;
}
public void setMo(Monitor mo) {
this.mo = mo;
}
//메인메서드에서 getter로 접근하여 모니터에 대한 정보를 확인하세요
}
|
package Model.Connection;
import java.sql.*;
public class JDBC_conn {
private Connection con = null;
public boolean getConnection(String user, String pass) throws SQLException {
boolean conSucess = true;
// Connect to database
String DB_USER = user;
String DB_PASS = pass;
String DB_URL = "jdbc:oracle:thin:@ora3.elka.pw.edu.pl:1521:ora3inf";
try {
con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
} catch (SQLException e){
if(e.getErrorCode() == 1017) conSucess = false;
}
return conSucess;
}
public ResultSet sendQuery(String sqlSelect) throws SQLException {
// Create and execute a SELECT SQL statement.
ResultSet rs;
Statement statement = con.createStatement();
rs = statement.executeQuery(sqlSelect);
return rs;
}
public Connection getCon() {
return con;
}
} |
package com.rx.rxmvvmlib.ui;
import android.os.Bundle;
public interface IBaseView {
/**
* 初始化根布局
*
* @return 布局layout的id
*/
int initLayoutId(Bundle savedInstanceState);
/**
* 初始化ViewModel的id
*
* @return BR的id
*/
int initVariableId();
/**
* 初始化界面传递参数
*/
void initParam();
/**
* 初始化界面
*/
void initView(Bundle savedInstanceState);
/**
* 初始化数据
*/
void initData();
/**
* 初始化界面观察者的监听
*/
void initViewObservable();
/**
* loading弹出布局
*
* @return
*/
int initLoadingLayoutId();
/**
* loading弹出是否消失
*
* @return
*/
boolean loadingCancelable();
/**
* 按返回键是否只是返回
*
* @return
*/
boolean isBack();
/**
* 按返回键仅仅只是返回上个界面时要做的操作
*/
void doSthIsBack();
}
|
package de.fafeitsch.maze.domain;
public class ShortestPathFinder {
private final char[][] maze;
public ShortestPathFinder(char[][] maze) {
this.maze = maze;
}
private static CellList findShortestPath(Cell start, int endRow, int endCol) {
CellList queue = new CellList();
queue.enqueue(start);
Cell current = null;
while (!queue.isEmpty()) {
current = queue.poll();
if (current.getRow() == endRow && current.getCol() == endCol) {
break;
}
Cell[] neighbours = current.getNeighboursAsArray();
for (int i = 0; i < neighbours.length; i++) {
Cell neighbour = neighbours[i];
if (neighbour.wasVisited() || neighbour == start) {
continue;
}
neighbour.setPredecessor(current);
queue.enqueue(neighbour);
}
}
CellList path = new CellList();
path.addToFront(current);
while (current.getPredecessor() != null) {
current = current.getPredecessor();
path.addToFront(current);
}
return path;
}
public void drawShortestPathInMaze(int startRow, int startCol, int endRow, int endCol) {
Cell start = MazeBuilder.buildMaze(this.maze, startRow, startCol);
CellList shortestPath = ShortestPathFinder.findShortestPath(start, endRow, endCol);
Cell current = shortestPath.poll();
while (!shortestPath.isEmpty()) {
this.maze[current.getRow()][current.getCol()] = '*';
current = shortestPath.poll();
}
this.maze[current.getRow()][current.getCol()] = '*';
}
}
|
package Search;
import java.io.File;
public class FileExample {
public static void main(String[] args) throws Exception{
System.out.println(File.separatorChar);
System.out.println(File.separator);
String s = "�������� \"name\" = \"Poll\"";
System.out.println(s);
File file1 = new File("c:\\work\\example.tXt");
System.out.println("file1.createNewFile()="+file1.createNewFile());
File file2 = new File("c:/work/temp1/temp2");
System.out.println("file2.mkdir()="+file2.mkdir());
//file2.mkdirs();
System.out.println();
System.out.println("getAbsolutePath()="+file1.getAbsolutePath());
System.out.println("getCanonicalPath()="+file1.getCanonicalPath());
System.out.println("getName()="+file1.getName());
System.out.println("getPath()="+file1.getPath());
System.out.println();
File dir = new File("c:\\work");
if(dir.isDirectory()){
File[] arr = dir.listFiles();
for(File f: arr){
System.out.println(f.getName());
}
File f = arr[0];
System.out.println("f="+f.getName());
}
}
}
|
package operations.commands.exceptions;
/**
* Thrown to indicate that a line of a DIMACS file has too many space separated arguments.
*/
public class ParseDIMACSTooManyArgs extends ParseDIMACSException {
private static final long serialVersionUID = 1L;
public ParseDIMACSTooManyArgs(int line) {
super(line);
}
@Override
public String getStringRepresentation() {
return super.getStringRepresentation() + ": Too many arguments.";
}
}
|
package cn.leo.produce.decode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @description:
* @author: fanrunqi
* @date: 2019/4/23 15:26
*/
public class DecoderBuild {
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType, ?> hints;
private String characterSet;
public DecoderBuild() {
Set<BarcodeFormat> formats = new HashSet<>();
formats.addAll(Arrays.asList(BarcodeFormat.values()));
decodeFormats = formats;
}
public Decoder createDecoder(Map<DecodeHintType, ?> baseHints) {
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.putAll(baseHints);
if (this.hints != null) {
hints.putAll(this.hints);
}
if (this.decodeFormats != null) {
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
}
if (characterSet != null) {
hints.put(DecodeHintType.CHARACTER_SET, characterSet);
}
MultiFormatReader reader = new MultiFormatReader();
reader.setHints(hints);
return new Decoder(reader);
}
}
|
package com.flutterwave.raveandroid.zmmobilemoney;
import com.flutterwave.raveandroid.RavePayInitializer;
import com.flutterwave.raveandroid.ViewObject;
import com.flutterwave.raveandroid.rave_presentation.zmmobilemoney.ZmMobileMoneyContract;
import java.util.HashMap;
/**
* Created by hfetuga on 28/06/2018.
*/
public interface ZmMobileMoneyUiContract {
interface View extends ZmMobileMoneyContract.Interactor {
void onAmountValidationSuccessful(String valueOf);
void showFieldError(int viewID, String message, Class<?> viewtype);
void onPhoneValidated(String phoneToSet, boolean isEditable);
void onValidationSuccessful(HashMap<String, ViewObject> dataHashMap);
void showToast(String validNetworkPrompt);
}
interface UserActionsListener extends ZmMobileMoneyContract.Handler {
void init(RavePayInitializer ravePayInitializer);
void onDataCollected(HashMap<String, ViewObject> dataHashMap);
void processTransaction(HashMap<String, ViewObject> dataHashMap, RavePayInitializer ravePayInitializer);
void onAttachView(View view);
void onDetachView();
}
}
|
package io.confluent.se.poc.utils;
import java.util.Properties;
import org.apache.kafka.clients.producer.*;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import java.io.*;
import java.util.*;
import org.json.*;
public class PocData {
public static void main(String[] args) throws Exception{
PocData pd = new PocData();
if (args.length == 0) {
pd.loadOrders();
pd.loadCustomers();
}
else if (args.length == 1) {
if (args[0].equals("customers")) {
pd.loadCustomers();
}
else if (args[0].equals("orders")) {
pd.loadOrders();
}
}
else {
System.out.println("ARGUMENTS: null -or- \"customers\" -or- \"orders\"");
}
}
public void loadOrders() throws Exception {
System.out.println("loading orders...");
Producer<String, GenericRecord> producer = null;
try {
String topicName = "orders_s";
Properties props = new Properties();
props.load(new java.io.FileInputStream(System.getProperty("streams-properties")));
props.put("bootstrap.servers","localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer","io.confluent.kafka.serializers.KafkaAvroSerializer");
producer = new KafkaProducer<String, GenericRecord>(props);
int i = 0;
Random r = new Random();
InputStream is = new FileInputStream(props.get("orders.schema.file").toString());
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while(line != null){
sb.append(line).append("\n");
line = buf.readLine();
}
String schemaString = sb.toString();
Schema schema = new Schema.Parser().parse(schemaString);
int j = 0;
while (i++ < 100) {
GenericData.Record gr = new GenericData.Record(schema);
String order_id = "OH";
gr.put("order_id","ORD" + i);
j = j++ > 20 ? 1 : j;
gr.put("customer_id","CUST" + r.nextInt(20));
gr.put("sku","SKU" + r.nextInt(50));
gr.put("quantity", r.nextInt(3));
gr.put("price", r.nextInt(50));
ProducerRecord record = new ProducerRecord<String, GenericRecord>(topicName,null,System.currentTimeMillis(),
"ORD" + i,
gr
);
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata metadata, Exception e) {
if (e != null)
e.printStackTrace();
}
});
}
}
finally {
try {
producer.close();
}
catch (Exception e) {
//ignore
}
}
}
public void loadCustomers() throws Exception{
System.out.println("loading customers...");
Producer<String, GenericRecord> producer = null;
try {
String topicName = "customers_stream";
Properties props = new Properties();
props.load(new java.io.FileInputStream(System.getProperty("streams-properties")));
String[] states = {"OH","KY","WV","VA","NC","SC","TN","AL","GA","AL","PA","FL"};
String[] genders = {"M","F"};
String[] fnames = {"Mark","Ben","John","Jim","Fred","Becky","Abby","Maddie","Jenna","Eileen","Marie","Olivia"};
String[] lnames = {"Kosar","Lynn","Rice","Warner","Linkowicz","Desseau","Lucas","Koch","Pickens","Hilton","Graves","Shepard"};
props.put("bootstrap.servers","localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer","io.confluent.kafka.serializers.KafkaAvroSerializer");
producer = new KafkaProducer<String, GenericRecord>(props);
int i = 0;
Random r = new Random();
InputStream is = new FileInputStream(props.get("customers.schema.file").toString());
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while(line != null){
sb.append(line).append("\n");
line = buf.readLine();
}
String schemaString = sb.toString();
Schema schema = new Schema.Parser().parse(schemaString);
while (i++ < 20) {
GenericData.Record gr = new GenericData.Record(schema);
gr.put("customer_id","CUST" + i);
gr.put("first_name",fnames[r.nextInt(fnames.length - 1)]);
gr.put("last_name",lnames[r.nextInt(lnames.length - 1)]);
gr.put("age", i);
gr.put("gender",genders[r.nextInt(genders.length - 1)]);
gr.put("state",states[r.nextInt(states.length - 1)]);
ProducerRecord record = new ProducerRecord<String, GenericRecord>(topicName,null,System.currentTimeMillis(),
"CUST" + i,
gr
);
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata metadata, Exception e) {
if (e != null)
e.printStackTrace();
}
});
}
}
finally {
try {
producer.close();
}
catch (Exception e) {
//ignore
}
}
}
}
|
package persistenza.dao;
import business.cassa.Scontrino;
import business.inventario.Prodotto;
import exceptions.DatabaseException;
import exceptions.ElencaException;
import exceptions.ProdottoException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import persistenza.DatabaseConnection;
/**
* DAO per la persistenza della relazione tra un codice di uno scontrino e i codici dei prodotti a
* cui si riferisce.
*/
public class ElencaDao {
/**
* Salva nel persistenza la relazione tra un codice di uno scontrino e i codici dei prodotti a cui
* si riferisce.
*
* @param s Lo Scontrino da cui ricavare le relazioni
* @throws DatabaseException Errore del Database
*/
public static void save(Scontrino s) throws DatabaseException, ProdottoException {
List<Prodotto> l = s.getList();
for (Prodotto c : l) {
try {
PreparedStatement state =
DatabaseConnection.getInstance().getCon().prepareStatement(Query.elenca);
state.setLong(1, s.getId());
state.setString(2, s.getData().substring(0, 10));
state.setLong(3, c.getCodice());
state.setInt(4, c.getAcquistato());
state.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new DatabaseException("Errore non fatale nel Database.");
}
c.leavedbquantity();
}
}
/**
* Controlla se nel persistenza alla tabella Elenca esiste una riga contenente codice e data dello
* Scontrino e codice Prodotto così come passato per parametro.
*
* @param codiceScontrino il codice dello Scontrino
* @param dataScontrino la data dello Scontrino
* @param codiceProdotto il codice del Prodotto
* @throws DatabaseException Errore del Database
* @throws ElencaException Relazione non trovata
*/
public static void checkCorrispondenza(
long codiceScontrino, String dataScontrino, long codiceProdotto)
throws DatabaseException, ElencaException {
try {
PreparedStatement state =
DatabaseConnection.getInstance().getCon().prepareStatement(Query.elencaCheck);
state.setLong(1, codiceScontrino);
state.setString(2, dataScontrino);
state.setLong(3, codiceProdotto);
ResultSet rs = state.executeQuery();
if (!rs.next()) {
throw new ElencaException("Prodotto non correlato allo Scontrino immesso");
} else {
int i = 1;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new DatabaseException("Errore nel Database.");
}
}
}
|
package com.ntil.habiture;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.habiture.Friend;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
public class InviteFriendAdapter extends BaseAdapter {
private List<Item> items;
private LayoutInflater inflater;
public InviteFriendAdapter(Context context, List<Friend> friends) {
inflater = LayoutInflater.from(context);
items = new ArrayList<>(friends.size());
for (Friend friend : friends) {
Item item = new Item();
item.friend = friend;
items.add(item);
}
}
public class Item {
Friend friend;
boolean isSelected = false;
public Friend getFriend() {
return friend;
}
public boolean isSelected() {
return isSelected;
}
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.singleitem_invite_friend, parent, false);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvFriendsName);
holder.ivSelected = (ImageView) convertView.findViewById(R.id.ivSelected);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
Item item = (Item) getItem(position);
// 設定姓名
holder.tvName.setText(item.friend.getName());
// 設定是否已選擇
holder.ivSelected.setVisibility(item.isSelected() ? View.VISIBLE : View.INVISIBLE);
return convertView;
}
public void setSelected(int position, boolean selected) {
Item item = (Item) getItem(position);
item.isSelected = selected;
notifyDataSetChanged();
}
private class ViewHolder {
TextView tvName;
ImageView ivSelected;
}
}
|
package com.test.gurukul.pages;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
public class GkBranchPage extends GkBasePage {
public GkBranchPage(WebDriver driver) {
super(driver);
}
private static Logger myLog = Logger.getLogger(GkBranchPage.class);
public String branchPageHeader(){
String header=null;
try{
driver.findElement(objmap.getLocator("branchHeader")).isDisplayed();
header=driver.findElement(objmap.getLocator("branchHeader")).getText();
}catch(Exception e) {
myLog.error(e.getMessage());
Assert.fail(e.getMessage());
}
return header;
}
}
|
package com.union.design.generator;
import freemarker.template.Configuration;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class FreeMarkerConfig {
public static Configuration getConfig() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
cfg.setDirectoryForTemplateLoading(new File(Objects.requireNonNull(
FreeMarkerConfig.class.getClassLoader().getResource("templates")
).getFile()));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.displayName());
return cfg;
}
} |
package com.tyss.javacloud.loanproject.exceptions;
@SuppressWarnings("serial")
public class FormReviewChoiceException extends RuntimeException {
public FormReviewChoiceException(String msg) {
super(msg);
}
}
|
package org.george.library;
import org.george.library.entities.Book;
import org.george.library.entities.Review;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/library")
public class MyResource {
private static final Logger logger = LoggerFactory.getLogger(MyResource.class);
@GET
@Path("/books")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getIt() {
Book b = Book.BookBuilder.withId(15).build();
return Response.ok().entity(b).build();
}
}
|
package com.rofour.baseball.dao.user.bean;
import java.io.Serializable;
/**
* @ClassName: TbUserTypeBean
* @Description: 操作用户类型DTO
* @author ZhangLei
* @date 2016年3月25日 下午6:35:30
*
*/
public class UserTypeBean implements Serializable{
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = 4356791132617077894L;
/**
* @Fields userTypeId :用户类型编码
*/
private Long userTypeId;
/**
* @Fields userId :用户编码
*/
private Long userId;
/**
* @Fields userType :类型
*/
private Integer userType;
/**
* @Fields beEnabled :是否启用
*/
private Byte beEnabled;
public UserTypeBean(Long userTypeId, Long userId, Integer userType, Byte beEnabled) {
this.userTypeId = userTypeId;
this.userId = userId;
this.userType = userType;
this.beEnabled = beEnabled;
}
public UserTypeBean() {
super();
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Byte getBeEnabled() {
return beEnabled;
}
public void setBeEnabled(Byte beEnabled) {
this.beEnabled = beEnabled;
}
public Long getUserTypeId() {
return userTypeId;
}
public void setUserTypeId(Long userTypeId) {
this.userTypeId = userTypeId;
}
} |
package strategycustomburger;
public class HousemadeVeganVeggie implements BurgerCharges {
public HousemadeVeganVeggie()
{
}
@Override
public double BurgerCharge(double burgerprice) {
System.out.println("House made Vegan Veggie Charge");
double burgercharge = burgerprice + 3;
return burgercharge;
}
}
|
package rugal.westion.jiefanglu.core.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Westion
*
* @category entity
*
* 用户
*/
@Entity
@Table(name = "jfl_article")
// 指定映射的表名
public class Article implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "article_id")
private Integer id;
@Column(name = "article_title")
private String title;
@Column(name = "article_content", columnDefinition = "TEXT")
private String content;
@Column(name = "publish_time")
private Long publishTime;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private Account account;
@Column(columnDefinition = "TEXT")
private String coverURL;
public Article() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Long getPublishTime() {
return publishTime;
}
public void setPublishTime(Long publishTime) {
this.publishTime = publishTime;
}
@JsonIgnore
public Account getAccount() {
return account;
}
@JsonProperty
public void setAccount(Account account) {
this.account = account;
}
public String getCoverURL() {
return coverURL;
}
public void setCoverURL(String coverURL) {
this.coverURL = coverURL;
}
}
|
package com.example.nicolas4.nicolasminesweeper;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class welcome extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
public void tInsClick (View view) {
Intent i = new Intent (this,instructions.class);
startActivity(i);
}
public void toGame (View view) {
Intent i = new Intent (this,game_screen.class);
startActivity(i);
}
}
|
import tester.Tester;
// represents a picture
interface IPicture {
// computes the width of this picture
int getWidth();
// computes the number of shapes in this picture
int countShapes();
// computes how deeply operations are nested in the construction of this picture
int comboDepth();
// reflects the picture down the middle like a mirror
IPicture mirror();
// produces a String representing the contents of this picture, and the steps
// to produce it
String pictureRecipe(int depth);
}
// represents an operation
interface IOperation {
// computes the total width of this Operation
int widthOfOperation();
// computes the count of shapes in this Operation
int shapeCountOfOperation();
// computes the combo depth of this Operation
int comboDepthOfOperation();
// mirrors the picture created by this operation
IOperation mirrorOperation();
// returns the recipe of this operation given a starting name and depth
String operationRecipe(int depth);
}
// represents a shape
class Shape implements IPicture {
String kind; // the type of shape
int size; // the size of the shape
Shape(String kind, int size) {
this.kind = kind;
this.size = size;
}
/* TEMPLATE
* FIELDS
* this.kind ... String
* this.size ... int
* METHODS
* this.getWidth() ... int
* this.countShapes() ... int
* this.comboDepth() ... int
* this.mirror() ... IPicture
* this.pictureRecipe(int depth) ... String
*/
public int getWidth() {
// computes the width of this Shape
return this.size;
}
// computes the count of shapes in this Shape
public int countShapes() {
return 1;
}
// computes the combo depth of this Shape
public int comboDepth() {
return 0;
}
// mirrors this Shape across the middle
public IPicture mirror() {
return new Shape(this.kind, this.size);
}
// returns the recipe of this Shape at given depth
public String pictureRecipe(int depth) {
return this.kind;
}
}
// represents a combo
class Combo implements IPicture {
String name; // the name of the combo
IOperation operation; // the operation that will take place
Combo(String name, IOperation operation) {
this.name = name;
this.operation = operation;
}
/* TEMPLATE
* FIELDS
* this.name ... String
* this.operation ... IOperation
* METHODS
* this.getWidth() ... int
* this.countShapes() ... int
* this.comboDepth() ... int
* this.mirror() ... IPicture
* this.pictureRecipe(int depth) ... String
* METHODS FOR FIELDS
* this.widthOfOperation() ... int
* this.shapeCountOfOperation() ... int
* this.comboDepthOfOperation() ... int
* this.mirrorOperation() ... IOperation
* this.operationRecipe(int depth) ... String
*/
public int getWidth() {
// computes the width of this Combo
return this.operation.widthOfOperation();
}
public int countShapes() {
return this.operation.shapeCountOfOperation();
}
// computes the combo depth of this Combo
public int comboDepth() {
return this.operation.comboDepthOfOperation();
}
// mirrors this combo across the middle
public IPicture mirror() {
return new Combo(this.name, this.operation.mirrorOperation());
}
// returns the recipe of a Combo
public String pictureRecipe(int depth) {
if (depth <= 0) {
return this.name;
}
else {
return this.operation.operationRecipe(depth);
}
}
}
// represents a scale operation
class Scale implements IOperation {
IPicture picture; // a picture
Scale(IPicture picture) {
this.picture = picture;
}
/* TEMPLATE
* FIELDS
* this.picture ... IPicture
* METHODS
* this.widthOfOperation() ... int
* this.shapeCountOfOperation() ... int
* this.comboDepthOfOperation() ... int
* this.mirrorOperation() ... IOperation
* this.operationRecipe(int depth) ... String
* METHODS FOR FIELDS
* this.getWidth() ... int
* this.countShapes() ... int
* this.comboDepth() ... int
* this.mirror() ... IPicture
* this.pictureRecipe(int depth) ... String
*/
// returns the width of this Scale operation
public int widthOfOperation() {
return 2 * this.picture.getWidth();
}
// computes the shape count of this Scale operation
public int shapeCountOfOperation() {
return this.picture.countShapes();
}
// computes the combo depth of this Scale operation
public int comboDepthOfOperation() {
return 1 + this.picture.comboDepth();
}
// mirrors this Scale operation
public IOperation mirrorOperation() {
return new Scale(this.picture.mirror());
}
// returns the operation recipe of this Scale operation
public String operationRecipe(int depth) {
if (depth == 1) {
return "scale(" + this.picture.pictureRecipe(0) + ")";
}
return "scale(" + this.picture.pictureRecipe(depth - 1) + ")";
}
}
// represents a beside operation
class Beside implements IOperation {
IPicture picture1; // the picture on the left
IPicture picture2; // the picture on the right
Beside(IPicture picture1, IPicture picture2) {
this.picture1 = picture1;
this.picture2 = picture2;
}
/* TEMPLATE
* FIELDS
* this.picture1 ... IPicture
* this.picture2 ... IPicture
* METHODS
* this.widthOfOperation() ... int
* this.shapeCountOfOperations() ... int
* this.comboDepthOfOperation() ... int
* this.mirrorOperation() ... IOperation
* this.operationRecipe(int depth) ... String
* METHODS FOR FIELDS
* this.getWidth() ... int
* this.countShapes() ... int
* this.comboDepth() ... int
* this.mirror() ... IPicture
* this.pictureRecipe(int depth) ... String
*/
// computes the width of this Beside operation
public int widthOfOperation() {
return this.picture1.getWidth() + this.picture2.getWidth();
}
// computes the shape count of this Beside Operation
public int shapeCountOfOperation() {
return this.picture1.countShapes() + this.picture2.countShapes();
}
// computes the combo depth of this Beside operation
public int comboDepthOfOperation() {
return 1 + Math.max(this.picture1.comboDepth(), this.picture2.comboDepth());
}
// mirrors this Beside operation
public IOperation mirrorOperation() {
return new Beside(this.picture2.mirror(), this.picture1.mirror());
}
// returns the operation recipe of this Beside operation
public String operationRecipe(int depth) {
if (depth == 1) {
return "beside(" + this.picture1.pictureRecipe(0) + ", " + this.picture2.pictureRecipe(0)
+ ")";
}
return "beside(" + this.picture1.pictureRecipe(depth - 1) + ", "
+ this.picture2.pictureRecipe(depth - 1) + ")";
}
}
// represents an overlay operation
class Overlay implements IOperation {
IPicture topPicture; // the picture on top
IPicture bottomPicture; // the picture on bottom
Overlay(IPicture topPicture, IPicture bottomPicture) {
this.topPicture = topPicture;
this.bottomPicture = bottomPicture;
}
/* TEMPLATE
* FIELDS
* this.topPicture ... IPicture
* this.bottomPicture ... IPicture
* METHODS
* this.widthOfOperation() ... int
* this.shapeCountOfOperations() ... int
* this.comboDepthOfOperation() ... int
* this.mirrorOperation() ... IOperation
* this.operationRecipe(int depth) ... String
* METHODS FOR FIELDS
* this.getWidth() ... int
* this.countShapes() ... int
* this.comboDepth() ... int
* this.mirror() ... IPicture
* this.pictureRecipe(int depth) ... String
*/
// computes the width of this Overlay operation
public int widthOfOperation() {
if (this.topPicture.getWidth() > this.bottomPicture.getWidth()) {
return this.topPicture.getWidth();
}
else {
return this.bottomPicture.getWidth();
}
}
// computes the count of shapes of this Overlay operation
public int shapeCountOfOperation() {
return this.topPicture.countShapes() + this.bottomPicture.countShapes();
}
// computes the combo depth of this Overlay operation
public int comboDepthOfOperation() {
return 1 + Math.max(this.topPicture.comboDepth(), this.bottomPicture.comboDepth());
}
// mirrors this Overlay operation
public IOperation mirrorOperation() {
return new Overlay(this.topPicture.mirror(), this.bottomPicture.mirror());
}
// returns the operation recipe of this Overlay operation
public String operationRecipe(int depth) {
if (depth == 1) {
return "overlay(" + this.topPicture.pictureRecipe(0) + ", "
+ this.bottomPicture.pictureRecipe(0) + ")";
}
return "overlay(" + this.topPicture.pictureRecipe(depth - 1) + ", "
+ this.bottomPicture.pictureRecipe(depth - 1) + ")";
}
}
// represents examples and tests of picture
class ExamplesPicture {
// explicit examples
IPicture circle = new Shape("circle", 20);
IPicture square = new Shape("square", 30);
IPicture bigCircle = new Combo("big circle", new Scale(this.circle));
IPicture squareOnCircle = new Combo("square on circle", new Overlay(this.square, this.bigCircle));
IPicture doubledSquareOnCircle = new Combo("doubled square on circle",
new Beside(this.squareOnCircle, this.squareOnCircle));
// examples of each operation
IPicture scaleExample = new Combo("big square", new Scale(this.square));
IPicture overlayExample = new Combo("circle on square", new Overlay(this.circle, this.square));
IPicture besideExample = new Combo("two squares", new Beside(this.square, this.square));
IPicture twoBesideExample = new Combo("three squares",
new Beside(this.square, this.besideExample));
IPicture squareNextToCircle = new Combo("square next to circle",
new Beside(this.square, this.circle));
IPicture doubleCircle = new Combo("double circle", new Beside(this.circle, this.circle));
IPicture squareNextToDoubleCircle = new Combo("square next to double circle",
new Beside(this.square, this.doubleCircle));
IPicture biggerCircle = new Combo("bigger circle", new Scale(this.bigCircle));
IPicture doubleCircleNextToSquare = new Combo("double circle next to square",
new Beside(this.doubleCircle, this.square));
IOperation bigCircleOperation = new Scale(this.circle);
IOperation squareOnCircleOperation = new Overlay(this.square, this.bigCircle);
IOperation doubledSquareOnCircleOperation = new Beside(this.squareOnCircle, this.squareOnCircle);
IOperation twoBesideExampleOperation = new Beside(this.square, this.besideExample);
IOperation squareNextToCircleOperation = new Beside(this.square, this.circle);
IOperation squareNextToDoubleCircleOperation = new Beside(this.square, this.doubleCircle);
IOperation biggerCircleOperation = new Scale(this.bigCircle);
IOperation doubleCircleNextToSquareOperation = new Beside(this.doubleCircle, this.square);
// tests for getWidth
boolean testGetWidth(Tester t) {
return t.checkExpect(this.circle.getWidth(), 20) && t.checkExpect(this.square.getWidth(), 30)
&& t.checkExpect(this.bigCircle.getWidth(), 40)
&& t.checkExpect(this.squareOnCircle.getWidth(), 40)
&& t.checkExpect(this.doubledSquareOnCircle.getWidth(), 80)
&& t.checkExpect(this.twoBesideExample.getWidth(), 90);
}
// tests for widthOfOperation
boolean testWidthOfOperation(Tester t) {
return t.checkExpect(this.bigCircleOperation.widthOfOperation(), 40)
&& t.checkExpect(this.squareOnCircleOperation.widthOfOperation(), 40)
&& t.checkExpect(this.doubledSquareOnCircleOperation.widthOfOperation(), 80)
&& t.checkExpect(this.twoBesideExampleOperation.widthOfOperation(), 90);
}
// tests for countShapes
boolean testCountShapes(Tester t) {
return t.checkExpect(this.circle.countShapes(), 1)
&& t.checkExpect(this.bigCircle.countShapes(), 1)
&& t.checkExpect(this.squareOnCircle.countShapes(), 2)
&& t.checkExpect(this.doubledSquareOnCircle.countShapes(), 4)
&& t.checkExpect(this.twoBesideExample.countShapes(), 3)
&& t.checkExpect(this.doubleCircleNextToSquare.countShapes(), 3);
}
// tests for shapecountOfOperation
boolean testShapeCountOfOperation(Tester t) {
return t.checkExpect(this.bigCircleOperation.shapeCountOfOperation(), 1)
&& t.checkExpect(this.squareOnCircleOperation.shapeCountOfOperation(), 2)
&& t.checkExpect(this.doubledSquareOnCircleOperation.shapeCountOfOperation(), 4)
&& t.checkExpect(this.twoBesideExampleOperation.shapeCountOfOperation(), 3)
&& t.checkExpect(this.doubleCircleNextToSquareOperation.shapeCountOfOperation(), 3);
}
// tests for comboDepth
boolean testComboDepth(Tester t) {
return t.checkExpect(this.circle.comboDepth(), 0)
&& t.checkExpect(this.bigCircle.comboDepth(), 1)
&& t.checkExpect(this.twoBesideExample.comboDepth(), 2)
&& t.checkExpect(this.doubledSquareOnCircle.comboDepth(), 3)
&& t.checkExpect(this.doubleCircleNextToSquare.comboDepth(), 2);
}
// tests for comboDepthOfOperation
boolean testComboDepthOfOperation(Tester t) {
return t.checkExpect(this.bigCircleOperation.comboDepthOfOperation(), 1)
&& t.checkExpect(this.squareOnCircleOperation.comboDepthOfOperation(), 2)
&& t.checkExpect(this.doubledSquareOnCircleOperation.comboDepthOfOperation(), 3)
&& t.checkExpect(this.twoBesideExampleOperation.comboDepthOfOperation(), 2);
}
// tests for mirror
boolean testMirror(Tester t) {
return t.checkExpect(this.circle.mirror(), this.circle)
&& t.checkExpect(this.squareOnCircle.mirror(), this.squareOnCircle)
&& t.checkExpect(this.doubledSquareOnCircle.mirror(), this.doubledSquareOnCircle)
&& t.checkExpect(this.twoBesideExample.mirror(),
new Combo("three squares", new Beside(this.besideExample, this.square)))
&& t.checkExpect(this.squareNextToCircle.mirror(),
new Combo("square next to circle", new Beside(this.circle, this.square)))
&& t.checkExpect(this.squareNextToDoubleCircle.mirror(),
new Combo("square next to double circle", new Beside(this.doubleCircle, this.square)));
}
// tests for mirrorOperation
boolean testMirrorOperation(Tester t) {
return t.checkExpect(this.bigCircleOperation.mirrorOperation(), this.bigCircleOperation)
&& t.checkExpect(this.squareOnCircleOperation.mirrorOperation(),
this.squareOnCircleOperation)
&& t.checkExpect(this.doubledSquareOnCircleOperation.mirrorOperation(),
this.doubledSquareOnCircleOperation)
&& t.checkExpect(this.twoBesideExampleOperation.mirrorOperation(),
new Beside(this.besideExample, this.square))
&& t.checkExpect(this.squareNextToCircleOperation.mirrorOperation(),
new Beside(this.circle, this.square))
&& t.checkExpect(this.squareNextToDoubleCircleOperation.mirrorOperation(),
new Beside(this.doubleCircle, this.square));
}
// tests for pictureRecipe
boolean testPictureRecipe(Tester t) {
return t.checkExpect(this.circle.pictureRecipe(-1), "circle")
&& t.checkExpect(this.circle.pictureRecipe(0), "circle")
&& t.checkExpect(this.circle.pictureRecipe(1), "circle")
&& t.checkExpect(this.circle.pictureRecipe(2), "circle")
&& t.checkExpect(this.doubledSquareOnCircle.pictureRecipe(2),
"beside(overlay(square, big circle), overlay(square, big circle))")
&& t.checkExpect(this.doubledSquareOnCircle.pictureRecipe(3),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))")
&& t.checkExpect(this.doubledSquareOnCircle.pictureRecipe(10),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))");
}
// tests for operationRecipe
boolean testOperationRecipe(Tester t) {
// only calls this function when the depth is greater than 0, so no need to test
// for
// negative or 0 depth
return t.checkExpect(this.doubledSquareOnCircleOperation.operationRecipe(1),
"beside(square on circle, square on circle)")
&& t.checkExpect(this.doubledSquareOnCircleOperation.operationRecipe(2),
"beside(overlay(square, big circle), overlay(square, big circle))")
&& t.checkExpect(this.doubledSquareOnCircleOperation.operationRecipe(3),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))")
&& t.checkExpect(this.doubledSquareOnCircleOperation.operationRecipe(10),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))")
&& t.checkExpect(this.bigCircleOperation.operationRecipe(1), "scale (circle)")
&& t.checkExpect(this.bigCircleOperation.operationRecipe(2), "scale (circle)")
&& t.checkExpect(this.bigCircleOperation.operationRecipe(10), "scale (circle)")
&& t.checkExpect(this.biggerCircleOperation.operationRecipe(1), "scale (big circle)")
&& t.checkExpect(this.biggerCircleOperation.operationRecipe(2), "scale (scale (circle))")
&& t.checkExpect(this.biggerCircleOperation.operationRecipe(3), "scale (scale (circle))")
&& t.checkExpect(this.biggerCircleOperation.operationRecipe(10), "scale (scale (circle))");
}
}
|
package com.example.myreadproject8.ui.presenter.book;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import androidx.core.app.ActivityCompat;
import com.example.myreadproject8.Application.App;
import com.example.myreadproject8.Application.SysManager;
import com.example.myreadproject8.R;
import com.example.myreadproject8.entity.Setting;
import com.example.myreadproject8.enums.BookcaseStyle;
import com.example.myreadproject8.greendao.entity.Book;
import com.example.myreadproject8.greendao.entity.Chapter;
import com.example.myreadproject8.greendao.service.BookGroupService;
import com.example.myreadproject8.greendao.service.BookService;
import com.example.myreadproject8.greendao.service.ChapterService;
import com.example.myreadproject8.ui.activity.IndexActivity;
import com.example.myreadproject8.ui.adapter.bookcase.ReadAdapter;
import com.example.myreadproject8.ui.adapter.bookcase.ReadDragAdapter;
import com.example.myreadproject8.ui.dialog.BookGroupDialog;
import com.example.myreadproject8.ui.dialog.DialogCreator;
import com.example.myreadproject8.ui.fragment.bookcase.BookcaseFragment;
import com.example.myreadproject8.ui.fragment.bookcase.ReadFragment;
import com.example.myreadproject8.ui.presenter.base.BasePresenter;
import com.example.myreadproject8.util.net.crawler.base.ReadCrawler;
import com.example.myreadproject8.util.net.crawler.read.ReadCrawlerUtil;
import com.example.myreadproject8.util.net.webapi.api.CommonApi;
import com.example.myreadproject8.util.net.webapi.callback.ResultCallback;
import com.example.myreadproject8.util.read.notification.NotificationUtil;
import com.example.myreadproject8.util.sharedpre.SharedPreUtils;
import com.example.myreadproject8.util.toast.ToastUtils;
import com.example.myreadproject8.widget.custom.DragSortGridView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* created by ycq on 2021/4/24 0024
* describe:
*/
public class ReadPresenter implements BasePresenter {
private final ReadFragment mReadFragment;
private final ArrayList<Book> mBooks = new ArrayList<>();//书目数组
private ReadAdapter mReadAdapter;
private final BookService mBookService;
private final ChapterService mChapterService;
private final IndexActivity mMainActivity;
private Setting mSetting;
private final List<Book> errorLoadingBooks = new ArrayList<>();
private int finishLoadBookCount = 0;
private NotificationUtil notificationUtil;//通知工具类
private ExecutorService es = Executors.newFixedThreadPool(1);//更新/下载线程池
@SuppressLint("HandlerLeak")
public final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
if (!App.isDestroy(mMainActivity)) {
App.runOnUiThread(() -> mReadAdapter.notifyDataSetChanged());
finishLoadBookCount++;
mReadFragment.getSrlContent().finishRefresh();
}
break;
case 2:
mReadFragment.getSrlContent().finishRefresh();
break;
case 3:
mReadAdapter.notifyDataSetChanged();
break;
case 4:
showErrorLoadingBooks();
break;
}
}
};
//构造方法
public ReadPresenter(ReadFragment readFragment) {
mReadFragment = readFragment;//全部书籍书架
mBookService = BookService.getInstance();//书籍数据库服务类
mChapterService = ChapterService.getInstance();//章节数据库服务类
mMainActivity = (IndexActivity) (mReadFragment.getActivity());//主活动
mSetting = SysManager.getSetting();//设置类
}
@Override
public void start() {
mSetting.setBookcaseStyle(BookcaseStyle.threePalaceMode);//
notificationUtil = NotificationUtil.getInstance();//初始化通知工具
getData();
//是否启用下拉刷新(默认启用)
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mReadFragment.getSrlContent().setEnableRefresh(false);
}
//设置是否启用内容视图拖动效果
mReadFragment.getSrlContent().setEnableHeaderTranslationContent(false);
//设置刷新监听器
mReadFragment.getSrlContent().setOnRefreshListener(refreshlayout -> initNoReadNum());
//长按事件监听
mReadFragment.getGvBook().setOnItemLongClickListener((parent, view, position, id) -> false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//滑动监听器
mReadFragment.getGvBook().getmScrollView().setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
mReadFragment.getSrlContent().setEnableRefresh(scrollY == 0);
});
}
}
//获取数据
public void getData() {
init();
if (mSetting.isRefreshWhenStart()) {
mHandler.postDelayed(this::initNoReadNum, 500);
}
}
//初始化
public void init() {
initBook();
if (mBooks.size() == 0) {
mReadFragment.getGvBook().setVisibility(View.GONE);
mReadFragment.getLlNoDataTips().setVisibility(View.VISIBLE);
} else {
if (mReadAdapter == null) {
mReadAdapter = new ReadDragAdapter(mMainActivity, R.layout.gridview_book_item, mBooks, this);
mReadFragment.getGvBook().setNumColumns(3);
mReadFragment.getGvBook().setDragModel(-1);
mReadFragment.getGvBook().setTouchClashparent(mMainActivity.getViewPagerMain());
mReadFragment.getGvBook().setOnDragSelectListener(new DragSortGridView.OnDragSelectListener() {
@Override
public void onDragSelect(View mirror) {
mirror.setScaleX(1.05f);
mirror.setScaleY(1.05f);
}
@Override
public void onPutDown(View itemView) {
}
});
mReadFragment.getGvBook().setAdapter(mReadAdapter);
} else {
mReadAdapter.notifyDataSetChanged();
}
mReadFragment.getLlNoDataTips().setVisibility(View.GONE);
mReadFragment.getGvBook().setVisibility(View.VISIBLE);
}
}
//初始化书籍
private void initBook() {
mBooks.clear();
mBooks.addAll(mBookService.getReadBooks());
if (mSetting.getSortStyle() == 1) {
Collections.sort(mBooks, (o1, o2) -> {
if (o1.getLastReadTime() < o2.getLastReadTime()){
return 1;
}else if (o1.getLastReadTime() > o2.getLastReadTime()){
return -1;
}
return 0;
});
}else if (mSetting.getSortStyle() == 2){
Collections.sort(mBooks, (o1, o2) -> {
Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
return cmp.compare(o1.getName(), o2.getName());
});
}
for (int i = 0; i < mBooks.size(); i++) {
int sort = mBooks.get(i).getSortCode();
if (sort != i + 1) {
mBooks.get(i).setSortCode(i + 1);
mBookService.updateEntity(mBooks.get(i));
}
}
}
//检查书籍更新
public void initNoReadNum() {
errorLoadingBooks.clear();
finishLoadBookCount = 0;
for (Book book : mBooks) {
mReadAdapter.getIsLoading().put(book.getId(), true);
}
if (mBooks.size() > 0) {
mHandler.sendMessage(mHandler.obtainMessage(3));
}
for (final Book book : mBooks) {
if ("本地书籍".equals(book.getType()) || book.getIsCloseUpdate()) {
mReadAdapter.getIsLoading().put(book.getId(), false);
mHandler.sendMessage(mHandler.obtainMessage(1));
continue;
}
Thread update = new Thread(() -> {
final ArrayList<Chapter> mChapters = (ArrayList<Chapter>) mChapterService.findBookAllChapterByBookId(book.getId());
final ReadCrawler mReadCrawler = ReadCrawlerUtil.getReadCrawler(book.getSource());
CommonApi.getBookChapters(book.getChapterUrl(), mReadCrawler, true, new ResultCallback() {
@Override
public void onFinish(Object o, int code) {
ArrayList<Chapter> chapters = (ArrayList<Chapter>) o;
int noReadNum = chapters.size() - book.getChapterTotalNum();
book.setNoReadNum(Math.max(noReadNum, 0));
book.setNewestChapterTitle(chapters.get(chapters.size() - 1).getTitle());
mReadAdapter.getIsLoading().put(book.getId(), false);
mChapterService.updateAllOldChapterData(mChapters, chapters, book.getId());
mHandler.sendMessage(mHandler.obtainMessage(1));
mBookService.updateEntity(book);
}
@Override
public void onError(Exception e) {
mReadAdapter.getIsLoading().put(book.getId(), false);
errorLoadingBooks.add(book);
mHandler.sendMessage(mHandler.obtainMessage(1));
}
});
});
es.submit(update);
}
App.getmApplication().newThread(() -> {
while (true) {
if (finishLoadBookCount == mBooks.size()) {
mHandler.sendMessage(mHandler.obtainMessage(4));
mHandler.sendMessage(mHandler.obtainMessage(2));
break;
}
}
});
}
/**
* 显示更新失败的书籍信息
*/
private void showErrorLoadingBooks() {
StringBuilder s = new StringBuilder();
for (Book book : errorLoadingBooks) {
s.append(book.getName());
s.append("、");
}
if (errorLoadingBooks.size() > 0) {
s.deleteCharAt(s.lastIndexOf("、"));
s.append(" 更新失败");
ToastUtils.showError(s.toString());
}
}
/**
* 销毁
*/
public void destroy() {
notificationUtil.cancelAll();
for (int i = 0; i < 13; i++) {
mHandler.removeMessages(i + 1);
}
}
}
|
package com.brunocalou.guitarstudio;
/**
* Created by bruno on 05/02/16.
*/
public class AudioProcessorException extends Exception {
public AudioProcessorException(String message) {
super(message);
}
public AudioProcessorException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public AudioProcessorException(Throwable throwable) {
super(throwable);
}
public AudioProcessorException() {
}
}
|
package utils;
public class Log
{
public static void i(String str1, String str2)
{
System.out.println(String.valueOf(str1) + ": " + String.valueOf(str2));
}
public static void e(String str1, String str2)
{
System.err.println(String.valueOf(str1) + ": " + String.valueOf(str2));
}
}
|
package com.zhonghuilv.shouyin.mapper;
import com.zhonghuilv.shouyin.common.CommonMapper;
import com.zhonghuilv.shouyin.pojo.ArticleType;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArticleTypeMapper extends CommonMapper<ArticleType> {
} |
/**
* Write a description of interface BusinessClass here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface BusinessClass
{
/**
* The base fares and charges for business class passengers
*/
public static final int CAPETOWN_BASE_FARE = 1000;
public static final int GLASGOW_BASE_FARE = 800;
public static final int TYPE_CHARGE = 20;
/**
* The start number for business class Passengers. This should result in
* passenger numbers like 2001, 2002, etc (see coursework spec. )
*/
public static final int START_NUMBER = 2000;
}
|
package com.wcy.netty.protocol.request;
import com.wcy.netty.protocol.Packet;
import lombok.Data;
import static com.wcy.netty.protocol.command.Command.WX_MESSAGE_REQUEST;
@Data
public class WxMessageRequestPacket extends Packet {
private String packetId;
private String message;
@Override
public Byte getCommand() {
return WX_MESSAGE_REQUEST;
}
}
|
package br.com.maikel.poc.bold.facebold.factory;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import br.com.maikel.poc.bold.facebold.entity.Post;
import br.com.maikel.poc.bold.facebold.response.PostResponse;
@Component
public class PostResponseFactory {
public PostResponse create(Post post) {
PostResponse resp = new PostResponse();
resp.setId(post.getId());
resp.setText(post.getText());
resp.setUserId(post.getUser().getId());
resp.setUserName(post.getUser().getName());
resp.setDate(post.getDate());
this.populateComments(post, resp);
this.populateActions(post, resp);
return resp;
}
private void populateActions(Post post, PostResponse resp) {
if(post.getActions() == null || post.getActions().isEmpty())
return;
post.getActions().forEach(act -> {
resp.addAction(act.getAction().name(), act.getUser().getId(), act.getUser().getName());
});
}
private void populateComments(Post post, PostResponse resp) {
if(post.getComments() == null || post.getComments().isEmpty())
return;
post.getComments().forEach(com -> {
resp.addComments(com.getText(), com.getUser().getId(), com.getUser().getName(), com.getDate());
});
}
public List<PostResponse> createMany(List<Post> posts){
List<PostResponse> responses = new ArrayList<>();
posts.forEach(post -> {
responses.add(create(post));
});
return responses;
}
}
|
public class Vehicle extends TaxableItem {
/** The cost of the vehicle to the dealer. */
private double dealerCost;
/** The amount the dealer marks up the price. */
private double dealerMarkup;
/**
* Constructs a new Vehicle, given dealer cost, dealer markup, and tax rate.
*
* @param dealerCost The cost of the vehicle to the dealer.
* @param dealerMarkup The amount the dealer marks up the price.
* @param taxRate The rate at which the vehicle is taxed.
*/
public Vehicle(double dealerCost, double dealerMarkup, double taxRate) {
super(taxRate);
this.dealerCost = dealerCost;
this.dealerMarkup = dealerMarkup;
}
/**
* Returns the list price of an item.
*
* @return The list price.
*/
public double getListPrice() {
return dealerCost + dealerMarkup;
}
/**
* Changes the dealer markup on a vehicle.
*
* @param dealerMarkup The new dealer markup value.
*/
public void changeMarkup(double dealerMarkup) {
this.dealerMarkup = dealerMarkup;
}
/**
* Gets a String representation of this object.
*
* @return A string representation of this object.
*/
public String toString() {
return String.format("Vehicle [dealerCost=%f, dealerMarkup=%f, " +
"taxRate=%f, listPrice=%f, purchasePrice=%f]",
dealerCost, dealerMarkup, getTaxRate(),
getListPrice(), purchasePrice());
}
} |
/*
* Copyright 1995-2014 Caplin Systems Ltd
*/
package com.caplin.datasource;
public class PeerStatusEventImpl implements PeerStatusEvent
{
private final PeerStatus status;
public PeerStatusEventImpl(PeerStatus status)
{
this.status = status;
}
@Override
public Peer getPeer()
{
// TODO Auto-generated method stub
return null;
}
@Override
public PeerStatus getPeerStatus()
{
return status;
}
}
|
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import model.Student;
public class StudentJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
System.out.println("Connecting to database");
// 1. Driver
// REFLECTION API
Class.forName("com.mysql.jdbc.Driver");
// 2. Connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sa44", "root", "password");
// 3. Statement
Statement st = connection.createStatement();
// 4. Execute the query
ResultSet rs = st.executeQuery("SELECT * FROM sa44.student;");
// 5. Process
while (rs.next()) {
Student s = new Student();
s.setId(rs.getInt("id"));
s.setName(rs.getString("name"));
s.setNickName(rs.getString("nick_name"));
s.setFee(rs.getDouble("fee"));
System.out.println(s.toString());
}
// 6. Close
st.close();
connection.close();
}
}
|
package test.io;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Created by maguoqiang on 2016/5/6.
* NIO测试
*/
public class NioDemo {
@Test
public void testNioOne()throws IOException{
FileInputStream fin=new FileInputStream("E:\\data\\env\\env.properties");//源文件
FileOutputStream fos=new FileOutputStream("E:\\data\\test.properties");
FileChannel fc=fin.getChannel();
FileChannel fi=fos.getChannel();
//要从channel中读取数据,必须使用buffer
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
while (true){
byteBuffer.clear();
int len=fc.read(byteBuffer);
if (len==-1){
break;
}
byteBuffer.flip();
fi.write(byteBuffer);
}
fc.close();
fi.close();
}
}
|
package retrogene.discover;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import htsjdk.samtools.SAMFormatException;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.cram.ref.ReferenceSource;
import htsjdk.samtools.util.IntervalTree;
import htsjdk.samtools.util.IntervalTree.Node;
import retrogene.gene.GenesLoader.Exon;
import retrogene.utilities.CalculateInsertDistribution.NullInsertDistribution;
import retrogene.utilities.CheckReadStatus;
import retrogene.utilities.CheckReadStatus.Direction;
import retrogene.utilities.QualityChecker;
public class BamParser implements Closeable {
private SamReader bamReader;
private Double cutoffPercentile;
private Map<SAMRecord,Boolean> foundReads;
public BamParser(File bamFile, File bamIndex, ReferenceSource refSource, double cutoffPercentile) throws NullInsertDistribution, IOException {
this.cutoffPercentile = cutoffPercentile;
bamReader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(SamInputResource.of(bamFile).index(bamIndex));
foundReads = new HashMap<SAMRecord,Boolean>();
}
public Map<SAMRecord,Boolean> getFoundReads() {
return foundReads;
}
public int findDPs (String chr, Node<Exon> exon, IntervalTree<Exon> exons, boolean isRescue) {
SAMRecordIterator samItr;
if (isRescue) {
samItr = bamReader.queryOverlapping(chr, exon.getStart(), exon.getEnd());
} else {
samItr = bamReader.queryContained(chr, exon.getStart(), exon.getEnd());
}
Set<SAMRecord> DPs = new HashSet<SAMRecord>();
int totalReadsParsed = 0;
while (samItr.hasNext() && totalReadsParsed <= 1000) {
SAMRecord currentRecord = samItr.next();
totalReadsParsed++;
boolean isDP = CheckReadStatus.checkDPStatus(currentRecord, cutoffPercentile);
if (isDP) {
DPs.add(currentRecord);
}
}
samItr.close();
int foundDP = 0;
for (SAMRecord currentRecord : DPs) {
try {
SAMRecord currentMate = bamReader.queryMate(currentRecord);
if (currentMate != null) {
boolean isDP = CheckReadStatus.checkDPStatus(currentMate, cutoffPercentile);
if (isRescue == true || (isRescue == false && isDP)) {
Iterator<Node<Exon>> foundExons = exons.overlappers(currentMate.getAlignmentStart(), currentMate.getAlignmentEnd());
while (foundExons.hasNext()) {
Node<Exon> foundExon = foundExons.next();
int foundExonNum = foundExon.getValue().getExonNum();
int exonNum = exon.getValue().getExonNum();
Set<String> foundTranscripts = foundExon.getValue().getTranscripts();
Set<String> transcripts = exon.getValue().getTranscripts();
int distance;
if (foundExon.getRelationship(exon) == Node.HAS_LESSER_PART) {
distance = exon.getStart() - foundExon.getEnd();
} else {
distance = foundExon.getStart() - exon.getEnd();
}
if (exonNum != foundExonNum && checkTranscripts(foundTranscripts, transcripts) && distance > cutoffPercentile) {
foundDP++;
//Only add a read once
foundReads.put(currentRecord, false);
foundReads.put(currentMate, false);
break;
}
}
}
}
} catch (SAMFormatException e) {
continue;
}
}
return foundDP;
}
public int findSRs (String chr, int breakpoint, Direction direction, IntervalTree<Exon> exons) throws IOException {
SAMRecordIterator samItr = bamReader.queryOverlapping(chr, breakpoint, breakpoint);
int totalReadsParsed = 0;
int totalSRs = 0;
QualityChecker checker = new QualityChecker();
while (samItr.hasNext() && totalReadsParsed <= 1000) {
SAMRecord currentRecord = samItr.next();
totalReadsParsed++;
boolean isSR = CheckReadStatus.checkSRStatus(currentRecord, breakpoint, direction, checker);
if (isSR && foundReads.containsKey(currentRecord) == false) {
totalSRs++;
foundReads.put(currentRecord, true);
}
}
samItr.close();
return totalSRs;
}
public void close() throws IOException {
// bamWriter.close();
bamReader.close();
}
private boolean checkTranscripts(Set<String> foundTranscripts, Set<String> currentTranscripts) {
boolean found = false;
for (String t : currentTranscripts) {
if (foundTranscripts.contains(t)) {
found = true;
break;
}
}
return found;
}
}
|
package com.maia.bank.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.maia.bank.domain.Banco;
@Repository
public interface BancoRepository extends JpaRepository<Banco, Long> {
Optional<Banco> findByNumero(Integer numero);
}
|
package com.budget.serviceImpl;
import com.budget.service.MyUserService;
public class MyUsersServiceImpl implements MyUserService
{
@Override
public void MyUSers()
{
// TODO Auto-generated method stub
}
}
|
package javabasico.aula15labs;
import java.util.Scanner;
/**
* @author Kim Tsunoda
* Objetivo Um posto está vendendo combustíveis com a seguinte tabela de descontos:
*/
public class Exercicio21 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("Digite o tipo de combustivel: A- Alcool ou G-Gasolina: ");
String combustivel = scan.next();
System.out.println ("Digite a quantidade de combustivel: ");
double quantidade = scan.nextDouble();
double totalBruto = 0;
double desconto = 0;
double totalLiquido = 0;
if (combustivel.equalsIgnoreCase("a")) {
if (quantidade <= 20) {
totalBruto = (quantidade * 1.9);
desconto = totalBruto * 0.03;
totalLiquido = totalBruto - desconto;
System.out.println("Valor a Pagar : " + totalLiquido);
} else if (quantidade > 20) {
totalBruto = (quantidade * 1.9);
desconto = totalBruto * 0.05;
totalLiquido = totalBruto - desconto;
System.out.println("Valor a Pagar : " + totalLiquido);
}
} else if (combustivel.equalsIgnoreCase("g")) {
if (quantidade <= 20) {
totalBruto = (quantidade * 2.5);
desconto = totalBruto * 0.04;
totalLiquido = totalBruto - desconto;
System.out.println("Valor a Pagar : " + totalLiquido);
} else if (quantidade > 20) {
totalBruto = (quantidade * 2.5);
desconto = totalBruto * 0.06;
totalLiquido = totalBruto - desconto;
System.out.println("Valor a Pagar : " + totalLiquido);
}
}
}
} |
package net.adoptopenjdk.bumblebench.examples;
public final class LargeArrayGenerator {
public static long[] generate(long state, final long[] data)
{
state = (state & 0x1FFFFFFL) + 1L;
for (int i = 0; i < data.length; i++) {
data[i] = (state = 0xC6BC279692B5CC8BL - (state << 35 | state >>> 29));
}
return data;
}
public static int[] generate(int stateA, int stateB, final int[] data)
{
for (int i = 0; i < data.length; i++)
{
final int s = (stateA += 0xC1C64E6D);
int x = (s ^ s >>> 17) * ((stateB += (s | -s) >> 31 & 0x9E3779BB) >>> 12 | 1);
x = (x ^ x >>> 16) * 0xAC451;
data[i] = (x ^ x >>> 15);
}
return data;
}
}
|
package com.module.helpers;
import com.module.model.entity.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class WordDocumentGenerator {
public static void generateWordReport(VeteranEntity veteranEntity, File file) {
if (veteranEntity != null && file != null)
try {
XWPFDocument document = new XWPFDocument(WordDocumentGenerator.class.getResourceAsStream("/shablon.docx"));
/** ---Title Paragraph--- */
XWPFParagraph titleParagraph = document.createParagraph();
titleParagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleText = titleParagraph.createRun();
titleText.setFontFamily("Times New Roman");
titleText.setFontSize(16);
titleText.setBold(true);
titleText.setText("УЧЕТНАЯ КАРТОЧКА");
/** ---Name Paragraph--- */
String name = "";
name += veteranEntity.getSecondName() + " " + veteranEntity.getFirstName() + " " + veteranEntity.getMiddleName();
if (!name.equals("")) {
XWPFParagraph nameParagraph = document.createParagraph();
nameParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun nameLabel = nameParagraph.createRun();
nameLabel.setFontFamily("Times New Roman");
nameLabel.setFontSize(14);
nameLabel.setText("Фамилия, имя, отчество: ");
XWPFRun nameValue = nameParagraph.createRun();
nameValue.setFontFamily("Times New Roman");
nameValue.setFontSize(14);
nameValue.setBold(true);
nameValue.setCapitalized(true);
nameValue.setText(name);
}
/** ---Birth Paragraph---*/
if (veteranEntity.getDateOfBirth() != null) {
XWPFParagraph birthParagraph = document.createParagraph();
birthParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun birthLaber = birthParagraph.createRun();
birthLaber.setFontFamily("Times New Roman");
birthLaber.setFontSize(14);
birthLaber.setText("Дата рождения: ");
XWPFRun birthValue = birthParagraph.createRun();
birthValue.setFontFamily("Times New Roman");
birthValue.setFontSize(14);
birthValue.setBold(true);
birthValue.setCapitalized(true);
birthValue.setText(veteranEntity.getDateOfBirth().toString());
}
/** ---Rank Paragraph---*/
if (veteranEntity.getMilitaryRank() != null) {
XWPFParagraph rankParagraph = document.createParagraph();
rankParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun rankLabel = rankParagraph.createRun();
rankLabel.setFontFamily("Times New Roman");
rankLabel.setFontSize(14);
rankLabel.setText("Воинское звание: ");
XWPFRun rankValue = rankParagraph.createRun();
rankValue.setFontFamily("Times New Roman");
rankValue.setFontSize(14);
rankValue.setBold(true);
rankValue.setText(veteranEntity.getMilitaryRank().getName());
}
/** ---MilitaryTerm Paragraph---*/
if (veteranEntity.getMilitaryTerms().size() > 0) {
String term = "";
MilitaryTermEntity militaryTermEntity = veteranEntity.getMilitaryTerms().get(veteranEntity.getMilitaryTerms().size() - 1);
term += !militaryTermEntity.getStartOfMilitaryService().toString().equals("") ? "c " + militaryTermEntity.getStartOfMilitaryService().toString() : "";
term += !militaryTermEntity.getEndOfMilitaryService().toString().equals("") ? " по " + militaryTermEntity.getEndOfMilitaryService().toString() : "";
term += !militaryTermEntity.getCountry().equals("") ? ", " + militaryTermEntity.getCountry() : "";
term += !militaryTermEntity.getLocality().equals("") ? ", " + militaryTermEntity.getLocality() : "";
term += !militaryTermEntity.getUnit().equals("") ? ", " + militaryTermEntity.getUnit() : "";
term += !veteranEntity.getPosition().equals("") ? ", " + veteranEntity.getPosition() : "";
if (!term.equals("")) {
XWPFParagraph termParagraph = document.createParagraph();
termParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun termLabel = termParagraph.createRun();
termLabel.setFontFamily("Times New Roman");
termLabel.setFontSize(14);
termLabel.setText("Период и место прохождения службы: ");
XWPFRun termValue = termParagraph.createRun();
termValue.setFontFamily("Times New Roman");
termValue.setFontSize(14);
termValue.setBold(true);
termValue.setText(term);
}
}
/** ---Honors Paragraph---*/
if (veteranEntity.getVeteranHonors().size() > 0) {
XWPFParagraph honorParagraph = document.createParagraph();
honorParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun honorLabel = honorParagraph.createRun();
honorLabel.setFontFamily("Times New Roman");
honorLabel.setFontSize(14);
honorLabel.setText("Награды: ");
for (VeteranHonorEntity veteranHonor : veteranEntity.getVeteranHonors()) {
if (veteranHonor.getHonor().getName() != null) {
XWPFRun honorValue = honorParagraph.createRun();
honorValue.setFontFamily("Times New Roman");
honorValue.setFontSize(14);
honorValue.setBold(true);
honorValue.setText(veteranHonor.getHonor().getName() + "; ");
}
}
}
/** ---Wounds Type Paragraph---*/
if (veteranEntity.getWounds().size() > 0) {
XWPFParagraph woundParagraph = document.createParagraph();
woundParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun woundLabel = woundParagraph.createRun();
woundLabel.setFontFamily("Times New Roman");
woundLabel.setFontSize(14);
woundLabel.setText("Ранения: ");
for (VeteranWoundEntity wound : veteranEntity.getWounds()) {
if (wound.getWoundType().getType() != null) {
XWPFRun woundTypeValue = woundParagraph.createRun();
woundTypeValue.setFontFamily("Times New Roman");
woundTypeValue.setFontSize(14);
woundTypeValue.setBold(true);
woundTypeValue.setText(wound.getWoundType().getType() + "; ");
}
}
}
/** ---Wounds Disability Paragraph---*/
if (veteranEntity.getWounds().size() > 0) {
XWPFParagraph woundParagraph = document.createParagraph();
woundParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun woundLabel = woundParagraph.createRun();
woundLabel.setFontFamily("Times New Roman");
woundLabel.setFontSize(14);
woundLabel.setText("Инвалидности: ");
for (VeteranWoundEntity wound : veteranEntity.getWounds()) {
if (wound.getWoundDisability().getDisability() != null) {
XWPFRun woundDisabilityValue = woundParagraph.createRun();
woundDisabilityValue.setFontFamily("Times New Roman");
woundDisabilityValue.setFontSize(14);
woundDisabilityValue.setBold(true);
woundDisabilityValue.setText(wound.getWoundType().getType() + "; ");
}
}
}
if (veteranEntity.getDocuments().size()>0){
XWPFParagraph documentParagraph = document.createParagraph();
documentParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun documentLabel = documentParagraph.createRun();
documentLabel.setFontFamily("Times New Roman");
documentLabel.setFontSize(14);
documentLabel.setText("Документы: ");
for (DocumentEntity documentEntity : veteranEntity.getDocuments()){
XWPFRun documentValue = documentParagraph.createRun();
documentValue.setFontFamily("Times New Roman");
documentValue.setFontSize(14);
documentValue.setBold(true);
documentValue.setCapitalized(true);
documentValue.setText(documentEntity.toString());
}
}
/** ---Address Paragraph--- */
if (veteranEntity.getAddress() != null) {
XWPFParagraph addressParagraph = document.createParagraph();
addressParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun addressLabel = addressParagraph.createRun();
addressLabel.setFontFamily("Times New Roman");
addressLabel.setFontSize(14);
addressLabel.setText("Домашний адрес: ");
XWPFRun addressValue = addressParagraph.createRun();
addressValue.setFontFamily("Times New Roman");
addressValue.setFontSize(14);
addressValue.setBold(true);
addressValue.setCapitalized(true);
addressValue.setText(veteranEntity.getAddress());
}
/** ---Phone Paragraph--- */
if (veteranEntity.getPhoneNumber() != null) {
XWPFParagraph phoneParagraph = document.createParagraph();
phoneParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun phoneLabel = phoneParagraph.createRun();
phoneLabel.setFontFamily("Times New Roman");
phoneLabel.setFontSize(14);
phoneLabel.setText("Номер телефона: ");
XWPFRun phoneValue = phoneParagraph.createRun();
phoneValue.setFontFamily("Times New Roman");
phoneValue.setFontSize(14);
phoneValue.setBold(true);
phoneValue.setCapitalized(true);
phoneValue.setText(veteranEntity.getPhoneNumber());
}
/** ---WorkPlace Paragraph---*/
if (veteranEntity.getWorkPlaces().size() > 0) {
String place = "";
WorkPlaceEntity workPlaceEntity = veteranEntity.getWorkPlaces().get(veteranEntity.getWorkPlaces().size() - 1);
place += !workPlaceEntity.getLocality().equals("") ? workPlaceEntity.getLocality() : "";
place += !workPlaceEntity.getOrganization().equals("") ? ", " + workPlaceEntity.getOrganization() : "";
place += !workPlaceEntity.getPosition().equals("") ? ", " + workPlaceEntity.getPosition() : "";
if (!place.equals("")) {
XWPFParagraph placeParagraph = document.createParagraph();
placeParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun placeLabel = placeParagraph.createRun();
placeLabel.setFontFamily("Times New Roman");
placeLabel.setFontSize(14);
placeLabel.setText("Место работы: ");
XWPFRun placeValue = placeParagraph.createRun();
placeValue.setFontFamily("Times New Roman");
placeValue.setFontSize(14);
placeValue.setBold(true);
placeValue.setText(place);
}
}
/** ---Rank Rgvk---*/
if (veteranEntity.getRgvk() != null) {
XWPFParagraph rgvkParagraph = document.createParagraph();
rgvkParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun rgvkLabel = rgvkParagraph.createRun();
rgvkLabel.setFontFamily("Times New Roman");
rgvkLabel.setFontSize(14);
rgvkLabel.setText("Р(Г)ВК: ");
XWPFRun rgvkValue = rgvkParagraph.createRun();
rgvkValue.setFontFamily("Times New Roman");
rgvkValue.setFontSize(14);
rgvkValue.setBold(true);
rgvkValue.setText(veteranEntity.getRgvk().getName());
}
if (veteranEntity.getPhoto() != null) {
XWPFParagraph photo = document.createParagraph();
XWPFRun run = photo.createRun();
photo.setAlignment(ParagraphAlignment.LEFT);
Image image = ImageConverter.convertBytesToImage(veteranEntity.getPhoto());
BufferedImage originalImage = SwingFXUtils.fromFXImage(image, null);
File outputFile = new File(System.getProperty("user.home") + "/Social Protection Module/saved.jpeg");
ImageIO.write(originalImage, "jpeg", outputFile);
String imgFile = System.getProperty("user.home") + "/Social Protection Module/saved.jpeg";
InputStream inputStream = new FileInputStream(imgFile);
run.addPicture(inputStream, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(125), Units.toEMU(150));
inputStream.close();
outputFile.delete();
}
document.write(new FileOutputStream(file.getAbsolutePath()));
document.close();
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
|
package tij.concurrents.part5;
import java.util.concurrent.TimeUnit;
public class Test1{
private Restaurant restaurant;
class WaitPerson{
public void run() throws InterruptedException {
synchronized (this){
while(restaurant.meal == null){ wait(); }
}
// System.out.println("Waitperson got "+restaurant.meal);
synchronized (restaurant.chef){
restaurant.meal = null;
restaurant.chef.notifyAll();
}
}
}
class Chef {
public void run() throws InterruptedException {
synchronized (this){
while(restaurant.meal != null){ wait(); }
}
// System.out.println("Order up! ");
synchronized (restaurant.waitPerson){
// restaurant.meal = new Meal(count);
restaurant.waitPerson.notifyAll();
}
TimeUnit.MILLISECONDS.sleep(100);
}
}
}
//如果同步块a的操作会影响到同步块b的判断条件,那么二者应当使用同一个锁
|
package ioio.examples.hello;
import ioio.examples.hello.R;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.ToggleButton;
//holds all the buttons that needs listening to
public class MainActivity extends IOIOActivity {
//potentiometer pins
private static final int DISTANCE_PIN = 35;
private static final int SHOLDER_POT_PIN = 36;
private static final int ELBOW_POT_PIN = 37;
private static final int WRIST_POT_PIN = 38;
//arm pins
private static final int ARM_STBY = 31;
private static final int ARM_PWM = 28;
//turn and led
private static final int TURN_A02_PIN = 19;
private static final int TURN_A01_PIN = 20;
private static final int LED_B01_PIN = 21;
private static final int LED_B02_PIN = 22;
//sholder and elbow
private static final int SHOLDER_A02_PIN = 26;
private static final int SHOLDER_A01_PIN = 25;
private static final int ELBOW_B02_PIN = 23;
private static final int ELBOW_B01_PIN = 24;
//wrist and grasp
private static final int WRIST_A01_PIN = 29;
private static final int WRIST_A02_PIN = 30;
private static final int GRASP_B01_PIN = 32;
private static final int GRASP_B02_PIN = 33;
//front side motors on chassi
private static final int FRONT_CHASSIS_E1_PIN = 39;
private static final int FRONT_CHASSIS_E2_PIN = 40;
private static final int FRONT_CHASSIS_M1_PIN = 41;
private static final int FRONT_CHASSIS_M2_PIN = 42;
//front side motors on chassi
private static final int BACK_CHASSIS_M1_PIN = 43;
private static final int BACK_CHASSIS_M2_PIN = 44;
private static final int BACK_CHASSIS_E1_PIN = 45;
private static final int BACK_CHASSIS_E2_PIN = 46;
//sides
private static final boolean TURN_LEFT = false;
private static final boolean TURN_RIGHT = true;
//buttons pressed
private static final int PRESSED_UP = 1;
private static final int PRESSED_DOWN = 2;
private static final int PRESSED_LEFT = 4;
private static final int PRESSED_RIGHT = 8;
//GUI fields
private Button chassiUpButton_;
private Button chassiDownButton_;
private Button chassiLeftButton_;
private Button chassiRightButton_;
private SeekBar chassiSpeedSeekBar_;
private ToggleButton systemEnabled;
private Button armTurnRight;
private Button armTurnLeft;
private ToggleButton ledOnOff;
private Button armSholderUp;
private Button armSholderDown;
private Button armElbowDown;
private Button armElbowUp;
private Button armWristUp;
private Button armWristDown;
private Button armGrasp;
private Button armRelease;
private ChassisFrame _chasiss;
private RoboticArmEdge _arm;
private MovmentSystem _movmentModule;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
systemEnabled = (ToggleButton) findViewById(R.id.panicButton);
systemEnabled.setChecked(true);
chassiUpButton_ = (Button) findViewById(R.id.up);
chassiDownButton_ = (Button) findViewById(R.id.down);
chassiLeftButton_ = (Button) findViewById(R.id.Left);
chassiRightButton_ = (Button) findViewById(R.id.Right);
chassiSpeedSeekBar_ = (SeekBar) findViewById(R.id.speedSeekBar);
chassiSpeedSeekBar_.setProgress(0);
armTurnRight = (Button) findViewById(R.id.TurnRight);
armTurnLeft = (Button) findViewById(R.id.TurnLeft);
ledOnOff = (ToggleButton) findViewById(R.id.LedOnOff);
armSholderUp = (Button) findViewById(R.id.SholderUp);
armSholderDown = (Button) findViewById(R.id.SholderDown);
armElbowUp = (Button) findViewById(R.id.Elbow_up);
armElbowDown = (Button) findViewById(R.id.Elbow_Down);
armWristUp = (Button) findViewById(R.id.Wrist_Up);
armWristDown = (Button) findViewById(R.id.Wrist_Down);
armGrasp = (Button) findViewById(R.id.arm_Grasp);
armRelease = (Button) findViewById(R.id.arm_Release);
}
// holds all the components connected to the IOIO and responsible for their update
class Looper extends BaseIOIOLooper {
protected void setup() throws ConnectionLostException {
BigMotorDriver chassiFront = new BigMotorDriver(ioio_, FRONT_CHASSIS_M1_PIN, FRONT_CHASSIS_E1_PIN, FRONT_CHASSIS_M2_PIN, FRONT_CHASSIS_E2_PIN);
BigMotorDriver chassiBack = new BigMotorDriver(ioio_, BACK_CHASSIS_M1_PIN, BACK_CHASSIS_E1_PIN, BACK_CHASSIS_M2_PIN, BACK_CHASSIS_E2_PIN);
_chasiss = new ChassisFrame(chassiFront, chassiBack);
SmallMotorDriver turn_and_led = new SmallMotorDriver(ioio_, TURN_A01_PIN, TURN_A02_PIN, LED_B01_PIN, LED_B02_PIN);
SmallMotorDriver sholder_and_elbow = new SmallMotorDriver(ioio_, SHOLDER_A01_PIN, SHOLDER_A02_PIN, ELBOW_B01_PIN, ELBOW_B02_PIN);
SmallMotorDriver wrist_and_grasp = new SmallMotorDriver(ioio_, WRIST_A01_PIN, WRIST_A02_PIN, GRASP_B01_PIN, GRASP_B02_PIN);
_arm = new RoboticArmEdge(ioio_, wrist_and_grasp, sholder_and_elbow, turn_and_led, ARM_STBY, ARM_PWM);
_movmentModule = new MovmentSystem(ioio_, _chasiss, _arm, WRIST_POT_PIN, SHOLDER_POT_PIN, ELBOW_POT_PIN, DISTANCE_PIN);
}
public void loop() throws ConnectionLostException, InterruptedException {
System.out.println("Elbow= "+_movmentModule.get_elbowPosition()+ " Sholder= "+_movmentModule.get_sholderPosition());
//ensures that loop runs only if systemEnabled button is pressed
if (!systemEnabled.isChecked()) {
_chasiss.stop();
_arm.stop();
return;
}
_arm.turnTurning(armTurnLeft.isPressed(), armTurnRight.isPressed());
_arm.toggleLed(ledOnOff.isChecked());
_arm.turnSholder(armSholderUp.isPressed(), armSholderDown.isPressed());
_arm.turnElbow(armElbowUp.isPressed(), armElbowDown.isPressed());
_arm.turnWrist(armWristUp.isPressed(), armWristDown.isPressed());
_arm.turnGrasp(armRelease.isPressed(), armGrasp.isPressed());
//Chassis part
int buttonState = (chassiUpButton_.isPressed()? 0x1:0x0) + (chassiDownButton_.isPressed()? 0x2:0x0) + (chassiLeftButton_.isPressed()? 0x4:0x0) + (chassiRightButton_.isPressed()? 0x8:0x0);
if (buttonState == PRESSED_UP){
_chasiss.driveForward();
}
else if((buttonState == PRESSED_DOWN)){
_chasiss.driveBackwards();
}
else if(buttonState == PRESSED_LEFT){
_chasiss.turnLeft();
}
else if(buttonState == PRESSED_RIGHT){
_chasiss.turnRight();
}
else{}
//Chassis speed
float newSpeed = ((buttonState & 15) != 0? 1:0) * ((float) chassiSpeedSeekBar_.getProgress()/100);
_chasiss.setSpeed(newSpeed);
}
}
@Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
} |
package br.com.engenharia;
public class Dimensao {
private float x;
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getZ() {
return z;
}
public void setZ(float z) {
this.z = z;
}
private float y;
private float z;
private float angulo;
private float densidade;
public float getDensidade() {
return densidade;
}
public void setDensidade(float densidade) {
this.densidade = densidade;
}
public float getAngulo() {
return angulo;
}
public void setAngulo(float angulo) {
this.angulo = angulo;
}
}
|
package rest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import rest.model.TimeCoracao;
import rest.repository.TimeCoracaoRepository;
@Controller
@RequestMapping(path="/rest-time")
public class TimesController {
@Autowired
private TimeCoracaoRepository timeCoracaoRepository;
@GetMapping(path="/getAllTimes")
public @ResponseBody Iterable<TimeCoracao> getAllTimes() {
return timeCoracaoRepository.findAll();
}
@GetMapping(path="/getTimeById/{id}")
public ResponseEntity getTimeById(@PathVariable Long id) {
if(!timeCoracaoRepository.exists(id)){
return new ResponseEntity("Usuario nao encontrado :(.\n ID informado: " + id, HttpStatus.NOT_FOUND);
} else{
return new ResponseEntity(timeCoracaoRepository.findOne(id),HttpStatus.OK);
}
}
@PostMapping(path="/createNewTime")
public ResponseEntity createNewTime(@RequestBody TimeCoracao timeCoracao){
try{
timeCoracaoRepository.save(timeCoracao);
return new ResponseEntity("Time cadastrado com sucesso! ;)", HttpStatus.OK);
}catch(Exception ex){
return new ResponseEntity("Ocorreu um erro a criar o usuario. :( \n" + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
package com.lanltn.homestay.applicationModule;
public class AppComponent {
}
|
package com.thoughtworks.rslist.repository;
import com.thoughtworks.rslist.dto.UserDto;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by wzw on 2020/8/6.
*/
public interface UserRepository extends CrudRepository<UserDto, Integer> {
@Override
List<UserDto> findAll();
@Query(value = "ALTER TABLE user AUTO_INCREMENT=1", nativeQuery = true)
@Modifying
@Transactional
void resetAutoIncrement();
}
|
package com.hb.rssai.presenter;
import android.text.TextUtils;
import android.view.View;
import com.hb.rssai.bean.ResSubscription;
import com.hb.rssai.constants.Constant;
import com.hb.rssai.view.iView.IFindView;
import java.util.HashMap;
import java.util.Map;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Administrator on 2017/8/15.
*/
public class FindPresenter extends BasePresenter<IFindView> {
private IFindView iFindView;
public FindPresenter(IFindView iFindView) {
this.iFindView = iFindView;
}
public void findMoreList() {
if (iFindView != null) {
findApi.findMoreList(getFindMoreParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resFindMore -> iFindView.setFindMoreResult(resFindMore), this::loadFindError);
}
}
public void recommendList() {
if (iFindView != null) {
findApi.recommendList(getRecommendParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resFindMore -> iFindView.setRecommendResult(resFindMore), this::loadError);
}
}
public void findMoreListById(View v, boolean isRecommend) {
if (iFindView != null) {
findApi.findMoreListById(getFindMoreByIdParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resSubscription -> setFindMoreByIdResult(resSubscription, v, isRecommend), this::loadError);
}
}
public void addSubscription(View v, boolean isRecommend) {
findApi.subscribe(getSubscribeParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resBase -> iFindView.setAddResult(resBase, v, isRecommend), this::loadError);
}
public void delSubscription(View v, boolean isRecommend) {
findApi.delSubscription(getDelParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resBase -> iFindView.setDelResult(resBase, v, isRecommend), this::loadError);
}
public void setFindMoreByIdResult(ResSubscription resSubscription, View v, boolean isRecommend) {
if (resSubscription.getRetCode() == 0) {
if (resSubscription.getRetObj().isDeleteFlag()) {
addSubscription(v, isRecommend);
} else { //如果发现没有被删除
if (TextUtils.isEmpty(resSubscription.getRetObj().getUserId())) {//如果也没有被添加过
addSubscription(v, isRecommend);
} else {//如果被添加过
String userId = iFindView.getUserID();
if (userId.equals(resSubscription.getRetObj().getUserId())) {//如果是等于当前登录ID
delSubscription(v, isRecommend);
} else {//不等于
addSubscription(v, isRecommend);
}
}
}
} else if (resSubscription.getRetCode() == 10013) {
//从来没订阅过
addSubscription(v, isRecommend);
} else {
iFindView.showToast(resSubscription.getRetMsg());
}
}
private void loadFindError(Throwable throwable) {
throwable.printStackTrace();
iFindView.showFindError();
}
private void loadError(Throwable throwable) {
iFindView.showLoadError();
throwable.printStackTrace();
}
private Map<String, String> getDelParams() {
Map<String, String> map = new HashMap<>();
String userId = iFindView.getUserID();
String subscribeId = iFindView.getRowsBeanId();
String jsonParams = "{\"subscribeId\":\"" + subscribeId + "\",\"usId\":\"" + userId + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
System.out.println(map);
return map;
}
private Map<String, String> getFindMoreParams() {
Map<String, String> map = new HashMap<>();
String jsonParams = "{\"page\":\"" + iFindView.getPage() + "\",\"size\":\"" + Constant.PAGE_SIZE + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
System.out.println(map);
return map;
}
private Map<String, String> getFindMoreByIdParams() {
Map<String, String> map = new HashMap<>();
String subscribeId = iFindView.getRowsBeanId();
String jsonParams = "{\"subscribeId\":\"" + subscribeId + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
System.out.println(map);
return map;
}
private Map<String, String> getRecommendParams() {
Map<String, String> map = new HashMap<>();
String jsonParams = "{\"page\":\"" + iFindView.getRecommendPage() + "\",\"size\":\"" + Constant.RECOMMEND_PAGE_SIZE + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
return map;
}
private Map<String, String> getSubscribeParams() {
Map<String, String> map = new HashMap<>();
String subscribeId = iFindView.getRowsBeanId();
String userId = iFindView.getUserID();
String jsonParams = "{\"userId\":\"" + userId + "\",\"subscribeId\":\"" + subscribeId + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
return map;
}
}
|
package com.gnomikx.www.gnomikx;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.gnomikx.www.gnomikx.ActivityWidgetHandler.MakeVisible;
import com.gnomikx.www.gnomikx.Data.UserDetail;
import com.gnomikx.www.gnomikx.Handlers.FirebaseHandler;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity implements MakeVisible {
private static final String TAG = "MainActivity";
public static final String DISPLAY_BLOG_TAG = "DisplayBlogFragment";
public static final String DISPLAY_USER_FRAGMENT = "DisplayUserFragment";
public static final String QUERY_RESPONSE_FRAGMENT = "QueryResponseFragment";
public static final String VIEW_QUERY_FRAGMENT = "ViewQueryFragment";
public static final String SIGN_UP_FRAGMENT = "SignUpFragment";
private DrawerLayout mDrawerLayout;
public UserDetail userDetail;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseAuth firebaseAuth;
public static final String blogTag = "BlogFragment";
private NavigationView navigationView;
//gender constants
public static final int GENDER_MALE = 0;
public static final int GENDER_FEMALE = 1;
public static final int GENDER_OTHER = 2;
//Role constants
public static final String ROLE_PATIENT = "Patient";
public static final String ROLE_DOCTOR = "Doctor";
public static final String ROLE_ADMIN = "Admin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userDetail = null;
FirebaseHandler handler = new FirebaseHandler();
firebaseAuth = handler.getFirebaseAuth();
//setting toolbar as the Activity's ActionBar
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.nav_view);
//setting an auth state listener to fetch userDetails from database and
//to display the correct elements on the navigation drawer
authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
Log.i(TAG, "Auth state listener called");
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
if(userDetail == null) {
FirebaseHandler handler = new FirebaseHandler();
DocumentReference userDetailsDocumentReference = handler.getUserDetailsDocumentRef();
userDetailsDocumentReference.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
UserDetail detail = documentSnapshot.toObject(UserDetail.class);
setUserDetail(detail);
showMenuAndNavFields(detail);
}
}
});
} else {
showMenuAndNavFields(userDetail);
}
}
else { //user is not signed in
hideMenuAndNavFields();
userDetail = null; //set userDetails to null, if not already set
}
}
};
ActionBar actionbar = getSupportActionBar();
assert actionbar != null;
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = findViewById(R.id.drawer_layout);
//displaying pre_loader fragment
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
PreLoader preLoader = new PreLoader();
fragmentTransaction.add(R.id.fragment_container, preLoader);
actionbar.hide();
fragmentTransaction.disallowAddToBackStack();
fragmentTransaction.commit();
FirebaseUser user = handler.getFirebaseUser();
if(user != null && userDetail != null) {
DocumentReference userDetailsDocRef = handler.getUserDetailsDocumentRef();
userDetailsDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()) {
userDetail = documentSnapshot.toObject(UserDetail.class);
}
}
});
}
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
/*
use these lines (with alterations to call the correct class
for switching between fragments according to the element
selected by the user. Remember to create a new FragmentTransaction
every time, as reusing one such instance can throw an exception
causing app to crash
*/
displaySelectedFragment(menuItem.getItemId(), fragmentManager);
return true;
}
});
}
public void displaySelectedFragment(int id, FragmentManager fragmentManager) {
switch(id) {
case R.id.nav_home_id: {
showFragment(new BlogFragment(), fragmentManager);
} break;
case R.id.nav_sign_id: {
showFragment(new FragmentAuthentication(), fragmentManager);
} break;
case R.id.nav_bmi_id: {
showFragment(new BodyMassIndexFragment(), fragmentManager);
} break;
case R.id.nav_genetic_test_id: {
showFragment(new FragmentGeneticTests(), fragmentManager);
} break;
case R.id.nav_register_patients_id: {
showFragment(new FragmentRegisterPatients(), fragmentManager);
} break;
case R.id.nav_queries_id: {
showFragment(new FragmentQueries(), fragmentManager);
} break;
case R.id.nav_submit_blog_id: {
showFragment(new FragmentSubmitBlog(), fragmentManager);
} break;
case R.id.nav_my_account_id: {
showFragment(new FragmentMyAccount(), fragmentManager);
} break;
case R.id.nav_see_users_id: {
showFragment(new AllUsersFragment(), fragmentManager);
} break;
case R.id.nav_see_queries: {
showFragment(new AnswerQueriesFragment(), fragmentManager);
} break;
case R.id.nav_submitted_blogs: {
showFragment(new ApproveBlogsFragment(), fragmentManager);
} break;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public UserDetail getUserDetail() {
return userDetail;
}
public void setUserDetail(UserDetail userDetail) {
this.userDetail = userDetail;
}
/**
* method to make the action bar visible when needed
*/
@Override
public void makeVisible() {
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.show();
}
@Override
protected void onStart() {
firebaseAuth.addAuthStateListener(authStateListener);
super.onStart();
}
@Override
protected void onResume() {
Log.i(TAG, "onResume() called");
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null && !user.isEmailVerified()) {
user.reload().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "FirebaseUser reloaded successfully");
}
});
}
super.onResume();
}
@Override
protected void onStop() {
firebaseAuth.removeAuthStateListener(authStateListener);
super.onStop();
}
@Override
public void onBackPressed() {
//close drawer if it is open, else display home fragment if it is not displayed, else close app
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(Gravity.START, true);
Log.i(TAG, "Navigation drawer closed");
} else if(getSupportFragmentManager().findFragmentByTag(DISPLAY_BLOG_TAG) != null ||
getSupportFragmentManager().findFragmentByTag(DISPLAY_USER_FRAGMENT) != null ||
getSupportFragmentManager().findFragmentByTag(QUERY_RESPONSE_FRAGMENT) != null ||
getSupportFragmentManager().findFragmentByTag(VIEW_QUERY_FRAGMENT) != null ||
getSupportFragmentManager().findFragmentByTag(SIGN_UP_FRAGMENT) != null) {
//blog contents are being displayed
Log.i(TAG, "Blog details or User details fragments closed");
super.onBackPressed();
}
else if(getSupportFragmentManager().findFragmentByTag(blogTag) == null) {
Log.i(TAG, "displaying home screen");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new BlogFragment(), blogTag);
fragmentTransaction.commit();
MenuItem menuItem = navigationView.getMenu().findItem(R.id.nav_home_id);
menuItem.setChecked(true);
}
else {
super.onBackPressed();
}
}
/**
* Method to hide fields that should not be shown to an unauthenticated user
* and add placeholder text to navigation drawer heading
*/
private void hideMenuAndNavFields() {
//setting placeholder elements as text for username and user email in nav_bar
View headerView = navigationView.getHeaderView(0);
TextView usernameText = headerView.findViewById(R.id.nav_drawer_user_name);
usernameText.setText(getString(R.string.gnomikx_user));
TextView userEmail = headerView.findViewById(R.id.nav_drawer_user_email);
userEmail.setText(R.string.gnomikx_email_id);
//setting sign in label and icon for FragmentAuthentication
MenuItem authentication = navigationView.getMenu().findItem(R.id.nav_sign_id);
authentication.setTitle(getString(R.string.nav_sign));
authentication.setIcon(R.drawable.ic_sign_in_24dp);
//hiding My Account page
MenuItem menuItem = navigationView.getMenu().findItem(R.id.nav_my_account_id);
menuItem.setVisible(false);
//hiding register patients menu
MenuItem registerPatients = navigationView.getMenu().findItem(R.id.nav_register_patients_id);
registerPatients.setVisible(false);
//displaying some required elements
MenuItem geneticTests = navigationView.getMenu().findItem(R.id.nav_genetic_test_id);
geneticTests.setVisible(true);
MenuItem postQuery = navigationView.getMenu().findItem(R.id.nav_queries_id);
postQuery.setVisible(true);
//admin level menu items
MenuItem seeUsers = navigationView.getMenu().findItem(R.id.nav_see_users_id);
seeUsers.setVisible(false);
MenuItem seeQueries = navigationView.getMenu().findItem(R.id.nav_see_queries);
seeQueries.setVisible(false);
MenuItem seeBlogs = navigationView.getMenu().findItem(R.id.nav_submitted_blogs);
seeBlogs.setVisible(false);
}
/**
* Method to show the appropriate menu fields for the current user
* and add user's details to the navigation drawer
* @param detail - contains the details of the user
*/
public void showMenuAndNavFields(UserDetail detail) {
//setting username and user email to nav_drawer fields
View headerView = navigationView.getHeaderView(0);
TextView usernameText = headerView.findViewById(R.id.nav_drawer_user_name);
usernameText.setText(detail.getUserName());
TextView userEmail = headerView.findViewById(R.id.nav_drawer_user_email);
userEmail.setText(detail.getUserEmailID());
Menu menu = navigationView.getMenu();
//setting sign out label and icon for FragmentAuthentication
MenuItem authentication = menu.findItem(R.id.nav_sign_id);
authentication.setTitle(getString(R.string.sign_out_button_text));
authentication.setIcon(R.drawable.ic_sign_out_24dp);
//hide register patients option for patients, reveal it for doctors
switch (userDetail.getRole()) {
case ROLE_PATIENT: {
MenuItem menuItem = menu.findItem(R.id.nav_register_patients_id);
menuItem.setVisible(false);
//making My Account section visible
MenuItem myAccount = menu.findItem(R.id.nav_my_account_id);
myAccount.setVisible(true);
MenuItem geneticTests = menu.findItem(R.id.nav_genetic_test_id);
geneticTests.setVisible(true);
MenuItem postQuery = menu.findItem(R.id.nav_queries_id);
postQuery.setVisible(true);
//admin level menu items
MenuItem seeUsers = navigationView.getMenu().findItem(R.id.nav_see_users_id);
seeUsers.setVisible(false);
MenuItem seeQueries = navigationView.getMenu().findItem(R.id.nav_see_queries);
seeQueries.setVisible(false);
MenuItem seeBlogs = navigationView.getMenu().findItem(R.id.nav_submitted_blogs);
seeBlogs.setVisible(false);
break;
}
case ROLE_DOCTOR: {
MenuItem registerPatients = menu.findItem(R.id.nav_register_patients_id);
registerPatients.setVisible(true);
//making My Account section visible
MenuItem myAccount = menu.findItem(R.id.nav_my_account_id);
myAccount.setVisible(true);
//admin level menu items
MenuItem seeUsers = navigationView.getMenu().findItem(R.id.nav_see_users_id);
seeUsers.setVisible(false);
MenuItem seeQueries = navigationView.getMenu().findItem(R.id.nav_see_queries);
seeQueries.setVisible(false);
MenuItem seeBlogs = navigationView.getMenu().findItem(R.id.nav_submitted_blogs);
seeBlogs.setVisible(false);
MenuItem geneticTests = menu.findItem(R.id.nav_genetic_test_id);
geneticTests.setVisible(true);
MenuItem postQuery = menu.findItem(R.id.nav_queries_id);
postQuery.setVisible(true);
break;
}
case ROLE_ADMIN:
//admin level menu items
MenuItem seeUsers = menu.findItem(R.id.nav_see_users_id);
seeUsers.setVisible(true);
MenuItem seeQueries = menu.findItem(R.id.nav_see_queries);
seeQueries.setVisible(true);
MenuItem seeBlogs = menu.findItem(R.id.nav_submitted_blogs);
seeBlogs.setVisible(true);
//admin won't register for genetic tests, post queries, register patients or need "my account"
MenuItem geneticTests = menu.findItem(R.id.nav_genetic_test_id);
geneticTests.setVisible(false);
MenuItem postQuery = menu.findItem(R.id.nav_queries_id);
postQuery.setVisible(false);
MenuItem registerPatients = menu.findItem(R.id.nav_register_patients_id);
registerPatients.setVisible(false);
MenuItem myAccount = menu.findItem(R.id.nav_my_account_id);
myAccount.setVisible(false);
break;
}
}
/**
* Method to display the correct fragment
* @param fragment - the fragment to be displayed
* @param fragmentManager - an instance of SupportFragmentManager, to manage the fragments
*/
private void showFragment(Fragment fragment, FragmentManager fragmentManager) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//remove DisplayBlogContentsFragment from back stack if it exists in back stack
if(fragmentManager.findFragmentByTag(DISPLAY_BLOG_TAG ) != null) {
Log.i(TAG, "Removed " + DISPLAY_BLOG_TAG + " from back stack");
fragmentTransaction.remove(fragmentManager.findFragmentByTag(DISPLAY_BLOG_TAG));
fragmentManager.popBackStackImmediate(DISPLAY_BLOG_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
if(fragmentManager.findFragmentByTag(DISPLAY_USER_FRAGMENT ) != null) {
Log.i(TAG, "Removed " + DISPLAY_USER_FRAGMENT + " from back stack");
fragmentTransaction.remove(fragmentManager.findFragmentByTag(DISPLAY_USER_FRAGMENT));
fragmentManager.popBackStackImmediate(DISPLAY_USER_FRAGMENT, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
if(fragmentManager.findFragmentByTag(QUERY_RESPONSE_FRAGMENT ) != null) {
Log.i(TAG, "Removed " + QUERY_RESPONSE_FRAGMENT + " from back stack");
fragmentTransaction.remove(fragmentManager.findFragmentByTag(QUERY_RESPONSE_FRAGMENT));
fragmentManager.popBackStackImmediate(QUERY_RESPONSE_FRAGMENT, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
if(fragmentManager.findFragmentByTag(VIEW_QUERY_FRAGMENT ) != null) {
Log.i(TAG, "Removed " + VIEW_QUERY_FRAGMENT + " from back stack");
fragmentTransaction.remove(fragmentManager.findFragmentByTag(VIEW_QUERY_FRAGMENT));
fragmentManager.popBackStackImmediate(VIEW_QUERY_FRAGMENT, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
if(fragmentManager.findFragmentByTag(SIGN_UP_FRAGMENT ) != null) {
Log.i(TAG, "Removed " + SIGN_UP_FRAGMENT + " from back stack");
fragmentTransaction.remove(fragmentManager.findFragmentByTag(SIGN_UP_FRAGMENT));
fragmentManager.popBackStackImmediate(SIGN_UP_FRAGMENT, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
// Replace whatever is in the fragment_container view with this fragment,
// and not allowing addition of the transaction to the back stack.
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.disallowAddToBackStack();
//commit changes - this will inflate the fragment layout
fragmentTransaction.commit();
}
}
|
import java.util.*;
/**
* 632. Smallest Range
* So Hard -_-b
* 求多个整数数组列表中,每个数组取至少一个值,组成的最小数值范围
*/
class Solution {
public int[] smallestRangePointer(List<List<Integer>> nums) {
int minx = 0, miny = Integer.MAX_VALUE;
int[] next = new int[nums.size()]; // 遍历时指向每个list的指针
boolean flag = true;
for (int i = 0; i < nums.size() && flag; i++) {
for (int j = 0; j < nums.get(i).size() && flag; j++) {
int min_i = 0, max_i = 0;
for (int k = 0; k < nums.size(); k++) { // 遍历所有list当前next下标的值,求出当前范围最大最小值list下标
if (nums.get(min_i).get(next[min_i]) > nums.get(k).get(next[k]))
min_i = k;
if (nums.get(max_i).get(next[max_i]) < nums.get(k).get(next[k]))
max_i = k;
}
// 与记录的最小的范围比较大小,并取小的范围
if (miny - minx > nums.get(max_i).get(next[max_i]) - nums.get(min_i).get(next[min_i])) {
miny = nums.get(max_i).get(next[max_i]);
minx = nums.get(min_i).get(next[min_i]);
}
next[min_i]++; // 增加最小值对应list的next下标
if (next[min_i] == nums.get(min_i).size()) { // 若最小next指针到了末尾,则结束
flag = false;
}
}
}
return new int[] {minx, miny};
}
public int[] smallestRange(List<List<Integer>> nums) {
int minx = 0, miny = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
int[] next = new int[nums.size()];
boolean flag = true;
PriorityQueue<Integer> min_queue = new PriorityQueue<Integer>( // 优先队列(小顶堆),优化比较速度
(i, j) -> nums.get(i).get(next[i]) - nums.get(j).get(next[j])); // 比较函数
for (int i = 0; i < nums.size(); i++) {
min_queue.offer(i);
max = Math.max(max, nums.get(i).get(0));
}
for (int i = 0; i < nums.size() && flag; i++) {
for (int j = 0; j < nums.get(i).size() && flag; j++) {
int min_i = min_queue.poll();
if (miny - minx > max - nums.get(min_i).get(next[min_i])) {
minx = nums.get(min_i).get(next[min_i]);
miny = max;
}
next[min_i]++;
if (next[min_i] == nums.get(min_i).size()) {
flag = false;
break;
}
min_queue.offer(min_i);
max = Math.max(max, nums.get(min_i).get(next[min_i]));
}
}
return new int[] {minx, miny};
}
public static void main(String[] args) {
Solution s = new Solution();
Integer[][] nums1 = {{4,10,15,24,26}, {0,9,12,20,50}, {5,18,22,30,99}};
List<List<Integer>> nums = new ArrayList<List<Integer>>();
for (int i = 0; i < nums1.length; i++) {
List<Integer> t = Arrays.asList(nums1[i]);
nums.add(t);
}
int[] result = s.smallestRange(nums);
System.out.println("[" + result[0] + ", " + result[1] + "]");
}
} |
package entities.pages.pepboys;
import entities.pages.BasePage;
import org.openqa.selenium.By;
public class PepBoysTrackingPage extends BasePage {
public boolean isPage() {
return isElementVisible(By.id("tracking"));
}
}
|
package com.vilio.plms.service.quartz;
import com.vilio.plms.service.base.BaseService;
/**
* Created by martin on 2017/8/28.
*/
public interface BmsSynchronizationBaseDataService{
public void execute() throws Exception;
}
|
package packone;
public class FirstClass {
int a,b;
public FirstClass(int a, int b) {
this.a = a;
this.b = b;
System.out.println(this.a + this.b);
}
}
|
package com.simbircite.demo.controller;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.Valid;
import com.google.common.collect.Lists;
import com.simbircite.demo.form.Message;
import com.simbircite.demo.model.User;
import com.simbircite.demo.model.UserGrid;
import com.simbircite.demo.service.UserService;
import com.simbircite.demo.util.DateUtil;
import com.simbircite.demo.util.UrlUtil;
import com.simbircite.demo.util.spring.CustomDateTimeEditor;
import com.simbircite.demo.validator.UserValidator;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Пример контроллера Spring.
*
* В Spring MVC существует целая иерархия контроллеров,
* базовый интерфейс среди которых, - Controller.
*
* Все контроллеры в Spring MVC реализуют этот интерфейс.
* Однако нам реализовывать его не нужно будет.
*
* В Spring MVC есть несколько контроллеров для разных видов запросов и ответов.
* Самые используемые - это AbstractController, SimpleFormController и MultiActionController.
*
* Отображение URL на представления:
*
* /users GET list() Список пользователей
* /users/{id} GET show() Карточка пользователя
* /users/{id}?form GET updateForm() Форма редактирования карточки
* /users/{id}?form POST update() Обновление карточки пользователя
* /users/{id} DELETE remove() Удаление карточки пользователя
* /users?form GET createForm() Форма создания карточки
* /users?form POST create() Создание карточки пользователя
* /users/photo/{id} GET downloadPhoto() Загрузка фотографии
*/
@Controller /* объявляем, что данный класс является контроллером */
@RequestMapping("/users")
public class UserController {
private static final String CONTROLLER_PATH = "users/";
private static final Logger logger = Logger.getLogger(UserController.class);
/* внедряем бин сервиса для работы с пользователями */
@Autowired
private UserService userService;
/* внедряем бин валидатора модели пользователя */
@Autowired
private UserValidator userValidator;
/* внедряем бин для извлечения сообщений с поддержкой интернационализации */
@Autowired
private MessageSource messageSource;
/**
* Метод получения списка пользователей.
* Вызывается при обращении к URL user при помощи метода GET
* (http://localhost:8080/SpringJpaDemo/users)
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public ModelAndView list() {
/* Возвращает вид с логическим именем users.
* В этот вид передаются данные:
* - "users" список всех пользователей
*/
ModelAndView mav = new ModelAndView();
mav.setViewName(route("list"));
mav.addObject("users", userService.getAll());
return mav;
}
@RequestMapping(
value = "/listgrid",
method = RequestMethod.GET,
produces = "application/json")
@ResponseBody
public UserGrid listGrid(
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "rows", required = false) Integer rows,
@RequestParam(value = "sidx", required = false) String sortBy,
@RequestParam(value = "sord", required = false) String order
) {
Sort sort = null;
String orderBy = sortBy;
if ((orderBy != null) && orderBy.equals("birthString")) {
orderBy = "birth";
}
if ((orderBy != null) && (order != null)) {
if (order.equals("desc")) {
sort = new Sort(Sort.Direction.DESC, orderBy);
} else {
sort = new Sort(Sort.Direction.ASC, orderBy);
}
}
PageRequest pageRequest = null;
if (sort != null) {
pageRequest = new PageRequest(page - 1, rows, sort);
} else {
pageRequest = new PageRequest(page - 1, rows);
}
Page<User> userPage = userService.getAllByPage(pageRequest);
UserGrid userGrid = new UserGrid();
userGrid.setCurrentPage(userPage.getNumber() + 1);
userGrid.setTotalPages(userPage.getTotalPages());
userGrid.setTotalRecords(userPage.getTotalElements());
userGrid.setUserData(Lists.newArrayList(userPage.iterator()));
return userGrid;
}
/**
* Переход к форме просмотра пользователя с идентификатором id.
*/
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public String show(@PathVariable("id") Long id, Model model) {
User user = userService.getById(id);
model.addAttribute("user", user);
return route("show");
}
/**
* Переход к форме редактирования пользователя с идентификатором id.
*/
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "{id}", params = "form", method = RequestMethod.GET)
public String updateForm(@PathVariable("id") Long id, Model model) {
User user = userService.getById(id);
model.addAttribute("user", user);
return route("update");
}
/**
* Метод для сохранения параметров существующего пользователя.
* Вызывается при сабмите формы.
* Перед сохранением параметров происходит проверка корректности данных.
* Если ошибок нет, то происходит переход на форму просмотра пользователя.
* Если есть, то выводится сообщения об ошибках.
*
* Параметры модели пользователя заполняются автоматически
* атрибутами модели вида (формы) с именем "user".
*/
@RequestMapping(value = "{id}", params = "form", method = RequestMethod.POST)
public String update(
@Valid @ModelAttribute("user") User user,
BindingResult bindingResult,
Model uiModel,
HttpServletRequest httpServletRequest,
RedirectAttributes redirectAttributes,
Locale locale,
@RequestParam(value = "photoFile", required = false) Part photoFile
) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("message", new Message("error",
messageSource.getMessage("users.save.fail", new Object[] {}, locale)));
uiModel.addAttribute("user", user);
return route("update");
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success",
messageSource.getMessage("users.save.success", new Object[] {}, locale)));
setUserPhoto(user, photoFile);
userService.update(user);
return "redirect:/" + route("")
+ UrlUtil.encodeUrlPathSegment(user.getId().toString(), httpServletRequest);
}
/**
* Переход к форме создания нового пользователя.
*/
@PreAuthorize("isAuthenticated()")
@RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model model) {
User user = new User();
model.addAttribute("user", user);
return route("create");
}
/**
* Метод для создания нового пользователя.
* Вызывается при сабмите формы.
* Перед сохранением параметров происходит проверка корректности данных.
* Если ошибок нет, то происходит переход на форму просмотра пользователя.
* Если есть, то выводится сообщения об ошибках.
*
* Параметры модели пользователя заполняются автоматически
* атрибутами модели вида (формы) с именем "user".
*/
@RequestMapping(params="form", method = RequestMethod.POST)
public String create(
@Valid @ModelAttribute("user") User user,
BindingResult bindingResult,
Model uiModel,
HttpServletRequest httpServletRequest,
RedirectAttributes redirectAttributes,
Locale locale,
@RequestParam(value = "photoFile", required = false) Part photoFile
) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("message", new Message("error",
messageSource.getMessage("users.save.fail", new Object[] {}, locale)));
uiModel.addAttribute("user", user);
return route("create");
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success",
messageSource.getMessage("users.save.success", new Object[] {}, locale)));
setUserPhoto(user, photoFile);
userService.update(user);
return "redirect:/" + route("")
+ UrlUtil.encodeUrlPathSegment(user.getId().toString(), httpServletRequest);
}
/**
* Удаление карточки пользователя.
*/
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public String remove(
@PathVariable("id") Long id,
RedirectAttributes redirectAttributes,
Locale locale
) {
User user = userService.getById(id);
if (user != null) {
userService.delete(user);
redirectAttributes.addFlashAttribute("message", new Message("success",
messageSource.getMessage("users.remove.success", new Object[] {}, locale)));
}
return "redirect:/" + route("");
}
/** Загрузка фотографии из карточки пользователя */
@RequestMapping(value = "/photo/{id}", method = RequestMethod.GET)
@ResponseBody
public byte[] downloadPhoto(@PathVariable("id") Long id) {
User user = userService.getById(id);
return user.getPhoto();
}
/**
* Обработчик даты, введенной пользователем на странице формы
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DateUtil.getDateFormat());
binder.registerCustomEditor(
DateTime.class, new CustomDateTimeEditor(formatter));
}
private void setUserPhoto(User user, Part photoFile) {
if (photoFile != null) {
byte[] photoFileContent = null;
try {
InputStream inputStream = photoFile.getInputStream();
if (inputStream != null) {
photoFileContent = IOUtils.toByteArray(inputStream);
user.setPhoto(photoFileContent);
}
} catch (IOException ex) {
logger.error("Error saving uploaded file");
}
}
}
private String route(String viewName) {
return CONTROLLER_PATH + viewName;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.