text
stringlengths 10
2.72M
|
|---|
package com.research.hadoop.sort.groupsort;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
/**
* @fileName: OrderGroupingComparator.java
* @description: 主要用于分组的
* @author: by echo huang
* @date: 2020-07-24 23:26
*/
public class OrderGroupingComparator extends WritableComparator {
public OrderGroupingComparator() {
// 设置为true 会去创建key对象
super(OrderDetail.class,true);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
OrderDetail aOrder = (OrderDetail) a;
OrderDetail bOrder = (OrderDetail) b;
return Integer.compare(aOrder.getId(), bOrder.getId());
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.04.17 at 08:40:10 PM ICT
//
package object.visualparadigm;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://www.visual-paradigm.com/product/vpuml/modelexporter}diagramElement">
* <sequence>
* <element name="RoleA" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/>
* <element name="RoleB" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/>
* <element name="Points">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded">
* <element name="Point" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="from" use="required" type="{http://www.visual-paradigm.com/product/vpuml/modelexporter}modelId" />
* <attribute name="to" use="required" type="{http://www.visual-paradigm.com/product/vpuml/modelexporter}modelId" />
* <attribute name="connectorStyle" type="{http://www.visual-paradigm.com/product/vpuml/modelexporter}connectorStyle" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"roleA",
"roleB",
"points"
})
@XmlRootElement(name = "Connector")
public class Connector
extends DiagramElement
{
@XmlElement(name = "RoleA")
protected Object roleA;
@XmlElement(name = "RoleB")
protected Object roleB;
@XmlElement(name = "Points", required = true)
protected Connector.Points points;
@XmlAttribute(name = "from", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String from;
@XmlAttribute(name = "to", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String to;
@XmlAttribute(name = "connectorStyle")
protected ConnectorStyle connectorStyle;
/**
* Gets the value of the roleA property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getRoleA() {
return roleA;
}
/**
* Sets the value of the roleA property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setRoleA(Object value) {
this.roleA = value;
}
/**
* Gets the value of the roleB property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getRoleB() {
return roleB;
}
/**
* Sets the value of the roleB property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setRoleB(Object value) {
this.roleB = value;
}
/**
* Gets the value of the points property.
*
* @return
* possible object is
* {@link Connector.Points }
*
*/
public Connector.Points getPoints() {
return points;
}
/**
* Sets the value of the points property.
*
* @param value
* allowed object is
* {@link Connector.Points }
*
*/
public void setPoints(Connector.Points value) {
this.points = value;
}
/**
* Gets the value of the from property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFrom() {
return from;
}
/**
* Sets the value of the from property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFrom(String value) {
this.from = value;
}
/**
* Gets the value of the to property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTo() {
return to;
}
/**
* Sets the value of the to property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTo(String value) {
this.to = value;
}
/**
* Gets the value of the connectorStyle property.
*
* @return
* possible object is
* {@link ConnectorStyle }
*
*/
public ConnectorStyle getConnectorStyle() {
return connectorStyle;
}
/**
* Sets the value of the connectorStyle property.
*
* @param value
* allowed object is
* {@link ConnectorStyle }
*
*/
public void setConnectorStyle(ConnectorStyle value) {
this.connectorStyle = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded">
* <element name="Point" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"point"
})
public static class Points {
@XmlElement(name = "Point")
protected List<Connector.Points.Point> point;
/**
* Gets the value of the point property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the point property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPoint().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Connector.Points.Point }
*
*
*/
public List<Connector.Points.Point> getPoint() {
if (point == null) {
point = new ArrayList<Connector.Points.Point>();
}
return this.point;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Point {
@XmlAttribute(name = "x", required = true)
protected BigInteger x;
@XmlAttribute(name = "y", required = true)
protected BigInteger y;
/**
* Gets the value of the x property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getX() {
return x;
}
/**
* Sets the value of the x property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setX(BigInteger value) {
this.x = value;
}
/**
* Gets the value of the y property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getY() {
return y;
}
/**
* Sets the value of the y property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setY(BigInteger value) {
this.y = value;
}
}
}
}
|
package tenet.node.l2switch;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.PriorityQueue;
import tenet.core.Simulator;
import tenet.node.INode;
import tenet.protocol.datalink.FrameParamStruct;
import tenet.protocol.datalink.IDataLinkLayer;
import tenet.protocol.datalink.MediumAddress;
import tenet.protocol.datalink.SEther.SimpleEthernetDatalink;
import tenet.protocol.interrupt.InterruptObject;
import tenet.protocol.interrupt.InterruptParam;
import tenet.util.pattern.serviceclient.IClient;
public class L2Switch extends InterruptObject implements INode {
public class MACWithTimestamp implements Comparable<MACWithTimestamp> {
public Double m_time;
public MediumAddress m_mac;
public MACWithTimestamp(Double m_time, MediumAddress m_mac) {
super();
this.m_time = m_time;
this.m_mac = m_mac;
}
@Override
public int compareTo(MACWithTimestamp arg0) {
return m_time.compareTo(arg0.m_time);
}
}
protected final static int TIMER = 0x00000001;
/**
* 存储二层交换机上的所有SimpleEthernetDatalink的信息
*/
public HashMap<MediumAddress, SimpleEthernetDatalink> m_datalinks;
/**
* 存储转发目的地所对应的出口,即MAC表
*/
public HashMap<MediumAddress, SimpleEthernetDatalink> m_macport_map;
public PriorityQueue<MACWithTimestamp> m_timeout;
protected boolean m_state = false;
public L2Switch() {
super();
wait(TIMER, 1.0); // 通过超时等待,每秒触发一次计时器
m_datalinks = new HashMap<MediumAddress, SimpleEthernetDatalink>();
m_macport_map = new HashMap<MediumAddress, SimpleEthernetDatalink>();
m_timeout = new PriorityQueue<MACWithTimestamp>();
}
@Override
public void disable() {
if (!m_state)
return;
for (IDataLinkLayer iface : m_datalinks.values())
iface.disable();
m_state = false;
}
@Override
public void dump() {
}
@Override
public void enable() {
if (m_state)
return;
for (IDataLinkLayer iface : m_datalinks.values())
iface.enable();
m_state = true;
}
/**
* 获得mac地址所对应的二层交换机上的SimpleEthernetDatalink
*/
public SimpleEthernetDatalink getDatalink(MediumAddress mac) {
return m_datalinks.get(mac);
}
/**
* 获得二层交换机上的所有SimpleEthernetDatalink
*/
public Collection<SimpleEthernetDatalink> getDatalinks() {
return m_datalinks.values();
}
/**
* 从mac表中获得mac地址所对应的端口上的SimpleEthernetDatalink
*/
public SimpleEthernetDatalink getTransmitDatalink(MediumAddress mac) {
return m_macport_map.get(mac);
}
@Override
protected void interruptHandle(int signal, InterruptParam param) {
switch (signal) {
case TIMER:
// TODO 重新开始计时器读时
this.resetInterrupt(TIMER);
wait(TIMER, 1.0);
// TODO 检查是否有需要清除的mac记录
//I am lazy...
}
}
@Override
public boolean isEnable() {
return m_state;
}
public void learnMAC(MediumAddress mac, SimpleEthernetDatalink iface) {
// TODO 更新MAC表,将MAC地址与所对应的SimpleEthernetDatalink放入表中
if (m_macport_map.containsKey(mac) && m_macport_map.get(mac)!=iface ) m_macport_map.remove(mac);
m_macport_map.put(mac, iface);
}
@Override
public void registryClient(IClient client) {
// TODO 将一个IDatalinkLayer安置到二层交换机上
if (client instanceof SimpleEthernetDatalink){
m_datalinks.put((MediumAddress)client.getUniqueID(), (SimpleEthernetDatalink)client);
client.attachTo(this);
}
}
@Override
public void unregistryClient(IClient<Object> client) {
if (m_datalinks.containsKey((MediumAddress)client.getUniqueID())){
m_datalinks.remove((MediumAddress)client.getUniqueID());
client.detachFrom(this);
}
}
@Override
public void unregistryClient(Object id) {
if (id instanceof MediumAddress){
IClient<MediumAddress> client = this.m_datalinks.get(id);
m_datalinks.remove(id);
client.detachFrom(this);
}
}
@Override
public void setAddress(IClient<?> protocol, byte[] address){
}
@Override
public byte[] getAddress(IClient<?> protocol){
return null;
}
private LinkedList<byte[]> recent = new LinkedList<byte[]>();
public HashMap<MediumAddress, SimpleEthernetDatalink> getlinks(byte[] data) {
boolean flag = false;
for (int i=0;i<recent.size();i++){
boolean miao = true;
byte[] odata = recent.get(i);
if (data.length!=odata.length) continue;
for (int p=0;p<odata.length;p++){
if (data[p]!=odata[p]){
miao = false;
break;
}
}
if (miao){
flag = true;
break;
}
}
recent.add(data);
while (recent.size()>10) recent.remove();
if (flag) return new HashMap<MediumAddress, SimpleEthernetDatalink>();
return m_datalinks;
}
}
|
package kr.ds.fragment;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import kr.ds.ObservableScrollView.ObservableListView;
import kr.ds.custom.BookMarkDB;
import kr.ds.custom.ProgressFragment;
import kr.ds.mylotto.R;
public class Fragment_8 extends ProgressFragment{
private Context mContext;
private View mView;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mView = inflater.inflate(R.layout.content8, null);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
}
|
public class PointComparator {
public static double compareToX(Point2D point, Point2D otherPoint){
return point.getX() - otherPoint.getX();
}
public static double compareToY(Point2D point, Point2D otherPoint){
return point.getY() - otherPoint.getY();
}
public static boolean isContainedX(Point2D point, Point2D first, Point2D second){
return compareToX(point, first) * compareToX(point, second) >= 0;
}
public static boolean isContainedY(Point2D point, Point2D first, Point2D second){
return compareToY(point, first) * compareToY(point, second) >= 0;
}
public static double distance(Point2D point, Point2D otherPoint){
return Math.sqrt(Math.pow((point.getX() - otherPoint.getX()), 2) + Math.pow((point.getY() - otherPoint.getY()), 2));
}
}
|
package com.szxs.dto;
import java.util.Date;
public class VoItemLike {
private Integer id;
private String itemName;
private Date startTime;
private Date endTime;
private Integer areaId;
private String areaName;
private double minPrice;
private String imgUrl;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getAreaId() {
return areaId;
}
public void setAreaId(Integer areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public double getMinPrice() {
return minPrice;
}
public void setMinPrice(double minPrice) {
this.minPrice = minPrice;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
/*
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6521334 6712743 8007902 8151901
* @requires (sun.arch.data.model == "64" & os.maxMemory >= 4g)
* @summary test general packer/unpacker functionality
* using native and java unpackers
* @modules jdk.management
* jdk.zipfs
* @compile -XDignore.symbol.file Utils.java Pack200Test.java
* @run main/othervm/timeout=1200 -Xmx1280m -Xshare:off Pack200Test
*/
import java.util.*;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.jar.*;
/**
* Tests the packing/unpacking via the APIs.
*/
public class Pack200Test {
private static ArrayList <File> jarList = new ArrayList<File>();
static final MemoryMXBean mmxbean = ManagementFactory.getMemoryMXBean();
static final long m0 = getUsedMemory();
static final int LEAK_TOLERANCE = 21000; // OS and GC related variations.
// enable leak checks only if required, GC charecteristics vary on
// platforms and this may not yield consistent results
static final boolean LEAK_CHECK = Boolean.getBoolean("Pack200Test.enableLeakCheck");
/** Creates a new instance of Pack200Test */
private Pack200Test() {}
static long getUsedMemory() {
mmxbean.gc();
mmxbean.gc();
mmxbean.gc();
return mmxbean.getHeapMemoryUsage().getUsed()/1024;
}
private static void leakCheck() throws Exception {
if (!LEAK_CHECK)
return;
long diff = getUsedMemory() - m0;
System.out.println(" Info: memory diff = " + diff + "K");
if (diff > LEAK_TOLERANCE) {
throw new Exception("memory leak detected " + diff);
}
}
private static void doPackUnpack() throws IOException {
for (File in : jarList) {
JarOutputStream javaUnpackerStream = null;
JarOutputStream nativeUnpackerStream = null;
JarFile jarFile = null;
try {
jarFile = new JarFile(in);
// Write out to a jtreg scratch area
File packFile = new File(in.getName() + Utils.PACK_FILE_EXT);
System.out.println("Packing [" + in.toString() + "]");
// Call the packer
Utils.pack(jarFile, packFile);
System.out.println("Done Packing [" + in.toString() + "]");
jarFile.close();
System.out.println("Start leak check");
leakCheck();
System.out.println(" Unpacking using java unpacker");
File javaUnpackedJar = new File("java-" + in.getName());
// Write out to current directory, jtreg will setup a scratch area
javaUnpackerStream = new JarOutputStream(
new FileOutputStream(javaUnpackedJar));
Utils.unpackj(packFile, javaUnpackerStream);
javaUnpackerStream.close();
System.out.println(" Testing...java unpacker");
leakCheck();
// Ok we have unpacked the file, lets test it.
Utils.doCompareVerify(in.getAbsoluteFile(), javaUnpackedJar);
System.out.println(" Unpacking using native unpacker");
// Write out to current directory
File nativeUnpackedJar = new File("native-" + in.getName());
nativeUnpackerStream = new JarOutputStream(
new FileOutputStream(nativeUnpackedJar));
Utils.unpackn(packFile, nativeUnpackerStream);
nativeUnpackerStream.close();
System.out.println(" Testing...native unpacker");
leakCheck();
// the unpackers (native and java) should produce identical bits
// so we use use bit wise compare, the verification compare is
// very expensive wrt. time.
Utils.doCompareBitWise(javaUnpackedJar, nativeUnpackedJar);
System.out.println("Done.");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Utils.close(nativeUnpackerStream);
Utils.close(javaUnpackerStream);
Utils.close((Closeable) jarFile);
}
}
Utils.cleanup(); // cleanup artifacts, if successful run
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// select the jars carefully, adding more jars will increase the
// testing time.
jarList.add(Utils.createRtJar());
jarList.add(Utils.getGoldenJar());
System.out.println(jarList);
doPackUnpack();
}
}
|
/**
* url : https://www.acmicpc.net/problem/2309
*
* [문제]
* 왕비를 피해 일곱 난쟁이들과 함께 평화롭게 생활하고 있던 백설공주에게 위기가 찾아왔다. 일과를 마치고 돌아온 난쟁이가 일곱 명이 아닌 아홉 명이었던 것이다.
*
* 아홉 명의 난쟁이는 모두 자신이 "백설 공주와 일곱 난쟁이"의 주인공이라고 주장했다. 뛰어난 수학적 직관력을 가지고 있던 백설공주는, 다행스럽게도 일곱 난쟁이의 키의 합이 100이 됨을 기억해 냈다.
*
* 아홉 난쟁이의 키가 주어졌을 때, 백설공주를 도와 일곱 난쟁이를 찾는 프로그램을 작성하시오.
*
* [입력]
* 아홉 개의 줄에 걸쳐 난쟁이들의 키가 주어진다. 주어지는 키는 100을 넘지 않는 자연수이며, 아홉 난쟁이의 키는 모두 다르며, 가능한 정답이 여러 가지인 경우에는 아무거나 출력한다.
*
* [출력]
* 일곱 난쟁이의 키를 오름차순으로 출력한다. 일곱 난쟁이를 찾을 수 없는 경우는 없다.
*/
package brute_force;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Seven_dwarf_v2 {
static final int DWARFS_HEIGHT = 100;
static final int MAX_DWARFS = 9;
static final int DWARFS = 7;
static int[] dwarfs;
static int sum = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
dwarfs = new int[MAX_DWARFS];
for (int i = 0; i < MAX_DWARFS; i++) {
final int height = Integer.parseInt(br.readLine());
dwarfs[i] = height;
sum += height;
}
findSeven(0, 1);
Arrays.sort(dwarfs);
showDwarfs(dwarfs.length - DWARFS, MAX_DWARFS);
}
public static void findSeven(int pivot, int cnt) {
if( DWARFS_HEIGHT == sum - (dwarfs[pivot] + dwarfs[cnt]) ) {
dwarfs[pivot] = -1;
dwarfs[cnt] = -1;
return;
}
if( cnt == dwarfs.length - 1 )
{
pivot ++;
cnt = pivot + 1;
} else { cnt ++; }
findSeven(pivot, cnt);
}
public static void showDwarfs(final int overLen, final int dwarfLen) {
for (int i = overLen; i < dwarfLen; i++) {
System.out.println(dwarfs[i]);
}
}
}
|
//@@author A0141021H
package seedu.whatnow.model.task;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import seedu.whatnow.commons.exceptions.IllegalValueException;
public class DateTest {
@Test
public void isValidDate_noDate_returnTrue() throws ParseException{
try {
TaskDate.formatDateToStandardDate("");
} catch (IllegalValueException e) {
assertEquals(e.getMessage(), TaskDate.INVALID_TASK_DATE_NO_DATE);
}
}
@Test
public void isValidDate_invalidTaskDateLength_returnTrue() throws ParseException{
try {
TaskDate.formatDateToStandardDate("236");
} catch (IllegalValueException e) {
assertEquals(e.getMessage(), TaskDate.INVALID_TASK_DATE);
}
}
@Test
public void isValidDate_validMon_returnTrue() {
assertTrue(TaskDate.isDay("mon"));
}
@Test
public void isValidDate_validTue_returnTrue() {
assertTrue(TaskDate.isDay("tue"));
}
@Test
public void isValidDate_validWed_returnTrue() {
assertTrue(TaskDate.isDay("wed"));
}
@Test
public void isValidDate_validThur_returnTrue() {
assertTrue(TaskDate.isDay("thur"));
}
@Test
public void isValidDate_validFri_returnTrue() {
assertTrue(TaskDate.isDay("fri"));
}
@Test
public void isValidDate_validSat_returnTrue() {
assertTrue(TaskDate.isDay("sat"));
}
@Test
public void isValidDate_validSun_returnTrue() {
assertTrue(TaskDate.isDay("sun"));
}
@Test
public void isValidDate_validMonDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("mon") != null);
assertTrue(TaskDate.formatDayToDate("monday") != null);
}
@Test
public void isValidDate_validTueDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("tue") != null);
assertTrue(TaskDate.formatDayToDate("tuesday") != null);
}
@Test
public void isValidDate_validWedDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("wed") != null);
assertTrue(TaskDate.formatDayToDate("wednesday") != null);
}
@Test
public void isValidDate_validThurDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("thur") != null);
assertTrue(TaskDate.formatDayToDate("thursday") != null);
}
@Test
public void isValidDate_validFriDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("fri") != null);
assertTrue(TaskDate.formatDayToDate("friday") != null);
}
@Test
public void isValidDate_validSatDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("sat") != null);
assertTrue(TaskDate.formatDayToDate("saturday") != null);
}
@Test
public void isValidDate_validSunDayToDate_returnTrue() throws ParseException {
assertTrue(TaskDate.formatDayToDate("sun") != null);
assertTrue(TaskDate.formatDayToDate("sunday") != null);
}
@Test
public void isValidDate_invalidDateYearLength_returnTrue() throws ParseException, IllegalValueException{
assertTrue(TaskDate.formatDateToStandardDate("03/04/16") != null);
}
@Test
public void isValidDate_month_returnTrue(){
assertTrue(TaskDate.isValidMonth("jAn"));
assertTrue(TaskDate.isValidMonth("january"));
assertTrue(TaskDate.isValidMonth("fEb"));
assertTrue(TaskDate.isValidMonth("febrUARY"));
assertTrue(TaskDate.isValidMonth("mAr"));
assertTrue(TaskDate.isValidMonth("MaRcH"));
assertTrue(TaskDate.isValidMonth("aPr"));
assertTrue(TaskDate.isValidMonth("april"));
assertTrue(TaskDate.isValidMonth("may"));
assertTrue(TaskDate.isValidMonth("MAY"));
assertTrue(TaskDate.isValidMonth("juN"));
assertTrue(TaskDate.isValidMonth("jUNe"));
assertTrue(TaskDate.isValidMonth("Jul"));
assertTrue(TaskDate.isValidMonth("juLY"));
assertTrue(TaskDate.isValidMonth("AuG"));
assertTrue(TaskDate.isValidMonth("aUgUst"));
assertTrue(TaskDate.isValidMonth("seP"));
assertTrue(TaskDate.isValidMonth("SepTEMber"));
assertTrue(TaskDate.isValidMonth("oCt"));
assertTrue(TaskDate.isValidMonth("OCToBER"));
assertTrue(TaskDate.isValidMonth("NOV"));
assertTrue(TaskDate.isValidMonth("noVEMber"));
assertTrue(TaskDate.isValidMonth("dEc"));
assertTrue(TaskDate.isValidMonth("deCEMbeR"));
}
@Test
public void isValidDate_month_returnFalse(){
assertFalse(TaskDate.isValidMonth("month"));
assertFalse(TaskDate.isValidMonth("junuary"));
assertFalse(TaskDate.isValidMonth("freb"));
assertFalse(TaskDate.isValidMonth("muy"));
assertFalse(TaskDate.isValidMonth("apirl"));
assertFalse(TaskDate.isValidMonth("junne"));
assertFalse(TaskDate.isValidMonth("jully"));
assertFalse(TaskDate.isValidMonth("augustus"));
assertFalse(TaskDate.isValidMonth("septimber"));
assertFalse(TaskDate.isValidMonth("octi"));
assertFalse(TaskDate.isValidMonth("novmember"));
assertFalse(TaskDate.isValidMonth("decamber"));
}
@Test
public void isValidDate_today_returnTrue() throws ParseException, IllegalValueException{
assertTrue(TaskDate.getIsValidDate("today"));
assertTrue(TaskDate.getIsValidDate("tdy"));
assertTrue(TaskDate.getIsValidDate("TDY"));
}
@Test
public void isValidDate_today_returnFalse() throws ParseException, IllegalValueException{
assertFalse(TaskDate.getIsValidDate("2day"));
}
@Test
public void isValidDate_tmr_returnTrue() throws ParseException, IllegalValueException{
assertTrue(TaskDate.getIsValidDate("tomorrow"));
assertTrue(TaskDate.getIsValidDate("tmr"));
assertTrue(TaskDate.getIsValidDate("TMR"));
}
@Test
public void isValidDate_tmr_returnFalse() throws ParseException, IllegalValueException{
assertFalse(TaskDate.getIsValidDate("tmmr"));
}
@Test
public void isValidDate_taskDate_returnTrue() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate("23/09/2017", null, null);
assertTrue(taskdate.getDate() != null);
}
@Test
public void isValidDate_taskDate_returnFalse() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate("23/09/2017", null, null);
assertFalse(taskdate.getDate() == null);
}
@Test
public void isValidDate_taskStartDate_returnTrue() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertTrue(taskdate.getStartDate() != null);
}
@Test
public void isValidDate_taskStartDate_returnFalse() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertFalse(taskdate.getStartDate() == null);
}
@Test
public void isValidDate_taskEndDate_returnTrue() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertTrue(taskdate.getEndDate() != null);
}
@Test
public void isValidDate_taskEndDate_returnFalse() throws IllegalValueException, ParseException{
TaskDate taskdate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertFalse(taskdate.getEndDate() == null);
}
@Test
public void isValidDate_variousDateFormat_returnTrue() throws ParseException, IllegalValueException{
assertTrue(TaskDate.getIsValidDate("03/12/2019"));
assertTrue(TaskDate.getIsValidDate("5/11/2017"));
assertTrue(TaskDate.getIsValidDate("7/8/2018"));
assertTrue(TaskDate.getIsValidDate("8/5/2017"));
assertTrue(TaskDate.getIsValidDate("30/12/2018"));
assertTrue(TaskDate.getIsValidDate(TaskDate.formatDateToStandardDate("01.12.2020")));
assertTrue(TaskDate.getIsValidDate(TaskDate.formatDateToStandardDate("13/06/2019")));
assertTrue(TaskDate.getIsValidDate(TaskDate.formatDateToStandardDate("7-10-2023")));
assertTrue(TaskDate.getIsValidDate(TaskDate.formatDateToStandardDate("19 12 2019")));
assertTrue(TaskDate.getIsValidDate(TaskDate.formatDateToStandardDate("05072018")));
}
@Test
public void isValidDate_wrongDate_returnFalse() throws ParseException, IllegalValueException {
assertFalse(TaskDate.getIsValidDate("34/12/2018"));
assertFalse(TaskDate.getIsValidDate("11/18/2016"));
assertFalse(TaskDate.getIsValidDate("44/20/2018"));
}
@Test
public void isValidDate_PastDateFormat_returnTrue() throws ParseException {
try {
new TaskDate("14/10/2015", null, null);
} catch (IllegalValueException e){
assertEquals(e.getMessage(), TaskDate.EXPIRED_TASK_DATE);
}
}
@Test
public void isValidDate_checkDateValidity_returnFalse() throws ParseException, IllegalValueException{
assertFalse(TaskDate.getIsValidDate("32/09/2018"));
assertFalse(TaskDate.getIsValidDate("31/02/2020"));
assertFalse(TaskDate.getIsValidDate("10/16/2020"));
}
@Test
public void isValidDate_dateRange_returnTrue() throws ParseException {
assertTrue(TaskDate.getIsValidDateRange(null, null));
assertTrue(TaskDate.getIsValidDateRange("12/12/2017", "23/11/2018"));
assertTrue(TaskDate.getIsValidDateRange("12/12/2016", "12/12/2016"));
}
@Test
public void isValidDate_invalidDateRange_returnFalse() throws ParseException {
assertFalse(TaskDate.getIsValidDateRange("12/12/2016", "23/11/2015"));
assertFalse(TaskDate.getIsValidDateRange("12/11/2019", "23/09/2017"));
}
@Test
public void isValidDate_beforeAfter_returnTrue() throws ParseException {
assertTrue(TaskDate.getIsValidDateRange("mon", "wed"));
assertTrue(TaskDate.getIsValidDateRange("wed", "mon"));
}
@Test
public void isValidDate_tmrDate_returnTrue() throws ParseException {
String tmrDate;
DateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
tmrDate = dateFormat.format(cal.getTime());
assertEquals(tmrDate, TaskDate.assignTmrDate());
}
@Test
public void isValidDate_startDateTdy_returnTrue() throws ParseException, IllegalValueException {
String todayDate;
DateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = dateFormat.format(cal.getTime());
TaskDate taskDate = new TaskDate(null, "tdy", "12/12/2020");
assertEquals(taskDate.assignTodayDate(), todayDate);
}
@Test
public void isValidDate_endDateTdy_returnTrue() throws ParseException, IllegalValueException {
try{
TaskDate taskDate = new TaskDate(null, "12/12/2020", "tdy");
} catch (IllegalValueException e) {
assertEquals(e.getMessage(), TaskDate.INVALID_TASK_DATE_RANGE_FORMAT);
}
}
@Test
public void isValidDate_taskDateTdy_returnTrue() throws ParseException, IllegalValueException {
String todayDate;
DateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = dateFormat.format(cal.getTime());
TaskDate taskDate = new TaskDate("tdy", null, null);
assertEquals(taskDate.assignTodayDate(), todayDate);
}
@Test
public void isValidDate_taskDateTmr_returnTrue() throws ParseException, IllegalValueException {
String tmrDate;
DateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
tmrDate = dateFormat.format(cal.getTime());
TaskDate taskDate = new TaskDate("tmr", null, null);
assertEquals(taskDate.assignTmrDate(), tmrDate);
}
//@@author A0139772U
@Test
public void getFullDateOneDate_validDate_fullDateReturned() throws IllegalValueException, ParseException {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
String today = df.format(cal.getTime());
TaskDate taskDate = new TaskDate(today, null, null);
assertEquals(taskDate.toString(), today);
}
@Test
public void getFullDateTwoDate_validDate_fullDateReturned() throws IllegalValueException, ParseException {
TaskDate taskDate = new TaskDate(null, "12/04/2018", "15/06/2019");
taskDate.setFullDate(null);
assertEquals(taskDate.toString(), "12/04/2018 15/06/2019");
}
@Test
public void getStartDate_validDate_fullDateReturned() throws IllegalValueException, ParseException {
TaskDate taskDate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertEquals(taskDate.getStartDate(), "12/04/2018");
}
@Test
public void getEndDate_validDate_fullDateReturned() throws IllegalValueException, ParseException {
TaskDate taskDate = new TaskDate(null, "12/04/2018", "15/06/2019");
assertEquals(taskDate.getEndDate(), "15/06/2019");
}
@Test
public void isValidDate_validDate_dateIsValid() throws IllegalValueException, ParseException {
assertTrue(TaskDate.getIsValidDate("12/12/2222"));
}
@Test
public void isEqual_twoValidEqualDates_datesAreEqual() throws IllegalValueException, ParseException {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
String today = df.format(cal.getTime());
TaskDate taskDate1 = new TaskDate(today, null, null);
TaskDate taskDate2 = new TaskDate(today, null, null);
assertEquals(taskDate1, taskDate2);
}
@Test
public void formatDayToDate_today_dateofDayReturned() {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
String today = df.format(cal.getTime());
assertEquals(TaskDate.formatDayToDate("today"), today);
}
@Test
public void formatDayToDate_tomorrow_dateofDayReturned() {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
String tomorrow = df.format(cal.getTime());
assertEquals(TaskDate.formatDayToDate("tomorrow"), tomorrow);
}
}
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.service.exteno.jms_2_0;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.jboss.ejb3.annotation.ResourceAdapter;
import ${package}.util.system.Messages;
/**
* Classe responsável por processar as mensagens recebidas localmente via JMS de forma assincrona, utilizando ActiveMQ do próprio Jboss.
* @author c112141
* @since 1.0
* @version 1.0.0
*
*/
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/${parentArtifactId}AsyncQueue"),
})
@ResourceAdapter(value = "activemq-ra.rar")
public class JMSLocalConsumerMDBService implements MessageListener {
private static final Logger log = Logger.getLogger(JMSLocalConsumerMDBService.class.getName());
@Override
public void onMessage(Message message) {
try {
TextMessage tm = (TextMessage) message;
log.info("Mensagem recebida: "+tm.getText());
} catch (JMSException ex) {
log.severe(Messages.getString("MSG_ERRO_MENSAGEM") + " | causa: " + ex);
}
}
}
|
package com.duck.proj;
import org.openqa.selenium.By;
import static com.codeborne.selenide.Selenide.$;
/**
* Created by Admin on 14.06.2017.
*/
public class DuckBase {
public void Logout() {
$(By.cssSelector("a[href*='logout']")).click();// Logout
}
public void homeButton() {
$(By.cssSelector("[title*='Home']")).click();// кнопка "Home"
}
public void shoppingCartConfirmOrder() {
$(By.cssSelector("#box-checkout-cart > div > table > tbody > tr:nth-child(1) > td:nth-child(6) > button")).click();
//удалить уточку
$(By.cssSelector("[name*='confirm_order']")).click();
}
public void purpleDuck() {
$(By.cssSelector("a[href*='#latest-products']")).click();// выбираю категорию Latest Products
$(By.cssSelector("#box-latest-products [href*='purple-duck-p-5']")).click();// нажать на товар Purple Duck
$(By.cssSelector("[name*='add_cart_product']")).click();// добавить утку в корзину
$(By.cssSelector("[aria-label*='Close']")).click();// закрыть окно с уточкой
$(By.cssSelector("#cart")).click();// перейти в корзину
}
public void greenDuck() {
$(By.cssSelector("a[href*='#popular-products']")).click();// выбираю категорию Popular Products
$(By.cssSelector("#box-popular-products [href*='green-duck-p-2']")).click();// нажать на товар Green Duck
$(By.cssSelector("[step*='1']")).setValue("2");// колличество уток
$(By.cssSelector("[name*='add_cart_product']")).click();// довить уток в корзину
$(By.cssSelector("[aria-label*='Close']")).click();// закрыть окно с уточкой
}
public void currencyChange() {
$(By.cssSelector("#region > div.change > a")).click();// кнопка "Change"
$(By.cssSelector("[name*=currency_code]")).click();// строка с выпадающим списком Currency
$(By.cssSelector("[value*=EUR]")).click();// поменяли валюту на евро
$(By.cssSelector("#box-regional-settings [value='0']")).click();// выбрать Exclude tax
$(By.cssSelector("[value='Save']")).click();// нажать на кнопку Save
}
public void createNewAccount() {
//создаем новый аккаунт в магазине
$(By.cssSelector("#box-account-login a")).pressEnter(); //нажать на "New customers click here"
// Сщздаю нового пользователя
$(By.cssSelector("[name*='tax_id']")).setValue("12345");// Tax ID
$(By.cssSelector("[name*=company]")).setValue("QA");// Company
$(By.cssSelector("[name*=firstname]")).setValue("Lida");// Firstname
$(By.cssSelector("[name*=lastname]")).setValue("Stass");// Lastname
$(By.cssSelector("[name*=address1]")).setValue("Frunze street");// Address 1
$(By.cssSelector("[name*=address2]")).setValue("Kirilovskaya street");// Address 2
$(By.cssSelector("[name*=postcode]")).setValue("04080");// Postcode
$(By.cssSelector("[name*=city]")).setValue("Kiev");// City
$(By.cssSelector("[name*=country_code]")).click();// строка с выпадающим списком
$(By.cssSelector("[value*=UA]")).click();// выбор страны, в данном случае Украина
$(By.cssSelector("#box-create-account > form > div:nth-child(7) input")).setValue("h@gmail.com");// Email
$(By.cssSelector("[name*=phone]")).setValue("+380633599934");// Phone
$(By.cssSelector("#box-create-account > form > div:nth-child(8) input")).setValue("lida123");// Desired Password
$(By.cssSelector("[name*=confirmed_password]")).setValue("lida123");// Confirm Password
$(By.cssSelector("[value*='Create Account']")).click();// Create Account
}
}
|
package org.fuusio.api.rest;
import org.fuusio.api.util.KeyValue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public abstract class RestRequest<T_Response, T_PeerRequest> {
protected static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
protected static final String PATH_SEPARATOR = "/";
protected final HttpHeaders mHeaders;
protected final HttpParams mParams;
protected final HttpParams mPathParams;
protected Object mBody;
protected HttpMethod mMethod;
protected T_PeerRequest mPeerRequest;
protected String mRelativeUrl;
protected RequestListener<T_Response> mRequestListener;
protected RestRequest(final String relativeUrl, final RequestListener<T_Response> requestListener) {
this(HttpMethod.GET, relativeUrl, requestListener);
}
protected RestRequest(final HttpMethod method, final String relativeUrl, final RequestListener<T_Response> requestListener) {
mMethod = method;
mRelativeUrl = relativeUrl;
mRequestListener = requestListener;
mHeaders = new HttpHeaders();
mPathParams = new HttpParams(getParamsEncoding());
mParams = new HttpParams(getParamsEncoding());
}
protected abstract String getBaseUrl();
protected String getParamsEncoding() {
return DEFAULT_PARAMS_ENCODING;
}
public String getRelativeUrl() {
return mRelativeUrl;
}
public T_PeerRequest getPeerRequest() {
return mPeerRequest;
}
public int getMethodCode() {
return mMethod.getMethodCode();
}
/**
* Construct the request url.
*
* @return The constructed url as a {@link String}.
*/
protected String constructUrl() {
final String baseUrl = getBaseUrl();
final StringBuilder builder = new StringBuilder(baseUrl);
final String relativeUrl = getRelativeUrl();
if (!baseUrl.endsWith(PATH_SEPARATOR)) {
if (!relativeUrl.startsWith(PATH_SEPARATOR)) {
builder.append(PATH_SEPARATOR);
}
builder.append(relativeUrl);
} else {
if (relativeUrl.startsWith(PATH_SEPARATOR)) {
builder.append(relativeUrl.substring(1));
} else {
builder.append(relativeUrl);
}
}
if (hasQueryParams()) {
builder.append('?');
getParams().encodeParameters(builder);
}
// Process path parameters
String url = builder.toString();
if (mPathParams != null) {
try {
final List<KeyValue<String, String>> keyValues = mPathParams.getKeyValues();
for (final KeyValue<String, String> keyValue : keyValues) {
final String key = "{" + keyValue.getKey() + "}";
final String value = URLEncoder.encode(keyValue.getValue(), HttpParams.DEFAULT_ENCODING);
url = url.replace(key, value);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Failed to encode path parameter.", e);
}
}
return url;
}
public final void constructRequest() {
mPeerRequest = createRequest();
initializeRequest(mPeerRequest);
}
protected abstract T_PeerRequest createRequest();
protected abstract void initializeRequest(T_PeerRequest request);
public boolean hasQueryParams() {
return (mParams != null && mParams.getSize() > 0);
}
/**
* Set the body of the request. The given object is assumed to be a POJO that can be converted
* by GSON to JSON.
*
* @param body A POJO as an {@link Object}.
*/
public void setBody(final Object body) {
mBody = body;
}
/**
* Add the specified query parameter with the given value.
*
* @param key The name of the parameter to be added as a {@link String}.
* @param value The value of the parameter.
*/
public RestRequest addParam(final String key, final String value) {
mParams.add(key, value);
return this;
}
public RestRequest addParam(final String key, final boolean value) {
mParams.add(key, Boolean.toString(value));
return this;
}
public RestRequest addParam(final String key, final float value) {
mParams.add(key, Float.toString(value));
return this;
}
public RestRequest addParam(final String key, final int value) {
mParams.add(key, Integer.toString(value));
return this;
}
public RestRequest addParam(final String key, final long value) {
mParams.add(key, Long.toString(value));
return this;
}
/**
* Add the specified path parameter with the given value.
*
* @param key The name of the parameter to be added as a {@link String}.
* @param value The value of the parameter.
*/
public RestRequest addPathParam(final String key, final String value) {
mPathParams.add(key, value);
return this;
}
public RestRequest addPathParam(final String key, final boolean value) {
mPathParams.add(key, Boolean.toString(value));
return this;
}
public RestRequest addPathParam(final String key, final float value) {
mPathParams.add(key, Float.toString(value));
return this;
}
public RestRequest addPathParam(final String key, final int value) {
mPathParams.add(key, Integer.toString(value));
return this;
}
public RestRequest addPathParam(final String key, final long value) {
mPathParams.add(key, Long.toString(value));
return this;
}
public RestRequest addHeader(final String field, final String value) {
mHeaders.add(field, value);
return this;
}
public final HttpHeaders getHeaders() {
return mHeaders;
}
public final HttpParams getParams() {
return mParams;
}
public void setParams(final HttpParams params) {
mParams.clear();
mParams.addAll(params);
}
public final HttpParams getPathParams() {
return mPathParams;
}
public void setPathParams(final HttpParams params) {
mPathParams.clear();
mPathParams.addAll(params);
}
public final RequestListener<T_Response> getRequestListener() {
return mRequestListener;
}
public boolean isDelete() {
return (mMethod == HttpMethod.DELETE);
}
public boolean isGet() {
return (mMethod == HttpMethod.GET);
}
public boolean isPost() {
return (mMethod == HttpMethod.POST);
}
public boolean isPut() {
return (mMethod == HttpMethod.PUT);
}
}
|
package org.ejemplos.stripes;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
/**
* Clase que sera la base de las demas acciones
* @author JAguilar
*/
public abstract class AccionBase implements ActionBean {
protected ActionBeanContext contexto;
@Override
public void setContext(ActionBeanContext abc) {
contexto = abc;
}
@Override
public ActionBeanContext getContext() {
return contexto;
}
}
|
package pe.gob.trabajo.web.rest;
import com.codahale.metrics.annotation.Timed;
import pe.gob.trabajo.domain.Sucesor;
import pe.gob.trabajo.repository.SucesorRepository;
import pe.gob.trabajo.repository.search.SucesorSearchRepository;
import pe.gob.trabajo.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Sucesor.
*/
@RestController
@RequestMapping("/api")
public class SucesorResource {
private final Logger log = LoggerFactory.getLogger(SucesorResource.class);
private static final String ENTITY_NAME = "sucesor";
private final SucesorRepository sucesorRepository;
private final SucesorSearchRepository sucesorSearchRepository;
public SucesorResource(SucesorRepository sucesorRepository, SucesorSearchRepository sucesorSearchRepository) {
this.sucesorRepository = sucesorRepository;
this.sucesorSearchRepository = sucesorSearchRepository;
}
/**
* POST /sucesors : Create a new sucesor.
*
* @param sucesor the sucesor to create
* @return the ResponseEntity with status 201 (Created) and with body the new sucesor, or with status 400 (Bad Request) if the sucesor has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/sucesors")
@Timed
public ResponseEntity<Sucesor> createSucesor(@Valid @RequestBody Sucesor sucesor) throws URISyntaxException {
log.debug("REST request to save Sucesor : {}", sucesor);
if (sucesor.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new sucesor cannot already have an ID")).body(null);
}
Sucesor result = sucesorRepository.save(sucesor);
sucesorSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/sucesors/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /sucesors : Updates an existing sucesor.
*
* @param sucesor the sucesor to update
* @return the ResponseEntity with status 200 (OK) and with body the updated sucesor,
* or with status 400 (Bad Request) if the sucesor is not valid,
* or with status 500 (Internal Server Error) if the sucesor couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/sucesors")
@Timed
public ResponseEntity<Sucesor> updateSucesor(@Valid @RequestBody Sucesor sucesor) throws URISyntaxException {
log.debug("REST request to update Sucesor : {}", sucesor);
if (sucesor.getId() == null) {
return createSucesor(sucesor);
}
Sucesor result = sucesorRepository.save(sucesor);
sucesorSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sucesor.getId().toString()))
.body(result);
}
/**
* GET /sucesors : get all the sucesors.
*
* @return the ResponseEntity with status 200 (OK) and the list of sucesors in body
*/
@GetMapping("/sucesors")
@Timed
public List<Sucesor> getAllSucesors() {
log.debug("REST request to get all Sucesors");
return sucesorRepository.findAll();
}
/**
* GET /sucesors/:id : get the "id" sucesor.
*
* @param id the id of the sucesor to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the sucesor, or with status 404 (Not Found)
*/
@GetMapping("/sucesors/{id}")
@Timed
public ResponseEntity<Sucesor> getSucesor(@PathVariable Long id) {
log.debug("REST request to get Sucesor : {}", id);
Sucesor sucesor = sucesorRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(sucesor));
}
/** JH
* GET /sucesors : get all the sucesors.
*
* @return the ResponseEntity with status 200 (OK) and the list of sucesors in body
*/
@GetMapping("/sucesors/activos")
@Timed
public List<Sucesor> getAll_Activos() {
log.debug("REST request to get all sucesors");
return sucesorRepository.findAll_Activos();
}
/** JH
* GET /sucesors/trabajador/id/:id_trab :
* @param id_trab es el id del trabajador
* @return the ResponseEntity with status 200 (OK) and with body the Sucesor, or with status 404 (Not Found)
*/
@GetMapping("/sucesors/trabajador/id/{id_trab}")
@Timed
public ResponseEntity<Sucesor> getSucesorBy_IdTrabajador(@PathVariable Long id_trab) {
log.debug("REST request to get Sucesor : id_trab {}", id_trab);
Sucesor sucesor = sucesorRepository.findSucesorBy_IdTrabajador(id_trab);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(sucesor));
}
/**
* DELETE /sucesors/:id : delete the "id" sucesor.
*
* @param id the id of the sucesor to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/sucesors/{id}")
@Timed
public ResponseEntity<Void> deleteSucesor(@PathVariable Long id) {
log.debug("REST request to delete Sucesor : {}", id);
sucesorRepository.delete(id);
sucesorSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/sucesors?query=:query : search for the sucesor corresponding
* to the query.
*
* @param query the query of the sucesor search
* @return the result of the search
*/
@GetMapping("/_search/sucesors")
@Timed
public List<Sucesor> searchSucesors(@RequestParam String query) {
log.debug("REST request to search Sucesors for query {}", query);
return StreamSupport
.stream(sucesorSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
public final class bxh extends a {
public String hbP;
public String jPG;
public String jSv;
public String rOw;
public String reT;
public String ruf;
public String sbQ;
public long stL;
protected final int a(int i, Object... objArr) {
int h;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.ruf != null) {
aVar.g(1, this.ruf);
}
if (this.reT != null) {
aVar.g(2, this.reT);
}
if (this.sbQ != null) {
aVar.g(3, this.sbQ);
}
if (this.jSv != null) {
aVar.g(4, this.jSv);
}
if (this.hbP != null) {
aVar.g(5, this.hbP);
}
if (this.jPG != null) {
aVar.g(6, this.jPG);
}
if (this.rOw != null) {
aVar.g(7, this.rOw);
}
aVar.T(8, this.stL);
return 0;
} else if (i == 1) {
if (this.ruf != null) {
h = f.a.a.b.b.a.h(1, this.ruf) + 0;
} else {
h = 0;
}
if (this.reT != null) {
h += f.a.a.b.b.a.h(2, this.reT);
}
if (this.sbQ != null) {
h += f.a.a.b.b.a.h(3, this.sbQ);
}
if (this.jSv != null) {
h += f.a.a.b.b.a.h(4, this.jSv);
}
if (this.hbP != null) {
h += f.a.a.b.b.a.h(5, this.hbP);
}
if (this.jPG != null) {
h += f.a.a.b.b.a.h(6, this.jPG);
}
if (this.rOw != null) {
h += f.a.a.b.b.a.h(7, this.rOw);
}
return h + f.a.a.a.S(8, this.stL);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bxh bxh = (bxh) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
bxh.ruf = aVar3.vHC.readString();
return 0;
case 2:
bxh.reT = aVar3.vHC.readString();
return 0;
case 3:
bxh.sbQ = aVar3.vHC.readString();
return 0;
case 4:
bxh.jSv = aVar3.vHC.readString();
return 0;
case 5:
bxh.hbP = aVar3.vHC.readString();
return 0;
case 6:
bxh.jPG = aVar3.vHC.readString();
return 0;
case 7:
bxh.rOw = aVar3.vHC.readString();
return 0;
case 8:
bxh.stL = aVar3.vHC.rZ();
return 0;
default:
return -1;
}
}
}
}
|
package com.tencent.mm.ui.chatting.b;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.a.e;
import com.tencent.mm.ak.o;
import com.tencent.mm.bg.d;
import com.tencent.mm.model.au;
import com.tencent.mm.model.br;
import com.tencent.mm.model.c;
import com.tencent.mm.model.s;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.pluginsdk.model.app.ao;
import com.tencent.mm.pluginsdk.model.app.f;
import com.tencent.mm.pluginsdk.model.app.l;
import com.tencent.mm.pluginsdk.p;
import com.tencent.mm.pluginsdk.ui.tools.m;
import com.tencent.mm.sdk.e.j;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.w;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.storage.u;
import com.tencent.mm.ui.chatting.ar;
import com.tencent.mm.ui.chatting.as;
import com.tencent.mm.ui.chatting.b.a.a;
import com.tencent.mm.y.g;
import java.io.File;
import java.util.Locale;
@a(cwo = com.tencent.mm.ui.chatting.b.b.a.class)
public class b extends a implements com.tencent.mm.ui.chatting.b.b.a {
private com.tencent.mm.plugin.wallet.a myP = null;
private ar tNY = null;
private final j.a tNZ = new 1(this);
private final j.a tOa = new 2(this);
public final void n(f fVar) {
if (fVar == null) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "onAppSelected, info is null, %s", new Object[]{bi.cjd()});
return;
}
if (!(fVar == null || !f.qzE.equals(fVar.field_appId) || this.myP == null)) {
this.myP.aM(2, this.bAG.oLT.field_username);
}
if (fVar.cbJ()) {
if (fVar == null || !fVar.cbJ()) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "serviceAppSelect not service app");
} else if (this.bAG.oLT == null || bi.oW(this.bAG.oLT.field_username)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "serviceAppSelect talker is null");
} else {
x.i("MicroMsg.ChattingUI.AppMsgComponent", "serviceApp, jumpType[%d], package[%s], appid[%s]", new Object[]{Integer.valueOf(fVar.cmZ), fVar.field_packageName, fVar.field_appId});
if (fVar.cmZ == 2 && !bi.oW(fVar.cmY)) {
o(fVar);
} else if (fVar.cmZ == 3) {
if (bi.oW(fVar.field_openId)) {
ao.bmh().pS(fVar.field_appId);
x.e("MicroMsg.ChattingUI.AppMsgComponent", "JUMP 3RD APP fail, openId is null, go get it");
} else if (this.tNY == null || bi.oW(fVar.field_packageName)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "JUMP 3RD APP fail");
o(fVar);
} else {
x.i("MicroMsg.ChattingUI.AppMsgComponent", "JUMP 3RD APP success[%s]", new Object[]{Boolean.valueOf(this.tNY.gh(fVar.field_packageName, fVar.field_openId))});
if (!this.tNY.gh(fVar.field_packageName, fVar.field_openId)) {
o(fVar);
}
}
} else if (fVar.cmZ == 1) {
x.i("MicroMsg.ChattingUI.AppMsgComponent", "JUMP NATIVE ForwardUrl[%s]", new Object[]{fVar.cmY});
p.a.qyl.a(this.bAG.tTq.getContext(), fVar.cmY, false, new 3(this));
}
}
} else if (fVar.field_status == 3) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "onAppSeleted fail, app is in blacklist, packageName = " + fVar.field_packageName);
} else if (!this.tNY.gh(fVar.field_packageName, fVar.field_openId) && fVar.field_status == 5) {
x.d("MicroMsg.ChattingUI.AppMsgComponent", "SuggestionApp appSuggestionIntroUrl = %s", new Object[]{fVar.cmM});
if (!bi.oW(fVar.cmM)) {
Intent intent = new Intent();
intent.putExtra("rawUrl", fVar.cmM);
d.b(this.bAG.tTq.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
}
}
private void o(f fVar) {
if (fVar == null || bi.oW(fVar.field_appId)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "jumpServiceH5 error args");
} else if (bi.oW(fVar.cmY)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "ForwardUrl is null");
} else {
int size;
Intent intent;
Bundle bundle;
SharedPreferences sharedPreferences = this.bAG.tTq.getContext().getSharedPreferences(ad.chY(), 0);
this.bAG.tTq.getContext();
String d = w.d(sharedPreferences);
if ("language_default".equalsIgnoreCase(d) && Locale.getDefault() != null) {
d = Locale.getDefault().toString();
}
if (s.fq(this.bAG.getTalkerUserName())) {
au.HU();
u ih = c.Ga().ih(this.bAG.getTalkerUserName());
if (ih != null) {
size = ih.Nn().size();
intent = new Intent();
bundle = new Bundle();
bundle.putString("jsapi_args_appid", fVar.field_appId);
bundle.putBoolean("isFromService", true);
intent.putExtra("forceHideShare", true);
bundle.putString("sendAppMsgToUserName", this.bAG.oLT.field_username);
intent.putExtra("jsapiargs", bundle);
intent.putExtra("show_bottom", false);
intent.putExtra("rawUrl", String.format("%s&wxchatmembers=%s&lang=%s", new Object[]{fVar.cmY, Integer.valueOf(size), d}));
d.b(this.bAG.tTq.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
}
size = 1;
intent = new Intent();
bundle = new Bundle();
bundle.putString("jsapi_args_appid", fVar.field_appId);
bundle.putBoolean("isFromService", true);
intent.putExtra("forceHideShare", true);
bundle.putString("sendAppMsgToUserName", this.bAG.oLT.field_username);
intent.putExtra("jsapiargs", bundle);
intent.putExtra("show_bottom", false);
intent.putExtra("rawUrl", String.format("%s&wxchatmembers=%s&lang=%s", new Object[]{fVar.cmY, Integer.valueOf(size), d}));
d.b(this.bAG.tTq.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
}
public final void aR(bd bdVar) {
String iC;
g.a gp;
f bl;
Intent intent;
String str = bdVar.field_content;
if (bdVar.field_isSend == 0) {
com.tencent.mm.ui.chatting.c.a aVar = this.bAG;
int i = bdVar.field_isSend;
if (!((com.tencent.mm.ui.chatting.b.b.c) aVar.O(com.tencent.mm.ui.chatting.b.b.c.class)).cus() && s.fq(aVar.getTalkerUserName()) && str != null && i == 0) {
iC = com.tencent.mm.model.bd.iC(str);
gp = g.a.gp(iC);
bl = com.tencent.mm.pluginsdk.model.app.g.bl(gp.appId, true);
if (bl != null || !com.tencent.mm.pluginsdk.model.app.p.r(this.bAG.tTq.getContext(), bl.field_packageName)) {
iC = com.tencent.mm.pluginsdk.model.app.p.y(this.bAG.tTq.getContext(), gp.appId, "message");
intent = new Intent();
intent.putExtra("rawUrl", iC);
d.b(this.bAG.tTq.getContext(), "webview", ".ui.tools.WebViewUI", intent);
} else if (bl.field_status == 3) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "requestAppShow fail, app is in blacklist, packageName = " + bl.field_packageName);
return;
} else if (!com.tencent.mm.pluginsdk.model.app.p.b(this.bAG.tTq.getContext(), bl)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "The app %s signature is incorrect.", new Object[]{bl.field_appName});
Toast.makeText(this.bAG.tTq.getContext(), this.bAG.tTq.getMMResources().getString(R.l.game_launch_fail_alert, new Object[]{com.tencent.mm.pluginsdk.model.app.g.b(this.bAG.tTq.getContext(), bl, null)}), 1).show();
return;
} else if (!a(bdVar, bl)) {
WXAppExtendObject wXAppExtendObject = new WXAppExtendObject();
wXAppExtendObject.extInfo = gp.extInfo;
if (gp.bGP != null && gp.bGP.length() > 0) {
com.tencent.mm.pluginsdk.model.app.b SR = ao.asF().SR(gp.bGP);
wXAppExtendObject.filePath = SR == null ? null : SR.field_fileFullPath;
}
WXMediaMessage wXMediaMessage = new WXMediaMessage();
wXMediaMessage.sdkVer = 620823808;
wXMediaMessage.mediaObject = wXAppExtendObject;
wXMediaMessage.title = gp.title;
wXMediaMessage.description = gp.description;
wXMediaMessage.messageAction = gp.messageAction;
wXMediaMessage.messageExt = gp.messageExt;
wXMediaMessage.thumbData = e.e(o.Pf().lN(bdVar.field_imgPath), 0, -1);
new as(this.bAG.tTq.getContext()).a(bl.field_packageName, wXMediaMessage, bl.field_appId, bl.field_openId);
return;
} else {
return;
}
}
}
iC = str;
gp = g.a.gp(iC);
bl = com.tencent.mm.pluginsdk.model.app.g.bl(gp.appId, true);
if (bl != null) {
}
iC = com.tencent.mm.pluginsdk.model.app.p.y(this.bAG.tTq.getContext(), gp.appId, "message");
intent = new Intent();
intent.putExtra("rawUrl", iC);
d.b(this.bAG.tTq.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
private boolean a(bd bdVar, f fVar) {
if (!bdVar.field_talker.endsWith("@qqim") || !fVar.field_packageName.equals("com.tencent.mobileqq")) {
return false;
}
int i;
x.d("MicroMsg.ChattingUI.AppMsgComponent", "jacks open QQ");
Intent intent = new Intent("android.intent.action.MAIN", null);
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(268435456);
intent.setClassName("com.tencent.mobileqq", aF(this.bAG.tTq.getContext(), "com.tencent.mobileqq"));
intent.putExtra("platformId", "wechat");
au.HU();
Object obj = c.DT().get(9, null);
if (obj == null || !(obj instanceof Integer)) {
i = 0;
} else {
i = ((Integer) obj).intValue();
}
if (i != 0) {
try {
byte[] bytes = String.valueOf(i).getBytes("utf-8");
byte[] bytes2 = "asdfghjkl;'".getBytes("utf-8");
int length = bytes2.length;
i = 0;
int i2 = 0;
while (i < length) {
byte b = bytes2[i];
if (i2 >= bytes.length) {
break;
}
int i3 = i2 + 1;
bytes[i2] = (byte) (b ^ bytes[i2]);
i++;
i2 = i3;
}
intent.putExtra("tencent_gif", bytes);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.ChattingUI.AppMsgComponent", e, "", new Object[0]);
}
}
try {
this.bAG.tTq.startActivity(intent);
} catch (Exception e2) {
}
return true;
}
private static String aF(Context context, String str) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(str, 0);
Intent intent = new Intent("android.intent.action.MAIN", null);
intent.addCategory("android.intent.category.LAUNCHER");
intent.setPackage(packageInfo.packageName);
ResolveInfo resolveInfo = (ResolveInfo) packageManager.queryIntentActivities(intent, 0).iterator().next();
if (resolveInfo != null) {
return resolveInfo.activityInfo.name;
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.ChattingUI.AppMsgComponent", e, "", new Object[0]);
}
return null;
}
public final void a(m mVar) {
br.IE().c(38, new Object[]{Integer.valueOf(1)});
String str = mVar.filePath;
WXMediaMessage wXMediaMessage = new WXMediaMessage(new WXFileObject(str));
wXMediaMessage.title = new File(str).getName();
wXMediaMessage.description = bi.bF((long) e.cm(str));
f fVar = new f();
fVar.field_appId = "wx4310bbd51be7d979";
ao.bmf().b(fVar, new String[0]);
l.a(wXMediaMessage, fVar.field_appId, fVar.field_appName, this.bAG.getTalkerUserName(), 2, null);
}
public final void onActivityResult(int i, int i2, Intent intent) {
super.onActivityResult(i, i2, intent);
switch (i) {
case 210:
if (i2 == -1) {
long longExtra = intent.getLongExtra("App_MsgId", 0);
au.HU();
aR(c.FT().dW(longExtra));
return;
}
return;
case 222:
if (i2 == -1 && intent != null) {
String stringExtra = intent.getStringExtra("service_app_package_name");
String stringExtra2 = intent.getStringExtra("service_app_openid");
String stringExtra3 = intent.getStringExtra("service_app_appid");
String str = "MicroMsg.ChattingUI.AppMsgComponent";
String str2 = "request send wx msg, wxmessage[%b], package[%s], appId[%s], openId[%s]";
Object[] objArr = new Object[4];
objArr[0] = Boolean.valueOf(this.tNY != null);
objArr[1] = stringExtra;
objArr[2] = stringExtra3;
objArr[3] = stringExtra2;
x.i(str, str2, objArr);
if (bi.oW(stringExtra3)) {
x.e("MicroMsg.ChattingUI.AppMsgComponent", "REQUEST_CODE_SERVICE_APP openId is null");
return;
} else if (this.tNY == null || bi.oW(stringExtra)) {
o(com.tencent.mm.pluginsdk.model.app.g.bl(stringExtra3, true));
return;
} else if (bi.oW(stringExtra2)) {
ao.bmh().pS(stringExtra3);
x.e("MicroMsg.ChattingUI.AppMsgComponent", "request send wx msg fail, openId is null, go get it");
return;
} else {
x.d("MicroMsg.ChattingUI.AppMsgComponent", "request send wx msg success = %b", new Object[]{Boolean.valueOf(this.tNY.gh(stringExtra, stringExtra2))});
if (!this.tNY.gh(stringExtra, stringExtra2)) {
o(com.tencent.mm.pluginsdk.model.app.g.bl(stringExtra3, true));
return;
}
return;
}
}
return;
default:
return;
}
}
public final void cpH() {
this.myP = com.tencent.mm.plugin.wallet.a.cp(this.bAG.oLT.field_username, 1);
this.myP.aM(1, this.bAG.oLT.field_username);
ao.asF().c(this.tNZ);
ao.bmf().c(this.tOa);
if (this.tNY == null) {
this.tNY = new ar(this.bAG);
}
ar arVar = this.tNY;
this.bAG.tTq.getContext();
ar.tNy.a(arVar, null);
}
public final void cpJ() {
com.tencent.mm.ui.chatting.ao.clear();
}
public final void cpK() {
ar arVar = this.tNY;
this.bAG.tTq.getContext();
ar.tNy.remove(arVar);
arVar.tNx.clear();
ar.b(arVar.tNw.getContext(), null);
if (au.HX()) {
ao.asF().d(this.tNZ);
ao.bmf().d(this.tOa);
}
}
}
|
package com.seemoreinteractive.seemoreinteractive;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.seemoreinteractive.seemoreinteractive.Model.SessionManager;
import com.seemoreinteractive.seemoreinteractive.helper.Common;
public class OptionsTermsConditions extends Activity {
public boolean isBackPressed = false;
final Context context = this;
String className =this.getClass().getSimpleName();
public Boolean alertErrorType = true;
String getProductId, getProductName, getProductPrice, getClientLogo, getClientId, getClientBackgroundImage, getClientBackgroundColor;
SessionManager session;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_terms_conditions);
try{
//new Common().pageHeaderTitle(OptionsTermsConditions.this, "Terms & Conditions");
/*new Common().clientLogoOrTitleWithThemeColorAndBgImgByPassingColor(
this, Common.sessionClientBgColor,
Common.sessionClientBackgroundLightColor,
Common.sessionClientBackgroundDarkColor,
Common.sessionClientLogo, "Terms & Conditions", ""); */
new Common().clientLogoOrTitleWithThemeColorAndBgImgByPassingColor(
this, "ff2600",
"ff2600",
"ff2600",
Common.sessionClientLogo, "Terms & Conditions", "");
//findViewById(R.id.imgvBtnCart).setVisibility(View.INVISIBLE);
//new Common().showDrawableImageFromAquery(this, R.id.closetProgressBar, R.id.imgvBtnCart);
ImageView imgBtnCart = (ImageView) findViewById(R.id.imgvBtnCart);
imgBtnCart.setImageAlpha(0);
WebView webview = (WebView)findViewById(R.id.wbvTermsCond);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(getString(R.string.url_terms_condition));
new Common().clickingOnBackButtonWithAnimation(OptionsTermsConditions.this, ProductList.class,"0");
/*ImageView imgBtnCart = (ImageView) findViewById(R.id.imgvBtnCart);
imgBtnCart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Intent prodInfo = new Intent(getApplicationContext(), ProductList.class);
setResult(RESULT_OK, prodInfo);
finish();
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error: Terms & Conditions imgBtnCart onClick.", Toast.LENGTH_LONG).show();
}
}
});*/
findViewById(R.id.closetProgressBar).setVisibility(View.INVISIBLE);
String screenName = "/web/termsandcondition/?url="+getString(R.string.url_terms_condition);
String productIds = "";
String offerIds = "";
Common.sendJsonWithAQuery(this, ""+Common.sessionIdForUserLoggedIn, screenName, productIds, offerIds);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error: Terms & Conditions onCreate.", Toast.LENGTH_LONG).show();
ex.printStackTrace();
String errorMsg = className+" | onCreate | " +ex.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
try{
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Log.i("Press Back", "BACK PRESSED EVENT");
onBackPressed();
isBackPressed = true;
}
// Call super code so we dont limit default interaction
return super.onKeyDown(keyCode, event);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error: HowTo onKeyDown.", Toast.LENGTH_LONG).show();
String errorMsg = className+" | onKeyDown | " +ex.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
return false;
}
}
@Override
public void onBackPressed() {
try{
//new Common().clickingOnBackButtonWithAnimationWithBackPressed(this, ProductList.class, "0");
finish();
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error: HowTo onBackPressed.", Toast.LENGTH_LONG).show();
String errorMsg = className+" | onBackPressed | " +ex.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
return;
}
@Override
public void onStart() {
try{
super.onStart();
Tracker easyTracker = EasyTracker.getInstance(this);
easyTracker.set(Fields.SCREEN_NAME, " /terms&conditions/?="+getString(R.string.url_terms_condition));
easyTracker.send(MapBuilder
.createAppView()
.build()
);
}catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | onBackPressed | " +e.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
}
@Override
public void onStop() {
try{
super.onStop();
//The rest of your onStop() code.
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | onStop | " +e.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
}
@Override
protected void onPause()
{
try{
super.onPause();
Boolean appInBackgrnd = new Common().isApplicationBroughtToBackground(OptionsTermsConditions.this);
if(appInBackgrnd){
Common.isAppBackgrnd = true;
}
}catch (Exception e) {
e.printStackTrace();
String errorMsg = className+" | onPause | " +e.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
}
@Override
protected void onResume() {
try{
super.onResume();
if(Common.isAppBackgrnd){
new Common().storeChangeLogResultFromServer(OptionsTermsConditions.this);
Common.isAppBackgrnd = false;
}
}catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | onResume | " +e.getMessage();
Common.sendCrashWithAQuery(OptionsTermsConditions.this,errorMsg);
}
}
}
|
package com.tencent.mm.plugin.wenote.ui.nativenote;
import com.tencent.mm.R;
import com.tencent.mm.plugin.wenote.ui.nativenote.NoteEditorUI.6;
import com.tencent.mm.ui.widget.snackbar.b;
class NoteEditorUI$6$1 implements Runnable {
final /* synthetic */ 6 qut;
NoteEditorUI$6$1(6 6) {
this.qut = 6;
}
public final void run() {
this.qut.iYD.dismiss();
b.h(this.qut.qur, this.qut.qur.getString(R.l.finish_sent));
}
}
|
package main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.media.opengl.*;
/**
* This class creates frame and opengl canvas to render
* graphic, starts render thread and makes it visible
* @author Darek
*/
public class JOGL extends JFrame implements WindowListener
{
/**
* rendering canvas for this application
*/
private TetrisGL canvas;
/**
* constructor, starts game
*/
public JOGL()
{
super("Tetris 3D");
Container c = getContentPane();
c.setLayout( new BorderLayout() );
c.add( makeRenderPanel(), BorderLayout.CENTER);
addWindowListener(this);
pack();
setVisible(true);
}
/**
* this method makes rendering panel with opengl rendering canvas
* @return panel witch rendering ranvas
*/
public JPanel makeRenderPanel()
{
JPanel renderPane = new JPanel();
renderPane.setLayout( new BorderLayout() );
renderPane.setOpaque(true);
renderPane.setPreferredSize( new Dimension(800, 600));
canvas = makeCanvas();
renderPane.add(canvas, BorderLayout.CENTER);
canvas.setFocusable(true);
canvas.requestFocus();
renderPane.addComponentListener( new ComponentAdapter() {
public void componentResized(ComponentEvent evt)
{ Dimension d = evt.getComponent().getSize();
canvas.reshape(d.width, d.height);
}
});
return renderPane;
}
/**
* create canvas accordin to hardware capabilities,
* alse enabls 2x antialiasing
* @return game canvas
*/
public TetrisGL makeCanvas()
{
GLCapabilities capabilities = new GLCapabilities();
capabilities.setHardwareAccelerated(true);
capabilities.setNumSamples(2); // 2x antialiasing
capabilities.setSampleBuffers(true);
return new TetrisGL(capabilities);
}
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowActivated(WindowEvent e)
{ }
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowDeactivated(WindowEvent e)
{ }
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowDeiconified(WindowEvent e)
{ }
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowIconified(WindowEvent e)
{ }
/**
* implemented method from WindowListener interface,
* stops game when closing
* @param e window event
*/
public void windowClosing(WindowEvent e)
{ canvas.stopGame(); }
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowClosed(WindowEvent e) {}
/**
* implemented method from WindowListener interface
* @param e window event
*/
public void windowOpened(WindowEvent e) {}
/**
* main application method, starts game
* @param args args for this application
*/
public static void main(String[] args)
{
new JOGL();
}
}
|
/*
* 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 eje2;
/**
*
* @author Mery Acevedo
*/
public interface impuesto {
Double pedirPrecio();
Double generarImpuesto(double a);
Double precioTotal();
}
|
package tp1;
import java.util.Random;
public class alteracaoAleatoria {
public static void main(String[] args) {
String read = MyIO.readLine();
while(!read.equals("FIM")){
System.out.println(aleatorio(read));
read = MyIO.readLine();
}
}
public static String aleatorio(String frase){
Random gerador = new Random();
gerador.setSeed(4);
char a = 0;
String novaFrase = "";
a = (char) (Math.abs(gerador.nextInt())%26);
char b = 0;
b = (char) (Math.abs(gerador.nextInt())%26);
for (int i = 0; i < frase.length(); i++){
if(frase.charAt(i) == a){
novaFrase = novaFrase + b;
}else if(frase.charAt(i) == b){
novaFrase = novaFrase + a;
}else{
novaFrase = novaFrase + frase.charAt(i);
}
}
return novaFrase;
}
}
|
public class Persona{
private int eta;
private String nome, cognome;
public Persona(String nome, String cognome, int eta){
this.nome = nome;
this.cognome = cognome;
this.eta = eta;
}
public int getEta(){
return this.eta;
}
public boolean equals(Object obj){
//If the cell is the same one, the two are equals
if (this == obj) return true;
// If obect point to null, surely the the are NOT equals
if( obj == null) return false;
if( ! ( obj instanceof Persona ) ) return false;
Persona other = (Persona) obj;
if(this.eta != other.eta) return false;
if ( nome == null){
if( other.nome != null)
return false;
}else if ( !nome.equals(other.name)
return false;
return true;
}
}
|
package com.sneaker.mall.api.service.impl;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.sneaker.mall.api.dao.admin.FavoriteDao;
import com.sneaker.mall.api.dao.admin.GoodsDao;
import com.sneaker.mall.api.dao.info.CompanyDao;
import com.sneaker.mall.api.model.*;
import com.sneaker.mall.api.service.GoodsService;
import com.sneaker.mall.api.service.MarketService;
import com.sneaker.mall.api.service.PriceService;
import com.sneaker.mall.api.util.CONST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
@Service
public class B2GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsDao goodsDao;
@Autowired
private PriceService priceService;
@Autowired
private MarketService marketService;
@Autowired
private FavoriteDao favoriteDao;
@Autowired
private CompanyDao companyDao;
@Autowired
@Qualifier("default_img_url")
private String default_img_url;
@Autowired
@Qualifier("img_server_prefix")
private String img_server_prefix;
@Override
public List<Goods> getGoodsBycid(long cid, long cateid, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(cateid > 0);
//查询客户的客户类型与仓库
List<Goods> goodses = Lists.newArrayList();
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByCidAndCateid(cid, cateid, customer.getCctype(), customer.getSid());
if (goodses != null) {
//补充绑定信息
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getHotGoodsByCid(long cid, int limit, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(ccid > 0);
Preconditions.checkArgument(limit > 0);
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findHotGoods(cid, limit, customer.getCctype(), customer.getSid());
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getGoodsByTypeIdAndCid(long cid, long typeid, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(typeid > 0);
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByCidAndTypeid(cid, typeid, customer.getCctype(), customer.getSid());
if (goodses != null) {
//补充绑定信息
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getGoodsByCidAndTypeCode(int page, int limit, long cid, String code, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkNotNull(code);
int start = (page - 1) * limit;
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByCidAndTypeCode(start, limit, cid, code, customer.getCctype(), customer.getSid());
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getGoodsByCidAndTypeCode(int page, int limit, long cid, String code, String cctype, String sid) {
Preconditions.checkNotNull(cctype);
Preconditions.checkNotNull(sid);
Preconditions.checkNotNull(code);
int start = (page - 1) * limit;
List<Goods> goodses = this.goodsDao.findGoodsByCidAndTypeCode(start, limit, cid, code, cctype, sid);
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, cctype, sid);
}
return goodses;
}
@Override
public int countGoodsByCidAndTypeCode(long cid, String code, long ccid) {
Preconditions.checkArgument(cid > 0);
int count = 0;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
count = this.goodsDao.countGoodsByCidAndTypeCode(cid, code, customer.getCctype(), customer.getSid());
}
return count;
}
@Override
public int countGoodsByCidAndTypeCode(long cid, String code, String cctype, String sid) {
Preconditions.checkArgument(cid > 0);
int count = this.goodsDao.countGoodsByCidAndTypeCode(cid, code, cctype, sid);
return count;
}
@Override
public List<Goods> getGoodsByCidAndPage(long cid, int pageNumber, int size, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(pageNumber > 0);
Preconditions.checkArgument(size > 0);
int start = (pageNumber - 1) * size;
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByCidAndPage(cid, start, size, customer.getCctype(), customer.getSid());
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getGoodsByCidAndPage(long cid, int pageNumber, int size, String cctype, String sid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(pageNumber > 0);
Preconditions.checkArgument(size > 0);
int start = (pageNumber - 1) * size;
List<Goods> goodses = null;
goodses = this.goodsDao.findGoodsByCidAndPage(cid, start, size, cctype, sid);
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, cctype, sid);
}
return goodses;
}
@Override
public int countGoodsByCid(long cid, long ccid) {
Preconditions.checkArgument(cid > 0);
int count = 0;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
count = this.goodsDao.countGoodsByCid(cid, customer.getCctype(), customer.getSid());
}
return count;
}
@Override
public int countGoodsByCid(long cid, String cctype, String sid) {
Preconditions.checkArgument(cid > 0);
int count = 0;
count = this.goodsDao.countGoodsByCid(cid, cctype, sid);
return count;
}
@Override
public List<Goods> getGoodsByCidAndCateidAndLimit(long cid, long cateid, int limit, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(cateid > 0);
Preconditions.checkArgument(limit > 0);
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByCidAndCateIdAndLimit(cid, cateid, limit, customer.getCctype(), customer.getSid());
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getGoodsByCidAndCateidAndLimit(long cid, long cateid, int limit, String cctype, String sid) {
Preconditions.checkNotNull(cctype);
Preconditions.checkNotNull(sid);
Preconditions.checkArgument(cateid > 0);
Preconditions.checkArgument(limit > 0);
List<Goods> goodses = this.goodsDao.findGoodsByCidAndCateIdAndLimit(cid, cateid, limit, cctype, sid);
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, cctype, sid);
}
return goodses;
}
@Override
public int countGoodsByCidAndCateid(long cid, long cateid, long ccid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(cateid > 0);
int count = 0;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
count = this.goodsDao.countGoodsByCidAndCateId(cid, cateid, customer.getCctype(), customer.getSid());
}
return count;
}
@Override
public int countGoodsByCidAndCateid(long cid, long cateid, String cctype, String sid) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(cateid > 0);
int count = this.goodsDao.countGoodsByCidAndCateId(cid, cateid, cctype, sid);
return count;
}
@Override
public Goods getGoodsByGidAndCid(long gid, long cid) {
return null;
}
@Override
public Goods getGoodsById(long id, long cid, long ccid) {
Preconditions.checkArgument(id > 0);
Goods goods = this.goodsDao.findGoodsById(id);
if (goods != null) {
//补充绑定信息
this.genartePhoto(goods);
this.paddingSingleMarket(goods, cid, ccid);
}
return goods;
}
@Override
public Goods getGoodsByBarCode(String barcode, long cid, long ccid) {
Preconditions.checkNotNull(barcode);
Preconditions.checkArgument(cid > 0);
Goods goods = this.goodsDao.findGoodsByCidAndBarCode(cid, barcode);
if (goods != null) {
//补充绑定信息
this.genartePhoto(goods);
this.paddingSingleMarket(goods, cid, ccid);
}
return goods;
}
@Override
public List<Goods> getGoodsByKeywordAndCid(String keywrod, long cid, long ccid) {
Preconditions.checkNotNull(keywrod);
Preconditions.checkArgument(cid > 0);
List<Goods> goodses = null;
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
goodses = this.goodsDao.findGoodsByKeywordAndCid(cid, keywrod, customer.getCctype(), customer.getSid());
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
}
return goodses;
}
@Override
public List<Goods> getFavoriteGoodsCidAndScid(long scid, long cid, int page, int limit) {
Preconditions.checkArgument(cid > 0);
Preconditions.checkArgument(scid > 0);
Preconditions.checkArgument(page > 0);
Preconditions.checkArgument(limit > 0);
int start = (page - 1) * limit;
List<Goods> goodses = this.favoriteDao.findFavoriteForCidAndScid(scid, cid, start, limit); //考虑这里面是否带入价格与营销活动信息
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, scid, cid);
}
return goodses;
}
@Override
public List<Goods> getFavoriteGoodsForUser(long uid, int page, int limit, long cid, long ccid) {
Preconditions.checkArgument(uid > 0);
Preconditions.checkArgument(page > 0);
Preconditions.checkArgument(limit > 0);
int start = (page - 1) * limit;
List<Goods> goodses = this.favoriteDao.findFavoriteForUid(uid, start, limit);
if (goodses != null) {
//加载是不是绑定的
this.paddingMarket(goodses, cid, ccid);
}
return goodses;
}
@Override
public List<Goods> getChlidGoodsByMainGoodsId(long id, long cid, long ccid) {
Preconditions.checkNotNull(id > 0);
Goods mainGoods = this.getGoodsById(id, cid, ccid);
if (mainGoods != null && mainGoods.getIsbind() == 1) {
List<Goods> goodses = this.goodsDao.findGoodsByMarket(id);
if (goodses != null) {
goodses.stream().forEach(goods -> {
this.genartePhoto(goods);
});
}
return goodses;
}
return null;
}
/**
* 填充商品信息
*
* @param goodses
*/
public void paddingMarket(List<Goods> goodses, long cid, long ccid) {
Preconditions.checkNotNull(goodses);
goodses.stream().forEach(goods -> {
this.genartePhoto(goods);
goods.setContent("");//读取列表均不返回Content
if (goods.getIsbind() == 1 || goods.getPkgSize() == 1 || goods.getShop_price() == 1) {
//是绑定商品,读取绑定商品信息列表
this.paddingSingleMarket(goods, cid, ccid);
}
});
}
/**
* 填充商品信息 根据sid,cctype
*
* @param goodses
*/
public void paddingMarket(List<Goods> goodses, long cid, String cctype, String sid) {
Preconditions.checkNotNull(goodses);
goodses.stream().forEach(goods -> {
this.genartePhoto(goods);
goods.setContent("");//读取列表均不返回Content
if (goods.getIsbind() == 1 || goods.getPkgSize() == 1 || goods.getShop_price() == 1) {
//是绑定商品,读取绑定商品信息列表
this.paddingSingleMarket(goods, cid, cctype, sid);
}
});
}
@Override
public List<Goods> getOrderForAKeyOrder(Order order, long ccid, long scid) {
Preconditions.checkNotNull(order);
Preconditions.checkArgument(ccid > 0);
Preconditions.checkArgument(scid > 0);
List<OrderItem> orderItems = order.getItems();
List<Goods> goodses = Lists.newArrayList();
if (orderItems != null) {
orderItems.stream().forEach(orderItem -> {
if (orderItem.getGiveaway() != CONST.MARKET_GIVEWAYA_GIVE) {
Goods goods = null;
if (orderItem.getBindId() > 0) {
//打包商品
goods = this.getGoodsById(orderItem.getBindId(), scid, ccid);
} else {
//单号
goods = this.getGoodsById(orderItem.getMgid(), scid, ccid);
}
if (goods != null && goods.getPublish() == CONST.GOODS_PUBLISH_ONLINE) {
//判断商品是不是打包商品,如果是打包商品需要判断该客户是否可以购买
if (goods.getIsbind() == 1) {
//判断该商品是不是可以卖给该客户类型,及仓库的判断
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(scid, ccid);
if (customer != null) {
//判断客户类型与仓库
if (("," + goods.getCctype() + ",").indexOf("," + customer.getCctype() + ",") >= 0 && ("," + goods.getSids() + ",").indexOf("," + customer.getSid() + ",") >= 0) {
goodses.add(goods);
}
}
} else {
goodses.add(goods);
}
}
}
});
}
return goodses;
}
/**
* 补充商品的绑定信息
*
* @param goods
*/
public void paddingSingleMarket(Goods goods, long cid, long ccid) {
//设置商品价格
//根据公司ID与公司ID读取客户类型与仓库信息
Customer customer = this.companyDao.findCustomerByCompanyIdAndCoustomerCompanyId(cid, ccid);
if (customer != null) {
ShopPrice shopPrice = this.priceService.getShopPriceByCcTypeAndSidAndMgid(cid, Integer.valueOf(customer.getCctype())
, Integer.valueOf(customer.getSid())
, goods.getId());
if (shopPrice != null) {
goods.setPrice(shopPrice.getPrice());
}
}
//绑定商品
if (goods.getIsbind() == 1) {
//读取绑定信息
List<Goods> marketGoods = this.goodsDao.findGoodsByMarket(goods.getId());
if (marketGoods != null) {
//组合打包信息文字
Map<Integer, List<Goods>> goodsMap = marketGoods.stream().collect(Collectors.groupingBy(Goods::getGiveaway));
if (goodsMap != null && goodsMap.size() >= 1) {
//拼接绑定商品信息
List<Goods> mainGoods = goodsMap.get(CONST.MARKET_GIVEWAYA_MAIN);
if (mainGoods != null) {
mainGoods.stream().forEach(mGoods -> {
this.genartePhoto(mGoods);
});
goods.setMainGoods(mainGoods);
}
}
}
}
}
/**
* 补充商品的绑定信息
*
* @param goods
*/
public void paddingSingleMarket(Goods goods, long cid, String cctype, String sid) {
//设置商品价格
//根据公司ID与公司ID读取客户类型与仓库信息
ShopPrice shopPrice = this.priceService.getShopPriceByCcTypeAndSidAndMgid(cid, Integer.valueOf(cctype)
, Integer.valueOf(sid)
, goods.getId());
if (shopPrice != null) {
goods.setPrice(shopPrice.getPrice());
}
//绑定商品
if (goods.getIsbind() == 1) {
//读取绑定信息
List<Goods> marketGoods = this.goodsDao.findGoodsByMarket(goods.getId());
if (marketGoods != null) {
//组合打包信息文字
Map<Integer, List<Goods>> goodsMap = marketGoods.stream().collect(Collectors.groupingBy(Goods::getGiveaway));
if (goodsMap != null && goodsMap.size() >= 1) {
//拼接绑定商品信息
List<Goods> mainGoods = goodsMap.get(CONST.MARKET_GIVEWAYA_MAIN);
if (mainGoods != null) {
mainGoods.stream().forEach(mGoods -> {
this.genartePhoto(mGoods);
});
goods.setMainGoods(mainGoods);
}
}
}
}
}
/**
* 生成图片地址
*
* @param goods
*/
public void genartePhoto(Goods goods) {
if (!Strings.isNullOrEmpty(goods.getGphoto()) && !"0".equals(goods.getGphoto())) {
goods.setGphoto(img_server_prefix + "/" + goods.getGcode() + "_" + goods.getGphoto() + ".jpg");
} else {
goods.setGphoto(default_img_url);
}
}
}
|
package com.gin.pixivmanager.util;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* 更新进度工具
*/
@Slf4j
public class Progress implements Comparable<Progress> {
/**
* 任务名称
*/
String name;
/**
* 当前和最大进度
*/
long count;
long size;
int times;
public Progress(String name, long count, long size) {
this.name = name;
this.count = count;
this.size = size;
}
public Progress(String name, long size) {
this(name, 0, size);
}
public Progress(String k, Map<String, Integer> map) {
name = k;
count = map.get("count");
size = map.get("size");
times = map.get("times");
}
/**
* 进度是否完成
*
* @return 任务是否完成
*/
public boolean isCompleted() {
return count == size;
}
/**
* 使任务完成
*/
public void complete() {
count = size;
}
/**
* 增加当前进度
*
* @param num 增加进度
* @return 当前进度
*/
public long add(long num) {
this.count += num;
return this.count;
}
/**
* 格式化输出大小
*
* @param num 文件大小(B)
* @return 字符串
*/
private static String inSize(long num) {
String s = "" + num;
int k = 1024;
if (num > k * k) {
double v = Math.floor(num * 100.0 / k / k) / 100;
s = v + "M";
} else if (num > 10 * k) {
double v = Math.floor(num * 10.0 / k) / 10;
s = v + "K";
}
return s;
}
/**
* 绝对值进度
*
* @return 绝对值进度
*/
public String getProgress() {
return count + "/" + size;
}
/**
* 文件大小进度
*
* @return 文件大小进度
*/
public String getProgressInSize() {
return inSize(count) + "/" + inSize(size);
}
/**
* 百分比进度
*
* @return 百分比进度
*/
public String getProgressInPercent() {
return String.valueOf(Math.floor(1.0 * count / size * 1000) / 10);
}
@Override
public String toString() {
return getProgress() + " " + getProgressInSize() + " " + getProgressInPercent();
}
public String getName() {
return name;
}
public int getTimes() {
return times;
}
@Override
public int compareTo(Progress o) {
return this.name.compareTo(o.getName());
}
}
|
import java.util.Scanner;
public class Bob2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Continue? [y/n]");
String continueTalking = sc.next();
boolean userTalk = continueTalking.equalsIgnoreCase("y");
sc.nextLine();
if (userTalk) {
do {
System.out.println("What would you like to say to Bob?");
String saidToBob = sc.nextLine();
if (saidToBob.endsWith("?")){
System.out.println("Sure.");
}else if (saidToBob.endsWith("!")){
System.out.println("Woah, chill out!");
}else if (saidToBob.equals("")){
System.out.println("Fine. Be that way!");
}else{
System.out.println("Whatever.");
}
System.out.println("Continue talking to Bob? [y/n]");
continueTalking = sc.next();
userTalk = continueTalking.equalsIgnoreCase("y");
sc.nextLine();
} while (userTalk);
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests the old mapred APIs with {@link Reporter#getProgress()}.
*/
public class TestReporter {
private static final Path rootTempDir =
new Path(System.getProperty("test.build.data", "/tmp"));
private static final Path testRootTempDir =
new Path(rootTempDir, "TestReporter");
private static FileSystem fs = null;
@BeforeClass
public static void setup() throws Exception {
fs = FileSystem.getLocal(new Configuration());
fs.delete(testRootTempDir, true);
fs.mkdirs(testRootTempDir);
}
@AfterClass
public static void cleanup() throws Exception {
fs.delete(testRootTempDir, true);
}
// an input with 4 lines
private static final String INPUT = "Hi\nHi\nHi\nHi\n";
private static final int INPUT_LINES = INPUT.split("\n").length;
@SuppressWarnings("deprecation")
static class ProgressTesterMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, Text> {
private float progressRange = 0;
private int numRecords = 0;
private Reporter reporter = null;
@Override
public void configure(JobConf job) {
super.configure(job);
// set the progress range accordingly
if (job.getNumReduceTasks() == 0) {
progressRange = 1f;
} else {
progressRange = 0.667f;
}
}
@Override
public void map(LongWritable key, Text value,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException {
this.reporter = reporter;
// calculate the actual map progress
float mapProgress = ((float)++numRecords)/INPUT_LINES;
// calculate the attempt progress based on the progress range
float attemptProgress = progressRange * mapProgress;
assertEquals("Invalid progress in map",
attemptProgress, reporter.getProgress(), 0f);
output.collect(new Text(value.toString() + numRecords), value);
}
@Override
public void close() throws IOException {
super.close();
assertEquals("Invalid progress in map cleanup",
progressRange, reporter.getProgress(), 0f);
}
}
/**
* Test {@link Reporter}'s progress for a map-only job.
* This will make sure that only the map phase decides the attempt's progress.
*/
@SuppressWarnings("deprecation")
@Test
public void testReporterProgressForMapOnlyJob() throws IOException {
Path test = new Path(testRootTempDir, "testReporterProgressForMapOnlyJob");
JobConf conf = new JobConf();
conf.setMapperClass(ProgressTesterMapper.class);
conf.setMapOutputKeyClass(Text.class);
// fail early
conf.setMaxMapAttempts(1);
conf.setMaxReduceAttempts(0);
RunningJob job =
UtilsForTests.runJob(conf, new Path(test, "in"), new Path(test, "out"),
1, 0, INPUT);
job.waitForCompletion();
assertTrue("Job failed", job.isSuccessful());
}
/**
* A {@link Reducer} implementation that checks the progress on every call
* to {@link Reducer#reduce(Object, Iterator, OutputCollector, Reporter)}.
*/
@SuppressWarnings("deprecation")
static class ProgressTestingReducer extends MapReduceBase
implements Reducer<Text, Text, Text, Text> {
private int recordCount = 0;
private Reporter reporter = null;
// reduce task has a fixed split of progress amongst copy, shuffle and
// reduce phases.
private final float REDUCE_PROGRESS_RANGE = 1.0f/3;
private final float SHUFFLE_PROGRESS_RANGE = 1 - REDUCE_PROGRESS_RANGE;
@Override
public void configure(JobConf job) {
super.configure(job);
}
@Override
public void reduce(Text key, Iterator<Text> values,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException {
float reducePhaseProgress = ((float)++recordCount)/INPUT_LINES;
float weightedReducePhaseProgress =
reducePhaseProgress * REDUCE_PROGRESS_RANGE;
assertEquals("Invalid progress in reduce",
SHUFFLE_PROGRESS_RANGE + weightedReducePhaseProgress,
reporter.getProgress(), 0.02f);
this.reporter = reporter;
}
@Override
public void close() throws IOException {
super.close();
assertEquals("Invalid progress in reduce cleanup",
1.0f, reporter.getProgress(), 0f);
}
}
/**
* Test {@link Reporter}'s progress for map-reduce job.
*/
@SuppressWarnings("deprecation")
@Test
public void testReporterProgressForMRJob() throws IOException {
Path test = new Path(testRootTempDir, "testReporterProgressForMRJob");
JobConf conf = new JobConf();
conf.setMapperClass(ProgressTesterMapper.class);
conf.setReducerClass(ProgressTestingReducer.class);
conf.setMapOutputKeyClass(Text.class);
// fail early
conf.setMaxMapAttempts(1);
conf.setMaxReduceAttempts(1);
RunningJob job =
UtilsForTests.runJob(conf, new Path(test, "in"), new Path(test, "out"),
1, 1, INPUT);
job.waitForCompletion();
assertTrue("Job failed", job.isSuccessful());
}
}
|
package com.orca.page.objects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.orca.selenium.utils.TestUtils;
public class Support extends BasePageObject {
protected WebDriver driver;
protected SurveySubmenu submenu;
public Support(WebDriver driver) {
submenu = new SurveySubmenu(driver);
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(xpath="//*[@id='support']/input[2]")
private WebElement nextMetric;
@FindBy(xpath="//*[@id='support']/input[3]")
private WebElement goToSummary;
@FindBy(id="commercialSupportSlider")
private WebElement commercialSupportSlider;
@FindBy(id="indemnificationSlider")
private WebElement indemnificationSlider;
@FindBy(id="communitySupportSlider")
private WebElement communitySupportSlider;
public void setMetrics(int xAxis){
TestUtils.slideElement(driver, commercialSupportSlider, xAxis);
TestUtils.slideElement(driver, indemnificationSlider, xAxis);
TestUtils.slideElement(driver, communitySupportSlider, xAxis);
}
public Velocity continueSurvey(){
TestUtils.slideElement(driver, commercialSupportSlider, 200);
TestUtils.slideElement(driver, indemnificationSlider, 100);
TestUtils.slideElement(driver, communitySupportSlider, 200);
nextMetric.click();
return new Velocity(driver);
}
public EvaluationSummary goToSummary(){
goToSummary.click();
return new EvaluationSummary(driver);
}
public SurveySubmenu getSubmenu() {
return submenu;
}
public void setSubmenu(SurveySubmenu submenu) {
this.submenu = submenu;
}
}
|
package io.github.gronnmann.coinflipper.gui.configurationeditor.materials;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import io.github.gronnmann.coinflipper.ConfigManager;
import io.github.gronnmann.coinflipper.customizable.CustomMaterial;
import io.github.gronnmann.coinflipper.customizable.Message;
import io.github.gronnmann.coinflipper.gui.configurationeditor.FileEditSelector;
import io.github.gronnmann.utils.coinflipper.Debug;
import io.github.gronnmann.utils.coinflipper.ItemUtils;
public class MaterialEditor implements Listener{
private MaterialEditor(){}
private static MaterialEditor instance = new MaterialEditor();
public static MaterialEditor getInstance(){
return instance;
}
private Plugin pl;
protected Inventory selectionScreen;
int RELOAD, BACK;
public void setup(Plugin pl){
this.pl = pl;
int howManySlots = 0;
for (CustomMaterial materials : CustomMaterial.values()){
howManySlots++;
}
int size = ((howManySlots/9)+2)*9;
if (size > 54){
size = 54;
}
selectionScreen = Bukkit.createInventory(new MaterialsEditorHolder(), size, "CoinFlipper materials.yml");
RELOAD = size-2;
BACK = size-1;
int index = 0;
for (CustomMaterial materials : CustomMaterial.values()){
String cvars = materials.getPath();
if (index > 54 )return;
Material toUse = materials.getMaterial();
int data = materials.getData();
selectionScreen.setItem(index, ItemUtils.addToLore(ItemUtils.addToLore(ItemUtils.createItem(toUse, ChatColor.GOLD + cvars, data), ChatColor.YELLOW + "Material: " +
ChatColor.GREEN + materials.getMaterial().toString()), ChatColor.YELLOW + "Data: " +
ChatColor.GREEN + materials.getData()+""));
index++;
}
selectionScreen.setItem(RELOAD, ItemUtils.createItem(Material.STAINED_GLASS_PANE, ChatColor.YELLOW.toString() + ChatColor.BOLD + "RELOAD", 4));
selectionScreen.setItem(BACK, ItemUtils.createItem(Material.STAINED_GLASS_PANE, Message.BACK.getMessage(), 14));
}
private void refresh(){
for (ItemStack item : selectionScreen.getContents()){
if (item == null)continue;
if (item.getType().equals(Material.STAINED_GLASS_PANE))continue;
String value = CustomMaterial.fromPath(ChatColor.stripColor(item.getItemMeta().getDisplayName())).getMaterial().toString();
ItemUtils.setLore(item, ChatColor.YELLOW + "Value: " + ChatColor.GREEN + value);
}
}
public void openEditor(Player p){
p.openInventory(selectionScreen);
}
public HashMap<String, CustomMaterial> cvarsEdited = new HashMap<String, CustomMaterial>();
@EventHandler
public void clickDetector(InventoryClickEvent e){
if (e.getClickedInventory() == null)return;
if (!(e.getClickedInventory().getHolder() instanceof MaterialsEditorHolder))return;
e.setCancelled(true);
Player p = (Player)e.getWhoClicked();
if (e.getCurrentItem().getType().equals(Material.AIR))return;
//Reload
if (e.getSlot() == RELOAD){
if (!p.hasPermission("coinflipper.reload")){
p.sendMessage(Message.NO_PERMISSION.getMessage());
return;
}
System.out.println("[CoinFlipper] Attempting to reload CoinFlipper (requested by " + p.getName() + ")");
ConfigManager.getManager().reload();
p.sendMessage(Message.RELOAD_SUCCESS.getMessage());
openEditor(p);
return;
}else if (e.getSlot() == BACK){
FileEditSelector.getInstance().openConfigurator(p);
return;
}
String cvar = ChatColor.stripColor(e.getCurrentItem().getItemMeta().getDisplayName());
String value = e.getCurrentItem().getType().toString();
Debug.print("Editing: " + cvar + ":" + value);
cvarsEdited.put(p.getName(), CustomMaterial.fromPath(cvar));
e.getWhoClicked().sendMessage(Message.CONFIGURATOR_SPEC.getMessage().replace("%CVAR%", e.getCurrentItem().getItemMeta().getDisplayName()));
e.getWhoClicked().closeInventory();
MaterialChooser.getInstance().openEditor(p, cvar);
}
public void processEditing(Player p, ItemStack newValue){
CustomMaterial cvar = cvarsEdited.get(p.getName());
System.out.println("[CoinFlipper] " + p.getName() + " changed material " + cvarsEdited.get(p.getName()) + " value from " +
cvar.getMaterial().toString() + " to " + newValue.getData().toString());
cvar.setMaterial(newValue.getType());
cvar.setData(newValue.getDurability());
Debug.print("Editing cvar: " + cvarsEdited.get(p.getName()) + " Material: " + newValue.getType().toString() + ", Data: " + newValue.getDurability());
setup(pl);
ConfigManager.getManager().saveMaterials();
p.sendMessage(Message.CONFIGURATOR_EDIT_SUCCESSFUL.getMessage().
replace("%VALUE%", newValue.getData().toString()).replace("%CVAR%", cvar.getPath()));
cvarsEdited.remove(p.getName());
refresh();
openEditor(p);
}
@EventHandler
public void cancelDrag(InventoryDragEvent e) {
if (e.getInventory().getHolder() instanceof MaterialsEditorHolder)e.setCancelled(true);
}
}
class MaterialsEditorHolder implements InventoryHolder{
@Override
public Inventory getInventory() {
return null;
}
}
|
package ac.iie.nnts.DDWW;
public class TopkElement {
private long timestamp; //meaning
private int key;//数据项的key
private int sim;//相似性
public TopkElement(long TS,int key,int sim)
{
this.timestamp = TS;
this.key = key;
this.sim = sim;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getSim() {
return sim;
}
public void setSim(int sim) {
this.sim = sim;
}
}
|
package com.pangpang6.books.pattern;
public class Extractor {
public void extract2txt(PdfFile pdfFile) {
System.out.println("Extract PDF.");
}
}
|
package com.vilio.plms.service.query;
import com.vilio.plms.dao.QueryDao;
import com.vilio.plms.exception.ErrorException;
import com.vilio.plms.service.base.BaseService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Map;
/**
* 类名: Plms300060<br>
* 功能:查看逾期记录详细<br>
* 版本: 1.0<br>
* 日期: 2017年7月31日<br>
* 作者: fengliuzhu<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class Plms300060 extends BaseService {
private static final Logger logger = Logger.getLogger(Plms300060.class);
@Resource
QueryDao queryDao;
/**
* 参数验证
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
}
/**
* 业务流程实现
*
* @param head
* @param body
*/
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception {
String repaymentScheduleCode = body.get("repaymentScheduleCode").toString();
//根据还款计划code查找还款计划信息
Map repaymentScheduleInfo = queryDao.queryOverDueRepaymentScheduleDetail(repaymentScheduleCode);
if (StringUtils.isBlank(repaymentScheduleCode) || repaymentScheduleInfo == null || repaymentScheduleInfo.isEmpty()) {
return;
}
//查找还款计划明细(详情)
resultMap.putAll(repaymentScheduleInfo);
}
}
|
package com.tencent.mm.plugin.subapp.ui.pluginapp;
import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.R;
import com.tencent.mm.ax.e;
import com.tencent.mm.bg.d;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.p.a;
import com.tencent.mm.plugin.account.bind.ui.BindMContactIntroUI;
import com.tencent.mm.plugin.account.bind.ui.MobileFriendUI;
import com.tencent.mm.plugin.account.friend.a.l;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.websearch.api.p;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ap;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.ui.MMWizardActivity;
import com.tencent.mm.ui.base.preference.MMPreference;
import com.tencent.mm.ui.base.preference.Preference;
import com.tencent.mm.ui.base.preference.PreferenceInfoCategory;
import com.tencent.mm.ui.base.preference.f;
import com.tencent.mm.ui.e.i;
import java.util.Map;
public class AddMoreFriendsUI extends MMPreference {
private f eOE;
private final int otl = 4;
private final int otm = 9;
public final int Ys() {
return R.o.add_more_friends;
}
public final int getForceOrientation() {
return 1;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initView();
}
public void onResume() {
CharSequence string;
super.onResume();
if (d.QS("brandservice")) {
this.eOE.bw("find_friends_by_web", false);
} else {
this.eOE.bw("find_friends_by_web", true);
}
this.eOE.notifyDataSetChanged();
AddFriendSearchPreference addFriendSearchPreference = (AddFriendSearchPreference) this.eOE.ZZ("find_friends_by_input");
addFriendSearchPreference.otd = getString(R.l.contact_search_account_hint);
addFriendSearchPreference.otf = new 3(this);
PreferenceInfoCategory preferenceInfoCategory = (PreferenceInfoCategory) this.eOE.ZZ("find_friends_info");
String GF = q.GF();
String GG = q.GG();
au.HU();
String Ww = ap.Ww((String) c.DT().get(6, null));
if (!bi.oW(GG)) {
string = getString(R.l.find_friends_my_account, new Object[]{GG});
} else if (!ab.XT(GF)) {
string = getString(R.l.find_friends_my_account, new Object[]{GF});
} else if (bi.oW(Ww)) {
string = getString(R.l.find_friends_my_qrcode);
} else {
string = getString(R.l.find_friends_my_mobile, new Object[]{ap.Wv(Ww)});
}
preferenceInfoCategory.setTitle(string);
preferenceInfoCategory.tgI = R.g.info_qr_code;
4 4 = new 4(this);
preferenceInfoCategory.tDA = 4;
preferenceInfoCategory.tDB = 4;
((AddFriendItemPreference) this.eOE.ZZ("find_friends_create_pwdgroup")).mQk = 8;
Intent intent = new Intent();
intent.setComponent(new ComponentName(i.thA, "com.tencent.mm.booter.MMReceivers$ToolsProcessReceiver"));
intent.putExtra("tools_process_action_code_key", "com.tencent.mm.intent.ACTION_START_TOOLS_PROCESS");
sendBroadcast(intent);
if (this.tCL != null) {
Preference ZZ = this.tCL.ZZ("find_friends_by_web");
if (ZZ != null) {
ZZ.setEnabled(true);
}
}
}
public void onPause() {
super.onPause();
}
public void onDestroy() {
super.onDestroy();
}
public final boolean a(f fVar, Preference preference) {
Intent intent;
if ("find_friends_by_qrcode".equals(preference.mKey)) {
intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 1);
intent.putExtra("GetFriendQRCodeUI.INTENT_FROM_ACTIVITY", 0);
intent.setFlags(65536);
h.mEJ.h(11265, new Object[]{Integer.valueOf(1)});
if (!(a.bx(this) || e.Sz())) {
d.b(this, "scanner", ".ui.BaseScanUI", intent);
}
return true;
} else if ("find_friends_by_other_way".equals(preference.mKey)) {
if (l.XC() != l.a.eKt) {
intent = new Intent(this, BindMContactIntroUI.class);
intent.putExtra("key_upload_scene", 6);
MMWizardActivity.D(this, intent);
return true;
}
startActivity(new Intent(this, MobileFriendUI.class));
return true;
} else if ("find_friends_by_web".equals(preference.mKey)) {
if (p.zO(0)) {
((com.tencent.mm.plugin.websearch.api.i) g.l(com.tencent.mm.plugin.websearch.api.i.class)).a(ad.getContext(), new Runnable() {
public final void run() {
Intent adR = p.adR();
adR.putExtra("KRightBtn", true);
adR.putExtra("ftsneedkeyboard", true);
adR.putExtra("key_load_js_without_delay", true);
adR.putExtra("ftsType", 1);
adR.putExtra("ftsbizscene", 9);
Map b = p.b(9, true, 0);
String zK = p.zK(bi.WU((String) b.get("scene")));
b.put("sessionId", zK);
b.put("subSessionId", zK);
adR.putExtra("sessionId", zK);
adR.putExtra("subSessionId", zK);
adR.putExtra("rawUrl", p.v(b));
Bundle bundle = null;
if (VERSION.SDK_INT >= 21) {
bundle = ActivityOptions.makeSceneTransitionAnimation(AddMoreFriendsUI.this, new Pair[0]).toBundle();
}
d.a(AddMoreFriendsUI.this, "webview", ".ui.tools.fts.FTSSearchTabWebViewUI", adR, bundle);
}
});
preference.setEnabled(false);
} else {
x.e("MicroMsg.AddMoreFriendsUI", "fts h5 template not avail");
}
return true;
} else if ("find_friends_by_radar".equals(preference.mKey)) {
d.A(this, "radar", ".ui.RadarSearchUI");
return true;
} else if ("find_friends_create_pwdgroup".equals(preference.mKey)) {
h.mEJ.h(11140, new Object[]{Integer.valueOf(1)});
d.A(this, "pwdgroup", ".ui.FacingCreateChatRoomAllInOneUI");
return true;
} else if (!"find_friends_by_invite".equals(preference.mKey)) {
return false;
} else {
int intExtra = getIntent().getIntExtra("invite_friend_scene", 4);
h.mEJ.h(14034, new Object[]{Integer.valueOf(intExtra)});
Intent intent2 = new Intent(this, InviteFriendsBy3rdUI.class);
intent2.putExtra("Invite_friends", intExtra);
startActivity(intent2);
return true;
}
}
protected final void initView() {
setMMTitle(R.l.add_more_friends_title);
this.eOE = this.tCL;
AddFriendItemPreference addFriendItemPreference = new AddFriendItemPreference(this.mController.tml);
addFriendItemPreference.setKey("find_friends_by_invite");
addFriendItemPreference.setTitle(R.l.find_friends_by_invite_friend);
int i = R.k.addfriend_icon_invite;
addFriendItemPreference.Hu = i;
Drawable drawable = addFriendItemPreference.mContext.getResources().getDrawable(i);
if ((drawable == null && addFriendItemPreference.hh != null) || !(drawable == null || addFriendItemPreference.hh == drawable)) {
addFriendItemPreference.hh = drawable;
addFriendItemPreference.notifyChanged();
}
addFriendItemPreference.setSummary(R.l.find_friends_by_invite_friend_summary);
if ((bi.getInt(com.tencent.mm.k.g.AT().getValue("InviteFriendsControlFlags"), 0) & 4) > 0) {
this.eOE.a(addFriendItemPreference, 4);
}
setBackBtn(new OnMenuItemClickListener() {
public final boolean onMenuItemClick(MenuItem menuItem) {
AddMoreFriendsUI.this.finish();
return true;
}
});
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
return super.onKeyDown(i, keyEvent);
}
}
|
package com.puti.pachong.parser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.puti.pachong.entity.extract.*;
import com.puti.pachong.entity.pachong.Pachong;
import com.puti.pachong.util.TemplateUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* 对抓取的页面进行解析
*/
@Component
@Slf4j
public class HtmlParser extends ExtractResultParser {
public PaginationResult parse(ExtractPagination pagination) {
log.info("HTML解析器-启动");
PaginationResult paginationResult = new PaginationResult();
Pachong pachong = pagination.getPachong();
paginationResult.setPachong(pachong);
Map<String, String> urlToExtractVal = pagination.getUrlToExtractVal();
int currPage = 0;
for (String originUrl : urlToExtractVal.keySet()) {
currPage++;
log.info("HTML解析器-正在解析:" + originUrl);
String pageContent = urlToExtractVal.get(originUrl);
if (StringUtils.isEmpty(pageContent)) {
continue;
}
ExtractUnit extractUnit = JSON.parseObject(pachong.getExtractUnit(), ExtractUnit.class);
// 如果爬取单元为空,表示不用解析
if (extractUnit == null) {
return PaginationResult.error("抓取单元不能为空");
}
List<ExtractPoint> pointList = extractUnit.getPoints();
ExtractPageResult extractPageResult = new ExtractPageResult();
paginationResult.addPageResult(extractPageResult);
extractPageResult.setCurrPage(currPage);
// 简单判断 返回内容格式
if (pageContent.startsWith("{") || pageContent.startsWith("[")) {
// 说明json
pointList.stream().forEach((e) -> {
String name = e.getName();
String selector = e.getSelector();
Object extract = JSONPath.extract(pageContent, selector);
ExtractUnitResult unitResult = new ExtractUnitResult();
extractPageResult.addUnitResult(unitResult);
// 先不写了 todo 先把悟空问答自动答题写完再说,然后再改这个代码
});
}
Document doc = Jsoup.parse(pageContent);
// key:抓取点所有可能的选择器
// value:该抓取点
Map<List<String>, ExtractPoint> pointSelectorMap = new LinkedHashMap<>();
for (ExtractPoint extractPoint : pointList) {
List<String> realSelectorList = TemplateUtil.parseTemplate(extractPoint.getSelector());
pointSelectorMap.put(realSelectorList, extractPoint);
}
List<List<String>> pointSelectors = new LinkedList<>(pointSelectorMap.keySet());
// 判断每个抓取点对应页面中实际标签的个数是否一致
long count = pointSelectors.stream().map(List::size).distinct().count();
if (count != 1) {
return PaginationResult.error("抓取点个数不一致,选择器对应个数不一致");
}
List<String> orderList = new LinkedList<>();
List<String> selectorList = pointSelectors.get(0);
for (int i = 0; i < selectorList.size(); i++) {
for (int j = 0; j < pointSelectors.size(); j++) {
orderList.add(pointSelectors.get(j).get(i));
}
}
ExtractUnitResult unitResult = new ExtractUnitResult();
for (int i = 0; i < orderList.size(); i++) {
String realSelector = orderList.get(i);
if (i % pointSelectors.size() == 0) {
unitResult = new ExtractUnitResult();
extractPageResult.addUnitResult(unitResult);
log.info("=====================================");
}
ExtractPoint extractPoint = pointSelectorMap.get(pointSelectorMap.keySet().stream().filter((list) -> list.contains(realSelector)).findFirst().orElse(Collections.emptyList()));
ExtractPointResult extractPointResult = new ExtractPointResult();
Element element = doc.selectFirst(realSelector);
String extractVal;
if (element == null) {
extractVal = "空值";
} else {
if (!StringUtils.isEmpty(extractPoint.getAttrName())) {
extractVal = element.attr(extractPoint.getAttrName());
} else {
extractVal = element.text();
}
}
log.info("【" + extractPoint.getName() + "】" + "====>【" + extractVal + "】");
extractPointResult.setName(extractPoint.getName());
extractPointResult.setValue(extractVal);
unitResult.addPointResult(extractPointResult);
}
}
log.info("HTML解析器-结束");
return paginationResult;
}
}
|
package com.github.manage.service.common;
import com.github.manage.form.LoginForm;
import com.github.manage.form.RegisterForm;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;
/**
* @ProjectName: spring-cloud-examples
* @Package: com.github.manage.service.common
* @Description: 登录
* @Author: Vayne.Luo
* @date 2018/12/19
*/
public interface AuthService {
/**
* 用户登录
*/
String doLogin(LoginForm loginForm) throws AuthenticationException;
}
|
package day27_arrays_Part4;
public class Length {
public static void main(String[] args) {
int [][] numbers=
{
{1,2,3}, // row0
{2,3,5,7,89}, // row1
{98,89,78,76,45,98,9}, //row2
{45,54,78,98} // row3
};
System.out.println("Number of the rows: "+ numbers.length);
for(int i=0; i<numbers.length; i++) {
System.out.println("The number of coloums in row "+ i+" is "+ numbers[i].length );
}
for(int i=0; i<numbers.length; i++) {
for( int j=0; j<numbers[i].length; j++) {
System.out.println(numbers[i][j]);
}
}
}
}
|
package com.capgemini.tournament.model;
import com.sun.scenario.animation.AbstractMasterTimer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TeamList {
public static boolean size;
private HashMap list;
// Creates teams and add them to an ArrayList.
public List<Team> teams() {
List<Team> teams = new ArrayList<>();
teams.add(new Team("Utrecht", "Professionals", "sponsor"));
teams.add(new Team("Amsterdam", "Professionals", "sponsor"));
teams.add(new Team("Rotterdam", "Amateurs", "drinkbuddy"));
teams.add(new Team("Den Haag", "Professionals", "sponsor"));
teams.add(new Team("Enschede", "Amateurs", "drinkbuddy"));
teams.add(new Team("Groningen", "Professionals", "sponsor"));
teams.add(new Team("Eindhoven", "Amateurs", "drinkbuddy"));
teams.add(new Team("Maastricht", "Amateurs", "drinkbuddy"));
return teams;
}
}
/**
private void shuffle(List teamList) {
// Size of the list
int totalElements = teamList.size();
// initialize random number generator
Random random = new Random();
for (int loopCounter = 0; loopCounter < totalElements; loopCounter++) {
// get the list element at current index
int currentElement = teamList.get(loopCounter);
// generate a random index within the range of list size
int randomIndex = loopCounter + random.nextInt(totalElements - loopCounter);
// set the element at current index with the element at random
// generated index
list.set(loopCounter, list.get(randomIndex));
// set the element at random index with the element at current loop
// index
list.set(randomIndex, currentElement);
}
}
}
// Here the player can choose its team
public static void playerTeam() {
Scanner reader = new Scanner(System.in);
System.out.println("What is the name of your team?");
String s = reader.next();
reader.close();
}
*/
|
package com.jim.multipos.ui.product_class_new;
import android.os.Bundle;
import com.jim.mpviews.MpToolbar;
import com.jim.multipos.core.SimpleActivity;
import com.jim.multipos.ui.product_class_new.fragments.ProductsClassFragment;
/**
* Created by developer on 17.10.2017.
*/
public class ProductsClassActivity extends SimpleActivity {
ProductsClassFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment = new ProductsClassFragment();
addFragment(fragment);
}
@Override
protected int getToolbar() {
return WITH_TOOLBAR;
}
@Override
protected int getToolbarMode() {
return MpToolbar.DEFAULT_TYPE;
}
@Override
public void onBackPressed() {
fragment.closeAction();
}
}
|
package ru.itis.javalab.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* created: 20-02-2021 - 23:05
* project: SemesterWork
*
* @author dinar
* @version v0.1
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserSignUpForm {
@NotEmpty(message = "")
@Pattern(regexp = "[A-Za-z0-9]{4,8}", message = "")
private String login;
@NotEmpty(message = "")
@Email(message = "")
private String email;
@NotEmpty(message = "")
@Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", message = "")
private String password;
}
|
/**
*
*/
package ucl.cs.testingEmulator.contexNotifierScripts;
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JComponent;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import ucl.cs.testingEmulator.location.TestingLocationProvider;
/**
* @author -Michele Sama- aka -RAX-
*
* University College London
* Dept. of Computer Science
* Gower Street
* London WC1E 6BT
* United Kingdom
*
* Email: M.Sama (at) cs.ucl.ac.uk
*
* Group:
* Software Systems Engineering
*
*/
public class MovementJComponent extends Canvas implements Runnable, PropertyChangeListener{
private static final long serialVersionUID = 1L;
protected int _cursorX=180;
protected int _cursorY=90;
protected int _targetCursorX=180;
protected int _targetCursorY=90;
protected Thread _updateThread;
/**
*
*/
public MovementJComponent() {
super();
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(360, 180);
this.setBackground(new Color(153, 153, 255));
//this.setBorder(BorderFactory.createLineBorder(Color.gray, 2));
this.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent e) {
startUpdating(e.getX(),e.getY());
}
});
}
private synchronized void startUpdating(int newX, int newY)
{
_targetCursorX=newX;
_targetCursorY=newY;
if(this._updateThread==null||this._updateThread.getState()==Thread.State.TERMINATED)
{
this._updateThread=new Thread(this,"MovementJComponent");
this._updateThread.start();
}
}
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.gray);
g.drawLine(this._cursorX-5, this._cursorY, this._cursorX+5, this._cursorY);
g.drawLine(this._cursorX, this._cursorY-5, this._cursorX, this._cursorY+5);
g.setColor(Color.darkGray);
g.drawLine(this._cursorX, this._cursorY, _targetCursorX, _targetCursorY);
g.drawLine(this._targetCursorX-5, this._targetCursorY, this._targetCursorX+5, this._targetCursorY);
g.drawLine(this._targetCursorX, this._targetCursorY-5, this._targetCursorX, this._targetCursorY+5);
}
public void run() {
while(Thread.currentThread()==this._updateThread&&(this._cursorX!=this._targetCursorX||this._cursorY!=this._targetCursorY))
{
if(this._cursorX<this._targetCursorX)
{
this._cursorX++;
}else if(this._cursorX>this._targetCursorX)
{
this._cursorX--;
}
if(this._cursorY<this._targetCursorY)
{
this._cursorY++;
}else if(this._cursorY>this._targetCursorY)
{
this._cursorY--;
}
this.repaint();
TestingLocationProvider.getInstance().setLongitude(this._cursorX-180);
TestingLocationProvider.getInstance().setLatitude(-(this._cursorY-90));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void propertyChange(PropertyChangeEvent evt) {
String action=evt.getPropertyName();
if(action.equals(TestingLocationProvider.LATITUDE_UPDATED))
{
this._cursorY=(int)Math.round(((Double)evt.getNewValue()).doubleValue())-90;
this.repaint();
}else if(action.equals(TestingLocationProvider.LONGITUDE_UPDATED))
{
this._cursorX=(int)Math.round(((Double)evt.getNewValue()).doubleValue())-180;
this.repaint();
}
}
}
|
package algorithm.StringProcessing;
import java.util.LinkedList;
import java.util.Queue;
public class ACAutomaton {
private Node root;
private char base='a';
public ACAutomaton(){
root=new Node();
}
public void put(String pattern){
Node cur=root;
for(int i=0;i<pattern.length();i++)
cur=cur.put(pattern.charAt(i));
cur.endNum++;
}
/**
* 匹配字符串
*/
public void match(String source){
Node p=root,tmp;
for (char value : source.toCharArray()) {
while (!p.contains(value) && p != root) p = p.fail;
p = p.get(value);
if (p == null) p = root;
tmp = p;
while (tmp != root) {
if(tmp.endNum>0) //匹配到模式串
tmp.cnt++;
tmp=tmp.fail;
}
}
}
//生成fail指针
private void buildFailPointer(){
Queue<Node> queue=new LinkedList<>();
Node tmp,t1;
queue.add(root);
while (!queue.isEmpty()){
tmp=queue.poll();
for(char i=base;i<=base+25;i++){
if(tmp.contains(i)){
if(tmp==root) tmp.get(i).fail=root;
else { //与kmp的next数组求法相同
t1=tmp.fail;
while(t1!=null&&!t1.contains(i))
t1=t1.fail;
if(t1!=null)tmp.get(i).fail=t1.get(i);
else tmp.get(i).fail=root;
}
queue.add(tmp.get(i));
}
}
}
}
public class Node{
private Node fail;
private int endNum=0,cnt=0;
private Node[]next=new Node[26];
public Node get(char c){
return next[c-base];
}
public Node put(char c){
if(next[c-base]==null) next[c-base]=new Node();
return next[c-base];
}
public int getCount(){
return cnt;
}
public boolean contains(char c) {
return next[c-base]!=null;
}
}
}
|
/*
Készítsünk egy Calculator programot, mely egy számsorozatot és egy számot kap argumentumként. A program a számsorozat minden eleméhez hozzáadja a második argumentumot. Például:
$ java Calculator 1,2,3 5
[6 7 8]
*/
import util.IntVector;
class Calculator {
public static void main(String[] args) {
String[] nums = args[0].split(","); // nums -> "1", "2", "3"
int[] nums2 = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
nums2[i] = Integer.parseInt(nums[i]);
} // nums2 -> 1, 2, 3
int n = Integer.parseInt(arrgs[1]);
IntVector v = new IntVector(nums2);
v.add(n);
System.out.println(v);
}
}
|
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Random rd = new Random();
Link link = new Link();
List list = new List();
link = list.CreateNode();
for (int i = 0; i < 5; i++) {
list.AddNode(link, rd.nextInt(100)+1);
} list.PrintNode(link);
System.out.println("\nCount : " + list.CountNode(link));
int count = 0;
System.out.println("**Search**");
System.out.print("DATA : ");
count = list.SearchNode(link, sc.nextInt());
System.out.println("Search Number : " + count);
int data = 0;
int val = 0;
System.out.println("**NextInsert**");
System.out.print("Search : "); data = sc.nextInt();
System.out.print("Updata val : "); val = sc.nextInt();
list.NextInsertNode(link, data, val);
list.PrintNode(link);
System.out.println("\n**PrevioustInsert**");
System.out.print("Search : "); data = sc.nextInt();
System.out.print("Updata val : "); val = sc.nextInt();
list.PreviousInsertNode(link, data, val);
list.PrintNode(link);
System.out.println("\n**Delete**");
System.out.print("Delete val : "); data = sc.nextInt();
list.DeleteNode(link, data);
list.PrintNode(link);
System.out.println("\n**Reverse**");
list.ReverseNode(link);
list.PrintNode(link);
System.out.println("\n**Sort**");
list.SortNode(link);
list.PrintNode(link);
}
}
|
package cn.ck.service.impl;
import cn.ck.entity.Bidding;
import cn.ck.mapper.BiddingMapper;
import cn.ck.service.BiddingService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ${author}
* @since 2018-09-21
*/
@Service
public class BiddingServiceImpl extends ServiceImpl<BiddingMapper, Bidding> implements BiddingService {
}
|
package com.vetroumova.sixjars.database;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
import com.vetroumova.sixjars.R;
import com.vetroumova.sixjars.app.Prefs;
import com.vetroumova.sixjars.model.Cashflow;
import com.vetroumova.sixjars.model.Jar;
import com.vetroumova.sixjars.model.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import io.realm.internal.IOException;
/**
* Created by OLGA on 11.09.2016.
*/
public class RealmManager {
/*private static final File EXPORT_REALM_PATH = Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOCUMENTS);*/
private static final File EXPORT_REALM_PATH = new File(Environment.getExternalStorageDirectory()
+ "/SixJars");
private static final String EXPORT_REALM_FILE_NAME = "backup_sixjars.realm";
private static final String IMPORT_REALM_FILE_NAME = Realm.DEFAULT_REALM_NAME;
private static final String TAG = "VOlga";
//from Realm
private static RealmManager realmManagerInstance;
private Realm realm;
public RealmManager(Application application) {
realm = Realm.getDefaultInstance();
realm.setAutoRefresh(true);
}
public static RealmManager with(Fragment fragment) {
if (realmManagerInstance == null) {
realmManagerInstance = new RealmManager(fragment.getActivity().getApplication());
}
return realmManagerInstance;
}
public static RealmManager with(Activity activity) {
if (realmManagerInstance == null) {
realmManagerInstance = new RealmManager(activity.getApplication());
}
return realmManagerInstance;
}
public static RealmManager with(Application application) {
if (realmManagerInstance == null) {
realmManagerInstance = new RealmManager(application);
}
return realmManagerInstance;
}
public static RealmManager getInstance() {
return realmManagerInstance;
}
@NonNull
public static void initialiseJars(final Context context) {
final Realm realm = RealmManager.getInstance().getRealm();
realm.executeTransactionAsync(realm1 -> {
realm1.where(User.class).findAll().deleteAllFromRealm();
realm1.where(Jar.class).findAll().deleteAllFromRealm();
realm1.where(Cashflow.class).findAll().deleteAllFromRealm();
User user = new User();
//todo work with multiple users
user.setLogin("test");
//for backup without sharedprefs export/import
Prefs.with(context).setPrefUser(user.getLogin());
Jar jar = new Jar();
jar.setJar_id(context.getResources().getString(R.string.db_jar_id_NEC));
jar.setJar_float_id(0f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_NEC));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_NEC));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
jar = new Jar();
jar.setJar_id(context.getResources().getString(R.string.db_jar_id_PLAY));
jar.setJar_float_id(1f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_PLAY));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_PLAY));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
jar = new Jar();
jar.setJar_id(context.getResources().getString(R.string.db_jar_id_GIVE));
jar.setJar_float_id(2f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_GIVE));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_GIVE));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
jar = new Jar();
jar.setJar_id("EDU");
jar.setJar_float_id(3f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_EDU));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_EDU));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
jar = new Jar();
jar.setJar_id(context.getResources().getString(R.string.db_jar_id_LTSS));
jar.setJar_float_id(4f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_LTSS));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_LTSS));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
jar = new Jar();
jar.setJar_id(context.getResources().getString(R.string.db_jar_id_FFA));
jar.setJar_float_id(5f);
jar.setJar_name(context.getResources().getString(R.string.db_jar_name_FFA));
jar.setJar_info(context.getResources().getString(R.string.db_jar_info_FFA));
jar.setUser(user);
realm1.copyToRealmOrUpdate(jar);
});
}
public static void setUserPrefsFromSharedPrefs(Context context, User user) {
final Realm realm = RealmManager.getInstance().getRealm();
realm.executeTransaction(realm1 -> {
Prefs prefs = Prefs.with(context);
user.setLanguage(prefs.getPrefLanguage());
user.setPreLoad(prefs.getPreLoad());
user.setNecPerc(prefs.getPercentJar("NEC"));
user.setPlayPerc(prefs.getPercentJar("PLAY"));
user.setGivePerc(prefs.getPercentJar("GIVE"));
user.setEduPerc(prefs.getPercentJar("EDU"));
user.setLtssPerc(prefs.getPercentJar("LTSS"));
user.setFfaPerc(prefs.getPercentJar("FFA"));
user.setNecMaxVolume(prefs.getMaxVolumeJar("NEC"));
user.setPlayMaxVolume(prefs.getMaxVolumeJar("PLAY"));
user.setGiveMaxVolume(prefs.getMaxVolumeJar("GIVE"));
user.setEduMaxVolume(prefs.getMaxVolumeJar("EDU"));
user.setLtssMaxVolume(prefs.getMaxVolumeJar("LTSS"));
user.setFfaMaxVolume(prefs.getMaxVolumeJar("FFA"));
Log.d("VOlga", "perc " + prefs.getPercentJar("NEC"));
Log.d("VOlga", "perc " + prefs.getPercentJar("PLAY"));
Log.d("VOlga", "perc " + prefs.getPercentJar("GIVE"));
Log.d("VOlga", "perc " + prefs.getPercentJar("EDU"));
Log.d("VOlga", "perc " + prefs.getPercentJar("LTSS"));
Log.d("VOlga", "perc " + prefs.getPercentJar("FFA"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("NEC"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("PLAY"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("GIVE"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("EDU"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("LTSS"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("FFA"));
Log.d("VOlga", prefs.getPrefLanguage());
Log.d("VOlga", "restore " + prefs.getPrefRestoreMark());
Log.d("VOlga", "perc " + user.getNecPerc());
Log.d("VOlga", "perc " + user.getPlayPerc());
Log.d("VOlga", "perc " + user.getGivePerc());
Log.d("VOlga", "perc " + user.getEduPerc());
Log.d("VOlga", "perc " + user.getLtssPerc());
Log.d("VOlga", "perc " + user.getFfaPerc());
Log.d("VOlga", "max " + user.getNecMaxVolume());
Log.d("VOlga", "max " + user.getPlayMaxVolume());
Log.d("VOlga", "max " + user.getGiveMaxVolume());
Log.d("VOlga", "max " + user.getEduMaxVolume());
Log.d("VOlga", "max " + user.getLtssMaxVolume());
Log.d("VOlga", "max " + user.getFfaMaxVolume());
Log.d("VOlga", user.getLanguage());
});
}
public static void loadUserPrefsToSharedPrefs(Context context, User user) {
Prefs prefs = Prefs.with(context);
if (user.getLanguage() != null) {
prefs.setPrefLanguage(user.getLanguage());
prefs.setPreLoad(true);
} else {
prefs.setPrefLanguage("default"); //todo check
}
List<Integer> percentageList = Arrays.asList(user.getNecPerc(), user.getPlayPerc(),
user.getGivePerc(), user.getEduPerc(), user.getLtssPerc(), user.getFfaPerc());
prefs.setPercentage(percentageList);
//change a max volumes for bottles from user data
float[] sums = {user.getNecMaxVolume(), user.getPlayMaxVolume(), user.getGiveMaxVolume(),
user.getEduMaxVolume(), user.getLtssMaxVolume(), user.getFfaMaxVolume()};
Prefs.with(context).setMaxVolumes(sums);
Log.d("VOlga", "perc " + prefs.getPercentJar("NEC"));
Log.d("VOlga", "perc " + prefs.getPercentJar("PLAY"));
Log.d("VOlga", "perc " + prefs.getPercentJar("GIVE"));
Log.d("VOlga", "perc " + prefs.getPercentJar("EDU"));
Log.d("VOlga", "perc " + prefs.getPercentJar("LTSS"));
Log.d("VOlga", "perc " + prefs.getPercentJar("FFA"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("NEC"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("PLAY"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("GIVE"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("EDU"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("LTSS"));
Log.d("VOlga", "max " + prefs.getMaxVolumeJar("FFA"));
Log.d("VOlga", prefs.getPrefLanguage());
Log.d("VOlga", "restore " + prefs.getPrefRestoreMark());
Log.d("VOlga", "perc " + user.getNecPerc());
Log.d("VOlga", "perc " + user.getPlayPerc());
Log.d("VOlga", "perc " + user.getGivePerc());
Log.d("VOlga", "perc " + user.getEduPerc());
Log.d("VOlga", "perc " + user.getLtssPerc());
Log.d("VOlga", "perc " + user.getFfaPerc());
Log.d("VOlga", "max " + user.getNecMaxVolume());
Log.d("VOlga", "max " + user.getPlayMaxVolume());
Log.d("VOlga", "max " + user.getGiveMaxVolume());
Log.d("VOlga", "max " + user.getEduMaxVolume());
Log.d("VOlga", "max " + user.getLtssMaxVolume());
Log.d("VOlga", "max " + user.getFfaMaxVolume());
Log.d("VOlga", user.getLanguage());
}
public void changeUserPassword(User user, String newPass) {
realm.beginTransaction();
user.setPassword(newPass);
realm.commitTransaction();
}
/**
* localisation name
*/
public void changeJarName(Jar jar, String newName) {
realm.beginTransaction();
jar.setJar_name(newName);
realm.commitTransaction();
}
public void setRealm() {
realm = Realm.getDefaultInstance();
realm.setAutoRefresh(true);
}
public void backup(Context context) {
boolean isPresent = true;
if (!EXPORT_REALM_PATH.exists()) {
isPresent = EXPORT_REALM_PATH.mkdir();
}
if (isPresent) {
try {
// create a backup file
File exportRealmFile = new File(EXPORT_REALM_PATH, EXPORT_REALM_FILE_NAME);
// if backup file already exists, delete it
exportRealmFile.delete();
// copy current realm to backup file
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
String msg = context.getString(R.string.db_saved_text) + EXPORT_REALM_PATH + "/"
+ EXPORT_REALM_FILE_NAME /*+ context.getString(R.string.prefs_saved_text) +
EXPORT_REALM_PATH + "/" + EXPORT_PREFS_FILE_NAME*/;
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Log.d(TAG, msg);
} else {
// Failure to find a directory
Log.d(TAG, "Failure to find a directory");
}
}
public void restore(Context context) {
String restoreFilePath = EXPORT_REALM_PATH + "/" + EXPORT_REALM_FILE_NAME;
Log.d(TAG, "oldFilePath = " + restoreFilePath);
File file = new File(restoreFilePath);
if (file.exists() && file.isFile()) {
copyBundledRealmFile(context, restoreFilePath, IMPORT_REALM_FILE_NAME);
Log.d(TAG, "DB restore is done");
Toast.makeText(context, R.string.db_restore_done_text, Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "DB Restore file is not found");
Toast.makeText(context, context.getString(R.string.restore_not_found), Toast.LENGTH_SHORT).show();
}
}
private String copyBundledRealmFile(Context context, String restoreFilePath, String outFileName) {
realm.close();
try {
try {
File file = new File(context.getFilesDir(), outFileName);
FileOutputStream outputStream = new FileOutputStream(file);
FileInputStream inputStream = new FileInputStream(new File(restoreFilePath));
byte[] buf = new byte[1024];
int bytesRead;
try {
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
outputStream.close();
inputStream.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
setRealm();
return null;
}
//export by email
public void exportDatabase(Activity activity) {
File exportRealmFile = null;
try {
// get or create an export.realm" file
exportRealmFile = new File(activity.getExternalCacheDir(), "export.realm");
// if "export.realm" already exists, delete
exportRealmFile.delete();
// copy current realm to "export.realm"
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Uri> arrayUri = new ArrayList<>();
Uri realmUri = Uri.fromFile(exportRealmFile);
if (realmUri != null) {
arrayUri.add(realmUri);
}
// init email intent and add export.realm as attachment
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, activity.getString(R.string.export_mail_text));
intent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.export_subject_text));
intent.putExtra(Intent.EXTRA_TEXT, activity.getString(R.string.export_message_text));
if (arrayUri.isEmpty()) {
//Send email without file attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
} else if (arrayUri.size() == 1) {
//Send email with ONE file attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("plain/*");
} else {
//Send email with MULTI files attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("plain/*");
}
// start email intent
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.send_base_text)));
}
public Realm getRealm() {
if (realm.isClosed()) {
setRealm();
}
return realm;
}
/**
* find all objects in the Jar.class
*/
public RealmResults<Jar> getJars() {
return realm.where(Jar.class).findAll();
}
/**
* query a single item with the given id
*/
public Jar getJar(String id) {
Jar jar = new Jar();
try {
jar = realm.where(Jar.class).equalTo("jar_id", id).findFirst();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return jar;
}
public boolean editCashflow(long cashID, Date newDate, float newSum, String description, String jarID) {
Cashflow oldCashflow = realm.where(Cashflow.class).equalTo("id", cashID).findFirst();
Cashflow newCashflow = new Cashflow();
Jar oldJar = oldCashflow.getJar();
Jar newJar = realm.where(Jar.class).equalTo("jar_id", jarID).findFirst();
newCashflow.setId(cashID);
//TODO if date is less than first income - how to correct
newCashflow.setDate(newDate);
newCashflow.setSum(newSum);
newCashflow.setCurrpercent(oldCashflow.getCurrpercent());
newCashflow.setDescription(description);
newCashflow.setPhoto("");
newCashflow.setJar(newJar);
if (newJar.equals(oldJar)) {
//check for negatives
if ((oldJar.getTotalCash() - oldCashflow.getSum() + newSum) < 0) {
return false;
} else {
realm.beginTransaction();
realm.copyToRealmOrUpdate(newCashflow);
realm.commitTransaction();
checkSumTotalInJar(oldJar.getJar_id());
return true;
}
}
//if different jars
else {
if ((oldJar.getTotalCash() - oldCashflow.getSum()) < 0 || (newJar.getTotalCash() + newSum) < 0) {
return false;
} else {
realm.beginTransaction();
realm.copyToRealmOrUpdate(newCashflow);
realm.commitTransaction();
checkSumTotalInJar(oldJar.getJar_id());
checkSumTotalInJar(newJar.getJar_id());
return true;
}
}
}
public Cashflow getCashflowByID(long cashID) {
return realm.where(Cashflow.class)
.equalTo("id", cashID)
.findFirst();
}
public RealmResults<Cashflow> getCashflowInJar(String jarID) {
//one month back
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(Calendar.MONTH, -3);
return realm.where(Cashflow.class)
.equalTo("jar.jar_id", jarID)
.greaterThan("date", new Date(calendar.getTimeInMillis()))
//.findAllSortedAsync("date", Sort.DESCENDING);
.findAllSorted("date", Sort.DESCENDING);
}
public RealmResults<Cashflow> getCashflowInJarFromDate(String jarID, Date startDate, Date endDate) {
return realm.where(Cashflow.class)
//.greaterThanOrEqualTo("date", fromDayToNow)
.between("date", startDate, endDate)
.equalTo("jar.jar_id", jarID)
.findAllSorted("date", Sort.DESCENDING);
}
public RealmResults<Cashflow> getCashflowsFromDate(Date startDate, Date endDate) {
return realm.where(Cashflow.class)
//.greaterThanOrEqualTo("date", fromDayToNow)
.between("date", startDate, endDate)
.findAllSorted("date", Sort.DESCENDING);
}
public void clearAllCashflow() {
realm.delete(Cashflow.class);
}
public boolean deleteCashflow(long cashflowID) {
Cashflow cash = realm.where(Cashflow.class).equalTo("id", cashflowID).findFirst();
float cashInJar = cash.getJar().getTotalCash();
if (cashInJar - cash.getSum() < 0) {
return false;
} else {
realm.beginTransaction();
Jar currentJar = cash.getJar();
cash.deleteFromRealm();
realm.commitTransaction();
checkSumTotalInJar(currentJar.getJar_id());
return true;
}
}
public float checkSumTotalInJar(String jarID) {
Jar jar = realm.where(Jar.class)
.equalTo("jar_id", jarID).findFirst();
double cashflowsInJar = (double) realm.where(Cashflow.class)
.equalTo("jar.jar_id", jar.getJar_id())
.findAll().sum("sum");
realm.beginTransaction();
//set field in jar
jar.setTotalCash(((float) cashflowsInJar));
realm.commitTransaction();
return jar.getTotalCash();
}
public boolean addCashToJar(String jarID, float cashSum, Date date, int currPerc, String description) {
Jar jar = realm.where(Jar.class).equalTo("jar_id", jarID).findFirst();
//check for negative sum and rest in jar
if ((jar.getTotalCash() + cashSum) < 0) {
return false;
} else {
realm.beginTransaction();
long id = realmManagerInstance.getJars().size() + System.currentTimeMillis();
Cashflow cashflow = realm.createObject(Cashflow.class, id);
//TODO path of photo
cashflow.setDate(date);
cashflow.setSum(cashSum);
cashflow.setCurrpercent(currPerc);
cashflow.setDescription(description);
cashflow.setPhoto("");
cashflow.setJar(jar);
Log.d("VOlga", "New Cash : " + cashflow.getId() + ", " + cashflow.getDate() + ", "
+ cashflow.getSum() + ", " + cashflow.getCurrpercent());
realm.commitTransaction();
realm.beginTransaction();
float currTotal = realm.where(Jar.class)
.equalTo("jar_id", jarID)
.findFirst().getTotalCash();
realm.commitTransaction();
realm.beginTransaction();
realm.where(Jar.class)
.equalTo("jar_id", jarID)
.findFirst().setTotalCash(currTotal + cashSum);
realm.commitTransaction();
return true;
}
}
}
|
package br.com.tomioka.vendashortalicas.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
public class Pedido implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne @JoinColumn(name = "cliente_id")
private Cliente cliente;
@JsonIgnore // evita serialização cíclica
@OneToMany(mappedBy = "id.pedido")
private Set<ItemPedido> produtosPedidos = new HashSet<>();
public Pedido() {
}
public Pedido(Long id, Set<ItemPedido> produtos, BigDecimal totalPedido, Cliente cliente) {
this.id = id;
this.produtosPedidos = produtos;
this.cliente = cliente;
}
@Transient
public BigDecimal getPrecoTotalDoPedido() {
BigDecimal total = new BigDecimal("0");
Set<ItemPedido> produtosPedidos = getProdutosPedidos();
for (ItemPedido itemPedido : produtosPedidos) {
total = total.add(itemPedido.getSubTotal());
}
return total;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<ItemPedido> getProdutosPedidos() {
return produtosPedidos;
}
public void setProdutosPedidos(Set<ItemPedido> produtos) {
this.produtosPedidos = produtos;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
}
|
package net.minecraft.entity.ai;
import com.google.common.collect.Lists;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.pathfinding.Path;
import net.minecraft.pathfinding.PathNavigateGround;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.village.Village;
import net.minecraft.village.VillageDoorInfo;
public class EntityAIMoveThroughVillage extends EntityAIBase {
private final EntityCreature theEntity;
private final double movementSpeed;
private Path entityPathNavigate;
private VillageDoorInfo doorInfo;
private final boolean isNocturnal;
private final List<VillageDoorInfo> doorList = Lists.newArrayList();
public EntityAIMoveThroughVillage(EntityCreature theEntityIn, double movementSpeedIn, boolean isNocturnalIn) {
this.theEntity = theEntityIn;
this.movementSpeed = movementSpeedIn;
this.isNocturnal = isNocturnalIn;
setMutexBits(1);
if (!(theEntityIn.getNavigator() instanceof PathNavigateGround))
throw new IllegalArgumentException("Unsupported mob for MoveThroughVillageGoal");
}
public boolean shouldExecute() {
resizeDoorList();
if (this.isNocturnal && this.theEntity.world.isDaytime())
return false;
Village village = this.theEntity.world.getVillageCollection().getNearestVillage(new BlockPos((Entity)this.theEntity), 0);
if (village == null)
return false;
this.doorInfo = findNearestDoor(village);
if (this.doorInfo == null)
return false;
PathNavigateGround pathnavigateground = (PathNavigateGround)this.theEntity.getNavigator();
boolean flag = pathnavigateground.getEnterDoors();
pathnavigateground.setBreakDoors(false);
this.entityPathNavigate = pathnavigateground.getPathToPos(this.doorInfo.getDoorBlockPos());
pathnavigateground.setBreakDoors(flag);
if (this.entityPathNavigate != null)
return true;
Vec3d vec3d = RandomPositionGenerator.findRandomTargetBlockTowards(this.theEntity, 10, 7, new Vec3d(this.doorInfo.getDoorBlockPos().getX(), this.doorInfo.getDoorBlockPos().getY(), this.doorInfo.getDoorBlockPos().getZ()));
if (vec3d == null)
return false;
pathnavigateground.setBreakDoors(false);
this.entityPathNavigate = this.theEntity.getNavigator().getPathToXYZ(vec3d.xCoord, vec3d.yCoord, vec3d.zCoord);
pathnavigateground.setBreakDoors(flag);
return (this.entityPathNavigate != null);
}
public boolean continueExecuting() {
if (this.theEntity.getNavigator().noPath())
return false;
float f = this.theEntity.width + 4.0F;
return (this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) > (f * f));
}
public void startExecuting() {
this.theEntity.getNavigator().setPath(this.entityPathNavigate, this.movementSpeed);
}
public void resetTask() {
if (this.theEntity.getNavigator().noPath() || this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) < 16.0D)
this.doorList.add(this.doorInfo);
}
private VillageDoorInfo findNearestDoor(Village villageIn) {
VillageDoorInfo villagedoorinfo = null;
int i = Integer.MAX_VALUE;
for (VillageDoorInfo villagedoorinfo1 : villageIn.getVillageDoorInfoList()) {
int j = villagedoorinfo1.getDistanceSquared(MathHelper.floor(this.theEntity.posX), MathHelper.floor(this.theEntity.posY), MathHelper.floor(this.theEntity.posZ));
if (j < i && !doesDoorListContain(villagedoorinfo1)) {
villagedoorinfo = villagedoorinfo1;
i = j;
}
}
return villagedoorinfo;
}
private boolean doesDoorListContain(VillageDoorInfo doorInfoIn) {
for (VillageDoorInfo villagedoorinfo : this.doorList) {
if (doorInfoIn.getDoorBlockPos().equals(villagedoorinfo.getDoorBlockPos()))
return true;
}
return false;
}
private void resizeDoorList() {
if (this.doorList.size() > 15)
this.doorList.remove(0);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\entity\ai\EntityAIMoveThroughVillage.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package my.battleships;
import my.battleships.Players.ComputerPlayer;
import my.battleships.Players.Player;
import my.battleships.ships.ShipTypes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;
public class ConsoleHelper implements Observer{
public static final String letters = " a b c d e f g h i j";
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private Battleships game;
ConsoleHelper(Battleships game) {
this.game = game;
}
//write message with new line (NL)
public static void writeMessageNL(Object message) {
System.out.println(message);
}
//write message without new line
public static void writeMessage(Object message) {
System.out.print(message);
}
public static String readString() {
String readString = null;
try {
readString = bufferedReader.readLine();
} catch (IOException e) {
writeMessageNL("FATAL ERROR " + Thread.currentThread().getName() + " : " + e.getMessage());
e.printStackTrace();
}
return readString;
}
void printGame() {
printGame(null);
}
void printGame(String message) {
writeMessageNL("\n\n " + letters + " " + letters);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
writeMessage(' ');
if(j == 10) writeMessage(" ");
if(j==0 || j == 10) writeMessage(i + " ");
if(j < 10) game.getHumanPlayer().getGameField().getFieldCell(i, j).print();
else game.getComputerPlayer().getGameField().getFieldCell(i, j-10).print();
}
writeMessageNL("");
}
if (message != null) writeMessageNL("\n" + message);
}
public void update(Observable o, Object arg) {
if (arg != null) printGame("\n"+((Player)o).getName() + ", " + arg);
else printGame();
if (o instanceof ComputerPlayer) pause();
}
static void pause(){
ConsoleHelper.writeMessageNL("Enter - continue");
ConsoleHelper.readString();
}
static boolean askPlayerAboutHisOwnShipInstallation(){
writeMessageNL("Do you want to setup your ships by yourself? Y/y - for \"yes\"");
if (readString().matches("[Yy].*")) return true;
return false;
}
static void winMessageAndCloseTheProgram(String playersName){
writeMessageNL("GAME OVER! " + playersName + " WIN!");
System.exit(0);
}
public static void messageForShipsSetup(ShipTypes shipType){
writeMessageNL("\nOk, " + shipType.getName()+ " will be at... \n" +
"(\"d3\" - on \"d3\" will be head, default direction is horizontal, \"d3v\" for vertical)");
}
}
|
package org.a55889966.bleach.saran.tourguide;
/**
* Created by Nizam Uddin Shamrat on 1/30/2018.
*/
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.BookListViewHolder> {
private Context context;
private ArrayList<EventClass> events;
private clickListener listener;
public EventAdapter(Context context, ArrayList<EventClass> events,clickListener listener) {
this.context = context;
this.events = events;
this.listener = listener;
}
@Override
public BookListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.event_single_row,parent,false);
return new BookListViewHolder(view);
}
@Override
public void onBindViewHolder(BookListViewHolder holder, int position) {
EventClass eventClass=events.get(position);
holder.eventNameTv.setText(eventClass.getEventName());
holder.createdDateTv.setText("Created Date: "+eventClass.getStartedDate());
holder.departureDateTv.setText("Starting Date: "+eventClass.getDepartureDate());
int daysLeft = eventClass.getDaysLeft();
if (daysLeft>0){
holder.daysLeftTv.setText(String.valueOf(eventClass.getDaysLeft())+" days Left");
}
else {
holder.daysLeftTv.setText("Event has already started");
}
}
@Override
public int getItemCount() {
return events.size();
}
public class BookListViewHolder extends RecyclerView.ViewHolder {
TextView eventNameTv;
TextView createdDateTv;
TextView departureDateTv;
TextView daysLeftTv;
public BookListViewHolder(View itemView) {
super(itemView);
eventNameTv=itemView.findViewById(R.id.eventNameTv);
createdDateTv=itemView.findViewById(R.id.createdDateTv);
departureDateTv =itemView.findViewById(R.id.departureDateTv);
daysLeftTv = itemView.findViewById(R.id.daysLeftTv);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onClickEvent(events.get(getAdapterPosition()));
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
listener.onLogClickEvent(events.get(getAdapterPosition()));
return true;
}
});
}
}
public void Update(ArrayList<EventClass> events){
this.events=events;
notifyDataSetChanged();
}
public interface clickListener{
void onClickEvent(EventClass eventClass);
void onLogClickEvent(EventClass eventClass);
}
}
|
package main;
import java.awt.*;
import java.util.ArrayList;
import java.util.Stack;
public class Board {
public static int sizeX = 20;
public static int sizeY = 20;
public enum Square {
HIT,
NOTHIT
}
private Square[][] squares;
private Stack<Move> moves;
Board(){
squares = new Square[sizeX][sizeY];
for (int y = 0; y < sizeY; y++){
for (int x = 0; x < sizeX; x++){
squares[x][y] = Square.NOTHIT;
}
}
}
public Square getSquare(int x, int y){
if (x < 0 || x > squares[1].length || y < 0 || y > squares[0].length){
return null;
} else {
return squares[x][y];
}
}
static boolean checkValidPoints(ArrayList<Point> points){
for (Point p : points){
if (!( p.x >= 0 && p.x <= sizeX && p.y >= 0 && p.y <= sizeY)) { return false; }
}
return true;
}
}
|
/**
* This class is a adapted portion of the original Python code globalmaptiles.py created by Klokan Petr Pridal on 2008-07-03.
*
*
*
* @author Ricardo Pontes Bonfiglioli
*
*/
/*!
* Copyright (c) 2008 Klokan Petr Pridal. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*/
package br.org.funcate.glue.model.canvas;
import br.org.funcate.glue.utilities.PropertiesReader;
public abstract class GlobalMapTiles {
public static final int TILE_SIZE = PropertiesReader.getIntegerProperty("tile.size");
private static final double INITIAL_RESOLUTION;
private static final double ORIGIN_SHIFT;
/**
* Inicialize the TMS Global Mercator pyramid
*/
static {
double constValue = 2 * Math.PI * 6378137;
INITIAL_RESOLUTION = constValue / TILE_SIZE;
ORIGIN_SHIFT = constValue / 2.0;
}
/**
* Returns resolution (meters/pixel) for a given zoom level (measured at
* Equator)
*
* @param zoomLevel
* @return
*/
private static double getResolution(int zoomLevel) {
return INITIAL_RESOLUTION / Math.pow(2, zoomLevel);
}
/**
* Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84
* Datum
*
* @param mx
* @param my
* @return
*/
private static double[] convertMetersToLatLong(double mx, double my) {
double lon = (mx / ORIGIN_SHIFT) * 180.0;
double lat = (my / ORIGIN_SHIFT) * 180.0;
lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0);
return new double[] { lat, lon };
}
/**
* Converts pixel coordinates in given zoom level of pyramid to EPSG:900913
*
* @param px
* @param py
* @param zoomLevel
* @return
*/
private static double[] convertPixelsToMeters(double px, double py, int zoomLevel) {
double resolution = getResolution(zoomLevel);
double mx = px * resolution - ORIGIN_SHIFT;
double my = py * resolution - ORIGIN_SHIFT;
return new double[] { mx, my };
}
/**
* Returns bounds of the given tile in EPSG:900913 coordinates
*
* @param tx
* @param ty
* @param zoomLevel
* @return
*/
private static double[] getTileBounds(int tx, int ty, int zoomLevel) {
int xPosition = tx * TILE_SIZE;
int yPosition = ty * TILE_SIZE;
double[] minPoint = convertPixelsToMeters(xPosition, yPosition, zoomLevel);
double[] maxPoint = convertPixelsToMeters(xPosition + TILE_SIZE, yPosition + TILE_SIZE, zoomLevel);
return new double[] { minPoint[0], minPoint[1], maxPoint[0], maxPoint[1] };
}
/**
* Returns bounds of the given tile in latitude/longitude using WGS84 datum
*
* @param tx
* @param ty
* @param zoomLevel
* @return
*/
private static double[] getTileLatLongBounds(int tx, int ty, int zoomLevel) {
double[] bounds = getTileBounds(tx, ty, zoomLevel);
double[] minLatLong = convertMetersToLatLong(bounds[0], bounds[1]);
double[] maxLatLong = convertMetersToLatLong(bounds[2], bounds[3]);
return new double[] { minLatLong[0], minLatLong[1], maxLatLong[0], maxLatLong[1] };
}
// /**
// * Converts TMS tile coordinates to Google Tile coordinates
// *
// * @param tx
// * @param ty
// * @param zoomLevel
// * @return
// */
// private static int[] getGoogleTile (int tx, int ty, int zoomLevel) {
// return new int[] {tx, (int) Math.round((Math.pow(2, zoomLevel) - 1) -
// ty)};
// }
/**
* Returns latitude/longitude of a given tile
*
* @param tx
* @param ty
* @param zoomLevel
* @return
*/
public static double[] getTileLatLongCenter(int tx, int ty, int zoomLevel) {
double[] tileLatLongBounds = getTileLatLongBounds(tx, ty, zoomLevel);
return new double[] { ((tileLatLongBounds[0] + tileLatLongBounds[2]) / 2) * (-1), (tileLatLongBounds[1] + tileLatLongBounds[3]) / 2 };
}
}
|
package rabaty;
import rabatlosowy.LosowyRabat;
public class AdapterRabatuKlasowy extends LosowyRabat implements IObliczCenePoRabacie {
@Override
public double obliczCenePoRabacie(double cena) {
return cena-this.losujRabat();
}
}
|
package org.shadow.service.impl;
import org.shadow.dao.LoginMapper;
import org.shadow.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginMapper loginMapper;
@Override
public boolean verity(String name, String password) {
if (loginMapper.verify(name, password) == 1) {
return true;
}
return false;
}
}
|
package com.dais.service;
import com.common.pojo.ResultModel;
import com.dais.model.Fees;
import java.util.List;
/**
* @author xxp
* @version 2017- 09- 09 18:14
* @description
* @copyright www.zhgtrade.com
*/
public interface FeesService {
int insert(Fees fees);
int update(Fees fees);
ResultModel selectFees(int start, int limit, String search);
List<Fees> selectFees();
Fees selectFees(int symbol);
}
|
package com.module.controllers.veterandialog.tabs;
import com.module.controllers.veterandialog.tables.AddDocumentController;
import com.module.helpers.CustomAlertCreator;
import com.module.model.entity.DocumentEntity;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
@Data
@Component
public class DocumentsTabController {
@FXML
private Tab documentsTab;
@FXML
private TableView<DocumentEntity> documentsTable;
@FXML
private TableColumn<DocumentEntity, String> documentNameColumn;
@FXML
private TableColumn<DocumentEntity, String> seriesOfDocumentColumn;
@FXML
private TableColumn<DocumentEntity, String> numberOfDocumentColumn;
@FXML
private TableColumn<DocumentEntity, String> documentIssuedByColumn;
@FXML
private TableColumn<DocumentEntity, LocalDate> dateOfIssueDocumentColumn;
@FXML
private Button addDocumentButton;
@FXML
private Button editDocumentButton;
@FXML
private Button deleteDocumentButton;
private Stage dialogStage;
private ObservableList<DocumentEntity> documentsData = FXCollections.observableArrayList();
@FXML
public void initialize() {
documentNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
seriesOfDocumentColumn.setCellValueFactory(new PropertyValueFactory<>("series"));
numberOfDocumentColumn.setCellValueFactory(new PropertyValueFactory<>("number"));
documentIssuedByColumn.setCellValueFactory(new PropertyValueFactory<>("issuedBy"));
dateOfIssueDocumentColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
dateOfIssueDocumentColumn.setCellFactory(getTableColumnTableCellCallback());
documentsData.clear();
}
private Callback<TableColumn<DocumentEntity, LocalDate>, TableCell<DocumentEntity, LocalDate>> getTableColumnTableCellCallback() {
return (TableColumn<DocumentEntity, LocalDate> column) -> new TableCell<DocumentEntity, LocalDate>() {
@Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
}
}
};
}
@FXML
private void handleAddDocument() {
DocumentEntity documentEntity = new DocumentEntity();
boolean addButtonClicked = showAddDocumentDialog(documentEntity);
if (addButtonClicked) {
documentsData.add(documentEntity);
documentsTable.refresh();
}
}
@FXML
private void handleDeleteDocument() {
int selectedIndex = documentsTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
CustomAlertCreator customAlertCreator = new CustomAlertCreator();
Optional<ButtonType> result = customAlertCreator.createDeleteConfirmationAlert().showAndWait();
if (result.get() == customAlertCreator.getButtonTypeOk()) {
documentsData.remove(selectedIndex);
documentsTable.refresh();
}
}
}
@FXML
private void handleEditDocument() {
DocumentEntity documentEntity = documentsTable.getSelectionModel().getSelectedItem();
int selectedIndex = documentsTable.getSelectionModel().getSelectedIndex();
if (documentEntity != null) {
boolean addButtonClicked = showAddDocumentDialog(documentEntity);
if (addButtonClicked) {
documentsData.set(selectedIndex, documentEntity);
documentsTable.refresh();
}
}
}
private boolean showAddDocumentDialog(DocumentEntity documentEntity) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("view/veterandialog/veterantabledialogs/AddDocumentDialog.fxml"));
AnchorPane pane = loader.load();
Stage stage = new Stage();
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(dialogStage);
stage.setResizable(false);
stage.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(pane);
stage.setScene(scene);
AddDocumentController controller = loader.getController();
controller.setDialogStage(stage);
controller.setDocumentEntity(documentEntity);
stage.showAndWait();
return controller.isSaveClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.massive;
import java.util.ArrayList;
import java.util.Collection;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTFolder;
import com.openkm.frontend.client.service.OKMMassiveService;
import com.openkm.frontend.client.service.OKMMassiveServiceAsync;
import com.openkm.frontend.client.util.CommonUI;
import com.openkm.frontend.client.util.OKMBundleResources;
import com.openkm.frontend.client.util.Util;
/**
* Categories popup
*
* @author jllort
*/
public class CategoriesPopup extends DialogBox {
private final OKMMassiveServiceAsync massiveService = (OKMMassiveServiceAsync) GWT.create(OKMMassiveService.class);
private FlexTable table;
private CellFormatter cellFormatter;
private VerticalPanel vPanel;
private ScrollPanel scrollDirectoryPanel;
private VerticalPanel verticalDirectoryPanel;
private FolderSelectTree folderSelectTree;
private Button add;
private Button close;
private FlexTable tableSubscribedCategories;
private Collection<GWTFolder> assignedCategories;
private boolean remove = true;
private Status status;
/**
* CategoriesPopup
*/
public CategoriesPopup() {
// Establishes auto-close when click outside
super(false, true);
setText(Main.i18n("category.add"));
// Status
status = new Status(this);
status.setStyleName("okm-StatusPopup");
table = new FlexTable();
tableSubscribedCategories = new FlexTable();
assignedCategories = new ArrayList<GWTFolder>();
cellFormatter = table.getCellFormatter(); // Gets the cell formatter
table.setWidth("100%");
table.setCellPadding(0);
table.setCellSpacing(2);
// Categories
vPanel = new VerticalPanel();
vPanel.setWidth("470px");
vPanel.setHeight("175px");
scrollDirectoryPanel = new ScrollPanel();
scrollDirectoryPanel.setSize("460px", "150px");
scrollDirectoryPanel.setStyleName("okm-Popup-text");
verticalDirectoryPanel = new VerticalPanel();
verticalDirectoryPanel.setSize("100%", "100%");
folderSelectTree = new FolderSelectTree();
folderSelectTree.setSize("100%", "100%");
verticalDirectoryPanel.add(folderSelectTree);
scrollDirectoryPanel.add(verticalDirectoryPanel);
add = new Button(Main.i18n("button.add"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addCategory(folderSelectTree.getCategory());
}
});
add.setEnabled(false);
close = new Button(Main.i18n("button.close"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isMassive()) {
Main.get().mainPanel.topPanel.toolBar.executeRefresh();
}
hide();
}
});
vPanel.add(scrollDirectoryPanel);
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.add(close);
hPanel.add(new HTML(" "));
hPanel.add(add);
vPanel.add(hPanel);
vPanel.setCellHorizontalAlignment(scrollDirectoryPanel, HasAlignment.ALIGN_CENTER);
vPanel.setCellHorizontalAlignment(hPanel, HasAlignment.ALIGN_CENTER);
vPanel.setCellVerticalAlignment(hPanel, HasAlignment.ALIGN_MIDDLE);
vPanel.setCellHeight(scrollDirectoryPanel, "150px");
vPanel.setCellHeight(hPanel, "25px");
table.setWidget(0, 0, vPanel);
table.getFlexCellFormatter().setColSpan(1, 0, 2);
cellFormatter.setHorizontalAlignment(1, 0, HasAlignment.ALIGN_CENTER);
table.setHTML(1, 0, " <b>" + Main.i18n("document.categories") + "</b>");
table.getFlexCellFormatter().setColSpan(2, 0, 2);
cellFormatter.setHorizontalAlignment(2, 0, HasAlignment.ALIGN_LEFT);
table.setWidget(2, 0, tableSubscribedCategories);
table.getFlexCellFormatter().setColSpan(3, 0, 2);
cellFormatter.setHorizontalAlignment(3, 0, HasAlignment.ALIGN_LEFT);
setRowWordWarp(0, 0, true, tableSubscribedCategories);
table.setStyleName("okm-DisableSelect");
close.setStyleName("okm-NoButton");
add.setStyleName("okm-AddButton");
tableSubscribedCategories.setStyleName("okm-DisableSelect");
setWidget(table);
}
/**
* reset
*/
public void reset() {
folderSelectTree.reset();
assignedCategories = new ArrayList<GWTFolder>();
tableSubscribedCategories.removeAllRows();
if (!Main.get().mainPanel.desktop.browser.fileBrowser.isMassive()) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isDocumentSelected()) {
assignedCategories = Main.get().mainPanel.desktop.browser.fileBrowser.getDocument().getCategories();
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isFolderSelected()) {
assignedCategories = Main.get().mainPanel.desktop.browser.fileBrowser.getFolder().getCategories();
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isMailSelected()) {
assignedCategories = Main.get().mainPanel.desktop.browser.fileBrowser.getMail().getCategories();
}
}
}
/**
* addCategory document
*/
public void addCategory(GWTFolder category) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isMassive()) {
if (!existCategory(category.getUuid())) {
assignedCategories.add(category);
drawCategory(category, remove);
status.setFlagCategories();
massiveService.addCategory(Main.get().mainPanel.desktop.browser.fileBrowser.getAllSelectedPaths(),
category.getUuid(), new AsyncCallback<Object>() {
@Override
public void onSuccess(Object result) {
status.unsetFlagCategories();
}
@Override
public void onFailure(Throwable caught) {
status.unsetFlagCategories();
Main.get().showError("addNote", caught);
}
});
}
} else {
// Aqui hem de fer alguna cosa !!!!!!!!!
if (!existCategory(category.getUuid())) {
drawCategory(category, remove);
// Filebrowser panel selected
if (Main.get().mainPanel.desktop.browser.fileBrowser.isPanelSelected()) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isDocumentSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.document.addCategory(category);
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isFolderSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.folder.addCategory(category);
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isMailSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabMail.mail.addCategory(category);
}
} else {
// Otherside tree panel is selected
Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.folder.addCategory(category);
}
}
}
}
/**
* removeCategory document
*/
public void removeCategory(final String UUID) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isMassive()) {
status.setFlagRemoveCategories();
massiveService.removeCategory(Main.get().mainPanel.desktop.browser.fileBrowser.getAllSelectedPaths(), UUID,
new AsyncCallback<Object>() {
@Override
public void onSuccess(Object result) {
for (GWTFolder fld : assignedCategories) {
if (fld.getUuid().equals(UUID)) {
assignedCategories.remove(fld);
break;
}
}
status.unsetFlagRemoveCategories();
}
@Override
public void onFailure(Throwable caught) {
status.unsetFlagRemoveCategories();
Main.get().showError("addNote", caught);
}
});
} else {
// Filebrowser panel selected
if (Main.get().mainPanel.desktop.browser.fileBrowser.isPanelSelected()) {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isDocumentSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.document.removeCategory(UUID);
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isFolderSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.folder.removeCategory(UUID);
} else if (Main.get().mainPanel.desktop.browser.fileBrowser.isMailSelected()) {
Main.get().mainPanel.desktop.browser.tabMultiple.tabMail.mail.removeCategory(UUID);
}
} else {
// Otherside tree panel is selected
Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.folder.removeCategory(UUID);
}
}
}
/**
* existCategory
*
* @param Uuid
* @return
*/
private boolean existCategory(String Uuid) {
boolean found = false;
for (GWTFolder fld : assignedCategories) {
if (fld.getUuid().equals(Uuid)) {
found = true;
break;
}
}
return found;
}
/**
* Enables or disables move button
*
* @param enable
*/
public void enable(boolean enable) {
add.setEnabled(enable);
}
/**
* drawCategory
*
* @param category
*/
private void drawCategory(final GWTFolder category, boolean remove) {
int row = tableSubscribedCategories.getRowCount();
Anchor anchor = new Anchor();
// Looks if must change icon on parent if now has no childs and properties with user security atention
String path = category.getPath().substring(16); // Removes /okm:categories
if (category.isHasChildren()) {
anchor.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", path, "top"));
} else {
anchor.setHTML(Util.imageItemHTML("img/menuitem_empty.gif", path, "top"));
}
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent arg0) {
CommonUI.openPath(category.getPath(), null);
}
});
anchor.setStyleName("okm-KeyMap-ImageHover");
Image delete = new Image(OKMBundleResources.INSTANCE.deleteIcon());
delete.setStyleName("okm-KeyMap-ImageHover");
delete.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
removeCategory(category.getUuid());
tableSubscribedCategories.removeRow(tableSubscribedCategories.getCellForEvent(event).getRowIndex());
}
});
tableSubscribedCategories.setWidget(row, 0, anchor);
if (remove) {
tableSubscribedCategories.setWidget(row, 1, delete);
} else {
tableSubscribedCategories.setWidget(row, 1, new HTML(""));
}
setRowWordWarp(row, 1, true, tableSubscribedCategories);
}
/**
* Set the WordWarp for all the row cells
*
* @param row The row cell
* @param columns Number of row columns
* @param warp
* @param table The table to change word wrap
*/
private void setRowWordWarp(int row, int columns, boolean warp, FlexTable table) {
CellFormatter cellFormatter = table.getCellFormatter();
for (int i = 0; i < columns; i++) {
cellFormatter.setWordWrap(row, i, warp);
}
}
/**
* langRefresh
*/
public void langRefresh() {
setText(Main.i18n("category.add"));
}
}
|
package com.espendwise.manta.model.view;
// Generated by Hibernate Tools
import com.espendwise.manta.model.ValueObject;
/**
* CMSView generated by hbm2java
*/
public class CMSView extends ValueObject implements java.io.Serializable {
private static final long serialVersionUID = -1;
public static final String PRIMARY_ENTITY_ID = "primaryEntityId";
public static final String PRIMARY_ENTITY_NAME = "primaryEntityName";
public static final String CONTENT_MANAGEMENT_PROPERTIES = "contentManagementProperties";
private Long primaryEntityId;
private String primaryEntityName;
private ContentManagementView contentManagementProperties;
public CMSView() {
}
public CMSView(Long primaryEntityId) {
this.setPrimaryEntityId(primaryEntityId);
}
public CMSView(Long primaryEntityId, String primaryEntityName, ContentManagementView contentManagementProperties) {
this.setPrimaryEntityId(primaryEntityId);
this.setPrimaryEntityName(primaryEntityName);
this.setContentManagementProperties(contentManagementProperties);
}
public Long getPrimaryEntityId() {
return this.primaryEntityId;
}
public void setPrimaryEntityId(Long primaryEntityId) {
this.primaryEntityId = primaryEntityId;
setDirty(true);
}
public String getPrimaryEntityName() {
return this.primaryEntityName;
}
public void setPrimaryEntityName(String primaryEntityName) {
this.primaryEntityName = primaryEntityName;
setDirty(true);
}
public ContentManagementView getContentManagementProperties() {
return this.contentManagementProperties;
}
public void setContentManagementProperties(ContentManagementView contentManagementProperties) {
this.contentManagementProperties = contentManagementProperties;
setDirty(true);
}
}
|
package com.tencent.mm.app;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.tencent.mm.a.g;
import com.tencent.mm.g.a.ie;
import com.tencent.mm.plugin.base.stub.WXBizEntryActivity;
import com.tencent.mm.pluginsdk.model.app.p;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class WorkerProfile$17 extends c<ie> {
final /* synthetic */ WorkerProfile bzO;
WorkerProfile$17(WorkerProfile workerProfile) {
this.bzO = workerProfile;
this.sFo = ie.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
ie ieVar = (ie) bVar;
Context context = ieVar.bRF.context;
if (context == null) {
x.e("MicroMsg.WorkerProfile", "context is null");
} else {
String str;
String str2;
String[] strArr = ieVar.bRF.bGj;
if (strArr == null || strArr.length <= 0) {
str = null;
str2 = null;
} else {
str2 = strArr[0];
str = g.u(p.bh(ieVar.bRF.context, strArr[0])[0].toByteArray());
}
String[] strArr2 = ieVar.bRF.selectionArgs;
if (strArr2 == null || strArr2.length <= 0) {
x.e("MicroMsg.WorkerProfile", "args is null");
} else {
String str3;
String str4;
if (strArr2 == null || strArr2.length <= 1) {
str3 = null;
str4 = null;
} else {
str4 = strArr2[0];
str3 = strArr2[1];
}
x.i("MicroMsg.WorkerProfile", "handleScanResult, appid = %s, scanResult = %s", new Object[]{str4, str3});
if (!(bi.oW(str4) || bi.oW(str3))) {
String format = String.format("weixin://dl/handleScanResult?appid=%s&result=%s", new Object[]{str4, str3});
Intent intent = new Intent(context, WXBizEntryActivity.class);
intent.setData(Uri.parse(format));
intent.addFlags(268435456).addFlags(134217728).addFlags(67108864);
intent.putExtra("key_command_id", 17);
intent.putExtra("key_package_name", str2);
intent.putExtra("translate_link_scene", 1);
intent.putExtra("key_package_signature", str);
context.startActivity(intent);
return true;
}
}
}
return false;
}
}
|
package com.tencent.mm.pluginsdk.g.a.a;
import com.tencent.mm.a.g;
import com.tencent.mm.pluginsdk.g.a.a.b.c;
import com.tencent.mm.pluginsdk.g.a.c.q.a;
import com.tencent.mm.pluginsdk.g.a.c.s;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
final class f$b {
static void a(s sVar, boolean z, boolean z2) {
if (sVar == null) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "get null record, skip");
return;
}
String str = sVar.field_urlKey;
String str2 = sVar.field_filePath;
String str3 = sVar.field_md5;
boolean z3 = sVar.field_fileCompress;
boolean z4 = sVar.field_fileEncrypt;
Object obj = sVar.field_eccSignature;
int i = bi.getInt(sVar.field_fileVersion, 0);
int i2 = sVar.field_keyVersion;
String str4 = sVar.field_encryptKey;
boolean z5 = sVar.field_deleted;
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "queried info: deleted = " + z5 + ", filePath = " + str2 + ", md5 = " + str3 + ", originalMd5 = " + sVar.field_originalMd5 + ", fileCompress = " + z3 + ", fileEncrypt = " + z4 + ", eccSignature = " + obj + ", fileVersion = " + i + ", (encrypt key == empty) = " + bi.oW(str4));
x.d("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "queried encryptKey = %s", str4);
if (!z4) {
if (z) {
j.n(sVar.field_reportId, 53);
j.n(sVar.field_reportId, 45);
}
if (!z3) {
x.e("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "file is not encrypted nor compressed, just return");
return;
}
}
if (i2 != i && z4) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "file version(%d) != key version(%d), skip", Integer.valueOf(i), Integer.valueOf(i2));
if (i2 >= 0) {
j.n(sVar.field_reportId, 52);
j.n(sVar.field_reportId, 45);
}
} else if (z5) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "this file should have been deleted, skip this decrypt-op");
j.n(sVar.field_reportId, 51);
j.n(sVar.field_reportId, 45);
} else if (bi.oW(str4) && z4) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "encryptKey invalid, skip");
j.n(sVar.field_reportId, 54);
j.n(sVar.field_reportId, 45);
} else if (bi.oW(str3) || bi.oW(str2)) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "this decrypt-op is invalid, record.md5 = %s, record.filePath = %s", str3, str2);
} else if (a.ccH().To(str)) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "request(%s) is downloading or queueing, hold this decrypt-op", str);
} else if (!bi.oV(g.cu(str2)).equals(str3)) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "md5 not match, file spoiled, skip this decrypt-op");
sVar.field_status = 3;
a.ccH().g(sVar);
j.n(sVar.field_reportId, 56);
j.n(sVar.field_reportId, 45);
} else if (!a.ccH().To(str)) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.DoDecryptLogic", "request supposed to complete, send decrypt request %s", sVar.field_urlKey);
c.ccr().f(sVar.field_resType, sVar.field_subType, 1, bi.oV(sVar.field_groupId2).equals("NewXml"));
if (z2) {
c.ccr();
x.i("MicroMsg.ResDownloader.CheckResUpdateHelper", "performDecryptDirectly, urlkey %s", sVar.field_urlKey);
k.f(sVar);
return;
}
c.ccr().b(sVar);
}
}
}
|
@ModuleGen(name = "demo", groupPackage = "kafka.vertx")
package kafka.vertx;
import io.vertx.codegen.annotations.ModuleGen;
|
package edu.mines.msmith1.universepoint.test.dao;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import edu.mines.msmith1.universepoint.SQLiteHelper;
import edu.mines.msmith1.universepoint.dao.OffensiveStatDAO;
import edu.mines.msmith1.universepoint.dto.Game;
import edu.mines.msmith1.universepoint.dto.OffensiveStat;
import edu.mines.msmith1.universepoint.dto.Player;
import edu.mines.msmith1.universepoint.dto.Team;
import edu.mines.msmith1.universepoint.test.DatabaseBaseTest;
import edu.mines.msmith1.universepoint.test.util.DatabaseUtil;
public class OffensiveStatDAOTest extends DatabaseBaseTest {
OffensiveStatDAO offensiveStatDAO;
OffensiveStat offensiveStat;
Game game;
Team team1, team2;
Player player, assistingPlayer, turnoverPlayer;
@Override
public void setUp() throws Exception {
super.setUp();
offensiveStatDAO = new OffensiveStatDAO(context);
offensiveStatDAO.open();
// add teams to db
team1 = DatabaseUtil.addTeamToDatabase(context, "Test 1");
team2 = DatabaseUtil.addTeamToDatabase(context, "Test 2");
// add game
game = DatabaseUtil.addGameToDatabase(context, team1, team2);
// add players
player = DatabaseUtil.addPlayerToDatabase(context, "Player 1", team1);
assistingPlayer = DatabaseUtil.addPlayerToDatabase(context, "Player 2", team1);
turnoverPlayer = DatabaseUtil.addPlayerToDatabase(context, "Turnover Player", team2);
// create offensive stat
offensiveStat = new OffensiveStat();
offensiveStat.setGame(game);
offensiveStat.setTeam(team1);
offensiveStat.setPlayer(player);
offensiveStat.setAssistingPlayer(assistingPlayer);
offensiveStat.setTurnoverPlayer(turnoverPlayer);
}
@Test
public void testInsert() {
OffensiveStat result = offensiveStatDAO.createOffensiveStat(offensiveStat);
assertEquals(game.getId(), result.getGame().getId());
assertEquals(player.getId(), result.getPlayer().getId());
assertEquals(assistingPlayer.getId(), result.getAssistingPlayer().getId());
assertNotNull(result.getId());
}
@Test
public void testInsertWithoutAssistingPlayer() {
OffensiveStat offensiveStatWithoutAssist = offensiveStat;
offensiveStatWithoutAssist.setAssistingPlayer(null);
OffensiveStat result = offensiveStatDAO.createOffensiveStat(offensiveStatWithoutAssist);
assertNotNull(result.getId());
assertNull(result.getAssistingPlayer());
}
@Test
public void testInsertList() {
List<OffensiveStat> offensiveStats = new ArrayList<OffensiveStat>();
offensiveStats.add(offensiveStat);
offensiveStats.add(offensiveStat);
List<OffensiveStat> result = offensiveStatDAO.createOffensiveStats(offensiveStats);
assertEquals(2, result.size());
assertNotNull(result.get(0).getId());
assertNotNull(result.get(1).getId());
}
@Test
public void testDelete() {
OffensiveStat result = offensiveStatDAO.createOffensiveStat(offensiveStat);
assertNotNull(result);
offensiveStatDAO.deleteOffensiveStat(result);
OffensiveStat deleted = offensiveStatDAO.getOffensiveStatById(result.getId());
assertNull(deleted);
}
@Test
public void testGetAllPointsForPlayer() {
offensiveStatDAO.createOffensiveStat(offensiveStat);
offensiveStatDAO.createOffensiveStat(offensiveStat);
List<OffensiveStat> result = offensiveStatDAO.getAllPointsForPlayer(player);
assertNotNull(result);
assertEquals(2, result.size());
}
@Test
public void testGetScoreForTeam() {
OffensiveStat stat1 = offensiveStatDAO.createOffensiveStat(offensiveStat);
List<OffensiveStat> result = offensiveStatDAO.getOffensiveStatsForTeam(team1, game);
assertEquals(1, result.size());
assertEquals(stat1.getId(), result.get(0).getId());
assertEquals(team1.getId(), result.get(0).getTeam().getId());
}
@Test
public void testInsertOffensiveStatWithoutPlayer() {
OffensiveStat anonOffensiveStat = offensiveStat;
anonOffensiveStat.setPlayer(null);
anonOffensiveStat.setAssistingPlayer(null);
OffensiveStat result = offensiveStatDAO.createOffensiveStat(anonOffensiveStat);
assertNotNull(result);
assertNull(result.getPlayer());
}
@Test
public void testGetAssistsForPlayer() {
offensiveStatDAO.createOffensiveStat(offensiveStat);
offensiveStatDAO.createOffensiveStat(offensiveStat);
List<OffensiveStat> result = offensiveStatDAO.getAllAssistsForPlayer(assistingPlayer);
assertNotNull(result);
assertEquals(2, result.size());
}
@Test
public void testGetTurnoversForPlayer() {
offensiveStatDAO.createOffensiveStat(offensiveStat);
offensiveStatDAO.createOffensiveStat(offensiveStat);
List<OffensiveStat> result = offensiveStatDAO.getAllTurnoversForPlayer(turnoverPlayer);
assertNotNull(result);
assertEquals(2, result.size());
}
@Override
public void tearDown() throws Exception {
super.tearDown();
offensiveStatDAO.close();
SQLiteHelper sqLiteHelper = new SQLiteHelper(context);
sqLiteHelper.truncateTables();
sqLiteHelper.close();
}
}
|
package net.sssanma.mc.listener;
import net.sssanma.mc.ECore;
import net.sssanma.mc.EStrings;
import net.sssanma.mc.Prefixes;
import net.sssanma.mc.data.user.EUserManager;
import net.sssanma.mc.data.user.User;
import net.sssanma.mc.utility.NMSUtil;
import net.sssanma.mc.utility.Utility;
import net.sssanma.mc.world.EWorlds;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.util.Calendar;
import java.util.Locale;
public class ServerListener implements Listener {
private String[] motds;
public ServerListener() {
motds = EStrings.getSubStringsByPath("motd", "random").getAllValue();
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
if (event.isNewChunk() && !EWorlds.isAnySigenWorld(event.getWorld().getName())) {
Bukkit.getScheduler().runTaskTimer(ECore.getPlugin(), new Runnable() {
@Override
public void run() {
if (NMSUtil.getNMSChunk(event.getChunk()).done) {
NMSUtil.deleteResource(event.getChunk());
}
}
}, 1, 2);
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onServerListPing(ServerListPingEvent event) {
if (ECore.getPlugin().conf.isPanic()) {
event.setMaxPlayers(0);
event.setMotd(ChatColor.RED + "緊急停止状態");
} else {
event.setMaxPlayers(ECore.getPlugin().conf.getMaxPlayer());
String[] motd = new String[2];
Calendar cal = Calendar.getInstance(Locale.JAPAN);
String dateMotd = EStrings.getValueByPath("motd", "date", String.valueOf(cal.get(Calendar.MONTH) + 1) + "-" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)));
if (dateMotd != null)
motd[0] = dateMotd;
else {
if (motds.length > 0) {
ChatColor[] colors = ChatColor.values();
ChatColor motdColor = colors[ECore.rand.nextInt(colors.length - 6)];
motd[0] = String.format(motds[ECore.rand.nextInt(motds.length)], motdColor.toString(), ECore.getPlugin().getPluginVersion(), NMSUtil.getMinecraftServerVersion());
} else
motd[0] = "E-Server";
}
String restartMotd;
if (ECore.getPlugin().restartCountingTask != null && (restartMotd = EStrings.getValueByPath("motd", "other", "restart")) != null) {
long timeLeft = ECore.getPlugin().restartCountingTask.shutdownTime - System.currentTimeMillis();
motd[1] = restartMotd.replaceAll("%s", String.valueOf(timeLeft));
} else {
String hiMotd = EStrings.getValueByPath("motd", "other", "hi");
if (hiMotd != null) {
String ip = event.getAddress().getHostAddress();
// 探す
User user = EUserManager.getUserByIP(ip);
if (user != null) {
String userMessage = "";
if (user.isLoadFailed()) {
userMessage = ChatColor.RED + Prefixes.ERROR + "あなたの情報が読み込めませんでした。";
}
if (user.isBanned())
userMessage = ChatColor.RED + Prefixes.ERROR + "あなたはBANされています。";
motd[1] = String.format(hiMotd, user.getLastUserName(), userMessage);
} else {
String firstMotd = EStrings.getValueByPath("motd", "other", "first");
if (firstMotd != null) {
motd[1] = Utility.rainbow(firstMotd);
} else {
motd[1] = ChatColor.GREEN + "ここをダブルクリックで接続";
}
}
} else {
motd[1] = "内部エラー#1";
}
}
event.setMotd(motd[0] + "\n" + ChatColor.RESET + motd[1]);
}
}
}
|
package org.fuserleer.console;
import java.io.PrintStream;
import java.util.Map.Entry;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.fuserleer.Context;
import org.fuserleer.serialization.Serialization;
public class Serializer extends Function
{
private final static Options options = new Options().addOption("stats", false, "Outputs serializerstatistics");
public Serializer()
{
super("serializer", options);
}
@Override
public void execute(Context context, String[] arguments, PrintStream printStream) throws Exception
{
CommandLine commandLine = Function.parser.parse(options, arguments);
if (commandLine.hasOption("stats") == true)
{
for (Entry<Class<?>, Entry<Long, Long>> type: Serialization.getInstance().statistics())
printStream.println(type.getKey()+": "+type.getValue().getKey()+" -> "+type.getValue().getValue()+" / "+(type.getValue().getValue() / type.getValue().getKey()));
}
}
}
|
package com.myseriousorganization.nginx;
/**
* Created by crazysoftwarecoder on 11/30/14.
*/
public class nGinxxerException extends Exception {
public nGinxxerException(String message) {
super(message);
}
}
|
package com.example.root.monerotest;
public class Transaction {
private boolean isSending;
private String amount;
private String fee;
private String date;
private String time;
private String paymentID;
private String txid;
private int BH;
public Transaction(boolean isSending, String amount, String fee, String date, String time, int BlockHeight , String TXid,String PaymentID){
this.isSending = isSending;
this.amount = amount;
this.fee = fee;
this.date = date;
this.time = time;
this.BH = BlockHeight;
this.txid = TXid;
this.paymentID = PaymentID;
}
public boolean getIsSending(){
return isSending;
}
public String getAmount() {
return amount;
}
public String getTXid() {
return txid;
}
public int getBlockheight() {
return BH;
}
public String getpaymentID() {return paymentID;}
public String getFee() {
return fee;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
|
package com.tencent.mm.plugin.remittance.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.remittance.ui.RemittanceBusiUI.23;
import com.tencent.mm.sdk.platformtools.ah;
class RemittanceBusiUI$23$2 implements OnClickListener {
final /* synthetic */ 23 mBy;
RemittanceBusiUI$23$2(23 23) {
this.mBy = 23;
}
public final void onClick(DialogInterface dialogInterface, int i) {
ah.i(new 1(this), 500);
}
}
|
package MonteCarlo;
public class InverseNormal {
/***
* Calculating the "Y" value we use to know if the desired accuracy level is reached
* @param The probability we input.
* @return
*/
public static double getY(double prob){
double p=1-(0.5-prob/2);
double t=Math.sqrt(Math.log(1/Math.pow(p, 2)));
double y=-t+(2.515517+0.802853*t+0.010328*Math.pow(t, 2))/(1+1.432788*t+0.189269*Math.pow(t, 2)+0.001308*Math.pow(t, 3));
return y;
}
}
|
/******************************************************
Cours: LOG121
Projet: Framework.TP3
Nom du fichier: DeIterateur.java
Date créé: 2016-03-03
*******************************************************
Historique des modifications
*******************************************************
*@author Vincent Leclerc(LECV07069406)
*@author Gabriel Déry(DERG30049401)
2016-03-03 Version initiale
*******************************************************/
package Framework.Des;
import java.util.Iterator;
/**
* Classe qui va gérer l'itérateur de dés
*/
public class DeIterateur implements Iterator<De> {
private CollectionDes cDe;
private int position = 0;
/**
* Constructeur de l'itérateur
* @param cDe Collection de dés qui va être itéré
*/
public DeIterateur(CollectionDes cDe)
{
this.cDe = cDe;
}
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
if(position < cDe.getLength())
{
return true;
}
else {
return false;
}
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
@Override
public De next() {
De unDe = cDe.get(position);
position++;
return unDe;
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
@Override
public void remove(){}
}
|
package com.huanuo.npo.pojo;
import javax.persistence.*;
@Entity
public class MyBook {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "book_detail")
/*
@JoinColumn重命名了添加的列,如果不指定,添加的列就叫bookDetail
*/
private BookDetail bookDetail;
public MyBook() {
}
public MyBook(String name, BookDetail bookDetail) {
this.name = name;
this.bookDetail = bookDetail;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BookDetail getBookDetail() {
return bookDetail;
}
public void setBookDetail(BookDetail bookDetail) {
this.bookDetail = bookDetail;
}
}
|
package com.tencent.mm.plugin.backup.g;
import com.tencent.mm.ak.o;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.backup.a.a;
import com.tencent.mm.plugin.chatroom.b.b;
import com.tencent.mm.plugin.emoji.model.i;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class d extends a {
private static String TAG = "MicroMsg.BackupStorageModel";
private static d gYO;
private b gYP;
private a gYQ;
public static d asG() {
if (gYO == null) {
d dVar = new d();
gYO = dVar;
a(dVar);
}
return gYO;
}
public final void aqK() {
gYO = null;
}
public final b asH() {
if (this.gYP == null) {
this.gYP = new b();
}
return this.gYP;
}
public final a asI() {
if (this.gYQ == null) {
this.gYQ = new a();
}
return this.gYQ;
}
public final void asJ() {
x.i(TAG, "backupInitStorage");
b asH = asH();
au.HU();
String Gq = c.Gq();
au.HU();
x.i("MicroMsg.BackupStorage", "setBackupStorage, accPath:%s, accUin:%d, caller:%s", new Object[]{Gq, Integer.valueOf(c.Df()), bi.cjd()});
asH.uin = r2;
asH.dqp = Gq;
au.HU();
asH.dqq = c.FO();
au.HU();
asH.gYC = c.DT();
au.HU();
asH.gYD = c.FR();
au.HU();
asH.gYF = c.FW();
au.HU();
asH.gYE = c.FT();
au.HU();
asH.gYI = c.FZ();
asH.gYG = o.Pf();
asH.gYH = i.aEA().igx;
asH.gYK = ((b) g.l(b.class)).Ga();
asH.gYJ = com.tencent.mm.modelvideo.o.Ta();
asH.gYL = com.tencent.mm.plugin.ac.a.bmg();
asH.gYM = com.tencent.mm.plugin.ac.a.bmf();
asH.gYN = com.tencent.mm.plugin.ac.a.asF();
}
}
|
package com.rabbitmq_spring;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.ConsumerTagStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.rabbitmq.client.Channel;
@Configuration
@ComponentScan({"com.rabbitmq_spring.*"})
public class RabbitmqConfig {
/*@Bean
public ConnectionFactory connectionFactory(){
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
cachingConnectionFactory.setAddresses("10.0.1.119");
cachingConnectionFactory.setUsername("guest");
cachingConnectionFactory.setPassword("guest");
cachingConnectionFactory.setVirtualHost("/");
return cachingConnectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
*//**
* AMQP声明
*//*
@Bean
public TopicExchange topicExchange001(){
return new TopicExchange("topicExchange001",true,false);
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
return rabbitTemplate;
}*/
/*@Bean
public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory){
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
//设置监听的队列
container.setQueueNames("queue001","queue002");
//设置当前消费者数量
container.setConcurrentConsumers(1);
container.setMaxConcurrentConsumers(5);
container.setDefaultRequeueRejected(false);
container.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String queue) {
String name = queue + "---------------";
return name;
}
});
container.setMessageListener(new ChannelAwareMessageListener() {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
// TODO Auto-generated method stub
String msg = new String(message.getBody());
System.out.println("-----------消费者:"+msg);
}
});
return container;
}
@Bean
public SimpleMessageListenerContainer messageContainer2(ConnectionFactory connectionFactory){
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
//设置监听的队列
container.setQueueNames("queue001","queue002");
//设置当前消费者数量
container.setConcurrentConsumers(1);
container.setMaxConcurrentConsumers(5);
container.setDefaultRequeueRejected(false);
container.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String queue) {
String name = queue + "---------------";
return name;
}
});
//MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate());
//container.setMessageListener(adapter);
return container;
}*/
}
|
package me.itsmas.minigames.scoreboard;
import me.itsmas.minigames.GameManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Handles scoreboard sidebars displayed to players
*/
public class ScoreboardManager implements Listener
{
/**
* The plugin instance
*/
private final GameManager manager;
public ScoreboardManager(GameManager manager)
{
this.manager = manager;
new BukkitRunnable()
{
@Override
public void run()
{
boards.values().forEach(BoardWrapper::update);
manager.getGame().resetBlanks();
}
}.runTaskTimer(manager, 0L, 2L);
}
/**
* Map linking player {@link UUID}s to {@link BoardWrapper}s
*/
private final Map<UUID, BoardWrapper> boards = new HashMap<>();
@EventHandler
public void onJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
boards.put(player.getUniqueId(), new BoardWrapper(manager, player));
}
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
Player player = event.getPlayer();
BoardWrapper board = boards.get(player.getUniqueId());
board.unregister();
boards.remove(player.getUniqueId());
}
}
|
package com.tencent.mm.plugin.offline.ui;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import com.tencent.mm.plugin.wxpay.a.c;
import com.tencent.mm.plugin.wxpay.a.g;
import java.util.ArrayList;
class WalletOfflineCoinPurseUI$a extends BaseAdapter {
ArrayList<String> gBc = new ArrayList();
ArrayList<Boolean> lMB = new ArrayList();
final /* synthetic */ WalletOfflineCoinPurseUI lMe;
public WalletOfflineCoinPurseUI$a(WalletOfflineCoinPurseUI walletOfflineCoinPurseUI) {
this.lMe = walletOfflineCoinPurseUI;
}
public final int getCount() {
return this.gBc.size();
}
public final Object getItem(int i) {
return this.gBc.get(i);
}
public final long getItemId(int i) {
return (long) i;
}
public final boolean isEnabled(int i) {
return ((Boolean) this.lMB.get(i)).booleanValue();
}
public final View getView(int i, View view, ViewGroup viewGroup) {
CheckedTextView checkedTextView = (CheckedTextView) View.inflate(this.lMe, g.wallet_list_dialog_item_singlechoice, null);
checkedTextView.setText((String) this.gBc.get(i));
if (WalletOfflineCoinPurseUI.blw() == i) {
checkedTextView.setChecked(true);
} else {
checkedTextView.setChecked(false);
}
if (isEnabled(i)) {
checkedTextView.setTextColor(this.lMe.getResources().getColor(c.normal_text_color));
checkedTextView.setEnabled(true);
} else {
checkedTextView.setTextColor(this.lMe.getResources().getColor(c.hint_text_color));
checkedTextView.setEnabled(false);
}
return checkedTextView;
}
}
|
package com.bluemingo.bluemingo.persistence;
import java.util.List;
import com.bluemingo.bluemingo.domain.Item_companyVO;
import com.bluemingo.bluemingo.domain.SearchVO;
import com.bluemingo.bluemingo.generic.GenericDAO;
public interface Item_companyDAO extends GenericDAO<Item_companyVO, Integer> {
public List<Item_companyVO> listAll_ref_list(SearchVO svo, String PREFIX);
}
|
package de.jmda.gen.java.impl;
import static org.junit.Assert.assertTrue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import de.jmda.gen.GeneratorException;
import de.jmda.gen.LineIndenter;
import de.jmda.gen.java.ClassGenerator;
import de.jmda.gen.java.InstanceFieldGenerator;
import de.jmda.gen.java.InstanceMethodGenerator;
import de.jmda.gen.java.TypeKindGenerator;
public class JUTDefaultClassGenerator
{
private final static Logger LOGGER = LogManager.getLogger(JUTDefaultClassGenerator.class);
@Test public void testDefaultClassGenerator() throws GeneratorException
{
ClassGenerator generator = new DefaultClassGenerator();
StringBuffer generated = generator.generate();
LOGGER.debug("generated [" + generated + "]");
String expected =
TypeKindGenerator.CLASS.getTypeKind() + " " +
DefaultDeclaredTypeGenerator.DEFAULT_TYPE_NAME +
System.lineSeparator() +
DefaultTypeBodyGenerator.DEFAULT_TYPE_BODY;
LOGGER.debug("expected [" + expected + "]");
assertTrue(
"unexpected declared element [" + generated + "]",
expected.contentEquals(generated));
}
@Test public void testDefaultClassGeneratorWithInstanceMethod() throws GeneratorException
{
ClassGenerator generator = new DefaultClassGenerator();
InstanceMethodGenerator instanceMethodDeclarationGenerator =
new DefaultInstanceMethodGenerator();
instanceMethodDeclarationGenerator.setLineIndenter(LineIndenter.TAB_SINGLE);
generator.addMethodGenerator(instanceMethodDeclarationGenerator);
StringBuffer generated = generator.generate();
LOGGER.debug("generated [" + generated + "]");
assertTrue(
"can't find method",
generated.indexOf(DefaultMethodNameGenerator.DEFAULT_METHOD_NAME) > 0);
}
@Test public void testDefaultClassGeneratorWithInstanceField() throws GeneratorException
{
ClassGenerator generator = new DefaultClassGenerator();
InstanceFieldGenerator instanceFieldDeclarationGenerator =
new DefaultInstanceFieldGenerator();
instanceFieldDeclarationGenerator.setLineIndenter(LineIndenter.TAB_SINGLE);
generator.addFieldGenerator(instanceFieldDeclarationGenerator);
StringBuffer generated = generator.generate();
LOGGER.debug("generated [" + generated + "]");
assertTrue("can't find field", generated.indexOf("field_name") > 0);
}
}
|
package com.axicik;
import java.sql.SQLException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author Ioulios Tsiko: cs131027
* @author Theofilos Axiotis: cs131011
*/
@Path("services")
public class GetServicesResource {
@Context
private UriInfo context; // Δημιουργείτε μόνο του απο το Net-beans, όταν δημιουργείτε η κλάση και δεν το χρησιμοποιούμε κάπου.
/**
* Creates a new instance of RolesResources
*/
public GetServicesResource() {
}
/**
* Επιστρέφει τις υπηρεσίες που έχει δiκαίωμα να καλέσει ο χρήστης.
* @param a Όνομα Χρήστη
* @param b Ρόλος Χρήστη
* @return String - οι υπηρεσίες που έχει δικαίωμα να καλέσει ο χρήστης.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getServices(@QueryParam ("n1") String a,@QueryParam ("n2") String b) {
try {
DBManager dm=DBManager.getInstance(); // Πέρνει το μοναδικό αντεικήμενο τηs κλάσης DBManager.
return dm.getServices(a,b); //Επιστρέφει τις υπηρεσίες που έχει δiκαίωμα να καλέσει ο χρήστης.
} catch (ClassNotFoundException ex) {
return "-1";
} catch (SQLException ex) {
return "Error "+ex.getErrorCode();
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.solrfacetsearch.indexer.strategies.impl;
import static org.junit.Assert.assertTrue;
import de.hybris.bootstrap.annotations.IntegrationTest;
import de.hybris.platform.solrfacetsearch.config.FacetSearchConfig;
import de.hybris.platform.solrfacetsearch.config.IndexedType;
import de.hybris.platform.solrfacetsearch.indexer.strategies.IndexOperationIdGenerator;
import de.hybris.platform.solrfacetsearch.integration.AbstractIntegrationTest;
import de.hybris.platform.solrfacetsearch.model.SolrIndexModel;
import de.hybris.platform.solrfacetsearch.solr.Index;
import de.hybris.platform.solrfacetsearch.solr.SolrIndexService;
import de.hybris.platform.solrfacetsearch.solr.SolrSearchProvider;
import de.hybris.platform.solrfacetsearch.solr.SolrSearchProviderFactory;
import javax.annotation.Resource;
import org.junit.Test;
@IntegrationTest
public class DefaultIndexOperationIdGeneratorTest extends AbstractIntegrationTest
{
private static final String QUALIFIER = "qualifier";
@Resource
private IndexOperationIdGenerator indexOperationIdGenerator;
@Resource
private SolrIndexService solrIndexService;
@Resource
private SolrSearchProviderFactory solrSearchProviderFactory;
@Test
public void testNextIdIsBiggerThanPrevious() throws Exception
{
// given
final FacetSearchConfig facetSearchConfig = getFacetSearchConfig();
final IndexedType indexedType = facetSearchConfig.getIndexConfig().getIndexedTypes().values().iterator().next();
final SolrIndexModel index = solrIndexService.createIndex(facetSearchConfig.getName(), indexedType.getIdentifier(),
QUALIFIER);
final SolrSearchProvider solrSearchProvider = solrSearchProviderFactory.getSearchProvider(facetSearchConfig, indexedType);
final Index solrIndex = solrSearchProvider.resolveIndex(facetSearchConfig, indexedType, index.getQualifier());
// when
final long indexOperationId1 = indexOperationIdGenerator.generate(facetSearchConfig, indexedType, solrIndex);
final long indexOperationId2 = indexOperationIdGenerator.generate(facetSearchConfig, indexedType, solrIndex);
// then
assertTrue(indexOperationId1 > 0);
assertTrue(indexOperationId2 > 0);
assertTrue(indexOperationId2 > indexOperationId1);
}
}
|
package com.ceiba.parkingceiba.domain.imp;
import java.util.Date;
import org.springframework.stereotype.Component;
import com.ceiba.parkingceiba.domain.ICronometroParqueadero;
import com.ceiba.parkingceiba.util.ParametrosGlobalesParqueadero;
@Component
public class CronometroParqueaderoImp implements ICronometroParqueadero {
public int getObtenerMinutosDeParqueo(Date fechaIngreso, Date fechaSalida) {
return (int) ((fechaSalida.getTime() - fechaIngreso.getTime()) / ParametrosGlobalesParqueadero.MILI_SEGUNDOS);
}
public TiempoParqueaderoImp obtenerTiempoDeParqueo(int minutosParqueo) {
int dias = (minutosParqueo / 60) / 24;
int horas = (minutosParqueo / 60) % 24;
int minutos = minutosParqueo % 60;
if (horas > ParametrosGlobalesParqueadero.NUMERO_HORAS_PARA_COBRO_DIA) {
dias++;
horas = 0;
}
if (minutos > 0) {
horas++;
}
return new TiempoParqueaderoImp(dias, horas);
}
}
|
package io.peppermint100.server.exception.Item;
public class ItemNotExistException extends RuntimeException{
}
|
package com.vibexie.jianai.LoginRegister;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.vibexie.jianai.Dao.Bean.UserBean;
import com.vibexie.jianai.Dao.DBHelper.UserDBHelper;
import com.vibexie.jianai.Dao.DBManager.DBManager;
import com.vibexie.jianai.Utils.ActivityStackManager;
import com.vibexie.jianai.Constants.RegisterAndRegisterCmd;
import com.vibexie.jianai.Constants.ServerConf;
import com.vibexie.jianai.MainActivity.MainActivity;
import com.vibexie.jianai.R;
import com.vibexie.jianai.Utils.NetworkSettingsAlertDialog;
import com.vibexie.jianai.Utils.BlowfishUtils.BlowfishUtil;
import com.vibexie.jianai.Utils.HttpClientUtil;
import com.vibexie.jianai.Utils.NetworkStateUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by vibexie on 3/7/15
* LoginActivity为程序的登录界面,包含输入用户名,密码,还有登录和注册按钮
* 另外,保存密码和自动登录信息保存在sharePerfermance中
*/
public class LoginActivity extends Activity {
/**
* 声明所有的控件
*/
private ProgressDialog progressDialog;
private EditText usernameEditText;
private EditText passwordEditText;
private Button loginButton;
private Button registerBubtton;
private CheckBox remenberCheckBox;
private CheckBox autologinCheckBox;
/**
* 声明从EditText控件中得到的数据
*/
private String username;
private String password;
private final String LOGIN_PREFERENCES_NAME="login_preferences";
/**
* 对用户保存的密码和自动登录选项进行处理
*/
SharedPreferences loginPreferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/**
* 压入到ActivityStack中
*/
ActivityStackManager.getInstance().push(this);
initWidgets();
initClickListener();
initSharedPreferences();
if(loginPreferences.contains("username")){
usernameEditText.setText(loginPreferences.getString("username",null));
/**
* 对密码进行解密
*/
passwordEditText.setText(new BlowfishUtil(ServerConf.PASSWORD_KEY).decryptString(loginPreferences.getString("password", null)));
remenberCheckBox.setChecked(true);
if(loginPreferences.contains("antologin") && loginPreferences.getBoolean("antologin",false)==true){
autologinCheckBox.setChecked(true);
if(NetworkStateUtil.isNetWorkConnected(LoginActivity.this)){
/*网络连接上的话,向服务器请求新的数据,因为可能数据发生了改变*/
/**
* 自动调用登录操作
*/
loginButton.callOnClick();
}else {
/*无法联网的情况下,携带保存的用户名,密码,用户id跳转到MainActivity*/
/**
* 切换到MainActivity,并finish本activity,这里同时还要携带自己的用户名和密码,用户id及lover用户名过去
*/
Intent intent=new Intent(LoginActivity.this,MainActivity.class);
intent.putExtra("username",usernameEditText.getText().toString());
intent.putExtra("password",passwordEditText.getText().toString());
intent.putExtra("userid",loginPreferences.getInt("userid",0));
startActivity(intent);
finish();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
/**
* 从ActivityStack中弹出
*/
ActivityStackManager.getInstance().pop(this);
}
private void initWidgets(){
usernameEditText = (EditText) this.findViewById(R.id.username);
passwordEditText = (EditText) this.findViewById(R.id.password);
loginButton = (Button) this.findViewById(R.id.login);
registerBubtton = (Button) this.findViewById(R.id.register);
remenberCheckBox = (CheckBox) this.findViewById(R.id.remember);
autologinCheckBox = (CheckBox) this.findViewById(R.id.autologin);
progressDialog=new ProgressDialog(this);
progressDialog.setTitle("温馨提示");
progressDialog.setMessage("正在登录...");
progressDialog.setCancelable(false);
}
/**
* 初始化button的监听事件
*/
private void initClickListener(){
/**
* 登录按钮监听事件
*/
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isAllEditTextEdited()) {
/*用户名和密码未输入,直接返回*/
return;
}
if (!NetworkStateUtil.isNetWorkConnected(getApplicationContext())) {
/*网络未连接,提示用户设置网络*/
NetworkSettingsAlertDialog networkSettingsAlertDialog = new NetworkSettingsAlertDialog(LoginActivity.this);
networkSettingsAlertDialog.show();
/*返回,不进行请求*/
return;
}
/**
* 构建请求url
*/
String url = ServerConf.LOGIN_SERVLET_URL;
/**
* 构建url请求参数
*/
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cmd", RegisterAndRegisterCmd.REQUEST_LOGIN));
params.add(new BasicNameValuePair("username", username));
/**
* 对密码进行加密
*/
params.add(new BasicNameValuePair("password", new BlowfishUtil(ServerConf.PASSWORD_KEY).encryptString(password)));
/*处理请求结果*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
/**
* 请求结果
*/
String result = msg.obj.toString();
if (result.equals("refused")) {
/*请求超时或服务器关闭*/
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "请求超时或服务器关闭", Toast.LENGTH_SHORT).show();
} else if (result.equals(RegisterAndRegisterCmd.RESPONSE_LOGIN_SUCCESS)) {
/*登录成功*/
progressDialog.dismiss();
workWhenLoginSucceed();
} else if (result.equals(RegisterAndRegisterCmd.RESPONSE_LOGIN_PASSWORD_WRONG)) {
/*密码错误*/
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
} else if (result.equals(RegisterAndRegisterCmd.RESPONSE_LOGIN_USER_NOT_EXIST)) {
/*用户不存在*/
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "用户不存在", Toast.LENGTH_SHORT).show();
}
}
};
/**
* 进行请求
*/
progressDialog.show();
HttpClientUtil.doPost(url, params, handler);
}
});
/**
* 注册按钮监听事件,跳转到注册界面
*/
registerBubtton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterForVerifyingCodeActivity.class);
startActivity(registerIntent);
}
});
}
/**
* 初始化
*/
private void initSharedPreferences(){
loginPreferences=getSharedPreferences(LOGIN_PREFERENCES_NAME, Context.MODE_PRIVATE);
editor=loginPreferences.edit();
/**
* 第一次启动App,创建Preferences文件
*/
File file=new File("/data/data/"+getPackageName().toString()+"/shared_prefs",LOGIN_PREFERENCES_NAME+".xml");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断用户名和密码是否已经输入
* @return
*/
private boolean isAllEditTextEdited(){
username=usernameEditText.getText().toString();
password=passwordEditText.getText().toString();
if(username.equals("")){
Toast.makeText(getApplicationContext(),"请输入用户名",Toast.LENGTH_SHORT).show();
return false;
}
if(password.equals("")){
Toast.makeText(getApplicationContext(),"请输入密码",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/**
* 成功登录后的一些处理,如添加lover,获取自己和lover信息,跳转到MainActivity
*/
private void workWhenLoginSucceed(){
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.arg1==1){
/*对自己及lover信息进行操作*/
ArrayList<UserBean> userBeans=(ArrayList<UserBean>)msg.obj;
UserBean myBean=userBeans.get(0);
UserBean loverBean=userBeans.get(1);
/**
* 数据库名已用户id+.db的形式进行命名
*/
UserDBHelper helper=new UserDBHelper(LoginActivity.this,myBean.getId()+".db");
DBManager dbManager=new DBManager(helper);
/**
* 对自己的信息进行操作
*/
if(dbManager.getBeans(new UserBean(),"user_info","username=?",new String[]{myBean.getUsername()}).size()==0){
/*不存在则插入*/
dbManager.insertBean("user_info",myBean);
}else {
/*存在则更新*/
dbManager.updateBean(myBean,"user_info","username=?",new String[]{myBean.getUsername()});
}
/**
* 对lover的信息进行操作
*/
if(dbManager.getBeans(new UserBean(),"user_info","username=?",new String[]{loverBean.getUsername()}).size()==0){
/*不存在则插入*/
dbManager.insertBean("user_info", loverBean);
}else {
/*存在则更新*/
dbManager.updateBean(loverBean,"user_info","username=?",new String[]{loverBean.getUsername()});
}
dbManager.close();
/**
* 将用户名和密码,用户id,lover用户名及是否自动登录添加到loginPreference中
*/
if(remenberCheckBox.isChecked()){
editor.clear();
editor.commit();
editor.putString("username",username);
/**
* 对密码进行加密保存
*/
editor.putString("password",new BlowfishUtil(ServerConf.PASSWORD_KEY).encryptString(password));
editor.commit();
}
if(autologinCheckBox.isChecked()){
editor.clear();
editor.commit();
editor.putString("username",username);
/**
* 对密码进行加密保存
*/
editor.putString("password",new BlowfishUtil(ServerConf.PASSWORD_KEY).encryptString(password));
editor.putInt("userid",myBean.getId());
editor.putBoolean("antologin",true);
editor.commit();
}
/**
* 切换到MainActivity,并finish本activity,这里同时还要携带自己的用户名和密码及id过去
*/
Intent intent=new Intent(LoginActivity.this,MainActivity.class);
intent.putExtra("username",myBean.getUsername());
intent.putExtra("password",password);
intent.putExtra("userid",myBean.getId());
startActivity(intent);
finish();
}else if(msg.arg1==2){
/**
* 进行添加lover操作
*/
AddLoverDialog addLoverDialog = new AddLoverDialog(LoginActivity.this, username, password);
addLoverDialog.show();
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
GetUserInfoFromServer getUserInfoFromServer=new GetUserInfoFromServer();
Message message=Message.obtain();
if(getUserInfoFromServer.isLoverAdded(username)){
/*已添加lover*/
message.arg1=1;
/**
* 获取自己及lover信息
*/
ArrayList<UserBean> userBeans=new ArrayList<UserBean>();
UserBean myBean=getUserInfoFromServer.getUserInfo(username);
UserBean loverBean=getUserInfoFromServer.getUserInfo(myBean.getLoverName());
userBeans.add(myBean);
userBeans.add(loverBean);
message.obj=userBeans;
}else {
/*未添加lover*/
message.arg1 = 2;
}
handler.sendMessage(message);
}
}).start();
}
}
|
package com.example.airforce;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initView();
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
startActivity(new Intent(SplashActivity.this, MainActivityBB.class));
finish();
}
};
private void initView() {
handler.sendEmptyMessageDelayed(1, 2000);
}
}
|
package com.fixit.data;
import java.util.Date;
/**
* Created by Kostyantin on 12/24/2016.
*/
public class ServerLog {
private String userId;
private String installationId;
private String level;
private String tag;
private String message;
private String stackTrace;
private DeviceInfo deviceInfo;
private VersionInfo versionInfo;
private Date createdAt;
public ServerLog() { }
public ServerLog(String userId, String installationId, String level, String tag, String message, String stackTrace,
DeviceInfo deviceInfo, VersionInfo versionInfo, Date createdAt) {
this.userId = userId;
this.installationId = installationId;
this.level = level;
this.tag = tag;
this.message = message;
this.stackTrace = stackTrace;
this.deviceInfo = deviceInfo;
this.versionInfo = versionInfo;
this.createdAt = createdAt;
}
public ServerLog(String level, String tag, String message, String stackTrace,
DeviceInfo deviceInfo, VersionInfo versionInfo, Date createdAt) {
this.level = level;
this.tag = tag;
this.message = message;
this.stackTrace = stackTrace;
this.deviceInfo = deviceInfo;
this.versionInfo = versionInfo;
this.createdAt = createdAt;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getInstallationId() {
return installationId;
}
public void setInstallationId(String installationId) {
this.installationId = installationId;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStackTrace() {
return stackTrace;
}
public void setStackTrace(String stackTrace) {
this.stackTrace = stackTrace;
}
public DeviceInfo getDeviceInfo() {
return deviceInfo;
}
public void setDeviceInfo(DeviceInfo deviceInfo) {
this.deviceInfo = deviceInfo;
}
public VersionInfo getVersionInfo() {
return versionInfo;
}
public void setVersionInfo(VersionInfo versionInfo) {
this.versionInfo = versionInfo;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Override
public String toString() {
return "ServerLog{" +
"userId='" + userId + '\'' +
", installationId='" + installationId + '\'' +
", level='" + level + '\'' +
", tag='" + tag + '\'' +
", message='" + message + '\'' +
", stackTrace='" + stackTrace + '\'' +
", deviceInfo=" + deviceInfo +
", versionInfo=" + versionInfo +
", createdAt=" + createdAt +
'}';
}
}
|
package com.poker.cards;
/**
* All the possible card suits
*
* @author Zack Davidson <zackdavidson2014@outlook.com>
*/
public enum CardSuit
{
/**
* The hearts suit
*/
HEARTS
{
@Override
public String toString()
{
return "Hearts";
}
},
/**
* The spades suit
*/
SPADES
{
@Override
public String toString()
{
return "Spades";
}
},
/**
* The diamonds suit
*/
DIAMONDS
{
@Override
public String toString()
{
return "Diamonds";
}
},
/**
* The clubs suit
*/
CLUBS
{
@Override
public String toString()
{
return "Clubs";
}
}
}
|
package com.tencent.mm.plugin.radar.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import b.b;
import b.c;
import b.c.a.a;
import b.c.b.i;
import b.c.b.j;
import b.e.d;
import com.tencent.mm.plugin.radar.b.c.e;
import com.tencent.mm.sdk.platformtools.x;
public final class RadarStateView extends RelativeLayout {
private static final String TAG = TAG;
static final /* synthetic */ d[] mkL = new d[]{j.a(new i(j.X(RadarStateView.class), "slideOutAnim", "getSlideOutAnim()Landroid/view/animation/Animation;")), j.a(new i(j.X(RadarStateView.class), "slideInAnim", "getSlideInAnim()Landroid/view/animation/Animation;"))};
private static final int mlL = mlL;
public static final a mlM = new a((byte) 0);
e mkq = e.mjz;
private final b mlA = c.b((a) new c(this));
private final b mlB = c.b((a) new b(this));
boolean mlI = true;
final d mlJ = new d(this);
private ImageView mlK;
boolean mlz;
private final Animation getSlideInAnim() {
return (Animation) this.mlB.getValue();
}
private final Animation getSlideOutAnim() {
return (Animation) this.mlA.getValue();
}
public final e getState() {
return this.mkq;
}
public final void setState(e eVar) {
b.c.b.e.i(eVar, "<set-?>");
this.mkq = eVar;
}
private final void setShowing(boolean z) {
this.mlz = z;
}
public RadarStateView(Context context, AttributeSet attributeSet) {
b.c.b.e.i(context, "context");
b.c.b.e.i(attributeSet, "attrs");
super(context, attributeSet);
}
public RadarStateView(Context context, AttributeSet attributeSet, int i) {
b.c.b.e.i(context, "context");
b.c.b.e.i(attributeSet, "attrs");
super(context, attributeSet, i);
}
/* renamed from: bpE */
final void a() {
x.d(TAG, " state : " + this.mkq);
if (this.mlI) {
ImageView imageView;
switch (f.mkC[this.mkq.ordinal()]) {
case 1:
setVisibility(8);
return;
case 2:
setBackgroundResource(com.tencent.mm.plugin.radar.a.e.radar_search_blue_bg);
imageView = this.mlK;
if (imageView == null) {
b.c.b.e.cJM();
}
imageView.setImageResource(com.tencent.mm.plugin.radar.a.e.radar_search_waiting);
setVisibility(0);
return;
case 3:
setBackgroundResource(com.tencent.mm.plugin.radar.a.e.radar_search_green_bg);
imageView = this.mlK;
if (imageView == null) {
b.c.b.e.cJM();
}
imageView.setImageResource(com.tencent.mm.plugin.radar.a.e.radar_search_ok);
setVisibility(0);
return;
case 4:
setBackgroundResource(com.tencent.mm.plugin.radar.a.e.radar_search_green_bg);
imageView = this.mlK;
if (imageView == null) {
b.c.b.e.cJM();
}
imageView.setImageResource(com.tencent.mm.plugin.radar.a.e.radar_search_hi);
setVisibility(0);
return;
default:
return;
}
}
setVisibility(8);
}
final void init() {
if (this.mlK == null) {
this.mlK = new ImageView(getContext());
LayoutParams layoutParams = new LayoutParams(-2, -2);
layoutParams.addRule(11);
layoutParams.addRule(15);
layoutParams.setMargins(0, 0, com.tencent.mm.bp.a.fromDPToPix(getContext(), 5), com.tencent.mm.bp.a.fromDPToPix(getContext(), 2));
ImageView imageView = this.mlK;
if (imageView != null) {
imageView.setLayoutParams(layoutParams);
}
addView(this.mlK);
}
}
public final void bpF() {
if (this.mlI) {
init();
a();
this.mlz = true;
startAnimation(getSlideOutAnim());
}
}
public final void bpG() {
if (this.mlI) {
init();
a();
startAnimation(getSlideInAnim());
}
}
}
|
package com.passing.hibernate.dao;
import java.util.List;
import com.passing.hibernate.beans.TbEnFrequency;
public interface TbEnFrequencyDao {
/**
* @param searchWord
* @return a list contains matched records for auto complete source
*/
List<TbEnFrequency> searchForAutoComplete(String searchWord);
boolean insertWord(TbEnFrequency wordInFrequency);
boolean updateWordFrequency(TbEnFrequency wordInFrequency);
}
|
/**
* Created by jessastbury on 15/02/2017.
*/
public class Diamond {
public void isoscelesTriangle(int num, boolean diamond) {
int lines = diamond ? num - 1 : num;
for (int i = 0; i < lines; i++) {
printSpaces(num, i);
printStars(i);
System.out.println("");
}
}
public void drawDiamond(int num) {
isoscelesTriangle(num, true);
middleLine(num);
reverseIsoscelesTriangle(num, true);
}
public void drawDiamondName(int num, String name) {
isoscelesTriangle(num, true );
System.out.println(name);
reverseIsoscelesTriangle(num, true);
}
private void reverseIsoscelesTriangle(int num, boolean diamond) {
int lines = diamond ? num - 1 : num;
for (int i = lines; i > 0; i--) {
printSpaces(num + 1, i);
printStars(i - 1);
System.out.println("");
}
}
private void printSpaces(int size, int line) {
for (int x = line; x < size - 1; x++)
System.out.print(" ");
}
private void printStars(int line) {
for (int x = 0; x < line * 2 + 1; x++)
System.out.print("*");
}
private void middleLine(int size) {
printStars(size - 1);
System.out.println();
}
}
|
package com.paytechnologies.cloudacar;
import java.util.ArrayList;
import java.util.List;
import com.paytechnologies.cloudacar.parsetask.Message;
import com.paytechnologies.cloudacar.parsetask.MessageHelper;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;
import android.util.Log;
public class PendingNotification extends SQLiteOpenHelper{
SharedPreferences ifTableExistprefs;
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
public static String TABLE_CONTACTS = "";
Context c;
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_MESSAGE = "message";
static boolean ifExists = false;
SQLiteDatabase db;
ArrayList<String> contacts;
public PendingNotification(Context context, String name) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.TABLE_CONTACTS = name;
Log.d("Table to be created", name);
createTable(context, name);
this.c = context;
}
private void createTable(Context context, String name) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getWritableDatabase();
String tableName = "userId"+name;
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + tableName + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT, " + KEY_MESSAGE + " TEXT)";
Log.d("table name", TABLE_CONTACTS);
Log.d("Table is", CREATE_CONTACTS_TABLE);
db.execSQL(CREATE_CONTACTS_TABLE);
setPrefs(context);
}
public PendingNotification(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
// ifExists(TABLE_CONTACTS);
}
public void setPrefs(Context c) {
// TODO Auto-generated method stub
Log.d("shared prefs", "Shared prefs");
ifTableExistprefs = PreferenceManager.getDefaultSharedPreferences(c);
Editor editor = ifTableExistprefs.edit();
editor.putBoolean("TableExist", true);
editor.commit();
Boolean ifexist = ifTableExistprefs.getBoolean("TableExist", false);
Log.d("Table Created Shard Prefs DB helper", ""+ifexist);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
public void addContact(MessageHelper contact,String userId) {
SQLiteDatabase db = this.getWritableDatabase();
String tableName = "userId"+userId;
Log.d("name is", ""+contact.getName());
Log.d("name is", ""+contact.getMessage());
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_MESSAGE, contact.getMessage()); // Contact Phone Number
// Inserting Row
db.insert(tableName, null, values);
db.close(); // Closing database connection
}
public List<ArrayList<String>> getAllTRipRequests(String toS) {
List<ArrayList<String>> contactList = new ArrayList<ArrayList<String>>();
Log.d("Table to be retived", toS);
String selectQuery = "SELECT * FROM " + toS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Message m = new Message();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contacts = new ArrayList<String>();
Log.d("Name is:", cursor.getString(1));
Log.d("Message is is:", cursor.getString(2));
contacts.add(cursor.getString(1));
contacts.add(cursor.getString(2));
contactList.add(contacts);
} while (cursor.moveToNext());
}
Log.d("size in db", ""+contactList.size());
return contactList;
}
}
|
package cn.fuego.led.ui.home;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import cn.fuego.led.R;
import cn.fuego.led.ui.base.LedBaseListActivity;
import cn.fuego.led.ui.widget.OrderButton;
import cn.fuego.led.webservice.up.model.base.EvalJson;
import cn.fuego.led.webservice.up.model.base.EvalTypeJson;
import cn.fuego.led.webservice.up.model.base.ProductJson;
import cn.fuego.led.webservice.up.rest.WebServiceContext;
import cn.fuego.misp.service.http.MispHttpHandler;
import cn.fuego.misp.service.http.MispHttpMessage;
import cn.fuego.misp.ui.model.ListViewResInfo;
import cn.fuego.misp.webservice.json.MispBaseReqJson;
import cn.fuego.misp.webservice.json.MispBaseRspJson;
public class ProEvalCreateActivity extends LedBaseListActivity<EvalTypeJson>
{
private ProductJson product;
private Map<Integer,EvalJson> eval_map = new HashMap<Integer, EvalJson>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public void initRes()
{
this.activityRes.setAvtivityView(R.layout.activity_pro_eval_create);
this.activityRes.setSaveBtnName(getResources().getString(R.string.btn_save));
this.activityRes.setName(getResources().getString(R.string.title_activity_pro_eval_create));
this.listViewRes.setListView(R.id.pro_eval_create_list);
this.listViewRes.setListItemView(R.layout.list_item_eval_create);
product = (ProductJson) this.getIntent().getSerializableExtra(ListViewResInfo.SELECT_ITEM);
}
public static void jump(Context context,ProductJson json)
{
Intent i = new Intent();
i.setClass(context, ProEvalCreateActivity.class);
i.putExtra(ListViewResInfo.SELECT_ITEM, json);
context.startActivity(i);
}
@Override
public void saveOnClick(View v)
{
if(eval_map.size()==0)
{
return;
}
List<EvalJson> evalList = new ArrayList<EvalJson>();
for(Integer key :eval_map.keySet())
{
evalList.add(eval_map.get(key));
}
MispBaseReqJson req = new MispBaseReqJson();
req.setObj(evalList);
WebServiceContext.getInstance().getProductRest(new MispHttpHandler(){
@Override
public void handle(MispHttpMessage message)
{
if(message.isSuccess())
{
finish();
}
else
{
showMessage(message);
}
}
}).createEvalList(req);
}
@Override
public View getListItemView(View view, final EvalTypeJson item)
{
if(null==eval_map.get(item.getEval_type_id()))
{
EvalJson e = new EvalJson();
e.setEval_type(item.getEval_type_id());
e.setEval_obj_id(product.getProduct_id());
eval_map.put(item.getEval_type_id(), e);
}
TextView txt_name = (TextView) view.findViewById(R.id.item_eval_create_name);
txt_name.setText(item.getEval_type_name());
RatingBar rb_score = (RatingBar) view.findViewById(R.id.item_eval_create_rating);
rb_score.setRating(0);
rb_score.setOnRatingBarChangeListener(new OnRatingBarChangeListener()
{
@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser)
{
if(null!=eval_map.get(item.getEval_type_id()))
{
eval_map.get(item.getEval_type_id()).setEval_value(rating);
}
}
});
return view;
}
@Override
public void loadSendList()
{
MispBaseReqJson req = new MispBaseReqJson();
WebServiceContext.getInstance().getProductRest(this).loadEvalType(req);
}
@Override
public List<EvalTypeJson> loadListRecv(Object obj)
{
MispBaseRspJson rsp = (MispBaseRspJson) obj;
return rsp.GetReqCommonField(new TypeReference<List<EvalTypeJson>>(){});
}
@Override
public void onOrderStateChanged(OrderButton orderBtn, Integer orderState)
{
// TODO Auto-generated method stub
}
@Override
public void onHeightChanged(CompoundButton buttonView)
{
// TODO Auto-generated method stub
}
}
|
package MainPackage;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AccountTest {
Account myTest;
@Before
public void setUp() throws Exception {
myTest = new Account(1112, 20000);
}
@After
public void tearDown() throws Exception {
myTest = null;
}
@Test
public void test() throws InsufficientFundsException {
myTest.setAnnualInterestRate(4.5);
myTest.withdraw(2500);
assertEquals("Withdraw Test", (long)myTest.getBalance(), (long)17500.00);
myTest.deposite(3000);
assertEquals("Deposit Test", (long)myTest.getBalance(), (long)20500.00);
Date myDate = myTest.getDateCreated();
System.out.printf("The monthly interest rate is %.2f%%, current balance is $%.2f, the date account is %s", myTest.getMonthlyInterestRate(), myTest.getBalance(), myDate);
}
@Test (expected = InsufficientFundsException.class)
public final void withdraw_more() throws InsufficientFundsException {
myTest.withdraw(300000);
}
}
|
package com.wanglu.movcat.controller;
import com.wanglu.movcat.model.Variety;
import com.wanglu.movcat.service.VarietyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/variety")
public class VarietyController {
@Autowired
private VarietyService varietyService;
/**
* 获取猫品种列表
* @return
*/
@GetMapping("/getVariety")
public List<Variety> getVariety() {
return varietyService.getVariety();
}
/**
* 获取猫详情
* @return
*/
@GetMapping("/getVarietyDetail")
public String getVarietyDetail(Integer id,Model model) {
model.addAttribute("variety", varietyService.getVarietyDetail(id));
return "detail";
}
}
|
package com.ibeiliao.pay.commons.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import javax.sql.DataSource;
/**
* 事务管理
* copy 了 com.beiliao.shared.datasource.MultiDataSourceTransactionManager
* @author linyi 2016/8/9.
*/
public class MultiDataSourceTransactionManager extends DataSourceTransactionManager {
private static final Logger logger = LoggerFactory.getLogger(MultiDataSourceTransactionManager.class);
public MultiDataSourceTransactionManager(DataSource dataSource){
super(dataSource);
}
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
if (definition != null && definition.isReadOnly()) {
DataSourceContext.setReadonly(true);
} else {
DataSourceContext.setReadonly(false);
if (definition == null)
logger.info("definition: IS NULL");
else
logger.info("definition name: {}, isolationLevel: {}, readonly: {}",
definition.getName(), definition.getIsolationLevel(), definition.isReadOnly());
}
super.doBegin(transaction, definition);
}
@Override
protected void doCleanupAfterCompletion(Object transaction) {
super.doCleanupAfterCompletion(transaction);
DataSourceContext.remove();
}
}
|
package oblici;
import java.awt.Graphics;
public class Krug extends PovrsinskiOblik implements Pomerljiv{
private Tacka centar;
private int poluprecnik;
public Krug() {
}
public Krug(Tacka centar, int poluprecnik) {
this.centar = centar;
this.poluprecnik = poluprecnik;
}
public Krug(Tacka centar, int poluprecnik, String boja) {
this(centar, poluprecnik);
this.setBoja(boja);
}
public Krug(Tacka centar, int poluprecnik, String boja, String bojaUnutrasnjosti) {
this(centar, poluprecnik, boja);
this.setBojaUnutrasnjosti(bojaUnutrasnjosti);
}
public Tacka getCentar() {
return centar;
}
public void setCentar(Tacka centar) {
this.centar = centar;
}
public int getPoluprecnik() {
return poluprecnik;
}
public void setPoluprecnik(int poluprecnik) {
this.poluprecnik = poluprecnik;
}
public void pomeriNa(int novoX, int novoY) {
centar.pomeriNa(novoX, novoY);
}
public void pomeriZa(int novoX, int novoY) {
centar.pomeriZa(novoX, novoY);
}
public double obim() {
return 2*poluprecnik*Math.PI;
}
public double povrsina() {
return poluprecnik*poluprecnik*Math.PI;
}
@Override
public void crtajSe(Graphics g) {
g.setColor(this.pronadjiBoju(getBoja()));
g.drawOval(this.getCentar().getX()-poluprecnik,
this.getCentar().getY()-poluprecnik,
2*poluprecnik,
2*poluprecnik);
if(this.isSelektovan()) {
selektovan(g);
}
}
@Override
public void popuni(Graphics g) {
g.setColor(this.pronadjiBoju(getBojaUnutrasnjosti()));
g.fillOval(this.getCentar().getX()-poluprecnik,
this.getCentar().getY()-poluprecnik,
2*poluprecnik,
2*poluprecnik);
}
@Override
public int compareTo(Object o) {
if (o instanceof Krug) {
Krug prosledjen = (Krug)o;
return this.poluprecnik - prosledjen.poluprecnik;
} else {
return 0;
}
}
@Override
public void selektovan(Graphics g) {
centar.selektovan(g);
Tacka gore = new Tacka(centar.getX(), centar.getY()-poluprecnik);
Tacka dole = new Tacka(centar.getX(), centar.getY()+poluprecnik);
Tacka levo = new Tacka(centar.getX()-poluprecnik, centar.getY());
Tacka desno = new Tacka(centar.getX()+poluprecnik, centar.getY());
gore.selektovan(g);
dole.selektovan(g);
levo.selektovan(g);
desno.selektovan(g);
}
}
|
package com.javastudio.tutorial.spring;
import com.javastudio.tutorial.spring.api.ProductService;
import com.javastudio.tutorial.spring.service.ProductServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// ProductServiceImpl productService = context.getBean(ProductServiceImpl.class);
ProductService productService = (ProductServiceImpl) context.getBean("ps");
productService.findAllProducts();
//productService.findProduct(1L);
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.jobs;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import edu.tsinghua.lumaqq.models.User;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.resource.Colors;
import edu.tsinghua.lumaqq.ui.MainShell;
import edu.tsinghua.lumaqq.ui.SendIMWindow;
import edu.tsinghua.lumaqq.ui.helper.MessageIDGenerator;
import edu.tsinghua.lumaqq.ui.helper.NormalIMFormalizer;
import edu.tsinghua.lumaqq.widgets.rich.LineStyle;
/**
* 发送普通消息的任务
*
* @author luma
*/
public class SendNormalIMJob extends AbstractJob {
private String msg;
private byte[] bytes;
private User friend;
private int totalFragments;
private int currentFragment;
private char messageId;
public SendNormalIMJob(String msg, User u) {
this.msg = msg;
this.bytes = NormalIMFormalizer.formalize(msg);
this.friend = u;
// 计算分片数
totalFragments = bytes.length / QQ.QQ_MAX_SEND_IM + 1;
// 初始化其他变量
currentFragment = -1;
messageId = MessageIDGenerator.getNext();
}
@Override
public void prepare(MainShell m) {
super.prepare(m);
main.getClient().addQQListener(this);
}
@Override
public void clear() {
main.getClient().removeQQListener(this);
}
@Override
protected boolean canRun() {
return bytes.length > 0;
}
@Override
protected void preLoop() {
sendNextFragment();
}
@Override
protected void postLoop() {
if(exitCode == SUCCESS) {
if(!friend.talkMode) {
// 关闭聊天窗口
main.getDisplay().asyncExec(new Runnable() {
public void run() {
SendIMWindow win = main.getShellRegistry().getSendIMWindow(friend);
if(win != null)
win.closeWindow();
}
});
}
} else if(exitCode == TIMEOUT) {
if(friend.talkMode) {
// 追加失败消息到输出框
main.getDisplay().syncExec(new Runnable() {
public void run() {
SendIMWindow win = main.getShellRegistry().getSendIMWindow(friend);
if(win != null)
win.appendHint(NLS.bind(cluster_im_hint_timemout, msg), SendIMWindow.getOtherStyle());
}
});
} else {
// 解除输入框的不可写状态,显示提示框
main.getDisplay().syncExec(new Runnable() {
public void run() {
SendIMWindow win = main.getShellRegistry().getSendIMWindow(friend);
if(win != null) {
win.getInputBox().setReadonly(false);
win.getInputBox().setBackground(Colors.WHITE);
win.setMinimized(false);
win.setActive();
MessageDialog.openError(win.getShell(), message_box_common_fail_title, message_box_send_message_timeout);
}
}
});
}
}
}
/**
* 发送下一个分片
*/
private void sendNextFragment() {
currentFragment++;
if(currentFragment >= totalFragments) {
exitCode = SUCCESS;
wake();
} else {
LineStyle style = main.getDefaultStyle();
int start = currentFragment * QQ.QQ_MAX_SEND_IM;
byte[] b = new byte[Math.min(QQ.QQ_MAX_SEND_IM, bytes.length - start)];
System.arraycopy(bytes, start, b, 0, b.length);
main.getClient().im_Send(
friend.qq,
b,
messageId,
totalFragments,
currentFragment,
style.fontName,
(style.fontStyle & SWT.BOLD) != 0,
(style.fontStyle & SWT.ITALIC) != 0,
false,
style.fontSize,
style.foreground.getRed(),
style.foreground.getGreen(),
style.foreground.getBlue(),
QQ.QQ_IM_NORMAL_REPLY);
}
}
@Override
protected void OnQQEvent(QQEvent e) {
switch(e.type) {
case QQEvent.IM_SEND_OK:
processSendIMSuccess(e);
break;
case QQEvent.SYS_TIMEOUT:
if(e.operation == QQ.QQ_CMD_SEND_IM)
processSendIMTimeout(e);
break;
}
}
private void processSendIMTimeout(QQEvent e) {
exitCode = TIMEOUT;
wake();
}
private void processSendIMSuccess(QQEvent e) {
sendNextFragment();
}
}
|
package suddenStop;
public class Tim2 extends Cohort {
public Tim2(Firm f) {
super(f);
}
}
|
package assemAssist.model.clock.clock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Test;
import assemAssist.model.clock.clock.ModifiableClock;
import assemAssist.model.clock.event.Event;
import assemAssist.model.clock.event.TimeChangedEvent;
/**
* A test class for the {@link ModifiableClock} class.
*
* @author SWOP Group 3
* @version 3.0
*/
public class ClockTest {
private ModifiableClock clock;
private DateTime time;
@Before
public void initialise() {
time = DateTime.now();
clock = new ModifiableClock(time);
}
@Test
public void testConstructorClock() {
assertEquals(time, clock.getTime());
}
@Test
public void testIsValidTimeTrue() {
assertTrue(clock.isValidTime(time));
}
@Test
public void testIsValidTimeFalse() {
assertFalse(clock.isValidTime(null));
}
@Test
public void testIncreaseTimeTrue() {
DateTime prev = clock.getTime();
Duration passedTime = Duration.ZERO
.plus(Duration.standardMinutes((long) (Math.random() * 10)));
clock.increaseTime(passedTime);
assertEquals(clock.getTime(), prev.plus(passedTime));
}
@Test
public void testIncreaseTimeTrueZero() {
DateTime prev = clock.getTime();
clock.increaseTime(Duration.ZERO);
assertEquals(clock.getTime(), prev);
}
@Test(expected = IllegalArgumentException.class)
public void testIncreaseTimeFalseNull() {
clock.increaseTime(null);
}
@Test(expected = IllegalArgumentException.class)
public void testIncreaseTimeFalseNegative() {
clock.increaseTime(Duration.ZERO.minus(Duration.standardMinutes(5)));
}
@Test
public void testSetTimeValid() {
time = DateTime.now();
clock.setTime(time);
assertEquals(time, clock.getTime());
}
@Test(expected = IllegalArgumentException.class)
public void testSetTimeIllegalArgument() {
clock.setTime(null);
}
@Test
public void testAdvanceDayNotNewDay() {
ModifiableClock clock = new ModifiableClock(DateTime.now().withHourOfDay(23));
clock.advanceDay();
assertEquals(
clock.getTime(),
DateTime.now().plusDays(1).withHourOfDay(6).withMinuteOfHour(0)
.withSecondOfMinute(0).withMillisOfSecond(0));
}
@Test
public void testAdvanceDayAlreadyNewDay() {
ModifiableClock clock = new ModifiableClock(DateTime.now().withHourOfDay(4));
clock.advanceDay();
assertEquals(clock.getTime(), DateTime.now().withHourOfDay(6).withMinuteOfHour(0)
.withSecondOfMinute(0).withMillisOfSecond(0));
}
@Test
public void testAddEvent() {
Event event = new TimeChangedEvent() {
@Override
public void execute(DateTime time) {
return;
}
};
clock.addEvent(event);
assertTrue(clock.events.contains(event));
}
@Test(expected = IllegalArgumentException.class)
public void testAddEventFalse() {
clock.addEvent(null);
}
}
|
package ru.bm.eetp.dto;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import ru.bm.eetp.config.Constants;
@JacksonXmlRootElement(localName = "GWFault", namespace = Constants.ERROR_NAMESPACE)
public class ErrorDetail {
@JacksonXmlProperty(namespace = Constants.ERROR_NAMESPACE)
private String faultString;
@JacksonXmlProperty(namespace = Constants.ERROR_NAMESPACE)
private Detail detail;
public ErrorDetail(int code, String description) {
this.faultString = "DataPower error";
this.detail = new Detail(code, description);
}
public String getFaultString() {
return faultString;
}
public Detail getDetail() {
return detail;
}
public static class Detail {
@JacksonXmlProperty(namespace = Constants.ERROR_NAMESPACE)
private int code;
@JacksonXmlProperty(namespace = Constants.ERROR_NAMESPACE)
private String description;
public Detail(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
}
}
|
package com.rofour.baseball.dao.wallet.mapper;
import javax.inject.Named;
@Named("walletExceptionMapper")
public interface WalletExceptionMapper {
}
|
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class FormPage {
public static void submitForm(WebDriver driver)
{
driver.findElement(By.id("first-name")).sendKeys("bhagya");
driver.findElement(By.id("last-name")).sendKeys("kudupudi");
driver.findElement(By.id("job-title")).sendKeys("QA Engineer");
driver.findElement(By.cssSelector("input#radio-button-3")).click();
driver.findElement(By.id("checkbox-2")).click();
WebElement dropDown = driver.findElement(By.id("select-menu"));
Select s = new Select(dropDown);
s.selectByVisibleText("5-9");
driver.findElement(By.id("datepicker")).click();
driver.findElement(By.xpath("//table[@class='table-condensed']/tbody/tr[5]/td[4]")).click();
driver.findElement(By.cssSelector("a.btn.btn-lg.btn-primary")).click();
}
}
|
package eu.lsem.bakalarka.service;
import org.krysalis.jcharts.properties.PropertyException;
import org.krysalis.jcharts.chartData.ChartDataException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import eu.lsem.bakalarka.model.ChartTypes;
public interface ChartGenerator {
// public void regenerateCharts();
public void setRegenerate();
public InputStream getChart(ChartTypes type);
}
|
package Collections;
import java.util.*;
public class HpComparator_2 {
public static void sort(List list, Comparator c) {
Object anArray[] = list.toArray();
// Arrays.sort(a, c); /////// this is the trick
// http://www.cs.rit.edu/~hpb/Jdk5/api/java/util/ListIterator.html
for (int index=0; index<anArray.length - 1; index++) {
for (int walker=0; walker<anArray.length - index - 1; walker++) {
Object left = anArray[walker];
Object right = anArray[walker+1];
if ( c.compare(left, right ) > 0 ) {
Object tmp = anArray[walker];
anArray[walker] = anArray[walker + 1];
anArray[walker+1] = tmp;
}
}
}
ListIterator i = list.listIterator();
for (int j=0; j<anArray.length; j++) {
i.next();
i.set(anArray[j]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.