text
stringlengths 10
2.72M
|
|---|
package com.ibm.ive.tools.japt.inline;
import com.ibm.ive.tools.japt.AccessChecker;
import com.ibm.ive.tools.japt.AccessPermissionsChanger;
import com.ibm.ive.tools.japt.JaptRepository;
import com.ibm.jikesbt.BT_Class;
import com.ibm.jikesbt.BT_CodeAttribute;
import com.ibm.jikesbt.BT_CodeException;
import com.ibm.jikesbt.BT_CodeVisitor;
import com.ibm.jikesbt.BT_ExceptionTableEntry;
import com.ibm.jikesbt.BT_Ins;
import com.ibm.jikesbt.BT_InsVector;
import com.ibm.jikesbt.BT_InvokeSpecialIns;
import com.ibm.jikesbt.BT_JumpIns;
import com.ibm.jikesbt.BT_Method;
import com.ibm.jikesbt.BT_MethodRefIns;
import com.ibm.jikesbt.BT_Misc;
import com.ibm.jikesbt.BT_SwitchIns;
/**
* @author sfoley
*
* Represents a method call site that may or may not be inlined.
*/
public class MethodCallSite {
Boolean isInlinable;
private boolean hasBeenInlined;
private boolean overridePermissions;
private boolean inlineFromAnywhere;
final BT_Method resolvedTarget;
final InliningCodeAttribute inliningCode;
final BT_MethodRefIns instruction;
private AccessChecker enabler;
/**
* Constructs a method call site at the given instruction which exists within
* the given code, and has the sole target method. If the target method supplied is null,
* then this call site will not be inlinable or inlined.
* @param overridePermissions if inlining a method would cause a violation of access permissions,
* then inline the method anyway while broadening the permissions. For example, this would allow
* the inlining of getter and setter methods which access private members.
*/
MethodCallSite(InliningCodeAttribute code,
BT_MethodRefIns instruction,
BT_Method resolvedTarget,
boolean overridePermissions,
boolean inlineFromAnywhere) {
this.inliningCode = code;
this.instruction = instruction;
this.resolvedTarget = resolvedTarget;
this.overridePermissions = overridePermissions;
this.inlineFromAnywhere = inlineFromAnywhere;
}
BT_Method getContainingMethod() {
return inliningCode.getCode().getMethod();
}
private void getEnabler() {
BT_Class oldClass = resolvedTarget.cls;
BT_Class newClass = getContainingMethod().cls;
if(enabler == null) {
enabler = new AccessChecker(
resolvedTarget,
oldClass,
newClass,
new AccessPermissionsChanger(newClass));
}
}
/**
* verifies whether or not acess permissions will permit the inlining of this call site. The inlined
* code will contain method calls, field accesses and method calls which might not have the same
* visibility from the new location as they did from the old location.
*/
private boolean areAccessesPreserved() {
getEnabler();
return enabler.isLegal();
}
/**
* Checks whether visibility is preserved and tries to preserve
* visibility by changing access permissions if possible.
* returns whether visibility is successfully preserved.
*/
private boolean preserveAccesses() {
getEnabler();
return enabler.makeLegal();
}
private boolean canPreserveAccesses() {
getEnabler();
return enabler.canMakeLegal();
}
boolean uninitializedObjectsAtCallSite() throws BT_CodeException {
// Section 4.9.4 of bytecode verification in VM spec:
// "A valid instruction sequence must not have an uninitialized object on the operand stack
// or in a local variable during a backwards branch,
// or in a local variable in code protected by an exception handler or a finally clause"
//
class CallSiteVisitor extends BT_CodeVisitor {
int uninitializedObjects[]; //the number of uninitialized obects at each instruction index
boolean isConstructor;
boolean uninitializedObjectsAtCallSite;
protected void setUp() {
isConstructor = code.getMethod().isConstructor();
uninitializedObjects = new int[code.getInstructionSize()];
}
protected boolean visit(BT_Ins instr, int iin, BT_Ins previousInstr, int prev_iin, BT_ExceptionTableEntry handler) {
if (prev_iin == ENTRY_POINT) {
uninitializedObjects[iin] = isConstructor ? 1 : 0;
} else if(handler != null) {
uninitializedObjects[iin] = 0;
} else {
if(previousInstr.isInvokeSpecialIns()) {
BT_InvokeSpecialIns invokeSpecial = (BT_InvokeSpecialIns) previousInstr;
if(invokeSpecial.target.isConstructor()) {
uninitializedObjects[iin] = uninitializedObjects[prev_iin] - 1;
}
else {
uninitializedObjects[iin] = uninitializedObjects[prev_iin];
}
}
else if(previousInstr.isNewIns() && !previousInstr.isNewArrayIns()) {
uninitializedObjects[iin] = uninitializedObjects[prev_iin] + 1;
}
else {
uninitializedObjects[iin] = uninitializedObjects[prev_iin];
}
}
if(instr.equals(instruction)) {
uninitializedObjectsAtCallSite = uninitializedObjectsAtCallSite || (uninitializedObjects[iin] > 0);
}
return true;
}
};
CallSiteVisitor visitor = new CallSiteVisitor();
inliningCode.visitReachableCode(visitor);
return visitor.uninitializedObjectsAtCallSite;
}
boolean targetHasBackwardBranches() {
if(resolvedTarget == null) {
return false;
}
BT_CodeAttribute code = resolvedTarget.getCode();
if(code == null) {
return false;
}
BT_InsVector instructions = code.getInstructions();
for(int i=0; i<instructions.size(); i++) {
BT_Ins ins = instructions.elementAt(i);
if (ins.isSwitchIns()) {
BT_SwitchIns s = (BT_SwitchIns) ins;
BT_Ins targets[] = s.getAllTargets();
for (int k = 0; k < targets.length; k++) {
BT_Ins target = targets[k];
if(target.byteIndex < ins.byteIndex) {
return true;
}
}
}
else if (ins.isJumpIns()) {
BT_JumpIns jumpIns = (BT_JumpIns) ins;
BT_Ins target = jumpIns.getTarget();
if(target.byteIndex < ins.byteIndex) {
return true;
}
}
}
return false;
}
boolean inline(boolean alterTargetClass, boolean provokeInitialization) throws BT_CodeException {
if(!hasBeenInlined && isInlinable()) {
BT_CodeAttribute inliningCodeAtt = inliningCode.getCode();
//MethodCallSite.errorStream.println("inlining " + resolvedTarget.useName() + " into " + inliningCodeAtt.getMethod().useName());
if(inliningCodeAtt.inline(resolvedTarget.getCode(), instruction, alterTargetClass, provokeInitialization)
&& verifyInline()) {
if(overridePermissions && !preserveAccesses()) {
//should never reach here
throw new RuntimeException("not properly checking whether "
+ "we can change method visibilities before inlining");
}
hasBeenInlined = true;
}
}
return hasBeenInlined;
}
boolean isRecursive() {
return getContainingMethod().equals(resolvedTarget);
}
//static PrintStream errorStream = InlineExtension.errorStream;
/**
* checks whether a callsite is inlinable. Note that this does not check whether the method
* being inlined is inlinable, which must be done by a separate call to Method.isInlinable()
* @return
*/
boolean isInlinable() throws BT_CodeException {
//errorStream.println("checking to inline " + (resolvedTarget != null ? resolvedTarget.useName() : "null") + " into " + inliningCode.getCode().getMethod().useName());
if(isInlinable == null) {
if(resolvedTarget == null) {
isInlinable = Boolean.FALSE;
} else {
JaptRepository rep = (JaptRepository) resolvedTarget.getDeclaringClass().getRepository();
boolean canInline =
!BT_Misc.overflowsUnsignedShort(inliningCode.getLocalVarCount() + resolvedTarget.getCode().getMaxLocals())
/* The following limitiation comes from VM spec 2nd ed, paragraph 4.10 */
&& !BT_Misc.overflowsUnsignedShort(inliningCode.getBytecodeSize() + resolvedTarget.getCode().computeMaxInstructionSizes() - 1)
&& !resolvedTarget.isSynchronized() //TODO remove this condition when inliner can handle synchronized methods, which is no small matter
&& !isRecursive() /*it is quite possible that a callsite is recursive while the targetted or containing method is not:
* class A implements Runnable {
* Runnable r;
* public void run() {
* r.run(); //this callsite is recursive if r holds an instance of A which in turn has the same instance in the field r,
* //otherwise it is not recursive
* }
* }
*/
&& isAccessible()
&& rep.isInternalClass(getContainingMethod().cls)
&& (inlineFromAnywhere || rep.isInternalClass(resolvedTarget.cls))
&& (overridePermissions ? canPreserveAccesses() : areAccessesPreserved())
//the following check should be last since it is expensive - see uninitializedObjectsAtCallSite() for description of this check
&& !(targetHasBackwardBranches() && uninitializedObjectsAtCallSite());
//TODO: a case not yet handled: if there are uninitialized objects in local variables in the inlined method, and we have inlined
//into a section of code protected by an exception handler, then we cannot do the inline
//This case is not created by any known compiler - there is no need to put uninit objects into local variables.
isInlinable = canInline ? Boolean.TRUE : Boolean.FALSE;
}
}
return isInlinable.booleanValue();
}
boolean isAccessible() {
BT_Class from = getContainingMethod().getDeclaringClass();
return (resolvedTarget != null) && resolvedTarget.getDeclaringClass().isVisibleFrom(from)
&& resolvedTarget.isVisibleFrom(from);
}
/**
* after inlining we must ensure that the local variable count and the bytecode size
* are not too large
*/
boolean verifyInline() {
//MethodCallSite.errorStream.println("verifying " + inliningCode.getCode().getMethod().useName());
try {
return !BT_Misc.overflowsUnsignedShort(inliningCode.getLocalVarCount())
/* The following limitiation comes from VM spec 2nd ed, paragraph 4.10 */
&& !BT_Misc.overflowsUnsignedShort(inliningCode.getBytecodeSize() - 1);
} catch(BT_CodeException e) {}
return false;
}
}
|
package br.com.exemplo.dataingestion.adapters.events.entities;
import lombok.*;
import java.util.UUID;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class LoadEntity {
private UUID idConta;
private int quantidadeDias;
}
|
public class packingslip implements PrintReceiptInterface{
String key[];
String final_string[];
packingslip(String display){
key = new String[10];
final_string = new String[10];
System.out.println(display);
}
@Override
public void print_receipt(String array[], double value[],double tax) {
// TODO Auto-generated method stub
for(int i=0;i<7;i++)
{
if(value[i]!=0){
key[i] = array[i] + " " +String.valueOf(value[i]);
}
else{
key[i] = array[i];
}
final_string[0] = key[0];
if(key[i].charAt(7)=='L')
final_string[1] = key[i];
else if(key[i].charAt(7)=='T')
final_string[2] = key[i];
else if(key[i].charAt(7)=='-')
final_string[i-1] = key[i];
else if(key[i].charAt(7)=='{')
final_string[5] = key[i];
final_string[6] = key[6];
}
for(int i=0;i<7;i++)
{
System.out.println(final_string[i]);
}
System.out.println("\n");
System.out.printf("Tax: ",tax);
System.out.println(tax);
}
}
|
package ca.mcgill.ecse211.lab5;
import ca.mcgill.ecse211.odometer.*;
//import Odometer.Odometer;
//import Odometer.OdometerExceptions;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
/**
* This class is used to Navigate through a series of way points
*/
public class Navigation extends Thread {
private EV3LargeRegulatedMotor leftMotor;
private EV3LargeRegulatedMotor rightMotor;
private static final int MOTOR_STRAIGHT = 80;
private static final int MOTOR_ROTATE = 70;
public static final double WHEEL_RAD = 2.12;
public static final double TRACK = 16.05;
private boolean isNavigating;
private Odometer odometer;
public static int pointcounter;
// destination position
private double x;
private double y;
// angle toward destination
private double Theta;
// current position
private double currentX;
private double currentY;
private double currentTheta;
// difference between current position and destination position
private double dX; //
private double dY; //
private double dTheta;
// distance between current position and destination position
private double distance;
/**
* This is the class constructor
*
* @param leftMotor
* @param rightMotor
*
*/
public Navigation(EV3LargeRegulatedMotor leftMotor, EV3LargeRegulatedMotor rightMotor) {
this.leftMotor = leftMotor;
this.rightMotor = rightMotor;
try {
this.odometer = Odometer.getOdometer();
} catch (OdometerExceptions e) {
e.printStackTrace();
}
}
/**
* This method is used to calculate the distance to map point given Cartesian
* coordinates x and y
*
* @param x
* @param y
*
*/
public void travelTo(double x, double y) {
isNavigating = true;
this.x = x;
this.y = y;
// get current position
currentX = odometer.getX();
currentY = odometer.getY();
// compute the difference
dX = x - currentX;
dY = y - currentY;
distance = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
Theta = (Math.atan2(dX, dY)) * 180 / Math.PI; // convert from radius to degree
// rotate toward destination
turnTo(Theta);
// move straight
rightMotor.setSpeed(MOTOR_STRAIGHT);
leftMotor.setSpeed(MOTOR_STRAIGHT);
leftMotor.rotate(convertDistance(WHEEL_RAD, distance), true);
rightMotor.rotate(convertDistance(WHEEL_RAD, distance), false);
isNavigating = false;
}
/**
* This method is used to make sure robot rotates at the minimum angle when
* traveling to next waypoint
*
*/
public void turnTo(double Theta) {
currentTheta = odometer.getTheta(); // currentTheta is in degree
dTheta = Theta - currentTheta;
// avoid maximal angle turn
if (dTheta > 180) {
dTheta = 360 - dTheta;
} else if (dTheta < -180) {
dTheta = 360 + dTheta;
}
// turn minTheta degree
leftMotor.setSpeed(MOTOR_ROTATE);
rightMotor.setSpeed(MOTOR_ROTATE);
leftMotor.rotate(convertAngle(WHEEL_RAD, TRACK, dTheta), true);
rightMotor.rotate(-convertAngle(WHEEL_RAD, TRACK, dTheta), false);
}
public void turn(double Theta) {
currentTheta = odometer.getTheta(); // currentTheta is in degree
dTheta = Theta - currentTheta;
leftMotor.setSpeed(MOTOR_ROTATE);
rightMotor.setSpeed(MOTOR_ROTATE);
leftMotor.rotate(convertAngle(WHEEL_RAD, TRACK, Theta), true);
rightMotor.rotate(-convertAngle(WHEEL_RAD, TRACK, Theta), true);
}
/**
* This method determines whether another thread has called travelTo and turnTo
* methods or not
*
* @return
*/
public boolean isNavigating() {
return isNavigating;
}
/**
* This method allows the conversion of a distance to the total rotation of each
* wheel need to cover that distance.
*
* @param radius
* @param distance
* @return
*/
public static int convertDistance(double radius, double distance) {
return (int) ((180.0 * distance) / (Math.PI * radius));
}
/**
* This method allows the conversion of an angle to the total rotation of each
* wheel need to cover that distance.
*
* @param radius
* @param distance
* @param angle
* @return
*/
public static int convertAngle(double radius, double width, double angle) {
return convertDistance(radius, Math.PI * width * angle / 360.0);
}
}
|
package com.tencent.mm.plugin.location.model;
import com.tencent.mm.g.a.oa;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
class l$3 extends c<oa> {
final /* synthetic */ l kDB;
l$3(l lVar) {
this.kDB = lVar;
this.sFo = oa.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
oa oaVar = (oa) bVar;
x.d("MicroMsg.SubCoreLocation", "trackEvent state " + oaVar.bYW.ahg);
if (oaVar.bYW.ahg) {
if (l.aZi().aZn() && l.aZi().kDO) {
l.aZi().aZo();
}
} else if (l.aZi().aZn()) {
o aZi = l.aZi();
x.d("MicorMsg.TrackRefreshManager", "pause refresh");
aZi.kDO = true;
if (aZi.dMm != null) {
aZi.dMm.c(aZi.cXs);
}
if (aZi.kDF != null) {
aZi.kDF.b(aZi.kDU);
}
}
return false;
}
}
|
package engine.assets;
import org.lwjgl.BufferUtils;
import org.lwjgl.system.MemoryStack;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL13.GL_TEXTURE0;
import static org.lwjgl.opengl.GL13.glActiveTexture;
import static org.lwjgl.opengl.GL30.glGenerateMipmap;
import static org.lwjgl.stb.STBImage.*;
public class Texture {
private final int id;
public Texture(String fileName) throws Exception {
this(loadTexture(fileName));
}
public Texture(int id) {
this.id = id;
}
public void bind() {
glBindTexture(GL_TEXTURE_2D, id);
}
public void bind(int sampler) {
if (sampler >= 0 && sampler <= 31) {
glActiveTexture(GL_TEXTURE0 + sampler);
glBindTexture(GL_TEXTURE_2D, id);
}
}
public int getId() {
return id;
}
private static int loadTexture(String fileName) throws Exception {
int width;
int height;
ByteBuffer buf;
// Load Texture file
try (MemoryStack stack = MemoryStack.stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer channels = stack.mallocInt(1);
buf = stbi_load(fileName, w, h, channels, 4);
if (buf == null) {
throw new Exception("Image file [" + fileName + "] not loaded: " + stbi_failure_reason());
}
/* Get width and height of image */
width = w.get();
height = h.get();
}
// Create a new OpenGL texture
int textureId = glGenTextures();
// Bind the texture
glBindTexture(GL_TEXTURE_2D, textureId);
// Tell OpenGL how to unpack the RGBA bytes. Each component is 1 byte size
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload the texture data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, buf);
// Generate Mip Map
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(buf);
return textureId;
}
// public Texture(BufferedImage bi) {
//
// int width = bi.getWidth();
// int height = bi.getHeight();
//
// int[] pixels_raw; //new int[width * height * 4]
// pixels_raw = bi.getRGB(0, 0, width, height, null, 0, width);
//
// ByteBuffer pixels = BufferUtils.createByteBuffer(width * height * 4);
// int pixel;
// for (int j = 0; j < height; j++) {
// for (int i = 0; i < width; i++) {
// pixel = pixels_raw[j * width + i];
// pixels.put((byte) ((pixel >> 16) & 0xFF)); // RED
// pixels.put((byte) ((pixel >> 8) & 0xFF)); // GREEN
// pixels.put((byte) ((pixel) & 0xFF)); // BLUE
// pixels.put((byte) ((pixel >> 24) & 0xFF)); // ALPHA
// }
// }
//
// pixels.flip();
//
// id = glGenTextures();
//
// glBindTexture(GL_TEXTURE_2D, id);
//
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
//
// }
public void cleanup() {
glDeleteTextures(id);
}
}
|
package com.crewmaker.repository;
import com.crewmaker.entity.EventPlace;
import com.crewmaker.entity.EventPlaceOpinion;
import com.crewmaker.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface EventPlaceOpinionRepository extends JpaRepository<EventPlaceOpinion,Long> {
List<EventPlaceOpinion> findAllByEventPlaceEventPlaceId(Long id);
EventPlaceOpinion findByEventPlaceAndUserAuthorUsername(EventPlace eventPlace, String current);
EventPlaceOpinion findByEventPlaceAndUserAuthor(EventPlace eventPlace, User current);
}
|
// Sun Certified Java Programmer
// Chapter 7, P614
// Generics and Collections
import java.util.*;
public class Tester614 {
public void addAnimal(Animal[] animals) {
animals[0] = new Dog(); // no problem, any Animal works
// in Animal[]
}
public void addAnimal(ArrayList<Animal> animals) {
animals.add(new Dog()); // sometimes allowed...
}
public void foo() {
Dog[] dogs = {new Dog(), new Dog()};
addAnimal(dogs); // no problem, send the Dog[] to the method
}
public void addAnimal(Animal[] animals) {
animals[0] = new Dog(); // ok, any Animal subtype works
}
// P615
public void foo() {
Cat[] cats = {new Cat(), new Cat()};
addAnimal(cats); // no problem, send the Cat[] to the method
}
public void addAnimal(Animal[] animals) {
animals[0] = new Dog(); // Eeek! We just put a Dog
// in a Cat array!
}
public static void main(String[] args) {
}
}
|
package com.igp.authenticationservice.controllers;
import org.springframework.web.bind.annotation.*;
@RestController("/hello")
public class HelloWorldController {
@RequestMapping(path = "/hello/{name}", method = RequestMethod.GET)
public String helloWorld(@PathVariable("name") String string) {
return String.format("Hello %s!", string);
}
}
|
package com.mochasoft.fk.cache.ehcache;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
public class EhcacheUtil {
private static CacheManager ehcacheManager = CacheManager.getInstance();
private static ConcurrentMap<String, Ehcache> ehcaches;
public static String[] getCacheNames(){
return ehcacheManager.getCacheNames();
}
public static Map getAppCaches(){
try {
Field field = CacheManager.class.getDeclaredField("ehcaches");
field.setAccessible(true);
ehcaches = (ConcurrentMap<String, Ehcache>) field.get(ehcacheManager);
field.setAccessible(false);
Ehcache ehcache = ehcaches.get("ehcache");
boolean flag = ehcaches.get("ehcache") instanceof Cache;
System.out.println(flag);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Map map = new HashMap();
String[] cacheNames = getCacheNames();
for (int i = 0; i < cacheNames.length; i++) {
String cacheName = cacheNames[i];
Cache cache = getCache(cacheName);
map.put(cacheName, cache);
}
return map;
}
public static Cache getCache(String cacheName){
Cache cache = ehcacheManager.getCache(cacheName);
return cache;
}
}
|
package example.test.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Liu Lei
* @date 2018/11/26
*/
public class DateUtilsTest {
private static ExecutorService threadExecutor = new ThreadPoolExecutor(4, 20, 10L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10000),
new ThreadFactoryBuilder().setNameFormat("rate-voucher-thread").build(),
new ThreadPoolExecutor.AbortPolicy());
@Test
public void getEndOfDay() throws InterruptedException {
threadExecutor.execute(() -> {
try {
synchronized (this) {
this.wait(3000L);
}
System.out.println(111);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
|
package com.bfchengnuo.security.core.validate.code;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 基本验证码属性
*
* @author Created by 冰封承諾Andy on 2019/8/2.
*/
@Data
@AllArgsConstructor
public class ValidateCode implements Serializable {
private String code;
/**
* 过期时间
*/
private LocalDateTime expireTime;
public ValidateCode(String code, int expireIn4Second) {
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn4Second);
}
public boolean isExpired() {
return LocalDateTime.now().isAfter(expireTime);
}
}
|
package com.sample.bookstore.app;
import java.util.List;
import com.sample.bookstore.dao.BookDAO;
import com.sample.bookstore.dao.OrderDAO;
import com.sample.bookstore.util.KeyboardUtil;
import com.sample.bookstore.vo.Book;
import com.sample.bookstore.vo.Order;
public class BookstoreOrderApp {
public static void main(String[] args) throws Exception {
OrderDAO orderDao = new OrderDAO();
while (true) {
System.out.println("---------------------------------------");
System.out.println("[OrderDAO 기능 확인 APP]");
System.out.println("---------------------------------------");
System.out.println("1.등록 2.전체조회 3.검색 0.종료");
System.out.println("---------------------------------------");
System.out.print("메뉴를 선택하세요: ");
int menuNo = KeyboardUtil.nextInt();
if (menuNo == 0) {
System.out.println("---------------------------------------");
System.out.println("[프로그램 종료]");
System.out.println("---------------------------------------");
KeyboardUtil.close();
break;
} else if (menuNo == 1) {
// System.out.println("---------------------------------------");
// System.out.println("[주문 등록]");
// System.out.println("---------------------------------------");
//
// Order order = new Order();
// System.out.print("고객아이디를 입력하세요: ");
// order.setUserId(KeyboardUtil.nextString());
// System.out.print("도서번호를 입력하세요: ");
// int bookNo = KeyboardUtil.nextInt();
// order.setBookNo(bookNo);
// System.out.print("수량을 입력하세요: ");
// int amount = KeyboardUtil.nextInt();
// order.setAmount(amount);
//
// BookDAO bookDao = new BookDAO();
// Book book = bookDao.getBookByNo(bookNo);
// order.setPrice(book.getDiscountPrice()*amount);
//
// orderDao.addOrder(order);
// System.out.println("---------------------------------------");
// System.out.println("[주문 등록 절차가 완료되었습니다.]\n\n");
} else if (menuNo == 2) {
System.out.println("---------------------------------------");
// System.out.println("[주문 내역 조회]");
// System.out.println("---------------------------------------");
// System.out.print("고객아이디를 입력하세요: ");
// List<Order> orders = orderDao.getOrdersByUserId(KeyboardUtil.nextString());
// System.out.printf("%-3s\t%-7s\t%-3s\t%-3s\t%-3s\t%-7s\n"
// ,"주문번호","ID","도서번호","수량","주문금액","주문일자");
// System.out.println("---------------------------------------");
// for (Order order : orders) {
// System.out.printf("%-3s\t%-7s\t%-3s\t%-3s\t%-3s\t%-7s\n"
// ,order.getOrderNo(), order.getUserId(), order.getBookNo(), order.getAmount(), order.getPrice(), order.getRegistredDate());
// }
// System.out.println("---------------------------------------");
// System.out.println("[주문 내역 조회가 완료되었습니다.]\n\n");
// } else if (menuNo == 3) {
// System.out.println("---------------------------------------");
// System.out.println("[주문 번호로 검색]");
// System.out.println("---------------------------------------");
// System.out.print("주문번호를 입력하세요: ");
// Order order = orderDao.getOrderByNo(KeyboardUtil.nextInt());
// System.out.printf("%-3s\t%-7s\t%-3s\t%-3s\t%-3s\t%-7s\n"
// ,"주문번호","ID","도서번호","수량","주문금액","주문일자");
// System.out.println("---------------------------------------");
// System.out.printf("%-3s\t%-7s\t%-3s\t%-3s\t%-3s\t%-7s\n"
// ,order.getOrderNo(), order.getUserId(), order.getBookNo(), order.getAmount(), order.getPrice(), order.getRegistredDate());
// System.out.println("---------------------------------------");
// System.out.println("[주문 번호 검색이 완료되었습니다.]\n\n");
}
}
}
}
|
package com.company;
import java.util.Random;
public class Flicker_Phrase {
public static void main(String[] args) {
Random random= new Random();
for (int i=0; i<6; i++) {
int num = 1 + random.nextInt(5);
if (num == 1) {
first();
} else if (num == 2) {
second();
} else if (num == 3) {
third();
} else if (num == 4) {
forth();
} else if (num == 5) {
fifth();
}
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I pledge allegiance to the flag.");
}
public static void first(){
System.out.print("I ");
}
public static void second(){
System.out.print(" pledge");
}
public static void third(){
System.out.print(" allegiance");
}
public static void forth(){
System.out.print(" to the");
}
public static void fifth(){
System.out.print(" flag.");
}
}
|
package com.worker.framework.python;
public class PythonProcessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PythonProcessException(String message) {
super(message);
}
public PythonProcessException(String message, Throwable cause) {
super(message, cause);
}
public PythonProcessException(Throwable cause) {
super(cause);
}
}
|
package com.Entoss;
public interface Lift {
public void move();
}
|
package ru.otus.gwt.client.gin;
/*
* Created at autumn 2018.
*/
import com.google.gwt.core.client.GWT;
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import ru.otus.gwt.client.service.LoginServiceAsync;
import ru.otus.gwt.client.service.InsideServiceAsync;
import ru.otus.gwt.client.text.ApplicationConstants;
import ru.otus.gwt.client.validation.ValidatorFactory.GwtValidator;
import ru.otus.gwt.client.widget.AddView.AddViewUiBinder;
import ru.otus.gwt.client.widget.SearchView.SearchViewUiBinder;
import ru.otus.gwt.client.widget.LoginView.LoginViewUiBinder;
import ru.otus.gwt.client.widget.image.ApplicationImages;
@GinModules(ApplicationGinModule.class)
public interface ApplicationInjector extends Ginjector {
ApplicationInjector INSTANCE = GWT.create(ApplicationInjector.class);
LoginServiceAsync getLoginService();
InsideServiceAsync getInsideService();
ApplicationConstants getConstants();
LoginViewUiBinder getLoginViewUiBinder();
AddViewUiBinder getAddViewUiBinder();
SearchViewUiBinder getSearchViewUiBinder();
GwtValidator getValidator();
ApplicationImages getImages();
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package jie.android.ip.screen.play;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import jie.android.ip.CommonConsts.PackConfig;
import jie.android.ip.CommonConsts.ScreenConfig;
import jie.android.ip.Resources;
import jie.android.ip.common.actor.ScreenGroup;
import jie.android.ip.screen.play.lesson.BaseLesson;
import jie.android.ip.screen.play.lesson.LessonFour;
import jie.android.ip.screen.play.lesson.LessonOne;
import jie.android.ip.screen.play.lesson.LessonThree;
import jie.android.ip.screen.play.lesson.LessonTwo;
public class LessonGroup extends ScreenGroup {
private final Resources resources;
private final TextureAtlas textureAtlas;
private final TweenManager tweenManager;
final PlayScreenListener.RendererInternalEventListener internalListener;
private BaseLesson lesson;
public LessonGroup(final PlayScreen screen, final PlayScreenListener.RendererInternalEventListener internalListener) {
super(screen);
this.resources = super.resources;
this.textureAtlas = super.resources.getTextureAtlas(PackConfig.SCREEN_PLAY);
this.tweenManager = this.screen.getTweenManager();
this.internalListener = internalListener;
initStage();
}
@Override
protected void initStage() {
// this.setColor(1.0f, 1.0f, 1.0f, 0.4f);
this.setTouchable(Touchable.disabled);
this.setBounds(0, 0, ScreenConfig.WIDTH, ScreenConfig.HEIGHT);
screen.addActor(this);
}
private void loadNextStage() {
if (lesson != null) {
if (!lesson.loadNextStage()) {
closeLesson();
}
}
}
public void closeLesson() {
if (internalListener != null) {
internalListener.onLessonGroupRemoved();
}
screen.removeActor(this);
}
protected void onTrapActorHit(float x, float y) {
loadNextStage();
}
public boolean loadLesson(int id) {
switch(id) {
case 1:
lesson = new LessonOne(this);
break;
case 2:
lesson = new LessonTwo(this);
break;
case 3:
lesson = new LessonThree(this);
break;
case 4:
lesson = new LessonFour(this);
break;
default:
return false;
}
if (internalListener != null) {
internalListener.onLessonGroupAdded();
}
return true;
}
public final Resources getResources() {
return resources;
}
public final TextureAtlas getTextureAtlas() {
return textureAtlas;
}
public final TweenManager getTweenManager() {
return tweenManager;
}
public boolean hitTrap(int x, int y, boolean up) {
if (lesson != null) {
if (lesson.hitTrap(x, y)) {
if (up) {
onTrapActorHit(x, y);
}
return true;
}
}
return false;
}
public void onExecuteEnd(boolean succ) {
loadNextStage();
}
}
|
package ga.fitness;
import ga.Individual;
import ga.Population;
import java.util.List;
import neural_net.Network;
import driver.DataPoint;
import driver.TrainingMethod;
public class FitnessDefault extends Fitness {
/**
* Calculate the fitness based on how well the individuals'
* performances at a specific task
* (in this case training a neural network).
*
* @param popoulation The population of individuals whose fitnesses will be evaluated.
* @param neuralNetwork The neural network that will be used to test fitness.
* @param testSet The set of test data to evaluate fitness with.
*/
public void calculateFitness(Population population, Network neuralNetwork, List<DataPoint> testSet) {
double fitness = 0.0;
// loop through every individual in the population
for (Individual individual : population.getIndividuals()){
// convert the individual's genes to network weights
neuralNetwork.setWeights(individual.getGenes());
//feed test set forward in network
List<Double> outputs;
int correct = 0;
// loop through all data points
for (DataPoint dataPoint : testSet) {
// feed data point through network
outputs = TrainingMethod.networkOperations.feedForward(dataPoint);
// get class found by neural network
int classFound = TrainingMethod.networkOperations.getMaxIndex(outputs);
// store class expected from data point
int classExpected = dataPoint.getClassIndex();
// increment count if classification was correct
if (classFound == classExpected)
correct++;
outputs.clear();
}
// divide by testSet size to get % correct
fitness = ((double) correct) / testSet.size();
// set individual's fitness as % correct
individual.setFitness(fitness);
}
}
}
|
package com.tencent.mm.pluginsdk.model.app;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.ac.a;
import com.tencent.mm.sdk.platformtools.x;
class w$1 implements OnCancelListener {
final /* synthetic */ w qAb;
public w$1(w wVar) {
this.qAb = wVar;
}
public final void onCancel(DialogInterface dialogInterface) {
x.w("MicroMsg.LoadAppInfoAfterLogin", "do init canceled");
g.DF().c(this.qAb.bKq);
a.bmi().b(7, this.qAb);
if (this.qAb.qAa != null) {
this.qAb.qAa.Zq();
}
}
}
|
package com.example.fitnesstracker;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openWorkoutsBtn = (Button)findViewById(R.id.openWorkoutsButton);
openWorkoutsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startIntent = new Intent(getApplicationContext(), workoutsView.class);
startActivity(startIntent);
}
});
}
}
|
package TrabalhoFinal;
import java.util. *;
public class Compra {
List<Veiculo> listaVeiculos = new ArrayList<Veiculo>(100);
}
|
package com.lupan.HeadFirstDesignMode.chapter2_observer.observers;
import com.lupan.HeadFirstDesignMode.chapter2_observer.interfaces.IDisplay;
import com.lupan.HeadFirstDesignMode.chapter2_observer.interfaces.IObserver;
/**
* TODO
*
* @author lupan
* @version 2016/3/18 0018
*/
public class Observer2 implements IObserver,IDisplay {
private double temperature;
@Override
public void update(double temperature) {
this.temperature = temperature;
this.display();
}
@Override
public void display() {
if(temperature<10){
System.out.println("观察者2:\n太冷了,记得加衣服哦。。。");
}else if(10<=temperature && temperature<30){
System.out.println("观察者2:\n温度适宜。。。");
}else{
System.out.println("观察者2:\n热成狗了。。。");
}
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import com.tencent.mm.ui.tools.k;
import com.tencent.smtt.sdk.WebView;
class SnsSightPlayerUI$13 implements OnTouchListener {
final /* synthetic */ SnsSightPlayerUI obb;
SnsSightPlayerUI$13(SnsSightPlayerUI snsSightPlayerUI) {
this.obb = snsSightPlayerUI;
}
public final boolean onTouch(View view, MotionEvent motionEvent) {
float f = 1.0f;
SnsSightPlayerUI.m(this.obb).onTouchEvent(motionEvent);
if (SnsSightPlayerUI.n(this.obb) == null) {
SnsSightPlayerUI.a(this.obb, VelocityTracker.obtain());
}
SnsSightPlayerUI.n(this.obb).addMovement(motionEvent);
switch (motionEvent.getAction() & WebView.NORMAL_MODE_ALPHA) {
case 0:
SnsSightPlayerUI.a(this.obb, motionEvent.getX());
SnsSightPlayerUI.b(this.obb, motionEvent.getY());
break;
case 1:
if (SnsSightPlayerUI.o(this.obb)) {
((View) SnsSightPlayerUI.f(this.obb)).setPivotX((float) (this.obb.ndZ.getWidth() / 2));
((View) SnsSightPlayerUI.f(this.obb)).setPivotY((float) (this.obb.ndZ.getHeight() / 2));
((View) SnsSightPlayerUI.f(this.obb)).setScaleX(1.0f);
((View) SnsSightPlayerUI.f(this.obb)).setScaleY(1.0f);
((View) SnsSightPlayerUI.f(this.obb)).setTranslationX(0.0f);
((View) SnsSightPlayerUI.f(this.obb)).setTranslationY(0.0f);
SnsSightPlayerUI snsSightPlayerUI = this.obb;
if (snsSightPlayerUI.contextMenuHelper == null) {
snsSightPlayerUI.contextMenuHelper = new k(snsSightPlayerUI.mController.tml);
}
snsSightPlayerUI.contextMenuHelper.a((View) snsSightPlayerUI.hEl, snsSightPlayerUI.oba, snsSightPlayerUI.hqV);
if (SnsSightPlayerUI.p(this.obb) != null) {
SnsSightPlayerUI.p(this.obb).setVisibility(0);
}
SnsSightPlayerUI.c(this.obb, false);
SnsSightPlayerUI.b(this.obb, false);
break;
} else if (!SnsSightPlayerUI.l(this.obb) || SnsSightPlayerUI.q(this.obb)) {
SnsSightPlayerUI.b(this.obb, false);
break;
} else {
this.obb.ayH();
SnsSightPlayerUI.b(this.obb, false);
return true;
}
break;
case 2:
float translationX = ((View) SnsSightPlayerUI.f(this.obb)).getTranslationX();
float translationY = ((View) SnsSightPlayerUI.f(this.obb)).getTranslationY();
VelocityTracker n = SnsSightPlayerUI.n(this.obb);
n.computeCurrentVelocity(1000);
int xVelocity = (int) n.getXVelocity();
int yVelocity = (int) n.getYVelocity();
if ((Math.abs(translationX) > 250.0f || Math.abs(yVelocity) <= Math.abs(xVelocity) || yVelocity <= 0 || SnsSightPlayerUI.q(this.obb)) && !SnsSightPlayerUI.l(this.obb)) {
SnsSightPlayerUI.c(this.obb, false);
} else {
float height = 1.0f - (translationY / ((float) this.obb.ndZ.getHeight()));
if (height <= 1.0f) {
f = height;
}
if (((yVelocity > 0 && f < SnsSightPlayerUI.r(this.obb)) || yVelocity < 0) && ((double) f) >= 0.5d) {
SnsSightPlayerUI.a(this.obb, (int) translationX);
SnsSightPlayerUI.b(this.obb, (int) translationY);
SnsSightPlayerUI.c(this.obb, f);
if (SnsSightPlayerUI.p(this.obb) != null) {
SnsSightPlayerUI.p(this.obb).setVisibility(8);
}
((View) SnsSightPlayerUI.f(this.obb)).setPivotX((float) (this.obb.ndZ.getWidth() / 2));
((View) SnsSightPlayerUI.f(this.obb)).setPivotY((float) (this.obb.ndZ.getHeight() / 2));
((View) SnsSightPlayerUI.f(this.obb)).setScaleX(f);
((View) SnsSightPlayerUI.f(this.obb)).setScaleY(f);
SnsSightPlayerUI.s(this.obb).setAlpha(f);
}
SnsSightPlayerUI.c(this.obb, true);
}
if (translationY > 200.0f) {
SnsSightPlayerUI.d(this.obb, false);
} else if (translationY > 10.0f) {
SnsSightPlayerUI.d(this.obb, true);
}
if (translationY > 50.0f) {
((View) SnsSightPlayerUI.f(this.obb)).setOnLongClickListener(null);
}
if (SnsSightPlayerUI.n(this.obb) != null) {
SnsSightPlayerUI.n(this.obb).recycle();
SnsSightPlayerUI.a(this.obb, null);
}
if (SnsSightPlayerUI.l(this.obb)) {
return true;
}
break;
}
return false;
}
}
|
package com.e6soft.bpm.service;
import java.util.List;
import com.e6soft.api.bpm.dto.BpmFormData;
import com.e6soft.api.bpm.dto.BpmRunInfo;
import com.e6soft.bpm.dto.FLowNextOperatorInfo;
import com.e6soft.bpm.dto.OperatorInfo;
import com.e6soft.bpm.model.FlowCurrentOperator;
import com.e6soft.core.service.BaseService;
public interface FlowCurrentOperatorService extends BaseService<FlowCurrentOperator,String> {
/**
* 返回操作数量
* @return
* @author 王瑜
*/
public int getAllByNodeId(String nodeId);
/**
* 根据操作id获取所有未操作者<br>
* 旧方法中通过java代码获取代码,现在已经改成用Sql处理,暂时保留
* @param operatorId
* @return
*/
public List<OperatorInfo> getUndoOperatorById(String operatorId);
/**
* 提交任务
* @param bpmFormData
*/
public void completeTask(BpmFormData bpmFormData);
/**
* 根据出口提交任务
* @param operatorId
* @param userId
* @param linkId
*/
public void completeTask(String linkId,BpmFormData bpmFormData);
/**
* 保存下一个节点操作者
* @param bpmRunInfo
* @param info
*/
public void saveNextOperator(BpmRunInfo bpmRunInfo,FLowNextOperatorInfo info);
/**
* 更新当前任务状态
* @param bpmFormData
*/
public void updateCurrentOperator(BpmFormData bpmFormData);
/**
* 根据流程实例id删除流程
* @param requestId
*/
public void deleteByRequestId(String requestId);
public List<String> getCurentOperatorId(String requestId);
/**
* 验证当前操作者是否合法
* @param userId
* @param operator
* @return
*/
public boolean checkCurrentOperatorId(String userId,FlowCurrentOperator operator);
}
|
package com.koreait.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Ex07_request")
public class Ex07_request extends HttpServlet {
private static final long serialVersionUID = 1L;
public Ex07_request() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 기본 3종
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>");
out.print("회원 가입 결과");
out.print("</title>");
out.print("</head>");
out.print("<body>");
// Ex07_request.html 에서 전달된 데이터 처리하기
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String name = request.getParameter("name");
String email = request.getParameter("email");
String gender = request.getParameter("gender");
String[] hobbies = request.getParameterValues("hobbies");
out.print("<ul>");
out.print("<li>아이디: " + id + "</li>");
out.print("<li>패스워드: " + pw + "</li>");
out.print("<li>이름: " + name + "</li>");
out.print("<li>이메일: " + email + "</li>");
out.print("<li>성별: " + gender + "</li>");
out.print("<li>취미");
out.print("<ul>");
for ( String hobby : hobbies ) {
out.print("<li>" + hobby + "</li>");
}
out.print("</ul>");
out.print("</li>");
out.print("</ul>");
out.print("</body>");
out.print("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
/**
*/
package com.rockwellcollins.atc.limp;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Enum Type</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.rockwellcollins.atc.limp.EnumType#getEnumDef <em>Enum Def</em>}</li>
* </ul>
*
* @see com.rockwellcollins.atc.limp.LimpPackage#getEnumType()
* @model
* @generated
*/
public interface EnumType extends Type
{
/**
* Returns the value of the '<em><b>Enum Def</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Enum Def</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Enum Def</em>' reference.
* @see #setEnumDef(EnumTypeDef)
* @see com.rockwellcollins.atc.limp.LimpPackage#getEnumType_EnumDef()
* @model
* @generated
*/
EnumTypeDef getEnumDef();
/**
* Sets the value of the '{@link com.rockwellcollins.atc.limp.EnumType#getEnumDef <em>Enum Def</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Enum Def</em>' reference.
* @see #getEnumDef()
* @generated
*/
void setEnumDef(EnumTypeDef value);
} // EnumType
|
/**
* MouTai
*/
package com.kite.modules.att.entity;
import com.kite.common.persistence.DataEntity;
import com.kite.common.utils.excel.annotation.ExcelField;
/**
* 教练员资格Entity
* @author lyb
* @version 2019-11-13
*/
public class SysCertificatesCoach extends DataEntity<SysCertificatesCoach> {
private static final long serialVersionUID = 1L;
private String coathId; // 教练员id
private String qualification; // 资格名称
private String obtainYearMonth; // 考获年月
public SysCertificatesCoach() {
super();
}
public SysCertificatesCoach(String id){
super(id);
}
@ExcelField(title="教练员id", align=2, sort=1)
public String getCoathId() {
return coathId;
}
public void setCoathId(String coathId) {
this.coathId = coathId;
}
@ExcelField(title="资格名称", align=2, sort=2)
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
@ExcelField(title="考获年月", align=2, sort=3)
public String getObtainYearMonth() {
return obtainYearMonth;
}
public void setObtainYearMonth(String obtainYearMonth) {
this.obtainYearMonth = obtainYearMonth;
}
}
|
package com.hdc.seckill.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName RespBean
* @Description 定义登陆成功和失败的弹出信息方法
* @Author prog_evil
* @Date 2021/7/19 9:59 下午
* @Version 1.0
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RespBean {
private long code;
private String message;
private Object obj;
//成功返回结果
public static RespBean success(){
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), null);
}
public static RespBean success(Object obj){
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), obj);
}
//失败返回结果
public static RespBean error(RespBeanEnum respBeanEnum){
return new RespBean(respBeanEnum.ERROR.getCode(), respBeanEnum.ERROR.getMessage(), null);
}
public static RespBean error(RespBeanEnum respBeanEnum,Object obj){
return new RespBean(respBeanEnum.ERROR.getCode(), respBeanEnum.ERROR.getMessage(), obj);
}
}
|
package com.klocek.lowrez;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
/**
* Created by Konrad on 2016-04-17.
*/
public class Help extends GameScreen {
private Texture helpTexture1;
private Texture helpTexture2;
private Texture actual;
public Help(LowRez game) {
super(game);
helpTexture1 = new Texture(Gdx.files.internal("help1.png"));
helpTexture2 = new Texture(Gdx.files.internal("help2.png"));
actual = helpTexture1;
getControls().setRightArrowIdle(false);
getControls().setLeftArrowIdle(true);
}
@Override
public void goLeft() {
if(actual == helpTexture2) {
actual = helpTexture1;
getControls().setLeftArrowIdle(true);
getControls().setRightArrowIdle(false);
}
}
@Override
public void goRight() {
if(actual == helpTexture1) {
actual = helpTexture2;
getControls().setLeftArrowIdle(false);
} else {
getGame().backToMenu();
}
}
@Override
public void render(float delta) {
getBatch().setProjectionMatrix(getCamera().projection);
getBatch().setTransformMatrix(getCamera().view);
Gdx.gl.glClearColor(255, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
getCamera().update();
getViewport().apply();
getBatch().begin();
getBatch().draw(actual, 0, 128);
getControls().update(delta);
getBatch().end();
}
@Override
public void dispose() {
helpTexture1.dispose();
helpTexture2.dispose();
}
}
|
package Stack;
import java.util.Stack;
public class ScoreOfParentheses_856 {
/*856.括号的分数*/
/*
括号问题一律用栈解决;
栈底压入0作为最终结果;
当压入‘(’时判断下一位是否为‘)’若是压入1,否则压入0;
当压入‘)’时判断上一位是否为‘(’若是将栈顶元素加一,否则栈顶元素乘2;
*/
public int scoreOfParentheses(String S) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
for(int i = 0; i < S.length(); i++){
if(S.charAt(i) == '('){
if(S.charAt(i + 1) == ')'){
stack.push(1);
}else{
stack.push(0);
}
}else{
int num = stack.pop();
if(num == 1 && S.charAt(i - 1) == '('){
stack.push(stack.pop() + 1);
}else{
num *= 2;
stack.push(stack.pop() + num);
}
}
}
return stack.pop();
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be declared
* globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static final int LEFT_MOTOR_PORT = 0;
public static final int RIGHT_MOTOR_PORT = 1;
// Quadrature Encoders on the ROMI - uses 2 ports per encoder
// Left Side with Ports 4 and 5
public static final int LEFT_ENCODER_A = 4;
public static final int LEFT_ENCODER_B = 5;
// Right Side with Ports 6 and 7
public static final int RIGHT_ENCODER_A = 6;
public static final int RIGHT_ENCODER_B = 7;
// Additional parameters - not specific PORTS related
// Wheel diameter is 2.83"
// public static final double WHEEL_DIA = 2.83;
public static final double WHEEL_DIA = 2.76;
// ROMI's encoder is 1440 pulse per revolution
// => resolution = 1440 pulses/360 degree or 4 pulse/degree of rotations) or 0.25 degree/pulse
// public static final double PULSES_PER_REVOLUTION = 1440.0;
public static final double PULSES_PER_REVOLUTION = 1437.0;
// convert to inches per revolution -> (Dia * Pi)/Pulse_Per_Rev
public static final double INCHES_PER_PULSE = Math.PI * WHEEL_DIA / PULSES_PER_REVOLUTION;
//
// Width of Robot = Wheel_Track
public static final double WHEEL_TRACK = 5.25;
public static final double INCHES_PER_TURN_DEGREE = Math.PI * WHEEL_TRACK / 360.0;
//
public static final int ControllerPort = 1;
}
|
package com.jyhd.black.service;
import com.jyhd.black.domain.ActivityData;
import com.jyhd.black.domain.Result;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpSession;
public interface AdminService {
Result loginPost(String account, String password, HttpSession session);
Page<ActivityData> activityAll(String userId,Pageable pageable);
int activitySum();
int activityPaySum();
int activityNotPaySum();
int active(String date);
}
|
package VSMOutsideFeatureObjects;
import java.util.Stack;
import VSMInterfaces.OutsideFeatureObject;
import VSMInterfaces.OutsideFeatureObjectStore;
import VSMUtilityClasses.Alphabet;
import VSMUtilityClasses.VSMUtil;
import edu.berkeley.nlp.syntax.Tree;
public class OutsideTreeabove1 implements OutsideFeatureObject {
/**
* TODO Alphabets that stores all the features
*/
private Alphabet outsideTreeAbove1;
private Alphabet outsideTreeAbove1Filtered;
/**
* TODO Initialize the inside_unary alphabet in the constructor
*/
public OutsideTreeabove1(OutsideFeatureObjectStore objectStore) {
this.outsideTreeAbove1 = new Alphabet();
this.outsideTreeAbove1Filtered = new Alphabet();
/*
* Counts
*/
this.outsideTreeAbove1.turnOnCounts();
this.outsideTreeAbove1Filtered.turnOnCounts();
/*
* Register
*/
objectStore.registerOutsideFeatureObject(this);
}
/**
* For description see the interface description
*/
@Override
public String getOutsideFeature(Stack<Tree<String>> foottoroot) {
/*
*
* extracting the feature TODO. The code is written by Dr Shay Cohen
*/
String feature = null;
if (foottoroot.size() >= 2) {
Tree<String> footTree = foottoroot.pop();
Tree<String> parentTree = foottoroot.pop();
/*
* TODO
*/
feature = VSMUtil.getStringFromParent(parentTree, footTree);
/*
* Putting them back TODO
*/
foottoroot.push(parentTree);
foottoroot.push(footTree);
} else {
/*
* TODO
*/
feature = "NOTVALID";
}
return feature;
}
@Override
public VSMUtilityClasses.Alphabet getFeatureDictionary() {
return this.outsideTreeAbove1;
}
@Override
public VSMUtilityClasses.Alphabet getFilteredDictionary() {
return this.outsideTreeAbove1Filtered;
}
}
|
/*
* UniTime 3.4 - 3.5 (University Timetabling Application)
* Copyright (C) 2012 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* 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 org.unitime.timetable.security.permissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.unitime.timetable.model.Curriculum;
import org.unitime.timetable.model.Department;
import org.unitime.timetable.model.DepartmentStatusType;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.security.UserContext;
import org.unitime.timetable.security.rights.Right;
/**
* @author Tomas Muller
*/
public class CurriculumPermissions {
@PermissionForRight(Right.CurriculumView)
public static class CurriculumView implements Permission<Session> {
@Autowired
PermissionSession permissionSession;
@Override
public boolean check(UserContext user, Session source) {
return permissionSession.check(user, source, DepartmentStatusType.Status.OwnerView, DepartmentStatusType.Status.ManagerView);
}
@Override
public Class<Session> type() { return Session.class; }
}
@PermissionForRight(Right.CurriculumAdd)
public static class CurriculumAdd implements Permission<Department> {
@Autowired
PermissionDepartment permissionDepartment;
@Override
public boolean check(UserContext user, Department source) {
return source != null && permissionDepartment.check(user, source, DepartmentStatusType.Status.OwnerEdit, DepartmentStatusType.Status.ManagerEdit);
}
@Override
public Class<Department> type() { return Department.class; }
}
@PermissionForRight(Right.CurriculumEdit)
public static class CurriculumEdit implements Permission<Curriculum> {
@Autowired
PermissionDepartment permissionDepartment;
@Override
public boolean check(UserContext user, Curriculum source) {
Department department = (source == null ? null : source.getDepartment());
return department != null && permissionDepartment.check(user, department, DepartmentStatusType.Status.OwnerEdit, DepartmentStatusType.Status.ManagerEdit);
}
@Override
public Class<Curriculum> type() { return Curriculum.class; }
}
@PermissionForRight(Right.CurriculumDetail)
public static class CurriculumDetail implements Permission<Curriculum> {
@Autowired
PermissionSession permissionSession;
@Override
public boolean check(UserContext user, Curriculum source) {
return source != null && permissionSession.check(user, source.getDepartment().getSession());
}
@Override
public Class<Curriculum> type() { return Curriculum.class; }
}
@PermissionForRight(Right.CurriculumDelete)
public static class CurriculumDelete extends CurriculumEdit { }
@PermissionForRight(Right.CurriculumMerge)
public static class CurriculumMerge extends CurriculumEdit { }
@PermissionForRight(Right.CurriculumAdmin)
public static class CurriculumAdmin implements Permission<Session> {
@Autowired PermissionSession permissionSession;
@Override
public boolean check(UserContext user, Session source) {
return user.getCurrentAuthority().hasRight(Right.DepartmentIndependent) && permissionSession.check(user, source);
}
@Override
public Class<Session> type() { return Session.class; }
}
@PermissionForRight(Right.CurriculumProjectionRulesDetail)
public static class CurriculumProjectionRulesDetail extends CurriculumView {}
@PermissionForRight(Right.CurriculumProjectionRulesEdit)
public static class CurriculumProjectionRulesEdit extends CurriculumAdmin {}
}
|
/*
* Copyright (C) 2021-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.services.fees.calculation.utils;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.CryptoApproveAllowance;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.CryptoCreate;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.CryptoDeleteAllowance;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.CryptoTransfer;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.CryptoUpdate;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenAccountWipe;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenBurn;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenCreate;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenFreezeAccount;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenGrantKycToAccount;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenMint;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenPause;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenRevokeKycFromAccount;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenUnfreezeAccount;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.TokenUnpause;
import com.hedera.mirror.web3.evm.store.Store;
import com.hedera.node.app.service.evm.accounts.HederaEvmContractAliases;
import com.hedera.services.fees.usage.state.UsageAccumulator;
import com.hedera.services.fees.usage.token.TokenOpsUsage;
import com.hedera.services.hapi.fees.usage.BaseTransactionMeta;
import com.hedera.services.hapi.fees.usage.SigUsage;
import com.hedera.services.hapi.fees.usage.crypto.CryptoOpsUsage;
import com.hedera.services.utils.accessors.TxnAccessor;
import com.hederahashgraph.api.proto.java.HederaFunctionality;
import java.util.EnumSet;
/**
* Copied Logic type from hedera-services. Differences with the original:
* 1. Remove FeeSchedule, UtilPrng, File logic
*/
public class AccessorBasedUsages {
public static final long THREE_MONTHS_IN_SECONDS = 7776000L;
private static final EnumSet<HederaFunctionality> supportedOps = EnumSet.of(
CryptoTransfer,
CryptoCreate,
CryptoUpdate,
CryptoApproveAllowance,
CryptoDeleteAllowance,
TokenCreate,
TokenBurn,
TokenMint,
TokenAccountWipe,
TokenFreezeAccount,
TokenUnfreezeAccount,
TokenPause,
TokenUnpause,
TokenRevokeKycFromAccount,
TokenGrantKycToAccount);
private final TokenOpsUsage tokenOpsUsage;
private final CryptoOpsUsage cryptoOpsUsage;
private final OpUsageCtxHelper opUsageCtxHelper;
public AccessorBasedUsages(
TokenOpsUsage tokenOpsUsage, CryptoOpsUsage cryptoOpsUsage, OpUsageCtxHelper opUsageCtxHelper) {
this.tokenOpsUsage = tokenOpsUsage;
this.cryptoOpsUsage = cryptoOpsUsage;
this.opUsageCtxHelper = opUsageCtxHelper;
}
public void assess(
SigUsage sigUsage,
TxnAccessor accessor,
UsageAccumulator into,
final Store store,
final HederaEvmContractAliases hederaEvmContractAliases) {
final var function = accessor.getFunction();
if (!supportedOps.contains(function)) {
throw new IllegalArgumentException("Usage estimation for " + function + " not yet migrated");
}
final var baseMeta = accessor.baseUsageMeta();
if (function == CryptoTransfer) {
estimateCryptoTransfer(sigUsage, accessor, baseMeta, into);
} else if (function == CryptoCreate) {
estimateCryptoCreate(sigUsage, accessor, baseMeta, into);
} else if (function == CryptoUpdate) {
estimateCryptoUpdate(sigUsage, accessor, baseMeta, into, store, hederaEvmContractAliases);
} else if (function == CryptoApproveAllowance) {
estimateCryptoApproveAllowance(sigUsage, accessor, baseMeta, into, store, hederaEvmContractAliases);
} else if (function == CryptoDeleteAllowance) {
estimateCryptoDeleteAllowance(sigUsage, accessor, baseMeta, into);
} else if (function == TokenCreate) {
estimateTokenCreate(sigUsage, accessor, baseMeta, into);
} else if (function == TokenBurn) {
estimateTokenBurn(sigUsage, accessor, baseMeta, into);
} else if (function == TokenMint) {
estimateTokenMint(sigUsage, accessor, baseMeta, into, store);
} else if (function == TokenFreezeAccount) {
estimateTokenFreezeAccount(sigUsage, accessor, baseMeta, into);
} else if (function == TokenUnfreezeAccount) {
estimateTokenUnfreezeAccount(sigUsage, accessor, baseMeta, into);
} else if (function == TokenAccountWipe) {
estimateTokenWipe(sigUsage, accessor, baseMeta, into);
} else if (function == TokenPause) {
estimateTokenPause(sigUsage, accessor, baseMeta, into);
} else if (function == TokenUnpause) {
estimateTokenUnpause(sigUsage, accessor, baseMeta, into);
}
}
public boolean supports(HederaFunctionality function) {
return supportedOps.contains(function);
}
private void estimateCryptoTransfer(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var xferMeta = accessor.availXferUsageMeta();
cryptoOpsUsage.cryptoTransferUsage(sigUsage, xferMeta, baseMeta, into);
}
private void estimateCryptoCreate(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var cryptoCreateMeta = accessor.getSpanMapAccessor().getCryptoCreateMeta(accessor);
cryptoOpsUsage.cryptoCreateUsage(sigUsage, baseMeta, cryptoCreateMeta, into);
}
private void estimateCryptoUpdate(
SigUsage sigUsage,
TxnAccessor accessor,
BaseTransactionMeta baseMeta,
UsageAccumulator into,
final Store store,
final HederaEvmContractAliases hederaEvmContractAliases) {
final var cryptoUpdateMeta = accessor.getSpanMapAccessor().getCryptoUpdateMeta(accessor);
final var cryptoContext =
opUsageCtxHelper.ctxForCryptoUpdate(accessor.getTxn(), store, hederaEvmContractAliases);
// explicitAutoAssocSlotLifetime is three months in services
cryptoOpsUsage.cryptoUpdateUsage(
sigUsage, baseMeta, cryptoUpdateMeta, cryptoContext, into, THREE_MONTHS_IN_SECONDS);
}
private void estimateCryptoApproveAllowance(
SigUsage sigUsage,
TxnAccessor accessor,
BaseTransactionMeta baseMeta,
UsageAccumulator into,
final Store store,
final HederaEvmContractAliases hederaEvmContractAliases) {
final var cryptoApproveMeta = accessor.getSpanMapAccessor().getCryptoApproveMeta(accessor);
final var cryptoContext = opUsageCtxHelper.ctxForCryptoAllowance(accessor, store, hederaEvmContractAliases);
cryptoOpsUsage.cryptoApproveAllowanceUsage(sigUsage, baseMeta, cryptoApproveMeta, cryptoContext, into);
}
private void estimateCryptoDeleteAllowance(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var cryptoDeleteAllowanceMeta = accessor.getSpanMapAccessor().getCryptoDeleteAllowanceMeta(accessor);
cryptoOpsUsage.cryptoDeleteAllowanceUsage(sigUsage, baseMeta, cryptoDeleteAllowanceMeta, into);
}
private void estimateTokenCreate(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenCreateMeta = accessor.getSpanMapAccessor().getTokenCreateMeta(accessor);
tokenOpsUsage.tokenCreateUsage(sigUsage, baseMeta, tokenCreateMeta, into);
}
private void estimateTokenBurn(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenBurnMeta = accessor.getSpanMapAccessor().getTokenBurnMeta(accessor);
tokenOpsUsage.tokenBurnUsage(sigUsage, baseMeta, tokenBurnMeta, into);
}
private void estimateTokenMint(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into, Store store) {
final var tokenMintMeta = opUsageCtxHelper.metaForTokenMint(accessor, store);
tokenOpsUsage.tokenMintUsage(sigUsage, baseMeta, tokenMintMeta, into);
}
private void estimateTokenWipe(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenWipeMeta = accessor.getSpanMapAccessor().getTokenWipeMeta(accessor);
tokenOpsUsage.tokenWipeUsage(sigUsage, baseMeta, tokenWipeMeta, into);
}
private void estimateTokenFreezeAccount(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenFreezeMeta = accessor.getSpanMapAccessor().getTokenFreezeMeta(accessor);
tokenOpsUsage.tokenFreezeUsage(sigUsage, baseMeta, tokenFreezeMeta, into);
}
private void estimateTokenUnfreezeAccount(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenUnFreezeMeta = accessor.getSpanMapAccessor().getTokenUnfreezeMeta(accessor);
tokenOpsUsage.tokenUnfreezeUsage(sigUsage, baseMeta, tokenUnFreezeMeta, into);
}
private void estimateTokenPause(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenPauseMeta = accessor.getSpanMapAccessor().getTokenPauseMeta(accessor);
tokenOpsUsage.tokenPauseUsage(sigUsage, baseMeta, tokenPauseMeta, into);
}
private void estimateTokenUnpause(
SigUsage sigUsage, TxnAccessor accessor, BaseTransactionMeta baseMeta, UsageAccumulator into) {
final var tokenUnpauseMeta = accessor.getSpanMapAccessor().getTokenUnpauseMeta(accessor);
tokenOpsUsage.tokenUnpauseUsage(sigUsage, baseMeta, tokenUnpauseMeta, into);
}
}
|
package zm.gov.moh.common.submodule.form.model.widgetModel;
public class DistrictPickerModel extends AbstractEditTextModel {
}
|
package my.application.repository;
import my.application.entity.Category;
import my.application.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByCategory(Category category);
@Query("SELECT p FROM Product p WHERE p.name LIKE %?1%")
List<Product> findByNameContaining(String name);
Product findTopById(Long id);
@Query(nativeQuery = true, value = "SELECT * FROM product ORDER BY name LIMIT ?1 OFFSET ?2")
List<Product> findAll(int limit, int offset);
@Query(nativeQuery = true, value = "SELECT COUNT(*) FROM product")
int countAllProduct();
}
|
package pub.iseekframework.utils.list;
/**
* desc: List公共类 <br>
* author: wangsong <br>
* date: 2018/5/21 下午6:38 <br>
* version: v1.0.0 <br>
*/
public class ListUtils {
}
|
package com.wxapp.dbbean;
public class TbSendmsg {
private long smId;
private String smMsg;
private long userId;
public long getSmId() {
return smId;
}
public void setSmId(long smId) {
this.smId = smId;
}
public String getSmMsg() {
return smMsg;
}
public void setSmMsg(String smMsg) {
this.smMsg = smMsg;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
|
package com.victoriachan.algorithmn;
/**
* @program: algorithm
* @description: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
* @author: VictoriaChan
* @create: 2020/03/14 21:44
**/
public class A23_VerifySquenceOfBST {
}
|
/*
* Check if input number is palindrom
*/
package Lab06D4;
/**
*
* @author Aliaksiej Protas
*/
public class Lab06D4 {
public static void main(String[] args) {
while (true) {
long number = UserInput.input("Input a number :");
View.print("Is it palindrome?: " + PalindromeNumber.isPalindrom(number));
if (!Complete.complete("Do you want to continue?")) {
break;
}
}
}
}
|
package com.ibeiliao.pay.admin.controller.bankaccount;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beiliao.common.domain.KidsbookKindergarten;
import com.beiliao.common.stub.KindergartenProvider;
import com.google.common.collect.Maps;
import com.ibeiliao.pay.account.api.dto.BankAccountPreEditVO;
import com.ibeiliao.pay.account.api.dto.request.AuditPassBindCardRequest;
import com.ibeiliao.pay.account.api.dto.request.AuditRejectBindCardRequest;
import com.ibeiliao.pay.account.api.dto.response.PreEditBankAccountPagerResp;
import com.ibeiliao.pay.account.api.enums.PreEditBankAccountStatus;
import com.ibeiliao.pay.account.api.provider.BankAccountProvider;
import com.ibeiliao.pay.admin.annotation.log.AdminLog;
import com.ibeiliao.pay.admin.context.AdminContext;
import com.ibeiliao.pay.admin.dto.PageResult;
import com.ibeiliao.pay.admin.dto.RestResult;
import com.ibeiliao.pay.admin.utils.resource.Menu;
import com.ibeiliao.pay.admin.utils.resource.MenuResource;
import com.ibeiliao.pay.api.ApiCode;
import com.ibeiliao.pay.api.ApiResultBase;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* Created by jingyesi on 16/8/9.
*/
@Controller
@RequestMapping("/admin/bankaccount")
@Menu(name = "审核修改账号", parent = "绑定账号管理", sequence = 4200000)
public class AuditPreEditController {
private static final Logger logger = LoggerFactory.getLogger(AuditPreEditController.class);
@Autowired
BankAccountProvider bankAccountProvider;
@Autowired
KindergartenProvider kindergartenProvider;
@RequestMapping("/toWaitingAuditPreEdit.xhtml")
@MenuResource("修改带审核列表页面")
public String toWaitingAuditPreEditPage(HttpServletRequest request, HttpServletResponse response){
return "/bankaccount/audit_preedit_list";
}
@RequestMapping("/getWaitingAuditPreEditList")
@MenuResource("获取待审核修改账号列表")
@ResponseBody
public PageResult getWaitingAuditPreEditList(HttpServletRequest request, HttpServletResponse response,
int currentPage, int pageSize){
Assert.isTrue(currentPage > 0, "页码错误");
Assert.isTrue(pageSize > 0, "分页大小错误");
PreEditBankAccountPagerResp pagerResp = bankAccountProvider.getPreEditPager(PreEditBankAccountStatus.AUDITING, currentPage, pageSize);
if(pagerResp.getCode() != ApiCode.SUCCESS){
logger.error("获取待审核修改账号列表失败, msg:{}", pagerResp.getMessage());
return new PageResult(ApiCode.FAILURE, "获取待审核修改账号列表失败");
}
JSONArray array = new JSONArray();
if (CollectionUtils.isNotEmpty(pagerResp.getList())) {
Map<Integer, String> schoolMap = Maps.newHashMap();
for (BankAccountPreEditVO vo : pagerResp.getList()) {
JSONObject obj = (JSONObject) JSONObject.toJSON(vo);
obj.put("status", vo.getStatus().getStatus());
int sid = (int) vo.getSchoolId();
if (!schoolMap.containsKey(sid)) {
KidsbookKindergarten kindergarten = kindergartenProvider.get(sid);
if(kindergarten != null){
schoolMap.put(sid, kindergarten.getName());
}
}
obj.put("schoolName", schoolMap.get(sid));
array.add(obj);
}
}
return new PageResult<>(currentPage, pageSize, pagerResp.getTotalCount(), array);
}
@RequestMapping(value = "/rejectPreEdit.do", method = RequestMethod.POST)
@MenuResource("驳回修改账号")
@ResponseBody
@AdminLog
public RestResult rejectPreEdit(HttpServletRequest request, HttpServletResponse response, long accountId, String auditComment){
Assert.isTrue(accountId > 0 , "账号ID错误");
AuditRejectBindCardRequest req = new AuditRejectBindCardRequest();
req.setAccountId(accountId);
req.setAuditComment(auditComment);
req.setAuditOpUid(AdminContext.getAccountId());
req.setAuditOpName(AdminContext.getName());
ApiResultBase resp = bankAccountProvider.auditRejectPreEditBindCard(req);
if(resp.getCode() != ApiCode.SUCCESS){
logger.error("admin#bankaccount#rejectPreEdit | 驳货修改账号失败, msg:{}", resp.getMessage());
return new PageResult(ApiCode.FAILURE, "驳回修改账号失败");
}
return new PageResult(ApiCode.SUCCESS, "驳回成功");
}
@RequestMapping(value = "/passPreEdit.do", method = RequestMethod.POST)
@MenuResource("审核通过修改账号")
@ResponseBody
@AdminLog
public RestResult passPreEdit(HttpServletRequest request, HttpServletResponse response, long accountId){
Assert.isTrue(accountId > 0 , "账号ID错误");
AuditPassBindCardRequest req = new AuditPassBindCardRequest();
req.setAccountId(accountId);
req.setAuditOpUid(AdminContext.getAccountId());
req.setAuditOpName(AdminContext.getName());
ApiResultBase resp = bankAccountProvider.auditPassPreEditBindCard(req);
if(resp.getCode() != ApiCode.SUCCESS){
logger.error("admin#bankaccount#passPreEdit | 审核通过修改账号失败 | msg:{}", resp.getMessage());
return new PageResult(ApiCode.FAILURE, "审核通过修改账号失败");
}
return new PageResult(ApiCode.SUCCESS, "审核通过成功");
}
}
|
package com.tuitaking.point2offer;
import com.tuitaking.tree.TreeNode;
import com.tuitaking.tree.TreeUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class PathSum_34T {
@Test
public void test(){
TreeNode node= TreeUtils.generateArrayToTree(new Integer[]{5,4,8,11,null,13,4,7,2,null,null,5,1});
PathSum_34 pathSum_34=new PathSum_34();
List<List<Integer>> res=pathSum_34.pathSum(node,22);
Assert.assertNotNull(res);
}
}
|
package com.lupan.javaStudy.chapter15;
import java.io.*;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
/**
* TODO nio学习
*
* @author lupan
* @version 2016/1/21 0021
*/
public class ChannelStudy {
public static void main(String[] args){
FileChannel inChannel=null;
FileChannel outChannel=null;
try {
File file = new File("a1.text");
RandomAccessFile rdf = new RandomAccessFile(file,"rw");
inChannel = rdf.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,0,file.length());
Charset charset = Charset.forName("UTF-8");
outChannel = new FileOutputStream("a.text").getChannel();
outChannel.position(file.length());
outChannel.write(buffer);
buffer.clear();
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer);
System.out.print(charBuffer.toString());
}catch (Exception e){
e.printStackTrace();
}finally{
try {
if(inChannel!=null){
inChannel.close();
}
if(outChannel!=null){
outChannel.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
|
package com.openkm.frontend.client.util;
import java.util.HashMap;
import java.util.Map;
import com.google.gwt.http.client.URL;
/**
* @author jllort
*
*/
public class Location {
private String hash;
private String host;
private String hostName;
private String href;
private String path;
private String port;
private String protocol;
private String queryString;
private HashMap<String, String> paramMap;
public String getHash() {
return hash;
}
public String getHost() {
return host;
}
public String getHostName() {
return hostName;
}
public String getHref() {
return href;
}
public String getPath() {
return path;
}
public String getContext() {
if (path.equals("/frontend/index.html")) {
return "";
} else {
String context = path.substring(path.indexOf("/") + 1);
context = context.substring(0, context.indexOf("/"));
return "/" + context;
}
}
public String getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public String getQueryString() {
return queryString;
}
protected void setHash(String hash) {
this.hash = hash;
}
protected void setHost(String host) {
this.host = host;
}
protected void setHostName(String hostName) {
this.hostName = hostName;
}
protected void setHref(String href) {
this.href = href;
}
protected void setPath(String path) {
this.path = path;
}
protected void setPort(String port) {
this.port = port;
}
protected void setProtocol(String protocol) {
this.protocol = protocol;
}
protected void setQueryString (String queryString) {
this.queryString = queryString;
paramMap = new HashMap<String, String>();
if (queryString != null && queryString.length() > 1) {
String qs = queryString.substring(1);
String[] kvPairs = qs.split("&");
for (int i = 0; i < kvPairs.length; i++) {
String[] kv = kvPairs[i].split("=");
if (kv.length > 1) {
paramMap.put(kv[0], URL.decodeQueryString(kv[1]));
}
else {
paramMap.put(kv[0], "");
}
}
}
}
public String getParameter (String name) {
return (String) paramMap.get(name);
}
public Map<String, String> getParameterMap() {
return paramMap;
}
}
|
package com.kishan;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.stream.Collectors;
public class HighestAndLowest {
public static void main(String[] args){
System.out.println(Kata.HighAndLow("8 3 -5 42 -1 0 0 -9 4 7 4 -4"));
}
}
class Kata {
public static String HighAndLow(String numbers) {
// Way1
// String[] numbers1 = numbers.split(java.util.regex.Pattern.quote(" "));
// int[] array = Arrays.asList(numbers1).stream().mapToInt(Integer::parseInt).toArray();
// Arrays.sort(array);
// return array[array.length-1]+ " "+ array[0];
// Way2
IntSummaryStatistics summary = Arrays
.stream(numbers.split(" "))
.collect(Collectors.summarizingInt(n -> Integer.parseInt(n)));
return String.format("%d %d", summary.getMax(), summary.getMin());
}
}
|
/**
* original(c) zhuoyan company
* projectName: java-design-pattern
* fileName: ITopicService.java
* packageName: cn.zy.pattern.proxy.dynamic
* date: 2018-12-18 22:01
* history:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package cn.zy.pattern.proxy.dynamic;
/**
* @version: V1.0
* @author: ending
* @className: ITopicService
* @packageName: cn.zy.pattern.proxy.dynamic
* @description:
* @data: 2018-12-18 22:01
**/
public class ITopicService implements TopicService{
@Override
public void add() {
System.out.println("主题添加成功");
}
}
|
package com.perhab.napalm.implementations.generics.methods;
import com.perhab.napalm.statement.Description;
import com.perhab.napalm.statement.Execute;
import com.perhab.napalm.statement.Parameter;
public interface CallMethod {
@Execute(parameters=@Parameter("A"))
@Description("Tests the performance of calling a method on an object of (currently) unkown type.")
String callMethod(String parameter) throws Exception;
}
|
/**
* Created by USER on 11/3/2018.
*/
public class ComplexNumber {
private double real;
private double complex;
public ComplexNumber(double real,double complex){
this.real = real;
this.complex = complex;
}
public int absSquare(){
return (int)(Math.pow(real,2) + Math.pow(complex,2));
}
public void add( ComplexNumber num){
setReal(this.getReal()+num.getReal());
setComplex(this.getComplex()+num.getComplex());
}
public void square(){
double realPart = Math.pow(this.getReal(),2) - Math.pow(this.getComplex(),2);
double complexPart = 2*this.getReal()*this.getComplex();
setComplex(complexPart);
setReal(realPart);
}
public double getReal() {
return real;
}
public double getComplex() {
return complex;
}
public void setReal(double real) {
this.real = real;
}
public void setComplex(double complex) {
this.complex = complex;
}
}
|
package com.example.androidtaskday5;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText name,email,mobile,college;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText) findViewById(R.id.name);
email=(EditText)findViewById(R.id.email);
mobile=(EditText)findViewById(R.id.mobile);
college=(EditText)findViewById(R.id.college);
btn=(Button)findViewById(R.id.submit_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sname=name.getText().toString();
String semail=email.getText().toString();
String smobile=mobile.getText().toString();
String scollege=college.getText().toString();
Intent intent=new Intent(MainActivity.this,second.class);
intent.putExtra("keyname",sname);
intent.putExtra("keyemail",semail);
intent.putExtra("keymobile",smobile);
intent.putExtra("keycollege",scollege);
startActivity(intent);
}
});
}
}
|
package com.jovin.models;
// Generated 9 Feb, 2016 6:00:21 PM by Hibernate Tools 4.0.0
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
/**
* Attachments generated by hbm2java
*/
@Entity
@Table(name = "attachments", catalog = "IssueTracker")
public class Attachments extends SuperModelClass
implements java.io.Serializable {
private Integer id;
private Issues issues;
private IssuesUpdates issuesUpdates;
private String link;
private Set<IssuesUpdates> issuesUpdateses = new HashSet<IssuesUpdates>(0);
private Set<Issues> issueses = new HashSet<Issues>(0);
public Attachments() {
}
public Attachments(Issues issues, IssuesUpdates issuesUpdates, String link, Set<IssuesUpdates> issuesUpdateses,
Set<Issues> issueses) {
this.issues = issues;
this.issuesUpdates = issuesUpdates;
this.link = link;
this.issuesUpdateses = issuesUpdateses;
this.issueses = issueses;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "issueId")
public Issues getIssues() {
return this.issues;
}
public void setIssues(Issues issues) {
this.issues = issues;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "issueUpdatesId")
public IssuesUpdates getIssuesUpdates() {
return this.issuesUpdates;
}
public void setIssuesUpdates(IssuesUpdates issuesUpdates) {
this.issuesUpdates = issuesUpdates;
}
@Column(name = "link", length = 300)
public String getLink() {
return this.link;
}
public void setLink(String link) {
this.link = link;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "attachments")
public Set<IssuesUpdates> getIssuesUpdateses() {
return this.issuesUpdateses;
}
public void setIssuesUpdateses(Set<IssuesUpdates> issuesUpdateses) {
this.issuesUpdateses = issuesUpdateses;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "attachments")
public Set<Issues> getIssueses() {
return this.issueses;
}
public void setIssueses(Set<Issues> issueses) {
this.issueses = issueses;
}
}
|
package createPreOut;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpConnectionUtil {
private static String sessionId;
// private static final Logger log = LoggerFactory.getLogger(HttpConnectionUtil.class);
/**
* 发送post数据
*
* @param path
* @param params
* @return
* @throws Exception
*/
public static String sendPostRequestByForm(String path, String params) throws Exception {
// log.warn("=============================发送地址:"+path);
// log.warn("=============================发送内容:"+params);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// if(sessionId==null){
// String session_value = conn.getHeaderField("Set-Cookie");
// sessionId = session_value.split(";")[0];
// }else{
// conn.setRequestProperty("Cookie", "720EFE58E23FE8495A5EAA28E54E9E67");
// }
// conn.setChunkedStreamingMode(5);
conn.setDoOutput(true);// 是否输入参数
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream = conn.getInputStream();
return readInputStream(inStream,"UTF-8");
}
/**
* 发送post数据
*
* @param path
* @param params
* @return
* @throws Exception
*/
public static String sendPostRequestByForm(String path, String params,String charset) throws Exception {
// log.info("=============================发送地址:"+path);
// log.info("=============================发送内容:"+params);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// conn.setChunkedStreamingMode(5);
conn.setDoOutput(true);// 是否输入参数
byte[] bypes = params.getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream = conn.getInputStream();
return readInputStream(inStream,charset);
}
/**
* 读取返回的结果
*@param inStream
*@return
*@throws Exception
*/
public static String readInputStream(InputStream inStream,String charset) throws Exception {
StringBuffer buffer = new StringBuffer();
InputStreamReader isr = new InputStreamReader(inStream,charset);
BufferedReader br = new BufferedReader(isr);
String content = "";
while ((content = br.readLine()) != null) {
buffer.append(content);
}
br.close();
isr.close();
// log.warn("=============================返回内容:"+buffer.toString());
return buffer.toString();
}
}
|
package com.cichonski.project.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import com.cichonski.project.ProjectServer;
/**
* <p>
* Note: while each thread/client will receive an incremented requestCount, it is not
* guaranteed that the server will return responses to multiple threads/clients
* in the exact order they were received, but the server will ensure that the
* requestCount returned reflects the position at the time that request was
* received. See {@link ProjectServer} docs for more detail.
* </p>
*
*
*/
public class Client {
// using default java logger and console output to reduce external dependencies/configuration.
private static final Logger LOGGER = Logger.getLogger(Client.class.getName());
// number of threads to send against the server
private static final int THREADS = 100;
// number of requests per thread
private static final int REQUESTS = 20;
// address of the remote host
private static final String HOST = "localhost";
// port of remote host
private static final int PORT = 8189;
public static void main(String[] args){
final BlockingQueue<Long> requestQueue = new LinkedBlockingQueue<Long>();
ExecutorService service = Executors.newFixedThreadPool(100);
for (int i = 0; i < THREADS; i++) {
service.execute(new Runnable() {
public void run() {
try {
for (int i = 0; i < REQUESTS; i++) {
Socket s = new Socket(HOST, PORT);
BufferedReader reader = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String line = reader.readLine();
System.out.println(line);
if (line != null && !line.isEmpty()){
String[] words = line.split(" ");
// the request number is the last thing on the line
long actualRequestCount = Long.parseLong(words[words.length - 1].trim());
requestQueue.add(actualRequestCount);
}
s.close();
//average network latency according to verizon, would be better to randomize
TimeUnit.MILLISECONDS.sleep(45);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e){
e.printStackTrace();
}
}
});
}
service.shutdown();
while (true) {
if (service.isTerminated()) {
// just wait until everything is done and force the exit.
break;
}
}
// inspect the request queue
int expectedSize = THREADS * REQUESTS;
Set<Long> requests = new TreeSet<Long>();
// will remove dupes (which should not exist) and order).
requestQueue.drainTo(requests);
int realSize = requests.size();
if (expectedSize != realSize){
LOGGER.warning("failure: expected number of requests was: " + expectedSize + ", but real size was: " + realSize);
} else {
LOGGER.info("success: received all " + expectedSize + " responses from server");
}
}
}
|
package com.hyty.tree.treejiegou.controller;
import com.alibaba.fastjson.JSON;
import com.hyty.tree.treejiegou.entity.BusinessModule;
import com.hyty.tree.treejiegou.entity.Personnel;
import com.hyty.tree.treejiegou.entity.RoleJurisdiction;
import com.hyty.tree.treejiegou.service.RoleJurisdictionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Whk on 2019/3/29.
* 角色与权限对应关系Controller
*/
@RestController
@RequestMapping(value = "/role")
public class RoleJurisdictionController {
@Autowired
RoleJurisdictionService roleJurisdictionService;
/**
* 新增/修改 角色权限
*
* @param roleJurisdiction
* @return staffRole实体
*/
@RequestMapping(value = "/saverolejurisdiction", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public Object saveRoleJurisdiction(RoleJurisdiction roleJurisdiction) {
Map<String, Object> map = new HashMap<>();
try {
RoleJurisdiction roleJurisdiction1 = roleJurisdictionService.saveRoleJurisdiction(roleJurisdiction);
map.put("result", true);
map.put("value", roleJurisdiction1);
map.put("msg", "保存成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("msg", "保存失败");
}
return JSON.toJSONString(map);
}
/**
* 新增/修改 角色权限关联企业员工_头体对应关系
*
* @param personnel
* @return
*/
@RequestMapping(value = "/savepersonnel", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public Object savePersonnel(Personnel personnel) {
Map<String, Object> map = new HashMap<>();
try {
Personnel personnel1 = roleJurisdictionService.savePersonnel(personnel);
map.put("result", true);
map.put("value", personnel1);
map.put("msg", "保存成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("msg", "保存失败,异常处理");
return JSON.toJSONString(map);
}
}
/* *//**
* 新增/修改 角色权限关联业务模块_头体对应关系
*
* @param module
* @return
*//*
@RequestMapping(value = "/savemodule", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public Object savebusinessModule(BusinessModule module) {
Map<String, Object> map = new HashMap<>();
try {
BusinessModule module1 = roleJurisdictionService.savebusinessModule(module);
map.put("result", true);
map.put("value", module1);
map.put("msg", "保存成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("msg", "保存失败,异常处理");
return JSON.toJSONString(map);
}
}*/
/**
* 查询所有 角色权限
*
* @param roleJurisdiction
* @return Json
*/
@RequestMapping(value = "/selectall", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public Object selectAll(RoleJurisdiction roleJurisdiction) {
Map<String, Object> map = new HashMap<>();
try {
List<RoleJurisdiction> list = roleJurisdictionService.selectAll();
map.put("result", true);
map.put("value", list);
map.put("msg", "查询成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("msg", "查询失败");
}
return JSON.toJSONString(map);
}
/**
* 根据Id 查询角色权限
*
* @param id
* @return
*/
@RequestMapping(value = "/selectrolejurisdiction", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object selectRoleJurisdiction(String id) {
Map<String, Object> map = new HashMap<>();
try {
RoleJurisdiction roleJurisdiction = roleJurisdictionService.selectRoleJurisdiction(id);
map.put("result", true);
map.put("value", roleJurisdiction);
map.put("msg", "查询成功");
return JSON.toJSONString(map);
} catch (Exception e) {
map.put("result", true);
map.put("msg", "查询成功");
return JSON.toJSONString(map);
}
}
/**
* 根据id 查询角色权限关联企业员工_头体对应关系
*
* @param id
* @return
*/
@RequestMapping(value = "/selectpersonnel", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object selectPersonnel(String id) {
Map<String, Object> map = new HashMap<>();
try {
List<Personnel> list = roleJurisdictionService.selectPersonnel(id);
map.put("result", true);
map.put("value", list);
map.put("msg", "查询成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", true);
map.put("msg", "查询失败");
return JSON.toJSONString(map);
}
}
/**
* 根据id 查询角色权限关联业务功能_头体对应关系
*
* @param id
* @return
*/
@RequestMapping(value = "/selectmodule", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object selectBusinessModule(String id) {
Map<String, Object> map = new HashMap<>();
try {
List<BusinessModule> list = roleJurisdictionService.selectBusinessModule(id);
map.put("result", true);
map.put("value", list);
map.put("msg", "查询成功");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", true);
map.put("msg", "查询失败");
return JSON.toJSONString(map);
}
}
/**
* 根据Id 删除角色权限
*
* @param id
* @return
* @RequestParam
*/
@RequestMapping(value = "/deleterolejurisdiction", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object deleteRoleJurisdiction(String id) {
Map<String, Object> map = new HashMap<>();
try {
boolean roleJurisdiction = roleJurisdictionService.deleteRoleJurisdiction(id);
if (roleJurisdiction) {
map.put("result", true);
map.put("msg", "删除成功");
return JSON.toJSONString(map);
} else {
map.put("result", false);
map.put("msg", "删除失败,检查ID是否表内存在");
return JSON.toJSONString(map);
}
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("msg", "删除失败, 系统异常");
return JSON.toJSONString(map);
}
}
/**
* 根据Id 删除角色权限关联企业员工_头体对应关系
*
* @param id
* @return
*/
@RequestMapping(value = "/deletepersonnel", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object deletePersonnel(String id) {
Map<String, Object> map = new HashMap<>();
try {
boolean personnel = roleJurisdictionService.deletePersonnel(id);
if (personnel) {
map.put("result", true);
map.put("mag", "删除成功");
return JSON.toJSONString(map);
}
map.put("result", false);
map.put("mag", "删除失败,检查ID是否表内存在");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("mag", "删除失败,系统异常");
return JSON.toJSONString(map);
}
}
/**
* 根据Id 删除角色权限关联业务模块_头体对应关系
*
* @param id
* @return
*/
@RequestMapping(value = "/deletemodule", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object deleteModule(String id) {
Map<String, Object> map = new HashMap<>();
try {
boolean module = roleJurisdictionService.deleteModule(id);
if (module) {
map.put("result", true);
map.put("mag", "删除成功");
return JSON.toJSONString(map);
}
map.put("result", false);
map.put("mag", "删除失败,检查ID是否表内存在");
return JSON.toJSONString(map);
} catch (Exception e) {
e.printStackTrace();
map.put("result", false);
map.put("mag", "删除失败,系统异常");
return JSON.toJSONString(map);
}
}
}
|
package at.fhj.swd.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
public class CDITestBase {
public void txBegin(EntityManager em){
EntityTransaction tx = em.getTransaction();
}
public void txCommit(EntityManager em){
EntityTransaction tx = em.getTransaction();
if (tx.getRollbackOnly()){
tx.rollback();
}
else {
tx.commit();
}
}
public void txRollback(EntityManager em){
EntityTransaction tx = em.getTransaction();
tx.rollback();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package co.tweetbuy.servlet;
import co.tweetbuy.bean.ErrorBean;
import co.tweetbuy.bean.UserBean;
import co.tweetbuy.db.DBUtil;
import co.tweetbuy.util.Constants;
import co.tweetbuy.util.Errors;
import co.tweetbuy.util.LogIt;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author emrah
*/
@WebServlet(name = "UserActivate", urlPatterns = {"/UserActivate"})
public class UserActivate extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
int id = Integer.parseInt(request.getParameter("uid")); // TODO user id gelmezse patliyor
String token = request.getParameter("t");
if (id > 0 && token != null && !"".equals(token)) {
if (isUserExist(id, token)) {
UserBean ub = new UserBean();
ub.setId(id);
ub.setType(Constants.USER_TYPE_ACTIVE);
int updatedUserId = DBUtil.updateUser(ub);
if (updatedUserId > 0) {
ArrayList<UserBean> users = DBUtil.getUsersSimple(ub);
if (users != null && !users.isEmpty()) {
for (UserBean u : users) {
setUserToSession(request, u);
setLastLoginTime(request, u);
response.sendRedirect("login.jsp?message=Thank you for your activation, please continue with login");
LogIt.logger.info(UserActivate.class + ">" + Thread.currentThread().getStackTrace()[1].getMethodName() + "> Account activated: " + ub.getEmail());
}
}
} else {
response.sendRedirect(Constants.AUTH_FILTER_DIRECTORY + "login.jsp?message=User cannot be activated");
ErrorBean error = new ErrorBean();
error.setErrorCode(Errors.ERROR_USER_CANNOT_ACTIVATED);
LogIt.logger.error(UserActivate.class + ">" + Thread.currentThread().getStackTrace()[1].getMethodName() + ">" + error.getErrorCode());
}
} else {
response.sendRedirect(Constants.AUTH_FILTER_DIRECTORY + "login.jsp?message=User token is not correct");
ErrorBean error = new ErrorBean();
error.setErrorCode(Errors.ERROR_USER_CANNOT_ACTIVATED);
LogIt.logger.error(UserActivate.class + ">" + Thread.currentThread().getStackTrace()[1].getMethodName() + ">" + error.getErrorCode());
}
} else {
response.sendRedirect(Constants.AUTH_FILTER_DIRECTORY + "login.jsp?message=User parameters are empty");
ErrorBean error = new ErrorBean();
error.setErrorCode(Errors.ERROR_USER_CANNOT_ACTIVATED);
LogIt.logger.error(UserActivate.class + ">" + Thread.currentThread().getStackTrace()[1].getMethodName() + ">" + error.getErrorCode());
}
} finally {
out.close();
}
}
private static boolean isUserExist(int id, String token) {
UserBean ub = new UserBean();
ub.setId(id);
ub.setToken(token);
ArrayList<UserBean> users = DBUtil.getUsers(ub);
for (UserBean u : users) {
if (u.getId() > 0) {
// IMPORTANT !!! Burada tekrar cagiriyoruz ki user token ile login yaptik, getUserPrivileges herzaman bilgileri vermeden önce tokeni degistiriyor
// IMPORTANT !!! Kullanici token ile login oldukdan sonra token degismeli ve degistriyoruz
ArrayList<UserBean> userForChangeToken = DBUtil.getUsersPrivileges(ub);
return true;
}
}
return false;
}
private static void setUserToSession(HttpServletRequest request, UserBean user) {
HttpSession session = request.getSession(true);
session.setAttribute(Constants.AUTHENTICATION_SESSION_USER_VARIABLE, user);
}
private static void setLastLoginTime(HttpServletRequest request, UserBean user) {
// last login time set ediyoruz, last login time 1 gönderirsek now() set ediliyor
UserBean userLastLogin = new UserBean();
userLastLogin.setId(user.getId());
userLastLogin.setLastLoginTime(1);
userLastLogin.setLastLoginWith(Constants.LAST_LOGIN_WITH_NORMAL);
DBUtil.updateUser(userLastLogin);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.jdyx.app.bean;
import lombok.Data;
import java.io.Serializable;
@Data
public class LikeInfoVo implements Serializable {
/**
* 编号
*/
private Integer videoId;
/**
* 视频点赞数
*/
private Integer videoLikes;
/**
* 是否点赞
*/
private Integer isLike;
}
|
package com.bit.myfood.model.enumclass;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum OrderStatus {
COMPLETE(0, "완료", "주문 완료"),
CONFIRM(1, "예정", "주문 예정"),
ORDERING(2, "주문중", "주문 중"),
;
private Integer id;
private String title;
private String description;
}
|
package com.tencent.mm.plugin.backup.backupmoveui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.backup.a.b.d;
import com.tencent.mm.plugin.backup.a.c;
import com.tencent.mm.plugin.backup.c.b;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMWizardActivity;
import com.tencent.mm.ui.base.h;
import org.xwalk.core.XWalkResourceClient;
public class BackupMoveQRCodeUI extends MMWizardActivity implements d {
private ImageView gVm;
private TextView gVn;
private TextView gVo;
private boolean gVp = false;
static /* synthetic */ void d(BackupMoveQRCodeUI backupMoveQRCodeUI) {
backupMoveQRCodeUI.gVp = false;
b.arv().arx().dw(false);
b.arv().arw().stop();
b.arv().arx().an(false);
b.arv().aqP().gRC = -100;
backupMoveQRCodeUI.DT(1);
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (!getIntent().getExtras().getBoolean("WizardRootKillSelf", false)) {
if (au.HX()) {
initView();
com.tencent.mm.plugin.backup.f.b.clear();
com.tencent.mm.plugin.backup.f.b.d arx = b.arv().arx();
com.tencent.mm.plugin.backup.f.b.a(arx.gUq);
com.tencent.mm.plugin.backup.a.d.mx(21);
com.tencent.mm.plugin.backup.f.b.a(arx.gUo);
b.arv().aqQ();
com.tencent.mm.plugin.backup.f.b.a(arx);
com.tencent.mm.plugin.backup.f.b.a(b.arv().arw());
com.tencent.mm.plugin.backup.f.b.mx(2);
b.arv().gRx = null;
arx.gUz = false;
b.arv().arx().gUA = c.gRn;
com.tencent.mm.plugin.backup.a.d.aqV();
return;
}
finish();
}
}
public void onStart() {
super.onStart();
com.tencent.mm.plugin.backup.f.b.a(b.arv().arx());
b.arv().arx().gSW = this;
b.arv().arx().gUF.start();
}
public void onResume() {
super.onResume();
mw(b.arv().aqP().gRC);
}
public final void initView() {
setMMTitle(R.l.backup_move);
this.gVm = (ImageView) findViewById(R.h.backup_move_qrcode_image);
this.gVn = (TextView) findViewById(R.h.backup_move_qrcode_status_title);
this.gVo = (TextView) findViewById(R.h.backup_move_qrcode_status_content);
setBackBtn(new 1(this));
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i != 4) {
return super.onKeyDown(i, keyEvent);
}
arP();
return true;
}
private void arP() {
if (au.Dr()) {
h.a(this, R.l.backup_move_qrcode_exit_move_tip, R.l.backup_move_qrcode_exit_move, R.l.backup_move_stop_move, R.l.backup_cancel, false, new 2(this), null, R.e.backup_red);
return;
}
x.i("MicroMsg.BackupMoveQRCodeUI", "user click close. stop move.");
b.arv().arw().stop();
b.arv().arx().an(true);
b.arv().aqP().gRC = -100;
DT(1);
}
public void onStop() {
x.i("MicroMsg.BackupMoveQRCodeUI", "BackupMoveQRCodeUI onStop.");
if (b.arv().arx().gUF != null) {
b.arv().arx().gUF.stop();
}
super.onStop();
}
protected final int getLayoutId() {
return R.i.backup_move_qrcode;
}
public final void mw(int i) {
x.i("MicroMsg.BackupMoveQRCodeUI", "onUpdateUIProgress backupState:%d", new Object[]{Integer.valueOf(i)});
if (!this.gVp) {
switch (i) {
case -33:
this.gVp = true;
h.a(this, R.l.backup_move_error_not_support_quick_backup, 0, R.l.backup_all_types, R.l.backup_cancel, false, new 8(this), new 9(this), R.e.backup_green);
return;
case -32:
this.gVp = true;
h.a(this, R.l.backup_move_error_not_support_select_time, 0, R.l.backup_all_records, R.l.backup_cancel, false, new 5(this), new 6(this), R.e.backup_green);
return;
case -31:
this.gVp = true;
h.a(this, R.l.backup_move_error_not_support_select_time_and_quick_backup, 0, R.l.backup_all_types, R.l.backup_cancel, false, new 3(this), new 4(this), R.e.backup_green);
return;
case XWalkResourceClient.ERROR_BAD_URL /*-12*/:
h.a(this, R.l.backup_move_error_recover_phone_old_version, 0, R.l.backup_sure, 0, false, new OnClickListener() {
public final void onClick(DialogInterface dialogInterface, int i) {
x.i("MicroMsg.BackupMoveQRCodeUI", "move phone old version");
}
}, null, R.e.backup_green);
return;
case -11:
case XWalkResourceClient.ERROR_AUTHENTICATION /*-4*/:
this.gVn.setText(R.l.backup_move_error_move_gencode_err);
this.gVn.setTextColor(this.mController.tml.getResources().getColor(R.e.red));
this.gVm.setImageResource(R.k.backup_move_qrcode_light);
this.gVo.setVisibility(4);
return;
case 2:
x.i("MicroMsg.BackupMoveQRCodeUI", "auth success. go to BackupMoveUI.");
b.arv().aqP().gRC = 12;
MMWizardActivity.D(this, new Intent(this, BackupMoveUI.class));
return;
case 51:
byte[] bArr = b.arv().arx().bitmapData;
this.gVm.setImageBitmap(BitmapFactory.decodeByteArray(bArr, 0, bArr.length));
this.gVn.setText(R.l.backup_move_qrcode_success_tip);
this.gVn.setTextColor(this.mController.tml.getResources().getColor(R.e.black));
this.gVo.setVisibility(4);
return;
default:
return;
}
}
}
public final void aqO() {
}
}
|
package net.sssanma.mc.usefulcmd;
import net.sssanma.mc.ECore;
import net.sssanma.mc.EPermission;
import net.sssanma.mc.utility.Utility;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class UsefulGamemode extends UsefulCommand {
public UsefulGamemode() {
super("gm", false, EPermission.MODERATOR);
}
@Override
public Return execute(CommandSender sender, String[] cmd, int length, boolean fromConsole) {
Player senderPlayer = (Player) sender;
if (length == 0) {
GameMode gamemode = senderPlayer.getGameMode();
switch (gamemode) {
case ADVENTURE:
senderPlayer.setGameMode(GameMode.CREATIVE);
break;
case CREATIVE:
senderPlayer.setGameMode(GameMode.SURVIVAL);
break;
case SURVIVAL:
senderPlayer.setGameMode(GameMode.CREATIVE);
break;
default:
break;
}
senderPlayer.sendMessage(ChatColor.GRAY + "ゲームモードを" + Utility.gamemodeToJapanese(senderPlayer.getGameMode()) + "に変更しました");
ECore.getPlugin().getLogger().info("ゲームモード: " + senderPlayer.getGameMode() + " by " + senderPlayer.getName());
return Return.OK;
}
sender.sendMessage(ChatColor.RED + "/gm");
return Return.HELP_DISPLAYED;
}
}
|
package com.smxknife.netty.v5.demo13;
import java.util.HashMap;
import java.util.Map;
/**
* Netty协议消息头定义
* @author smxknife
* 2018-12-11
*/
public class Header {
/**
* 消息的校验码,由三部分组成
* 1)0xabef:固定值表明是netty协议消息,2个字节
* 2)主版本号:1~255,1个字节
* 3)次版本号:1~255,1个字节
*/
private int crcCode = 0xabef0101;
/**
* 消息的长度,整个消息,包括消息头和消息体
*/
private int length;
/**
* 集群节点内全局唯一,由会话id生成器生成
*/
private long sessionID;
/**
* 0:业务请求消息
* 1:业务响应消息
* 2:业务ONE_WAY消息(既是请求又是响应消息)
* 3:握手请求消息
* 4:握手应答消息
* 5:心跳请求消息
* 6:心跳应答消息
*/
private byte type;
/**
* 消息优先级:0~255
*/
private byte priority;
/**
* 可选字段,用于扩展消息头
*/
private Map<String, Object> attachment = new HashMap<>();
public final int getCrcCode() {
return crcCode;
}
public final void setCrcCode(int crcCode) {
this.crcCode = crcCode;
}
public final int getLength() {
return length;
}
public final void setLength(int length) {
this.length = length;
}
public final long getSessionID() {
return sessionID;
}
public final void setSessionID(long sessionID) {
this.sessionID = sessionID;
}
public final byte getType() {
return type;
}
public final void setType(byte type) {
this.type = type;
}
public final byte getPriority() {
return priority;
}
public final void setPriority(byte priority) {
this.priority = priority;
}
public final Map<String, Object> getAttachment() {
return attachment;
}
public final void setAttachment(Map<String, Object> attachment) {
this.attachment = attachment;
}
@Override
public String toString() {
return "Header {" +
"crcCode=" + crcCode +
", length=" + length +
", sessionID=" + sessionID +
", type=" + type +
", priority=" + priority +
", attachment=" + attachment +
'}';
}
public enum MessageType {
/**
* -1:失败
* 0:业务请求消息
* 1:业务响应消息
* 2:业务ONE_WAY消息(既是请求又是响应消息)
* 3:握手请求消息
* 4:握手应答消息
* 5:心跳请求消息
* 6:心跳应答消息
*/
FAIL((byte)-1),
LOGIC_REQ((byte)0),
LOGIC_RESP((byte)1),
LOGIC_ONE_WAY((byte)2),
LOGIN_REQ((byte)3),
LOGIN_RESP((byte)4),
HEART_BRAT_REQ((byte)5),
HEART_BRAT_RESP((byte)6);
byte code;
MessageType(byte code) {
this.code = code;
}
public byte getCode() {
return code;
}
}
}
|
package sokrisztian.todo.admin.logic.service;
import org.springframework.stereotype.Service;
import sokrisztian.todo.admin.api.model.CreateUserForm;
import sokrisztian.todo.admin.logic.converter.CreateUserFormToUserEntityConverter;
import sokrisztian.todo.admin.persistance.repository.UserBasicRepository;
@Service
public class CreateUserService {
private final UserBasicRepository repository;
private final CreateUserFormToUserEntityConverter converter;
public CreateUserService(UserBasicRepository repository, CreateUserFormToUserEntityConverter converter) {
this.repository = repository;
this.converter = converter;
}
public void create(CreateUserForm userForm) {
repository.save(converter.convert(userForm));
}
}
|
package problem_solve.basic.baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BaekJoon2357{
static int[] arr = new int[100001];
public static void main(String []args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
SegTree tree = new SegTree(n);
StringBuilder sb = new StringBuilder();
for(int i=1; i <= n; i++){
arr[i] = Integer.parseInt(br.readLine());
}
tree.init(arr, 1, 1, n);
for(int i=1; i <= m; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
Node target = tree.find(1, 1, n, a, b);
sb.append(target.min).append(" ").append(target.max).append("\n");
}
System.out.println(sb);
br.close();
}
private static class SegTree{
int size = 0;
Node[] arr;
int height;
public SegTree(int n){
this.height = (int)Math.ceil(Math.log(n) / Math.log(2));
this.size = (int)Math.pow(2, height+1);
this.arr = new Node[size];
}
public Node init(int nums[], int node_idx, int start, int end){
if(start == end){
Node newNode = new Node(nums[start], nums[start]);
return this.arr[node_idx] = newNode;
}
int mid = (start+end)/2;
Node leftChild = this.init(nums, node_idx*2, start, mid);
Node rightChild = this.init(nums, node_idx*2+1, mid+1, end);
int min = leftChild.min < rightChild.min ? leftChild.min : rightChild.min;
int max = leftChild.max < rightChild.max ? rightChild.max : leftChild.max;
Node newNode = new Node(min, max);
return this.arr[node_idx] = newNode;
}
public Node find(int node_idx, int start, int end, int left, int right){
if(left > end || right < start){
return new Node(Integer.MAX_VALUE, Integer.MIN_VALUE);
}
if(left <= start && end <= right){
return this.arr[node_idx];
}
int mid = (start+end)/2;
Node leftChild = this.find(node_idx*2, start, mid, left, right);
Node rightChild = this.find(node_idx*2+1, mid+1, end, left, right);
int min = leftChild.min < rightChild.min ? leftChild.min : rightChild.min;
int max = leftChild.max < rightChild.max ? rightChild.max : leftChild.max;
return new Node(min, max);
}
}
private static class Node{
int min;
int max;
public Node(int min, int max){
this.min = min;
this.max = max;
}
}
}
|
package algorithm.kakaoBlindTest._2019;
import java.util.*;
/*
* 프로그래머스 - 코딩테스트 연습 - 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방
* 시작 23:00
* 종료 23:25
* 걸린시간 25분
*
* [발전하기 위한 한마디]
* 문제 길이가 길 뿐이지 쉬운문제였음
* 하지만 처음 읽고나서 바로 코딩옮겼을때 실수할뻔했으니 자만하지말고 문제가 원하는게 뭔지 파악하는 것 잊지말것
*
*/
//채팅방에 누군가 들어오면 다음 메시지가 출력된다.[닉네임]님이 들어왔습니다.
//채팅방에서 누군가 나가면 다음 메시지가 출력된다. [닉네임]님이 나갔습니다.
//채팅방에서 닉네임을 변경하는 방법
//채팅방을 나간 후, 새로운 닉네임으로 다시 들어간다.
//채팅방에서 닉네임을 변경한다.
// 기존에 채팅방에 출력되어 있던 메시지의 닉네임도 전부 변경
//중복 닉네임을 허용
public class kakao_blind_2019_1 {
static String[] solution(String[] record) {
String[] answer = {};
ArrayList<String> answerL = new ArrayList<String>();
HashMap<String, String> map = new HashMap<>();
int size = record.length;
String[][] rec = new String[size][3];
for (int i = 0; i < size; i++) {
rec[i] = record[i].split(" ");
}
// 매칭
for (int i = 0; i < size; i++) {
switch (rec[i][0]) {
case "Enter":
map.put(rec[i][1], rec[i][2]);
break;
case "Change":
map.put(rec[i][1], rec[i][2]);
break;
}
}
// 메시지 출력
for (int i = 0; i < size; i++) {
switch (rec[i][0]) {
case "Enter":
answerL.add(map.get(rec[i][1])+"님이 들어왔습니다.");
break;
case "Leave":
answerL.add(map.get(rec[i][1])+"님이 나갔습니다.");
break;
}
}
return answerL.toArray(new String[answerL.size()]);
}
public static void main(String[] args) {
String[] record = { "Enter uid1234 Muzi", "Enter uid4567 Prodo", "Leave uid1234", "Enter uid1234 Prodo",
"Change uid4567 Ryan" };
for (String s : solution(record))
System.out.println(s);
}
}
|
package com.gnomikx.www.gnomikx;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.gnomikx.www.gnomikx.Data.QueryDetails;
import com.gnomikx.www.gnomikx.Handlers.FirebaseHandler;
import com.gnomikx.www.gnomikx.ViewHolders.QueryViewHolder;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class AnswerQueriesFragment extends Fragment {
private FirestoreRecyclerAdapter adapter;
private FirebaseUser user;
private TextView noQueryTextView;
public AnswerQueriesFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_answer_queries, container, false);
RecyclerView myQueryRecyclerView = rootView.findViewById(R.id.all_queries_recyclerview);
noQueryTextView = rootView.findViewById(R.id.all_queries_no_data);
FirebaseHandler handler = new FirebaseHandler();
user = handler.getFirebaseUser();
Query query;
if(user != null) {
if(user.isEmailVerified()) {
query = FirebaseFirestore.getInstance()
.collection("Queries")
.whereEqualTo("response", null)
.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<QueryDetails> options = new FirestoreRecyclerOptions.Builder<QueryDetails>()
.setQuery(query, QueryDetails.class)
.build();
adapter = new FirestoreRecyclerAdapter<QueryDetails, QueryViewHolder>(options) {
@Override
public void onBindViewHolder(QueryViewHolder holder, int position, final QueryDetails model) {
holder.itemView.setTag(model.getDocumentId());
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
String displayedString = (model.getBody().length() > 100) ? model.getBody().substring(0, 98) + getString(R.string.ellipsis)
: model.getBody();
holder.bind(dateFormat.format(model.getTimestamp()), model.getTitle(), displayedString);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("Date", dateFormat.format(model.getTimestamp()));
bundle.putString("Title", model.getTitle());
bundle.putString("Body", model.getBody());
bundle.putString("User Id", model.getUserID());
bundle.putString("User name", model.getUsername());
bundle.putString("documentId", model.getDocumentId());
bundle.putSerializable("Timestamp", model.getTimestamp());
QueryResponseFragment queryResponseFragment = new QueryResponseFragment();
queryResponseFragment.setArguments(bundle);
MainActivity activity = (MainActivity) AnswerQueriesFragment.this.getActivity();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//showing fragment
fragmentTransaction.replace(R.id.fragment_container, queryResponseFragment, MainActivity.QUERY_RESPONSE_FRAGMENT);
fragmentTransaction.addToBackStack(MainActivity.QUERY_RESPONSE_FRAGMENT).commit();
}
});
}
@Override
public void onDataChanged() {
if (getItemCount() == 0) {
noQueryTextView.setVisibility(View.VISIBLE);
} else {
noQueryTextView.setVisibility(View.GONE);
}
super.onDataChanged();
}
@Override
public void onError(@NonNull FirebaseFirestoreException e) {
super.onError(e);
}
@Override
public QueryViewHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.query_list_item, group, false);
return new QueryViewHolder(view);
}
};
myQueryRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
myQueryRecyclerView.setAdapter(adapter);
} else {
noQueryTextView.setVisibility(View.VISIBLE);
noQueryTextView.setText(R.string.email_not_verified_text);
Toast.makeText(getContext(), getText(R.string.email_not_verified_text), Toast.LENGTH_SHORT).show();
}
} else {
noQueryTextView.setVisibility(View.VISIBLE);
noQueryTextView.setText(R.string.user_not_signed_in_text);
Toast.makeText(getContext(), getString(R.string.user_not_signed_in_text), Toast.LENGTH_SHORT).show();
}
return rootView;
}
@Override
public void onStart() {
super.onStart();
if (user != null && adapter != null) {
adapter.startListening();
}
}
@Override
public void onStop() {
super.onStop();
if(user != null && adapter != null) {
adapter.stopListening();
}
}
}
|
package inherits.abstracts.salary;
public class PayoutProcessor {
public static void main(String[] args) {
BonusSalaryEmployee employee = new BonusSalaryEmployee(2000, 1);
PieceWorkSalaryEmployee employee1 = new PieceWorkSalaryEmployee(300, 5);
SalaryPayoutProcessor processor = new SalaryPayoutProcessor(employee);
processor.processPayout();
SalaryPayoutProcessor processor1 = new SalaryPayoutProcessor(employee1);
processor1.processPayout();
}
}
|
package category.dfs;
import java.util.ArrayList;
import java.util.List;
public class NQueens {
public List<String[]> solveNQueens(int n) {
List<String[]> res = new ArrayList<String[]>();
placeQueen(n, 0, new int[n], res);
return res;
}
// column[] = {1,2,0,3}; {{0,1}, {1,2}, {2,0}, {3,3}}
public void placeQueen(int n, int row, int[] column, List<String[]> res) {
if(n == row) {
String[] item = new String[n];
for (int i = 0; i < n; i++) {
StringBuilder builder = new StringBuilder();
for (int j = 0; j < item.length; j++) {
if(column[i] == j) {
builder.append('Q');
} else {
builder.append('.');
}
}
item[i] = builder.toString();
}
res.add(item);
} else {
for (int i = 0; i < column.length; i++) {
column[row] = i;
if(isAvailable(i, column)) {
placeQueen(n, row + 1, column, res);
}
}
}
}
public boolean isAvailable(int row, int[] columnForRow) {
return false;
}
}
|
package kmsUtill;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class KmsProperty {
private Properties pro;
private FileInputStream fis;
private String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public KmsProperty(String path){
try{
this.path = path;
this.fis = new FileInputStream(this.path);
this.pro.load(fis);
}
catch(IOException e){
e.printStackTrace();
System.out.println("property 읽기 실패");
}
finally{
if(fis != null){
try{
fis.close();
}catch (IOException ioe){
ioe.printStackTrace();
System.out.println("property 읽기 실패");
}
}
}
}
public String getProperty(String property_name) throws IOException {
if(pro != null){
return pro.getProperty(property_name, "");
}
else{
return "";
}
}
}
|
package com.waes.backend.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Entity
@Table(name = "USERS")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Builder
@Getter
@EqualsAndHashCode
@ToString
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
@NotNull
String username;
@NotNull
@JsonIgnore
String password;
@NotNull
String email;
String superpower;
@Column(name = "DATE_OF_BIRTH")
LocalDate dateOfBirth;
@Column(name = "IS_ADMIN")
Boolean isAdmin;
}
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "`User`")
public class User extends AbstractPersistable<Long> {
private static final long serialVersionUID = 1L;
@NotNull
@Length(max = 100)
@Column(unique = true)
private String userName;
@Length(max = 200)
private String name;
@Length(max = 200)
private String firstName;
@Email
@Length(max = 255)
@NotNull
private String email;
@Length(max = 64)
private String passwordHash;
@Length(max = 255)
private String openId;
@Length(max = 8)
private String locale;
private boolean enabled;
@Temporal(TemporalType.DATE)
private Date createDate;
@ManyToMany
@JoinTable(name = "UserRoles", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
private Set<Role> roles;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
private Set<Address> addresses = new HashSet<Address>();
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Set<Role> getRoles() {
return roles;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public Set<Address> getAddresses() {
return addresses;
}
public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
|
package cn.omsfuk.library.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/assets/**", "/register").permitAll()
.antMatchers("/admin/**").hasAuthority("admin")
.antMatchers("/reader/**").hasAuthority("reader")
.anyRequest().authenticated()
.and().csrf().disable()
.formLogin()
.loginPage("/login")
.successHandler((req, resp, auth) -> {
for (GrantedAuthority authority: auth.getAuthorities()) {
if (authority.getAuthority().equals("admin")) {
resp.sendRedirect("/admin/main");
return ;
}
if (authority.getAuthority().equals("reader")) {
resp.sendRedirect("/reader/main");
return ;
}
}
})
.permitAll();
super.configure(http);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
if (charSequence == null || s == null) return false;
return charSequence.equals(s);
}
};
}
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super(true);
//// auth.userDetailsService(new UserSecurityService());
// }
}
|
package lesson21.Ex1;
public class Cat extends Mammal{
private int age; //tuổi
private String interests; //sở thích
private String eyeColor; //màu mắt
private String petName; //tên gọi riêng
public Cat(int age, String interests, String eyeColor, String petName) {
this.age = age;
this.interests = interests;
this.eyeColor = eyeColor;
this.petName = petName;
}
public Cat(int footNumber, String color, int toothNumber, String behavior,
int age, String interests, String eyeColor, String petName) {
super(footNumber, color, toothNumber, behavior);
this.age = age;
this.interests = interests;
this.eyeColor = eyeColor;
this.petName = petName;
}
@Override
public void eat() {
super.eat();
}
@Override
public void move() {
super.move();
}
@Override
public void relax() {
super.relax();
}
//getter và setter dạng final
public final int getAge() {
return age;
}
public final void setAge(int age) {
this.age = age;
}
public final String getInterests() {
return interests;
}
public final void setInterests(String interests) {
this.interests = interests;
}
public final String getEyeColor() {
return eyeColor;
}
public final void setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
}
public final String getPetName() {
return petName;
}
public final void setPetName(String petName) {
this.petName = petName;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fetchfinance1;
import java.sql.*;
import java.io.FileOutputStream;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
import java.util.*;
/**
*
* @author Kat
*/
public class invoice {
public static void acPayReport(){
Connection conn = null;
try{
//create mysql db connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/fetchdb", "root", "mysqlpw");
String query = "SELECT * FROM invoice " + "WHERE ";
Statement stmt = conn.createStatement();
ResultSet acPayData = stmt.executeQuery(query);
Document accountPayable = new Document();
PdfWriter.getInstance(accountPayable, new FileOutputStream("accountPayableReport.pdf"));
accountPayable.open();
PdfPTable accountPayTable = new PdfPTable(4);
PdfPCell payTableCell;
while (acPayData.next()){
String invoiceId = acPayData.getString("invoiceId");
payTableCell = new PdfPCell(new Phrase(invoiceId));
accountPayTable.addCell(payTableCell);
String date1 = (acPayData.getString("DATE"));
}
// ResultSet acData = conn.prepareStatement("SELECT INVOICE");
}catch(Exception e){
}
}
}
|
package com.atrariksa.testng.simple;
public class PlainJavaGreeter {
private String hello = "hello";
public String greet(String input) {
return hello + ", " +input;
}
public String greet() {
return hello;
}
}
|
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
public class menu {
// LOCALIZAÇAO DOS RECTS MENU e PARA MENU RESTART (Usado apenas para localizacao)
protected Rectangle2D Classic = new Rectangle2D.Double(300, 150, 150, 50);
protected Rectangle2D Invert = new Rectangle2D.Double(300, 210, 150, 50);
protected Rectangle2D fantasma = new Rectangle2D.Double(300, 270, 150, 50);
protected Rectangle2D crazy = new Rectangle2D.Double(300, 330, 150, 50);
protected Rectangle2D sair = new Rectangle2D.Double(300, 390, 150, 50);
// Renderiza o MENU
public void render(Graphics g){
Graphics2D g2 = (Graphics2D) g; // cria um graphics 2D
g2.setColor(Color.white); // Cria os rects 3D com a COR BRANCA
g2.draw3DRect(300, 150, 150, 50,false);
g2.draw3DRect(300, 210, 150, 50,false);
g2.draw3DRect(300, 270, 150, 50,false);
g2.draw3DRect(300, 330, 150, 50,false);
g2.draw3DRect(300, 390, 150, 50,false);
Font font = new Font ("arial",Font.ROMAN_BASELINE,20); // Carrega a fonte
g.setFont(font);// seleciona a fonte
g.setColor(Color.white);// seleciona a cor
g.drawString("TGENIUS™", 310,100);
// Renderiza os nomes dos modos
g.drawString("Modo Classico", 310,180);
g.drawString("Modo Espelhado", 302,240);
g.drawString("Modo Fantasma", 305,300);
g.drawString("Modo Loucura", 310,360);
g.drawString("Quit", 353,420);
}
// Renderiza o MENU RESTART
public void renderRestart(Graphics g){
Graphics2D g2 = (Graphics2D) g;// cria um graphics 2D
g2.setColor(Color.white); // Cria os rects 3D com a COR BRANCA
g2.draw3DRect(300, 210, 150, 50,false);
g2.draw3DRect(300, 270, 150, 50,false);
Font font = new Font ("arial",Font.ROMAN_BASELINE,20); // Carrega a fonte
g.setFont(font);// seleciona a fonte
g.setColor(Color.white);// seleciona a cor
g.drawString("TGENIUS™", 330,100);
// Renderiza os nomes dos quadrado
g.drawString("Reiniciar", 340,240);
g.drawString("Quit", 360,300);
}
}
|
public class Interview
{
}
|
package SebastianMiklaszewski.Excercises.Presentation.UseCase.ExerciseOne;
import SebastianMiklaszewski.Excercises.Presentation.Shared.AbstractSpeaker;
public class ExerciseOneSpeaker extends AbstractSpeaker {
public void welcome() {
super.welcome(1, "Withdraw money from the wallet");
}
public void cannotWithdrawMoreThanYouHave() {
super.output.print("You have not enough money in your wallet.");
}
public void howMuchDoYouWantToWithdraw() {
super.output.print("How much do you want to withdraw? I remind you that you have only 5 USD.");
}
public void moneyWithdrawnSuccessful() {
super.output.print("Money withdrawn successful.");
}
}
|
package com.pybeta.daymatter.ui;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.pybeta.daymatter.R;
import com.pybeta.daymatter.core.MatterApplication;
import com.pybeta.daymatter.utils.DateUtils;
import com.pybeta.ui.widget.NumberPickerDialog;
import com.pybeta.ui.widget.NumberPickerDialog.OnNumberSetListener;
import com.pybeta.ui.widget.UcTitleBar;
import com.pybeta.widget.NumberPicker;
public class CountdownRecActivity extends Activity implements OnClickListener{
//原本继承SherlockFragment
private UcTitleBar mTitleBar = null;
//----------Date------------
private Calendar mStartCalendar;
private Calendar mEndCalendar;
private Button mStartBtn;
private Button mEndBtn;
private TextView mResultText;
//----------Dates-----------
private Calendar mCalendar;
private Button mCalendarBtn;
private Button mBeforeResult;
private Button mBeforeInput;
private Button mAfterResult;
private Button mAfterInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.fragment_countdown);
initTitleBar();
initDateView();
initDatesView();
//下方视图
// ViewGroup daysCountLayout = (ViewGroup) this.findViewById(R.id.days_fragment);
// LinearLayout datesCountView = new DaysCountFragment(this);
// daysCountLayout.addView(datesCountView);
//上方视图
// ViewGroup dateCountLayout = (ViewGroup) this.findViewById(R.id.date_fragment);
// LinearLayout dateCountView = new DateCountFragment(this);
// LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, 0 ,1);
// lp.gravity = Gravity.CENTER;
// dateCountLayout.setLayoutParams(lp);
// dateCountLayout.addView(dateCountView);
}
private void initTitleBar(){
mTitleBar = (UcTitleBar)this.findViewById(R.id.uc_titlebar_countdown);
mTitleBar.setTitleText(getResources().getString(R.string.date_cal));
mTitleBar.setViewVisible(false, true, false, false, false, false, false, false);
mTitleBar.setListener(new UcTitleBar.ITitleBarListener(){
@Override
public void shareClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void menuClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void feedBackClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void editClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void completeClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void backClick(Object obj) {
// TODO Auto-generated method stub
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
@Override
public void addClick(Object obj) {
// TODO Auto-generated method stub
}
@Override
public void closeClick(Object obj) {
// TODO Auto-generated method stub
}
});
}
private void initDateView(){
mStartCalendar = Calendar.getInstance();
mEndCalendar = Calendar.getInstance();
mStartBtn = (Button) this.findViewById(R.id.count_date_start_btn_date);
mEndBtn = (Button) this.findViewById(R.id.count_date_end_btn_date);
mResultText = (TextView) this.findViewById(R.id.count_date_result_num_date);
mStartBtn.setOnClickListener(this);
mEndBtn.setOnClickListener(this);
dateCount();
}
protected void dateCount() {
String datePattern = getString(R.string.matter_calendar_gregorian_date_format);
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
mStartBtn.setText(dateFormat.format(mStartCalendar.getTime()));
mEndBtn.setText(dateFormat.format(mEndCalendar.getTime()));
String result = String.valueOf(DateUtils.getDaysBetween(mEndCalendar, mStartCalendar));
SpannableString ss = new SpannableString(result + " " +getResources().getString(R.string.matter_unit));
ss.setSpan(new ForegroundColorSpan(Color.RED), 0, result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mResultText.setText(ss);
}
private void initDatesView(){
mCalendar = Calendar.getInstance();
mCalendarBtn = (Button) findViewById(R.id.count_date_start_btn_dates);
mBeforeResult = (Button) findViewById(R.id.count_before_days_result_dates);
mBeforeInput = (Button) findViewById(R.id.count_before_days_input_dates);
mBeforeInput.setText("0");
mAfterResult = (Button) findViewById(R.id.count_after_days_result_dates);
mAfterInput = (Button) findViewById(R.id.count_after_days_input_dates);
mAfterInput.setText("0");
mCalendarBtn.setOnClickListener(this);
mBeforeInput.setOnClickListener(this);
mAfterInput.setOnClickListener(this);
datesCount();
}
protected void datesCount() {
String datePattern = getString(R.string.matter_calendar_gregorian_date_format);
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
mCalendarBtn.setText(dateFormat.format(mCalendar.getTime()));
int beforeDays = 0;
try {
beforeDays = Integer.parseInt(mBeforeInput.getText().toString());
} catch (Exception e) {
}
Calendar beforeCal = (Calendar) mCalendar.clone();
beforeCal.add(Calendar.DAY_OF_MONTH, 0 - beforeDays);
mBeforeResult.setText(dateFormat.format(beforeCal.getTime()));
int afterDays = 0;
try {
afterDays = Integer.parseInt(mAfterInput.getText().toString());
} catch (Exception e) {
}
Calendar afterCal = (Calendar) mCalendar.clone();
afterCal.add(Calendar.DAY_OF_MONTH, afterDays);
mAfterResult.setText(dateFormat.format(afterCal.getTime()));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
//-----------------DateBtn---------------------
case R.id.count_date_start_btn_date: {
new DatePickerDialog(CountdownRecActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mStartCalendar.set(year, monthOfYear, dayOfMonth);
dateCount();
}
}, mStartCalendar.get(Calendar.YEAR), mStartCalendar.get(Calendar.MONTH),mStartCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
}
case R.id.count_date_end_btn_date: {
new DatePickerDialog(CountdownRecActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mEndCalendar.set(year, monthOfYear, dayOfMonth);
dateCount();
}
}, mEndCalendar.get(Calendar.YEAR), mEndCalendar.get(Calendar.MONTH),
mEndCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
}
//-----------------DatesBtn---------------------
case R.id.count_date_start_btn_dates: {
new DatePickerDialog(CountdownRecActivity.this,new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(year, monthOfYear, dayOfMonth);
datesCount();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
}
case R.id.count_before_days_input_dates: {
int beforeDays = 0;
try {
beforeDays = Integer.parseInt(mBeforeInput.getText().toString());
} catch (Exception e) {
}
NumberPickerDialog dialog = new NumberPickerDialog(CountdownRecActivity.this, new OnNumberSetListener() {
@Override
public void onDateSet(NumberPicker view, int value) {
mBeforeInput.setText(String.valueOf(value));
datesCount();
}
}, beforeDays);
dialog.show();
break;
}
case R.id.count_after_days_input_dates: {
int afterDays = 0;
try {
afterDays = Integer.parseInt(mAfterInput.getText().toString());
} catch (Exception e) {
}
new NumberPickerDialog(CountdownRecActivity.this, new OnNumberSetListener() {
@Override
public void onDateSet(NumberPicker view, int value) {
mAfterInput.setText(String.valueOf(value));
datesCount();
}
}, afterDays).show();
break;
}
default:
break;
}
}
// public class DateCountFragment extends LinearLayout implements OnClickListener {
//
// private Calendar mStartCalendar;
// private Calendar mEndCalendar;
//
// private Button mStartBtn;
// private Button mEndBtn;
// private TextView mResultText;
//
// public DateCountFragment(Context context) {
// super(context);
//
// mStartCalendar = Calendar.getInstance();
// mEndCalendar = Calendar.getInstance();
//
// ViewGroup container = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.count_date_fragement_layout, null);
// LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// container.setLayoutParams(lp);
//
// addView(container);
//
// mStartBtn = (Button) container.findViewById(R.id.count_date_start_btn);
// mEndBtn = (Button) container.findViewById(R.id.count_date_end_btn);
// mResultText = (TextView) container.findViewById(R.id.count_date_result_num);
//
// mStartBtn.setOnClickListener(this);
// mEndBtn.setOnClickListener(this);
//
// count();
// }
//
// protected void count() {
// String datePattern = getString(R.string.matter_calendar_gregorian_date_format);
// SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
// mStartBtn.setText(dateFormat.format(mStartCalendar.getTime()));
// mEndBtn.setText(dateFormat.format(mEndCalendar.getTime()));
//
// String result = String.valueOf(DateUtils.getDaysBetween(mEndCalendar, mStartCalendar));
//
// SpannableString ss = new SpannableString(result + " " +getResources().getString(R.string.matter_unit));
// ss.setSpan(new ForegroundColorSpan(Color.RED), 0, result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//
// mResultText.setText(ss);
//
//// if (Math.abs(result) > 1) {
//// mResultText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.string.matter_unit, 0);
//// } else {
//// mResultText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.string.matter_unit, 0);
//// }
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.count_date_start_btn: {
// new DatePickerDialog(CountdownRecActivity.this, new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// mStartCalendar.set(year, monthOfYear, dayOfMonth);
// count();
// }
// }, mStartCalendar.get(Calendar.YEAR), mStartCalendar.get(Calendar.MONTH),
// mStartCalendar.get(Calendar.DAY_OF_MONTH)).show();
// break;
// }
// case R.id.count_date_end_btn: {
// new DatePickerDialog(CountdownRecActivity.this, new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// mEndCalendar.set(year, monthOfYear, dayOfMonth);
// count();
// }
// }, mEndCalendar.get(Calendar.YEAR), mEndCalendar.get(Calendar.MONTH),
// mEndCalendar.get(Calendar.DAY_OF_MONTH)).show();
// break;
// }
// default:
// break;
// }
// }
// }
//
// public class DaysCountFragment extends LinearLayout implements OnClickListener {
//
// private Calendar mCalendar;
// private Button mCalendarBtn;
// private Button mBeforeResult;
// private Button mBeforeInput;
//
// private Button mAfterResult;
// private Button mAfterInput;
//
// public DaysCountFragment(Context context) {
// super(context);
// mCalendar = Calendar.getInstance();
//
// LayoutInflater.from(context).inflate(R.layout.count_days_fragement_layout, this, true);
// LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// this.setLayoutParams(lp);
//
//
// mCalendarBtn = (Button) findViewById(R.id.count_date_start_btn);
// mBeforeResult = (Button) findViewById(R.id.count_before_days_result);
// mBeforeInput = (Button) findViewById(R.id.count_before_days_input);
// mBeforeInput.setText("0");
//
// mAfterResult = (Button) findViewById(R.id.count_after_days_result);
// mAfterInput = (Button) findViewById(R.id.count_after_days_input);
// mAfterInput.setText("0");
//
// mCalendarBtn.setOnClickListener(this);
// mBeforeInput.setOnClickListener(this);
// mAfterInput.setOnClickListener(this);
//
// count();
//
// }
//
// protected void count() {
// String datePattern = getString(R.string.matter_calendar_gregorian_date_format);
// SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
// mCalendarBtn.setText(dateFormat.format(mCalendar.getTime()));
//
// int beforeDays = 0;
// try {
// beforeDays = Integer.parseInt(mBeforeInput.getText().toString());
// } catch (Exception e) {
// }
//
// Calendar beforeCal = (Calendar) mCalendar.clone();
// beforeCal.add(Calendar.DAY_OF_MONTH, 0 - beforeDays);
// mBeforeResult.setText(dateFormat.format(beforeCal.getTime()));
//
// int afterDays = 0;
// try {
// afterDays = Integer.parseInt(mAfterInput.getText().toString());
// } catch (Exception e) {
// }
//
// Calendar afterCal = (Calendar) mCalendar.clone();
// afterCal.add(Calendar.DAY_OF_MONTH, afterDays);
// mAfterResult.setText(dateFormat.format(afterCal.getTime()));
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.count_date_start_btn: {
// new DatePickerDialog(CountdownRecActivity.this,
// new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// mCalendar.set(year, monthOfYear, dayOfMonth);
// count();
// }
// }, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();
// break;
// }
// case R.id.count_before_days_input: {
// int beforeDays = 0;
// try {
// beforeDays = Integer.parseInt(mBeforeInput.getText().toString());
// } catch (Exception e) {
// }
//
// new NumberPickerDialog(CountdownRecActivity.this, new OnNumberSetListener() {
// @Override
// public void onDateSet(NumberPicker view, int value) {
// mBeforeInput.setText(String.valueOf(value));
// count();
// }
// }, beforeDays).show();
// break;
// }
// case R.id.count_after_days_input: {
// int afterDays = 0;
// try {
// afterDays = Integer.parseInt(mAfterInput.getText().toString());
// } catch (Exception e) {
// }
//
// new NumberPickerDialog(CountdownRecActivity.this, new OnNumberSetListener() {
// @Override
// public void onDateSet(NumberPicker view, int value) {
// mAfterInput.setText(String.valueOf(value));
// count();
// }
// }, afterDays).show();
// break;
// }
// }
// }
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// getSherlockActivity().getSupportActionBar().setTitle(R.string.title_activity_count_down);
// return inflater.inflate(R.layout.fragment_countdown, null);
// }
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// ViewGroup dateCountView = (ViewGroup) view.findViewById(R.id.date_fragment);
// dateCountView.addView(new DateCountFragment(getSherlockActivity()));
//
// ViewGroup daysCountView = (ViewGroup) view.findViewById(R.id.days_fragment);
// daysCountView.addView(new DaysCountFragment(getSherlockActivity()));
// }
}
|
package com.casterlabs.vanishingwallapi.service;
import com.casterlabs.vanishingwallapi.modal.PostDetail;
import java.util.ArrayList;
public interface IPostDeliveryService {
ArrayList<PostDetail> deliverNewPost();
}
|
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Stack;
//This class contains the implementation of the recursive descent parser. Each function is representative of a non-terminal.
public class Parser
{
public boolean status;
public Token currentToken;
public int variableCount, functionCount, statementCount;
Scanner scanner;
PrintWriter newFile;
HashMap<String, Integer> localMap;
int localCount;
HashMap<String, Integer> globalMap;
String currrentGlobalID;
int globalCount;
String localFunction;
boolean declareFlag, inFunction, globalFlag;
int labelCount, startLabel, endLabel, condLabel;
//Function to evaluate an infix expression to the two operand mode.
public String evaluate(ArrayList<String> expression)
{
Stack<String> Values = new Stack<String>(), Operations = new Stack<String>();
for (int i = 0; i < expression.size(); i++)
{
if (expression.get(i).equals("("))
Operations.push(expression.get(i));
else if (expression.get(i).equals(")"))
{
while (Operations.peek().equals("("))
Values.push(apply(Operations.pop(), Values.pop(), Values.pop()));
Operations.pop();
}
else if (expression.get(i).equals("+") || expression.get(i).equals("-") || expression.get(i).equals("*") || expression.get(i).equals("/"))
{
while (!Operations.empty() && precedence(expression.get(i), Operations.peek()))
Values.push(apply(Operations.pop(), Values.pop(), Values.pop()));
Operations.push(expression.get(i));
}
else
{
Values.push(expression.get(i));
}
}
while (!Operations.empty())
Values.push(apply(Operations.pop(), Values.pop(), Values.pop()));
return Values.pop();
}
public boolean precedence(String o1, String o2)
{
if (o2.equals("(") || o2.equals(")"))
return false;
if ((o1.equals("*") || o1.equals("/")) && (o2.equals("+") || o2.equals("-")))
return false;
else
return true;
}
public String apply(String o, String b, String a)
{
switch (o)
{
case "+":
localFunction += "local[" + localCount + "] = " + a + " + " + b +";\n";
return "local[" + localCount++ + "]";
case "-":
localFunction += "local[" + localCount + "] = " + a + " - " + b +";\n";
return "local[" + localCount++ + "]";
case "*":
localFunction += "local[" + localCount + "] = " + a + " * " + b +";\n";
return "local[" + localCount++ + "]";
case "/":
localFunction += "local[" + localCount + "] = " + a + " / " + b +";\n";
return "local[" + localCount++ + "]";
}
return null;
}
//This function gets the next token from the scanner, checks if it is not meta or error.
private boolean UpdateToken()
{
try
{
Token tempToken = scanner.GetNextToken();
if(tempToken.GetTokenType() == TokenType.ERROR)
{
currentToken = tempToken;
return false;
}
if(tempToken.GetTokenType() == TokenType.META)
{
newFile.write(tempToken.GetTokenName() + "\n");
return UpdateToken();
}
currentToken = tempToken;
}
catch(Exception e)
{
}
return true;
}
//Initializes the parser and the scanner.
public Parser(String inputFile, PrintWriter newFile)
{
try
{
this.scanner = new Scanner(inputFile);
this.newFile = newFile;
variableCount = functionCount = statementCount = labelCount = startLabel = endLabel = condLabel = globalCount = localCount = 0;
globalFlag = true;
declareFlag = true;
inFunction = true;
globalMap = new HashMap<String, Integer>();
status = false;
UpdateToken();
}
catch(Exception e)
{
}
}
private boolean block_statements()
{
if(!currentToken.GetTokenName().equals("{"))
{
return false;
}
UpdateToken();
if(!statements())
{
return false;
}
if(!currentToken.GetTokenName().equals("}"))
{
return false;
}
UpdateToken();
return true;
}
private boolean statements()
{
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER) && !currentToken.GetTokenName().equals("if") && !currentToken.GetTokenName().equals("while") && !currentToken.GetTokenName().equals("return") && !currentToken.GetTokenName().equals("break") && !currentToken.GetTokenName().equals("continue") && !currentToken.GetTokenName().equals("read") && !currentToken.GetTokenName().equals("write") && !currentToken.GetTokenName().equals("print"))
{
return true;
}
if(!statement())
{
return false;
}
statementCount++;
if(!statements())
{
return false;
}
return true;
}
private boolean statement()
{
if(currentToken.GetTokenType() == TokenType.IDENTIFIER)
{
return statement_dash();
}
if(currentToken.GetTokenName().equals("if"))
{
return if_statement();
}
if(currentToken.GetTokenName().equals("while"))
{
return while_statement();
}
if(currentToken.GetTokenName().equals("return"))
{
return return_statement();
}
if(currentToken.GetTokenName().equals("break"))
{
return break_statement();
}
if(currentToken.GetTokenName().equals("continue"))
{
return continue_statement();
}
if(currentToken.GetTokenName().equals("read"))
{
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
if(localMap.get(currentToken.GetTokenName()) != null)
{
localFunction += "local[" + localMap.get(currentToken.GetTokenName()) + "]";
}
else
{
localFunction += "global[" + globalMap.get(currentToken.GetTokenName()) + "]";
}
UpdateToken();
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
localFunction += currentToken.GetTokenName() + "\n";
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("write"))
{
String writeFunction = "";
writeFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
writeFunction += currentToken.GetTokenName();
UpdateToken();
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
if(expression.size() > 0)
writeFunction += evaluate(expression);
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
writeFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
writeFunction += currentToken.GetTokenName();
localFunction += writeFunction + "\n";
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("print"))
{
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!(currentToken.GetTokenType() == TokenType.STRING))
{
return false;
}
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
localFunction += currentToken.GetTokenName();
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
localFunction += currentToken.GetTokenName() + "\n";
UpdateToken();
return true;
}
return false;
}
private boolean statement_dash()
{
boolean globalVariable = false;
StringBuilder stateFunction = new StringBuilder();
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
String tempAss;
if(localMap.get(currentToken.GetTokenName()) != null)
{
tempAss = "local[" + localMap.get(currentToken.GetTokenName()) + "]";
}
else
{
tempAss = "global[" + globalMap.get(currentToken.GetTokenName()) + "]";
globalVariable = true;
}
String IDName = currentToken.GetTokenName();
int arrCount = -1;
UpdateToken();
if(currentToken.GetTokenName().equals("["))
{
if(localMap.get(IDName) != null)
{
stateFunction.append("local[" + localCount++ + "] = " + localMap.get(IDName) + " + ");
arrCount = localCount - 1;
}
else
{
stateFunction.append("local[" + localCount++ + "] = " + globalMap.get(IDName) + " + ");
arrCount = localCount - 1;
globalVariable = true;
}
}
else if(currentToken.GetTokenName().equals("("))
{
stateFunction.append(IDName);
boolean retValues = func_call(stateFunction);
localFunction += stateFunction;
return retValues;
}
else
{
stateFunction.append(tempAss);
}
boolean retValues = assignment(stateFunction, "local[" + arrCount + "]", globalVariable);
localFunction += stateFunction;
return retValues;
}
private boolean assignment(StringBuilder assignFunction, String variable, Boolean globalVariable)
{
if(!id_dash(assignFunction, variable, globalVariable))
{
return false;
}
if(!currentToken.GetTokenName().equals("="))
{
return false;
}
assignFunction.append(currentToken.GetTokenName());
UpdateToken();
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
if(expression.size() > 0)
assignFunction.append(evaluate(expression));
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
assignFunction.append(currentToken.GetTokenName() + "\n");
UpdateToken();
return true;
}
private boolean func_call(StringBuilder funcFunction)
{
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
funcFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!expr_list(funcFunction))
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
funcFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
funcFunction.append(currentToken.GetTokenName() + "\n");
UpdateToken();
return true;
}
private boolean expr_list(StringBuilder funcFunction)
{
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER) && !(currentToken.GetTokenType() == TokenType.NUMBER) && !currentToken.GetTokenName().equals("(") && !currentToken.GetTokenName().equals("-"))
{
return true;
}
if(!non_empty_expr_list(funcFunction))
{
return false;
}
return true;
}
private boolean non_empty_expr_list(StringBuilder funcFunction)
{
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
funcFunction.append(evaluate(expression));
if(!non_empty_expr_list_dash(funcFunction))
{
return false;
}
return true;
}
private boolean non_empty_expr_list_dash(StringBuilder funcFunction)
{
if(!currentToken.GetTokenName().equals(","))
{
return true;
}
funcFunction.append(currentToken.GetTokenName());
UpdateToken();
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
funcFunction.append(evaluate(expression));
if(!non_empty_expr_list_dash(funcFunction))
{
return false;
}
return true;
}
private boolean if_statement()
{
StringBuilder ifFunction = new StringBuilder();
ifFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
ifFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!condition_expression(ifFunction))
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
ifFunction.append(currentToken.GetTokenName() + "\n");
int ifEndLabel = labelCount++;
int ifStartLabel = labelCount++;
ifFunction.append("goto L" + ifStartLabel + ";\n" + "goto L" + ifEndLabel + ";\n");
UpdateToken();
localFunction += ifFunction;
localFunction += "L" + ifStartLabel + ":;\n";
if(!block_statements())
{
return false;
}
localFunction += "L" + ifEndLabel + ":;\n";
return true;
}
private boolean condition_expression(StringBuilder ifFunction)
{
if(!condition(ifFunction))
{
return false;
}
if(!condition_expression_dash(ifFunction))
{
return false;
}
return true;
}
private boolean condition_expression_dash(StringBuilder ifFunction)
{
if(!currentToken.GetTokenName().equals("||") && !currentToken.GetTokenName().equals("&&"))
{
return true;
}
if(!condition_op(ifFunction))
{
return false;
}
if(!condition(ifFunction))
{
return false;
}
return true;
}
private boolean condition_op(StringBuilder ifFunction)
{
if(!currentToken.GetTokenName().equals("||") && !currentToken.GetTokenName().equals("&&"))
{
return false;
}
ifFunction.append(currentToken.GetTokenName());
UpdateToken();
return true;
}
private boolean condition(StringBuilder ifFunction)
{
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
ifFunction.append(evaluate(expression));
if(!comparison_op(ifFunction))
{
return false;
}
ArrayList<String> expression2 = new ArrayList<String>();
if(!expression(expression2))
{
return false;
}
ifFunction.append(evaluate(expression2));
return true;
}
private boolean comparison_op(StringBuilder ifFunction)
{
if(!currentToken.GetTokenName().equals("==") && !currentToken.GetTokenName().equals("!=") && !currentToken.GetTokenName().equals(">") && !currentToken.GetTokenName().equals(">=") && !currentToken.GetTokenName().equals("<") && !currentToken.GetTokenName().equals("<="))
{
return false;
}
ifFunction.append(currentToken.GetTokenName());
UpdateToken();
return true;
}
private boolean while_statement()
{
StringBuilder whileFunction = new StringBuilder();
int whileStartLabel = labelCount++;
int whileEndLabel = labelCount++;
int whileCondLabel = labelCount++;
startLabel = whileStartLabel;
endLabel = whileEndLabel;
condLabel = whileCondLabel;
whileFunction.append("L" + whileCondLabel + ":;\n");
whileFunction.append("if");
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
whileFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!condition_expression(whileFunction))
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
whileFunction.append(currentToken.GetTokenName() + "\n");
whileFunction.append("goto L" + whileStartLabel + ";\n");
whileFunction.append("goto L" + whileEndLabel + ";\n");
UpdateToken();
whileFunction.append("L" + whileStartLabel + ":;\n");
localFunction += whileFunction;
if(!block_statements())
{
return false;
}
whileFunction = new StringBuilder();
whileFunction.append("goto L" + whileCondLabel + ";\n");
whileFunction.append("L" + whileEndLabel + ":;\n");
localFunction += whileFunction;
return true;
}
private boolean return_statement()
{
String returnFunction = "";
UpdateToken();
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER) && !(currentToken.GetTokenType() == TokenType.NUMBER) && !currentToken.GetTokenName().equals("(") && !currentToken.GetTokenName().equals(")") && !currentToken.GetTokenName().equals("-"))
{
if(currentToken.GetTokenName().equals(";"))
{
returnFunction += "return " + currentToken.GetTokenName() + "\n";
UpdateToken();
localFunction += returnFunction;
return true;
}
}
int returnValuesue = localCount++;
returnFunction += "local[" + returnValuesue + "] = ";
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
returnFunction += evaluate(expression);
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
returnFunction += ";\n";
returnFunction += "return local[" + returnValuesue + "]" + currentToken.GetTokenName() + "\n";
UpdateToken();
localFunction += returnFunction;
return true;
}
private boolean break_statement()
{
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
localFunction += "goto L" + endLabel + ";\n";
UpdateToken();
return true;
}
private boolean continue_statement()
{
UpdateToken();
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
localFunction += "goto L" + condLabel + ";\n";
UpdateToken();
return true;
}
private boolean expression(ArrayList<String> expression)
{
if(!term(expression))
{
return false;
}
if(!expression_dash(expression))
{
return false;
}
return true;
}
private boolean expression_dash(ArrayList<String> expression)
{
if(!currentToken.GetTokenName().equals("+") && !currentToken.GetTokenName().equals("-"))
{
return true;
}
if(!addop(expression))
{
return false;
}
if(!term(expression))
{
return false;
}
if(!expression_dash(expression))
{
return false;
}
return true;
}
private boolean addop(ArrayList<String> expression)
{
if(!currentToken.GetTokenName().equals("+") && !currentToken.GetTokenName().equals("-"))
{
return false;
}
expression.add(currentToken.GetTokenName());
UpdateToken();
return true;
}
private boolean term(ArrayList<String> expression)
{
if(!factor(expression))
{
return false;
}
if(!term_dash(expression))
{
return false;
}
return true;
}
private boolean term_dash(ArrayList<String> expression)
{
if(!currentToken.GetTokenName().equals("*") && !currentToken.GetTokenName().equals("/"))
{
return true;
}
if(!mulop(expression))
{
return false;
}
if(!factor(expression))
{
return false;
}
if(!term_dash(expression))
{
return false;
}
return true;
}
private boolean mulop(ArrayList<String> expression)
{
if(!currentToken.GetTokenName().equals("*") && !currentToken.GetTokenName().equals("/"))
{
return false;
}
expression.add(currentToken.GetTokenName());
UpdateToken();
return true;
}
private boolean factor(ArrayList<String> expression)
{
if(currentToken.GetTokenType() == TokenType.IDENTIFIER)
{
String variable = "";
StringBuilder factorFunction = new StringBuilder();
String IDName = currentToken.GetTokenName();
boolean normalIDFlag = false;
UpdateToken();
if(currentToken.GetTokenName().equals("("))
{
factorFunction.append("local[" + localCount++ + "] = " + IDName);
variable = "local[" + (localCount - 1) + "]";
}
else if(currentToken.GetTokenName().equals("["))
{
if(localMap.get(IDName) != null)
{
factorFunction.append("local[" + localCount++ + "] = " + localMap.get(IDName) + " + ");
variable = "local[local[" + (localCount - 1) + "]]";
}
else
{
factorFunction.append("local[" + localCount++ + "] = " + globalMap.get(IDName) + " + ");
variable = "global[local[" + (localCount - 1) + "]]";
}
}
else
{
normalIDFlag = true;
if(localMap.get(IDName) != null)
{
variable = "local[" + localMap.get(IDName) + "]";
}
else
{
variable = "global[" + globalMap.get(IDName) + "]";
}
}
boolean retValues = factor_dash(factorFunction);
factorFunction.append(";\n");
expression.add(variable);
if(!normalIDFlag)
localFunction += factorFunction;
return retValues;
}
if(currentToken.GetTokenType() == TokenType.NUMBER)
{
localFunction += "local[" + localCount++ + "] = " + currentToken.GetTokenName() + ";\n";
expression.add("local[" + (localCount -1) + "]");
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("-"))
{
UpdateToken();
if(!(currentToken.GetTokenType() == TokenType.NUMBER))
{
return false;
}
localFunction += "local[" + localCount++ + "] = -" + currentToken.GetTokenName() + ";\n";
expression.add("local[" + (localCount -1) + "]");
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("("))
{
ArrayList<String> newExpression = new ArrayList<String>();
UpdateToken();
if(!expression(newExpression))
{
return false;
}
expression.add(evaluate(newExpression));
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
UpdateToken();
return true;
}
return false;
}
private boolean factor_dash(StringBuilder factorFunction)
{
if(currentToken.GetTokenName().equals("["))
{
ArrayList<String> expression = new ArrayList<String>();
UpdateToken();
if(!expression(expression))
{
return false;
}
factorFunction.append(evaluate(expression));
if(!currentToken.GetTokenName().equals("]"))
{
return false;
}
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("("))
{
factorFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!expr_list(factorFunction))
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
factorFunction.append(currentToken.GetTokenName());
UpdateToken();
return true;
}
return true;
}
private boolean non_empty_list()
{
if(!type_name(new StringBuilder()))
{
return false;
}
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
localMap.put(currentToken.GetTokenName(), localCount++);
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!non_empty_list_dash())
{
return false;
}
return true;
}
private boolean non_empty_list_dash()
{
if(!currentToken.GetTokenName().equals(","))
{
return true;
}
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!type_name(new StringBuilder()))
{
return false;
}
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
localMap.put(currentToken.GetTokenName(), localCount++);
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!non_empty_list_dash())
{
return false;
}
return true;
}
private boolean parameter_list_dash()
{
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return true;
}
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!non_empty_list_dash())
{
return false;
}
return true;
}
private boolean parameter_list()
{
if(!currentToken.GetTokenName().equals("int") && !currentToken.GetTokenName().equals("void") && !currentToken.GetTokenName().equals("binary") && !currentToken.GetTokenName().equals("decimal"))
{
return true;
}
if(currentToken.GetTokenName().equals("void"))
{
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!parameter_list_dash())
{
return false;
}
return true;
}
if(!non_empty_list())
{
return false;
}
return true;
}
private boolean func_decl()
{
if(!type_name(new StringBuilder()))
{
return false;
}
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
localMap = new HashMap<String, Integer>();
localCount = 0;
localFunction = "";
declareFlag = true;
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!parameter_list())
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
newFile.write(currentToken.GetTokenName());
UpdateToken();
return true;
}
private boolean func_dash()
{
if(currentToken.GetTokenName().equals(";"))
{
newFile.write(currentToken.GetTokenName() + "\n");
UpdateToken();
return true;
}
Iterator it = localMap.entrySet().iterator();
while(it.hasNext())
{
Entry pair = (Entry)it.next();
localFunction += "local[" + pair.getValue() + "]" + "=" + pair.getKey() + ";\n";
}
if(!currentToken.GetTokenName().equals("{"))
{
return false;
}
inFunction = true;
newFile.write("\n" + currentToken.GetTokenName() + "\n");
UpdateToken();
if(!data_decls())
{
return false;
}
declareFlag = false;
if(!statements())
{
return false;
}
if(!currentToken.GetTokenName().equals("}"))
{
return false;
}
inFunction = false;
newFile.write("int local[" + localCount + "];\n");
newFile.write(localFunction);
newFile.write("\n" + currentToken.GetTokenName() + "\n");
UpdateToken();
return true;
}
private boolean func()
{
if(!func_decl())
{
return false;
}
if(!func_dash())
{
return false;
}
return true;
}
private boolean func_list()
{
if(!currentToken.GetTokenName().equals("int") && !currentToken.GetTokenName().equals("void") && !currentToken.GetTokenName().equals("binary") && !currentToken.GetTokenName().equals("decimal"))
{
return true;
}
if(!func())
{
return false;
}
functionCount++;
if(!func_list())
{
return false;
}
return true;
}
private boolean type_name(StringBuilder typeNameFunction)
{
if(currentToken.GetTokenName().equals("int"))
{
if(!inFunction)
{
newFile.write(currentToken.GetTokenName() + " ");
}
else
{
typeNameFunction.append(currentToken.GetTokenName() + " ");
}
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("void"))
{
if(!inFunction)
{
newFile.write(currentToken.GetTokenName() + " ");
}
else
{
typeNameFunction.append(currentToken.GetTokenName() + " ");
}
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("binary"))
{
if(!inFunction)
{
newFile.write(currentToken.GetTokenName() + " ");
}
else
{
typeNameFunction.append(currentToken.GetTokenName() + " ");
}
UpdateToken();
return true;
}
if(currentToken.GetTokenName().equals("decimal"))
{
if(!inFunction)
{
newFile.write(currentToken.GetTokenName() + " ");
}
else
{
typeNameFunction.append(currentToken.GetTokenName() + " ");
}
UpdateToken();
return true;
}
return false;
}
private boolean id_list()
{
if(!id())
{
return false;
}
if(!id_list_dash())
{
return false;
}
return true;
}
private boolean id_dash(StringBuilder iddashFunction, String variable, boolean globalVariable)
{
if(!currentToken.GetTokenName().equals("["))
{
return true;
}
UpdateToken();
if(declareFlag)
{
if(!(currentToken.GetTokenType() == TokenType.NUMBER))
{
return false;
}
int arrSize = Integer.parseInt(currentToken.GetTokenName());
if(globalFlag)
{
globalCount += arrSize - 1;
}
else
{
localCount += arrSize - 1;
}
UpdateToken();
}
else
{
ArrayList<String> expression = new ArrayList<String>();
if(!expression(expression))
{
return false;
}
iddashFunction.append(evaluate(expression));
if(globalVariable)
{
iddashFunction.append(";\nglobal[" + variable + "] ");
}
else
{
iddashFunction.append(";\nlocal[" + variable + "] ");
}
}
if(!currentToken.GetTokenName().equals("]"))
{
return false;
}
UpdateToken();
return true;
}
private boolean id_list_dash()
{
if(!currentToken.GetTokenName().equals(","))
{
return true;
}
UpdateToken();
if(!id())
{
return false;
}
if(!id_list_dash())
{
return false;
}
return true;
}
private boolean id()
{
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
if(globalFlag)
{
globalMap.put(currentToken.GetTokenName(), globalCount++);
currrentGlobalID = currentToken.GetTokenName();
}
else
{
localMap.put(currentToken.GetTokenName(), localCount++);
}
UpdateToken();
variableCount++;
if(!id_dash(new StringBuilder(), null, false))
{
return false;
}
return true;
}
private boolean data_decls()
{
if(!type_name(new StringBuilder()))
{
return true;
}
if(!id_list())
{
return false;
}
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
UpdateToken();
if(!data_decls())
{
return false;
}
return true;
}
private boolean program_dash(StringBuilder programDashFunction)
{
if(currentToken.GetTokenName().equals(",") || currentToken.GetTokenName().equals("["))
{
globalMap.put(currrentGlobalID, globalCount++);
variableCount++;
if(!id_dash(new StringBuilder(), null, false))
{
return false;
}
if(!id_list_dash())
{
return false;
}
if(!currentToken.GetTokenName().equals(";"))
{
return false;
}
UpdateToken();
if(!program_start())
{
return false;
}
return true;
}
if(currentToken.GetTokenName().equals(";"))
{
globalMap.put(currrentGlobalID, globalCount++);
UpdateToken();
if(!program_start())
{
return false;
}
variableCount++;
return true;
}
newFile.write("int global[" + globalCount +"];\n");
newFile.write(programDashFunction.toString());
if(!currentToken.GetTokenName().equals("("))
{
return false;
}
localMap = new HashMap<String, Integer>();
localCount = 0;
localFunction = "";
declareFlag = true;
globalFlag = false;
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!parameter_list())
{
return false;
}
if(!currentToken.GetTokenName().equals(")"))
{
return false;
}
newFile.write(currentToken.GetTokenName());
UpdateToken();
if(!func_dash())
{
return false;
}
if(!func_list())
{
return false;
}
functionCount++;
return true;
}
private boolean program_start()
{
StringBuilder programStartFunction = new StringBuilder();
if(currentToken.GetTokenType() == TokenType.EOF)
{
return true;
}
if(!type_name(programStartFunction))
{
return false;
}
if(!(currentToken.GetTokenType() == TokenType.IDENTIFIER))
{
return false;
}
currrentGlobalID = currentToken.GetTokenName();
programStartFunction.append(currentToken.GetTokenName());
UpdateToken();
if(!program_dash(programStartFunction))
{
return false;
}
return true;
}
private boolean program()
{
if(!program_start())
{
return false;
}
return true;
}
//Entry for the start of the parsing process
public void parse()
{
try
{
status = program();
}
catch(Exception e)
{
}
}
}
|
package backjoon.math;
import java.io.*;
public class Backjoon4948 {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
while(true){
int n = Integer.parseInt(br.readLine());
if(n == 0) break;
calcPrimeNumCnt(n);
}
br.close();
bw.close();
}
private static void calcPrimeNumCnt(int n) throws IOException {
int arr[] = new int[2 * n + 1];
int cnt = 0;
for(int i = 2; i <= 2 * n; i++){
arr[i] = i;
}
for(int i = 2; i <= Math.sqrt(2 * n); i++){
if(arr[i] == 0) continue;
for(int j = 2 * i; j <= 2 * n; j += i){
arr[j] = 0;
}
}
for(int i = n + 1; i <= 2 * n; i++){
if(arr[i] != 0) cnt++;
}
bw.write(cnt + "\n");
}
}
|
package com.xiaoxiao.provider;
import com.xiaoxiao.pojo.XiaoxiaoHobby;
import org.apache.ibatis.jdbc.SQL;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/4:13:08
* @author:shinelon
* @Describe:
*/
public class HobbyProvider
{
public String insert(final XiaoxiaoHobby hobby){
return new SQL(){
{
INSERT_INTO("xiaoxiao_hobby");
if(hobby.getHobbyId() != null && hobby.getHobbyId() !="")
VALUES("hobby_id","#{hobby.hobbyId}");
if(hobby.getBobbyName()!=null && hobby.getBobbyName() != "")
VALUES("bobby_name", "#{hobby.bobbyName}");
}
}.toString();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package oopProjectFinal;
/**
*
* @author Anna
*/
public class toRegisterGUI extends javax.swing.JFrame {
/**
* Creates new form toRegisterGUI
*/
public toRegisterGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
titleLbl = new javax.swing.JLabel();
registerBtn = new javax.swing.JButton();
backBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLbl.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
titleLbl.setText("Please register to pay for the order");
registerBtn.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
registerBtn.setText("Register");
registerBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerBtnActionPerformed(evt);
}
});
backBtn.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
backBtn.setText(" Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(titleLbl))
.addGroup(layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(registerBtn)
.addGap(56, 56, 56)
.addComponent(backBtn)))
.addContainerGap(57, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLbl)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(registerBtn)
.addComponent(backBtn))
.addContainerGap(42, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void registerBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerBtnActionPerformed
// TODO add your handling code here:
RegisterGUI newReg = new RegisterGUI();
newReg.setVisible(true);
}//GEN-LAST:event_registerBtnActionPerformed
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
// TODO add your handling code here:
OrderGUI order = new OrderGUI();
order.setVisible(true);
}//GEN-LAST:event_backBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(toRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(toRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(toRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(toRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new toRegisterGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backBtn;
private javax.swing.JButton registerBtn;
private javax.swing.JLabel titleLbl;
// End of variables declaration//GEN-END:variables
}
|
package com.solvd.farm.animal;
public class Animal {
private String voice;
private int size;
public Animal() {
voice = "default";
size = 1;
}
public Animal(String voice1, int size1) {
voice = voice1;
size = size1;
}
public void printFields() {
System.out.println("Voice: " + voice);
System.out.println("Size: " + size);
}
}
|
package com.tt.miniapp.route;
import android.support.v4.app.Fragment;
import android.support.v4.app.r;
import java.util.LinkedList;
import java.util.Queue;
public abstract class BaseRouteFragment extends Fragment implements RouteTransaction {
private Queue<Integer> transactionList = new LinkedList<Integer>();
public void doWithOutCommitByAnimationEnd(r paramr) {
if (paramr == null) {
this.transactionList.clear();
return;
}
while (this.transactionList.peek() != null) {
Integer integer = this.transactionList.poll();
if (integer != null) {
if (integer.intValue() == 1) {
paramr.c(this);
continue;
}
if (integer.intValue() == 2) {
paramr.b(this);
continue;
}
paramr.a(this);
}
}
}
public void executeHideWithOutCommit(r paramr) {
if (this.transactionList.isEmpty()) {
paramr.b(this);
return;
}
this.transactionList.offer(Integer.valueOf(2));
}
public void executeRemoveWithOutCommit(r paramr) {
if (this.transactionList.isEmpty()) {
paramr.a(this);
return;
}
this.transactionList.offer(Integer.valueOf(3));
}
public void executeShowWithOutCommit(r paramr) {
if (this.transactionList.isEmpty()) {
paramr.c(this);
return;
}
this.transactionList.offer(Integer.valueOf(1));
}
public void offerHideToQueue() {
this.transactionList.offer(Integer.valueOf(2));
}
public void offerRemoveToQueue() {
this.transactionList.offer(Integer.valueOf(3));
}
public void offerShowToQueue() {
this.transactionList.offer(Integer.valueOf(1));
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\route\BaseRouteFragment.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.commercetools.pspadapter.payone.transaction;
import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder;
import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike;
import com.commercetools.pspadapter.payone.domain.ctp.TypeCacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import io.sphere.sdk.carts.Cart;
import io.sphere.sdk.client.BlockingSphereClient;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.queries.PagedQueryResult;
import io.sphere.sdk.types.Type;
import io.sphere.sdk.types.queries.TypeQuery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import util.PaymentTestHelper;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static util.JvmSdkMockUtil.pagedQueryResultsMock;
/**
* @author fhaertig
* @since 18.01.16
*/
@RunWith(MockitoJUnitRunner.class)
public class IdempotentTransactionExecutorTest {
private static final Cart UNUSED_CART = null;
private static final PaymentTestHelper testHelper = new PaymentTestHelper();
private TestIdempotentTransactionExecutor testee;
@Mock
private BlockingSphereClient client;
@Before
public void setUp() {
when(client.executeBlocking(any(TypeQuery.class))).then(a -> {
PagedQueryResult<Type> customTypes = testHelper.getCustomTypes();
String queryString = Arrays.asList(a.getArguments()).get(0).toString();
if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_RESPONSE)) {
return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_RESPONSE, customTypes));
} else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION)) {
return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION, customTypes));
} else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_REDIRECT)) {
return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_REDIRECT, customTypes));
} else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST)) {
return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST, customTypes));
}
return PagedQueryResult.empty();
});
testee = new TestIdempotentTransactionExecutor(Caffeine.newBuilder().build(new TypeCacheLoader(client)));
}
@Test
public void nextSequenceNumber0() throws Exception {
Payment payment = testHelper.dummyPaymentCreatedByNotification();
payment.getTransactions().clear();
payment.getInterfaceInteractions().clear();
PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(payment, UNUSED_CART);
int sequenceNumber = testee.getNextSequenceNumber(paymentWithCartLike);
assertThat(sequenceNumber).isEqualTo(0);
}
@Test
public void nextSequenceNumber1() throws Exception {
Payment payment = testHelper.dummyPaymentCreatedByNotification();
payment.getTransactions().clear();
PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(payment, UNUSED_CART);
int sequenceNumber = testee.getNextSequenceNumber(paymentWithCartLike);
assertThat(sequenceNumber).isEqualTo(1);
}
@Test
public void nextSequenceNumber3() throws Exception {
Payment payment = testHelper.dummyPaymentTwoTransactionsSuccessPending();
PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(payment, UNUSED_CART);
int sequenceNumber = testee.getNextSequenceNumber(paymentWithCartLike);
assertThat(sequenceNumber).isEqualTo(3);
}
private class TestIdempotentTransactionExecutor extends IdempotentTransactionExecutor {
public TestIdempotentTransactionExecutor(final LoadingCache<String, Type> typeCache) {
super(typeCache);
}
@Override
protected int getNextSequenceNumber(final PaymentWithCartLike paymentWithCartLike) {
return super.getNextSequenceNumber(paymentWithCartLike);
}
@Override
public TransactionType supportedTransactionType() {
return null;
}
@Override
protected boolean wasExecuted(final PaymentWithCartLike paymentWithCartLike, final Transaction transaction) {
return false;
}
@Override
protected PaymentWithCartLike executeIdempotent(final PaymentWithCartLike paymentWithCartLike, final Transaction transaction) {
return null;
}
}
private Type findCustomTypeByKey(String key, PagedQueryResult<Type> customTypes) {
return customTypes
.getResults()
.stream()
.filter(p -> p.getKey().equals(key))
.findFirst()
.get();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package co.th.aten.network.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Atenpunk
*/
@Entity
@Table(name = "transaction_score_package_weekly")
@NamedQueries({
@NamedQuery(name = "TransactionScorePackageWeekly.findAll", query = "SELECT t FROM TransactionScorePackageWeekly t"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByRoundId", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.transactionScorePackageWeeklyPK.roundId = :roundId"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByCustomerId", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.transactionScorePackageWeeklyPK.customerId = :customerId"),
@NamedQuery(name = "TransactionScorePackageWeekly.findBySuggestId", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.transactionScorePackageWeeklyPK.suggestId = :suggestId"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByTrxStartDate", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.transactionScorePackageWeeklyPK.trxStartDate = :trxStartDate"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByTrxEndDate", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.transactionScorePackageWeeklyPK.trxEndDate = :trxEndDate"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByProductId", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.productId = :productId"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByPvPackage", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.pvPackage = :pvPackage"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByTrxPackageStatus", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.trxPackageStatus = :trxPackageStatus"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByTrxPackageFlag", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.trxPackageFlag = :trxPackageFlag"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByCreateBy", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.createBy = :createBy"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByCreateDate", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.createDate = :createDate"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByUpdateBy", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.updateBy = :updateBy"),
@NamedQuery(name = "TransactionScorePackageWeekly.findByUpdateDate", query = "SELECT t FROM TransactionScorePackageWeekly t WHERE t.updateDate = :updateDate")})
public class TransactionScorePackageWeekly implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected TransactionScorePackageWeeklyPK transactionScorePackageWeeklyPK;
@Column(name = "product_id")
private Integer productId;
@Column(name = "pv_package")
private BigDecimal pvPackage;
@Column(name = "trx_package_status")
private Integer trxPackageStatus;
@Column(name = "trx_package_flag")
private Integer trxPackageFlag;
@Column(name = "create_by")
private Integer createBy;
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "update_by")
private Integer updateBy;
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
public TransactionScorePackageWeekly() {
}
public TransactionScorePackageWeekly(TransactionScorePackageWeeklyPK transactionScorePackageWeeklyPK) {
this.transactionScorePackageWeeklyPK = transactionScorePackageWeeklyPK;
}
public TransactionScorePackageWeekly(int roundId, int customerId, int suggestId, Date trxStartDate, Date trxEndDate) {
this.transactionScorePackageWeeklyPK = new TransactionScorePackageWeeklyPK(roundId, customerId, suggestId, trxStartDate, trxEndDate);
}
public TransactionScorePackageWeeklyPK getTransactionScorePackageWeeklyPK() {
return transactionScorePackageWeeklyPK;
}
public void setTransactionScorePackageWeeklyPK(TransactionScorePackageWeeklyPK transactionScorePackageWeeklyPK) {
this.transactionScorePackageWeeklyPK = transactionScorePackageWeeklyPK;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public BigDecimal getPvPackage() {
return pvPackage;
}
public void setPvPackage(BigDecimal pvPackage) {
this.pvPackage = pvPackage;
}
public Integer getTrxPackageStatus() {
return trxPackageStatus;
}
public void setTrxPackageStatus(Integer trxPackageStatus) {
this.trxPackageStatus = trxPackageStatus;
}
public Integer getTrxPackageFlag() {
return trxPackageFlag;
}
public void setTrxPackageFlag(Integer trxPackageFlag) {
this.trxPackageFlag = trxPackageFlag;
}
public Integer getCreateBy() {
return createBy;
}
public void setCreateBy(Integer createBy) {
this.createBy = createBy;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Integer getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Integer updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
@Override
public int hashCode() {
int hash = 0;
hash += (transactionScorePackageWeeklyPK != null ? transactionScorePackageWeeklyPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TransactionScorePackageWeekly)) {
return false;
}
TransactionScorePackageWeekly other = (TransactionScorePackageWeekly) object;
if ((this.transactionScorePackageWeeklyPK == null && other.transactionScorePackageWeeklyPK != null) || (this.transactionScorePackageWeeklyPK != null && !this.transactionScorePackageWeeklyPK.equals(other.transactionScorePackageWeeklyPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.th.aten.network.entity.TransactionScorePackageWeekly[transactionScorePackageWeeklyPK=" + transactionScorePackageWeeklyPK + "]";
}
}
|
package thread;
import java.util.concurrent.ThreadLocalRandom;
public class Subscriber extends Thread{
private MessageQueue mq = null;
public Subscriber(MessageQueue mq){
this.mq = mq;
}
public void run(){
for (int i = 0; i < 20; i++){
String output = Util.getDate() +" Subscriber - ";
String m = mq.getMessage();
if (m == ""){
output += "tried to read but no message ...";
i-=1;
}else{
output += "reading \""+m+"\"";
}
Util.print(output);
try {
long v = ThreadLocalRandom.current().nextLong(0,1000);
//System.out.println("this is the random number"+ v);
Thread.sleep(v);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.marvik.apps.firstaid.customlist;
/**
* Created by victor on 9/1/2015.
*/
public class AttacksCustomList {
int attackId;
String attack, symptom;
public AttacksCustomList(int attackId, String attack, String symptom) {
this.attackId = attackId;
this.attack = attack;
this.symptom = symptom;
}
public int getAttackId() {
return attackId;
}
public String getAttack() {
return attack;
}
public String getSymptom() {
return symptom;
}
}
|
package es.uma.sportjump.sjs.dao.test.impl.jpa;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import es.uma.sportjump.sjs.dao.test.CalendarEventDaoTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-jpa-application-dao.xml")
public class CalendarEventDaoJpaTest extends CalendarEventDaoTest{
@Test
public void testCalendarEventCRUD(){
super.testCalendarEventCRUD();
}
@Test
public void testGetAllEventByTeam(){
super.testGetAllEventByTeam();
}
}
|
package com.common.utils;
import com.common.oss.AliyunService;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
public class Utils {
private static final char EXTENSION_SEPARATOR = '.';
private static final String FOLDER_SEPARATOR = "/";
public static boolean isAjax(HttpServletRequest request){
String header = request.getHeader("X-Requested-With");
return header != null && "XMLHttpRequest".equals(header);
}
public static String getIpAddr(HttpServletRequest request) {
String ipFromNginx = getHeader(request, "X-Real-IP");
if (!StringUtils.isEmpty(ipFromNginx)) {
return ipFromNginx;
}
return request.getRemoteAddr();
}
private static String getHeader(HttpServletRequest request, String headName) {
String value = request.getHeader(headName);
return !StringUtils.isEmpty(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
}
public static String MD5(String content) {
// MessageDigest md5 = MessageDigest.getInstance("MD5");
// sun.misc.BASE64Encoder baseEncoder = new sun.misc.BASE64Encoder();
// String retString = baseEncoder.encode(md5.digest(content.getBytes()));
return getMD5_32(content);
}
public static String getMD5_32(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException caught!");
System.exit(-1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString();
}
public final static boolean isNumeric(String s) {
if (s != null && !"".equals(s.trim()))
return s.matches("^[0-9]*$");
else
return false;
}
public static boolean uploadFileToOss(InputStream is, String filePath){
AliyunService aliyunService = SpringContextUtils.getBean(AliyunService.class);
try {
aliyunService.updateFile(is, filePath, getFileExt(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean deleteFileToOss(InputStream is, String filePath){
AliyunService aliyunService = SpringContextUtils.getBean(AliyunService.class);
try {
// aliyunService.deleteFile();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 不带电文件后缀名
* 招股金服
* CopyRight : www.zhgtrade.com
* Author : 俞杰(945351749@qq.com)
* Date : 2016年4月8日 上午11:55:18
*/
public static String getFileExt(String fileName) {
if (fileName.lastIndexOf(".") == -1)
return "";
int pos = fileName.lastIndexOf(".") + 1;
return fileName.substring(pos, fileName.length());
}
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
}
int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
if (extIndex == -1) {
return null;
}
int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (folderIndex > extIndex) {
return null;
}
return path.substring(extIndex + 1);
}
public static String getRelativeFilePath(String fileExt, byte[] bytes){
return getRelativeFilePath(fileExt, bytes, null);
}
public static String getRelativeFilePath(String fileExt, byte[] bytes, Object extFileName){
StringBuilder filePath = new StringBuilder();
filePath.append("/").append(DateUtils.formatDate(new Date(), "yyyyMM")).append("/");
if(bytes.length > 40){
byte[] copyArr = new byte[10];
System.arraycopy(bytes, 30, copyArr, 0, 10);
String hexStr = bytesToHexString(copyArr);
filePath.append(hexStr).append(randomString(5));
}else{
filePath.append(getRandomImageName());
}
if(null != extFileName){
// 标识参数
filePath.append("_").append(extFileName);
}
filePath.append(".").append(fileExt);
return filePath.toString();
}
private static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static Timestamp getTimestamp() {
return new Timestamp(new Date().getTime());
}
public static Long getTimeLong(){
return new Date().getTime();
}
// 获得随机字符串
public static String randomString(int count) {
String str = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
int size = str.length();
StringBuffer sb = new StringBuffer();
Random random = new Random();
while (count > 0) {
sb.append(String.valueOf(str.charAt(random.nextInt(size))));
count--;
}
return sb.toString();
}
public static String getRandomImageName() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyyMMddHHmmsss");
String path = simpleDateFormat.format(new Date());
path += "_" + randomString(5);
return path;
}
// 获得今天0点
public static long getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
public static boolean isImage(byte[] bytes){
if(0 == bytes.length){
return false;
}
byte[] copyArr = new byte[28];
System.arraycopy(bytes, 0, copyArr, 0, 28);
String hexStr = bytesToHexString(copyArr).toUpperCase();
// jpeg|png|gif
return hexStr.startsWith("FFD8FF") || hexStr.startsWith("89504E47") || hexStr.startsWith("47494638");
}
}
|
package com.tweetapp.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import com.tweetapp.entities.UserModel;
@Repository
public interface UserRepository extends MongoRepository<UserModel, String>{
UserModel findByUsername(String username);
@Query("{'username':{'$regex':'?0','$options':'i'}}")
List<UserModel> searchByUsername(String username);
}
|
package io.dmcapps.dshopping.stock;
import javax.enterprise.context.ApplicationScoped;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
@ApplicationScoped
@Transactional(REQUIRED)
public class StockEntryService {
@Transactional(SUPPORTS)
public List<StockEntry> findAllStockEntries() {
return StockEntry.listAll();
}
@Transactional(SUPPORTS)
public StockEntry findStockEntryById(Long id) {
return StockEntry.findById(id);
}
@Transactional(SUPPORTS)
public List<StockEntry> findStockEntryByStoreProduct(String storeId, Long productId) {
return StockEntry.find("storeId = ?1 and productId = ?2", storeId, productId).list();
}
public StockEntry persistStockEntry(@Valid StockEntry stockEntry) {
StockEntry.persist(stockEntry);
return stockEntry;
}
public StockEntry updateStockEntry(@Valid StockEntry stockEntry) {
StockEntry entity = StockEntry.findById(stockEntry.id);
entity.amount = stockEntry.amount;
return entity;
}
public void deleteStockEntry(Long id) {
StockEntry stockEntry = StockEntry.findById(id);
stockEntry.delete();
}
}
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.mm.platformtools.af;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.protocal.c.ate;
import com.tencent.mm.protocal.c.bsu;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
public final class av implements f {
private static HashMap<String, b> nrT = new HashMap();
private static HashMap<String, WeakReference<b>> nrU = new HashMap();
public static void Mu(String str) {
if (af.exM) {
x.d("MicroMsg.TimelineSmallPicStat", "recordStartLoadSmallPic, mediaId:%s", new Object[]{str});
}
WeakReference weakReference = (WeakReference) nrU.get(str);
if (weakReference != null) {
b bVar = (b) weakReference.get();
if (bVar != null) {
bVar.kdC = true;
}
}
}
public static void Mv(String str) {
if (af.exM) {
x.d("MicroMsg.TimelineSmallPicStat", "recordEndLoadSmallPic, mediaId:%s", new Object[]{str});
}
WeakReference weakReference = (WeakReference) nrU.get(str);
if (weakReference != null) {
b bVar = (b) weakReference.get();
if (bVar != null && bVar != null && bVar.nrV == -1) {
HashMap hashMap = bVar.nrZ;
if (hashMap != null && hashMap.containsKey(str)) {
a aVar = (a) hashMap.get(str);
if (aVar != null && aVar.nrV == -1) {
aVar.nrV = 1;
bVar.nrY++;
}
}
}
}
}
public static void Mw(String str) {
x.d("MicroMsg.TimelineSmallPicStat", "recordClickBigpic, localId:%s", new Object[]{str});
if (nrT.containsKey(str)) {
x.d("MicroMsg.TimelineSmallPicStat", "recordClickBigPic, localId:%s, update map", new Object[]{str});
b bVar = (b) nrT.get(str);
if (bVar != null && bVar.nrV == -1 && bVar.startTime != -1) {
bVar.nrV = 1;
bVar.nrY = bVar.dzO;
bVar.endTime = System.currentTimeMillis();
bVar.nrX = bVar.endTime - bVar.startTime;
for (a aVar : bVar.nrZ.values()) {
aVar.nrV = 1;
}
}
}
}
public final void a(String str, bsu bsu) {
if (!nrT.containsKey(str)) {
if (af.exM) {
x.d("MicroMsg.TimelineSmallPicStat", "put localId:%s into reportData", new Object[]{str});
}
if (bsu != null && bsu.sqc != null && bsu.sqc.ruz == 1 && bsu.sqc.ruA != null && bsu.sqc.ruA.size() > 0) {
b bVar = new b(this);
bVar.dzO = bsu.sqc.ruA.size();
bVar.nrY = 0;
bVar.nrZ = new HashMap();
Iterator it = bsu.sqc.ruA.iterator();
while (it.hasNext()) {
ate ate = (ate) it.next();
a aVar = new a(this);
aVar.mediaId = ate.ksA;
bVar.nrZ.put(ate.ksA, aVar);
nrU.put(ate.ksA, new WeakReference(bVar));
}
bVar.startTime = System.currentTimeMillis();
nrT.put(str, bVar);
} else if (af.exM) {
x.d("MicroMsg.TimelineSmallPicStat", "onItemAdd error, timelineObject is nulli");
}
}
}
public final void LX(String str) {
if (nrT.containsKey(str)) {
if (af.exM) {
x.d("MicroMsg.TimelineSmallPicStat", "load finish localId:%s", new Object[]{str});
}
b bVar = (b) nrT.get(str);
if (bVar != null && bVar.startTime != -1 && bVar.nrV == -1) {
bVar.endTime = System.currentTimeMillis();
bVar.nrX = bVar.endTime - bVar.startTime;
if (bVar.nrY == bVar.dzO) {
bVar.nrV = 1;
} else {
bVar.nrV = 2;
}
}
}
}
public final void bxB() {
x.d("MicroMsg.TimelineSmallPicStat", "reportAll, reportData.size:%d", new Object[]{Integer.valueOf(nrT.size())});
int bxa = i.bxa();
for (String str : nrT.keySet()) {
b bVar = (b) nrT.get(str);
if (bVar != null && bVar.kdC) {
if (bVar.nrX == -1 || bVar.nrV == -1 || bVar.startTime == -1) {
if (bVar.startTime != -1) {
bVar.endTime = System.currentTimeMillis();
bVar.nrX = bVar.endTime - bVar.startTime;
if (bVar.dzO == bVar.nrY) {
bVar.nrV = 1;
} else {
bVar.nrV = 2;
}
}
}
x.d("MicroMsg.TimelineSmallPicStat", "reportAll, picNum:%d, loadResult:%d, loadCostTime:%d, loadPicNum:%d, networkType:%d", new Object[]{Integer.valueOf(bVar.dzO), Long.valueOf(bVar.nrV), Long.valueOf(bVar.nrX), Integer.valueOf(bVar.nrY), Integer.valueOf(bxa)});
h.mEJ.h(11600, new Object[]{Integer.valueOf(bVar.dzO), Long.valueOf(bVar.nrV), Long.valueOf(bVar.nrX), Integer.valueOf(bVar.nrY), Integer.valueOf(bxa)});
}
}
nrT.clear();
nrU.clear();
}
}
|
package org.feup.ses.pbst.tests;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.feup.ses.pbst.Enums.PatternEnum;
import org.feup.ses.pbst.Enums.TestResultEnum;
import org.feup.ses.pbst.TestConfAndResult;
import org.feup.ses.pbst.patternTests.FormValuesHolder;
import org.feup.ses.pbst.patternTests.WebPage;
import java.net.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ClientDataStorageImpl extends Test {
private final String COOKIE_HEADER_RESPONSE = "Set-Cookie";
private final String COOKIE_HEADER_REQUEST = "Cookie";
public ClientDataStorageImpl() { super(); }
public void test(WebPage webPage, TestConfAndResult testConfAndResult, FormValuesHolder formValuesHolder,
PatternEnum informationDisclosureCds) {
super.setWebPage(webPage);
super.setPbstTest(testConfAndResult);
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
try {
CookieHandler.setDefault(manager);
URLConnection connection = webPage.getUrl().openConnection();
connection.getContent();
} catch (Exception ex) {
}
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies = cookieJar.getCookies();
for (HttpCookie cookie : cookies) {
if (getShannonEntropy(cookie.getValue()) < 3.6){
webPage.addTestResult(informationDisclosureCds, TestResultEnum.VULNERABLE,
"Client Data Storage", cookie.getName() + " might be vulnerable or have a weak crypto algorithm");
} else {
webPage.addTestResult(informationDisclosureCds, TestResultEnum.SECURE,
"Client Data Storage", cookie.getName() + " is probably secured or have a strong crypto algorithm");
}
}
}
private double getShannonEntropy(String s) {
int n = 0;
Map<Character, Integer> occ = new HashMap<>();
for (int c_ = 0; c_ < s.length(); ++c_) {
char cx = s.charAt(c_);
if (occ.containsKey(cx)) {
occ.put(cx, occ.get(cx) + 1);
} else {
occ.put(cx, 1);
}
++n;
}
double e = 0.0;
for (Map.Entry<Character, Integer> entry : occ.entrySet()) {
char cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * log2(p);
}
return -e;
}
private double log2(double a) {
return Math.log(a) / Math.log(2);
}
private boolean hasCookie(HttpResponse response){
return Arrays.stream(response.getAllHeaders())
.map(Header::getName)
.anyMatch((header) -> header.equals(COOKIE_HEADER_RESPONSE));
}
private String getCookies(HttpResponse response){
return Arrays.stream(response.getAllHeaders())
.filter(header -> header.getName().equals(COOKIE_HEADER_RESPONSE))
.map(header -> header.getValue().split(";")[0])
.collect(Collectors.joining("; "));
}
}
|
package br.com.utfpr.eventos.models;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
public class Event {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String description;
@DateTimeFormat(pattern="dd/MM/yyyy")
private String date;
private BigDecimal price;
private int max;
private String adress;
private String imagem;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getImagem() {
return imagem;
}
public void setImagem(String imagem) {
this.imagem = imagem;
}
public String getDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = format.parse(this.date);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
return dateFormat.format(date);
} catch (ParseException e) {
return this.date;
}
}
public void setDate(String date) {
this.date = date;
}
}
|
package com.tencent.tmassistantsdk.downloadclient;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceCallback;
import com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceCallback$Stub;
import com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceInterface;
import com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceInterface.Stub;
import com.tencent.tmassistantsdk.util.TMLog;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
public class TMAssistantDownloadSDKClient extends TMAssistantDownloadSDKClientBase {
protected static final String DOWNDLOADSDKSERVICENAME = "com.tencent.tmassistantsdk.downloadservice.TMAssistantDownloadSDKService";
protected static final String TAG = "TMAssistantDownloadSDKClient";
protected ReferenceQueue<ITMAssistantDownloadSDKClientListener> mListenerReferenceQueue;
protected ArrayList<WeakReference<ITMAssistantDownloadSDKClientListener>> mWeakListenerArrayList;
public TMAssistantDownloadSDKClient(Context context, String str) {
super(context, str, DOWNDLOADSDKSERVICENAME);
this.mListenerReferenceQueue = new ReferenceQueue();
this.mWeakListenerArrayList = new ArrayList();
this.mServiceCallback = new ITMAssistantDownloadSDKServiceCallback$Stub() {
public void OnDownloadSDKServiceTaskStateChanged(String str, String str2, int i, int i2, String str3, boolean z, boolean z2) {
TMLog.i(TMAssistantDownloadSDKClient.TAG, "OnDownloadStateChanged,clientKey:" + str + ",state:" + i + ", errorcode" + i2 + ",url:" + str2);
Iterator it = TMAssistantDownloadSDKClient.this.mWeakListenerArrayList.iterator();
while (it.hasNext()) {
WeakReference weakReference = (WeakReference) it.next();
ITMAssistantDownloadSDKClientListener iTMAssistantDownloadSDKClientListener = (ITMAssistantDownloadSDKClientListener) weakReference.get();
if (iTMAssistantDownloadSDKClientListener == null) {
TMLog.i(TMAssistantDownloadSDKClient.TAG, " listener = " + iTMAssistantDownloadSDKClientListener + " linstenerWeakReference :" + weakReference);
}
TMAssistantDownloadSDKMessageThread.getInstance().postTaskStateChangedMessage(TMAssistantDownloadSDKClient.this, iTMAssistantDownloadSDKClientListener, str2, i, i2, str3, z, z2);
}
}
public void OnDownloadSDKServiceTaskProgressChanged(String str, String str2, long j, long j2) {
TMLog.i(TMAssistantDownloadSDKClient.TAG, "OnDownloadProgressChanged,clientKey:" + str + ",receivedLen:" + j + ",totalLen:" + j2 + ",url:" + str2);
Iterator it = TMAssistantDownloadSDKClient.this.mWeakListenerArrayList.iterator();
while (it.hasNext()) {
WeakReference weakReference = (WeakReference) it.next();
ITMAssistantDownloadSDKClientListener iTMAssistantDownloadSDKClientListener = (ITMAssistantDownloadSDKClientListener) weakReference.get();
if (iTMAssistantDownloadSDKClientListener == null) {
TMLog.i(TMAssistantDownloadSDKClient.TAG, " listener = " + iTMAssistantDownloadSDKClientListener + " linstenerWeakReference :" + weakReference);
}
TMAssistantDownloadSDKMessageThread.getInstance().postTaskProgressChangedMessage(TMAssistantDownloadSDKClient.this, iTMAssistantDownloadSDKClientListener, str2, j, j2);
}
}
};
}
public synchronized TMAssistantDownloadTaskInfo getDownloadTaskState(String str) {
TMAssistantDownloadTaskInfo downloadTaskInfo;
TMLog.i(TAG, "getDownloadTaskState,clientKey:" + this.mClientKey + ",url:" + str);
if (str == null) {
throw new IllegalArgumentException("TMAssistantDownloadSDKClient.getDownloadTaskState url is null");
}
ITMAssistantDownloadSDKServiceInterface iTMAssistantDownloadSDKServiceInterface = (ITMAssistantDownloadSDKServiceInterface) super.getServiceInterface();
if (iTMAssistantDownloadSDKServiceInterface != null) {
downloadTaskInfo = iTMAssistantDownloadSDKServiceInterface.getDownloadTaskInfo(this.mClientKey, str);
} else {
super.initTMAssistantDownloadSDK();
downloadTaskInfo = null;
}
return downloadTaskInfo;
}
public synchronized int startDownloadTask(String str, String str2) {
return startDownloadTask(str, "", 0, 0, str2, null, true, null);
}
public synchronized int startDownloadTask(String str, String str2, Map<String, String> map) {
return startDownloadTask(str, "", 0, 0, str2, null, true, map);
}
public synchronized int startDownloadTask(String str, String str2, String str3) {
return startDownloadTask(str, "", 0, 0, str2, str3, true, null);
}
public synchronized int startDownloadTask(String str, String str2, long j, int i, String str3, String str4, boolean z, Map<String, String> map) {
int startDownloadTask;
TMLog.i(TAG, "startDownloadTask,clientKey:" + this.mClientKey + ",url:" + str + ",contentType:" + str3);
if (str == null) {
throw new IllegalArgumentException("TMAssistantDownloadSDKClient.startDownloadTask url is null");
}
if (str3.equals("resource/tm.android.unknown") && TextUtils.isEmpty(str4)) {
throw new IllegalArgumentException("if contentType is others, filename shouldn't be null!");
}
ITMAssistantDownloadSDKServiceInterface iTMAssistantDownloadSDKServiceInterface = (ITMAssistantDownloadSDKServiceInterface) super.getServiceInterface();
if (iTMAssistantDownloadSDKServiceInterface != null) {
iTMAssistantDownloadSDKServiceInterface.setServiceSetingIsDownloadWifiOnly(z);
startDownloadTask = iTMAssistantDownloadSDKServiceInterface.startDownloadTask(this.mClientKey, str, str2, j, 0, str3, str4, map);
} else {
TMLog.i(TAG, "startDownloadTask, serviceInterface is null");
super.initTMAssistantDownloadSDK();
startDownloadTask = 0;
}
return startDownloadTask;
}
public synchronized void pauseDownloadTask(String str) {
TMLog.i(TAG, "pauseDownloadTask,clientKey:" + this.mClientKey + ",url:" + str);
if (str == null) {
throw new IllegalArgumentException("TMAssistantDownloadSDKClient.startDownloadTask url is null");
}
ITMAssistantDownloadSDKServiceInterface iTMAssistantDownloadSDKServiceInterface = (ITMAssistantDownloadSDKServiceInterface) super.getServiceInterface();
if (iTMAssistantDownloadSDKServiceInterface != null) {
iTMAssistantDownloadSDKServiceInterface.pauseDownloadTask(this.mClientKey, str);
} else {
TMLog.i(TAG, "pauseDownloadTask, serviceInterface is null");
super.initTMAssistantDownloadSDK();
}
}
public synchronized void cancelDownloadTask(String str) {
TMLog.i(TAG, "cancelDownloadTask,clientKey:" + this.mClientKey + ",url:" + str);
if (str == null) {
throw new IllegalArgumentException("TMAssistantDownloadSDKClient.startDownloadTask url is null");
}
ITMAssistantDownloadSDKServiceInterface iTMAssistantDownloadSDKServiceInterface = (ITMAssistantDownloadSDKServiceInterface) super.getServiceInterface();
if (iTMAssistantDownloadSDKServiceInterface != null) {
iTMAssistantDownloadSDKServiceInterface.cancelDownloadTask(this.mClientKey, str);
} else {
TMLog.i(TAG, "cancelDownloadTask, serviceInterface is null");
super.initTMAssistantDownloadSDK();
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public synchronized boolean registerDownloadTaskListener(com.tencent.tmassistantsdk.downloadclient.ITMAssistantDownloadSDKClientListener r5) {
/*
r4 = this;
r1 = 1;
monitor-enter(r4);
if (r5 != 0) goto L_0x0007;
L_0x0004:
r0 = 0;
L_0x0005:
monitor-exit(r4);
return r0;
L_0x0007:
r0 = r4.mListenerReferenceQueue; Catch:{ all -> 0x001e }
r0 = r0.poll(); Catch:{ all -> 0x001e }
if (r0 == 0) goto L_0x0021;
L_0x000f:
r2 = "TMAssistantDownloadSDKClient";
r3 = "registerDownloadTaskListener removed listener!!!!";
com.tencent.tmassistantsdk.util.TMLog.i(r2, r3); Catch:{ all -> 0x001e }
r2 = r4.mWeakListenerArrayList; Catch:{ all -> 0x001e }
r2.remove(r0); Catch:{ all -> 0x001e }
goto L_0x0007;
L_0x001e:
r0 = move-exception;
monitor-exit(r4);
throw r0;
L_0x0021:
r0 = r4.mWeakListenerArrayList; Catch:{ all -> 0x001e }
r2 = r0.iterator(); Catch:{ all -> 0x001e }
L_0x0027:
r0 = r2.hasNext(); Catch:{ all -> 0x001e }
if (r0 == 0) goto L_0x003d;
L_0x002d:
r0 = r2.next(); Catch:{ all -> 0x001e }
r0 = (java.lang.ref.WeakReference) r0; Catch:{ all -> 0x001e }
r0 = r0.get(); Catch:{ all -> 0x001e }
r0 = (com.tencent.tmassistantsdk.downloadclient.ITMAssistantDownloadSDKClientListener) r0; Catch:{ all -> 0x001e }
if (r0 != r5) goto L_0x0027;
L_0x003b:
r0 = r1;
goto L_0x0005;
L_0x003d:
r0 = new java.lang.ref.WeakReference; Catch:{ all -> 0x001e }
r2 = r4.mListenerReferenceQueue; Catch:{ all -> 0x001e }
r0.<init>(r5, r2); Catch:{ all -> 0x001e }
r2 = r4.mWeakListenerArrayList; Catch:{ all -> 0x001e }
r2.add(r0); Catch:{ all -> 0x001e }
r0 = r1;
goto L_0x0005;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.tmassistantsdk.downloadclient.TMAssistantDownloadSDKClient.registerDownloadTaskListener(com.tencent.tmassistantsdk.downloadclient.ITMAssistantDownloadSDKClientListener):boolean");
}
public synchronized boolean unRegisterDownloadTaskListener(ITMAssistantDownloadSDKClientListener iTMAssistantDownloadSDKClientListener) {
boolean z;
if (iTMAssistantDownloadSDKClientListener == null) {
z = false;
} else {
Iterator it = this.mWeakListenerArrayList.iterator();
while (it.hasNext()) {
WeakReference weakReference = (WeakReference) it.next();
if (((ITMAssistantDownloadSDKClientListener) weakReference.get()) == iTMAssistantDownloadSDKClientListener) {
this.mWeakListenerArrayList.remove(weakReference);
z = true;
break;
}
}
z = false;
}
return z;
}
protected void onDownloadSDKServiceInvalid() {
Iterator it = this.mWeakListenerArrayList.iterator();
while (it.hasNext()) {
TMAssistantDownloadSDKMessageThread.getInstance().postSDKServiceInvalidMessage(this, (ITMAssistantDownloadSDKClientListener) ((WeakReference) it.next()).get());
}
}
protected void stubAsInterface(IBinder iBinder) {
this.mServiceInterface = Stub.asInterface(iBinder);
}
protected void registerServiceCallback() {
((ITMAssistantDownloadSDKServiceInterface) this.mServiceInterface).registerDownloadTaskCallback(this.mClientKey, (ITMAssistantDownloadSDKServiceCallback) this.mServiceCallback);
}
protected Intent getBindServiceIntent() {
return new Intent(this.mContext, Class.forName(this.mDwonloadServiceName));
}
protected void unRegisterServiceCallback() {
((ITMAssistantDownloadSDKServiceInterface) this.mServiceInterface).unregisterDownloadTaskCallback(this.mClientKey, (ITMAssistantDownloadSDKServiceCallback) this.mServiceCallback);
}
public static String about() {
return "TMAssistantDownloadSDKClient_2014_03_06_11_20_release_25634";
}
}
|
package P1;
public class Account {
long accNum;
double balance;
Person acctHolder;
public Account(long accNum, double balance, Person acctHolder) {
super();
this.accNum = accNum;
this.balance = balance;
this.acctHolder = acctHolder;
}
public Account() {
super();
// TODO Auto-generated constructor stub
}
public long getAccNum() {
return accNum;
}
public void setAccNum(long accNum) {
this.accNum = accNum;
}
public Person getAcctHolder() {
return acctHolder;
}
public void setAcctHolder(Person acctHolder) {
this.acctHolder = acctHolder;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void deposit(int amount)
{
balance = balance + amount;
System.out.println(" "+balance);
}
public void withdraw(int amount)
{
balance = balance - amount;
System.out.println(" "+balance);
}
public double getBalance()
{
System.out.println("Available balance :");
return balance;
}
}
class SavingsAccount extends Account
{
long minBalance = 500;
@Override
public void withdraw(int amount) {
if(balance-amount > 500) {
System.out.println("Available balance :"+(balance-amount));
}
else
System.out.println("Not enough minimum balance ");
}
}
class CurrentAccount extends Account
{
long overdraftLimit = 1000;
Boolean b= false;
@Override
public void withdraw(int amount) {
if(amount> overdraftLimit)
{
b=false;
System.out.println(b);
}
else
{
b=true;
System.out.println(b);
}
}
}
|
package edu.iss.caps.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.persistence.Convert;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import edu.iss.caps.exception.FailedAuthentication;
import edu.iss.caps.model.Course;
import edu.iss.caps.model.Enrolment;
import edu.iss.caps.model.LecturerDetail;
import edu.iss.caps.model.StudentDetail;
import edu.iss.caps.model.User;
import edu.iss.caps.repository.CourseRepository;
import edu.iss.caps.service.CourseService;
import edu.iss.caps.service.EnrolmentService;
import edu.iss.caps.service.LecturerService;
import edu.iss.caps.service.StudentService;
@Controller
@RequestMapping("/Lec")
public class Lecturercontroller {
@Autowired
private EnrolmentService ens;
@Autowired
private CourseService cs;
@Autowired
private StudentService sds;
// 1.view all course to select enrole details
@RequestMapping(value = "/viewallenrole", method = RequestMethod.GET)
public ModelAndView viewallcourseenrole() {
ModelAndView mav = new ModelAndView("enroleview");
List<Course> course = cs.findAllCourses();
mav.addObject("Enlist", course);
return mav;
}
// 1.[search] search courseid & course name(viewalleenrole)
@RequestMapping(value = "/2searchbyname", method = RequestMethod.GET)
public ModelAndView searchStudent2(Locale locale, Model model, @RequestParam Map<String, String> requestParams,
HttpServletRequest request) {
String searchContent = requestParams.get("searchcontent").toLowerCase();
ModelAndView mav = new ModelAndView("enroleview");
ArrayList<Course> lctList = cs.findAllCourses();
List<Course> searchList = new ArrayList<Course>();
int bn = 0;
String s2 = "";
for (Course l : lctList) {
bn = (l.getCourseId());
s2 = Integer.toString(bn);
if (l.getCourseName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (s2.toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
mav.addObject("datacount", searchList.size());
return mav;
}
// 1.1 view my course only.
@RequestMapping(value = "/mycourseenrole", method = RequestMethod.GET)
public ModelAndView mycourseenrole(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("enroleview");
try {
User u = (User) request.getSession().getAttribute("user");
String s = u.getUserId();
List<Course> course = cs.findbylecid(s);
mav.addObject("Enlist", course);
} catch (Exception e) {
}
return mav;
}
// 1.2 view all student enroled / with search
@RequestMapping(value = "/enrole/{id}", method = RequestMethod.GET)
public ModelAndView findonlyen(@PathVariable int id, HttpServletRequest request,
@RequestParam Map<String, String> requestParams) {
ModelAndView mav = new ModelAndView("enrolelist");
ArrayList<Enrolment> lctList = ens.findbycid(id);
List<Enrolment> searchList = new ArrayList<Enrolment>();
if (requestParams.get("searchcontent") != null && !requestParams.get("searchcontent").isEmpty()) {
String searchContent = requestParams.get("searchcontent").toLowerCase();
for (Enrolment l : lctList) {
if (l.getStudentDetails().getFirstName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getLastName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getStudentId().toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
mav.addObject("datacount", searchList.size());
return mav;
}
mav.addObject("Enlist", lctList);
return mav;
}
// 2.1 grade course - show course to select
@RequestMapping(value = "/viewalltograde", method = RequestMethod.GET)
public ModelAndView viewalltograde(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("courseforgrading");
try {
User u = (User) request.getSession().getAttribute("user");
String s = u.getUserId();
List<Course> course = cs.findbylecid(s);
List<Course> courseTemp = new ArrayList<Course>();
// List<Enrolment> enrolmentList = new ArrayList<Enrolment>();
for (Course c : course) {
if (ens.findungraded(s, c.getCourseId()).size() != 0) {
courseTemp.add(c);
}
}
mav.addObject("Enlist", courseTemp);
} catch (Exception e) {
}
return mav;
}
// search in 2.1 [for course name and id]
@RequestMapping(value = "/1searchbyname", method = RequestMethod.GET)
public ModelAndView searchStudentforgrd(Locale locale, Model model, @RequestParam Map<String, String> requestParams,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView("courseforgrading");
try {
String searchContent = requestParams.get("searchcontent").toLowerCase();
User u = (User) request.getSession().getAttribute("user");
String s = u.getUserId();
// ArrayList<Course> lctList = cs.findbylecid(s);
List<Course> searchList = new ArrayList<Course>();
List<Course> course = cs.findbylecid(s);
List<Course> courseTemp = new ArrayList<Course>();
for (Course c : course) {
if (ens.findungraded(s, c.getCourseId()).size() != 0) {
courseTemp.add(c);
}
}
int bn = 0;
String s2 = "";
for (Course l : courseTemp) {
bn = (l.getCourseId());
s2 = Integer.toString(bn);
if (l.getCourseName().toLowerCase().contains(searchContent)) {
searchList.add(l);
}
else if (s2.toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
mav.addObject("datacount", searchList.size());
} catch (Exception e) {
}
return mav;
}
// 2.2 grade a student
@RequestMapping(value = "/grade/{id}", method = RequestMethod.GET)
public ModelAndView searchgradeastudent(@PathVariable int id, HttpServletRequest request,
@RequestParam Map<String, String> requestParams) {
ModelAndView mav = new ModelAndView("gradinglist");
String searchContent = null;
String s = null;
try {
User u = (User) request.getSession().getAttribute("user");
s = u.getUserId();
searchContent = requestParams.get("searchcontent").toLowerCase();
} catch (Exception e) {
}
List<Enrolment> lctList = ens.findungraded(s, id);
List<Enrolment> searchList = new ArrayList<Enrolment>();
if (requestParams.get("searchcontent") != null && !requestParams.get("searchcontent").isEmpty()) {
for (Enrolment l : lctList) {
if (l.getStudentDetails().getFirstName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getLastName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getStudentId().toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
mav.addObject("datacount", searchList.size());
return mav;
}
mav.addObject("Enlist", lctList);
return mav;
}
// 3.2 view all student performance / search for all students.
@RequestMapping(value = "/viewsp/{id}", method = RequestMethod.GET)
public ModelAndView viewstudentbycid(@PathVariable int id, HttpServletRequest request,
@RequestParam Map<String, String> requestParams) {
ModelAndView mav = new ModelAndView("studentperformance");
List<Enrolment> lctList = ens.findcompletedbyid(id);
List<Enrolment> searchList = new ArrayList<Enrolment>();
if (requestParams.get("searchcontent") != null && !requestParams.get("searchcontent").isEmpty()) {
String searchContent = requestParams.get("searchcontent").toLowerCase();
for (Enrolment l : lctList) {
if (l.getStudentDetails().getFirstName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getLastName().toLowerCase().contains(searchContent)) {
searchList.add(l);
} else if (l.getStudentDetails().getStudentId().toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
mav.addObject("datacount", searchList.size());
ArrayList<String> gpa = new ArrayList<String>();
System.out.println(lctList.size());
for (Enrolment en : lctList) {
float f = sds.calcStudentGPA(en.getStudentDetails().getStudentId());
String ss = String.format("%.2f%n", f);
gpa.add(ss);
}
mav.addObject("Stgpa", gpa);
return mav;
}
mav.addObject("Enlist", lctList);
ArrayList<String> gpa = new ArrayList<String>();
for (Enrolment en : lctList) {
float f = sds.calcStudentGPA(en.getStudentDetails().getStudentId());
String ss = String.format("%.2f%n", f);
gpa.add(ss);
}
mav.addObject("Stgpa", gpa);
return mav;
}
// 3.1 to view performance
@RequestMapping(value = "/viewallcr", method = RequestMethod.GET)
public ModelAndView viewallcourse() {
ModelAndView mav = new ModelAndView("courseavi");
List<Course> course = cs.findAllCourses();
mav.addObject("Enlist", course);
ArrayList<Integer> ar = new ArrayList<Integer>();
for (Course num : course) {
ar.add(ens.countungraded(num.getCourseId()));
}
mav.addObject("cou", ar);
return mav;
}
// search courseid & course name(viewallcr) [3]
@RequestMapping(value = "/searchviewallcr", method = RequestMethod.GET)
public ModelAndView searchviewallcr(Locale locale, Model model, @RequestParam Map<String, String> requestParams,
HttpServletRequest request) {
String searchContent = null;
List<Course> searchList = null;
ModelAndView mav = null;
try {
searchContent = requestParams.get("searchcontent").toLowerCase();
mav = new ModelAndView("courseavi");
ArrayList<Course> lctList = cs.findAllCourses();
searchList = new ArrayList<Course>();
int bn = 0;
String s2 = "";
for (Course l : lctList) {
bn = (l.getCourseId());
s2 = Integer.toString(bn);
if (l.getCourseName().toLowerCase().contains(searchContent)) {
searchList.add(l);
}
else if (s2.toLowerCase().contains(searchContent)) {
searchList.add(l);
}
}
mav.addObject("Enlist", searchList);
ArrayList<Integer> ar = new ArrayList<Integer>();
for (Course num : searchList) {
ar.add(ens.countungraded(num.getCourseId()));
}
mav.addObject("cou", ar);
mav.addObject("datacount", searchList.size());
} catch (Exception e) {
}
return mav;
}
// 3.1 view my course for viewing performance
@RequestMapping(value = "/mycourse", method = RequestMethod.GET)
public ModelAndView mycourse(HttpServletRequest request) {
ModelAndView mav =null;
try {
User u = (User) request.getSession().getAttribute("user");
String s = u.getUserId();
mav = new ModelAndView("courseavi");
List<Course> course = cs.findbylecid(s);
mav.addObject("Enlist", course);
ArrayList<Integer> ar = new ArrayList<Integer>();
for (Course num : course) {
ar.add(ens.countungraded(num.getCourseId()));
}
mav.addObject("cou", ar);
} catch (Exception e) {
}
return mav;
}
// update the grade.. (2.2)
@RequestMapping(value = "/grade/update", method = RequestMethod.POST)
public String update(HttpServletRequest request) {
int cid =0;
try {
User u = (User) request.getSession().getAttribute("user");
String s = u.getUserId();
String g = request.getParameter("glist");
String id = request.getParameter("sd");
cid = Integer.parseInt(request.getParameter("couid"));
int cred = cs.calcredit(g, cid);
String newstatus = cs.makestatus(g);
int enroleid = Integer.parseInt(request.getParameter("enid"));
Enrolment en = ens.findbyEnrolmentId(enroleid);
en.setGrade(g);
en.setEarnedCredit(cred);
en.setStatus(newstatus);
ens.updateEnrolment(en);
List<Course> course = cs.findbylecid(s);
// mav.addObject("Enlist", course);
} catch (Exception e) {
}
return "redirect:" + cid + "?actionstatus=0";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.