text
stringlengths 10
2.72M
|
|---|
package top.kylewang.bos.service.system;
import top.kylewang.bos.domain.system.Menu;
import top.kylewang.bos.domain.system.User;
import java.util.List;
/**
* @author Kyle.Wang
* 2018/1/10 0010 21:21
*/
public interface MenuService {
/**
* 查询菜单列表
* @return
*/
List<Menu> findAll();
/**
* 保存
* @param model
*/
void save(Menu model);
/**
* 根据用户查询菜单
* @param user
* @return
*/
List<Menu> findByUser(User user);
}
|
package LC0_200.LC50_100;
import LeetCodeUtils.MyMatrix;
import LeetCodeUtils.MyPrint;
import org.junit.Test;
import java.util.Arrays;
public class LC85_Maximal_Rectangle {
@Test
public void test() {
System.out.println(maximalRectangle(MyMatrix.matrixAdapter("[[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]", 4, 5)));
}
public int maximalRectangle(char[][] matrix) {
//MyPrint.print2DMatrix(matrix);
if (matrix.length == 0) return 0;
int max = 0;
int len = matrix.length, wid = matrix[0].length;
int[] width = new int[wid + 1];
int[] hight = new int[wid + 1];
for (int i = 0; i < len; ++i) {
Arrays.fill(width, 0);
for (int j = 0; j < wid; ++j) {
width[j + 1] = matrix[i][j] == '0' ? 0 : width[j] + 1;
hight[j + 1] = matrix[i][j] == '0' ? 0 : hight[j + 1] + 1;
int k = 1, idx = j + 1, h = hight[j + 1];
while (k <= width[j + 1]) {
h = Math.min(h, hight[idx]);
max = Math.max(max, h * k);
k++;
idx--;
}
}
}
return max;
}
}
|
package com.esp_ota_update.server.model;
import com.esp_ota_update.server.util.MD5Checksum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Software {
public static final String VERSION_REGEX = "^([A-z0-9_]*)_(\\d+\\.\\d+\\.\\d+)$";
public static final String SOFTWARE_DIRECTORY_PATH = "C:\\localhost\\espota\\";
private final Integer id;
private Integer deviceId;
private Integer previousVersionId;
private String version;
private String file;
private String md5;
private LocalDateTime createdAt;
//JSON constructor
public Software() {
this(0);
}
public Software(int id) {
this.id = id;
//These are defaults values that would be overwritten on db get
this.createdAt = LocalDateTime.now();
this.version = "0.0.0";
}
/**
* @param a Version string A
* @param b Version string B
* @return 1 on A > B, 0 on A = B, -1 on A < B
* @throws Exception when version string is incorrectly formatted or provided different scheme names
*/
public static int compareVersions(String a, String b) throws Exception {
if (!isValidVersionName(a) || !isValidVersionName(b)) {
throw new Exception("WRONG VERSION SCHEME");
}
if (!extractNameFromNameString(a).equals(extractNameFromNameString(b))) {
throw new Exception("DIFFERENT VERSION NAME");
}
String[] partsA = extractVersionFromNameString(a).split("\\.");
String[] partsB = extractVersionFromNameString(b).split("\\.");
int[] numA = Arrays.stream(partsA).mapToInt(Integer::parseInt).toArray();
int[] numB = Arrays.stream(partsB).mapToInt(Integer::parseInt).toArray();
long valA = (long) (numA[0] * 1e12 + numA[1] * 1e6 + numA[2]);
long valB = (long) (numB[0] * 1e12 + numB[1] * 1e6 + numB[2]);
if (valA == valB) {
return 0;
}
return valA > valB ? 1 : -1;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public static String extractVersionFromNameString(String nameString) {
if (nameString == null) {
return null;
}
Matcher m = Pattern.compile(Software.VERSION_REGEX).matcher(nameString);
m.matches();
return m.group(2);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public static String extractNameFromNameString(String nameString) {
if (nameString == null) {
return null;
}
Matcher m = Pattern.compile(Software.VERSION_REGEX).matcher(nameString);
m.matches();
return m.group(1);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean isValidVersionName(String name) {
return Pattern.compile(Software.VERSION_REGEX).matcher(name).matches();
}
public static String createSoftwareNameSchemeFromSoftwareName(String name) {
return name + "_#.#.#";
}
public static String getSoftwarePath(String file) {
return SOFTWARE_DIRECTORY_PATH + file;
}
/**
* @param update Software
* @return true on success
*/
public boolean applyUpdate(Software update) {
if (update.getId() != 0) {
return false;
}
if (update.getDeviceId() != null) {
this.deviceId = update.getDeviceId();
}
if (update.getFile() != null) {
this.file = update.getFile();
this.md5 = this.calculateFileHash(getSoftwarePath(this.file));
}
if (update.getVersion() != null) {
this.version = update.getVersion();
}
if (update.getPreviousVersionId() != null) {
this.previousVersionId = update.getPreviousVersionId();
}
return true;
}
private String calculateFileHash(String filePath) {
try {
return MD5Checksum.get(filePath);
} catch (Exception e) {
return "md5-error";
}
}
public String getSoftwarePath() {
return getSoftwarePath(this.file);
}
@JsonIgnore
public byte[] getBinaries() {
try {
return Files.readAllBytes(Path.of(this.getSoftwarePath()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Integer getDeviceId() {
return this.deviceId;
}
public void setDeviceId(Integer deviceId) {
this.deviceId = deviceId;
}
public Integer getPreviousVersionId() {
return previousVersionId;
}
public void setPreviousVersionId(Integer previousVersionId) {
this.previousVersionId = previousVersionId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
this.md5 = calculateFileHash(getSoftwarePath(file));
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public Integer getId() {
return id;
}
}
|
package jPhone;
import java.util.concurrent.BlockingQueue;
import java.net.*;
import jlibrtp.*;
/**
* this class sends out audio data to participants
* @author terry modified by Nelson
*
*/
public class RTPHandler implements RTPAppIntf {
/**
* the RTP session
*/
private RTPSession m_rtpReceiveSession;
private RTPSession m_rtpSendSession;
private String m_recevierIPAddr;
/**
* when an audio block is received, put the block into this queue.
* Note that for this queue, RTPReceiver is the producer, SoundPlayer is the consumer.
*/
private BlockingQueue<AudioBlock> m_carrierQueue;
/**
* when an audio block is received, RTPReceiver first obtain a blank block from this queue and then write the block.
* Note that for this queue, RTPReceiver is the consumer, SoundPlayer is the producer.
*/
private BlockingQueue<AudioBlock> m_returnQueue;
private boolean closed = false;
/**
* the constructor
* @param receiverIPAddrs specify the participants' IP addresses
* @param RTPport specify the UDP port used for RTP communication
*/
public RTPHandler(String receiverIPAddr, int rtpReceiverPort, int rtcpReceiverPort, int rtpSenderPort, int rtcpSenderPort, BlockingQueue<AudioBlock> carrierQueue, BlockingQueue<AudioBlock> returnQueue)
{
m_recevierIPAddr = receiverIPAddr;
m_carrierQueue = carrierQueue;
m_returnQueue = returnQueue;
// Receive Session
System.out.println("Receive from " + m_recevierIPAddr + " at " + rtpReceiverPort + " " + rtcpReceiverPort);
DatagramSocket rtpReceiverSocket = null;
DatagramSocket rtcpReceiverSocket = null;
try
{
rtpReceiverSocket = new DatagramSocket(rtpReceiverPort);
rtcpReceiverSocket = new DatagramSocket(rtcpReceiverPort);
}
catch(Exception e)
{
System.err.println("RTP session failed to obtain ports.");
e.printStackTrace();
System.exit(1);
}
/*****************************************************************
* Task 2 *
* TODO: *
* Initialize a RTP receive session RTPSession; *
* Set the naivePktReception to be true; *
* Register the RTP session. *
*****************************************************************/
/**** Nelson Code Add by Nelson** Start */
m_rtpReceiveSession = new RTPSession(rtpReceiverSocket, rtcpReceiverSocket);
m_rtpReceiveSession.naivePktReception(true);
m_rtpReceiveSession.RTPSessionRegister(this, null, null);
/**** Nelson Code Add by Nelson** End */
//Send Session
DatagramSocket rtpSenderSocket = null;
DatagramSocket rtcpSenderSocket = null;
try
{
rtpSenderSocket = new DatagramSocket();
rtcpSenderSocket = new DatagramSocket();
}
catch(Exception e)
{
System.err.println("RTP session failed to obtain ports.");
e.printStackTrace();
System.exit(1);
}
/*****************************************************************
* Task 2 *
* TODO: *
* Initialize a RTP send session RTPSession; *
* Register the RTP session. *
*****************************************************************/
/**** Nelson Code Add by Nelson***/
m_rtpSendSession = new RTPSession(rtpSenderSocket, rtcpSenderSocket);
m_rtpSendSession.RTPSessionRegister(this, null, null);
/**** Nelson Code Add by Nelson***/
System.out.println("Send to " + m_recevierIPAddr + " " + rtpSenderPort + " " + rtcpSenderPort);
m_rtpSendSession.addParticipant(new Participant(m_recevierIPAddr, rtpSenderPort, rtcpSenderPort));
}
public int frameSize(int payloadType) {
return 1;
}
public boolean isclosed(){
return closed;
}
public void receiveData(DataFrame frame, Participant participant) {
byte[] data = frame.getConcatenatedData(); // obtain the audio bytes carried by RTP frame
AudioBlock block = null;
System.out.println("Data received ...");
try
{
block = m_returnQueue.take(); // take a blank block from the return queue
System.arraycopy(data, 0, block.data, 0, data.length); // copy the audio data
block.nBytes = data.length;
m_carrierQueue.put(block); // put the block into the carrier queue
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void userEvent(int type, Participant[] participant) {
// do nothing
}
/**
* send out data
* @param data the bytes to be sent
*/
public void sendData(byte data[])
{
System.out.println("Data sent ...");
m_rtpSendSession.sendData(data);
}
public void close() {
/*****************************************************************
* Task 3 *
* TODO: *
* End the RTP send session; *
* End the RTP receive session. *
*****************************************************************/
/**** Nelson Code Add by Nelson***/
m_rtpReceiveSession.endSession();
m_rtpSendSession.endSession();
/**** Nelson Code Add by Nelson***/
}
}
|
import java.util.*;
import edu.duke.*;
public class WordFrequenciesMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
WordFrequenciesMap wfm = new WordFrequenciesMap();
wfm.tester();
}
public void countWords(String filename){
FileResource fr = new FileResource(filename);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> counters = new ArrayList<Integer>();
for(String w : fr.words()){
int index = words.indexOf(w);
if(index==-1){
words.add(w);
counters.add(1);
}else{
int value = counters.get(index);
counters.set(index, value + 1);
}
}
int total = 0;
for(int k = 0; k< words.size(); k++){
if(counters.get(k)>500){
System.out.println(counters.get(k)+"\t"+words.get(k));
}
total += counters.get(k);
}
System.out.println("Total: "+total +"\t"+ "Different: "+words.size());
}
public void countWordsMap(String filename){
FileResource fr = new FileResource(filename);
HashMap<String,Integer> map = new HashMap<String,Integer>();
for(String w: fr.words()){
if(!map.keySet().contains(w)){
map.put(w, 1);
}else{
int value = map.get(w);
map.put(w, value+1);
}
}
int total =0;
for(String w : map.keySet()){
if(map.get(w)>500){
System.out.println(map.get(w)+"\t"+w);
}
total += map.get(w);
}
System.out.println("Total: "+total+"\t"+"Different: "+map.keySet().size());
}
public void tester(){
String filename = "data/kjv10.txt";
double start = System.currentTimeMillis();
countWords(filename);
double end = System.currentTimeMillis();
double time = (end-start)/1000;
System.out.println("Time: "+time);
start = System.currentTimeMillis();
countWordsMap(filename);
end = System.currentTimeMillis();
time = (end-start)/1000;
System.out.println("Time: "+time);
}
}
|
package OCP;
/**
* @Author:Jack
* @Date: 2021/8/22 - 0:50
* @Description: OCP
* @Version: 1.0
*/
public interface IBook {
public String getName();
public double getPrice();
public String getAuthor();
}
|
package com.dictionary.controller;
import com.dictionary.domain.User;
import com.dictionary.reposity.UserRepository;
import com.dictionary.service.TokenManager;
import com.dictionary.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Bae on 2017-02-24.
*/
@RestController
public class TokenController {
@Autowired
TokenManager tokenManager;
@Autowired
UserRepository userRepository;
@RequestMapping(value = "token", method = RequestMethod.POST)
public Object getToen(User user) throws UnsupportedEncodingException {
HashMap<String,Object> map=new HashMap();
String token;
//아이디 비번이 같으면
token=tokenManager.getToken(user);
if(token!=null){
map.put("token",token);
return new ResponseEntity<>(map, HttpStatus.OK);
}
map.put("message","토큰발행 실패,아이디나 패스워드를 확인하세요.");
return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
}
@RequestMapping(value = "token/verify", method = RequestMethod.GET)
public Object authToken(@RequestParam(value = "token") String token) {
Map map=new HashMap();
try{
if(token!=null&&AuthToken.authToken(token)) {
User dbUser=userRepository.findOne(AuthToken.getUser(token));
if(dbUser!=null&&dbUser.getToken().equals(token)) {
map.put("message", "true");
return new ResponseEntity<>(map, HttpStatus.OK);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
map.put("message","토큰이잘못되었거나 만료되었습니다.");
return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
}
}
|
package yao.servlet.englishWordServlet;
import yao.bean.EnglishWord;
import yao.service.EnglishWordService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
public class ListEnglishWordsServlet extends HttpServlet {
private static final String LIST_ENGLISHWORDS = "listEnglishWord.jsp";
private EnglishWordService englishWordService;
private List<EnglishWord> englishWordList;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
englishWordService = new EnglishWordService();
HttpSession session = request.getSession();
englishWordList = englishWordService.getAllEnglishWord();
session.setAttribute("englishWordList",englishWordList);
request.getRequestDispatcher(LIST_ENGLISHWORDS).forward(request,response);
}
}
|
package opengl;
import javax.media.opengl.GL2;
public abstract class Drawable {
public abstract void draw(GL2 gl);
}
|
package iansteph.nhlp3.eventpublisher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class IntegrationTestBase {
protected static RestTemplate createRestTemplateAndRegisterCustomObjectMapper() {
final RestTemplate restTemplate = new RestTemplate();
final MappingJackson2HttpMessageConverter messageConverter = restTemplate.getMessageConverters().stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow( () -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
messageConverter.getObjectMapper().registerModule(new JavaTimeModule()).configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
false);
return restTemplate;
}
protected static ObjectMapper getObjectMapperFromRestTemplate(final RestTemplate restTemplate) {
return restTemplate.getMessageConverters().stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow( () -> new RuntimeException("MappingJackson2HttpMessageConverter not found"))
.getObjectMapper();
}
public static class SqsQueueMetadata {
private final String queueUrl;
private String queueArn;
public SqsQueueMetadata(final String queueUrl) {
this.queueUrl = queueUrl;
}
public String getQueueUrl() {
return this.queueUrl;
}
public void setQueueArn(final String queueArn) {
this.queueArn = queueArn;
}
public String getQueueArn() {
return this.queueArn;
}
}
}
|
import ui.Colour;
public class Node implements Cluster {
// Contains either Leaf or Cluster
public Cluster [] clusters;
private int depth, width;
private Cluster cluster1, cluster2;
private Colour colour;
Node(Cluster cluster1, Cluster cluster2){
this.cluster1 = cluster1;
this.cluster2 = cluster2;
clusters = new Cluster[2];
clusters[0] = cluster1;
clusters[1] = cluster2;
width = 2;
depth = getDepth();
}
public int getDepth(){
depth = Math.max(cluster1.getDepth(), cluster2.getDepth());
return depth;
}
public int getWidth(){
if (cluster1 != null && cluster2 != null){
width = cluster1.getWidth() + cluster2.getWidth();
return width;
} else {
return 0; // Should not happen
}
}
public UnitRow getUnits(){
UnitRow newUnitRow;
UnitRow unitRow1;
UnitRow unitRow2;
if (cluster1 != null && cluster2 != null){
newUnitRow = new UnitRow(getWidth());
unitRow1 = cluster1.getUnits();
unitRow2 = cluster2.getUnits();
for (int i = 0; i < cluster1.getWidth(); i++){
newUnitRow.addPredefinedUnit(unitRow1.getUnit(i));
}
for (int i = 0; i < cluster2.getWidth(); i++){
newUnitRow.addPredefinedUnit(unitRow2.getUnit(i));
}
return newUnitRow;
} else {
return null; // Should not happen
}
}
public boolean hasChildren(){
if (depth > 0){
return true;
} else {
return false;
}
}
}
|
package com.dict.hm.dictionary.ui.dialog;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import com.dict.hm.dictionary.R;
/**
* Created by hm on 15-5-28.
*/
public class SwitchDictDialog extends DialogFragment {
private SwitchDictDialogListener listener;
public static final String ARRAY_DATA = "data";
public static final String CHECKED = "checked";
public interface SwitchDictDialogListener {
void onSwitchDictClick(int which);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (SwitchDictDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SwitchDictDialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = getArguments();
CharSequence[] items = bundle.getCharSequenceArray(ARRAY_DATA);
int position = bundle.getInt(CHECKED);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.drawer_dict_switch);
builder.setSingleChoiceItems(items, position, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onSwitchDictClick(which);
dismiss();
}
});
return builder.create();
}
}
|
package conf;
// code basically very similiar to Nate's that we used during midterms https://github.com/YogoGit
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import play.db.DB;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
public class DataConfig {
@Bean //using hibernate
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter hibernateAdapter = new HibernateJpaVendorAdapter();
hibernateAdapter.setShowSql(false);
hibernateAdapter.setGenerateDdl(true);
hibernateAdapter.setDatabase(Database.MYSQL);
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPackagesToScan("models");
entityManagerFactory.setJpaVendorAdapter(hibernateAdapter);
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
@Bean
public DataSource dataSource() {
// Return the datasource from the play framework.
return DB.getDataSource();
}
}
|
package com.debugers.alltv.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class LiveRoom implements Comparable<LiveRoom>, Serializable {
private String roomId;//房间号
private String com;//哪个平台
private String cateId;//分类id
private String roomThumb;//房间缩略图
private String cateName;//分类名
private String roomName;//房间名
private Integer roomStatus; //1 开播 2 未开播
private Date startTime;
private String ownerName;//主播名
private String avatar;//主播头像
private Long online; //热度
private String realUrl; //真是直播地址
@Override
public int compareTo(LiveRoom room) {
return (int) (room.getOnline()-online);
}
}
|
/**
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.fountainhead.client.view;
import com.fountainhead.client.presenter.ReportPresenter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
/**
* The view implementation for
* {@link com.fountainhead.client.presenter.ReportPresenter}.
*
*/
@SuppressWarnings("rawtypes")
public class ReportView extends ViewWithUiHandlers<ReportUiHandlers>
implements
ReportPresenter.MyView {
/**
*/
public interface Binder extends UiBinder<Widget, ReportView> {
}
private final Widget widget;
@Inject
public ReportView(Binder uiBinder) {
widget = uiBinder.createAndBindUi(this);
this.bindCustomUiHandlers();
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setAdmin(boolean isAdmin) {
}
@Override
public void setUserName(String username) {
}
@UiField
Button button1;
@UiField
Button button2;
@UiField
Button button3;
@UiField
Button saveButton;
@UiField
Button runButton;
@UiField
ListBox itemsList;
@UiField
Tree itemsTree;
void onButtonClick(ClickEvent event) {
}
@Override
public Tree getTree() {
// TODO Auto-generated method stub
return itemsTree;
}
@SuppressWarnings("unchecked")
protected void bindCustomUiHandlers() {
itemsTree.addSelectionHandler(new SelectionHandler() {
@Override
public void onSelection(SelectionEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onSelection();
}
}
});
}
@Override
public ListBox getList() {
// TODO Auto-generated method stub
return itemsList;
}
}
|
package com.tencent.mm.plugin.remittance.bankcard.a;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.zx;
import com.tencent.mm.protocal.c.zy;
import com.tencent.mm.sdk.platformtools.x;
public final class g extends b {
private final String TAG = "MicroMsg.NetSceneBankRemitGetBankInfo";
public String bKg;
private b diG;
private e diJ;
public zy mtY;
public g(String str, String str2) {
a aVar = new a();
aVar.dIG = new zx();
aVar.dIH = new zy();
aVar.dIF = 1542;
aVar.uri = "/cgi-bin/mmpay-bin/getbankinfo_tsbc";
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
((zx) this.diG.dID.dIL).rrh = str;
this.bKg = str2;
}
public final int getType() {
return 1542;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
public final void b(int i, int i2, String str, q qVar) {
x.i("MicroMsg.NetSceneBankRemitGetBankInfo", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
this.mtY = (zy) ((b) qVar).dIE.dIL;
x.i("MicroMsg.NetSceneBankRemitGetBankInfo", "retcode: %s, retmsg: %s", new Object[]{Integer.valueOf(this.mtY.hUm), this.mtY.hUn});
if (this.diJ != null) {
this.diJ.a(i, i2, str, this);
}
}
protected final void f(q qVar) {
zy zyVar = (zy) ((b) qVar).dIE.dIL;
this.uXe = zyVar.hUm;
this.uXf = zyVar.hUn;
}
}
|
/**
* Usada como objeto de teste para compor as classes que encapsulam a coleção
* TreeSet.
*
* @author Luciano Junior
* @version 1.0 (junho-2019)
*/
public class Sorteio {
private final static int LIMITEINFERIOR = 1;
private final static int LIMITESUPERIOR = 98;
private final static int QUANTIDADE = 4;
protected static int limiteInferior = Sorteio.LIMITEINFERIOR;
protected static int limiteSuperior = Sorteio.LIMITESUPERIOR;
protected static int quantidade = Sorteio.QUANTIDADE;
/** */
private Data data;
private NumerosSorteados sorteio;
/**
* Construtor para inicializar valores nos campos
*
* @param _data data inicial do sorteio.
*/
public Sorteio (Data _data) {
this.data = _data;
this.sorteio = new NumerosSorteados(quantidade);
}
/**
* @return o Valor Minimo
*/
public static int getLimiteInf() {
return Sorteio.limiteInferior;
}
/**
* @param _limiteInferior o Valor Minimo
*/
public static void setLimiteInf(int _limiteInferior) {
Sorteio.limiteInferior = _limiteInferior;
}
/**
* @return o Valor Maximo
*/
public static int getLimiteSup() {
return Sorteio.limiteSuperior;
}
/**
* @param _limiteSuperior o Valor Maximo
*/
public static void setLimiteSup(int _limiteSuperior) {
Sorteio.limiteSuperior = _limiteSuperior;
}
/**
* @return A quantidade de numeros
*/
public static int getQuantidade() {
return Sorteio.quantidade;
}
/**
* @param _quantidade A Quantidade de numeros
*/
public static void setQuantidade(int _quantidade) {
Sorteio.quantidade = _quantidade;
}
/**
* pega a data
*
* @return data
*/
public Data getData() {
return this.data;
}
/**
* Método sobreposto para devolver os campos formatados em uma String
*
* @return retorna String com todos os valores dos campos
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getData());
builder.append(" ");
builder.append(sorteio);
return builder.toString();
}
}
|
package ls.example.t.zero2line.util;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* <pre>
* author:
* ___ ___ ___ ___
* _____ / /\ /__/\ /__/| / /\
* / /::\ / /::\ \ \:\ | |:| / /:/
* / /:/\:\ ___ ___ / /:/\:\ \ \:\ | |:| /__/::\
* / /:/~/::\ /__/\ / /\ / /:/~/::\ _____\__\:\ __| |:| \__\/\:\
* /__/:/ /:/\:| \ \:\ / /:/ /__/:/ /:/\:\ /__/::::::::\ /__/\_|:|____ \ \:\
* \ \:\/:/~/:/ \ \:\ /:/ \ \:\/:/__\/ \ \:\~~\~~\/ \ \:\/:::::/ \__\:\
* \ \::/ /:/ \ \:\/:/ \ \::/ \ \:\ ~~~ \ \::/~~~~ / /:/
* \ \:\/:/ \ \::/ \ \:\ \ \:\ \ \:\ /__/:/
* \ \::/ \__\/ \ \:\ \ \:\ \ \:\ \__\/
* \__\/ \__\/ \__\/ \__\/
* blog : http://blankj.com
* time : 16/12/08
* desc : utils about initialization
* </pre>
*/
public final class Utils {
private static final String PERMISSION_ACTIVITY_CLASS_NAME =
"com.blankj.utilcode.util.PermissionUtils$PermissionActivity";
private static final ls.example.t.zero2line.util.Utils.ActivityLifecycleImpl ACTIVITY_LIFECYCLE = new ls.example.t.zero2line.util.Utils.ActivityLifecycleImpl();
private static final java.util.concurrent.ExecutorService UTIL_POOL = java.util.concurrent.Executors.newFixedThreadPool(3);
private static final android.os.Handler UTIL_HANDLER = new android.os.Handler(android.os.Looper.getMainLooper());
@android.annotation.SuppressLint("StaticFieldLeak")
private static android.app.Application sApplication;
private Utils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Init utils.
* <p>Init it in the class of Application.</p>
*
* @param context context
*/
public static void init(final android.content.Context context) {
if (context == null) {
init(getApplicationByReflect());
return;
}
init((android.app.Application) context.getApplicationContext());
}
/**
* Init utils.
* <p>Init it in the class of Application.</p>
*
* @param app application
*/
public static void init(final android.app.Application app) {
if (sApplication == null) {
if (app == null) {
sApplication = getApplicationByReflect();
} else {
sApplication = app;
}
sApplication.registerActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE);
} else {
if (app != null && app.getClass() != sApplication.getClass()) {
sApplication.unregisterActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE);
ACTIVITY_LIFECYCLE.mActivityList.clear();
sApplication = app;
sApplication.registerActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE);
}
}
}
/**
* Return the context of Application object.
*
* @return the context of Application object
*/
public static android.app.Application getApp() {
if (sApplication != null) return sApplication;
android.app.Application app = getApplicationByReflect();
init(app);
return app;
}
static ls.example.t.zero2line.util.Utils.ActivityLifecycleImpl getActivityLifecycle() {
return ACTIVITY_LIFECYCLE;
}
static java.util.LinkedList<android.app.Activity> getActivityList() {
return ACTIVITY_LIFECYCLE.mActivityList;
}
static android.content.Context getTopActivityOrApp() {
if (isAppForeground()) {
android.app.Activity topActivity = ACTIVITY_LIFECYCLE.getTopActivity();
return topActivity == null ? ls.example.t.zero2line.util.Utils.getApp() : topActivity;
} else {
return ls.example.t.zero2line.util.Utils.getApp();
}
}
static boolean isAppForeground() {
android.app.ActivityManager am = (android.app.ActivityManager) ls.example.t.zero2line.util.Utils.getApp().getSystemService(android.content.Context.ACTIVITY_SERVICE);
if (am == null) return false;
java.util.List<android.app.ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return false;
for (android.app.ActivityManager.RunningAppProcessInfo aInfo : info) {
if (aInfo.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (aInfo.processName.equals(ls.example.t.zero2line.util.Utils.getApp().getPackageName())) {
return true;
}
}
}
return false;
}
static <T> ls.example.t.zero2line.util.Utils.Task<T> doAsync(final ls.example.t.zero2line.util.Utils.Task<T> task) {
UTIL_POOL.execute(task);
return task;
}
public static void runOnUiThread(final Runnable runnable) {
if (android.os.Looper.myLooper() == android.os.Looper.getMainLooper()) {
runnable.run();
} else {
ls.example.t.zero2line.util.Utils.UTIL_HANDLER.post(runnable);
}
}
public static void runOnUiThreadDelayed(final Runnable runnable, long delayMillis) {
ls.example.t.zero2line.util.Utils.UTIL_HANDLER.postDelayed(runnable, delayMillis);
}
static String getCurrentProcessName() {
String name = getCurrentProcessNameByFile();
if (!android.text.TextUtils.isEmpty(name)) return name;
name = getCurrentProcessNameByAms();
if (!android.text.TextUtils.isEmpty(name)) return name;
name = getCurrentProcessNameByReflect();
return name;
}
static void fixSoftInputLeaks(final android.view.Window window) {
android.view.inputmethod.InputMethodManager imm =
(android.view.inputmethod.InputMethodManager) ls.example.t.zero2line.util.Utils.getApp().getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
String[] leakViews = new String[]{"mLastSrvView", "mCurRootView", "mServedView", "mNextServedView"};
for (String leakView : leakViews) {
try {
java.lang.reflect.Field leakViewField = android.view.inputmethod.InputMethodManager.class.getDeclaredField(leakView);
if (leakViewField == null) continue;
if (!leakViewField.isAccessible()) {
leakViewField.setAccessible(true);
}
Object obj = leakViewField.get(imm);
if (!(obj instanceof android.view.View)) continue;
android.view.View view = (android.view.View) obj;
if (view.getRootView() == window.getDecorView().getRootView()) {
leakViewField.set(imm, null);
}
} catch (Throwable ignore) {/**/}
}
}
static SPUtils getSpUtils4Utils() {
return SPUtils.getInstance("Utils");
}
///////////////////////////////////////////////////////////////////////////
// private method
///////////////////////////////////////////////////////////////////////////
private static String getCurrentProcessNameByFile() {
try {
java.io.File file = new java.io.File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
java.io.BufferedReader mBufferedReader = new java.io.BufferedReader(new java.io.FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String getCurrentProcessNameByAms() {
android.app.ActivityManager am = (android.app.ActivityManager) ls.example.t.zero2line.util.Utils.getApp().getSystemService(android.content.Context.ACTIVITY_SERVICE);
if (am == null) return "";
java.util.List<android.app.ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return "";
int pid = android.os.Process.myPid();
for (android.app.ActivityManager.RunningAppProcessInfo aInfo : info) {
if (aInfo.pid == pid) {
if (aInfo.processName != null) {
return aInfo.processName;
}
}
}
return "";
}
private static String getCurrentProcessNameByReflect() {
String processName = "";
try {
android.app.Application app = ls.example.t.zero2line.util.Utils.getApp();
java.lang.reflect.Field loadedApkField = app.getClass().getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(app);
java.lang.reflect.Field activityThreadField = loadedApk.getClass().getDeclaredField("mActivityThread");
activityThreadField.setAccessible(true);
Object activityThread = activityThreadField.get(loadedApk);
java.lang.reflect.Method getProcessName = activityThread.getClass().getDeclaredMethod("getProcessName");
processName = (String) getProcessName.invoke(activityThread);
} catch (Exception e) {
e.printStackTrace();
}
return processName;
}
private static android.app.Application getApplicationByReflect() {
try {
@android.annotation.SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");
Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
Object app = activityThread.getMethod("getApplication").invoke(thread);
if (app == null) {
throw new NullPointerException("u should init first");
}
return (android.app.Application) app;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new NullPointerException("u should init first");
}
/**
* Set animators enabled.
*/
private static void setAnimatorsEnabled() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && android.animation.ValueAnimator.areAnimatorsEnabled()) {
return;
}
try {
//noinspection JavaReflectionMemberAccess
java.lang.reflect.Field sDurationScaleField = android.animation.ValueAnimator.class.getDeclaredField("sDurationScale");
sDurationScaleField.setAccessible(true);
float sDurationScale = (Float) sDurationScaleField.get(null);
if (sDurationScale == 0f) {
sDurationScaleField.set(null, 1f);
android.util.Log.i("Utils", "setAnimatorsEnabled: Animators are enabled now!");
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
static class ActivityLifecycleImpl implements android.app.Application.ActivityLifecycleCallbacks {
final java.util.LinkedList<android.app.Activity> mActivityList = new java.util.LinkedList<>();
final java.util.Map<Object, ls.example.t.zero2line.util.Utils.OnAppStatusChangedListener> mStatusListenerMap = new java.util.HashMap<>();
final java.util.Map<android.app.Activity, java.util.Set<ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener>> mDestroyedListenerMap = new java.util.HashMap<>();
private int mForegroundCount = 0;
private int mConfigCount = 0;
private boolean mIsBackground = false;
@Override
public void onActivityCreated(android.app.Activity activity, android.os.Bundle savedInstanceState) {
LanguageUtils.applyLanguage(activity);
setAnimatorsEnabled();
setTopActivity(activity);
}
@Override
public void onActivityStarted(android.app.Activity activity) {
if (!mIsBackground) {
setTopActivity(activity);
}
if (mConfigCount < 0) {
++mConfigCount;
} else {
++mForegroundCount;
}
}
@Override
public void onActivityResumed(final android.app.Activity activity) {
setTopActivity(activity);
if (mIsBackground) {
mIsBackground = false;
postStatus(true);
}
processHideSoftInputOnActivityDestroy(activity, false);
}
@Override
public void onActivityPaused(android.app.Activity activity) {
}
@Override
public void onActivityStopped(android.app.Activity activity) {
if (activity.isChangingConfigurations()) {
--mConfigCount;
} else {
--mForegroundCount;
if (mForegroundCount <= 0) {
mIsBackground = true;
postStatus(false);
}
}
processHideSoftInputOnActivityDestroy(activity, true);
}
@Override
public void onActivitySaveInstanceState(android.app.Activity activity, android.os.Bundle outState) {/**/}
@Override
public void onActivityDestroyed(android.app.Activity activity) {
mActivityList.remove(activity);
consumeOnActivityDestroyedListener(activity);
fixSoftInputLeaks(activity.getWindow());
}
android.app.Activity getTopActivity() {
if (!mActivityList.isEmpty()) {
for (int i = mActivityList.size() - 1; i >= 0; i--) {
android.app.Activity activity = mActivityList.get(i);
if (activity == null
|| activity.isFinishing()
|| (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed())) {
continue;
}
return activity;
}
}
android.app.Activity topActivityByReflect = getTopActivityByReflect();
if (topActivityByReflect != null) {
setTopActivity(topActivityByReflect);
}
return topActivityByReflect;
}
void addOnAppStatusChangedListener(final Object object,
final ls.example.t.zero2line.util.Utils.OnAppStatusChangedListener listener) {
mStatusListenerMap.put(object, listener);
}
void removeOnAppStatusChangedListener(final Object object) {
mStatusListenerMap.remove(object);
}
void removeOnActivityDestroyedListener(final android.app.Activity activity) {
if (activity == null) return;
mDestroyedListenerMap.remove(activity);
}
void addOnActivityDestroyedListener(final android.app.Activity activity,
final ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener listener) {
if (activity == null || listener == null) return;
java.util.Set<ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener> listeners;
if (!mDestroyedListenerMap.containsKey(activity)) {
listeners = new java.util.HashSet<>();
mDestroyedListenerMap.put(activity, listeners);
} else {
listeners = mDestroyedListenerMap.get(activity);
if (listeners.contains(listener)) return;
}
listeners.add(listener);
}
/**
* To solve close keyboard when activity onDestroy.
* The preActivity set windowSoftInputMode will prevent
* the keyboard from closing when curActivity onDestroy.
*/
private void processHideSoftInputOnActivityDestroy(final android.app.Activity activity, boolean isSave) {
if (isSave) {
final android.view.WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
final int softInputMode = attrs.softInputMode;
activity.getWindow().getDecorView().setTag(-123, softInputMode);
activity.getWindow().setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} else {
final Object tag = activity.getWindow().getDecorView().getTag(-123);
if (!(tag instanceof Integer)) return;
ls.example.t.zero2line.util.Utils.runOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
activity.getWindow().setSoftInputMode(((Integer) tag));
}
}, 100);
}
}
private void postStatus(final boolean isForeground) {
if (mStatusListenerMap.isEmpty()) return;
for (ls.example.t.zero2line.util.Utils.OnAppStatusChangedListener onAppStatusChangedListener : mStatusListenerMap.values()) {
if (onAppStatusChangedListener == null) return;
if (isForeground) {
onAppStatusChangedListener.onForeground();
} else {
onAppStatusChangedListener.onBackground();
}
}
}
private void setTopActivity(final android.app.Activity activity) {
if (PERMISSION_ACTIVITY_CLASS_NAME.equals(activity.getClass().getName())) return;
if (mActivityList.contains(activity)) {
if (!mActivityList.getLast().equals(activity)) {
mActivityList.remove(activity);
mActivityList.addLast(activity);
}
} else {
mActivityList.addLast(activity);
}
}
private void consumeOnActivityDestroyedListener(android.app.Activity activity) {
java.util.Iterator<java.util.Map.Entry<android.app.Activity, java.util.Set<ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener>>> iterator
= mDestroyedListenerMap.entrySet().iterator();
while (iterator.hasNext()) {
java.util.Map.Entry<android.app.Activity, java.util.Set<ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener>> entry = iterator.next();
if (entry.getKey() == activity) {
java.util.Set<ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener> value = entry.getValue();
for (ls.example.t.zero2line.util.Utils.OnActivityDestroyedListener listener : value) {
listener.onActivityDestroyed(activity);
}
iterator.remove();
}
}
}
private android.app.Activity getTopActivityByReflect() {
try {
@android.annotation.SuppressLint("PrivateApi")
Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
Object currentActivityThreadMethod = activityThreadClass.getMethod("currentActivityThread").invoke(null);
java.lang.reflect.Field mActivityListField = activityThreadClass.getDeclaredField("mActivityList");
mActivityListField.setAccessible(true);
java.util.Map activities = (java.util.Map) mActivityListField.get(currentActivityThreadMethod);
if (activities == null) return null;
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
java.lang.reflect.Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
java.lang.reflect.Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
return (android.app.Activity) activityField.get(activityRecord);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
}
public static final class FileProvider4UtilCode extends android.support.v4.content.FileProvider {
@Override
public boolean onCreate() {
ls.example.t.zero2line.util.Utils.init(getContext());
return true;
}
}
///////////////////////////////////////////////////////////////////////////
// interface
///////////////////////////////////////////////////////////////////////////
public abstract static class Task<Result> implements Runnable {
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int CANCELLED = 2;
private static final int EXCEPTIONAL = 3;
private volatile int state = NEW;
abstract Result doInBackground();
private ls.example.t.zero2line.util.Utils.Callback<Result> mCallback;
public Task(final ls.example.t.zero2line.util.Utils.Callback<Result> callback) {
mCallback = callback;
}
@Override
public void run() {
try {
final Result t = doInBackground();
if (state != NEW) return;
state = COMPLETING;
UTIL_HANDLER.post(new Runnable() {
@Override
public void run() {
mCallback.onCall(t);
}
});
} catch (Throwable th) {
if (state != NEW) return;
state = EXCEPTIONAL;
}
}
public void cancel() {
state = CANCELLED;
}
public boolean isDone() {
return state != NEW;
}
public boolean isCanceled() {
return state == CANCELLED;
}
}
public interface Callback<T> {
void onCall(T data);
}
public interface OnAppStatusChangedListener {
void onForeground();
void onBackground();
}
public interface OnActivityDestroyedListener {
void onActivityDestroyed(android.app.Activity activity);
}
}
|
package com.folcike.gamepanelf;
import com.folcike.gamepanelf.model.Server;
import com.folcike.gamepanelf.repository.ServerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.sql.SQLException;
@Controller
@RequestMapping("/admin")
public class AdminPanel {
private ServerRepository serverRepo;
@Autowired
public AdminPanel(ServerRepository serverRepo){
this.serverRepo = serverRepo;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String adminservers(Model model, RedirectAttributes redirect) {
Server serverModel = new Server();
serverModel.setName("Melika");
model.addAttribute("server", new Server());
model.addAttribute("servers", serverRepo.findAll());
return "adminservers";
}
@PostMapping("/addServer")
public String addServer(@ModelAttribute("server") Server server, Model model) throws ClassNotFoundException, SQLException {
System.out.println(server.getName() + " " + server.getPort());
serverRepo.save(server);
return "redirect:/admin";
}
}
|
package com.company;
import java.io.InputStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner src = new Scanner(System.in);
int num1 = 1;
int num2 = 1;
int num = src.nextInt();
int numOfFibonachi;
int i = 0;
while (i <= num) {
numOfFibonachi = num1 + num2;
num1 = num2;
num2 = numOfFibonachi;
if (i == num) {
System.out.println(numOfFibonachi);
}
i++;
}
}
}
|
package com.example.demo.command;
import com.example.demo.model.Meeting;
public class MeetingCommand {
Meeting meeting;
public Meeting getMeeting() {
return meeting;
}
public void setMeeting(Meeting meeting) {
this.meeting = meeting;
}
}
|
/**
* FormField.java
*
* Skarpetis Dimitris 2016, all rights reserved.
*/
package dskarpetis.elibrary.util.form;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.border.Border;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.SimpleFormComponentLabel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import dskarpetis.elibrary.util.*;
import dskarpetis.elibrary.util.alerts.*;
import dskarpetis.elibrary.util.bootstrap.*;
/**
* Border functionality of an input form field. The actual input form component
* is encapsulated here.
*
* @author palivosd
*/
public class FormField extends Border {
/**
* Default SUID.
*/
private static final long serialVersionUID = 1L;
private final IModel<Component> errorComponentModel = new LoadableDetachableModel<Component>() {
private static final long serialVersionUID = 1L;
@Override
public Component load () {
return FormField.this;
};
};
/**
* Model containing the errors of the component.
*/
private final IModel<String> componentErrorModel = new ComponentErrorModel(errorComponentModel);
/**
* Model indicating whether the component is in an error state.
*/
private final IModel<Boolean> isComponentInvalidModel = NegationConditionalModel.of(IsComponentValidModel.ofErrorModel(componentErrorModel));
/**
* Builder helper class to ease the creation of InputGroups.
*/
public static class Builder {
private static final String HELP_TITLE_FORMAT = "%s-help-title";
private static final String HELP_BODY_FORMAT = "%s-help-body";
private static final String BORDER_ID_FORMAT = "%s-group";
// Required parameters
private final FormComponent<?> formComponent;
// Optional parameters which have some sensible default value
private String borderId;
private IModel<String> helpTitle;
private IModel<String> helpBody;
/**
* Constructor with the required parameter. The builder assumes that the
* wicket id of the border is <code>id-group</code> where
* <code>id</code> is the wicket id of the provided form component. If
* the border id has a different format, then it must be specified using
* the appropriate helper function of the Builder. The builder also
* assumes that there are resources for the title and body of the help
* modal with the keys <code>id-help-title</code> and
* <code>id-help-body</code>. If those keys do not exist, the title and
* content of the help modal will be empty, unless specified using the
* appropriate helper functions.
*
* @param formComponent
* The component that is placed inside this FormField.
*/
public Builder (final FormComponent<?> formComponent) {
if (formComponent == null) {
throw new IllegalArgumentException(String.format("%s: Missing data", this.getClass().getSimpleName()));
}
this.formComponent = formComponent;
initDefaultOptionalValues();
}
/**
* Set the default values for {@link #borderId}, {@link #helpTitle} and
* {@link #helpBody} based on the conventions mentioned in the
* constructor.
*/
private void initDefaultOptionalValues () {
String formComponentId = formComponent.getId();
this.borderId = String.format(BORDER_ID_FORMAT, formComponentId);
String helpTitleResourceKey = String.format(HELP_TITLE_FORMAT, formComponentId);
String helpBodyResourceKey = String.format(HELP_BODY_FORMAT, formComponentId);
loadHelpResources(helpTitleResourceKey, helpBodyResourceKey);
}
/**
* Retrieve the resources for the title and content of the help modal by
* looking for the standard resource keys for this component which
* should have the format {@link #HELP_TITLE_FORMAT} and
* {@link #HELP_BODY_FORMAT}. If those keys are not found, the help
* title and author will be empty Strings.
*/
private void loadHelpResources (String helpTitleResourceKey, String helpContentResourceKey) {
this.helpTitle = new StringResourceModel(helpTitleResourceKey).setDefaultValue(new EmptyStringModel());
this.helpBody = new StringResourceModel(helpContentResourceKey).setDefaultValue(new EmptyStringModel());
}
/**
* Set the title of the help modal.
*
* @param title
* The model of the title of the modal which can be either plain
* text or HTML.
* @return An updated builder object.
*/
public Builder helpTitle (final IModel<String> title) {
this.helpTitle = title;
return this;
}
/**
* Set the body of the help modal.
*
* @param body
* The model of the body of the modal, which can be either plain
* text or HTML.
* @return An updated builder object.
*/
public Builder helpBody (final IModel<String> body) {
this.helpBody = body;
return this;
}
/**
* Create the InputGroup object using the values set inside the builder.
* Optional parameters will get their default values if they haven't
* been specified until this point.
*
* @return A new InputGroup object.
*/
public FormField build () {
return new FormField(this);
}
}
/**
* Single private COnstructor to be used by {@link Builder}
*
* @param builder
* Builder of the Component
*/
private FormField (Builder builder) {
super(builder.borderId);
WebMarkupContainer formFieldContainer = MarkupContainers.ofAdditionalCSSClasses("form-field", isComponentInvalidModel, "has-error", "has-feedback");
queue(formFieldContainer);
// Set form component with label text for major form field component
builder.formComponent.setLabel(new ResourceModel(builder.formComponent.getId()));
queue(builder.formComponent);
// Set label with CSS style
Behavior bootstrapLabelStyle = new BootstrapLabelStyle();
queue(new SimpleFormComponentLabel("inputLabel", builder.formComponent).add(bootstrapLabelStyle));
queue(new WebMarkupContainer("inputInnerGroup"));
// Error icon and message
queue(MarkupContainers.ofVisibilityAllowed("errorIcon", isComponentInvalidModel));
queue(new Label("errorMessage", componentErrorModel).setEscapeModelStrings(false));
// Help modal
queue(new HelpPanel("inputHelp", builder.helpTitle, builder.helpBody));
}
}
|
package giantfilereader;
import java.io.BufferedReader;
import java.util.Iterator;
import java.io.*;
import java.util.List;
import java.util.Arrays;
/**
* This is a class for building an iterator that iterates
* over the lines in the huge file.
*/
public class GFRdr extends Object implements Iterator<Integer>{
/**
* This data member is used for the reader.
*/
BufferedReader reader;
/**
* This is the class constructor for the file line
* iterator.
* @param fileName this is the filename that we want
* to use. It can be a simple filename
* (in the root of the app entry point),
* absolute path or resoure name. The
* constructor will try to build a reader
* from either of the three.
* @param fromResource this is a flag that lets the constructor
* know whether the filename is constructed form
* a resource
*/
public GFRdr(String fileName, Boolean fromResource){
File fromPath = new File(fileName);
System.out.println(fromPath.getPath());
if(fromPath.exists() &&
!fromPath.isDirectory() &&
!fromResource &&
fromPath.isAbsolute()){
System.out.println("Trying to use file from absolute path");
try {
reader = new BufferedReader( new FileReader(fileName));
} catch (FileNotFoundException e) {
// e.printStackTrace();
}
} else
if (!fromResource) {
System.out.println("Maybe this is a relative path");
List<String> pathParts = Arrays.asList( System.getProperty("user.dir"),
fileName );
String completePath = pathJoin(pathParts);
System.out.println("Complete path is: " + completePath);
System.out.println("Building buffered reader from the file");
try{
reader = new BufferedReader(new FileReader(completePath));
} catch (FileNotFoundException e) {
// e.printStackTrace();
}
} else
if(fromResource){
try{
reader = new BufferedReader(new FileReader(getClass().getClassLoader().getResource(fileName).getFile()));
} catch (FileNotFoundException e) {
// e.printStackTrace();
}
}
}
public BufferedReader getReader() {
return this.reader;
}
/**
* This does a path join usnig the system separator
* @param paths A list of the paths to be joined
* @return String representing the joined path resulting
* by concatenation of the elements of the list
* with os spearators.
*/
private String pathJoin(List<String> paths){
File summed = new File("");
StringBuilder path = new StringBuilder(20);
path.append("");
for(String subpath: paths){
summed = new File(path.toString(), subpath);
path.append(summed.getPath());
}
return summed.getPath();
}
/**
* Implementation of the iterator interface.
*/
public boolean hasNext() {
try{
return reader.ready();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public Integer next() {
try{
return Integer.parseInt(reader.readLine());
} catch (IOException e) {
return null;
}
}
public void remove() {
//throw new Exception("Read only access, remove not available");
}
}
|
package com.campus.service;
import com.campus.entity.CityBean;
import com.campus.entity.Grade;
import com.campus.entity.Student;
import com.campus.entity.UserBean;
import com.campus.common.Result;
import java.util.List;
public interface UserService {
List<UserBean> getUserList();
List<Student> getStuList();
List<Grade> getGradelist();
List<CityBean> getProlistById(Long id);
Result saveStuInfo(Student student);
Result deleteStuBatchBySid(Long[] sids);
Student saveStuById(Long sid);
}
|
package edu.sit.erro.editor;
public enum EErroEdicao {
ERRO_EDICAO_CLIENTE("Erro ao editar o cliente"),
ERRO_EDICAO_CONTATO("Erro ao editar o contato"),
ERRO_EDICAO_FUNCIONARIO("Erro ao editar o funcionario"),
ERRO_EDICAO_CATEGORIA("Erro ao editar a categoria"),
ERRO_EDICAO_FORNECEDOR("Erro ao editar o fornecedor"),
ERRO_EDICAO_PRODUTO("Erro ao editar o produto"),
ERRO_BUSCA_CLIENTE("Erro ao buscar o cliente informado para edição"),
ERRO_BUSCA_CONTATO("Erro ao editar o contato informado para edição"),
ERRO_BUSCA_FUNCIONARIO("Erro ao editar o funcionario informado para edição"),
ERRO_BUSCA_CATEGORIA("Erro ao editar a categoria informado para edição"),
ERRO_BUSCA_FORNECEDOR("Erro ao editar o fornecedor informado para edição"),
ERRO_BUSCA_PRODUTO("Erro ao editar o produto informado para edição");
private String mensage;
public String getMensage() {
return mensage;
}
private EErroEdicao(String mensage) {
}
}
|
package com.ipo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
import javax.imageio.ImageIO;
import javax.swing.AbstractListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Projects {
// Search a project
private class Btn_searchMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
String text_to_search = txtSearch.getText();
ArrayList<MyProjectPanel> panels_according_search = new ArrayList<>();
// Get panels that match with the search
for (int i = 0; i < pnl_project.size(); i++) {
if (pnl_project.get(i).associated_project.getName().contains(text_to_search)) {
panels_according_search.add(pnl_project.get(i));
}
}
// Paint the panels
pnl_projects.removeAll();
if (text_to_search.isEmpty()) {
repaintPanels();
} else {
for (int i = 0; i < panels_according_search.size(); i++) {
pnl_projects.add(panels_according_search.get(i), "Project");
pnl_project.get(i).addMouseListener(new PnlProjectMouseListener());
pnl_project.get(i).getCheckBox().addItemListener(new ChckbxSelectProjectItemListener());
}
}
pnl_projects.updateUI();
}
}
// Add a new project
private class BtnAddNewProjectMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
int len = pnl_project.size();
if (len < 9) {
JSONObject proj = new JSONObject();
try {
proj.put("name", "Default");
proj.put("id", pnl_project.size() + 1);
proj.put("image_path", "resources/project.png");
proj.put("created_at", new Date().toString());
proj.put("manager", "Default");
proj.put("description", "empty");
projects.put(proj);
obj.put("projects", projects);
FileWriter file = new FileWriter(this.getClass().getClassLoader().getResource("data.json").getPath());
BufferedWriter outstream = new BufferedWriter(file);
outstream.write(obj.toString());
outstream.close();
showStatusInfo(Color.GREEN, "Project has been added");
} catch (JSONException | IOException e) {
showStatusInfo(Color.RED, "Project has not been added correctly.");
e.printStackTrace();
}
try {
Project p = new Project(proj.getString("name"), proj.getString("image_path"), proj.getString("created_at"),
proj.getString("manager"), proj.getString("description"));
pnl_project.add(new MyProjectPanel(p));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pnl_projects.add(pnl_project.get(len));
pnl_project.get(len).getCheckBox().addItemListener(new ChckbxSelectProjectItemListener());
pnl_project.get(len).addMouseListener(new PnlProjectMouseListener());
frame.repaint();
frame.revalidate();
}
}
}
// Edit a project
private class BtnEditProjectInfoMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
MyProjectPanel panel_to_change = null;
for (int i = 0; i < pnl_project.size(); i++) {
if (pnl_project.get(i).associated_project.equals(current_proj)) {
panel_to_change = pnl_project.get(i);
break;
}
}
if (!txt_view_name.getText().equals("")) {
current_proj.setName(txt_view_name.getText());
panel_to_change.lblProjectName.setText(txt_view_name.getText());
}
if (!txt_view_manager.getText().equals(""))
current_proj.setManager(txt_view_manager.getText());
if (!txt_view_created.getText().equals(""))
current_proj.setCreated_at(txt_view_created.getText());
if (!textPane_description.getText().equals(""))
current_proj.setDescription(textPane_description.getText());
try {
JSONObject proj = projects.getJSONObject(ThreadLocalRandom.current().nextInt(0, projects.length() + 1));
proj.put("name", current_proj.getName());
proj.put("created_at", current_proj.getCreated_at());
proj.put("manager", current_proj.getManager());
proj.put("description", current_proj.getDescription());
// If image has been modified
if (new_path != null) {
// Save image into MyProjectPanel
if (new_path.contains("resources/")) {
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(new_path));
Image img = icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
panel_to_change.lblProjectImage.setIcon(scaled_icon);
} else {
ImageIcon icon = new ImageIcon(new_path);
Image img = icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
panel_to_change.lblProjectImage.setIcon(scaled_icon);
}
// Save path into JSON object
current_proj.setImage_path(new_path);
proj.put("image_path", current_proj.getImage_path());
new_path = null;
}
FileWriter file = new FileWriter(this.getClass().getClassLoader().getResource("data.json").getPath());
BufferedWriter outstream = new BufferedWriter(file);
outstream.write(obj.toString());
outstream.close();
showStatusInfo(Color.GREEN, "Project has been edited");
} catch (JSONException | IOException e) {
showStatusInfo(Color.RED, "Project has not been edited correctly");
e.printStackTrace();
}
repaintPanels();
}
}
// Select a project to delete it
private class ChckbxSelectProjectItemListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent arg0) {
panels_selected.clear();
// Obtain the selected panels.
for (int i = 0; i < pnl_project.size(); i++) {
if (pnl_project.get(i).getCheckBox().isSelected()) {
panels_selected.add(pnl_project.get(i));
}
}
if (panels_selected.size() > 0) {
txtSearch.setVisible(false);
lbl_Delete.setVisible(true);
btn_search.setVisible(false);
lbl_filter.setVisible(false);
lbl_projects_selected.setVisible(true);
lbl_projects_selected.setText("");
lbl_projects_selected.setText(panels_selected.size() + " Project Selected");
} else {
lbl_projects_selected.setVisible(false);
txtSearch.setVisible(true);
btn_search.setVisible(true);
lbl_filter.setVisible(true);
lbl_Delete.setVisible(false);
}
}
}
// Delete selected projects
private class Lbl_DeleteMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent mouse_event) {
for (int i = 0; i < panels_selected.size(); ) {
MyProjectPanel my_panel = panels_selected.get(i);
projects.remove(i);
// Save changes on disk
try {
obj.put("projects", projects);
FileWriter file = new FileWriter(this.getClass().getClassLoader().getResource("data.json").getPath());
BufferedWriter outstream = new BufferedWriter(file);
outstream.write(obj.toString());
outstream.close();
showStatusInfo(Color.GREEN, "Projects have been removed.");
} catch (JSONException | IOException e) {
showStatusInfo(Color.RED, "Projects have not been removed correctly");
e.printStackTrace();
}
my_panel.getCheckBox().setSelected(false);
pnl_projects.remove(my_panel);
pnl_project.remove(my_panel);
}
panels_selected.clear();
}
}
private class Lbl_filterMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
MyProjectInfo window = new MyProjectInfo(registered_user, language);
window.frame.setVisible(true);
frame.setVisible(false);
frame.dispose();
}
}
// Change image
private class Lbl_view_imageMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser file_chooser = new JFileChooser();
file_chooser.showOpenDialog(panel);
FileFilter imageFilter = new FileNameExtensionFilter("Image Files", ImageIO.getReaderFileSuffixes());
file_chooser.setFileFilter(imageFilter);
new_path = file_chooser.getSelectedFile().getAbsolutePath();
}
}
// View a specific project
private class PnlProjectMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent event) {
pnl_view_project.setVisible(true);
current_proj = ((MyProjectPanel) event.getSource()).associated_project;
if (current_proj.getImage_path().contains("resources/")) {
ImageIcon init_icon = new ImageIcon(this.getClass().getClassLoader().getResource(current_proj.getImage_path()));
Image img = init_icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
lbl_view_image.setIcon(scaled_icon);
}
else {
ImageIcon init_icon = new ImageIcon(current_proj.getImage_path());
Image img = init_icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
lbl_view_image.setIcon(scaled_icon);
}
txt_view_name.setText(((MyProjectPanel) event.getSource()).associated_project.getName());
txt_view_created.setText(((MyProjectPanel) event.getSource()).associated_project.getCreated_at());
textPane_description.setText(((MyProjectPanel) event.getSource()).associated_project.getDescription());
txt_view_manager.setText(((MyProjectPanel) event.getSource()).associated_project.getManager());
frame.repaint();
frame.revalidate();
}
}
private class Lbl_backMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
Profile window = new Profile(registered_user, language);
window.frame.setVisible(true);
frame.setVisible(false);
frame.dispose();
}
}
public JFrame frame;
private JPanel pnl_projects;
private JPanel panel;
private ArrayList<MyProjectPanel> pnl_project;
private JTextField txtSearch;
private JButton btn_search;
private JLabel lbl_filter;
private JButton btnAddNewProject;
private JLabel lbl_projects_selected;
private JLabel lbl_Delete;
private ArrayList<MyProjectPanel> panels_selected;
private JPanel pnl_view_project;
private JLabel lbl_view_image;
private JLabel lbl_view_name;
private JLabel lbl_view_created;
private JLabel lbl_view_manager;
private JTextField txt_view_name;
private JTextField txt_view_created;
private JTextField txt_view_manager;
private JLabel lbl_members;
private JLabel lbl_view_description;
private JTextPane textPane_description;
private JList list;
private JPanel pnl_auxiliar;
private JButton btnEditProjectInfo;
private JSONArray projects;
private JSONObject obj;
private String new_path;
private String language;
private String registered_user;
private Project current_proj;
private JLabel lblInfo;
private JLabel lbl_back;
/**
* Create the application.
*/
public Projects(String registered_user, String language) {
this.language = language;
this.registered_user = registered_user;
if (language.equals("spanish"))
ProjectsMessages.setIdioma("spanish");
else
MessagesProfile.setIdioma("");
pnl_project = new ArrayList<>();
panels_selected = new ArrayList<>();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new FileReader(this.getClass().getClassLoader().getResource("data.json").getPath()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
obj = new JSONObject(sb.toString());
projects = obj.getJSONArray("projects");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 310, 0};
gridBagLayout.rowHeights = new int[]{44, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 5, 5);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 0;
frame.getContentPane().add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{168, 114, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{19, 0, 0};
gbl_panel.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
txtSearch = new JTextField();
txtSearch.setToolTipText(ProjectsMessages.getString("Projects.txtSearch.toolTipText")); //$NON-NLS-1$
txtSearch.setText(ProjectsMessages.getString("Projects.txtSearch.text")); //$NON-NLS-1$
GridBagConstraints gbc_txtSearch = new GridBagConstraints();
gbc_txtSearch.insets = new Insets(0, 0, 5, 5);
gbc_txtSearch.gridx = 1;
gbc_txtSearch.gridy = 0;
panel.add(txtSearch, gbc_txtSearch);
txtSearch.setColumns(10);
btn_search = new JButton(ProjectsMessages.getString("Projects.btn_search.text")); //$NON-NLS-1$
btn_search.addMouseListener(new Btn_searchMouseListener());
GridBagConstraints gbc_btn_search = new GridBagConstraints();
gbc_btn_search.insets = new Insets(0, 0, 5, 5);
gbc_btn_search.gridx = 2;
gbc_btn_search.gridy = 0;
panel.add(btn_search, gbc_btn_search);
lbl_filter = new JLabel("");
lbl_filter.addMouseListener(new Lbl_filterMouseListener());
ImageIcon icon_filter = new ImageIcon(this.getClass().getClassLoader().getResource("resources/task.png"));
Image img_filter = icon_filter.getImage();
Image scaled_filter = img_filter.getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon_filter = new ImageIcon(scaled_filter);
lbl_filter.setIcon(scaled_icon_filter);
GridBagConstraints gbc_lbl_filter = new GridBagConstraints();
gbc_lbl_filter.insets = new Insets(0, 0, 5, 5);
gbc_lbl_filter.gridx = 3;
gbc_lbl_filter.gridy = 0;
panel.add(lbl_filter, gbc_lbl_filter);
lbl_projects_selected = new JLabel("");
GridBagConstraints gbc_lbl_projects_selected = new GridBagConstraints();
gbc_lbl_projects_selected.insets = new Insets(0, 0, 5, 5);
gbc_lbl_projects_selected.gridx = 5;
gbc_lbl_projects_selected.gridy = 0;
panel.add(lbl_projects_selected, gbc_lbl_projects_selected);
lbl_Delete = new JLabel("");
lbl_Delete.addMouseListener(new Lbl_DeleteMouseListener());
lbl_Delete.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("resources/trash.png")));
lbl_Delete.setVisible(false);
GridBagConstraints gbc_lbl_Delete = new GridBagConstraints();
gbc_lbl_Delete.insets = new Insets(0, 0, 5, 0);
gbc_lbl_Delete.gridx = 6;
gbc_lbl_Delete.gridy = 0;
panel.add(lbl_Delete, gbc_lbl_Delete);
lbl_back = new JLabel();
lbl_back.addMouseListener(new Lbl_backMouseListener());
ImageIcon icon_back = new ImageIcon(this.getClass().getClassLoader().getResource("resources/icon_back.png"));
Image img_back = icon_back.getImage();
Image scaled_back = img_back.getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon_back = new ImageIcon(scaled_back);
lbl_back.setIcon(scaled_icon_back);
GridBagConstraints gbc_lbl_back = new GridBagConstraints();
gbc_lbl_back.insets = new Insets(0, 0, 0, 5);
gbc_lbl_back.gridx = 0;
gbc_lbl_back.gridy = 0;
panel.add(lbl_back, gbc_lbl_back);
pnl_projects = new JPanel();
pnl_projects.setBorder(new TitledBorder(null, ProjectsMessages.getString("Projects.pnl_projects.borderTitle"), TitledBorder.LEADING, TitledBorder.TOP, null, null)); //$NON-NLS-1$
GridBagConstraints gbc_pnl_projects = new GridBagConstraints();
gbc_pnl_projects.insets = new Insets(0, 0, 5, 5);
gbc_pnl_projects.fill = GridBagConstraints.BOTH;
gbc_pnl_projects.gridx = 0;
gbc_pnl_projects.gridy = 1;
frame.getContentPane().add(pnl_projects, gbc_pnl_projects);
pnl_projects.setLayout(new GridLayout(3, 3, 0, 0));
ImageIcon imageIcon_view = new ImageIcon(this.getClass().getClassLoader().getResource("resources/trash.png"));
Icon icon = new ImageIcon(imageIcon_view.getImage().getScaledInstance(25, 25, Image.SCALE_DEFAULT));
pnl_auxiliar = new JPanel();
GridBagConstraints gbc_pnl_auxiliar = new GridBagConstraints();
gbc_pnl_auxiliar.insets = new Insets(0, 0, 5, 0);
gbc_pnl_auxiliar.fill = GridBagConstraints.BOTH;
gbc_pnl_auxiliar.gridx = 1;
gbc_pnl_auxiliar.gridy = 1;
frame.getContentPane().add(pnl_auxiliar, gbc_pnl_auxiliar);
pnl_auxiliar.setLayout(new BorderLayout(0, 0));
pnl_view_project = new JPanel();
pnl_auxiliar.add(pnl_view_project, BorderLayout.NORTH);
pnl_view_project.setVisible(false);
GridBagLayout gbl_pnl_view_project = new GridBagLayout();
gbl_pnl_view_project.columnWidths = new int[]{0, 0, 0, 0, 0, 0};
gbl_pnl_view_project.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_pnl_view_project.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
gbl_pnl_view_project.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE, 0.0, 0.0, 0.0};
pnl_view_project.setLayout(gbl_pnl_view_project);
lbl_view_image = new JLabel("");
lbl_view_image.addMouseListener(new Lbl_view_imageMouseListener());
if (current_proj != null) {
ImageIcon init_icon = new ImageIcon(current_proj.getImage_path());
Image img = init_icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
lbl_view_image.setIcon(scaled_icon);
} else {
ImageIcon init_icon = new ImageIcon(this.getClass().getClassLoader().getResource("resources/user.png"));
Image img = init_icon.getImage();
Image scaled = img.getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH);
ImageIcon scaled_icon = new ImageIcon(scaled);
lbl_view_image.setIcon(scaled_icon);
}
GridBagConstraints gbc_lbl_view_image = new GridBagConstraints();
gbc_lbl_view_image.insets = new Insets(0, 0, 5, 5);
gbc_lbl_view_image.gridx = 1;
gbc_lbl_view_image.gridy = 0;
pnl_view_project.add(lbl_view_image, gbc_lbl_view_image);
btnEditProjectInfo = new JButton(ProjectsMessages.getString("Projects.btnEditProjectInfo.text")); //$NON-NLS-1$
btnEditProjectInfo.addMouseListener(new BtnEditProjectInfoMouseListener());
GridBagConstraints gbc_btnEditProjectInfo = new GridBagConstraints();
gbc_btnEditProjectInfo.insets = new Insets(0, 0, 5, 5);
gbc_btnEditProjectInfo.gridx = 1;
gbc_btnEditProjectInfo.gridy = 8;
pnl_view_project.add(btnEditProjectInfo, gbc_btnEditProjectInfo);
list = new JList();
list.setModel(new AbstractListModel() {
String[] values = new String[] {"Item1", "Item2", "Item3", "Item4"};
@Override
public Object getElementAt(int index) {
return values[index];
}
@Override
public int getSize() {
return values.length;
}
});
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.gridheight = 3;
gbc_list.gridwidth = 2;
gbc_list.insets = new Insets(0, 0, 5, 0);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 3;
gbc_list.gridy = 1;
pnl_view_project.add(list, gbc_list);
textPane_description = new JTextPane();
GridBagConstraints gbc_textPane_description = new GridBagConstraints();
gbc_textPane_description.gridheight = 3;
gbc_textPane_description.gridwidth = 4;
gbc_textPane_description.fill = GridBagConstraints.BOTH;
gbc_textPane_description.gridx = 1;
gbc_textPane_description.gridy = 4;
pnl_view_project.add(textPane_description, gbc_textPane_description);
lbl_view_description = new JLabel(ProjectsMessages.getString("Projects.lbl_view_description.text")); //$NON-NLS-1$
GridBagConstraints gbc_lbl_view_description = new GridBagConstraints();
gbc_lbl_view_description.anchor = GridBagConstraints.EAST;
gbc_lbl_view_description.insets = new Insets(0, 0, 5, 5);
gbc_lbl_view_description.gridx = 0;
gbc_lbl_view_description.gridy = 4;
pnl_view_project.add(lbl_view_description, gbc_lbl_view_description);
lbl_members = new JLabel(ProjectsMessages.getString("Projects.lbl_members.text")); //$NON-NLS-1$
GridBagConstraints gbc_lbl_members = new GridBagConstraints();
gbc_lbl_members.anchor = GridBagConstraints.EAST;
gbc_lbl_members.insets = new Insets(0, 0, 5, 5);
gbc_lbl_members.gridx = 2;
gbc_lbl_members.gridy = 2;
pnl_view_project.add(lbl_members, gbc_lbl_members);
lbl_view_name = new JLabel(ProjectsMessages.getString("Projects.lbl_view_name.text")); //$NON-NLS-1$
GridBagConstraints gbc_lbl_view_name = new GridBagConstraints();
gbc_lbl_view_name.anchor = GridBagConstraints.EAST;
gbc_lbl_view_name.insets = new Insets(0, 0, 5, 5);
gbc_lbl_view_name.gridx = 0;
gbc_lbl_view_name.gridy = 1;
pnl_view_project.add(lbl_view_name, gbc_lbl_view_name);
lbl_view_created = new JLabel(ProjectsMessages.getString("Projects.lbl_view_created.text")); //$NON-NLS-1$
GridBagConstraints gbc_lbl_view_created = new GridBagConstraints();
gbc_lbl_view_created.anchor = GridBagConstraints.EAST;
gbc_lbl_view_created.insets = new Insets(0, 0, 5, 5);
gbc_lbl_view_created.gridx = 0;
gbc_lbl_view_created.gridy = 2;
pnl_view_project.add(lbl_view_created, gbc_lbl_view_created);
lbl_view_manager = new JLabel(ProjectsMessages.getString("Projects.lbl_view_manager.text")); //$NON-NLS-1$
GridBagConstraints gbc_lbl_view_manager = new GridBagConstraints();
gbc_lbl_view_manager.anchor = GridBagConstraints.EAST;
gbc_lbl_view_manager.insets = new Insets(0, 0, 5, 5);
gbc_lbl_view_manager.gridx = 0;
gbc_lbl_view_manager.gridy = 3;
pnl_view_project.add(lbl_view_manager, gbc_lbl_view_manager);
txt_view_name = new JTextField();
GridBagConstraints gbc_txt_view_name = new GridBagConstraints();
gbc_txt_view_name.insets = new Insets(0, 0, 5, 5);
gbc_txt_view_name.fill = GridBagConstraints.HORIZONTAL;
gbc_txt_view_name.gridx = 1;
gbc_txt_view_name.gridy = 1;
pnl_view_project.add(txt_view_name, gbc_txt_view_name);
txt_view_name.setColumns(10);
txt_view_created = new JTextField();
GridBagConstraints gbc_txt_view_created = new GridBagConstraints();
gbc_txt_view_created.insets = new Insets(0, 0, 5, 5);
gbc_txt_view_created.fill = GridBagConstraints.HORIZONTAL;
gbc_txt_view_created.gridx = 1;
gbc_txt_view_created.gridy = 2;
pnl_view_project.add(txt_view_created, gbc_txt_view_created);
txt_view_created.setColumns(10);
txt_view_manager = new JTextField();
GridBagConstraints gbc_txt_view_manager = new GridBagConstraints();
gbc_txt_view_manager.insets = new Insets(0, 0, 5, 5);
gbc_txt_view_manager.fill = GridBagConstraints.HORIZONTAL;
gbc_txt_view_manager.gridx = 1;
gbc_txt_view_manager.gridy = 3;
pnl_view_project.add(txt_view_manager, gbc_txt_view_manager);
txt_view_manager.setColumns(10);
btnAddNewProject = new JButton(ProjectsMessages.getString("Projects.btnAddNewProject.text")); //$NON-NLS-1$
btnAddNewProject.addMouseListener(new BtnAddNewProjectMouseListener());
GridBagConstraints gbc_btnAddNewProject = new GridBagConstraints();
gbc_btnAddNewProject.insets = new Insets(0, 0, 5, 5);
gbc_btnAddNewProject.gridx = 0;
gbc_btnAddNewProject.gridy = 2;
frame.getContentPane().add(btnAddNewProject, gbc_btnAddNewProject);
lblInfo = new JLabel("");
GridBagConstraints gbc_lblInfo = new GridBagConstraints();
gbc_lblInfo.insets = new Insets(0, 0, 0, 5);
gbc_lblInfo.gridx = 1;
gbc_lblInfo.gridy = 2;
frame.getContentPane().add(lblInfo, gbc_lblInfo);
for (int i = 0; i < projects.length(); i++) {
try {
pnl_project.add(new MyProjectPanel(new Project(projects.getJSONObject(i).getString("name"),
projects.getJSONObject(i).getString("image_path"),
projects.getJSONObject(i).getString("created_at"),
projects.getJSONObject(i).getString("manager"),
projects.getJSONObject(i).getString("description"))));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pnl_projects.add(pnl_project.get(i), "Project");
pnl_project.get(i).addMouseListener(new PnlProjectMouseListener());
pnl_project.get(i).getCheckBox().addItemListener(new ChckbxSelectProjectItemListener());
}
}
private void repaintPanels() {
pnl_projects.removeAll();
for (int i = 0; i < pnl_project.size(); i++) {
pnl_projects.add(pnl_project.get(i), "Project");
pnl_project.get(i).addMouseListener(new PnlProjectMouseListener());
pnl_project.get(i).getCheckBox().addItemListener(new ChckbxSelectProjectItemListener());
}
pnl_projects.updateUI();
}
private void showStatusInfo(Color color, String text_to_show) {
lblInfo.setForeground(color);
lblInfo.setText(text_to_show);
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lblInfo.setText("");
}
};
javax.swing.Timer timer = new javax.swing.Timer(2500, taskPerformer);
timer.setRepeats(false);
timer.start();
}
}
|
package com.mashibing;
import com.mashibing.facade.GameModel;
import java.awt.*;
/**
* @create: 2020-04-14 15:00
**/
public class Wall extends GameObject {
public Wall(Point point, int width, int heigth) {
this.point = point;
this.width = width;
this.height = heigth;
rectangle = new Rectangle(point.x, point.y, width, height);
GameModel.getInstance().getObjects().add(this);
}
@Override
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.yellow);
g.fillRect(point.x, point.y, width, height);
g.setColor(c);
}
}
|
package br.com.ecommerce.pages.retaguarda.cadastros.tiposconta;
import static br.com.ecommerce.config.DriverFactory.getDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import br.com.ecommerce.config.BasePage;
import br.com.ecommerce.util.Log;
import br.com.ecommerce.util.Utils;
public class PageEditarTipoConta extends BasePage {
public PageEditarTipoConta() {
PageFactory.initElements(getDriver(), this);
}
@FindBy(xpath = "//h1")
private WebElement titleEditarConta;
@FindBy(xpath = "//label[text()='Descrição']")
private WebElement labelDescricao;
@FindBy(xpath = "//label[text()='Despesa?']")
private WebElement labelDespesa;
@FindBy(id = "bill_type_description")
private WebElement inputDescricao;
@FindBy(id = "bill_type_is_expense")
private WebElement checkDespesa;
@FindBy(xpath = "//a[text()='Cancelar']")
private WebElement btCancelar;
@FindBy(name = "commit")
private WebElement btSalvar;
public void alterarTipoConta(String tipoConta) {
Log.info("Alterando dados da ["+tipoConta+"]...");
aguardarElementoVisivel(btSalvar);
preencherCampo(inputDescricao, tipoConta);
if (isContaDespesa(tipoConta)) {
marcarCheckbox(checkDespesa);
}else
desmarcarCheckbox(checkDespesa);
click(btSalvar);
Log.info("["+tipoConta+"] inserida");
}
public boolean isContaDespesa(String tipoConta){
if (tipoConta.contains("à pagar")) {
return true;
}else
return false;
}
public void verificarOrtografiaPageEditarTipoConta(){
Log.info("Verificando ortografia da página de cadastro de tipo de contas...");
Utils.assertEquals(getTextElement(titleEditarConta), "Editar Tipo de Conta");
Utils.assertEquals(getTextElement(labelDescricao) , "Descrição");
Utils.assertEquals(getTextElement(labelDespesa) , "Despesa?");
Utils.assertEquals(getTextElement(btCancelar) , "Cancelar");
Utils.assertEquals(getTextValueAtributo(btSalvar) , "Salvar");
Log.info("Ortografia validada com sucesso.");
}
}
|
package zust.service;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import zust.model.SChicken;
import java.util.List;
@Service
public interface SchickenService {
public PageInfo<SChicken> selectByTime(int pageNum, int pageSize);
public SChicken selectByPK(int id);
public List<SChicken> selectBYTIME();
}
|
package com.facebook.react.modules.accessibilityinfo;
import android.os.Build;
import android.view.accessibility.AccessibilityManager;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;
@ReactModule(name = "AccessibilityInfo")
public class AccessibilityInfoModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private AccessibilityManager mAccessibilityManager;
private boolean mEnabled;
private ReactTouchExplorationStateChangeListener mTouchExplorationStateChangeListener;
public AccessibilityInfoModule(ReactApplicationContext paramReactApplicationContext) {
super(paramReactApplicationContext);
this.mAccessibilityManager = (AccessibilityManager)paramReactApplicationContext.getApplicationContext().getSystemService("accessibility");
this.mEnabled = this.mAccessibilityManager.isTouchExplorationEnabled();
if (Build.VERSION.SDK_INT >= 19)
this.mTouchExplorationStateChangeListener = new ReactTouchExplorationStateChangeListener();
}
public String getName() {
return "AccessibilityInfo";
}
public void initialize() {
getReactApplicationContext().addLifecycleEventListener(this);
updateAndSendChangeEvent(this.mAccessibilityManager.isTouchExplorationEnabled());
}
@ReactMethod
public void isTouchExplorationEnabled(Callback paramCallback) {
paramCallback.invoke(new Object[] { Boolean.valueOf(this.mEnabled) });
}
public void onCatalystInstanceDestroy() {
super.onCatalystInstanceDestroy();
getReactApplicationContext().removeLifecycleEventListener(this);
}
public void onHostDestroy() {}
public void onHostPause() {
if (Build.VERSION.SDK_INT >= 19)
this.mAccessibilityManager.removeTouchExplorationStateChangeListener(this.mTouchExplorationStateChangeListener);
}
public void onHostResume() {
if (Build.VERSION.SDK_INT >= 19)
this.mAccessibilityManager.addTouchExplorationStateChangeListener(this.mTouchExplorationStateChangeListener);
updateAndSendChangeEvent(this.mAccessibilityManager.isTouchExplorationEnabled());
}
public void updateAndSendChangeEvent(boolean paramBoolean) {
if (this.mEnabled != paramBoolean) {
this.mEnabled = paramBoolean;
((DeviceEventManagerModule.RCTDeviceEventEmitter)getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)).emit("touchExplorationDidChange", Boolean.valueOf(this.mEnabled));
}
}
class ReactTouchExplorationStateChangeListener implements AccessibilityManager.TouchExplorationStateChangeListener {
private ReactTouchExplorationStateChangeListener() {}
public void onTouchExplorationStateChanged(boolean param1Boolean) {
AccessibilityInfoModule.this.updateAndSendChangeEvent(param1Boolean);
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\accessibilityinfo\AccessibilityInfoModule.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.lspring.iocother2;
import org.springframework.beans.factory.FactoryBean;
import com.lspring.springIoc.Person;
public class MyFactoryBean implements FactoryBean<Person> {
//要产品的时候会调用Object方法
public Person getObject() throws Exception {
System.out.println("getObject");
return new Person();
}
public Class<Person> getObjectType() {
System.out.println("getObjectType!");
return null;
}
public boolean isSingleton() {
System.out.println("isSingleton");
return true;
}
}
|
package LS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import alg.Node;
import alg.Policy;
import alg.RandCWS;
import alg.Edge;
import alg.Inputs;
import alg.Solution;
import alg.Test;
public class RandomizationPolicy {
public static Solution RandoPolicy(Inputs inputs, Solution baseSol,Test aTest, Random rng){
Solution newSol = null;
int index = 0;
Map<Integer,Double> PolicyCost = new LinkedHashMap<Integer, Double>();
for( int i = 1; i < inputs.getNodes().length; i++ ) //node 0 is depot
{
index = 0;
Node aNode = inputs.getNodes()[i];
Policy initActivePolicy = aNode.getActivePolicy();
float unitsToServe = 0;
double stockCosts = 0;
PolicyCost.clear();
PolicyCost.put(aNode.getIndexPolicy(initActivePolicy.getRefillUpToPercent()), baseSol.getTotalCosts());
for( Policy p : aNode.getPoliciesByRefill() )
{
//guardo el coste de la politica actual
if( p != initActivePolicy ) // try only policies other than the initial one
{
index++;
unitsToServe = baseSol.getDemandToServe() -
aNode.getActivePolicy().getUnitsToServe() + p.getUnitsToServe();
stockCosts = baseSol.getStockCosts() -
aNode.getActivePolicy().getExpStockCosts() + p.getExpStockCosts();
Policy auxActivePolicy = aNode.getActivePolicy(); // auxiliar copy
aNode.setActivePolicy(p); // change policy to test for improvement
newSol = RandCWS.solve(aTest, inputs, rng, false);
newSol.setDemandToServe(unitsToServe);
newSol.setStockCosts(stockCosts);
newSol.setTotalCosts(stockCosts + newSol.getRoutingCosts());
// check that finalServedDemand = demandToServe at the beginning
if( Math.abs(newSol.getDemandToServe() - newSol.getServedDemand()) > 0.001 ){
System.out.println("PROBLEM WITH DEMANDS, UNRELIABLE SOL!!! " + newSol.getDemandToServe() + " " + newSol.getServedDemand());
System.exit(1);
}
aNode.setActivePolicy(auxActivePolicy);
PolicyCost.put(aNode.getIndexPolicy(p.getRefillUpToPercent()), newSol.getTotalCosts());
}
}
Map<Integer, Double> sortedMapAsc = new LinkedHashMap<Integer, Double>();
sortedMapAsc = sortByComparator(PolicyCost, true);
Policy currentPolicy = inputs.getNodes()[i].getActivePolicy();
double currentUnitsToServe = currentPolicy.getUnitsToServe();
Boolean exDemand = true;
int times = 0;
// while(exDemand && times < 50){
times++;
int policyIndex = getRandomPosition(aTest.getIrpBias(),aTest.getIrpBias(),rng,aNode.getPoliciesByCosts().length-1);
List<Entry<Integer, Double> > indexedList = new ArrayList<Map.Entry<Integer, Double>>(sortedMapAsc.entrySet());
Map.Entry<Integer, Double> entry = indexedList.get(policyIndex);
int selectPolice = entry.getKey();
unitsToServe = baseSol.getDemandToServe() - aNode.getActivePolicy().getUnitsToServe() + aNode.getRandomPolicy(selectPolice).getUnitsToServe();
double unitsToServePolicy = inputs.getNodes()[i].getRandomPolicy(selectPolice).getUnitsToServe();
//double newDemand = inputs.getNodes()[i].getInRoute().getDemand() - currentUnitsToServe + unitsToServePolicy;
// exDemand = false;
//if(newDemand <= inputs.getVehCap()){
stockCosts = baseSol.getStockCosts() - aNode.getActivePolicy().getExpStockCosts() + aNode.getRandomPolicy(selectPolice).getExpStockCosts();
Policy auxActivePolicy2 = aNode.getActivePolicy(); // auxiliar copy
aNode.setActivePolicy(aNode.getRandomPolicy(selectPolice)); // change policy to test for improvement
newSol = RandCWS.solve(aTest, inputs, rng, false);
newSol.setDemandToServe(unitsToServe);
newSol.setStockCosts(stockCosts);
newSol.setTotalCosts(stockCosts + newSol.getRoutingCosts());
// check that finalServedDemand = demandToServe at the beginning
if( Math.abs(newSol.getDemandToServe() - newSol.getServedDemand()) > 0.001 ){
System.out.println("PROBLEM WITH DEMANDS, UNRELIABLE SOL!!! " + newSol.getDemandToServe() + " " + newSol.getServedDemand());
System.exit(1);
}
// System.err.println("New SOL: " + newSol.getTotalCosts());
/*int factible = checkCap(newSol,inputs.getVehCap() );
if (factible == 1){
aNode.setActivePolicy(auxActivePolicy2);
exDemand = true;
continue;
}*/
if( newSol.getTotalCosts() < baseSol.getTotalCosts() ) // If improvement
{
baseSol = newSol;
}
else // If not an improvement, reset active policy to its value
aNode.setActivePolicy(auxActivePolicy2);
//}else{
//exDemand = true;
// }
//}
} // end for, try another policy for this node
return baseSol;
} // try changing active policy in another node
private static int getRandomPosition(double alpha, double beta, Random r,int size) {
double randomValue = alpha + (beta - alpha) * r.nextDouble();
int index = (int) (Math.log(r.nextDouble()) / Math.log(1 - randomValue));
// int index = (int) (Math.log(r.nextDouble()) / Math.log(1 - beta));
index = index % size;
return index;
}
private static Map<Integer, Double> sortByComparator(Map<Integer, Double> unsortMap, final boolean order)
{
List<Entry<Integer, Double>> list = new LinkedList<Entry<Integer, Double>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<Integer, Double>>()
{
public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<Integer, Double> sortedMap = new LinkedHashMap<Integer, Double>();
for (Entry<Integer, Double> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
private static int checkCap(Solution auxSolDet , float capacity){
for(int i = 0; i < auxSolDet.getRoutes().size();i++){
double totservedIS = 0;
for(int jj =0; jj < auxSolDet.getRoutes().get(i).getEdges().size(); jj++ ){
Edge tE = auxSolDet.getRoutes().get(i).getEdges().get(jj);
if(tE.getEnd().getId() != 0 ){
totservedIS += tE.getEnd().getUnitsToServe();
}
if(totservedIS > capacity){
return 1;
}
}
}
return 0;
}
}
|
package com.example.fibonacci;
import androidx.annotation.NonNull;
public class Pais{
private String nombrePais;
private String capital;
private String nomPaInt;
private String sigla;
public String getNombrePais() {
return nombrePais;
}
public void setNombrePais(String nombrePais) {
this.nombrePais = nombrePais;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public String getNomPaInt() {
return nomPaInt;
}
public void setNomPaInt(String nomPaInt) {
this.nomPaInt = nomPaInt;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public Pais(String nombrePais, String capital, String nomPaInt, String sigla) {
this.nombrePais = nombrePais;
this.capital = capital;
this.nomPaInt = nomPaInt;
this.sigla = sigla;
}
@NonNull
@Override
public String toString() {
String Pais ="";
Pais = "Nombre: " + nombrePais +"\nSigla: " + sigla + "\nCapital: " + capital;
return Pais;
}
}
|
import java.util.Arrays;
public class CanMakeArithmeticProgressionFromSequence {
public static boolean canMakeArithmeticProgression1(int[] arr) {
boolean res = true;
if (arr.length ==2){
return false;
}
Arrays.sort(arr);
int current =Math.abs(arr[0] - arr[1]);
for (int i = 1;i< arr.length;i++){
if (current != (Math.abs(arr[i-1] - arr[i]))){
return false;
}
}
return res;
}
public static boolean canMakeArithmeticProgression(int[] arr) {
boolean res = true;
Arrays.sort(arr);
int current =Math.abs(arr[0] - arr[1]);
for (int i = 2;i< arr.length;i++){
if (current != (Math.abs(arr[i-1] - arr[i]))){
return false;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {-2,0};
System.out.print(canMakeArithmeticProgression(arr));
}
}
|
package com.sunteam.library.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.sunteam.common.menu.MenuActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.tts.TtsUtils;
import com.sunteam.common.utils.ArrayUtils;
import com.sunteam.library.R;
import com.sunteam.library.entity.BookmarkEntity;
import com.sunteam.library.utils.EbookConstants;
/**
* @Destryption 有声读物播放界面对应的功能菜单
* @Author Jerry
* @Date 2017-2-11 下午1:30:56
* @Note
*/
public class AudioFunctionMenu extends MenuActivity {
private float percent = 0.0f;
private BookmarkEntity mBookmarkEntity = null; //书签实体类
public void onCreate(Bundle savedInstanceState) {
initView();
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
TtsUtils.getInstance().restoreSettingParameters();
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK != resultCode) {
return;
}
switch(requestCode){
case 0: // 书签管理
setResult(resultCode, data); // 需要把跳转的书签返回给朗读界面
finish();
break;
case 4: // 跳至本章百分比
Intent intent = new Intent();
intent.putExtra("action", EbookConstants.TO_PART_PAGE);
intent.putExtra("percent", data.getFloatExtra("percent", 0.0f));
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
}
@Override
public void setResultCode(int resultCode, int selectItem, String menuItem) {
switch(selectItem){
case 0: // 书签管理
startBookmarkManager(selectItem, menuItem);
break;
case 1: // 上一章
{
Intent intent = new Intent();
intent.putExtra("action", EbookConstants.TO_PRE_PART);
setResult(RESULT_OK, intent);
finish();
}
break;
case 2: // 下一章
{
Intent intent = new Intent();
intent.putExtra("action", EbookConstants.TO_NEXT_PART);
setResult(RESULT_OK, intent);
finish();
}
break;
case 3: // 跳至本章开头
{
Intent intent = new Intent();
intent.putExtra("action", EbookConstants.TO_PART_START);
setResult(RESULT_OK, intent);
finish();
}
break;
case 4: // 跳至本章百分比
startPercentEdit(selectItem, menuItem);
break;
default:
break;
}
}
private void initView() {
// TODO 需要传递书签管理需要的信息、当前页码、页码总数
Intent intent = getIntent();
percent = intent.getFloatExtra("percent", 0.0f);
mBookmarkEntity = (BookmarkEntity) intent.getSerializableExtra("book_mark");
mTitle = getResources().getString(R.string.common_functionmenu);
mMenuList = ArrayUtils.strArray2List(getResources().getStringArray(R.array.library_audio_function_menu_list));
}
// 启动书签管理界面
public void startBookmarkManager(int selectItem, String menuItem) {
Intent intent = new Intent();
intent.putExtra(MenuConstant.INTENT_KEY_TITLE, menuItem);
// TODO 以下内容需要在播放界面按菜单键启动当前界面时传入,此时,启动书签管理界面时传给书签管理界面!
// intent.putExtra("book_id", chapterInfo.bookId); // 数目ID
// intent.putExtra("chapter_index", chapterInfo.chapterIndex); // 当前序号
// intent.putExtra("begin", 0); // 当前阅读位置
// intent.putExtra("bookmark_name", chapterInfo.bookId); // 书签名
intent.putExtra("book_mark", mBookmarkEntity);
intent.setClass(this, BookmarkManager.class);
// 如果希望启动另一个Activity,并且希望有返回值,则需要使用startActivityForResult这个方法,
// 第一个参数是Intent对象,第二个参数是一个requestCode值,如果有多个按钮都要启动Activity,则requestCode标志着每个按钮所启动的Activity
startActivityForResult(intent, selectItem);
}
// 启动跳转页码编辑界面
public void startPercentEdit(int selectItem, String menuItem) {
Intent intent = new Intent();
intent.putExtra(MenuConstant.INTENT_KEY_TITLE, menuItem);
intent.putExtra("percent", percent);
intent.setClass(this, PercentEdit.class);
startActivityForResult(intent, selectItem);
}
}
|
package com.github.swapnil.LabFolderProject.dao;
import com.github.swapnil.LabFolderProject.model.LabNotebook;
/**
* DataAccess interface for {@link LabNotebook} model
*
* @author Swap
*
*/
public interface LabNotebookDao {
/**
*
* @param id
* @return Data saved in the {@link LabNotebook} record
*/
public String getLabNotebookDataById(Long id);
}
|
/**
*/
package com.rockwellcollins.atc.limp;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>No Var Block</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.rockwellcollins.atc.limp.LimpPackage#getNoVarBlock()
* @model
* @generated
*/
public interface NoVarBlock extends VarBlock
{
} // NoVarBlock
|
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
* Represents the game board
*/
public class TetrisBoard extends JComponent
{
int [][] board;
int [][] currentShape;
int numCols;
int numRows;
int shapeSize;
@Override
public void paint(Graphics g) {
super.paint(g);
// create a background
g.setColor(Color.BLACK);
g.fillRect(0, 0, shapeSize*numCols, shapeSize*numRows);
// show the board
if (board!=null){
for (int x = 0; x < numCols; x++) {
for (int y = 0; y < numRows; y++) {
if (board[x][y]>0){
g.setColor(getColor(board[x][y]));
g.fillRect(shapeSize*x, shapeSize*y, shapeSize-1, shapeSize-1);
}
}
}
}
// show the current shape
if (currentShape!=null){
for (int i = 0; i < 4; ++i){
g.setColor(getColor(currentShape[i][2]));
g.fillRect(shapeSize*currentShape[i][0], shapeSize*currentShape[i][1], shapeSize-1, shapeSize-1);
}
}
}
public void setInstances(int numCols, int numRows, int shapeSize, int[][] boardFromModel, int [][] currentShape){
this.numCols=numCols;
this.numRows=numRows;
this.shapeSize=shapeSize;
this.board=boardFromModel;
this.currentShape=currentShape;
}
private Color getColor(int colorCode){
switch (colorCode){
case 1: return Color.RED;
case 2: return Color.PINK;
case 3: return Color.GREEN;
case 4: return Color.CYAN;
case 5: return Color.BLUE;
case 6: return Color.MAGENTA;
case 7: return Color.ORANGE;
default: return Color.WHITE;
}
}
}
|
package com.stackroute;
public class AddMatrices {
public static void main(String args[]){
}
public static int[] MatrixAddition (int rows,int columns,int[] matrix_1,int[] matrix_2){
return new int[]{0, 8};
}
}
|
package com.wzy.generator;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author wzy
* @title: TestGenerator
* @description: TODO
* @date 2019/7/1 21:21
*/
public class TestGenerator {
/**
* 实现BeanNameGenerator的generateBeanName方法,可以自定义beanName的生成策略
*/
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
String[] names = context.getBeanDefinitionNames();
for(String name : names) {
System.out.println(name);
}
}
}
|
package com.commercetools.pspadapter.payone;
import com.commercetools.pspadapter.payone.config.PayoneConfig;
import com.commercetools.pspadapter.payone.config.PropertyProvider;
import com.commercetools.pspadapter.payone.config.ServiceConfig;
import com.commercetools.pspadapter.payone.domain.payone.model.common.Notification;
import com.commercetools.pspadapter.payone.notification.NotificationDispatcher;
import com.commercetools.pspadapter.tenant.TenantConfig;
import com.commercetools.pspadapter.tenant.TenantFactory;
import com.commercetools.pspadapter.tenant.TenantPropertyProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.eclipse.jetty.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import spark.Spark;
import spark.utils.CollectionUtils;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.commercetools.pspadapter.payone.util.PayoneConstants.PAYONE;
import static com.commercetools.util.CorrelationIdUtil.attachFromRequestOrGenerateNew;
import static io.sphere.sdk.json.SphereJsonUtils.toJsonString;
import static io.sphere.sdk.json.SphereJsonUtils.toPrettyJsonString;
import static java.util.stream.Collectors.toList;
/**
* @author fhaertig
* @author Jan Wolter
*/
public class IntegrationService {
public static final Logger LOG = LoggerFactory.getLogger(IntegrationService.class);
static final int SUCCESS_STATUS = HttpStatus.OK_200;
private static final String STATUS_KEY = "status";
private static final String APPLICATION_INFO_KEY = "applicationInfo";
private static final String HEROKU_ASSIGNED_PORT = "PORT";
private List<TenantFactory> tenantFactories = null;
private ServiceConfig serviceConfig = null;
/**
* This constructor is only used for testing proposes
*/
public IntegrationService(@Nonnull final ServiceConfig config, List<TenantFactory> factories) {
this.serviceConfig = config;
this.tenantFactories = factories;
}
public IntegrationService(@Nonnull final ServiceConfig config,
@Nonnull final PropertyProvider propertyProvider) {
this.serviceConfig = config;
this.tenantFactories = serviceConfig.getTenants().stream()
.map(tenantName -> new TenantPropertyProvider(tenantName, propertyProvider))
.map(tenantPropertyProvider -> new TenantConfig(tenantPropertyProvider,
new PayoneConfig(tenantPropertyProvider)))
.map(tenantConfig -> new TenantFactory(PAYONE, tenantConfig))
.collect(toList());
if (CollectionUtils.isEmpty(this.tenantFactories)) {
throw new IllegalArgumentException("Tenants list must be non-empty");
}
}
private static void initTenantServiceResources(final TenantFactory tenantFactory) {
// create custom types
if (tenantFactory.getCustomTypeBuilder() != null) {
tenantFactory.getCustomTypeBuilder().run();
}
PaymentHandler paymentHandler = tenantFactory.getPaymentHandler();
NotificationDispatcher notificationDispatcher = tenantFactory.getNotificationDispatcher();
// register payment handler URL
String paymentHandlerUrl = tenantFactory.getPaymentHandlerUrl();
if (StringUtils.isNotEmpty(paymentHandlerUrl)) {
LOG.info("Register payment handler URL {}", paymentHandlerUrl);
Spark.get(paymentHandlerUrl, (req, res) -> {
final PayoneResult payoneResult = paymentHandler.handlePayment(req.params("id"));
if (!payoneResult.body().isEmpty()) {
LOG.debug("--> Result body of ${getTenantName()}/commercetools/handle/payments/{}: {}",
req.params("id"), payoneResult.body());
}
res.status(payoneResult.statusCode());
return res;
},
new HandlePaymentResponseTransformer());
}
// register start Session URL
String startSessionUrl = tenantFactory.getPayoneStartSessionUrl();
if (StringUtils.isNotEmpty(startSessionUrl)) {
LOG.info("Register start session URL {}", startSessionUrl);
KlarnaStartSessionHandler klarnaStartSessionHandler = tenantFactory.getSessionHandler();
Spark.get(startSessionUrl, (req, res) -> {
final PayoneResult payoneResult = klarnaStartSessionHandler.startSession(req.params("id"));
if (!payoneResult.body().isEmpty()) {
LOG.debug("--> Result body of ${getTenantName()}/commercetools/start/session/{}: {}",
req.params("id"), payoneResult.body());
}
res.status(payoneResult.statusCode());
res.body(payoneResult.body());
return res;
},
new HandlePaymentResponseTransformer());
}
// register Payone notifications URL
String payoneNotificationUrl = tenantFactory.getPayoneNotificationUrl();
if (StringUtils.isNotEmpty(payoneNotificationUrl)) {
LOG.info("Register payone notification URL {}", payoneNotificationUrl);
Spark.post(payoneNotificationUrl, (req, res) -> {
LOG.debug("<- Received POST from Payone: {}", req.body());
try {
final Notification notification = Notification.fromKeyValueString(req.body(), "\r?\n?&");
notificationDispatcher.dispatchNotification(notification);
} catch (Exception e) {
// Potential issues for this exception are:
// 1. req.body is mal-formed hence can't by parsed by Notification.fromKeyValueString
// 2. Invalid access secret values in the request (account id, key, portal id etc)
// 3. ConcurrentModificationException in case the respective payment could not be updated
// after two attempts due to concurrent modifications; a later retry might be successful
// 4. Execution timeout, if sphere client has not responded in time
// 5. unknown notification type
// Any other unexpected error.
LOG.error("Payone notification handling error. Request body: {}", req.body(), e);
res.status(400);
return "Payone notification handling error. See the logs. Requested body: " + req.body();
}
res.status(200);
return "TSOK";
});
}
}
/**
* @return Unmodifiable view of tenant factories list which are used for the service run.
*/
public List<TenantFactory> getTenantFactories() {
return Collections.unmodifiableList(tenantFactories);
}
public void start() {
initSparkService();
for (TenantFactory tenantFactory : tenantFactories) {
initTenantServiceResources(tenantFactory);
}
Spark.awaitInitialization();
}
private void initSparkService() {
Spark.port(port());
injectCorrelationIdIntoContext();
final Map<String, Object> healthResponse = createHealthResponse(serviceConfig);
final String healthRequestContent = toJsonString(healthResponse);
final String healthRequestPrettyContent = toPrettyJsonString(healthResponse);
// This is a temporary jerry-rig for the load balancer to check connection with the service itself.
// For now it just returns a JSON response with status code, tenants list and static application info.
// It should be expanded to a more real health-checker service, which really performs PAYONE status check.
// But don't forget, a load balancer may call this URL very often (like 1 per sec),
// so don't make this request processor heavy, or implement is as independent background service.
LOG.info("Register /health URL");
LOG.info("Use /health?pretty to pretty-print output JSON");
Spark.get("/health", (req, res) -> {
res.status(SUCCESS_STATUS);
res.type(ContentType.APPLICATION_JSON.getMimeType());
return req.queryParams("pretty") != null ? healthRequestPrettyContent : healthRequestContent;
});
}
private void injectCorrelationIdIntoContext() {
Spark.before(((request, response) -> attachFromRequestOrGenerateNew(request)));
Spark.after(((request, response) -> MDC.clear()));
}
public void stop() {
Spark.stop();
}
public int port() {
final String environmentVariable = System.getenv(HEROKU_ASSIGNED_PORT);
if (!StringUtils.isBlank(environmentVariable)) {
return Integer.parseInt(environmentVariable);
}
final String systemProperty = System.getProperty(HEROKU_ASSIGNED_PORT, "8080");
return Integer.parseInt(systemProperty);
}
private Map<String, Object> createHealthResponse(@Nonnull final ServiceConfig serviceConfig) {
final Map<String, String> applicationInfo = new LinkedHashMap<>();
applicationInfo.put("version", serviceConfig.getApplicationVersion());
applicationInfo.put("title", serviceConfig.getApplicationName());
final Map<String, Object> healthResponse = new LinkedHashMap<>();
healthResponse.put(STATUS_KEY, SUCCESS_STATUS);
healthResponse.put(APPLICATION_INFO_KEY, applicationInfo);
return healthResponse;
}
}
|
package com.me.graficos;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import com.me.entities.Npc;
import com.me.main.Game;
public class UI_User_Interface {
/*Nessa classe estamos aplicando a barra de vida do player*/
public void render(Graphics g) {
g.setColor(new Color(255, 255, 255, 150));
g.fillRoundRect(1 , -3 ,(int) (Game.player.maxLife * 0.81) + 2, 12, 2, 4);
g.setColor(new Color(200, 0, 0, 200));
g.fillRoundRect(2 , -2 ,(int) (Game.player.maxLife * 0.81), 10, 2, 4); //os 0.81 usados é para determinar que o desenvolvedor deseja que apareça 81% do tamanho original da variável
g.setColor(new Color(0, 200, 0, 200));
//usado na aula (Player.life / Player.maxLife) * 50)
//valor da vida / 100 (vida maxima) * 50 (a conta está pegando metade do valor da vida para a representação gráfica)
g.fillRoundRect(2 , -2 ,(int) ((Game.player.life * 0.81)), 10, 2, 4); //para manter em uma posição fixa na tela, apenas não coloque o offset da camera
//life precisa ser declarado como double, para aplicar a divisão corretamente
//(Player.life * 0.81) == ((Player.life /100) * 81) == 81% de Player.life
g.setColor(new Color(255, 255, 255, 150));
g.setFont(new Font("Arial", Font.BOLD, 10));
g.drawString((int) Game.player.life + " / " + (int) Game.player.maxLife, 5, 8);
if(Game.npc.isReading && (Math.abs(Game.player.getX() - Game.npc.getX()) < 50 && Math.abs(Game.player.getY() - Game.npc.getY()) < 50)) {
g.setFont(new Font("Arial", Font.BOLD, 9));
g.setColor(Color.black);
g.fillRect(Game.npc.getX() - 20, Game.npc.getY() + 50, 150, 45);
g.setColor(Color.white);
Game.npc.maxIndex1 = Npc.frases[Game.npc.myTextCont].length();
Game.npc.maxIndex2 = Npc.frases[Game.npc.myTextCont+1].length();
Game.npc.maxIndex3 = Npc.frases[Game.npc.myTextCont+2].length();
if(Game.npc.curIndex1 > Game.npc.maxIndex1)
Game.npc.curIndex1 = Game.npc.maxIndex1;
g.drawString(Npc.frases[Game.npc.myTextCont].substring(0, Game.npc.curIndex1), Game.npc.getX() - 10, Game.npc.getY() + 60);
if(Game.npc.curIndex2 > Game.npc.maxIndex2)
Game.npc.curIndex2 = Game.npc.maxIndex2;
g.drawString(Npc.frases[Game.npc.myTextCont+1].substring(0, Game.npc.curIndex2), Game.npc.getX() - 10, Game.npc.getY() + 70);
if(Game.npc.curIndex3 > Game.npc.maxIndex3)
Game.npc.curIndex3 = Game.npc.maxIndex3;
g.drawString(Npc.frases[Game.npc.myTextCont+2].substring(0, Game.npc.curIndex3), Game.npc.getX() - 10, Game.npc.getY() + 80);
g.setColor(Color.magenta);
g.setFont(new Font("Arial", Font.BOLD, 8));
g.drawString("PRESS ENTER", Game.npc.getX() + 75, Game.npc.getY() + 95);
if(Game.npc.nextMessage) {
Game.npc.nextMessage = false;
Game.npc.myTextCont+=3;
Game.npc.curIndex1 = 0;
Game.npc.curIndex2 = 0;
Game.npc.curIndex3 = 0;
}
}else {
if(Game.npc.showMessage) {
g.setFont(new Font("Arial", Font.BOLD, 10));
g.setColor(Color.black);
g.fillRect(Game.npc.getX(), Game.npc.getY() + 50, 120, 17);
g.setColor(Color.white);
g.drawString("Aperte Q para interagir", Game.npc.getX() + 4, Game.npc.getY() + 60);
}
/*ALERTA: Ao utilizar da classe para manipular a variável, todos os objetos com essa classe irão obedecer o comando,
* logo, eu um contexto de multijogadores, isso é delicado, pois se 1 jogador perder vida com Player.life aplicado,
* todos os players perderão aquela quantidade de vida, por estar manipulando a classe e não o objeto*/
}
}
}
|
package tr.edu.fsm.javaprogramingapp.quiz;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
import tr.edu.fsm.javaprogramingapp.R;
public class QuizSorularActivity extends AppCompatActivity implements FindCallback<ParseObject> {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private TextView mQuestionTextView;
ListView list1;
QuizBaseAdapter adapter;
private boolean isComplete = false;
private List<TrueFalse> list = new ArrayList<>();
private List<TrueFalse> mQuestionBank = new ArrayList<>();
@Override
public void done(List<ParseObject> list, ParseException e) {
for(ParseObject p : list){
String soru = p.getString("soru");
Boolean cvp = Boolean.valueOf(p.getString("cevap"));
Log.v("data", soru + cvp);
mQuestionBank.add(new TrueFalse(soru, cvp));
}
isComplete = true;
updateQuestion();
}
private int mCurrentIndex = 0;
private void updateQuestion(){
String question = mQuestionBank.get(mCurrentIndex).getStringQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue){
boolean answerIsTrue = mQuestionBank.get(mCurrentIndex).isTrueQuestion();
String messageResId = "";
if (userPressedTrue == answerIsTrue){
messageResId = "DOĞRU!";
} else{
messageResId = "YANLIŞ!";
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_sorular);
Bundle bndl = getIntent().getExtras();
String q = bndl.getString("quiztype");
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(q);
query.findInBackground(this);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
setmTrueButton((Button) findViewById(R.id.trueButton));
getmTrueButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
setmFalseButton((Button) findViewById(R.id.falseButton));
getmFalseButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.size();
updateQuestion();
}
});
if(isComplete) updateQuestion();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public Button getmTrueButton() {
return mTrueButton;
}
public void setmTrueButton(Button mTrueButton) {
this.mTrueButton = mTrueButton;
}
public Button getmFalseButton() {
return mFalseButton;
}
public void setmFalseButton(Button mFalseButton) {
this.mFalseButton = mFalseButton;
}
// new TrueFalse(R.string.question_interface, false),
}
|
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
Scanner scan = new Scanner(System.in);
Random generator = new Random();
private int upperLimit;
private int computerGuess;
private int userGuess;
// Creates GuessingGame constructor
public GuessingGame(int n) {
this.upperLimit = n;
this.computerGuess = generator.nextInt(n - 1) + 1;
}
// Prompts the user to guess a number between 1 and the upperLimit set by the user
public void guess() {
System.out.print("Guess a number between 1 and " + upperLimit + ": ");
userGuess = scan.nextInt();
}
// Creates the win condition that must be met by the user to win
public boolean userWon() {
System.out.println("The computer guessed: " + computerGuess);
if (userGuess == computerGuess) {
return true;
} else {
return false;
}
}
}
|
package com.mx.profuturo.bolsa.model.role;
public class VacanciesActions {
}
|
package com.mikronia.pixpaint.component.dialogs;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import com.mikronia.pixpaint.component.Canvas;
import com.mikronia.pixpaint.component.PixDialog;
/**
* PixPaint resize dialog
*
* @since PixPaint 1.0.0
* @version 1.0
*
* @author Thaynan M. Silva
*/
public class ResizeDialog extends PixDialog {
private static final long serialVersionUID = 1L;
public ResizeDialog() {
super("dialog.resize.title", 220, 180);
}
@Override
protected void createComponents() {
JPanel contentPane = getContentPane();
/////////////////////
// canvas
JPanel controlPane = new JPanel(null);
contentPane.add(controlPane);
/////////////////////
//
JLabel lbWidth = new JLabel(getLanguage("dialog.resize.label.width"), JLabel.RIGHT);
lbWidth.setBounds(10, 10, 100, 30);
controlPane.add(lbWidth);
//
JLabel lbHeight = new JLabel(getLanguage("dialog.resize.label.height"), JLabel.RIGHT);
lbHeight.setBounds(10, 50, 100, 30);
controlPane.add(lbHeight);
//
JSpinner spWidth = new JSpinner(new SpinnerNumberModel(16, 4, 512, 1));
spWidth.setBounds(120, 10, 80, 30);
controlPane.add(spWidth);
//
JSpinner spHeight = new JSpinner(new SpinnerNumberModel(16, 4, 512, 1));
spHeight.setBounds(120, 50, 80, 30);
controlPane.add(spHeight);
/////////////////////
JPanel buttonPanel = new JPanel();
contentPane.add(buttonPanel, BorderLayout.SOUTH);
JButton btConfirm = new JButton(getLanguage("dialog.resize.apply"));
btConfirm.addActionListener((e) -> {
// the canvas
Canvas canvas = Registry.getPixWindow().canvas;
// old dimensions
int oWidth = canvas.getImage().getWidth(),
oHeight = canvas.getImage().getHeight();
// new dimensions
int nWidth = (int) spWidth.getValue(),
nHeight = (int) spHeight.getValue();
// change test
if (nWidth - oWidth == 0 && nHeight - oHeight == 0) {
// show info message
JOptionPane.showMessageDialog(this,
getLanguage("app.message.question.nochanges"),
getTitle(), JOptionPane.INFORMATION_MESSAGE);
} else {
if (nWidth < oWidth || nHeight < oHeight) {
// show info message
JOptionPane.showMessageDialog(this,
getLanguage("app.message.question.dimension*"),
getTitle(), JOptionPane.PLAIN_MESSAGE);
}
// resize image
canvas.resizeImage(nWidth, nHeight);
}
// close dialog
dispose();
});
buttonPanel.add(btConfirm);
JButton btCancel = new JButton(getLanguage("dialog.resize.cancel"));
btCancel.addActionListener((e) -> dispose());
buttonPanel.add(btCancel);
}
}
|
package com.theksmith.steeringwheelinterface;
import com.theksmith.steeringwheelinterface.ElmInterface.DeviceOpenEvent;
import com.theksmith.steeringwheelinterface.ElmInterface.DeviceOpenEventListener;
import com.theksmith.steeringwheelinterface.R;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
/**
* Foreground service that keeps running even when main activity is destroyed.
* Manages the vehicle interface and provides status notifications.
*
* @author Kristoffer Smith <stuff@theksmith.com>
*/
public class SteeringWheelInterfaceService extends Service {
protected static final String TAG = SteeringWheelInterfaceService.class.getSimpleName();
protected static final int WATCHDOG_INTERVAL = 30000;
protected final Handler watchdog_Timer = new Handler();
protected NotificationManager mNoticeManager;
protected final Builder mNoticeBuilder = new Builder(this);
protected int mNoticeID;
protected ElmInterface mCarInterface;
protected ElmInterfaceOpenedListener mDeviceOpenListener = new ElmInterfaceOpenedListener();
/**
* Watch for device removal and stop interface or exit app completely depending on settings.
*/
public BroadcastReceiver mUsbDetachedReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean exitPrefDefault = Boolean.parseBoolean(getString(R.string.scantool_detach_disconnect));
Boolean exitPrefValue = settings.getBoolean("scantool_detach_disconnect", exitPrefDefault);
if (exitPrefValue) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
//verify this intent is regarding the specific device we opened, don't close another app's serial device
if (device != null && SteeringWheelInterfaceService.this.mCarInterface != null) {
if (device.getDeviceId() == SteeringWheelInterfaceService.this.mCarInterface.getDeviceID()) {
Intent exitIntent = new Intent(getBaseContext(), SteeringWheelInterfaceActivity.class);
exitIntent.setAction(Intent.ACTION_DELETE);
exitIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exitIntent);
Toast.makeText(getApplicationContext(), getString(R.string.msg_device_disconnected), Toast.LENGTH_SHORT).show();
}
}
} else {
carInterfaceStop();
}
}
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
watchdog_TimerStop();
unregisterReceiver(mUsbDetachedReceiver);
if (mCarInterface != null) {
mCarInterface.deviceClose();
mCarInterface = null;
}
mNoticeManager.cancelAll();
}
@Override
public void onCreate() {
IntentFilter filterUsbDetached = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbDetachedReceiver, filterUsbDetached);
Intent settingsIntent = new Intent(this, SteeringWheelInterfaceActivity.class);
settingsIntent.setAction(Intent.ACTION_EDIT);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(SteeringWheelInterfaceActivity.class);
stackBuilder.addNextIntent(settingsIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mNoticeBuilder.setContentIntent(resultPendingIntent);
mNoticeBuilder.setSmallIcon(R.drawable.ic_notice);
mNoticeBuilder.setContentTitle(getString(R.string.app_name));
mNoticeBuilder.setContentText(getString(R.string.msg_app_starting));
mNoticeManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNoticeManager.notify(mNoticeID, mNoticeBuilder.build());
mCarInterface = new ElmInterface(getApplicationContext());
mCarInterface.deviceOpenEvent_AddListener(mDeviceOpenListener);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String baudDefault = getString(R.string.scantool_baud);
int baudValue = Integer.parseInt(settings.getString("scantool_baud", baudDefault));
mCarInterface.setBaudRate(baudValue);
String deviceNumDefault = getString(R.string.scantool_device_number);
int deviceNumValue = Integer.parseInt(settings.getString("scantool_device_number", deviceNumDefault));
mCarInterface.setDeviceNumber(deviceNumValue);
String protocolCommandDefault = getString(R.string.scantool_protocol);
String protocolCommandValue = settings.getString("scantool_protocol", protocolCommandDefault);
mCarInterface.setProtocolCommand(protocolCommandValue);
String monitorCommandDefault = getString(R.string.scantool_monitor_command);
String monitorCommandValue = settings.getString("scantool_monitor_command", monitorCommandDefault);
mCarInterface.setMonitorCommand(monitorCommandValue);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(mNoticeID, mNoticeBuilder.build());
carInterfaceRestartIfNeeded();
watchdog_TimerReStart();
return START_STICKY;
}
protected void updateNotification() {
if (mCarInterface != null && mCarInterface.getsStatus() == ElmInterface.STATUS_OPEN_MONITORING) {
mNoticeBuilder.setContentText(getString(R.string.msg_monitoring));
} else {
mNoticeBuilder.setContentText(getString(R.string.msg_monitoring_stopped));
}
mNoticeManager.notify(mNoticeID, mNoticeBuilder.build());
}
/**
* Monitors the interface and re-starts monitoring or re-opens interface as needed.
*/
protected void carInterfaceRestartIfNeeded() {
int status = mCarInterface.getsStatus();
if (status == ElmInterface.STATUS_OPEN_STOPPED) {
try {
mCarInterface.monitorStart();
} catch (Exception ex) {
Log.e(TAG, "ERROR STARTING CAR INTERFACE MONITORING", ex);
}
} else if (status != ElmInterface.STATUS_OPEN_MONITORING) {
mCarInterface.deviceOpen();
//code flow continues when mDeviceOpenListener.onDeviceOpenEvent() is fired
}
updateNotification();
}
protected void carInterfaceStop() {
try {
mCarInterface.deviceClose();
} catch (Exception ex) {
Log.e(TAG, "ERROR STOPPING CAR INTERFACE", ex);
}
updateNotification();
}
protected Runnable watchdog_TimerRun = new Runnable() {
public void run() {
carInterfaceRestartIfNeeded();
watchdog_TimerReStart();
}
};
protected void watchdog_TimerStop() {
watchdog_Timer.removeCallbacks(watchdog_TimerRun);
}
protected void watchdog_TimerReStart() {
watchdog_TimerStop();
watchdog_Timer.postDelayed(watchdog_TimerRun, WATCHDOG_INTERVAL);
}
protected class ElmInterfaceOpenedListener implements DeviceOpenEventListener {
@Override
public void onDeviceOpenEvent(DeviceOpenEvent event) {
if (mCarInterface.getsStatus() == ElmInterface.STATUS_OPEN_STOPPED) {
try {
mCarInterface.monitorStart();
} catch (Exception ex) {
Log.e(TAG, "ERROR STARTING CAR INTERFACE MONITORING", ex);
}
} //else didn't finish opening, but should be good by next time around on the watchdog, so do nothing special now
updateNotification();
}
}
}
|
import java.io.*;
public class PizzaFactory
{
public Pizza createPizza(String type)
{
if(type.equals("CheesePizza"))
{
return new Pizza(type);
}
return new Pizza("Plain Pizza");
}
}
|
package com.smilehacker.timing.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import com.smilehacker.timing.R;
import com.smilehacker.timing.util.DLog;
/**
* Created by kleist on 14-5-25.
*/
public class MyListView extends ListView {
private View mHeader;
private int mHeaderHeight;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
mHeaderHeight = getResources().getDimensionPixelOffset(R.dimen.graph_view_height);
addHeader();
}
private void addHeader() {
mHeader = new View(getContext());
ListView.LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mHeaderHeight);
mHeader.setLayoutParams(lp);
this.addHeaderView(mHeader);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (isTouchHeader(ev)) {
return false;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (isTouchHeader(ev)) {
return false;
}
return super.onTouchEvent(ev);
}
private Boolean isTouchHeader(MotionEvent event) {
int y = (int) event.getY();
return y < mHeaderHeight + mHeader.getY();
}
}
|
package zomeapp.com.zomechat.activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import zomeapp.com.zomechat.R;
import zomeapp.com.zomechat.application.ZomeApplication;
public class SignUpActivity extends Activity {
private LinearLayout linearLayout;
private EditText etEmailSignUp, etPasswordSignUp, etConfirmPassword;
private Button btnSignUp;
private Button btnBack;
private Context context;
private ZomeApplication application;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
context = this;
application = (ZomeApplication) getApplication();
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
etEmailSignUp = (EditText) findViewById(R.id.etEmailSignUp);
etPasswordSignUp = (EditText) findViewById(R.id.etPasswordSignUp);
etConfirmPassword = (EditText) findViewById(R.id.etConfirmPassword);
btnSignUp = (Button) findViewById(R.id.btnSignUp);
btnBack = (Button) findViewById(R.id.btnBack);
RelativeLayout.LayoutParams llParams = (RelativeLayout.LayoutParams) linearLayout.getLayoutParams();
if (application.mZomeUtils.metrics.heightPixels <= 320) {
llParams.setMargins(application.mZomeUtils.dpToPx(32), 0, application.mZomeUtils.dpToPx(32), application.mZomeUtils.dpToPx(15));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
linearLayout.setGravity(Gravity.TOP);
}
linearLayout.setLayoutParams(llParams);
}
btnSignUp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
btnSignUp.setTextColor(Color.BLACK);
} else {
btnSignUp.setTextColor(Color.parseColor("#767a85"));
}
return false;
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!etPasswordSignUp.getText().toString().equals(etConfirmPassword.getText().toString())) {
Toast.makeText(context, "Passwords do not match. Please double-check your password.", Toast.LENGTH_SHORT).show();
} else if (etPasswordSignUp.getText().length() < 5) {
Toast.makeText(context, "Passwords must contain at least 5 characters.", Toast.LENGTH_SHORT).show();
} else {
if (application.mZomeUtils.isValidEmail(etEmailSignUp.getText())) {
postSignUpData();
} else {
Toast.makeText(context, "Not a valid email address.", Toast.LENGTH_SHORT).show();
}
}
}
});
btnBack.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
btnBack.setTextColor(Color.BLACK);
} else {
btnBack.setTextColor(Color.WHITE);
}
return false;
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
}
private void postSignUpData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("version", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
jsonObject.put("password", etPasswordSignUp.getText().toString());
jsonObject.put("uid", etEmailSignUp.getText().toString());
jsonObject.put("lat", application.lat);
jsonObject.put("lng", application.lng);
application.mSocket.emit("signup", jsonObject);
Intent returnData = new Intent();
returnData.putExtra("uid", jsonObject.getString("uid"));
returnData.putExtra("password", jsonObject.getString("password"));
setResult(RESULT_OK, returnData);
finish();
} catch (JSONException | PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
|
package stringhanding;
public class comparefirstChar {
String s1 = "Hello";
String s2 = "helmno";
public void firstChar(){
System.out.println(s1.substring(0,2));
System.out.println(s2.substring(0,2));
if(s1.substring(0,2).equalsIgnoreCase(s2.substring(0,2))){
System.out.println("starting 3 characters are equal in 2 strings");
}else{
System.out.println("Not equal");
}
}
}
|
package me.zakeer.justchat.imagecache;
import java.io.File;
import android.content.Context;
import android.util.Log;
import me.zakeer.justchat.utility.FileUtility;
public class FileCache {
private static final String TAG = "FileCache";
private File cacheDir;
public FileCache(Context context) {
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
FileUtility fileUtility = new FileUtility(context);
File appFolder = fileUtility.getAppFolder();
cacheDir=new File(appFolder, FileUtility.FOLDER_IMAGES);
}
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
public File getFile(String url) {
Log.e(TAG, "url : "+url);
String finalUrl = url;
if(url.contains("/"))
{
finalUrl = url.substring(url.lastIndexOf("/") +1);
}
Log.e(TAG, "finalUrl : "+finalUrl);
String filename= finalUrl;//String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
|
package com.smxknife.algorithm.demo01.selectionsort;
import com.google.common.base.Preconditions;
import java.util.*;
/**
* @author smxknife
* 2019-04-29
*/
public class SelectionSort {
/**
* 选择排序
* @param desc 是否是降序排列,null|false为升序,true为降序
* @param elements 需要排序的元素
* @param <T>
* @return 排序后的数组
*/
public static <T extends Comparable> List<T> sort(Boolean desc, T... elements) {
Preconditions.checkNotNull(elements);
List<T> sorted = new ArrayList<>(elements.length);
List<T> org = new LinkedList<>();
org.addAll(Arrays.asList(elements));
while (org.size() > 0) {
T target = null;
if (Boolean.TRUE.equals(desc)) {
target = findMax(org);
} else {
target = findMin(org);
}
sorted.add(target);
}
return sorted;
}
private static <T extends Comparable> T findMin(List<T> org) {
T target = org.get(0);
for (T t : org) {
if (target.compareTo(t) > 0) target = t;
}
org.remove(target);
return target;
}
private static <T extends Comparable> T findMax(List<T> org) {
T target = org.get(0);
for (T t : org) {
if (target.compareTo(t) < 0) target = t;
}
org.remove(target);
return target;
}
}
|
package com.yekong.rxmobile.retrofit;
import com.yekong.rxmobile.model.DoubanUserSearch;
import retrofit.http.GET;
import retrofit.http.Query;
import rx.Observable;
/**
* Created by baoxiehao on 16/1/15.
*/
public interface DoubanService {
String BASE_URL = "http://api.douban.com/v2/";
@GET("user")
Observable<DoubanUserSearch> searchUsers(@Query("q") String query,
@Query("count") int count,
@Query("start") int start);
}
|
package com.lubarov.daniel.web.util;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class UuidUtilsTest {
@Test
public void testRandomAlphanumericUuid() {
String uuid = UuidUtils.randomAlphanumericUuid();
for (char c : uuid.toCharArray())
assertTrue("Not alphanumeric: " + c, Character.isLetterOrDigit(c));
}
}
|
package com.liuwei.control;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Login {
@RequestMapping(value="/login",method=RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value="/loginOut",method=RequestMethod.GET)
public String loginOut() {
return "login";
}
@RequestMapping("welcome")
public String welcome(Model model,HttpServletRequest req) {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object principal = authentication.getPrincipal();
if(principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
String username = userDetails.getUsername();
String password = userDetails.getPassword();
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
Class<? extends UserDetails> class1 = userDetails.getClass();
System.out.println("username="+username);
System.out.println("password="+password);
System.out.println("authorities="+authorities);
System.out.println("class1="+class1);
req.setAttribute("username",username);
}else {
System.out.println("获取用户信息失败了");
}
// Object principal = principal;
// SecurityContextHolder.getContext();
// String username = principal instanceof String ?
// (String) principal : "名臣不是String";
// req.setAttribute("username",username);
// model.addAttribute("username",username);
// System.out.println("----------当前系统用户的名字="+username);
return "welcome";
}
@RequestMapping("/user")
@ResponseBody
public String userInfo() {
return "you have user role";
}
@RequestMapping("/admin/info")
@ResponseBody
public String info(){
return "you have role admin";
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class BOJ_13168_내일로_여행 {
private static StringBuilder sb = new StringBuilder();
private static int N,R,M,K;
private static int[][] noNaeil, Naeil;
private static HashMap<String, Integer> city;
private static String[] trav;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
city = new HashMap<>();
for (int i = 0; i < N; i++) {
city.put(st.nextToken(), i);
}
M = Integer.parseInt(br.readLine());
trav = new String[M];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) {
trav[i] = st.nextToken();
}
K = Integer.parseInt(br.readLine());
noNaeil = new int[N][N];
Naeil = new int[N][N];
init();
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
String traf = st.nextToken();
String start = st.nextToken();
String end = st.nextToken();
int cost = Integer.parseInt(st.nextToken());
// 양방향으로 저장해둔다(물론 최소값으로)
noNaeil[city.get(start)][city.get(end)] = Math.min(cost,noNaeil[city.get(start)][city.get(end)]);
noNaeil[city.get(end)][city.get(start)] = noNaeil[city.get(start)][city.get(end)];
Naeil[city.get(start)][city.get(end)] = Math.min(cost,Naeil[city.get(start)][city.get(end)]);
Naeil[city.get(end)][city.get(start)] = Naeil[city.get(start)][city.get(end)];
// 다만 내일로 일경우 값을 좀 수정
if(traf.equals("Mugunghwa")|| traf.equals("ITX-Saemaeul")|| traf.equals("ITX-Cheongchun")) {
Naeil[city.get(start)][city.get(end)] = 0;
Naeil[city.get(end)][city.get(start)] = 0;
}else if (traf.equals("S-Train") || traf.equals("V-Train")) {
Naeil[city.get(start)][city.get(end)] = Math.min(cost/2,Naeil[city.get(start)][city.get(end)]);
Naeil[city.get(end)][city.get(start)] = Naeil[city.get(start)][city.get(end)];
}
}
// 플로이드 와샬
fw();
// 총합 구하기(내일로는 티켓값 포함)
int sumNaeil=R, sumNo=0;
for (int i = 0; i < M-1; i++) {
sumNaeil+=Naeil[city.get(trav[i])][city.get(trav[i+1])];
sumNo+=noNaeil[city.get(trav[i])][city.get(trav[i+1])];
}
// 내일로가 더 비싸면? No
System.out.println(sumNaeil < sumNo ? "Yes": "No" );
}
// 초기화
public static void init() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
noNaeil[i][j] = Integer.MAX_VALUE;
Naeil[i][j] = Integer.MAX_VALUE;
}
}
}
// 플로이드 와샬
public static void fw() {
for (int k = 0; k < N; k++) { // 경유
for (int i = 0; i < N; i++) { // 출발
if(k == i) continue;
for (int j = 0; j < N; j++) { // 도착
if(k == j || i == j) continue;
if(noNaeil[i][k]!= Integer.MAX_VALUE && noNaeil[k][j]!= Integer.MAX_VALUE
&& noNaeil[i][j] > noNaeil[i][k] + noNaeil[k][j])
noNaeil[i][j] = noNaeil[i][k] + noNaeil[k][j];
if(Naeil[i][k]!= Integer.MAX_VALUE && Naeil[k][j]!= Integer.MAX_VALUE
&& Naeil[i][j] > Naeil[i][k] + Naeil[k][j])
Naeil[i][j] = Naeil[i][k] + Naeil[k][j];}
}
}
}
}
|
package me.yamas.tools.commands;
import me.yamas.tools.Main;
import me.yamas.tools.commands.utils.Executor;
import me.yamas.tools.objects.User;
import me.yamas.tools.utils.HomeUtil;
import me.yamas.tools.utils.Util;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ExcHome implements Executor{
@Override
public void execute(CommandSender sender, String[] args) {
if(!(sender instanceof Player)){
Util.sendMessage(Bukkit.getConsoleSender(), "&4Blad: &cMusisz byc na serwerze aby wykonac ta komende!");
return;
}
if(!sender.hasPermission("yamastools.cmd.home")){
Util.sendMessage(sender, "&cNie masz uprawnien do uzycia tej komendy &8(&7yamastools.cmd.home&8)");
return;
}
final Player p = (Player) sender;
final User user = User.get(p);
if(!user.hasHome()){
Util.sendMessage(p, "&4Blad: &cNie posiadasz zadnego domu!");
return;
}
if(!HomeUtil.getHomeTeleport().contains(p)){
HomeUtil.addPlayerHomeTeleport(p);
Util.sendMessage(p, "&8» &7Zostaniesz przeteleportowany za: &45 sekund &7Nie ruszaj sie!");
}
if(HomeUtil.getHomeTeleport().contains(p)){
Bukkit.getScheduler().runTaskLater(Main.getInstance(), new Runnable() {
@Override
public void run() {
HomeUtil.removePlayerHomeTeleport(p);
p.teleport(user.getHome());
Util.sendMessage(p, "&8» &7Zostales przeteleportowany do swojego domu!");
}
}, 5*20L);
}
}
}
|
package StringTest;
/**
* @Author weimin
* @Date 2020/10/7 0007 10:11
*/
public class Main5 {
public static void main(String[] args) {
String s1 = "helloworld";
String s2 = "hello";
String s3 = s2 + "world";
System.out.println(s1 == s3); //false
final String s4 = "hello";
String s5 = s4 + "world";
System.out.println(s1 == s5); // true 因为s4是常量
}
}
|
/**
* CommonFramework
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.tools.commonframework.core.config.user;
import java.io.Serializable;
/**
* An interface for classes that provide getters/setters for server-specific
* user credentials.
*/
public interface CommonUser extends Serializable {
/**
* Sets the server.
*
* @param servername
* the new server
*/
void setServer(String servername);
/**
* Sets the user name.
*
* @param username
* the new user name
*/
void setUserName(String username);
/**
* Sets the password.
*
* @param password
* the new password
*/
void setPassword(String password);
/**
* Gets the server.
*
* @return the server
*/
String getServer();
/**
* Gets the user name.
*
* @return the user name
*/
String getUserName();
/**
* Gets the password.
*
* @return the password
*/
String getPassword();
}
|
// Sun Certified Java Programmer
// Chapter 6, P470
// Strings, I/O, Formatting, and Parsing
import java.io.*;
class Bar implements Serializable {
transient int x = 42;
}
|
package com.example.l03.projektpaszport;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Krzysiek on 02.11.2016.
*/
public class Fragment_Preferencja_lubie extends Fragment {
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<Preferencja> preferencje;
private DatabaseHelper db;
public Fragment_Preferencja_lubie() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment Fragment_Preferencja_lubie.
*/
// TODO: Rename and change types and number of parameters
public static Fragment_Preferencja_lubie newInstance() {
Fragment_Preferencja_lubie fragment = new Fragment_Preferencja_lubie();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_preferencja_lubie, container, false);
listView = (ListView) rootView.findViewById(R.id.lvLubie);
db = new DatabaseHelper(getContext());
preferencje = db.getAllPreferencjaByLubie(true);
final PreferencjaLubieAdapter adapter = new PreferencjaLubieAdapter();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("naciśnięto element","true");
}
});
/* gridView.setOnClickListener(new View.OnClickListener() { //powinno być setOnItemClickListener bo wybierasz item z listy
@Override
public void onClick(View v) {
Log.e("naciśnięto element","true");
}
});
*/
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private class PreferencjaLubieAdapter extends BaseAdapter {
@Override
public int getCount() {
if (preferencje != null && preferencje.size() != 0)
return preferencje.size();
return 0;
}
@Override
public Object getItem(int position) {
return preferencje.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getActivity()); //byłem tak blisko...
convertView = inflater.inflate(R.layout.preferencja_listview_item, null);
holder.opis = (TextView)convertView.findViewById(R.id.tvItemText);
holder.opis.setText(preferencje.get(position).getOpis());
holder.zdjecie = (ImageView) convertView.findViewById(R.id.ivItemImage);
Bitmap bitmap = BitmapFactory.decodeFile(preferencje.get(position).getZdjecie());
holder.zdjecie.setImageBitmap(bitmap);
//holder.helper = (ImageView) convertView.findViewById(R.id.ivHelper);
//holder.helper.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.PreferencjeGreen));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
return convertView;
}
private class ViewHolder {
ImageView zdjecie;
ImageView helper;
TextView opis;
int ref;
}
}
}
|
package com.nishant.code;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
public class Monitor implements Job {
private String monitorFolder;
private long thresholdSize;
// private String archiveFolder;
public void makeSecure() throws IOException {
System.out.println("executing MONITOR");
removeExecutables();
System.out.println("monitorFolder size is : " + getfolderSize());
archive();
}
private long getfolderSize() {
try {
return Files.walk(Paths.get(monitorFolder)).mapToLong(p -> p.toFile().length()).sum();
} catch (IOException e) {
System.out.println("Unable to size of monitorFolder: secured");
// e.printStackTrace();
}
return 0;
}
private void removeExecutables() throws IOException {
Files.walk(Paths.get(monitorFolder)).filter(
p -> p.toString().endsWith(".exe") || p.toString().endsWith(".sh") || p.toString().endsWith(".bash"))
.forEach(execeutableFile -> {
try {
Files.delete(execeutableFile);
} catch (IOException e) {
System.out.println("Unable to delete executable file : " + execeutableFile);
// e.printStackTrace();
}
});
}
private Queue<File> filesSortedCreationTime() {
File monitorFolderFile = new File(monitorFolder);
File[] filesList = monitorFolderFile.listFiles();
Arrays.sort(filesList, new Comparator<File>() {
@Override
public int compare(File firstFile, File secondFile) {
long date1 = 0;
long date2 = 0;
try {
date1 = getCreationTime(firstFile).toMillis();
date2 = getCreationTime(secondFile).toMillis();
} catch (IOException e) {
System.out.println("Not able to get the file creation time");
e.printStackTrace();
}
if (date1 > date2)
return 1;
else if (date2 > date1)
return -1;
return 0;
}
});
// converting array to queue using linked list implementation
return new LinkedList<File>(Arrays.asList(filesList));
}
private void archive() {
if (getfolderSize() > thresholdSize) {
Queue<File> sortedFilesQueue = filesSortedCreationTime();
while (getfolderSize() > thresholdSize) {
try {
// File fileToBeMovedToArvhive = sortedFilesQueue.remove();
// moving files to archived folder
// String archivedFilePath = new
// File(archiveFolder).getAbsolutePath() + "\\"
// + fileToBeMovedToArvhive.getName();
// Path archiveDestination = Paths.get(archivedFilePath);
// Files.move(Paths.get(fileToBeMovedToArvhive.getAbsolutePath()),
// archiveDestination);
Files.delete(Paths.get(sortedFilesQueue.remove().getAbsolutePath()));
} catch (IOException e) {
System.out.println("Unable to delete file to reduce size from threshold size");
// e.printStackTrace();
}
;
}
}
}
private FileTime getCreationTime(File file) throws IOException {
Path p = Paths.get(file.getAbsolutePath());
BasicFileAttributes view = Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
FileTime fileTime = view.creationTime();
// also available view.lastAccessTine and view.lastModifiedTime
return fileTime;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
this.loadContextVariables(context);
try {
this.makeSecure();
} catch (IOException e) {
// e.printStackTrace();
}
}
private void loadContextVariables(JobExecutionContext context) {
SchedulerContext schedulerContext = null;
try {
schedulerContext = context.getScheduler().getContext();
} catch (SchedulerException e1) {
e1.printStackTrace();
}
this.monitorFolder = (String) schedulerContext.get("monitorFolder");
this.thresholdSize = (long) schedulerContext.get("monitorThreshold");
// this.archiveFolder = (String) schedulerContext.get("archiveFolder");
}
}
|
import static org.junit.Assert.*;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
*/
/**
* @author Bassem E-Hamed
* @version 3
*
*/
public class OverDueDAOTest {
private Connection myConn;
private int iSize =1;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
// get db properties
Properties props = new Properties();
props.load(new FileInputStream("demo.properties"));
String user = props.getProperty("user");
String password = props.getProperty("password");
String dburl = props.getProperty("dburl");
// connect to database
myConn = DriverManager.getConnection(dburl, user, password);
Statement myStmt = myConn.createStatement();
myStmt.executeUpdate("insert into borrow (return_date,borrow_date,member_id,book_id,status) value (" + "'2017-06-15'" + "," + "'2017-05-11'" + ",5,1,'A');");
}
/**
* @throws java.lang.Exception
*/
@Test
public void testSearchOverDueDAO() throws Exception {
try {
OverDueDAO overdue = new OverDueDAO();
List<OverDue> result = overdue.searchOverDue("test@test.com");
assertNotNull(result);
assertEquals(1, result.size());
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
@Test
public void testSearchOverDueDAOAll() throws Exception {
try {
OverDueDAO overdue = new OverDueDAO();
List<OverDue> result = overdue.getAllOverDue();
assertNotNull(result);
if (result.size() > 2){
iSize=result.size();
}
assertEquals(iSize, result.size());
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
@After
public void deleteTestRecord() throws Exception {
// get db properties
Properties props = new Properties();
props.load(new FileInputStream("demo.properties"));
String user = props.getProperty("user");
String password = props.getProperty("password");
String dburl = props.getProperty("dburl");
// connect to database
myConn = DriverManager.getConnection(dburl, user, password);
Statement myStmt = myConn.createStatement();
myStmt.executeUpdate("delete from borrow where member_id=5");
}
/**
* @param ok2
* @param overdue2
* @param c
*/
}
|
package com.fleet.mybatis.service;
import com.fleet.mybatis.entity.User;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
public interface UserService {
int insert(User user);
int delete(Long id);
int update(User user);
User get(Long id);
List<User> list(Map<String, Object> map);
}
|
package com.axess.smartbankapi.service.impl;
import java.time.LocalDate;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.axess.smartbankapi.dto.UserRedeemptionHistoryDto;
import com.axess.smartbankapi.exception.RecordExistException;
import com.axess.smartbankapi.exception.RecordNotCreatedException;
import com.axess.smartbankapi.exception.RecordNotFoundException;
import com.axess.smartbankapi.model.CCUser;
import com.axess.smartbankapi.model.UserRedeemptionHistory;
import com.axess.smartbankapi.repository.CCUserRepository;
import com.axess.smartbankapi.repository.RedeemptionHistoryRepository;
import com.axess.smartbankapi.service.RedeemptionHistoryService;
@Service
public class RedeemptionHistoryServiceImpl implements RedeemptionHistoryService {
@Autowired
private RedeemptionHistoryRepository historyRepo;
@Autowired
private CCUserRepository ccUserRepo;
@Override
public String saveHistory(UserRedeemptionHistoryDto historyDto) throws RecordExistException, RecordNotCreatedException {
String message ="Item saved in history";
CCUser user = ccUserRepo.findById(historyDto.getCcNumber()).get();
user.setAvailableRedeemPoints(user.getAvailableRedeemPoints() - historyDto.getTotalPointsRedeemed());
user.setTotalRewardsGained(historyDto.getTotalAmountGained());
ccUserRepo.save(user);
historyDto.getItemsRedeemed().forEach(item ->{
UserRedeemptionHistory historyData = new UserRedeemptionHistory();
historyData.setCatalogue(item);
historyData.setOrderdate(LocalDate.now());
historyData.setQuantity(historyDto.getQuantity());
historyData.setCcUser(user);
historyRepo.save(historyData);
});
return message;
}
@Override
public List<UserRedeemptionHistory> getAll() throws RecordNotFoundException {
return historyRepo.findAll();
}
@Override
public UserRedeemptionHistory getByUser(long id) throws RecordNotFoundException {
return null;
}
}
|
package com.sample.bootTest.main.controller;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SampleRepository extends JpaRepository<Sample, Long>{
public void deleteBySampleId(String sampleId);
}
|
package com.example.shedule.controller;
import com.example.shedule.domain.Shedule;
import com.example.shedule.service.SheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class SheduleController {
@Autowired
SheduleService service;
@RequestMapping(path = "/entity", method = RequestMethod.GET)
public ResponseEntity<List<Shedule>> getEntity(){
return new ResponseEntity(service.getShedule(), HttpStatus.OK);
}
}
|
package com.choa.book;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import com.choa.deal.DealDTO;
import com.choa.deposit.DepositDTO;
import com.choa.member.MemberDTO;
import com.choa.member.MemberLikeBooksDTO;
import com.choa.util.PageMaker;
@Service
public class BookService {
@Autowired
private BookDAO bookDAO;
public int insertBBB(DealDTO dealDTO)throws Exception{
return bookDAO.insertBBB(dealDTO);
}
public int addPointSuccessBuyer(int num)throws Exception{
return bookDAO.addPointSuccessBuyer(num);
}
public int addPointSuccessSeller(int num)throws Exception{
return bookDAO.addPointSuccessSeller(num);
}
//구매자가 책 확인하고 구매확정 누르면 책의 status 구매확정으로 바꾸기
public int confirm(int num)throws Exception{
return bookDAO.confirm(num);
}
public int depositSuccess(int num)throws Exception{
return bookDAO.depositSuccess(num);
}
//판매자가 택배 부치고나서 배송완료버튼 누르면 책의 status 배송중으로 바꾸기
public int delivery(int num)throws Exception{
return bookDAO.delivery(num);
}
//book의 status스 결제완료로 바꿔줄라고 만든 소스
public int statusDeposit(DepositDTO depositDTO)throws Exception{
System.out.println("북디에오에 디파짓에들어온다");
return bookDAO.statusDeposit(depositDTO);
}
//sellBookList에서 하트 검증용
public List<Integer> myHeart(String id, Model model)throws Exception{
List<Integer> heart = bookDAO.myHeart(id);
model.addAttribute("heart", heart);
model.addAttribute("heartSize", heart.size());
return heart;
}
//index에서 좋아요순으로 1~10 보여주기
public List<BookDTO> BookLikes(Model model)throws Exception{
List<BookDTO> ar = bookDAO.BookLikes();
model.addAttribute("bookLikes", ar);
model.addAttribute("count", 0);
model.addAttribute("listsize", ar.size());
return ar;
}
//search 했을때 list
public List<BookDTO> sellBookSearch(int curPage, int perPage, String search , Model model)throws Exception{
System.out.println("서비스의 서치 : " + search);
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
pageMaker.setSearch(search);
List<BookDTO> ar2 = bookDAO.sellBookSearch(pageMaker);
System.out.println("ar2.size : " + ar2.size());
model.addAttribute("count", 0);
model.addAttribute("list", ar2);
model.addAttribute("listsize", ar2.size());
model.addAttribute("paging", pageMaker);
model.addAttribute("check", true);
model.addAttribute("search", search);
return ar2;
}
//까망 하트 눌렀을때(mlb에 id랑 num으로 한줄 삽입 / book에 likes 하나 더하기)
public void changeLikesBlack(MemberLikeBooksDTO mlbDTO)throws Exception{
bookDAO.changeLikesAdd(mlbDTO.getNum());
bookDAO.insertMLB(mlbDTO);
}
//빨강 하트 눌렀을때(mlb에 id랑 num으로 한줄 삭제 / book에 likes 하나 빼기)
public void changeLikesRed(MemberLikeBooksDTO mlbDTO)throws Exception{
bookDAO.changeLikesDelete(mlbDTO.getNum());
bookDAO.deleteMLB(mlbDTO);
}
//판매도서등록
public int sellBookWrite(BookDTO bookDTO, BookPictureDTO bookPictureDTO, MultipartRequest mr,HttpSession session) throws Exception{
System.out.println(bookDTO.getId());
System.out.println(bookDTO.getProduct());
System.out.println(bookDTO.getPublisher());
System.out.println(bookDTO.getContents());
System.out.println(bookDTO.getPrice());
System.out.println(bookDTO.getBuy_date());
System.out.println(bookDTO.getK_id());
System.out.println(bookDTO.getLikes());
System.out.println(bookDTO.getPages());
System.out.println(bookDTO.getStatus());
System.out.println(bookDTO.getAuthor());
System.out.println(bookDTO.getSellingprice());
System.out.println(bookDTO.getQuality());
System.out.println(bookDTO.getGenre());
System.out.println(bookDTO.getBookdate());
System.out.println(bookPictureDTO.getFiles1());
System.out.println(bookPictureDTO.getNum());
System.out.println(bookDTO.getPictureNum());
String path = session.getServletContext().getRealPath("resources/upload");
List<MultipartFile> files = mr.getFiles("fileName1");
files.add(mr.getFile("fileName2"));
files.add(mr.getFile("fileName3"));
files.add(mr.getFile("fileName4"));
ArrayList<String> fileNames = new ArrayList<String>();
for(int i = 0; i<files.size(); i++){
MultipartFile mf = files.get(i);
String fileName = UUID.randomUUID().toString()+"_"+mf.getOriginalFilename();
File file = new File(path, fileName);
mf.transferTo(file);
fileNames.add(fileName);
}
return bookDAO.sellBookWrite(bookDTO, bookPictureDTO, fileNames);
}
public BookDTO sellBookView(int num, String id, Model model) throws Exception{
BookDTO bookDTO = bookDAO.sellBookView(num);
BookPictureDTO bookPictureDTO = bookDAO.sellBookPicture(num);
MemberDTO memberDTO = bookDAO.sellBookViewMember(id);
List<Integer> heartV = bookDAO.myHeart(id);
model.addAttribute("heartV", heartV);
model.addAttribute("view", bookDTO);
model.addAttribute("viewPicture", bookPictureDTO);
model.addAttribute("viewMember", memberDTO);
return bookDTO;
}
public List<BookDTO> sellBookList(int curPage, int perPage, Model model)throws Exception{
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
List<BookDTO> ar = bookDAO.sellBookList(pageMaker);
System.out.println("인덱스확인 : " + ar.size());
model.addAttribute("count", 0);
model.addAttribute("list", ar);
model.addAttribute("listsize", ar.size());
model.addAttribute("paging", pageMaker);
model.addAttribute("check", true);
return ar;
}
public List<BookDTO> sellBookList2(int curPage, int perPage, Model model)throws Exception{
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
List<BookDTO> ar = bookDAO.sellBookList2(pageMaker);
model.addAttribute("count", 0);
model.addAttribute("list2", ar);
model.addAttribute("listsize2", ar.size());
model.addAttribute("paging2", pageMaker);
model.addAttribute("check2", true);
return ar;
}
public List<BookDTO> sellBookList3(int curPage, int perPage, Model model)throws Exception{
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
List<BookDTO> ar = bookDAO.sellBookList3(pageMaker);
model.addAttribute("count", 0);
model.addAttribute("list3", ar);
model.addAttribute("listsize3", ar.size());
model.addAttribute("paging3", pageMaker);
model.addAttribute("check3", true);
return ar;
}
public List<BookDTO> sellBookList4(int curPage, int perPage, Model model)throws Exception{
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
List<BookDTO> ar = bookDAO.sellBookList4(pageMaker);
model.addAttribute("count", 0);
model.addAttribute("list4", ar);
model.addAttribute("listsize4", ar.size());
model.addAttribute("paging4", pageMaker);
model.addAttribute("check4", true);
return ar;
}
public List<BookDTO> sellBookList5(int curPage, int perPage, Model model)throws Exception{
int totalCount = bookDAO.bookCount();
PageMaker pageMaker = new PageMaker();
pageMaker.setCurPage(curPage);
pageMaker.setPerPage(perPage);
pageMaker.makeRow();//startRow & lastRow
pageMaker.makePage(totalCount);
List<BookDTO> ar = bookDAO.sellBookList5(pageMaker);
model.addAttribute("count", 0);
model.addAttribute("list5", ar);
model.addAttribute("listsize5", ar.size());
model.addAttribute("paging5", pageMaker);
model.addAttribute("check5", true);
return ar;
}
public List<BookDTO> myBookList(String id, Model model)throws Exception{
List<BookDTO> ar = bookDAO.myBookList(id);
model.addAttribute("booklist", ar);
return ar;
}
public List<BookDTO> mySellList(String id, Model model)throws Exception{
List<BookDTO> ar = bookDAO.mySellList(id);
model.addAttribute("sell", ar);
return ar;
}
public List<BookDTO> myBuyList(String id, Model model)throws Exception{
List<BookDTO> ar = bookDAO.myBuyList(id);
model.addAttribute("buylist", ar);
return ar;
}
//구매
public List<BookDTO> deposit(DepositDTO depositDTO, Model model)throws Exception{
BookPictureDTO bookPictureDTO = bookDAO.sellBookPicture(depositDTO.getNum());
List<BookDTO> ar = bookDAO.deposit(depositDTO.getId());
BookDTO bookDTO = bookDAO.sellBookView(depositDTO.getNum());
model.addAttribute("viewPicture", bookPictureDTO);
model.addAttribute("view", bookDTO);
model.addAttribute("deposit", ar);
return ar;
}
}
|
package com.google.android.exoplayer2.metadata.id3;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.google.android.exoplayer2.i.t;
import java.util.Arrays;
public final class ChapterFrame extends Id3Frame {
public static final Creator<ChapterFrame> CREATOR = new 1();
public final String aqG;
public final int aqH;
public final int aqI;
public final long aqJ;
public final long aqK;
private final Id3Frame[] aqL;
public ChapterFrame(String str, int i, int i2, long j, long j2, Id3Frame[] id3FrameArr) {
super("CHAP");
this.aqG = str;
this.aqH = i;
this.aqI = i2;
this.aqJ = j;
this.aqK = j2;
this.aqL = id3FrameArr;
}
ChapterFrame(Parcel parcel) {
super("CHAP");
this.aqG = parcel.readString();
this.aqH = parcel.readInt();
this.aqI = parcel.readInt();
this.aqJ = parcel.readLong();
this.aqK = parcel.readLong();
int readInt = parcel.readInt();
this.aqL = new Id3Frame[readInt];
for (int i = 0; i < readInt; i++) {
this.aqL[i] = (Id3Frame) parcel.readParcelable(Id3Frame.class.getClassLoader());
}
}
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ChapterFrame chapterFrame = (ChapterFrame) obj;
if (this.aqH == chapterFrame.aqH && this.aqI == chapterFrame.aqI && this.aqJ == chapterFrame.aqJ && this.aqK == chapterFrame.aqK && t.i(this.aqG, chapterFrame.aqG) && Arrays.equals(this.aqL, chapterFrame.aqL)) {
return true;
}
return false;
}
public final int hashCode() {
return (this.aqG != null ? this.aqG.hashCode() : 0) + ((((((((this.aqH + 527) * 31) + this.aqI) * 31) + ((int) this.aqJ)) * 31) + ((int) this.aqK)) * 31);
}
public final void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.aqG);
parcel.writeInt(this.aqH);
parcel.writeInt(this.aqI);
parcel.writeLong(this.aqJ);
parcel.writeLong(this.aqK);
parcel.writeInt(this.aqL.length);
for (Parcelable writeParcelable : this.aqL) {
parcel.writeParcelable(writeParcelable, 0);
}
}
public final int describeContents() {
return 0;
}
}
|
package br.com.teste.agenda.controller.query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import br.com.teste.agenda.dto.query.ContatoQueryDto;
import br.com.teste.agenda.service.query.IContatoQueryService;
@SpringBootTest
@ExtendWith(MockitoExtension.class)public class ContatoQueryControllerTest {
@InjectMocks
ContatoQueryRestController contatoQueryRestController;
@Mock
private IContatoQueryService contatoService;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
@Test
public void getAllContatos() {
MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
when(contatoService.getContatos()).thenReturn(criarMockList());
List<ContatoQueryDto> contatos = contatoQueryRestController.getAllContatos();
assertThat(contatos.size()).isEqualTo(3);
}
private List<ContatoQueryDto> criarMockList() {
List<ContatoQueryDto> contatos = new ArrayList<ContatoQueryDto>();
ContatoQueryDto contato = new ContatoQueryDto();
contato.setNome("Joao Vitor da Silva");
contato.setCpf("474.828.440-40");
contato.setDataNascimento(obterObjetoDataNascimento("15/05/1983"));
contatos.add(contato);
contato = new ContatoQueryDto();
contato.setNome("Rafaela Ribeiro");
contato.setCpf("589.555.980-21");
contato.setDataNascimento(obterObjetoDataNascimento("17/02/1990"));
contatos.add(contato);
contato = new ContatoQueryDto();
contato.setNome("Roberto Alves");
contato.setCpf("149.291.771-18");
contato.setDataNascimento(obterObjetoDataNascimento("17/03/1981"));
contatos.add(contato);
return contatos;
}
private Date obterObjetoDataNascimento(String dataNascimentoStr) {
try {
return df.parse(dataNascimentoStr);
} catch (ParseException e) {
return new Date();
}
}
}
|
package LeetCode.Trees;
import java.util.LinkedList;
import java.util.Queue;
public class NoOfIslands {
public void dfs(char[][] grid, int r, int c) {
int nr = grid.length;
int nc = grid[0].length;
if(r < 0 || c < 0 || r > nr-1 || c > nc -1 || grid[r][c] == '0') {
return;
}
grid[r][c] = '0';
dfs(grid, r-1, c);
dfs(grid, r+1, c);
dfs(grid, r, c-1);
dfs(grid, r, c+1);
}
// DFS approach
public int numIslands(char[][] grid) {
if(grid.length == 0) return 0;
int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
for(int i = 0; i < nr; i++) {
for(int j = 0; j < nc; j++) {
if(grid[i][j] == '1') {
++num_islands;
dfs(grid, i, j);
}
}
}
return num_islands;
}
// BFS approach
public int numIslandsBFS(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
for(int i = 0; i < nr; i++) {
for(int j = 0; j < nc; j++) {
if(grid[i][j] == '1') {
++num_islands;
grid[i][j] = '0';
Queue<Integer> q = new LinkedList<>();
q.add(i * nc + j);
while (!q.isEmpty()) {
int k = q.poll();
int r = k/nc;
int c = k%nc;
if(r-1 >= 0 && grid[r-1][c] == '1') {
q.add((r-1) * nc + c);
grid[r-1][c] = '0';
}
if(r+1 < nr && grid[r+1][c] == '1') {
q.add((r+1) * nc + c);
grid[r+1][c] = '0';
}
if(c-1 >= 0 && grid[r][c-1] == '1') {
q.add(r * nc + (c-1));
grid[r][c-1] = '0';
}
if(c+1 < nc && grid[r][c=1] == '1') {
q.add(r * nc + (c+1));
grid[r][c+1] = '0';
}
}
}
}
}
return num_islands;
}
public static void main(String[] args) {
char[][] a = {{'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'},{'0','0','0','1','1'}};
char[][] b = {{'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'},{'0','0','0','1','1'}};
NoOfIslands n = new NoOfIslands();
System.out.println(n.numIslands(a));
System.out.println(n.numIslandsBFS(b));
}
}
|
/**
* @Title: Teacher.java
* @Package com.wonders.task.sample.bo
* @Description: TODO(用一句话描述该文件做什么)
* @author zhoushun
* @date 2014年4月1日 上午9:08:19
* @version V1.0
*/
package com.wonders.task.sample.bo;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
/**
* @ClassName: Teacher
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2014年4月1日 上午9:08:19
*
*/
@Entity
@Table(name="Z_TEACHER")
public class Teacher {
private String id;
private String name;
private Clazz clazz;
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "NAME", length = 500)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name="class_id")
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
}
|
package com.charith.hackerrank.GreedyAlgorithms.MinimumAbsoluteDifferenceInAnArray;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void minimumAbsoluteDifference() {
Assertions.assertEquals(3, Solution.minimumAbsoluteDifference(new int[]{3, -7, 0}));
Assertions.assertEquals(1, Solution.minimumAbsoluteDifference(new int[]{-59, -36, -13, 1, -53, -92, -2, -96, -54, 75}));
Assertions.assertEquals(3, Solution.minimumAbsoluteDifference(new int[]{1, -3, 71, 68, 17}));
}
}
|
package Algorithm;
public class a221 {
public int maximalSquare(char[][] matrix) {
if (matrix==null||matrix.length==0)return 0;
int[][] square=new int[matrix.length][matrix[0].length];
int res=0;
for (int j=0;j<matrix[0].length;j++){
square[0][j]=matrix[0][j]-'0';
if (matrix[0][j]=='1')res=1;
}
for (int i=1;i<matrix.length;i++){
for (int j=0;j<matrix[0].length;j++){
if (matrix[i][j]=='1'){
if (j==0){
square[i][0]=1;
}else {
square[i][j]=Math.min(square[i][j-1],Math.min(square[i-1][j],square[i-1][j-1]))+1;
}
res=Math.max(res,square[i][j]);
}
}
}
return res*res;
}
public static void main(String[] args) {
char[][] matrix={{'0'},{'1'}};
System.out.println(new a221().maximalSquare(matrix));
}
}
|
package com.datatypes;
public class AreaOfTriangleDemo {
public static void main(String args[]) {
//variable Declaration
float Base = 10.5f;
float Height = 20.3f;
//Temp Variable
float AreaOfTriangle = (Height * Base) / 2;
System.out.println("Area Of Triangle is : " + AreaOfTriangle);
}
}
|
import org.junit.*;
import static org.junit.Assert.*;
public class ScrabbleTest{
@Test
public void calculateScore_returnScoreForSingleLetter_1(){
Scrabble testScrabble = new Scrabble();
Integer expected = 1;
assertEquals(expected, testScrabble.calculateScore("a"));
}
@Test
public void calculateScore_returnScoreForTwoLetters_2(){
Scrabble testScrabble = new Scrabble();
Integer expected = 2;
assertEquals(expected, testScrabble.calculateScore("ae"));
}
@Test
public void calculateScore_returnScoreForThreeLetters_12(){
Scrabble testScrabble = new Scrabble();
Integer expected = 12;
assertEquals(expected, testScrabble.calculateScore("aez"));
}
}
|
/*
* Copyright 2017 Sanjin Sehic
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package simple.actor.testing;
import org.junit.runner.RunWith;
import alioli.Scenario;
import simple.actor.Actor;
import static com.google.common.truth.Truth.assertThat;
/** Tests for {@link SpyContext}. */
@RunWith(Scenario.Runner.class)
public class SpyContextTest extends Scenario {
{
subject("spy context", () -> {
final SpyContext context = new SpyContext();
should("have no registered actors", () -> {
assertThat(context.getRegisteredActors()).isEmpty();
});
when("actor is registered", () -> {
final Actor<Object> actor = new SpyActor<>();
context.register(actor);
should("remember it", () -> {
assertThat(context.getRegisteredActors()).containsExactly(actor);
});
});
});
}
}
|
package day44_exceptions;
public class TryCatch {
public static void main(String[] args) {
try {
String str= "Java";
System.out.println(str.charAt(0));
System.out.println(str.charAt(5)); // wont stop here it directly jump to catch and execute there then go to next line
System.out.println(str.charAt(1));
}catch(Exception e) {
System.out.println("Exception happened in try block and was cought");
}
System.out.println("After try catch block");
}
}
|
package com.travel.services;
import com.travel.models.Role;
import com.travel.models.User;
import com.travel.repositories.RoleRepository;
import com.travel.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public void save(User user) {
HashSet<Role> participantRoles = new HashSet<>(roleRepository.findByName("PARTICIPANT"));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(participantRoles);
userRepository.save(user);
}
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public Set<User> findByRole(String roleName) {
List<Role> roles = roleRepository.findByName(roleName);
if (roles.size() == 0) {
return new HashSet<User>();
}
return roles.get(0).getUsers();
}
@Override
public User findById(Long userId) {
Optional<User> user = userRepository.findById(userId);
if (user.isPresent()) {
return user.get();
}
return null;
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public void deleteById(Long userId) {
userRepository.deleteById(userId);
}
@Override
public Boolean hasRole(User user, String roleName) {
Set<Role> roles = user.getRoles();
Boolean hasRole = false;
for (Role role: roles) {
System.out.println(role.getName());
if (role.getName().equals(roleName)) {
hasRole = true;
}
}
return hasRole;
}
@Override
public void addRole(User user, String roleName) {
Set<Role> roles = user.getRoles();
Role role = roleRepository.findByName("ORGANIZER").get(0);
roles.add(role);
userRepository.save(user);
}
@Override
public void removeRole(User user, String roleName) {
Set<Role> roles = user.getRoles();
Role role = roleRepository.findByName("ORGANIZER").get(0);
roles.remove(role);
userRepository.save(user);
}
}
|
package org.zxd.spring.boot.mail;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
/**
* @ProjectName:SpringBootInAction
* @PackageName:org.zxd.spring.boot.mail
* @FileName:MailController.java
* @author:ZXD
* @version 1.0
* @time:14 Sep 201722:21:36
* @since Jdk1.8
*/
@Api(value = "发送邮件相关接口")
@Controller
@RequestMapping("/mail")
@Slf4j
public class MailController {
/**
* @time:14 Sep 201721:59:20
*
* @desc:MAIL_TARGET 邮件收件人
*/
private static final String MAIL_TARGET = "15505883728@163.com";
@Resource(name = MailConfig.JAVA_MAIL_SENDER)
private JavaMailSenderImpl mailSender;
public void setMailSender(JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}
/**
* @author:ZXD
* @version:1.0
* @time:14 Sep 201721:56:02
* @desc:发送简单的文本邮件
* @since Jdk1.8
*/
@GetMapping("/simple")
public void sendSimpleMail() {
final SimpleMailMessage mailMessage = new SimpleMailMessage();
/**
* 邮件发件人
*/
mailMessage.setFrom(mailSender.getUsername());
/**
* 邮件收件人
*/
mailMessage.setTo(MailController.MAIL_TARGET);
/**
* 邮件抄送人
*/
mailMessage.setCc(MailController.MAIL_TARGET);
/**
* 邮件私密抄送人
*/
mailMessage.setBcc(MailController.MAIL_TARGET);
/**
* 发送时间
*/
mailMessage.setSentDate(new Date());
/**
* 邮件主题
*/
mailMessage.setSubject("spring mail test");
/**
* 邮件正文
*/
mailMessage.setText("a simple mail test from spring boot!");
/**
* 通过 JavaMailSenderImpl 发送邮件
*/
mailSender.send(mailMessage);
MailController.log.info("simple mail send successfully!");
}
/**
* @throws MessagingException
* @author:ZXD
* @version:1.0
* @time:14 Sep 201721:56:51
* @desc:发送带附件的邮件
* @since Jdk1.8
*/
@GetMapping("/attach")
public void sendAttach() throws MessagingException {
/**
* 创建复杂格式邮件
*/
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final boolean multipart = true;
/**
* 基于 MimeMessage 创建 MimeMessageHelper,并指定这是一个 multipart 邮件。
*/
final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, multipart);
messageHelper.setFrom(mailSender.getUsername());
messageHelper.setTo(MailController.MAIL_TARGET);
messageHelper.setSentDate(new Date());
messageHelper.setSubject("mail with attachment");
messageHelper.setText("mail with attachment");
/**
* 从类路径下获取资源
*/
final ClassPathResource resource = new ClassPathResource("mail/sockjs.min.js");
/**
* 设置文件名并添加资源
*/
messageHelper.addAttachment("sockjs.min.js", resource);
mailSender.send(mimeMessage);
}
/**
* @throws MessagingException
* @author:ZXD
* @version:1.0
* @time:14 Sep 201722:08:04
* @desc:发送 html 格式的富文本邮件
* @since Jdk1.8
*/
@GetMapping("/richText")
public void sendRichText() throws MessagingException {
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(mailSender.getUsername());
messageHelper.setTo(MailController.MAIL_TARGET);
messageHelper.setSentDate(new Date());
messageHelper.setSubject("rich text mail");
/**
* 基于 html 格式的富文本,嵌入文件需要使用 cid:contentId 的格式,并通过 contentId 关联实际的资源。
*/
final String richText = "<body><h3>Rich Text Email</h3></br><img src='cid:fire'/></body>";
/**
* 正文启用 html 格式
*/
final boolean html = true;
messageHelper.setText(richText, html);
/**
* 读取类路径下的资源文件
*/
final ClassPathResource resource = new ClassPathResource("mail/fire.jpg");
/**
* 设置内联资源,通过 contentId 标识。
*/
messageHelper.addInline("fire", resource);
mailSender.send(mimeMessage);
}
@Resource(name = MailConfig.VELOCITY_ENGINE)
private VelocityEngine velocityEngine;
/**
* @throws MessagingException
* @author:ZXD
* @version:1.0
* @time:14 Sep 201722:21:44
* @desc:基于 velocity 模板定义邮件正文
* @since Jdk1.8
*/
@GetMapping("/template")
public void sendTemplate() throws MessagingException {
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(mailSender.getUsername());
messageHelper.setTo(MailController.MAIL_TARGET);
messageHelper.setSentDate(new Date());
messageHelper.setSubject("velocity template mail");
final Map<String, Object> params = new HashMap<>();
/**
* 添加参数映射
*/
params.put("user", "kristy");
params.put("content", "velocity template mail from spring boot");
/**
* 模板路径
*/
final String templateLocation = "mail/mailTemplate.vm";
/**
* 文本编码
*/
final String encoding = StandardCharsets.UTF_8.name();
/**
* 通过模板引擎合并模板和参数映射,生成文本字符串。
*/
final String finalText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, encoding,
params);
messageHelper.setText(finalText, true);
/**
* 读取类路径下的资源文件
*/
final ClassPathResource resource = new ClassPathResource("mail/fire.jpg");
/**
* 设置内联资源,通过 contentId 标识。
*/
messageHelper.addInline("fire", resource);
mailSender.send(mimeMessage);
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
}
|
package com.tt.miniapp.component.nativeview;
public class Position {
public int height;
public boolean isFixed;
public int width;
public int x;
public int y;
public Position() {}
public Position(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
this.x = paramInt1;
this.y = paramInt2;
this.width = paramInt3;
this.height = paramInt4;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\component\nativeview\Position.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package structural.decorator;
import java.util.function.Supplier;
class Circle2 implements Shape{
private float radius;
public Circle2(){
}
public Circle2(float radius) {
this.radius = radius;
}
void resize(float factor){
radius *= factor;
}
@Override
public String info() {
return "A circle of radius " + radius;
}
}
class Square2 implements Shape{
private float side;
public Square2(){
}
public Square2(float side) {
this.side = side;
}
@Override
public String info() {
return null;
}
}
class TransparentShape2<T extends Shape> implements Shape{
private Shape shape;
private int transparency;
public TransparentShape2(Supplier<? extends T> ctor, int transparency) {
shape = ctor.get();
this.transparency = transparency;
}
@Override
public String info() {
return shape.info() + " has "
+ transparency + "% transparency";
}
}
class ColoredShape2<T extends Shape> implements Shape{
private Shape shape;
private String color;
public ColoredShape2(Supplier<? extends T> ctor, String color){
shape = ctor.get();
this.color = color;
}
@Override
public String info() {
return shape.info() + " has the color " + color;
}
}
public class StaticDecorator {
public static void main(String[] args){
ColoredShape2<Square> blueSquare =
new ColoredShape2<>(
() -> new Square(20),
"blue"
);
System.out.println(blueSquare.info());
TransparentShape2<ColoredShape2<Circle>> myCircle =
new TransparentShape2<>(
() -> new ColoredShape2<>(() -> new Circle(5), "green"), 50
);
System.out.println(myCircle.info());
}
}
|
package com.qimou.sb.web.tool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.springframework.stereotype.Component;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import com.google.gson.Gson;
import com.qimou.sb.web.entity.Policy;
//@Component
public class JsonUtil {
public static void main(String[] args) {
/*String reqBody="{\"parkID\":\"shicheng1\",\"title\":\"title0.13708906058025083\"}";
Policy policy = (Policy) js.jsonStr2Bean(reqBody, Policy.class);
System.out.println(policy);
reqBody="[{\"parkID\":\"shicheng1\",\"title\":\"title0.13708906058025083\"},{\"parkID\":\"shicheng2\",\"title\":\"title0.13708906058025083\"}]";
Object o = js.jsonStr2Beans(reqBody,Policy.class);
System.out.println("s:"+o.toString());
reqBody="[{\"taskID\": \"101\",\"userID\": \"haom\"}]";
o = js.jsonStr2Beans(reqBody,Map.class);
System.out.println("s:"+o.toString());*/
/*policy = new Policy();
policy.setParkID("shicheng1");
policy.setTitle("title"+Math.random());
policy.setPolicyStr("policyStr"+Math.random());
policy.setPolicyID(UUID.randomUUID().toString());
List<Object> filterList = new ArrayList<Object>();
filterList.add("parkID");
System.out.println(js.bean2JsonStr(policy, filterList));
System.out.println(js.bean2JsonStr(policy, null));
JSONObject jsonObject = js.bean2JsonObj(policy);
System.out.println(jsonObject.get("parkID"));
Map<Object, Object> map = js.jsonStr2Map(reqBody);
System.out.println(map.entrySet().toString());
System.out.println(js.map2JsonStr(map));
Set<Object> set = new HashSet<Object>();
set.add(policy);
policy = new Policy();
policy.setParkID("shicheng1");
policy.setTitle("title"+Math.random());
policy.setPolicyStr("policyStr"+Math.random());
policy.setPolicyID(UUID.randomUUID().toString());
set.add(policy);
System.out.println(js.set2JsonStr(set));
List<Policy> list = new ArrayList<Policy>();
list.add(policy);
list.add(policy);
System.out.println(js.list2JsonStr(list));
System.out.println("generalMixJson : "+js.generalMixJson(list,map,"listStr"));*/
/*Map<Object, Object> map = new HashMap<Object, Object>();
map.put("serviceID", "1");
map.put("cityCode","1");
map.put("serviceCode","1");
map.put("serviceName","服务名称");
map.put("serviceBak","递交专利");
map.put("serviceType", "12");
map.put("priceNumMin",123);
map.put("priceNumMax",456);
System.out.println(js.map2JsonStr(map));*/
/*String s= "serviceBak=";
String[] split = s.split("=");
System.out.println(split.length);
System.out.println(split[0]);
System.out.println(split.length==1?"hhh":split[1]);*/
String str = "{check:{enable: true},data:{simpleData:{enable:true}},callback:{onCheck:\"onCheck\"}}";
System.out.println(str);
System.out.println(JSONObject.fromObject(str));
}
public static String generalMixJson(List<?> list,Map<Object,Object> map,String listName){
String json = map2JsonStr(map);
json = json.replace("}", ",");
json += "\""+listName+"\":"+list2JsonStr(list);
json += "}";
return json;
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:46:26
* @Return_type:Object
* @Desc :json字符串转javabean
*/
public static Object jsonStr2Bean(String jsonStr,Class<?> beanClass) {
/*if (jsonStr.indexOf("[") != -1) {
jsonStr = jsonStr.replace("[", "");
}
if (jsonStr.indexOf("]") != -1) {
jsonStr = jsonStr.replace("]", "");
}*/
JSONObject obj = JSONObject.fromObject(jsonStr);
return JSONObject.toBean(obj,beanClass);
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:patent
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-27 下午12:15:00
* @Return_type:Object
* @Desc :
*/
public static List<Object> jsonStr2Beans(String jsonStr,Class<?> beanClass) {
if (jsonStr.indexOf("[") == -1 || jsonStr.indexOf("]") == -1) {
return null;
}
List<Object> returnList = new ArrayList<Object>();
JSONArray jsonAarry = JSONArray.fromObject(jsonStr);
for (int i = 0; i < jsonAarry.size(); i++) {
JSONObject obj = JSONObject.fromObject(jsonAarry.get(i));
returnList.add(JSONObject.toBean(obj,beanClass));
}
return returnList;
}
public static JSONObject bean2JsonObj(Object vo){
return JSONObject.fromObject(vo);
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:46:52
* @Return_type:String
* @Desc :带过滤字段的beanToJson方法:javabean转json字符串
*/
public static String bean2JsonStr(Object vo,final List<?> filterList) {
String returnStr="";
if(filterList != null){
JsonConfig jsonConfig=new JsonConfig();
PropertyFilter filter = new PropertyFilter() {
public boolean apply(Object arg0, String arg1, Object arg2) {
// Object o String fieldName Stirng fieldValue
if(filterList.contains(arg1)){
return true;
}else{
return false;
}
}
};
jsonConfig.setJsonPropertyFilter(filter);
returnStr = JSONObject.fromObject(vo, jsonConfig).toString();
}else{
// returnStr = JSONObject.fromObject(vo).toString();
JSONObject json = JSONObject.fromObject(vo);//将java对象转换为json对象
returnStr = json.toString();//将json对象转换为字符串
}
return returnStr;
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:47:15
* @Return_type:String
* @Desc :map对象转json字符串
*/
public static String map2JsonStr(Map<?,?> map){
if(map.isEmpty()){
return "";
}
return JSONObject.fromObject(map).toString();
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:47:37
* @Return_type:Map<Object,Object>
* @Desc :json字符串转map对象
*/
public static Map<Object,Object> jsonStr2Map(String jsonString) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Iterator<?> keyIter = jsonObject.keys();
String key;
Object value;
Map<Object,Object> returnMap = new HashMap<Object, Object>();
while (keyIter.hasNext()) {
key = (String) keyIter.next();
value = jsonObject.get(key);
returnMap.put(key, value);
}
return returnMap;
}
/**
*
* @author : haoming
* @date : 2018年8月14日上午8:58:36
* @patent com.qimou.sb.web.tool.JsonUtil.java.url2Map
* @returnType : Map<Object,Object>
* @desc :currentPage=1&serviceType=-1&serviceCode= 转 map
*/
public static Map<Object,Object> url2Map(String urlString,String regex) {
Map<Object,Object> returnMap = new HashMap<Object, Object>();
String[] split = urlString.split(regex);
for (String item:split) {
String[] it = item.split("=");
returnMap.put(it[0], it.length==1?"":it[1]);
}
return returnMap;
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:47:51
* @Return_type:String
* @Desc :list对象转json字符串
*/
public static String list2JsonStr(List<?> list){
return new Gson().toJson(list);
}
/**
*
* @Author:HaoMing(郝明)
* @Project_name:mavenWebProj
* @Full_path:com.qimou.sb.web.tool.JsonUtil.java
* @Date:@2018 2018-7-20 下午1:48:14
* @Return_type:String
* @Desc :set对象转json字符串
*/
public static String set2JsonStr(Set<?> set){
return new Gson().toJson(set);
}
}
|
public class ArrayExample
{
public static void main(String[] args)
{
int arrays[] = {2,5,1,3,4};
int temp;
if(arrays[0] > arrays[1])//ตฺาปฬหลละ๒
{
temp = arrays[0];
arrays[0] = arrays[1];
arrays[1] = temp;
}
if(arrays[1]>arrays[2])
{
temp = arrays[1];
arrays[1] = arrays[2];
arrays[2] = temp;
}
if(arrays[2]>arrays[3])
{
temp = arrays[2];
arrays[2] = arrays[3];
arrays[3] = temp;
}
if(arrays[3]>arrays[4])
{
temp = arrays[3];
arrays[3] = arrays[4];
arrays[4] = temp;
}
for(int i:arrays)
{
System.out.println(i);
}
}
}
|
package com.tt.miniapp.suffixmeta;
import android.text.TextUtils;
import com.tt.miniapp.service.suffixmeta.SuffixMetaEntity;
import com.tt.miniapphost.AppBrandLogger;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SuffixMetaParser {
private static List<String> jsonArray2StringList(JSONArray paramJSONArray) {
ArrayList<String> arrayList = new ArrayList();
if (paramJSONArray == null)
return arrayList;
try {
int j = paramJSONArray.length();
for (int i = 0; i < j; i++) {
String str = paramJSONArray.optString(i);
if (!TextUtils.isEmpty(str))
arrayList.add(str);
}
} catch (Exception exception) {
AppBrandLogger.e("SuffixMetaParser", new Object[] { exception });
}
return arrayList;
}
public static SuffixMetaEntity parse(String paramString) {
try {
return parse(new JSONObject(paramString));
} catch (JSONException jSONException) {
AppBrandLogger.e("SuffixMetaParser", new Object[] { jSONException });
return null;
}
}
public static SuffixMetaEntity parse(JSONObject paramJSONObject) {
String str = paramJSONObject.optString("shield_page");
List<String> list = jsonArray2StringList(paramJSONObject.optJSONArray("shareChannelBlackList"));
SuffixMetaEntity suffixMetaEntity = new SuffixMetaEntity();
suffixMetaEntity.shieldPage = str;
suffixMetaEntity.shareChannelBlackList = list;
suffixMetaEntity.mNativeOrH5 = paramJSONObject.optInt("nativeOrH5", -2147483648);
suffixMetaEntity.isNew = paramJSONObject.optInt("is_new", 0);
suffixMetaEntity.mLivePlayNativeOrH5 = paramJSONObject.optInt("liveNativeOrH5", -2147483648);
suffixMetaEntity.awemeUserId = paramJSONObject.optString("aweme_user_id");
suffixMetaEntity.awemeSecUserId = paramJSONObject.optString("aweme_sec_user_id");
return suffixMetaEntity;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\suffixmeta\SuffixMetaParser.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.zero.b;
import com.tencent.mm.k.c;
import com.tencent.mm.k.e;
public interface a extends com.tencent.mm.kernel.c.a {
e AT();
c AU();
}
|
package com.suirui.drouter.login.application;
import com.suirui.drouter.login.BuildConfig;
import org.suirui.drouter.common.app.BaseCommonApplication;
public class LoginApplication extends BaseCommonApplication {
@Override
public void onCreate() {
super.onCreate();
// DRouter.openDebug();
// DRouter.getInstance().init(this);
initRouterAndModule();
}
}
|
package one.kii.summer.asdf.api;
import one.kii.summer.io.context.ReadContext;
public interface SimpleSearchApi<R, F> extends SearchApi<R, ReadContext, F> {
}
|
import java.util.Scanner;
public class String_token{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
String arr[]=str.split(" ");
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.business.api.system;
import seava.ad.domain.impl.system.FrameExtension;
import seava.j4e.api.service.business.IEntityService;
/**
* Interface to expose business functions specific for {@link FrameExtension} domain
* entity.
*/
public interface IFrameExtensionService extends IEntityService<FrameExtension> {
/**
* Find by unique key
*/
public FrameExtension findByName(String frame, String fileLocation);
}
|
package arrays.module;
import java.util.Arrays;
import java.util.*;
public class DuringTheWeek {
// reference arrayy
public static void main(String[] args) {
int[] option = {1,2,3},
my = option,
yours = my;
String m = "Shopping,Buying,Selling";
String[] menu = new String[option.length];
int count = 0;
for(String item: m.split(",") ){
System.out.println(m.split(",")[count]);
count++;
}
System.out.println("Value from my "+ Arrays.toString(my)+"\n value from your "+Arrays.toString(yours));
yours[2] = 233;
collection(option);
System.out.println("Value from my "+ Arrays.toString(my)+"\n value from your "+Arrays.toString(yours));
}
private static int[] collection(int[] array){
array[1] = 33;
array[0] = 3211;
return array;
}
}
|
package com.acmicpc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
ACMICPC
문제 번호 : 17143
문제 제목 : 낚시왕
풀이 날짜 : 2020-11-06
Solved By Reamer
*/
public class acm_17143 {
static int[] dx = { 0, -1, 1, 0, 0 };
static int[] dy = { 0, 0, 0, 1, -1 };
private static Shark[][] sharkMap;
private static int R, C, M;
private static int answer;
private static Shark[][] tmpSharkMap;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
sharkMap = new Shark[R][C];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
int s = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int z = Integer.parseInt(st.nextToken());
sharkMap[r - 1][c - 1] = new Shark(s, d, z);
}
if (M != 0)
fishing(-1, 0);
System.out.println(answer);
}
private static void fishing(int fisher, int sumShark) {
// 1. 오른쪽이동
fisher++;
if (fisher == C) {
answer = sumShark;
return;
}
// 2. 제일 낮은 행 잡기
for (int i = 0; i < R; i++) {
if (sharkMap[i][fisher] != null) {
sumShark += sharkMap[i][fisher].size;
sharkMap[i][fisher] = null;
break;
}
}
// 3. 상어 이동
tmpSharkMap = new Shark[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
Shark s = sharkMap[i][j];
if (s != null) {
int xSpeed = s.speed % ((R - 1) * 2);
int ySpeed = s.speed % ((C - 1) * 2);
int newX = i + dx[s.dir] * xSpeed;
int newY = j + dy[s.dir] * ySpeed;
if (newX < 0) {
newX = Math.abs(newX);
int even = newX / (R - 1);
int idx = newX % (R - 1);
if (even > 0) {
if (idx == 0)
s.dir = 2;
newX = R - 1 - idx;
} else {
s.dir = 2;
newX = idx;
}
} else if (newX >= R) {
int even = newX / (R - 1);
int idx = newX % (R - 1);
if (even == 2) {
if (idx == 0)
s.dir = 1;
newX = idx;
} else {
s.dir = 1;
newX = R - 1 - idx;
}
} else if (newY < 0) {
newY = Math.abs(newY);
int even = newY / (C - 1);
int idx = newY % (C - 1);
if (even > 0) {
if (idx == 0)
s.dir = 3;
newY = C - 1 - idx;
} else {
s.dir = 3;
newY = idx;
}
} else if (newY >= C) {
int even = newY / (C - 1);
int idx = newY % (C - 1);
if (even == 2) {
if (idx == 0)
s.dir = 4;
newY = idx;
} else {
s.dir = 4;
newY = C - 1 - idx;
}
}
if (tmpSharkMap[newX][newY] != null && tmpSharkMap[newX][newY].size > s.size) {
continue;
}
tmpSharkMap[newX][newY] = s;
}
}
}
// 복사
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
sharkMap[i][j] = tmpSharkMap[i][j];
}
}
// 다음 호출
fishing(fisher, sumShark);
}
static class Shark {
int speed, dir, size;
public Shark(int speed, int dir, int size) {
super();
this.speed = speed;
this.dir = dir;
this.size = size;
}
}
}
|
package com.guli.acl.untils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.acl.entity.Permission;
import org.springframework.stereotype.Component;
import java.security.Permissions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class BuildUntils {
public static Map<String,Object> buildPermission(List<Permission> permissions){
List<Permission> firstNode=new ArrayList<>();
Map<String,Object> map = new HashMap<>();
for (Permission permission : permissions) {
if ("0".equals(permission.getPid())) {
permission.setLevel(1);
map.put(permission.getName(),getChildren(permission,permissions));
}
}
return map;
}
public static Permission getChildren(Permission firstNode, List<Permission> permissions){
firstNode.setChildren(new ArrayList<>());
permissions.forEach(p -> {
if (firstNode.getId().equals(p.getPid())) {
int level=firstNode.getLevel()+1;
p.setLevel(level);
firstNode.getChildren().add(getChildren(p,permissions));
}
});
return firstNode;
}
}
|
package com.csc214.rebeccavandyke.socialnetworkingproject2;
import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
/*
* Rebecca Van Dyke
* rvandyke@u.rochester.edu
* CSC 214 Project 2
* TA: Julian Weiss
*/
public abstract class MenuActivity extends AppCompatActivity {
private static final String TAG = "MenuActivity";
public static String KEY_USERNAME = "USERNAME";
protected String mActiveUser;
private static final int RC_ACTIVE_USER = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.activity_main_menu, menu);
return true;
} //onCreateOptionsMenu()
@Override
public boolean onOptionsItemSelected(MenuItem item){
boolean handled;
switch(item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
handled=true;
break;
case R.id.menu_item_home:
Log.d(TAG, "Main Feed launched from Menu");
Intent mainFeed = new Intent(this, MainActivity.class);
mainFeed.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
mainFeed.putExtra(KEY_USERNAME, mActiveUser);
startActivity(mainFeed);
handled=true;
break;
case R.id.menu_item_write_post:
Log.d(TAG, "Write Post launched from Menu");
Intent writePost = new Intent(this, WritePostActivity.class);
writePost.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
writePost.putExtra(KEY_USERNAME, mActiveUser);
startActivity(writePost);
handled=true;
break;
case R.id.menu_item_edit_profile:
Log.d(TAG, "Edit Profile launched from Menu");
Intent editProfile = new Intent(this, EditProfileActivity.class);
editProfile.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
editProfile.putExtra(KEY_USERNAME, mActiveUser);
startActivityForResult(editProfile, RC_ACTIVE_USER);
handled=true;
break;
case R.id.menu_item_view_users:
Log.d(TAG, "View Users launched from Menu");
Intent userList = new Intent(this, UserListActivity.class);
userList.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
userList.putExtra(KEY_USERNAME, mActiveUser);
startActivity(userList);
handled=true;
break;
case R.id.menu_item_sign_out:
Log.d(TAG, "Signed out from Menu");
Intent signOut = new Intent(this, LoginActivity.class);
signOut.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(signOut);
handled=true;
break;
default:
handled = super.onOptionsItemSelected(item);
break;
}
return handled;
} //onOptionsItemSelected()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
mActiveUser = data.getStringExtra(KEY_USERNAME);
}
} //onActivityResult()
} //end class MenuActivity
|
package edu.cnm.deepdive.stockrollersservice.controller;
import com.google.common.collect.Lists;
import edu.cnm.deepdive.stockrollersservice.model.dao.IndustryRepository;
import edu.cnm.deepdive.stockrollersservice.model.entity.Industry;
import edu.cnm.deepdive.stockrollersservice.model.entity.Stock;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/industries")
public class IndustryController {
private final IndustryRepository industryRepository;
@Autowired
public IndustryController(IndustryRepository industryRepository) {
this.industryRepository = industryRepository;
}
/**
* Gets a list of all the industries.
* @return List of All Industries
*/
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Industry> getIndustries() {
return Lists.newArrayList(industryRepository.findAll());
//return get(id).getIndustries();
}
/**
* Gets a single industry.
* @param id
* @return
*/
@GetMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Industry get(@PathVariable long id) {
return industryRepository.findById(id).get();
}
/**
* Gets a list of stocks based industry.
* @param id
* @return
*/
//May not need this Later on because it should/could get autogenerated.
@GetMapping(value = "{id}/stocks", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Stock> getStocks(@PathVariable long id) {
return get(id).getStocks();
}
/**
* Returns a 404 not found if a NoSuchElementException is thrown.
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoSuchElementException.class)
public void notFound() {
}
/**
* Returns a 400 bad request error.
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public void badRequest() {
}
}
|
package com.spring.shop.service.transfer;
import com.spring.shop.model.User;
import com.spring.shop.repository.UserRepository;
import com.spring.shop.security.SecurityHelper;
import com.spring.shop.security.model.JwtUserDetails;
import com.spring.shop.security.service.AuthenticationHelper;
import com.spring.shop.service.dto.AuthUserDto;
import com.spring.shop.service.dto.JsonException;
import com.spring.shop.service.dto.LoginRequestDto;
import com.spring.shop.service.dto.LoginResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@Transactional
@RequiredArgsConstructor
public class AuthenticationService {
private final UserRepository userRepository;
private final AuthUserTransformer authUserTransformer;
private final AuthenticationHelper authenticationHelper;
private final AuthenticationManager authenticationManager;
public LoginResponseDto login(final LoginRequestDto loginRequestDto) {
try {
String username = Optional.ofNullable(loginRequestDto.getUsername())
.orElseThrow(() -> new BadCredentialsException("Username should be passed."));
String password = Optional.ofNullable(loginRequestDto.getPassword())
.orElseThrow(() -> new BadCredentialsException("Password should be passed."));
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password);
// Try to authenticate with this token
final Authentication authResult = this.authenticationManager.authenticate(authRequest);
// Set generated JWT token to response header
if (authResult.isAuthenticated()) {
JwtUserDetails userDetails = (JwtUserDetails) authResult.getPrincipal();
if (!userRepository.existsById(userDetails.getId())) {
throw new JsonException("User not exist in system.");
}
String token = this.authenticationHelper.generateToken(userDetails.getId());
return new LoginResponseDto(token);
} else {
throw new JsonException("Authentication failed.");
}
} catch (BadCredentialsException exception) {
throw new JsonException("Username or password was incorrect. Please try again.", exception);
}
}
/**
* Get user info.
*
* @return user info.
*/
@Transactional(readOnly = true)
public AuthUserDto getMe() {
Authentication authentication = SecurityHelper.getAuthenticationWithCheck();
User byUsername = userRepository.findFirstByUsername(authentication.getName());
return authUserTransformer.makeDto(byUsername);
}
}
|
// This file is a part of Humanoid project.
// Copyright (C) 2020 Aleksander Gajewski <adiog@mindblow.io>.
package io.mindblow.humanoid.canvas.model;
import android.opengl.Matrix;
import java.util.Vector;
import io.mindblow.humanoid.context.MasterContext;
import io.mindblow.humanoid.canvas.mesh.Bone;
class BoneSequence {
private Vector<Bone> sequence = new Vector<Bone>();
private float[] position;
private float[] direction;
private float angle;
void insert(Bone bone)
{
sequence.add(bone);
}
void setStartingPoint(float[] v3)
{
position = v3;
}
void setDirection(float angle, float[] v3)
{
this.angle = angle;
direction = v3;
}
private float[] follow(float[] matrix)
{
float[] context = new float[16];
Matrix.translateM(context, 0, matrix, 0, position[0], position[1], position[2]);
Matrix.rotateM(context, 0, angle, direction[0], direction[1], direction[2]);
return context;
}
void redraw(MasterContext masterContext, float[] matrix)
{
float[] context = follow(matrix);
for (Bone bone : sequence)
{
bone.orient(masterContext, context);
bone.redraw(masterContext, context);
bone.follow(context);
bone.reorient(masterContext, context);
}
}
}
|
package com.huangyifei.android.androidexample.image;
import android.content.Context;
import com.bumptech.glide.load.model.stream.BaseGlideUrlLoader;
/**
* Created by huangyifei on 16/9/20.
*/
public class CustomImageSizeUrlLoader extends BaseGlideUrlLoader<CustomImageSizeModelFutureStudio> {
public CustomImageSizeUrlLoader(Context context) {
super(context);
}
@Override
protected String getUrl(CustomImageSizeModelFutureStudio model, int width, int height) {
return model.requestCustomSizeUrl(width, height);
}
}
|
package uz.pdp.apphemanagement.payload;
import lombok.Data;
import java.util.UUID;
@Data
public class SalaryDto {
private Double salary;
private UUID userId;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.