text
stringlengths 10
2.72M
|
|---|
//Leaf Node for Huff Tree
//Code in following block was used from OpenDSA
/*------------------------------------------*/
class HuffLeafNode implements HuffBaseNode{
private char element;
private int weight;
HuffLeafNode(char e, int w) {
element = e;
weight = w;
}
char getElement() {
return element;
}
public int weight() {
return weight;
}
public boolean isLeaf() {
return true;
}
}
/*------------------------------------------*/
|
package LeetCode.ArraysAndStrings;
public class AddBinary {
public void addBinary(String a, String b) {
int m = a.length();
int n = b.length();
int i = m, j = n;
int carry = 0;
while (i >= 0 && j >= 0) {
}
}
public static void main(String[] args) {
AddBinary a = new AddBinary();
a.addBinary("1010", "1011");
}
}
|
package kg.inai.equeuesystem.services;
import kg.inai.equeuesystem.entities.Organization;
import kg.inai.equeuesystem.models.OrganizationModel;
import java.util.List;
public interface OrganizationService {
Organization create(OrganizationModel organizationModel);
Organization update(OrganizationModel organizationModel);
List<Organization> findAll();
Organization getById(Long id);
}
|
/*
* Launa Buche-Austin
* This program will act like a 'choose your own adventure' game
* March 09 2019
*/
package adventure.game;
import java.util.Scanner;
/**
*
* @author labuc9806
*/
public class AdventureGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyedInput = new Scanner (System.in) ;
String response1;
String response2;
String response3;
String response4;
String response5;
System.out.println("Congratulations!");
System.out.println ("You have been selected to join Space Mission X! ");
System.out.println("You will be piloting our very first catstronaut to space,");
System.out.println("all in a great effort to save Earth from a perilous threat of Space Dinosaurs!");
System.out.println("So let's begin our adventure!");
System.out.println("Choose your method of transportation. Taco/Racecar ?");
response1 = keyedInput.nextLine();
if (response1.equals("Taco"))
{
System.out.println("Everyone knows a cat's favourite method of transportation is by taco!");
System.out.println("You 3, 2, 2 BLAST OFF into space!");
System.out.println("You enter the depths of space, and pick up a transmission...");
System.out.println("You listen to the transmission and find that it's a cry for help!");
System.out.println("Answer it? yes/no? ");
response2 = keyedInput.nextLine();
if (response2.equals ("no"))
{
System.out.println("You continue on your journey.");
System.out.println("After days of space travel, the catstronaute encounters a strange object.");
System.out.println("You decided to investigate, and stumble upon a flaoting bottle of...");
System.out.println("Dr. Pepper?!");
System.out.println("Do you wish to take the mystical powers of Dr. Pepper? yes/no?" );
response3 = keyedInput.nextLine();
if (response3.equals ("no"))
{
System.out.println("You decide not to take the Dr. Pepper, heading straight towards your destination.");
System.out.println("Upon arriving, you encounter the army of space dinosaurs!");
System.out.println("Unsure of what orders to give the catstronaut,");
System.out.println("You tell him to utter the following words : ");
System.out.println("longcat/tacgnol?");
response4 = keyedInput.nextLine();
if (response4.equals ("tacgnol"))
{
System.out.println("Unfortunately you uttered the wrong words.");
System.out.println("The space dinosaurs approach, and the catstronaut dies.");
System.out.println("Mission Failed.");
}
else if (response4.equals ("longcat"))
{
System.out.println("Surprisingly, a giant long cat emerges from the void of space!");
System.out.println("Smothering all dinosaurs in its path, longcat takes everyone home safely");
System.out.println("With the world saved and catstronaut back home, the world is once again at peace. ");
}
}
else if (response3.equals("yes"))
{ System.out.println("You take the Dr. Pepper.");
System.out.println("Upon receiving it, the catstronaut takes a long while just to admire its beauty...");
System.out.println("UNTIL an ambush appears!");
System.out.println("Should the catstronaut sacrifice their beloved space drink? yes/no?");
response5 = keyedInput.nextLine();
if (response5.equals("yes"))
{
System.out.println("You throw the bottle of Dr.Pepper at the sneaky dinosaurs!");
System.out.println("They instantly explode");
System.out.println("Sad that he had to sacrifice his Dr. Pepper, catstronaut has an existential crisis.");
System.out.println("He decides to go home so he can spend every single second of the day with a Dr. Pepper by his side.");
System.out.println("All to mourn his friend.");
System.out.println("Unfortunately, this doesn't save the world, and the mission is a failure.");
}
else if (response5.equals("no"))
{
System.out.println("Instead of sacrificing the drink, the catstronaute decides to drink it in his last moments.");
System.out.println("He feels refreshed, but this doesn't do anything to help.");
System.out.println("The space dinosaurs win, and the catstronaut is never seen again");
}
}
}
else if (response2.equals ("yes"))
{
System.out.println("Upon answering the transmission, you meet a lonely planet.");
System.out.println("The lonely planet wants to befriend the catstronaut.");
System.out.println("The catstronaut abandons mission, and enjoys the rest of his days with his stellar new friend.");
}
}
else
{
System.out.println("You attempt to launch the racecar into space!");
System.out.println("Unfortunately, the racecar crashes back down the earth.");
System.out.println("Mission Failed.");
}
}
}
|
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.fetch;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.Entity;
import com.rcwang.seal.expand.EntityList;
import com.rcwang.seal.util.ComboMaker;
import com.rcwang.seal.util.GlobalVar;
import com.rcwang.seal.util.Helper;
public class WebFetcher {
public static Logger log = Logger.getLogger(WebFetcher.class);
public static GlobalVar gv = GlobalVar.getGlobalVar();
// true to add quotation marks around queries
public static final boolean DEFAULT_QUOTE_SEED = true;
// true to fetch search engine's cache
// CAUTION: IP address *will* be blocked by Google after a few queries
public static final boolean DEFAULT_FETCH_ENGINE_CACHE = false;
// true to remove duplicate documents (slower)
public static final boolean DEFAULT_REMOVE_DUPLICATE_DOCS = false;
// true to annotate the query in snippet's title and summary (slower)
public static final boolean DEFAULT_ANNOTATE_QUERY = false;
// total number of searchers (update getSearcher() if more engines are added)
public static final int NUM_SEARCHERS = 5;
public static final int ENGINE_BING_API = 4;
public static final int ENGINE_CLUEWEB = 3;
public static final int ENGINE_GOOGLE_WEB = 2;
public static final int ENGINE_GOOGLE_API = 1;
public static final int ENGINE_YAHOO_API = 0;
private Set<Snippet> snippets;
private String langID;
private int numSubSeeds;
private int numResults;
private boolean[] useEngine;
private boolean annotateQuery;
private boolean fetchSearchEngineCache;
private boolean removeDuplicateDocument;
private boolean quoteSeed;
public WebFetcher() {
snippets = new HashSet<Snippet>();
setQuoteSeed(DEFAULT_QUOTE_SEED);
setAnnotateQuery(DEFAULT_ANNOTATE_QUERY);
setFetchSearchEngineCache(DEFAULT_FETCH_ENGINE_CACHE);
setRemoveDuplicateDocument(DEFAULT_REMOVE_DUPLICATE_DOCS);
setUseEngine(gv.getUseEngine());
setLangID(gv.getLangID());
setNumSubSeeds(gv.getNumSubSeeds());
setNumResults(gv.getNumResults());
}
public DocumentSet fetchDocuments(EntityList seeds, String hint) {
// retrieve snippets
DocumentSet documents = new DocumentSet();
if (seeds == null || seeds.isEmpty())
return documents;
Set<Snippet> snippets = fetchSnippets(seeds, hint);
return fetchDocuments(snippets,documents);
}
/**
* Queries search engines and crawls the web
* @param seeds
* @param hint
* @return crawled web pages
*/
public DocumentSet fetchDocuments(Collection<String> seeds, String hint) {
// retrieve snippets
DocumentSet documents = new DocumentSet();
if (seeds == null || seeds.isEmpty())
return documents;
Set<Snippet> snippets = fetchSnippets(seeds, hint);
return fetchDocuments(snippets,documents);
}
public DocumentSet fetchDocuments(Set<Snippet> snippets,DocumentSet documents) {
if (this.useEngine[ENGINE_CLUEWEB]) {
documents.addAll(ClueWebSearcher.getLastRun().getDocuments());
}
List<URL> urls = new ArrayList<URL>();
List<Snippet> snippetList = new ArrayList<Snippet>(snippets);
for (Snippet snippet : snippetList) {
if (fetchSearchEngineCache && snippet.getCacheURL() != null)
urls.add(snippet.getCacheURL());
else urls.add(snippet.getPageURL());
}
WebManager webManager = new WebManager();
webManager.setTimeOutInMS(0); // use auto timeout
List<String> webpages = webManager.get(urls);
Set<Integer> docHashSet = new HashSet<Integer>();
for (int i = 0; i < urls.size(); i++) {
String webpage = webpages.get(i);
URL url = urls.get(i);
if (webpage == null || url == null)
continue;
if (removeDuplicateDocument) {
int fingerPrint = webpage.toLowerCase().replaceAll("\\W+", "").hashCode();
if (docHashSet.contains(fingerPrint)) {
log.info("Found a duplicate document: " + url);
continue;
}
docHashSet.add(fingerPrint);
}
Document document = new Document(webpage, url);
document.setSnippet(snippetList.get(i));
documents.add(document);
}
return documents;
}
public Set<Snippet> fetchSnippets(EntityList seeds, String hint) {
snippets.clear();
if (seeds == null || seeds.isEmpty())
return snippets;
int numSeeds = (numSubSeeds <= 0) ? seeds.size() : Math.min(numSubSeeds, seeds.size());
ComboMaker<Entity> comboMaker = new ComboMaker<Entity>();
List<List<Entity>> subSeedsList = comboMaker.make(seeds.getEntities(), numSeeds);
List<Thread> threadList = new ArrayList<Thread>();
List<WebSearcher> searcherList = new ArrayList<WebSearcher>();
for (int i = 0; i < subSeedsList.size(); i++)
fetchSnippetsInThread(new EntityList(subSeedsList.get(i)).getEntityNames(), i, hint, threadList, searcherList);
joinSnippetThreads(threadList,searcherList);
return snippets;
}
/**
* Aggressively fetch snippets
* @param seeds
* @param hint
*/
public Set<Snippet> fetchSnippets(Collection<String> seeds, String hint) {
return fetchSnippets(new EntityList(seeds),hint);
// snippets.clear();
// if (seeds == null || seeds.isEmpty())
// return snippets;
//
// int numSeeds = (numSubSeeds <= 0) ? seeds.size() : Math.min(numSubSeeds, seeds.size());
// ComboMaker<String> comboMaker = new ComboMaker<String>();
// List<List<String>> subSeedsList = comboMaker.make(seeds, numSeeds);
//
// List<Thread> threadList = new ArrayList<Thread>();
// List<WebSearcher> searcherList = new ArrayList<WebSearcher>();
// for (int i = 0; i < subSeedsList.size(); i++)
// fetchSnippetsInThread(new EntityList(subSeedsList.get(i)).getEntityNames(), i, hint, threadList, searcherList);
//
// joinSnippetThreads(threadList,searcherList);
// return snippets;
}
private void joinSnippetThreads(List<Thread> threadList, List<WebSearcher> searcherList) {
try {
// wait for the threads to finish
for (int i = 0; i < threadList.size(); i++) {
Thread searchThread = threadList.get(i);
if (searchThread == null) continue;
searchThread.join();
WebSearcher searcher = searcherList.get(i);
snippets.addAll(searcher.getSnippets());
}
} catch (InterruptedException ie) {}
}
public String getLangID() {
return langID;
}
public int getNumResults() {
return numResults;
}
public int getNumSubSeeds() {
return numSubSeeds;
}
public Set<Snippet> getSnippets() {
return snippets;
}
public boolean[] getUseEngine() {
return useEngine;
}
public boolean isAnnotateQuery() {
return annotateQuery;
}
public boolean isFetchSearchEngineCache() {
return fetchSearchEngineCache;
}
public boolean isQuoteSeed() {
return quoteSeed;
}
public boolean isRemoveDuplicateDocument() {
return removeDuplicateDocument;
}
public void setAnnotateQuery(boolean annotateQuery) {
this.annotateQuery = annotateQuery;
}
public void setFetchSearchEngineCache(boolean fetchSearchEngineCache) {
this.fetchSearchEngineCache = fetchSearchEngineCache;
}
public void setLangID(String langID) {
this.langID = langID;
}
public void setNumResults(int numResults) {
this.numResults = numResults;
}
public void setNumSubSeeds(int numSubSeeds) {
this.numSubSeeds = numSubSeeds;
}
public void setQuoteSeed(boolean addQuote) {
this.quoteSeed = addQuote;
}
public void setRemoveDuplicateDocument(boolean removeDuplicateDocument) {
this.removeDuplicateDocument = removeDuplicateDocument;
}
public void setUseEngine(int engine) {
this.useEngine = Helper.toBinaryArray(engine, NUM_SEARCHERS);
if (log.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("Using engines: ");
StringBuilder sb2 = new StringBuilder("(others: ");
String[] engines = new String[] {"Yahoo API","Google API","Google Web","Clue Web","Bing API"};
for (int i=0; i<this.useEngine.length; i++) {
if (this.useEngine[i]) sb.append(engines[i]).append(" ");
else sb2.append(engines[i]).append(" ");
}
log.debug(sb.toString()+sb2.toString()+")");
}
}
private void fetchSnippetsInThread(List<String[]> seeds, int index, String hint,
List<Thread> threadList,
List<WebSearcher> searcherList) {
// create searcher threads
for (int i = 0; i < NUM_SEARCHERS; i++) {
WebSearcher searcher = getSearcher(i);
if (searcher == null) continue;
// add queries into the searcher
for (String[] seed : seeds) {
for (String s : seed)
searcher.addQuery(s, quoteSeed);
}
// configures the searcher
searcher.addQuery(hint);
searcher.setLangID(langID);
searcher.setNumResults(numResults);
searcher.setAnnotateQuery(annotateQuery);
searcher.setIndex(index);
Thread searchThread = new Thread(searcher);
searchThread.start();
threadList.add(searchThread);
searcherList.add(searcher);
}
}
// update NUM_SEARCHERS if more engines are added
private WebSearcher getSearcher(int i) {
if (!useEngine[i]) return null;
switch (i) {
case ENGINE_YAHOO_API: return new YahooAPISearcher();
case ENGINE_GOOGLE_API: return new GoogleCustomAPISearcher();//GoogleAPISearcher();
case ENGINE_GOOGLE_WEB: return new GoogleWebSearcher();
case ENGINE_CLUEWEB: return ClueWebSearcher.getSearcher();
case ENGINE_BING_API: return new BingAPISearcher();
default: return null;
}
}
}
|
package com.sixmac.entity;
import javax.persistence.*;
/**
* Created by Administrator on 2016/5/20 0020.
*/
@Entity
@Table(name = "t_user_reserve_join")
public class UserReserve extends BaseEntity{
@Transient
private Integer status;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
/**/
@ManyToOne
@JoinColumn(name = "reserve_id")
private Reserve reserve;
// @Column(name = "reserve_id")
// private Long reserveId;
@Transient
private String content;
public Reserve getReserve() {
return reserve;
}
public void setReserve(Reserve reserve) {
this.reserve = reserve;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/* public Reserve getReserve() {
return reserve;
}
public void setReserve(Reserve reserve) {
this.reserve = reserve;
}*/
// public Long getReserveId() {
// return reserveId;
// }
//
// public void setReserveId(Long reserveId) {
// this.reserveId = reserveId;
// }
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
package kr.co.ecommerce.repository.jpa.interfaces;
import org.springframework.data.jpa.repository.JpaRepository;
import kr.co.ecommerce.dao.Member;
public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {
}
|
package com.tencent.mm.plugin.game.wepkg.model;
import com.tencent.mm.plugin.game.wepkg.a.b;
import com.tencent.mm.plugin.game.wepkg.model.b.2;
import com.tencent.mm.plugin.game.wepkg.utils.d;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class b$2$1 implements Runnable {
final /* synthetic */ String keO;
final /* synthetic */ 2 keP;
b$2$1(2 2, String str) {
this.keP = 2;
this.keO = str;
}
public final void run() {
if (!bi.oW(this.keO)) {
return;
}
if (f.Ek(d.Et(this.keP.keN))) {
com.tencent.mm.plugin.game.wepkg.a.d.aVo().DU(this.keP.keN);
b.aVn().DU(this.keP.keN);
x.i("MicroMsg.Wepkg.CleanWepkgMgr", "clean wepkg success. pkgid:%s", new Object[]{this.keP.keN});
return;
}
x.i("MicroMsg.Wepkg.CleanWepkgMgr", "clean wepkg fail. pkgid:%s", new Object[]{this.keP.keN});
}
}
|
package iterators;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* 5.1.4. Создать convert(Iterator<Iterator>) [#152]
* Реализовать класс с методом Iterator<Integer> convert(Iterator<Iterator<Integer>> it).
Что из себя представляет запись Iterator<Iterator<Integer>?.
Каждый итератор это последовательность.
Итератор 1 – 4 2 0 4 6 4 9
Итератор 2 – 0 9 8 7 5
Итератор 3 – 1 3 5 6 7 0 9 8 4
Если мы говорим о записи Итератор Итераторов. Значит итератор содержит не конечные значения, а сложенные итераторы.
Итератор - Итератор 1, Итератор 2, Итератор 3.
Метод convert должен принимать объект итератор итератор и возвращать Итератор чисел.
Iterator<Iterator<Integer> - ((4 2 0 4 6 4 9), (0 9 8 7 5), (1 3 5 6 7 0 9 8 4))
Метод должен возвращать
Iterator<Integer> - (4 2 0 4 6 4 9 0 9 8 7 5 1 3 5 6 7 0 9 8 4)
Метод не должен копировать данные. Нужно реализовать итератор, который будет пробегать по вложенными итераторам без копирования данных.
*/
public class Converter {
public Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {
return new Iterator<Integer>() {
Iterator<Integer> itIn = it.next();
@Override
public boolean hasNext() {
boolean result = false;
if (itIn.hasNext()) {
result = true;
} else {
while (it.hasNext()) {
itIn = it.next();
if (itIn.hasNext()) {
result = true;
break;
}
}
}
//==============Старый рабочий вариант===========
// if (itIn.hasNext()) {
// result = true;
// } else if (it.hasNext()) {
// itIn = it.next();
// if (itIn.hasNext()) {
// result = true;
// }
// }
return result;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return itIn.next();
}
};
}
public static void main(String[] args) {
Iterator<Integer> its;
Iterator<Integer> it1 = Arrays.asList(1, 2, 3).iterator();
Iterator<Integer> it2 = Arrays.asList(4, 5, 6).iterator();
Iterator<Integer> it3 = Arrays.asList(7, 8, 9).iterator();
Iterator<Iterator<Integer>> it = Arrays.asList(it1, it2, it3).iterator();
Converter con = new Converter();
its = con.convert(it);
while (its.hasNext()) {
System.out.println(its.next());
}
}
}
|
package fi.lassemaatta.temporaljooq.feature.company.repository;
import fi.lassemaatta.temporaljooq.feature.company.dto.CompanyDto;
import fi.lassemaatta.temporaljooq.feature.company.dto.PersistableCompanyDto;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ICompanyRepository {
CompanyDto create(PersistableCompanyDto company);
CompanyDto update(CompanyDto company);
List<CompanyDto> findAll(boolean includeHistory);
Optional<CompanyDto> find(UUID id);
List<CompanyDto> findByIds(Collection<UUID> ids);
Optional<CompanyDto> findAt(UUID id,
Instant systemTime);
}
|
package ArraysJavaListsAutoboxingUnboxing.Arrays;
public class Main {
public static void main(String[] args) {
int[] myVariable;
myVariable = new int[9];
int[] myIntArray = new int[9]; // same as above.
myIntArray[5] = 50;
// array of doubles
double[] myDoubleArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(myDoubleArray[4]);
for (int i = 0; i < myDoubleArray.length; i++) {
myDoubleArray[i] = i*10;
}
printArray(myDoubleArray);
}
// pass an array as argument in a method.
public static void printArray(double[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("Element " + i + ", value is: " + array[i]) ;
}
}
}
|
package factory.abstractfactory.ingredients.concrete;
import factory.abstractfactory.ingredients.interfaces.Veggies;
public class VeggiesTho implements Veggies {
@Override
public String getName() {
return "VEGETABLES";
}
}
|
package sss.impl;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import sss.SuperSimpleStocks;
import sss.bean.Stock;
import sss.bean.TradeRecord;
public class SuperSimpleStocksImplTest {
private SuperSimpleStocks superSimpleStocks;
private Stock stock;
@BeforeTest
public void setup() {
superSimpleStocks = new SuperSimpleStocksImpl();
stock = new Stock();
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testCalculateDividendYieldWithError() {
Stock nullStock = null;
superSimpleStocks.calculateDividendYield(nullStock, 2);
}
@DataProvider(name="dividendYieldErrorData")
private Object[][] dividendYieldErrorData() {
return new Object[][] {
{Stock.Type.COMMON, 8, 0.02f, 100, 0.0},
{Stock.Type.COMMON, 8, 0.02f, 100, -2.0},
{Stock.Type.COMMON, -8, 0.02f, 100, 2.0},
{Stock.Type.PREFERRED, 8, 0.02f, 100, 0.0},
{Stock.Type.PREFERRED, 8, 0.02f, 100, -2.0},
{Stock.Type.PREFERRED, 8, 0.02f, -100, 2.0},
{Stock.Type.PREFERRED, 8, -0.02f, 100, 2.0}
};
}
@Test(expectedExceptions = IllegalArgumentException.class, dataProvider="dividendYieldErrorData")
public void testCalculateDividendYieldWithError(Stock.Type stockType, int lastDivinded, float fixedDividend, int parValue, double tickerPrice) {
stock.setType(stockType);
stock.setLastDividend(lastDivinded);
stock.setFixedDividend(fixedDividend);
stock.setParValue(parValue);
superSimpleStocks.calculateDividendYield(stock, tickerPrice);
}
@DataProvider(name="dividendYieldDataCommonStock")
private Object[][] dividendYieldDataCommonStock() {
return new Object[][] {
{Stock.Type.COMMON, 8, 2.0, 4.0},
{Stock.Type.COMMON, 8, 5.0, 1.6},
{Stock.Type.COMMON, 0, 2.0, 0.0},
};
}
@Test(dataProvider="dividendYieldDataCommonStock")
public void testCalculateDividendYieldCommonStock(Stock.Type stockType, int lastDivinded, double tickerPrice, double expected) {
stock.setType(stockType);
stock.setLastDividend(lastDivinded);
Assert.assertTrue(superSimpleStocks.calculateDividendYield(stock, tickerPrice) == expected);
}
@DataProvider(name="dividendYieldDataPreferredStock")
private Object[][] dividendYieldDataPreferredStock() {
return new Object[][] {
{Stock.Type.PREFERRED, 100, 0.02f, 2.0, 1.0},
{Stock.Type.PREFERRED, 0, 0.02f, 2.0, 0.0},
};
}
@Test(dataProvider="dividendYieldDataPreferredStock")
public void testCalculateDividendYieldPreferredStock(Stock.Type stockType, int parValue, float fixedDividend, double tickerPrice, double expected) {
stock.setType(stockType);
stock.setParValue(parValue);
stock.setFixedDividend(fixedDividend);
Assert.assertTrue(superSimpleStocks.calculateDividendYield(stock, tickerPrice) == expected);
}
@DataProvider(name="peRatioErrorData")
private Object[][] peRatioErrorData() {
return new Object[][] {
{0.0, 2.0},
{-5.0, 2.0},
{5.0, -2.0}
};
}
@Test(expectedExceptions = IllegalArgumentException.class, dataProvider="peRatioErrorData")
public void testCalculatePERatioWithError(double dividend, double tickerPrice) {
SuperSimpleStocks spySuperSimpleStocks = Mockito.spy(superSimpleStocks);
Mockito.doReturn(dividend).when(spySuperSimpleStocks).calculateDividendYield(Mockito.any(Stock.class), Mockito.anyDouble());
spySuperSimpleStocks.calculatePERatio(stock, tickerPrice);
}
@Test
public void testCalculatePERatio() {
double dividend = 5.0;
double tickerPrice = 2.0;
double expected = 0.4;
SuperSimpleStocks spySuperSimpleStocks = Mockito.spy(superSimpleStocks);
Mockito.doReturn(dividend).when(spySuperSimpleStocks).calculateDividendYield(Mockito.any(Stock.class), Mockito.anyDouble());
Assert.assertTrue(spySuperSimpleStocks.calculatePERatio(stock, tickerPrice) == expected);
}
@DataProvider(name="tradeRecordListErrorData")
private Object[][] tradeRecordListErrorData() {
TradeRecord invalidTradeRecord = new TradeRecord();
invalidTradeRecord.setPrice(10);
invalidTradeRecord.setQuantityOfShares(2);
invalidTradeRecord.setStockSymbol(Stock.Symbol.ALE);
return new Object[][] {
{null},
{Collections.emptyList()},
{Arrays.asList(new TradeRecord())},
{Arrays.asList(invalidTradeRecord)}
};
}
@Test(expectedExceptions = IllegalArgumentException.class, dataProvider="tradeRecordListErrorData")
public void testCalculateStockPriceWithError(List<TradeRecord> tradeRecords) {
LocalDateTime currentTime = LocalDateTime.of(2016, 10, 16, 10, 50);
superSimpleStocks.calculateStockPrice(Stock.Symbol.ALE, tradeRecords, currentTime);
}
@Test(expectedExceptions = IllegalArgumentException.class, dataProvider="tradeRecordListErrorData")
public void testCalculateStockPriceWithNoTradeRecord(List<TradeRecord> tradeRecords) {
LocalDateTime currentTime = LocalDateTime.of(2016, 10, 16, 10, 50);
Assert.assertTrue(superSimpleStocks.calculateStockPrice(Stock.Symbol.POP, tradeRecords, currentTime) == -1);
}
@Test
public void testCalculateStockPriceFromRecordedTrades() {
LocalDateTime currentTime = LocalDateTime.of(2016, 10, 16, 10, 50);
List<TradeRecord> tradeRecords = setupTradeRecordList();
Assert.assertTrue(superSimpleStocks.calculateStockPrice(Stock.Symbol.ALE, tradeRecords, currentTime) == 4.0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testCalculateGBCEAllShareIndexWithError() {
List<TradeRecord> tradeRecords = setupTradeRecordList();
superSimpleStocks.calculateGBCEAllShareIndex(Collections.emptyList(), tradeRecords);
}
private List<TradeRecord> setupTradeRecordList() {
List<TradeRecord> tradeRecords = new LinkedList<TradeRecord>();
TradeRecord tradeRecord1 = new TradeRecord();
tradeRecord1.setPrice(2);
tradeRecord1.setStockSymbol(Stock.Symbol.ALE);
tradeRecord1.setQuantityOfShares(2);
tradeRecord1.setTimeStamp(LocalDateTime.of(2016, 10, 16, 10, 55));
tradeRecords.add(tradeRecord1);
TradeRecord tradeRecord2 = new TradeRecord();
tradeRecord2.setPrice(4);
tradeRecord2.setStockSymbol(Stock.Symbol.GIN);
tradeRecord2.setQuantityOfShares(2);
tradeRecord2.setTimeStamp(LocalDateTime.of(2016, 10, 16, 10, 55));
tradeRecords.add(tradeRecord2);
TradeRecord tradeRecord3 = new TradeRecord();
tradeRecord3.setPrice(6);
tradeRecord3.setStockSymbol(Stock.Symbol.ALE);
tradeRecord3.setQuantityOfShares(2);
tradeRecord3.setTimeStamp(LocalDateTime.of(2016, 10, 16, 10, 45));
tradeRecords.add(tradeRecord3);
TradeRecord tradeRecord4 = new TradeRecord();
tradeRecord4.setPrice(8);
tradeRecord4.setStockSymbol(Stock.Symbol.ALE);
tradeRecord4.setQuantityOfShares(2);
tradeRecord4.setTimeStamp(LocalDateTime.of(2016, 10, 16, 10, 20));
tradeRecords.add(tradeRecord4);
return tradeRecords;
}
}
|
package com.workorder.activity.service;
import java.util.List;
import java.util.Map;
import org.activiti.engine.task.Task;
import com.workorder.ticket.model.TaskInfo;
public interface ActivityService {
/**
* 启动流程
*
* @param bizId
* 业务id
*/
public String startProcesses(String processDefinitionId,
Map<String, Object> variables);
/**
*
* <p>
* 描述: 根据用户id查询待办任务列表
* </p>
*
*/
public List<Task> findTasksByUserId(String processDefinitionId,
String processor);
/**
* <p>
* 描述:获取当前任务
* </p>
*
*/
public Task getCurrentTask(String processInstanceId);
/**
*
* <p>
* 描述:任务审批 (通过/拒接)
* </p>
*
* @param taskId
* 任务id
* @param userId
* 用户id
* @param result
* false OR true
*/
public void completeTask(String taskId, String processor, Boolean result,
String comment);
/**
*
* <p>
* 描述: 查询历史任务列表
* </p>
*
*/
public List<TaskInfo> findHistoryTasks(String processInstanceId);
/**
*
* <p>
* 描述:删除任务审批
* </p>
*
* @param processInstanceId
*/
public void deleteTask(String processInstanceId);
/**
*
* <p>
* 描述: 生成流程图 首先启动流程,获取processInstanceId,替换即可生成
* </p>
*
* @param processInstanceId
* @throws Exception
*/
public void queryProImg(String processInstanceId);
public String deploy(String bpmnKey);
}
|
package com.flutterwave.raveandroid.di;
import android.content.Context;
import android.os.Bundle;
import android.test.mock.MockContext;
import com.flutterwave.raveandroid.RavePayInitializer;
import com.flutterwave.raveandroid.data.DeviceIdGetter;
import com.flutterwave.raveandroid.rave_cache.SharedPrefsRepo;
import com.flutterwave.raveandroid.rave_presentation.data.PayloadEncryptor;
import com.flutterwave.raveandroid.rave_presentation.data.PayloadToJsonConverter;
import com.flutterwave.raveandroid.rave_presentation.data.validators.CardNoValidator;
import com.flutterwave.raveandroid.rave_presentation.data.validators.TransactionStatusChecker;
import com.flutterwave.raveandroid.rave_presentation.data.validators.UrlValidator;
import com.flutterwave.raveandroid.validators.AccountNoValidator;
import com.flutterwave.raveandroid.validators.AmountValidator;
import com.flutterwave.raveandroid.validators.BankCodeValidator;
import com.flutterwave.raveandroid.validators.BanksMinimum100AccountPaymentValidator;
import com.flutterwave.raveandroid.validators.BvnValidator;
import com.flutterwave.raveandroid.validators.CardExpiryValidator;
import com.flutterwave.raveandroid.validators.CvvValidator;
import com.flutterwave.raveandroid.validators.DateOfBirthValidator;
import com.flutterwave.raveandroid.validators.EmailValidator;
import com.flutterwave.raveandroid.validators.NetworkValidator;
import com.flutterwave.raveandroid.validators.PhoneValidator;
import org.mockito.Mockito;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class TestAndroidModule {
@Provides
@Singleton
public Context providesContext() {
return new MockContext();
}
@Provides
@Singleton
public SharedPrefsRepo providesSharedPrefsRequestImpl() {
return Mockito.mock(SharedPrefsRepo.class);
}
@Provides
@Singleton
public AmountValidator providesAmountValidator() {
return Mockito.mock(AmountValidator.class);
}
@Provides
@Singleton
public CvvValidator providesCvvValidator() {
return Mockito.mock(CvvValidator.class);
}
@Provides
@Singleton
public EmailValidator providesEmailValidator() {
return Mockito.mock(EmailValidator.class);
}
@Provides
@Singleton
public PhoneValidator providesPhoneValidator() {
return Mockito.mock(PhoneValidator.class);
}
@Provides
@Singleton
public NetworkValidator providesNetworkValidator() {
return Mockito.mock(NetworkValidator.class);
}
@Provides
@Singleton
public DateOfBirthValidator providesDateOfBirthValidator() {
return Mockito.mock(DateOfBirthValidator.class);
}
@Provides
@Singleton
public BvnValidator providesBvnValidator() {
return Mockito.mock(BvnValidator.class);
}
@Provides
@Singleton
public AccountNoValidator providesAccountNoValidator() {
return Mockito.mock(AccountNoValidator.class);
}
@Provides
@Singleton
public BankCodeValidator providesBankCodeValidator() {
return Mockito.mock(BankCodeValidator.class);
}
@Provides
@Singleton
public BanksMinimum100AccountPaymentValidator providesBanksMinimum100AccountPaymentValidator() {
return Mockito.mock(BanksMinimum100AccountPaymentValidator.class);
}
@Provides
@Singleton
public CardNoValidator providesCardNoValidator() {
return Mockito.mock(CardNoValidator.class);
}
@Provides
@Singleton
public CardExpiryValidator providesCardExpiryValidator() {
return Mockito.mock(CardExpiryValidator.class);
}
@Provides
@Singleton
public UrlValidator providesUrlValidator() {
return Mockito.mock(UrlValidator.class);
}
@Provides
@Singleton
public RavePayInitializer providesRavePayInitializer() {
return Mockito.mock(RavePayInitializer.class);
}
@Provides
@Singleton
public TransactionStatusChecker providesTransactionStatusChecker() {
return Mockito.mock(TransactionStatusChecker.class);
}
@Provides
@Singleton
public DeviceIdGetter providesDeviceIdGetter() {
return Mockito.mock(DeviceIdGetter.class);
}
@Provides
@Singleton
public PayloadToJsonConverter providesPayloadToJson() {
return Mockito.mock(PayloadToJsonConverter.class);
}
@Provides
@Singleton
public PayloadEncryptor providesGetEncryptedData() {
return Mockito.mock(PayloadEncryptor.class);
}
@Provides
@Singleton
public com.flutterwave.raveandroid.rave_core.models.DeviceIdGetter providesCoreDeviceIdGetter() {
return Mockito.mock(com.flutterwave.raveandroid.rave_core.models.DeviceIdGetter.class);
}
@Provides
@Singleton
public Bundle providesBundle() {
return Mockito.mock(Bundle.class);
}
}
|
package ua.rozhkov.messager.entity;
import java.io.Serializable;
import java.time.LocalDate;
public class Message implements Serializable{
private int id;
private LocalDate date;
private String content;
public Message(){};
public Message(int id, LocalDate date, String content) {
this.id = id;
this.date = date;
this.content = content;
}
@Override
public String toString() {
return "{"+
"id: "+this.getId()+"; "+
"date: "+this.getDate()+"; "+
"content: "+this.getContent()+
"}";
}
public int getId() {
return id;
}
public LocalDate getDate() {
return date;
}
public String getContent() {
return content;
}
public void setId(int id) {
this.id = id;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setContent(String content) {
this.content = content;
}
}
|
package modelo;
import java.io.File;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EnviarEmail {
/** Variables. */
private Properties props;
private String from, to, subject;
/** MultiPart para crear mensajes compuestos. */
MimeMultipart multipart = new MimeMultipart("related");
public EnviarEmail() {
props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
}
public void createAndSendEmail(String from, String to, String subject) throws Exception {
this.from = from;
this.to = to;
this.subject = subject;
enviarMailHtml(from, to, subject, null, null);
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public MimeMultipart getMultipart() {
return multipart;
}
public void setMultipart(MimeMultipart multipart) {
this.multipart = multipart;
}
/* <-------------------------- Métodos --------------------------------> */
public void addAttach(String pathname) throws Exception {
File file = new File(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
messageBodyPart.setDisposition(Part.ATTACHMENT);
this.multipart.addBodyPart(messageBodyPart);
}
public void addCID(String cidname, String pathname) throws Exception {
DataSource fds = new FileDataSource(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<" + cidname + ">");
this.multipart.addBodyPart(messageBodyPart);
}
public void addContent(String htmlText) throws Exception {
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html");
// add it
this.multipart.addBodyPart(messageBodyPart);
}
public void sendMultipart() throws Exception {
Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("juanjosehdez96@gmail.com", "gugamida2");
}
});
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(this.getSubject());
message.setFrom(new InternetAddress(this.getFrom()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.getTo()));
// put everything together
message.setContent(multipart);
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
public void enviarMailHtml(String from, String to, String subject, String body, List<String> adjuntos)
throws Exception {
// propiedades de conexion al servidor de correo
this.from = from;
this.subject = subject;
this.to = to;
String ipServidor = "localhost";
String puertoServidor = "8081";
String nombreAplicacion = "CANARYWHEY";
String parametros = "misParametros";
String cabecera = "<HTML><BODY><img src='cid:cidcabecera' /> <br/> <br/>";
String pie = "<br/> <br/> <img src='cid:cidpie' /></BODY></HTML>";
String boton = "<table><tr><td><form method='post' target='blank' action='http://" + ipServidor + ":"
+ puertoServidor + "/" + nombreAplicacion + "/servlet/MiServlet?param=" + parametros
+ "'> <input name='miBoton' type='submit' value='Boton' /></form>";
String formulario = String.format("%s%s%s%s%s", cabecera, body, "<br/> <br/>", boton, pie);
addContent(formulario);
// enviar el correo MULTIPART
sendMultipart();
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
/**
* Jobshop车间在检任务Id generated by hbm2java
*/
public class Jobshop车间在检任务Id implements java.io.Serializable {
private String deptid;
private String employeename;
private String partName;
private String drawingid;
private String taskuid;
private String batchnum;
private Long priority;
private Long checktasktype;
private BigDecimal planqty;
private String notes;
private String parentuid;
private String partNumber;
private Date createtime;
private Date latefinish;
private String delaytime;
public Jobshop车间在检任务Id() {
}
public Jobshop车间在检任务Id(String employeename, String taskuid, String partNumber) {
this.employeename = employeename;
this.taskuid = taskuid;
this.partNumber = partNumber;
}
public Jobshop车间在检任务Id(String deptid, String employeename, String partName, String drawingid, String taskuid,
String batchnum, Long priority, Long checktasktype, BigDecimal planqty, String notes, String parentuid,
String partNumber, Date createtime, Date latefinish, String delaytime) {
this.deptid = deptid;
this.employeename = employeename;
this.partName = partName;
this.drawingid = drawingid;
this.taskuid = taskuid;
this.batchnum = batchnum;
this.priority = priority;
this.checktasktype = checktasktype;
this.planqty = planqty;
this.notes = notes;
this.parentuid = parentuid;
this.partNumber = partNumber;
this.createtime = createtime;
this.latefinish = latefinish;
this.delaytime = delaytime;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getEmployeename() {
return this.employeename;
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
public String getPartName() {
return this.partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getDrawingid() {
return this.drawingid;
}
public void setDrawingid(String drawingid) {
this.drawingid = drawingid;
}
public String getTaskuid() {
return this.taskuid;
}
public void setTaskuid(String taskuid) {
this.taskuid = taskuid;
}
public String getBatchnum() {
return this.batchnum;
}
public void setBatchnum(String batchnum) {
this.batchnum = batchnum;
}
public Long getPriority() {
return this.priority;
}
public void setPriority(Long priority) {
this.priority = priority;
}
public Long getChecktasktype() {
return this.checktasktype;
}
public void setChecktasktype(Long checktasktype) {
this.checktasktype = checktasktype;
}
public BigDecimal getPlanqty() {
return this.planqty;
}
public void setPlanqty(BigDecimal planqty) {
this.planqty = planqty;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getParentuid() {
return this.parentuid;
}
public void setParentuid(String parentuid) {
this.parentuid = parentuid;
}
public String getPartNumber() {
return this.partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getLatefinish() {
return this.latefinish;
}
public void setLatefinish(Date latefinish) {
this.latefinish = latefinish;
}
public String getDelaytime() {
return this.delaytime;
}
public void setDelaytime(String delaytime) {
this.delaytime = delaytime;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Jobshop车间在检任务Id))
return false;
Jobshop车间在检任务Id castOther = (Jobshop车间在检任务Id) other;
return ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null
&& castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid())))
&& ((this.getEmployeename() == castOther.getEmployeename())
|| (this.getEmployeename() != null && castOther.getEmployeename() != null
&& this.getEmployeename().equals(castOther.getEmployeename())))
&& ((this.getPartName() == castOther.getPartName()) || (this.getPartName() != null
&& castOther.getPartName() != null && this.getPartName().equals(castOther.getPartName())))
&& ((this.getDrawingid() == castOther.getDrawingid()) || (this.getDrawingid() != null
&& castOther.getDrawingid() != null && this.getDrawingid().equals(castOther.getDrawingid())))
&& ((this.getTaskuid() == castOther.getTaskuid()) || (this.getTaskuid() != null
&& castOther.getTaskuid() != null && this.getTaskuid().equals(castOther.getTaskuid())))
&& ((this.getBatchnum() == castOther.getBatchnum()) || (this.getBatchnum() != null
&& castOther.getBatchnum() != null && this.getBatchnum().equals(castOther.getBatchnum())))
&& ((this.getPriority() == castOther.getPriority()) || (this.getPriority() != null
&& castOther.getPriority() != null && this.getPriority().equals(castOther.getPriority())))
&& ((this.getChecktasktype() == castOther.getChecktasktype())
|| (this.getChecktasktype() != null && castOther.getChecktasktype() != null
&& this.getChecktasktype().equals(castOther.getChecktasktype())))
&& ((this.getPlanqty() == castOther.getPlanqty()) || (this.getPlanqty() != null
&& castOther.getPlanqty() != null && this.getPlanqty().equals(castOther.getPlanqty())))
&& ((this.getNotes() == castOther.getNotes()) || (this.getNotes() != null
&& castOther.getNotes() != null && this.getNotes().equals(castOther.getNotes())))
&& ((this.getParentuid() == castOther.getParentuid()) || (this.getParentuid() != null
&& castOther.getParentuid() != null && this.getParentuid().equals(castOther.getParentuid())))
&& ((this.getPartNumber() == castOther.getPartNumber()) || (this.getPartNumber() != null
&& castOther.getPartNumber() != null && this.getPartNumber().equals(castOther.getPartNumber())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null
&& castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getLatefinish() == castOther.getLatefinish()) || (this.getLatefinish() != null
&& castOther.getLatefinish() != null && this.getLatefinish().equals(castOther.getLatefinish())))
&& ((this.getDelaytime() == castOther.getDelaytime()) || (this.getDelaytime() != null
&& castOther.getDelaytime() != null && this.getDelaytime().equals(castOther.getDelaytime())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode());
result = 37 * result + (getEmployeename() == null ? 0 : this.getEmployeename().hashCode());
result = 37 * result + (getPartName() == null ? 0 : this.getPartName().hashCode());
result = 37 * result + (getDrawingid() == null ? 0 : this.getDrawingid().hashCode());
result = 37 * result + (getTaskuid() == null ? 0 : this.getTaskuid().hashCode());
result = 37 * result + (getBatchnum() == null ? 0 : this.getBatchnum().hashCode());
result = 37 * result + (getPriority() == null ? 0 : this.getPriority().hashCode());
result = 37 * result + (getChecktasktype() == null ? 0 : this.getChecktasktype().hashCode());
result = 37 * result + (getPlanqty() == null ? 0 : this.getPlanqty().hashCode());
result = 37 * result + (getNotes() == null ? 0 : this.getNotes().hashCode());
result = 37 * result + (getParentuid() == null ? 0 : this.getParentuid().hashCode());
result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
result = 37 * result + (getLatefinish() == null ? 0 : this.getLatefinish().hashCode());
result = 37 * result + (getDelaytime() == null ? 0 : this.getDelaytime().hashCode());
return result;
}
}
|
package com.chan.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chan.demo.mapper.boardMapper;
import com.chan.demo.vo.boardVO;
import java.util.List;
@Service
public class boardService {
@Autowired private boardMapper bm;
// 게시글 목록 불러오기
public List<boardVO> getBoardList(){
return bm.getBoardList();
}
// 게시글 작성
public void postWrite(boardVO bv){
bm.postWrite(bv);
}
// 게시글 상세보기
public boardVO postView(int po_num){
return bm.postView(po_num);
}
// 게시글 삭제
public void postDelete(int po_num){
bm.postDelete(po_num);
}
public String getPostNum() {
return bm.getPostNum();
}
}
|
package com.restapi.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
/**
* This class represents a Digital Newspaper entity
* @author analia.hojman
*/
@Entity
public class DigitalNewspaper extends Informative {
/**
* Default constructor used by JPA
*/
public DigitalNewspaper() {}
/**
* DigitalNewspaper Constructor
* @param name
* @param editorialName
* @param date
* @param posts
*/
public DigitalNewspaper(String name, String editorialName, Date date,
List<Post> posts) {
super(name, editorialName, date, posts);
}
/**
* This method simulates how a digital newspaper is printed
*/
@Override
public void print() {
System.out.println("--------------------------");
System.out.println("I am " + this.getName() + ", a Digital Newspaper");
System.out.println("--------------------------");
}
}
|
package com.smxknife.energy.services.user.core.service;
import com.smxknife.energy.services.user.core.dao.UserDao;
import com.smxknife.energy.services.user.spi.domain.User;
import com.smxknife.energy.services.user.spi.service.UserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author smxknife
* 2021/5/19
*/
@DubboService(version = "v1", interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void create(User user) {
userDao.create(user);
}
@Override
public List<User> getAll() {
return userDao.getAll();
}
@Override
public List<User> getByAccountIn(List<String> accounts) {
return userDao.getByAccountIn(accounts);
}
}
|
package com.techlabs.accounttest;
import com.techlabs.account.Account;
public class AccountToStringTest {
public static void main(String[] args) {
Account a = new Account("101", "sonam", 5000);
try {
a.withdraw(4501);
} catch (Exception e) {
System.out.println(e.getMessage()); // polymorphic behaviour
}
printInfo(a);
// System.out.println(a);
// System.out.println(" ");
// System.out.println(a.toString());
}
public static void printInfo(Account a) {
System.out.println("Account no is:" + a.getAccountNo());
System.out.println("Account name is:" + a.getAccountName());
System.out.println("Account balance is " + a.getBalance());
}
}
|
package gr.james.influence.game;
public class GameDefinition {
private int actions;
private double budget;
private long execution;
private double precision;
public GameDefinition(int actions, double budget, long execution, double precision) {
this.actions = actions;
this.budget = budget;
this.execution = execution;
this.precision = precision;
}
public int getActions() {
return this.actions;
}
public double getBudget() {
return this.budget;
}
public long getExecution() {
return this.execution;
}
public double getPrecision() {
return this.precision;
}
@Override
public String toString() {
return String.format("{actions=%d, budget=%.2f, execution=%d, precision=%e}",
actions,
budget,
execution,
precision
);
}
}
|
package cn.omsfuk.library.web.config;
import cn.omsfuk.library.web.dao.UserDAO;
import cn.omsfuk.library.web.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserSecurityService implements UserDetailsService {
@Autowired
private UserDAO userDAO;
private Map<String, GrantedAuthority> authorityMap = new HashMap<>();
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
cn.omsfuk.library.web.model.User user = userDAO.selectUserByUsername(s);
SessionUtil.setAttribute("user", user);
return new User(user.getUsername(), user.getPassword(), resolveAuthoirity(user.getRoles()));
}
private List<GrantedAuthority> resolveAuthoirity(String roles) {
List<GrantedAuthority> authorities = new ArrayList<>(2);
for (String role : roles.split(",")) {
if (role != null && role.length() != 0) {
GrantedAuthority authority = authorityMap.get(role);
if (authority == null) {
authority = new SimpleGrantedAuthority(role);
authorityMap.put(role, authority);
}
authorities.add(authority);
}
}
return authorities;
}
}
|
/*
* 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.forsrc.utils;
import javax.crypto.*;
import org.apache.commons.codec.binary.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.*;
/**
* The type My rsa 2 utils.
*/
public final class MyRsa2Utils {
private static final String CHAR_SET = "UTF-8";
/**
* Decrypt string.
*
* @param rsaKey the rsa key
* @param cipherText the cipher text
* @return the string
* @throws RsaException the rsa exception
*/
public static String decrypt(RsaKey rsaKey, String cipherText) throws RsaException {
return decrypt(rsaKey.getKeyPair().getPrivate(), cipherText);
}
/**
* Decrypt string.
*
* @param privateKey the private key
* @param cipherText the cipher text
* @return the string
* @throws RsaException the rsa exception
*/
public static String decrypt(PrivateKey privateKey, String cipherText) throws RsaException {
Cipher cipher = null;
try {
cipher = Cipher.getInstance(RsaKey.ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException e) {
throw new RsaException(e);
} catch (NoSuchPaddingException e) {
throw new RsaException(e);
}
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
} catch (InvalidKeyException e) {
throw new RsaException(e);
}
byte[] input = null;
try {
input = new Base64().decode(cipherText);
} catch (Exception e) {
throw new RsaException(e);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
try {
int blockSize = cipher.getBlockSize();
blockSize = blockSize == 0 ? 117 : blockSize;
int i = 0;
int start = 0;
do {
start = i++ * blockSize;
baos.write(cipher.doFinal(input, start, blockSize));
} while (input.length - start - blockSize > 0);
} catch (IllegalBlockSizeException e) {
throw new RsaException(e);
} catch (BadPaddingException e) {
throw new RsaException(e);
} catch (IOException e) {
throw new RsaException(e);
}
return new String(baos.toByteArray());
}
/**
* Encrypt string.
*
* @param rsaKey the rsa key
* @param plaintext the plaintext
* @return the string
* @throws RsaException the rsa exception
*/
public static String encrypt(RsaKey rsaKey, String plaintext) throws RsaException {
return encrypt(rsaKey.getKeyPair().getPublic(), plaintext);
}
/**
* Encrypt string.
*
* @param publicKey the public key
* @param plaintext the plaintext
* @return the string
* @throws RsaException the rsa exception
*/
public static String encrypt(PublicKey publicKey, String plaintext) throws RsaException {
Cipher cipher = null;
try {
cipher = Cipher.getInstance(RsaKey.ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException e) {
throw new RsaException(e);
} catch (NoSuchPaddingException e) {
throw new RsaException(e);
}
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
throw new RsaException(e);
}
byte[] data = plaintext.getBytes();
int blockSize = cipher.getBlockSize();
blockSize = blockSize == 0 ? 117 : blockSize;
int outputSize = cipher.getOutputSize(data.length);
int count = (int) Math.ceil(data.length / blockSize) + 1;
byte[] output = new byte[outputSize * count];
try {
int i = 0;
int start = 0;
int outputStart = 0;
do {
start = i * blockSize;
outputStart = i * outputSize;
if (data.length - start >= blockSize) {
cipher.doFinal(data, start, blockSize, output, outputStart);
} else {
cipher.doFinal(data, start, data.length - start, output, outputStart);
}
i++;
} while (data.length - start - blockSize >= 0);
} catch (IllegalBlockSizeException e) {
throw new RsaException(e);
} catch (BadPaddingException e) {
throw new RsaException(e);
} catch (ShortBufferException e) {
throw new RsaException(e);
}
return new String(new Base64().encode(output));
}
/**
* Gets public key.
*
* @param key the key
* @return the public key
* @throws RsaException the rsa exception
*/
public static PublicKey getPublicKey(String key) throws RsaException {
byte[] keyBytes;
try {
keyBytes = (new Base64()).decode(key);
} catch (Exception e) {
throw new RsaException(e);
}
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = null;
try {
keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new RsaException(e);
}
PublicKey publicKey = null;
try {
publicKey = keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException e) {
throw new RsaException(e);
}
return publicKey;
}
/**
* Gets private key.
*
* @param key the key
* @return the private key
* @throws RsaException the rsa exception
*/
public static PrivateKey getPrivateKey(String key) throws RsaException {
byte[] keyBytes;
try {
keyBytes = (new Base64()).decode(key);
} catch (Exception e) {
throw new RsaException(e);
}
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = null;
try {
keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new RsaException(e);
}
PrivateKey privateKey = null;
try {
privateKey = keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
throw new RsaException(e);
}
return privateKey;
}
/**
* Gets rsa key.
*
* @return the rsa key
*/
public static RsaKey getRsaKey() {
return new RsaKey();
}
/**
* The type Rsa key.
*/
public static class RsaKey {
/**
* The constant KEY_SIZE.
*/
public static final int KEY_SIZE = 1024;
/**
* The constant ALGORITHM.
*/
public static final String ALGORITHM = "RSA";
private static Cipher cipher;
private static KeyFactory keyFactory;
private KeyPair keyPair;
/**
* Instantiates a new Rsa key.
*/
public RsaKey() {
try {
cipher = Cipher.getInstance(ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
keyFactory = KeyFactory.getInstance(ALGORITHM);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom()); // 1024 used for normal
this.keyPair = keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Gets key pair.
*
* @return the key pair
*/
public KeyPair getKeyPair() {
return keyPair;
}
/**
* Sets key pair.
*
* @param keyPair the key pair
*/
public void setKeyPair(KeyPair keyPair) {
this.keyPair = keyPair;
}
/**
* Gets rsa public key spec.
*
* @return the rsa public key spec
* @throws RsaException the rsa exception
*/
public RSAPublicKeySpec getRSAPublicKeySpec() throws RsaException {
try {
return keyFactory.getKeySpec(this.getKeyPair().getPublic(), RSAPublicKeySpec.class);
} catch (InvalidKeySpecException e) {
throw new RsaException(e);
}
}
/**
* Gets rsa private key spec.
*
* @return the rsa private key spec
* @throws RsaException the rsa exception
*/
public RSAPrivateKeySpec getRSAPrivateKeySpec() throws RsaException {
try {
return keyFactory.getKeySpec(this.getKeyPair().getPrivate(), RSAPrivateKeySpec.class);
} catch (InvalidKeySpecException e) {
throw new RsaException(e);
}
}
}
/**
* The type Rsa exception.
*/
public static class RsaException extends IOException {
/**
* Instantiates a new Rsa exception.
*
* @param e the e
*/
public RsaException(Exception e) {
super(e);
}
/**
* Instantiates a new Rsa exception.
*
* @param e the e
*/
public RsaException(String e) {
super(e);
}
}
}
|
package com.jk.jkproject.ui.inter;
import com.jk.jkproject.ui.entity.LiveChestInfo;
public interface LiveChestGiftAnimListener extends LiveRelease {
void addTimes(LiveChestInfo paramLiveChestInfo);
String getAnimate();
boolean isRunning();
void setLiveGiftActionListener(LiveGiftActionListener paramLiveGiftActionListener);
void startAnim(LiveChestInfo paramLiveChestInfo);
}
|
package p2.control;
import java.util.*;
import p2.logic.game.*;
/** Class "Controller":
*
* Controls the execution of the game.
* Receives the commands from the user and executes the corresponding actions, calls for the updates of the board and prints the game.
*
* */
public class Controller {
private Game game;
private Scanner in;
private Boolean print;
private Boolean exit;
private Boolean update;
private Command command;
private GamePrinter GPrinter;
/** Receives the game and assigns the default values for the control variables of the game */
public Controller(Game game) {
this.game = game;
this.in = new Scanner(System.in);
this.print = true;
this.exit = false;
this.update = true;
this.GPrinter = new RelasePrinter();
}
/** Receives the command input, calls for the parse of the command and checks if it is a valid input. Then executes the corresponding actions
* May or may not print & update the game
* Checks if the game keeps going or is ended
* */
public void Run () {
String input;
String[] command;
this.game.update();
printGame(this.game);
do {
System.out.print("Command > ");
this.print = true;
this.update = true;
input = in.nextLine();
command = input.toLowerCase().split(" ");
this.command = CommandParser.parseCommand(command, this);
if (this.command != null) {
this.command.execute(this.game, this);
if (this.update)
this.game.update();
if (this.print)
printGame(this.game);
if (!exit)
exit = game.endGame();
}
else {
System.out.println("[ERROR]: Command not recognised, try again.");
}
} while (!exit);
}
/** Calls for the game print */
public void printGame(Game game) {
this.GPrinter.printGame(this.game);
}
/** Avoids printing the game this turn */
public void setNoPrintGameState() {
this.print = false;
}
/** Avoids updating the game this turn */
public void setNoUpdateGameState() {
this.update = false;
}
/** Receives the desired printing mode and assigns the new GamePrinter */
public void setPrintMode(String mode) {
switch (mode) {
case "debug": case "d": this.GPrinter = new DebugPrinter(); break;
case "relase": case "r": this.GPrinter = new RelasePrinter(); break;
default: this.GPrinter = new RelasePrinter(); break;
}
}
/** Ends the game */
public void exit () {
this.exit = true;
}
}
|
package com.shagaba.kickstarter.auth.core.repository.security.account;
import org.junit.Assert;
import org.junit.Test;
import com.shagaba.kickstarter.auth.core.domain.security.account.UserAccount;
import com.shagaba.kickstarter.auth.core.repository.AbstractRepositoryTest;
public class UserAccountRepositoryTest extends AbstractRepositoryTest<UserAccount, String> {
@Test
public void getUserAccountByUsername() {
UserAccountRepository userAccountRepository = (UserAccountRepository) repository;
UserAccount entity = tstEntities.get(2);
UserAccount got = userAccountRepository.getUserAccountByUsername(entity.getUsername());
Assert.assertNotNull(got);
Assert.assertEquals(entity, got);
}
}
|
package com.example.disastermanagement.Files;
public class Resource {
String amount ,description,item,name,lat,lon,phone,area,datetime;
public Resource(String amount, String description, String item, String name, String lat, String lon, String phone, String area,String datetime) {
this.amount = amount;
this.description = description;
this.item = item;
this.name = name;
this.lat = lat;
this.lon = lon;
this.phone = phone;
this.area = area;
this.datetime=datetime;
}
public String getArea() {
return area;
}
public String getAmount() {
return amount;
}
public String getDescription() {
return description;
}
public String getItem() {
return item;
}
public String getName() {
return name;
}
public String getLat() {
return lat;
}
public String getDatetime() {
return datetime;
}
public String getLon() {
return lon;
}
public String getPhone() {
return phone;
}
@Override
public String toString() {
return area+amount+description+item+name+lat+lon+phone+" "+datetime;
}
}
|
/**********************************************************************************************
* Distributed computing spring 2014 group 4 //Alex Ryder//Nick Champagne//Hue Moua//
* //Daniel Gedge//Corey Jones//
* Project 2 Peer2Peer client/server
***********************************************************************************************/
/**********************************************************************************************
* This file is the representation of a client node inside the server. it keeps track of the
* IP address and the TCP server port it is currently using to send files.
***********************************************************************************************/
public class node
{
String IPaddress;
int port;
}
|
package NiuKe;
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String s = in.nextLine();
int legth = s.length();
if (legth>20||legth==0) {
System.out.println("ERROR!");
}
else {
char[] arr = s.toCharArray();
String result = "";
for (int i = 0; i < arr.length; i++) {
char ch = arr[i];
if (ch>='0'&&ch<='9'||ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') {
if (i%2==0) {
result+=ch;
}
}else {
result = "ERROR!";
break;
}
}
System.out.println(result);
}
}
in.close();
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_4256_트리 {
private static int T,N;
private static int[] pre, in;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
T = Integer.parseInt(br.readLine());
for (int t = 0; t < T; t++) {
N = Integer.parseInt(br.readLine());
pre = new int[N];
in = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
pre[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
in[i] = Integer.parseInt(st.nextToken());
}
post(0,N,0);
System.out.println();
}
}
private static void post(int start, int end,int d) {
for (int i = start; i < end; i++) {
// 만약 현재 위치의 루트랑 같은 중위순회를 찾는ㄷ면
if(pre[d] == in[i]) {
// 시작점부터 ~ i까지, 해당 트리의 루트 idx
post(start, i , d+1);
// i+1부터 ~끝점까지, 해당 트리의 루트 idx
post(i+1, end , d+(i-start)+1);
System.out.print(pre[d] + " ");
}
}
}
}
|
package com.example.pangrett.astroweather.data;
import org.json.JSONObject;
public class Condition implements JSONPopulator {
private String code;
private String temperature;
private String description;
private String date;
@Override
public void populate(JSONObject data) {
this.code = data.optString("code");
this.temperature = data.optString("temp");
this.description = data.optString("text");
this.date = data.optString("date");
}
public String getDate() {
return date;
}
public String getCode() {
return code;
}
public String getTemperature() {
return temperature;
}
public String getDescription() {
return description;
}
}
|
package com.andhikapanjiprasetyo.caltyfarm;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class DaftarStatusSapiActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edtID_Sapi, edtT_Lahir, edtUmur, edtT_Datang, edtT_Keluar, edtTanda, edtBB, edtU_Bunting, edtP_Lahir, edtS_Vaksin,
edtRiwayat, edtTemperatur, edtTonus, edtInseminasi, edtPengobatan, edtLokasi;
private Button btnUpdateSapi, btnHapusSapi;
private String id_sapi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daftar_status_sapi);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.daftar_sapi));
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PrefManager prefManager = new PrefManager(getApplicationContext());
prefManager.setFirstTimeLaunch(true);
startActivity(new Intent(DaftarStatusSapiActivity.this, BerandaActivity.class));
finish();
}
});
Intent intent = getIntent();
id_sapi = intent.getStringExtra(Konfigurasi.S_ID_SAPI);
//Inisialisasi dari View
edtID_Sapi = findViewById(R.id.edtIDSapi);
edtT_Lahir = findViewById(R.id.edtTandaSapi);
edtUmur = findViewById(R.id.edtUmur);
edtT_Datang = findViewById(R.id.edtTanggalDatang);
edtT_Keluar= findViewById(R.id.edtTanggalKeluar);
edtTanda = findViewById(R.id.edtTandaSapi);
edtBB = findViewById(R.id.edtBB);
edtU_Bunting= findViewById(R.id.edtUmurBunting);
edtP_Lahir = findViewById(R.id.edtPerkLahir);
edtS_Vaksin = findViewById(R.id.edtStatusVaksin);
edtRiwayat = findViewById(R.id.edtRiwayat);
edtTemperatur = findViewById(R.id.edtTemperatur);
edtTonus = findViewById(R.id.edtTonus);
edtInseminasi = findViewById(R.id.edtInseminasi);
edtPengobatan = findViewById(R.id.edtPengobatan);
edtLokasi = findViewById(R.id.edtLokasi);
btnUpdateSapi= findViewById(R.id.btnUpdateSapi);
btnHapusSapi= findViewById(R.id.btnHapusSapi);
btnUpdateSapi.setOnClickListener(this);
btnHapusSapi.setOnClickListener(this);
edtID_Sapi.setText(id_sapi);
getSapi();
}
private void getSapi() {
class GetSapi extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DaftarStatusSapiActivity.this, "Mengambil Data...", "Tunggu...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
tampilSapi(s);
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Konfigurasi.URL_GET_SAPI, id_sapi);
return s;
}
}
GetSapi gs = new GetSapi();
gs.execute();
}
private void tampilSapi(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Konfigurasi.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String tgl_lahir = c.getString(Konfigurasi.TAG_TGL_LAHIR);
String j_breed = c.getString(Konfigurasi.TAG_J_BREED);
String j_kelamin = c.getString(Konfigurasi.TAG_J_KELAMIN);
String umur = c.getString(Konfigurasi.TAG_UMUR);
String tgl_datang = c.getString(Konfigurasi.TAG_TGL_DATANG);
String tgl_keluar = c.getString(Konfigurasi.TAG_TGL_KELUAR);
String tanda_sapi = c.getString(Konfigurasi.TAG_TANDA_SAPI);
String berat_badan = c.getString(Konfigurasi.TAG_BERAT_BADAN);
String u_bunting = c.getString(Konfigurasi.TAG_U_BUNTING);
String p_lahir = c.getString(Konfigurasi.TAG_P_LAHIR);
String status_vaksin = c.getString(Konfigurasi.TAG_STATUS_VAKSIN);
String o_cacing = c.getString(Konfigurasi.TAG_O_CACING);
String riwayat_kasus = c.getString(Konfigurasi.TAG_RIWAYAT_KASUS);
String temperatur = c.getString(Konfigurasi.TAG_TEMPERATUR);
String tonus_rumen = c.getString(Konfigurasi.TAG_TONUS_RUMEN);
String inseminasi = c.getString(Konfigurasi.TAG_INSEMINASI);
String pengobatan = c.getString(Konfigurasi.TAG_PENGOBATAN);
String lokasi = c.getString(Konfigurasi.TAG_LOKASI);
edtT_Lahir.setText(tgl_lahir);
edtUmur.setText(umur);
edtT_Datang.setText(tgl_datang);
edtT_Keluar.setText(tgl_keluar);
edtTanda.setText(tanda_sapi);
edtBB.setText(berat_badan);
edtU_Bunting.setText(u_bunting);
edtP_Lahir.setText(p_lahir);
edtS_Vaksin.setText(status_vaksin);
edtRiwayat.setText(riwayat_kasus);
edtTemperatur.setText(temperatur);
edtTonus.setText(tonus_rumen);
edtInseminasi.setText(inseminasi);
edtPengobatan.setText(pengobatan);
edtLokasi.setText(lokasi);
}catch (JSONException e)
{
e.printStackTrace();
}
}
private void updateSapi() {
final String tgl_lahir = edtT_Lahir.getText().toString().trim();
final String umur = edtUmur.getText().toString().trim();
final String tgl_datang = edtT_Datang.getText().toString().trim();
final String tgl_keluar = edtT_Keluar.getText().toString().trim();
final String tanda_sapi = edtTanda.getText().toString().trim();
final String berat_badan = edtBB.getText().toString().trim();
final String u_bunting = edtU_Bunting.getText().toString().trim();
final String p_lahir = edtP_Lahir.getText().toString().trim();
final String status_vaksin = edtS_Vaksin.getText().toString().trim();
final String riwayat_kasus = edtRiwayat.getText().toString().trim();
final String temperatur = edtTemperatur.getText().toString().trim();
final String tonus_rumen = edtTonus.getText().toString().trim();
final String inseminasi = edtInseminasi.getText().toString().trim();
final String pengobatan = edtPengobatan.getText().toString().trim();
final String lokasi = edtLokasi.getText().toString().trim();
class UpdateSapi extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DaftarStatusSapiActivity.this, "Updating...", "Tunggu...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(DaftarStatusSapiActivity.this, s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(Konfigurasi.KEY_ID_SAPI, id_sapi);
hashMap.put(Konfigurasi.KEY_TGL_LAHIR, tgl_lahir);
hashMap.put(Konfigurasi.KEY_UMUR, umur);
hashMap.put(Konfigurasi.KEY_TGL_DATANG, tgl_datang);
hashMap.put(Konfigurasi.KEY_TGL_KELUAR, tgl_keluar);
hashMap.put(Konfigurasi.KEY_TANDA_SAPI, tanda_sapi);
hashMap.put(Konfigurasi.KEY_BERAT_BADAN, berat_badan);
hashMap.put(Konfigurasi.KEY_U_BUNTING, u_bunting);
hashMap.put(Konfigurasi.KEY_P_LAHIR, p_lahir);
hashMap.put(Konfigurasi.KEY_STATUS_VAKSIN, status_vaksin);
hashMap.put(Konfigurasi.KEY_RIWAYAT_KASUS, riwayat_kasus);
hashMap.put(Konfigurasi.KEY_TEMPERATUR, temperatur);
hashMap.put(Konfigurasi.KEY_TONUS_RUMEN, tonus_rumen);
hashMap.put(Konfigurasi.KEY_INSEMINASI, inseminasi);
hashMap.put(Konfigurasi.KEY_PENGOBATAN, pengobatan);
hashMap.put(Konfigurasi.KEY_LOKASI, lokasi);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Konfigurasi.URL_UPDATE_SAPI, hashMap);
return s;
}
}
UpdateSapi us = new UpdateSapi();
us.execute();
}
private void hapusSapi() {
class HapusSapi extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DaftarStatusSapiActivity.this, "Updating...", "Tunggu...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(DaftarStatusSapiActivity.this, s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Konfigurasi.URL_DELETE_SAPI, id_sapi);
return s;
}
}
HapusSapi hs = new HapusSapi();
hs.execute();
}
private void konfirmasiHapusSapi() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Apakah kamu yakin ingin menghapus data sapi ini?");
alertDialogBuilder.setPositiveButton("Ya",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
hapusSapi();
startActivity(new Intent(DaftarStatusSapiActivity.this, DaftarSapiActivity.class));
}
});
alertDialogBuilder.setNegativeButton("Tidak",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@Override
public void onClick(View v) {
if (v == btnUpdateSapi) {
updateSapi();
}
if (v == btnHapusSapi) {
konfirmasiHapusSapi();
}
}
}
|
package pixel.bus.model;
import pixel.bus.model.enu.GameSpeedEnum;
/**
* Created by vanley on 15/06/2017.
*/
public class GameData {
private CityLevel cityLevel;
private GameSpeedEnum gameSpeed = GameSpeedEnum.NORMAL;
private int tick = 0;
public GameData(CityLevel cityLevel) {
this.cityLevel = cityLevel;
}
public GameData(
CityLevel cityLevel,
GameSpeedEnum gameSpeed,
int tick) {
this.cityLevel = cityLevel;
this.gameSpeed = gameSpeed;
this.tick = tick;
}
public int getTick() {
return tick;
}
public void setTick(int tick) {
this.tick = tick;
}
public GameSpeedEnum getGameSpeed() {
return gameSpeed;
}
public void setGameSpeed(GameSpeedEnum gameSpeed) {
this.gameSpeed = gameSpeed;
}
public CityLevel getCityLevel() {
return cityLevel;
}
public void setCityLevel(CityLevel cityLevel) {
this.cityLevel = cityLevel;
}
}
|
package com.s24.redjob.worker;
import java.util.Set;
import com.s24.redjob.Dao;
/**
* DAO for worker stats.
*/
public interface WorkerDao extends Dao {
/**
* Ping Redis.
*/
void ping();
/**
* Update worker state.
*
* @param name
* Name of worker.
* @param state
* State of worker.
*/
void state(String name, WorkerState state);
/**
* Stop of worker.
*
* @param name
* Name of worker.
*/
void stop(String name);
/**
* Job has been successfully been processed.
*
* @param name
* Name of worker.
*/
void success(String name);
/**
* Job execution failed.
*
* @param name
* Name of worker.
*/
void failure(String name);
/**
* Names of all active workers.
*/
Set<String> names();
}
|
package com.icleveret.recipes.controller;
import com.icleveret.recipes.component.SessionHolder;
import com.icleveret.recipes.service.ImageService;
import com.icleveret.recipes.viewmodel.RecipeView;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class ImageController {
private ImageService imageService;
private SessionFactory sessionFactory;
static final Logger logger = LogManager.getLogger("MyLogger");
@Autowired
public ImageController(ImageService imageService, SessionFactory sessionFactory) {
this.imageService = imageService;
this.sessionFactory = sessionFactory;
}
@ModelAttribute("recipeView")
public RecipeView getRecipeView() {
return new RecipeView();
}
@RequestMapping(value = "/images/{imageid}", method = {RequestMethod.GET, RequestMethod.HEAD},
produces = "text/plain")
@ResponseBody
public byte[] findImage(@PathVariable("imageid") Long imageId) {
logger.info("in meth findImage");
try (SessionHolder sessionHolder = SessionHolder.open(sessionFactory)) {
return imageService.findOne(imageId, sessionHolder.getSessionContainer()).getData();
}
}
}
|
package com.shopify.api.lotte.delivery;
import lombok.Data;
/**
* @author SOLUGATE
* 롯데 택배 API 연동 DATA
*/
@Data
public class LotteInvnoData {
private long invNo; //운송장번호
private String masterCode; // master code - 롯데에는 "ordNo" 로 전송됨 - 주문번호
}
|
package com.tfxk.framework.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.tfxk.framework.R;
import com.tfxk.framework.utils.CommonUtils;
import com.tfxk.framework.utils.DialogUtils;
/**
* Created by chenchunpeng on 2017/5/13.
*/
public class NetworkStateRecceiver extends BroadcastReceiver {
private ConnectivityManager connectivityManager;
private NetworkInfo info;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//System.out.println("网络状态已经改变");
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String name = info.getTypeName();
// if (name.equals("WIFI")) {
// //System.out.println("WIFI");
//
//// editor.putString("netType", "wifi");
//// editor.commit();
//
// } else {
//
// editor.putString("netType", "3g");
// editor.commit();
//
// }
// EventBus.getDefault().post(new MessageEventNet(true));
} else {
if (CommonUtils.isAppRunningForeground(context))
DialogUtils.showNoNetWorkTipsDialog(context, R.mipmap.ic_launcher);
// EventBus.getDefault().post(new MessageEventNet(false));
}
}
}
}
|
package com.fancy.ownparking.ui.base.callbacks;
public interface SelectItemCallback<T> {
void onItemSelected(T item);
}
|
package com.company.Arrays;
import javax.swing.*;
import java.util.Arrays;
public class ArraysEx3 {
public static void main(String[] args) {
String numberInString = JOptionPane.showInputDialog("Podaj liczbę:");
int numberFromUser = Integer.valueOf(numberInString);
// System.out.println(Arrays.toString());
// evenNumber(numberFromUser);
evenNumberWhile(numberFromUser);
}
/* public static void evenNumber (int numberFromUser) {
// String numberInString = JOptionPane.showInputDialog("Podaj liczbę:");
// int numberFromUser = Integer.valueOf(numberInString);
int[] evenNumbersArray = new int[numberFromUser];
for (int i = 1; i <= numberFromUser; i++) {
evenNumbersArray[i - 1] = i * 2;
}
System.out.println(Arrays.toString(evenNumbersArray));
// return evenNumbersArray[];
}*/
public static void evenNumberWhile(int numberFromUser){
int[] evenNumbersArray = new int[numberFromUser];
int i =1;
while(i<=numberFromUser){
evenNumbersArray[i-1]=i*2;
i++;
}
System.out.println(Arrays.toString(evenNumbersArray));
}
}
//}
|
package ninja.littleed.util;
import info.clearthought.layout.TableLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
* Demo for the transference of
* @author LittleEd
*
*/
@SuppressWarnings("serial")
public class ClipboardExplorer extends JPanel implements ClipboardOwner {
private JComboBox<MergeField> mergeFields;
private JButton exportClipboard;
private JList<MergeField> list;
public ClipboardExplorer() {
mergeFields = new JComboBox<MergeField>(MergeField.values());
exportClipboard = new JButton("Copy to Clipboard");
exportClipboard.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exportClipboard();
}
});
MergeFieldTransferHandler handler = new MergeFieldTransferHandler();
list = new JList<MergeField>(MergeField.values());
list.setTransferHandler(handler);
list.setDragEnabled(true);
setLayout(new TableLayout(new double[][] {
{ TableLayout.FILL, TableLayout.PREFERRED,
TableLayout.PREFERRED, TableLayout.PREFERRED,
TableLayout.FILL },
{ TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL } }));
add(new JLabel("Merge Field: "), "1,1");
add(mergeFields, "2,1");
add(exportClipboard, "3,1");
add(list, "2,3");
}
public void exportClipboard() {
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
MergeFieldTransferable wd = new MergeFieldTransferable((MergeField)mergeFields.getSelectedItem());
c.setContents(wd, this);
}
public static void main(String[] args) {
// Set up components
JFrame testFrame = new JFrame();
testFrame.setAlwaysOnTop(true);
testFrame.setSize(500, 300);
testFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
testFrame.add(new ClipboardExplorer());
testFrame.setVisible(true);
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("AWWW NOOO! I've lost ownership! ... What does that mean?");
}
}
|
package com.example.firenotes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class showParticularNotes extends AppCompatActivity {
EditText title_tv;
EditText body_tv;
ImageButton delete_btn;
ImageButton update_btn;
int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_particular_notes);
id = getIntent().getIntExtra("id",0);
String title = getIntent().getStringExtra("TITLE");
String body = getIntent().getStringExtra("BODY");
title_tv = (EditText) findViewById(R.id.tv_title);
body_tv = (EditText)findViewById(R.id.tv_body);
delete_btn = (ImageButton)findViewById(R.id.delete_btn);
update_btn = (ImageButton)findViewById(R.id.update_btn);
title_tv.setText(title);
body_tv.setText(body);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setTitle(title);
delete_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(showParticularNotes.this);
builder.setTitle("Do you want to delete ?");
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DBHandler handler = new DBHandler(getApplicationContext());
handler.deleteNote(id);
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotesModel model = new NotesModel();
model.setId(id);
model.setTitle(title_tv.getText().toString());
model.setBody(body_tv.getText().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(showParticularNotes.this);
builder.setTitle("Do you want to update ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DBHandler handler = new DBHandler(getApplicationContext());
handler.updateNote(model);
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
});
}
}
|
package com.tencent.mm.plugin.remittance.bankcard.ui;
import android.widget.Toast;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.remittance.bankcard.a.h;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.h$a;
class BankRemitSelectBankUI$3 implements h$a {
final /* synthetic */ BankRemitSelectBankUI mwu;
final /* synthetic */ h mwv;
BankRemitSelectBankUI$3(BankRemitSelectBankUI bankRemitSelectBankUI, h hVar) {
this.mwu = bankRemitSelectBankUI;
this.mwv = hVar;
}
public final void g(int i, int i2, String str, l lVar) {
x.e("MicroMsg.BankRemitSelectBankUI", "response error: %s, %s", new Object[]{Integer.valueOf(this.mwv.mtZ.hUm), this.mwv.mtZ.hUn});
if (!bi.oW(this.mwv.mtZ.hUn)) {
Toast.makeText(this.mwu, this.mwv.mtZ.hUn, 1).show();
}
}
}
|
package interviewbit.string;
import java.util.ArrayList;
public class Zigzag_String {
public String convert(String a, int b) {
if(b==1||b==0){
return a;
}
StringBuilder r = new StringBuilder();
ArrayList<StringBuilder> s = new ArrayList<StringBuilder>();
for (int i = 0; i < b; i++) {
s.add(new StringBuilder());
}
int i = 0, l = 0;
boolean direction = true;
while (l < a.length()) {
s.get(i).append(a.charAt(l));
if (direction == true) {
i++;
if (i == s.size()) {
i -= 2;
direction = false;
}
} else {
i--;
if (i == -1) {
i = 1;
direction = true;
}
}
l++;
}
for (i = 0; i < b; i++) {
r.append(s.get(i));
}
System.out.println(s);
return r.toString();
}
}
|
/* Marlin Jayasekera - 40033721
* COMP 249
* Assignment 1
* February 1st, 2017
*/
/**
* Driver class, calls play() method to play Battleship
*
* @author Marlin Jayasekera
*
*/
public class Battleship extends Tools{
public static void main(String[] args) {
play();
}
}
|
/**
* Created by user on 03/05/2017.
*/
public interface Collidable {
/**
*get the borders of the Collidable.
* @return this rectangle.
*/
Rectangle getCollisionRectangle();
/**
* changing the velocity according to the hit.
* @param hitter the hitting ball.
* @param collisionPoint the point that the collision took place in.
* @param currentVelocity the current velocity.
* @return the new velocity.
*/
Velocity hit(Ball hitter, Point collisionPoint, Velocity currentVelocity);
}
|
package pers.pbyang.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pers.pbyang.connection.DAOFactory;
import pers.pbyang.entity.Member;
public class UserUpdateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String memid = request.getParameter("memid");
int id = Integer.parseInt(memid);
String birthday = request.getParameter("birthday");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
String department = request.getParameter("department");
String position = request.getParameter("position");
String despition = request.getParameter("despition");
String password = request.getParameter("password");
String desptition = request.getParameter("desptition");
System.out.println("--------------------------"+password);
System.out.println("--------------------------"+birthday);
System.out.println(department);
Member mem = new Member();
mem.setBirthday(birthday);
mem.setPhone(phone);
mem.setEmail(email);
mem.setDepartment(department);
mem.setPosition(position);
mem.setDespition(despition);
mem.setPassword(password);
mem.setDespition(desptition);
try {
DAOFactory.getmemberDAOInstance().update1(mem, id);
response.setContentType("text/html;charset=GBK");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.println("<script>alert('修改成功!')</script>");
out.println("<script>window.history.go(-1)</script>");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.bean.AppVersion;
import com.openkm.bean.ExtendedAttributes;
import com.openkm.bean.Folder;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.DatabaseException;
import com.openkm.core.LockException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.module.ModuleManager;
import com.openkm.module.RepositoryModule;
public class OKMRepository implements RepositoryModule {
private static Logger log = LoggerFactory.getLogger(OKMRepository.class);
private static OKMRepository instance = new OKMRepository();
private OKMRepository() {
}
public static OKMRepository getInstance() {
return instance;
}
@Override
public Folder getRootFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getRootFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder rootFolder = rm.getRootFolder(token);
log.debug("getRootFolder: {}", rootFolder);
return rootFolder;
}
@Override
public Folder getTrashFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getTrashFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder trashFolder = rm.getTrashFolder(token);
log.debug("getTrashFolder: {}", trashFolder);
return trashFolder;
}
@Override
public Folder getTrashFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getTrashFolderBase({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder trashFolder = rm.getTrashFolderBase(token);
log.debug("getTrashFolderBase: {}", trashFolder);
return trashFolder;
}
@Override
public Folder getTemplatesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getTemplatesFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder templatesFolder = rm.getTemplatesFolder(token);
log.debug("getTemplatesFolder: {}", templatesFolder);
return templatesFolder;
}
@Override
public Folder getPersonalFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getPersonalFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder personalFolder = rm.getPersonalFolder(token);
log.debug("getPersonalFolder: {}", personalFolder);
return personalFolder;
}
@Override
public Folder getPersonalFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getPersonalFolderBase({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder personalFolder = rm.getPersonalFolderBase(token);
log.debug("getPersonalFolderBase: {}", personalFolder);
return personalFolder;
}
@Override
public Folder getMailFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getMailFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder mailFolder = rm.getMailFolder(token);
log.debug("getMailFolder: {}", mailFolder);
return mailFolder;
}
@Override
public Folder getMailFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getMailFolderBase({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder mailFolder = rm.getMailFolderBase(token);
log.debug("getMailFolderBase: {}", mailFolder);
return mailFolder;
}
@Override
public Folder getThesaurusFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getThesaurusFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder thesaurusFolder = rm.getThesaurusFolder(token);
log.debug("getThesaurusFolder: {}", thesaurusFolder);
return thesaurusFolder;
}
@Override
public Folder getCategoriesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
log.debug("getCategoriesFolder({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
Folder categoriesFolder = rm.getCategoriesFolder(token);
log.debug("getCategoriesFolder: {}", categoriesFolder);
return categoriesFolder;
}
@Override
public void purgeTrash(String token) throws PathNotFoundException, AccessDeniedException, LockException, RepositoryException,
DatabaseException {
log.debug("purgeTrash({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
rm.purgeTrash(token);
log.debug("purgeTrash: void");
}
@Override
public String getUpdateMessage(String token) throws RepositoryException {
log.debug("getUpdateMessage({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
String updateMessage = rm.getUpdateMessage(token);
log.debug("getUpdateMessage: {}", updateMessage);
return updateMessage;
}
@Override
public String getRepositoryUuid(String token) throws RepositoryException {
log.debug("getRepositoryUuid({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
String uuid = rm.getRepositoryUuid(token);
log.debug("getRepositoryUuid: {}", uuid);
return uuid;
}
@Override
public boolean hasNode(String token, String path) throws AccessDeniedException, RepositoryException, DatabaseException {
log.debug("hasNode({})", token, path);
RepositoryModule rm = ModuleManager.getRepositoryModule();
boolean ret = rm.hasNode(token, path);
log.debug("hasNode: {}", ret);
return ret;
}
@Override
public String getNodePath(String token, String uuid) throws AccessDeniedException, PathNotFoundException, RepositoryException,
DatabaseException {
log.debug("getNodePath({}, {})", token, uuid);
RepositoryModule rm = ModuleManager.getRepositoryModule();
String ret = rm.getNodePath(token, uuid);
log.debug("getNodePath: {}", ret);
return ret;
}
@Override
public String getNodeUuid(String token, String path) throws AccessDeniedException, PathNotFoundException, RepositoryException,
DatabaseException {
log.debug("getNodeUuid({}, {})", token, path);
RepositoryModule rm = ModuleManager.getRepositoryModule();
String ret = rm.getNodeUuid(token, path);
log.debug("getNodeUuid: {}", ret);
return ret;
}
public AppVersion getAppVersion(String token) throws AccessDeniedException, RepositoryException, DatabaseException {
log.debug("getAppVersion({})", token);
RepositoryModule rm = ModuleManager.getRepositoryModule();
AppVersion ret = rm.getAppVersion(token);
log.debug("getAppVersion: {}", ret);
return ret;
}
@Override
public void copyAttributes(String token, String srcId, String dstId, ExtendedAttributes extAttr) throws AccessDeniedException,
PathNotFoundException, DatabaseException {
log.debug("copyAttributes({}, {}, {}, {})", new Object[] { token, srcId, dstId, extAttr });
RepositoryModule rm = ModuleManager.getRepositoryModule();
rm.copyAttributes(token, srcId, dstId, extAttr);
log.debug("copyAttributes: void");
}
}
|
package ThreadPool;
import java.util.concurrent.*;
public class 线程池重要参数 {
/*
随着业务增长,线程池是怎么变化的?
(1)corePoolSize常驻核心线程代表一开始就提供这么多线程执行任务
(2)后面再来的任务被放在阻塞队列(BlockingQueue)中,等前面的任务执行完之后才能运行
(3)如果又来了任务,但是这时候阻塞队列都已经满了,那此时会去扩增池子里的线程数,达到maxinumPoolSize,
此时阻塞队列的任务会先进去
(4)线程数扩到最大,而且阻塞队列也满了的情况下,再进来的线程就需要进行某种拒绝策略RejectedExecutionHandler(比如多长时间之后再次提交)
(5)等到业务高峰过去了,如果一定时间(keepAliveTime)内都没有任务进来,线程数又会从达到maxinumPoolSize回到corePoolSize。
*/
public static void main(String[] args) {
//得到内核数
System.out.println(Runtime.getRuntime().availableProcessors());
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,
2L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
// 拒绝策略往往发生在达到最大线程数,并且线程池
// AbortPolicy():直接抛出RejectedExecutionException 异常,阻止程序正常运行
//CallerRunsPolicy(): 会让提交这个任务的线程自己去运行,不会抛出异常,将任务调度回退到调用者
// DiscardPolicy(): 直接丢弃任务,不做任何处理
// DiscardOldestPolicy(): 抛弃BlockQueue中等待最久的
new ThreadPoolExecutor.DiscardPolicy());
try{
for(int i=0; i<100;i++){
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+":执行任务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
|
package cpracticeC;
public class a2
{
public static void main(String[] args)
{
// 배열 생성
String[] cities = { "서울", "부산", "인천", "대전", "대구" };
int[] visitors = { 599, 51, 46, 43, 27 };
for(int i = 0; i < cities.length; i++)
{
/* 3. 결과를 출력 하시오. */
System.out.printf("%s: %d 명\n", cities[i], visitors[i]);
}
}
}
|
public class TestLoops {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
for(int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
int [] numberss = {10, 20, 30, 40, 50};
for(int x : numberss ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
int [] numbersss = {10, 20, 30, 40, 50};
for(int x : numbersss ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
int xx = 10;
while( xx < 20 ) {
System.out.print("value of x : " + xx );
xx++;
System.out.print("\n");
}
int yx = 10;
do {
System.out.print("value of x : " + yx );
yx++;
System.out.print("\n");
}while( yx < 20 );
}
}
|
package com.sysh.util;
/**
* 中文转码
* Created by sjy Cotter on 2018/7/22.
*/
public class UnicodeUtil {
public static String unicodetoString(String unicode){
if(unicode==null||"".equals(unicode)){
return null;
}
StringBuilder sb = new StringBuilder();
int i = -1;
int pos = 0;
while((i=unicode.indexOf("\\u", pos)) != -1){
sb.append(unicode.substring(pos, i));
if(i+5 < unicode.length()){
pos = i+6;
sb.append((char)Integer.parseInt(unicode.substring(i+2, i+6), 16));
}
}
return sb.toString();
}
public static String stringtoUnicode(String string) {
if(string==null||"".equals(string)){
return null;
}
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
public static void main(String[] args) {
String s = stringtoUnicode("中文");
System.out.println("编码:"+s);
String s1 = unicodetoString(s);
System.out.println("解码:"+s1);
}
}
|
package com.funlib.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
/**
* 文件操作类
*
* @author taojianli
*
*/
public class FileUtily {
/**
* 获取SD卡路径
* @return
*/
public static String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
String tmpPath = sdDir.getAbsolutePath();
if(!tmpPath.endsWith(File.separator))
tmpPath += File.separator;
return tmpPath;
}
return null;
}
/**
* 获取应用在SD卡的路径
* @param name
* @return
*/
private static String sAppSDPath = null;
public static String getAppSDPath(){
return sAppSDPath;
}
public static boolean initAppSDPath(String name){
try {
String sdPath = getSDPath();
if(TextUtils.isEmpty(sdPath) == false){
sdPath += name + File.separator;
File file = new File(sdPath);
if(file.exists() == false)
file.mkdir();
sAppSDPath = sdPath;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static boolean saveBytes(String filePath, byte[] data) {
try {
if(data == null) return false;
File file = new File(filePath);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static boolean saveBytes(File file, byte[] data) {
try {
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static byte[] getBytes(String filePath) {
try {
File file = new File(filePath);
if(!file.exists() || !file.canRead()) return null;
FileInputStream inStream = new FileInputStream(file);
byte bytes[] = new byte[inStream.available()];
inStream.read(bytes);
inStream.close();
return bytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static boolean saveObject(String filePath, Object object) {
try {
File file = new File(filePath);
FileOutputStream outStream = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(outStream);
oos.writeObject(object);
oos.flush();
oos.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static boolean saveObject(File file, Object object) {
try {
FileOutputStream outStream = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(outStream);
oos.writeObject(object);
oos.flush();
oos.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 如果sdcard没有mounted,返回false
*
* @param os
* @return
*/
public static Object getObject(String filePath) {
try {
File file = new File(filePath);
if(!file.exists() || !file.canRead()) return null;
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ois.close();
fis.close();
ois = null;
fis = null;
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 创建文件夹
* @param dirPath
* @return
*/
public static boolean mkDir(String dirPath){
File file = new File(dirPath);
if(file.exists() == false){
return file.mkdirs();
}
return true;
}
/**
* 创建临时文件
* @param fielPath
* @return
*/
public static File createTmpFile(Context context){
String rootPath = context.getFilesDir().getAbsolutePath();
if(rootPath.endsWith("/") == false){
rootPath += "/";
}
try {
String tmpPath = rootPath + new Date().hashCode();
File file = new File(tmpPath);
file.createNewFile();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 应用退出时,删除所有临时文件
* @param context
*/
public static void deleteTmpFiles(Context context){
File rootFiles = context.getFilesDir();
File files[] = rootFiles.listFiles();
if(files != null){
int cnt = files.length;
for(int i = 0 ; i < cnt ; ++i){
File tmpFile = files[i];
tmpFile.delete();
}
}
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.jsapi;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import com.tencent.mm.a.m;
import com.tencent.mm.bp.a;
import com.tencent.mm.plugin.game.gamewebview.b.a.b;
import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.ax;
import com.tencent.mm.plugin.websearch.api.c;
import com.tencent.mm.plugin.webview.ui.tools.e;
import com.tencent.mm.pluginsdk.ui.tools.s;
import com.tencent.mm.protocal.JsapiPermissionWrapper;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.widget.MMWebView;
import com.tencent.smtt.sdk.TbsListener$ErrorCode;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class d implements c, b {
private static final int qhj = (com.tencent.mm.compatible.util.d.fS(19) ? 200 : 20);
public com.tencent.mm.plugin.webview.stub.d gcO;
public int pUz;
private List<String> qhA = new LinkedList();
private al qhB = new al(new 26(this), false);
public long qhC = 0;
public MMWebView qhk;
private final List<String> qhl = new LinkedList();
private final LinkedList<i> qhm = new LinkedList();
private ag qhn = null;
Map<String, Object> qho;
public Map<String, Object> qhp;
public boolean qhq = false;
private e qhr;
public boolean qhs = false;
public String qht = "";
private Set<a> qhu;
private final List<String> qhv = new LinkedList();
volatile String qhw = null;
volatile int qhx = 0;
private JSONObject qhy = new JSONObject();
private JSONArray qhz = new JSONArray();
/* renamed from: com.tencent.mm.plugin.webview.ui.tools.jsapi.d$36 */
class AnonymousClass36 implements Runnable {
final /* synthetic */ String fzV;
public AnonymousClass36(String str) {
this.fzV = str;
}
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + this.fzV + ")", null);
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "onGetPoiInfoReturn fail, ex = %s", new Object[]{e.getMessage()});
}
}
}
/* renamed from: com.tencent.mm.plugin.webview.ui.tools.jsapi.d$58 */
class AnonymousClass58 implements Runnable {
final /* synthetic */ String fzV;
public AnonymousClass58(String str) {
this.fzV = str;
}
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + this.fzV + ")", null);
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "onGetMsgProofItems fail, ex = %s", new Object[]{e.getMessage()});
}
}
}
/* renamed from: com.tencent.mm.plugin.webview.ui.tools.jsapi.d$60 */
class AnonymousClass60 implements Runnable {
final /* synthetic */ String qhH;
public AnonymousClass60(String str) {
this.qhH = str;
}
public final void run() {
try {
if (d.this.qhk != null) {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + this.qhH + ")", null);
}
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "eval onMiniProgramData, ex = %s", new Object[]{e});
}
}
}
/* renamed from: com.tencent.mm.plugin.webview.ui.tools.jsapi.d$61 */
class AnonymousClass61 implements Runnable {
final /* synthetic */ String fzV;
public AnonymousClass61(String str) {
this.fzV = str;
}
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + this.fzV + ")", null);
} catch (Exception e) {
}
}
}
/* renamed from: com.tencent.mm.plugin.webview.ui.tools.jsapi.d$6 */
class AnonymousClass6 implements Runnable {
final /* synthetic */ String fzV;
public AnonymousClass6(String str) {
this.fzV = str;
}
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + this.fzV + ")", null);
} catch (Exception e) {
x.w("MicroMsg.JsApiHandler", "onWXDeviceLanStateChange, %s", new Object[]{e.getMessage()});
}
}
}
static /* synthetic */ Map C(String[] strArr) {
int length = strArr == null ? 0 : strArr.length;
if (length == 0) {
return null;
}
Map hashMap = new HashMap();
for (int i = 0; i < length; i++) {
if (hashMap.keySet().contains(strArr[i])) {
hashMap.put(strArr[i], Integer.valueOf(((Integer) hashMap.get(strArr[i])).intValue() + 1));
} else {
hashMap.put(strArr[i], Integer.valueOf(1));
}
}
return hashMap;
}
static /* synthetic */ void c(d dVar) {
if (dVar.qhl.size() <= 0) {
x.i("MicroMsg.JsApiHandler", "dealMsgQueue fail, resultValueList is empty");
return;
}
x.i("MicroMsg.JsApiHandler", "dealMsgQueue, pre msgList = " + dVar.qhm.size());
Collection e = i$a.e((String) dVar.qhl.remove(0), dVar.qhs, dVar.qht);
if (!bi.cX(e)) {
dVar.qhm.addAll(e);
x.i("MicroMsg.JsApiHandler", "now msg list size : %d", new Object[]{Integer.valueOf(dVar.qhm.size())});
}
x.i("MicroMsg.JsApiHandler", "dealMsgQueue, post msgList = " + dVar.qhm.size());
dVar.bXT();
if (dVar.qhn != null) {
dVar.qhn.post(new 63(dVar));
}
}
static /* synthetic */ void l(d dVar) {
do {
} while (dVar.bXU());
}
public d(MMWebView mMWebView, e eVar, Map<String, Object> map, com.tencent.mm.plugin.webview.stub.d dVar, int i) {
this.qhk = mMWebView;
this.qhr = eVar;
this.qhn = new 1(this, Looper.getMainLooper());
this.gcO = dVar;
this.qho = map;
this.pUz = i;
}
public final void bXQ() {
this.qhs = true;
this.qht = bi.Dc(16);
x.i("MicroMsg.JsApiHandler", "js digest verification randomStr = %s", new Object[]{this.qht});
}
public final void bf(String str, boolean z) {
try {
this.gcO.i(str, z, this.pUz);
} catch (Exception e) {
x.w("MicroMsg.JsApiHandler", "addInvokedJsApiFromMenu, ex = " + e);
}
}
@JavascriptInterface
@org.xwalk.core.JavascriptInterface
public final void _sendMessage(String str) {
if (this.qhn != null) {
Message obtain = Message.obtain();
obtain.what = 1;
obtain.obj = str;
this.qhn.sendMessage(obtain);
}
}
@JavascriptInterface
@org.xwalk.core.JavascriptInterface
public final void _getAllHosts(final String str) {
if (str != null) {
this.qhn.post(new Runnable() {
public final void run() {
Map C = d.C(str.split(","));
String a = d.this.RK("hosts");
if (!d.r(a, C)) {
x.e("MicroMsg.JsApiHandler", "failed to write Hosts file");
} else if (d.this.gcO != null && d.this.qhk != null) {
try {
d.this.gcO.z(0, d.this.qhk.getUrl(), a);
} catch (RemoteException e) {
x.e("MicroMsg.JsApiHandler", "uploadFileToCDN error ", new Object[]{e.getMessage()});
}
}
}
});
}
}
@JavascriptInterface
@org.xwalk.core.JavascriptInterface
public final void _getHtmlContent(String str) {
if (str != null) {
this.qhn.post(new 64(this, str));
}
}
public final boolean Dt(String str) {
if (bi.oW(str)) {
return false;
}
return s.fj(str, "weixin://dispatch_message/");
}
public final boolean Du(final String str) {
this.qhk.evaluateJavascript("javascript:WeixinJSBridge._fetchQueue()", new ValueCallback<String>() {
public final /* synthetic */ void onReceiveValue(Object obj) {
String str = (String) obj;
x.i("MicroMsg.JsApiHandler", "handle url %s, re %s", new Object[]{str, str});
}
});
return true;
}
public final void am(Map<String, Object> map) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onPreloadWebViewInit success, ready");
String str = "MicroMsg.JsApiHandler";
String str2 = "onPreloadWebViewInit,params %s";
Object[] objArr = new Object[1];
objArr[0] = map == null ? "" : map.toString();
x.i(str, str2, objArr);
ah.A(new 44(this, i$a.a("onUiInit", (Map) map, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onPreloadWebViewInit fail, not ready");
}
public final void bXR() {
this.qhq = true;
if (this.qhu != null) {
for (a aVar : this.qhu) {
if (aVar != null) {
aVar.onReady();
}
}
}
}
public final void a(a aVar) {
if (this.qhu == null) {
this.qhu = new HashSet();
}
this.qhu.add(aVar);
}
public final void bXS() {
x.v("MicroMsg.JsApiHandler", "doAttachRunOn3rdApis, ready(%s).", new Object[]{Boolean.valueOf(this.qhq)});
if (this.qhk != null && this.qhq) {
MMWebView mMWebView = this.qhk;
StringBuilder stringBuilder = new StringBuilder("javascript:WeixinJSBridge._handleMessageFromWeixin(");
String str = "sys:attach_runOn3rd_apis";
Map hashMap = new HashMap();
JsapiPermissionWrapper bVR = this.qhr.bVR();
Collection linkedList = new LinkedList();
if (bVR != null) {
if (bVR.gu(88)) {
linkedList.add("menu:share:timeline");
}
if (bVR.gu(89)) {
linkedList.add("menu:share:appmessage");
}
if (bVR.gu(94)) {
linkedList.add("menu:share:qq");
}
if (bVR.gu(109)) {
linkedList.add("menu:share:weiboApp");
}
if (bVR.gu(134)) {
linkedList.add("menu:share:QZone");
}
if (bVR.gu(TbsListener$ErrorCode.RENAME_EXCEPTION)) {
linkedList.add("sys:record");
}
linkedList.add("onVoiceRecordEnd");
linkedList.add("onVoicePlayBegin");
linkedList.add("onVoicePlayEnd");
linkedList.add("onLocalImageUploadProgress");
linkedList.add("onImageDownloadProgress");
linkedList.add("onVoiceUploadProgress");
linkedList.add("onVoiceDownloadProgress");
linkedList.add("onVideoUploadProgress");
linkedList.add("onMediaFileUploadProgress");
linkedList.add("menu:setfont");
linkedList.add("menu:share:weibo");
linkedList.add("menu:share:email");
linkedList.add(com.tencent.mm.plugin.game.gamewebview.b.a.c.NAME);
linkedList.add(b.NAME);
linkedList.add("hdOnDeviceStateChanged");
linkedList.add("activity:state_change");
linkedList.add("onWXDeviceBluetoothStateChange");
linkedList.add("onWXDeviceLanStateChange");
linkedList.add("onWXDeviceBindStateChange");
linkedList.add("onReceiveDataFromWXDevice");
linkedList.add("onScanWXDeviceResult");
linkedList.add("onWXDeviceStateChange");
linkedList.add("onNfcTouch");
linkedList.add("onBeaconMonitoring");
linkedList.add("onBeaconsInRange");
linkedList.add("menu:custom");
linkedList.add("onSearchWAWidgetOpenApp");
linkedList.add("onSearchDataReady");
linkedList.add("onGetPoiInfoReturn");
linkedList.add("onSearchHistoryReady");
linkedList.add("onSearchWAWidgetOnTapCallback");
linkedList.add("onSearchImageListReady");
linkedList.add("onTeachSearchDataReady");
linkedList.add("onSearchGuideDataReady");
linkedList.add("onSearchInputChange");
linkedList.add("onSearchInputConfirm");
linkedList.add("onSearchSuggestionDataReady");
linkedList.add("onMusicStatusChanged");
linkedList.add("switchToTabSearch");
linkedList.add("onVideoPlayerCallback");
linkedList.add("onSelectContact");
linkedList.add("onSearchWAWidgetAttrChanged");
linkedList.add("onSearchWAWidgetReloadData");
linkedList.add("onSearchWAWidgetReloadDataFinish");
linkedList.add("onSearchWAWidgetStateChange");
linkedList.add("onSearchWAWidgetDataPush");
linkedList.add("onPullDownRefresh");
linkedList.add("onPageStateChange");
linkedList.add("onGetKeyboardHeight");
linkedList.add("onGetSmiley");
linkedList.add("onAddShortcutStatus");
linkedList.add("onFocusSearchInput");
linkedList.add("onGetA8KeyUrl");
linkedList.add("deleteAccountSuccess");
linkedList.add("onGetMsgProofItems");
linkedList.add("WNJSHandlerInsert");
linkedList.add("WNJSHandlerMultiInsert");
linkedList.add("WNJSHandlerExportData");
linkedList.add("WNJSHandlerHeaderAndFooterChange");
linkedList.add("WNJSHandlerEditableChange");
linkedList.add("WNJSHandlerEditingChange");
linkedList.add("WNJSHandlerSaveSelectionRange");
linkedList.add("WNJSHandlerLoadSelectionRange");
linkedList.add("onCustomGameMenuClicked");
linkedList.add("showLoading");
linkedList.add("getSearchEmotionDataCallBack");
linkedList.add("onNavigationBarRightButtonClick");
linkedList.add("onSearchActionSheetClick");
linkedList.add("onGetMatchContactList");
linkedList.add("onUiInit");
linkedList.add("onNetWorkChange");
linkedList.add("onMiniProgramData");
linkedList.add("onBackgroundAudioStateChange");
linkedList.add("onArticleReadingBtnClicked");
if (!bi.cX(null)) {
linkedList.addAll(null);
}
}
hashMap.put("__runOn3rd_apis", new JSONArray(linkedList));
mMWebView.evaluateJavascript(stringBuilder.append(i$a.a(str, hashMap, this.qhs, this.qht)).append(")").toString(), new 55(this));
}
}
private void bXT() {
do {
} while (bXU());
}
private boolean bXU() {
if (bi.cX(this.qhm)) {
x.i("MicroMsg.JsApiHandler", "dealNextMsg stop, msgList is empty");
return false;
}
boolean Au;
try {
Au = this.gcO.Au(this.pUz);
} catch (Exception e) {
x.w("MicroMsg.JsApiHandler", "isBusy, ex = " + e.getMessage());
Au = false;
}
x.i("MicroMsg.JsApiHandler", "dealNextMsg isBusy = " + Au);
if (Au) {
x.w("MicroMsg.JsApiHandler", "dealNextMsg fail, msgHandler is busy now");
return false;
} else if (this.qhm.size() == 0) {
x.w("MicroMsg.JsApiHandler", "msgList size is 0.");
return false;
} else {
i iVar = (i) this.qhm.remove(0);
if (iVar == null) {
x.e("MicroMsg.JsApiHandler", "dealNextMsg fail, msg is null");
return true;
} else if (iVar.qkl == null || iVar.mcy == null || iVar.type == null || this.qhk == null) {
x.e("MicroMsg.JsApiHandler", "dealNextMsg fail, can cause nullpointer, function = " + iVar.qkl + ", params = " + iVar.mcy + ", type = " + iVar.type + ", wv = " + this.qhk);
return true;
} else {
if (!(this.qhp == null || this.qhp.get("srcUsername") == null || bi.oW(this.qhp.get("srcUsername").toString()))) {
iVar.mcy.put("src_username", this.qhp.get("srcUsername").toString());
}
if (!(this.qhp == null || this.qhp.get("srcDisplayname") == null || bi.oW(this.qhp.get("srcDisplayname").toString()))) {
iVar.mcy.put("src_displayname", this.qhp.get("srcDisplayname").toString());
}
if (!(this.qhp == null || this.qhp.get("KTemplateId") == null || bi.oW(this.qhp.get("KTemplateId").toString()))) {
iVar.mcy.put("tempalate_id", this.qhp.get("KTemplateId").toString());
}
if (this.qhp != null) {
iVar.mcy.put("message_id", this.qhp.get("message_id"));
iVar.mcy.put("message_index", this.qhp.get("message_index"));
iVar.mcy.put("webview_scene", this.qhp.get("scene"));
iVar.mcy.put("pay_channel", this.qhp.get("pay_channel"));
iVar.mcy.put("pay_scene", this.qhp.get("pay_scene"));
x.i("MicroMsg.JsApiHandler", "getPackageName %s", new Object[]{this.qhp.get("pay_package")});
if (this.qhp.get("pay_package") != null) {
iVar.mcy.put("pay_packageName", this.qhp.get("pay_package"));
}
iVar.mcy.put("stastic_scene", this.qhp.get("stastic_scene"));
iVar.mcy.put("open_from_scene", this.qhp.get("from_scence"));
Bundle bundle = new Bundle();
bundle.putString("__jsapi_fw_ext_info_key_current_url", this.qhk.getUrl());
iVar.mcy.put("__jsapi_fw_ext_info", bundle);
}
if (!(iVar.qkl.equals("shareWeibo") || iVar.qkl.equals("openUrlByExtBrowser") || iVar.qkl.equals("openUrlWithExtraWebview") || iVar.qkl.equals("openCustomWebview") || iVar.qkl.equals("openGameWebView") || iVar.qkl.equals("addToEmoticon") || iVar.qkl.equals(ax.NAME) || iVar.qkl.equals("openGameUrlWithExtraWebView"))) {
iVar.mcy.put("url", this.qhk.getUrl());
x.i("MicroMsg.JsApiHandler", "cuiqi wv.getUrl" + this.qhk.getUrl());
}
if (iVar.qkl.equalsIgnoreCase("openDesignerEmojiView") || iVar.qkl.equalsIgnoreCase("openEmotionDetailViewLocal") || iVar.qkl.equalsIgnoreCase("openDesignerEmojiView") || iVar.qkl.equalsIgnoreCase("openDesignerEmojiViewLocal") || iVar.qkl.equalsIgnoreCase("openDesignerEmojiView") || iVar.qkl.equalsIgnoreCase("openDesignerProfile") || iVar.qkl.equalsIgnoreCase("openDesignerProfileLocal") || iVar.qkl.equalsIgnoreCase("getSearchEmotionData")) {
iVar.mcy.put("searchID", Long.valueOf(bXX()));
x.d("MicroMsg.JsApiHandler", "emoji search id:%d", new Object[]{Long.valueOf(bXX())});
}
try {
JsapiPermissionWrapper bVR = this.qhr.bVR();
Bundle bundle2 = new Bundle();
if (bVR != null) {
bVR.toBundle(bundle2);
}
Au = this.gcO.a(iVar.type, iVar.qkl, iVar.qkj, bundle2, i.aq(iVar.mcy), this.pUz);
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e2, "", new Object[0]);
x.w("MicroMsg.JsApiHandler", "handleMsg, ex = " + e2.getMessage());
Au = false;
}
x.i("MicroMsg.JsApiHandler", "dealNextMsg, %s, handleRet = %s", new Object[]{iVar.qkl, Boolean.valueOf(Au)});
if (Au) {
return false;
}
return true;
}
}
}
public final void detach() {
this.qhq = false;
this.qhm.clear();
this.qhl.clear();
this.qhn = null;
}
public final void keep_setReturnValue(String str, String str2) {
x.i("MicroMsg.JsApiHandler", "setResultValue, scene = " + str + ", resultValue = " + str2);
x.i("MicroMsg.JsApiHandler", "edw setResultValue = threadId = " + Thread.currentThread().getId() + ", threadName = " + Thread.currentThread().getName());
if (this.qhn != null) {
Message obtain = Message.obtain();
obtain.obj = str2;
if (str.equals("SCENE_FETCHQUEUE")) {
obtain.what = 1;
} else if (str.equals("SCENE_HANDLEMSGFROMWX")) {
obtain.what = 2;
}
this.qhn.sendMessage(obtain);
}
}
public final void bXV() {
if (this.qhq) {
Map hashMap = new HashMap();
hashMap.put("scene", "friend");
this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + i$a.a("menu:share:appmessage", hashMap, this.qhs, this.qht) + ")", null);
try {
this.gcO.H("scene", "friend", this.pUz);
return;
} catch (Exception e) {
x.w("MicroMsg.JsApiHandler", "jsapiBundlePutString, ex = " + e.getMessage());
return;
}
}
x.e("MicroMsg.JsApiHandler", "onSendToFriend fail, not ready");
}
public final void f(Bundle bundle, String str) {
if (!this.qhq || bundle == null) {
x.e("MicroMsg.JsApiHandler", "onDownloadStateChange fail, not ready");
return;
}
long j = bundle.getLong("download_manager_downloadid");
String string = bundle.getString("download_manager_appid", "");
int i = bundle.getInt("download_manager_errcode");
x.i("MicroMsg.JsApiHandler", "onDownloadStateChange, downloadId = " + j + ", state = " + str + ", errCode = " + i);
Map hashMap = new HashMap();
hashMap.put("appid", string);
hashMap.put("download_id", Long.valueOf(j));
hashMap.put("err_code", Integer.valueOf(i));
hashMap.put("state", str);
ah.A(new 65(this, i$a.a(com.tencent.mm.plugin.game.gamewebview.b.a.c.NAME, hashMap, this.qhs, this.qht)));
}
public final void g(String str, long j, int i) {
if (this.qhq) {
Map hashMap = new HashMap();
hashMap.put("appid", str);
hashMap.put("download_id", Long.valueOf(j));
hashMap.put("progress", Integer.valueOf(i));
ah.A(new 66(this, i$a.a(b.NAME, hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onDownloadStateChange fail, not ready");
}
public final void cB(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onExdeviceStateChange: device id = %s, state = %s", new Object[]{str, Integer.valueOf(i)});
if (bi.oW(str)) {
x.e("MicroMsg.JsApiHandler", "parameter error!!!");
return;
}
Map hashMap = new HashMap();
hashMap.put("deviceId", str);
if (i == 2) {
hashMap.put("state", "connected");
} else if (i == 1) {
hashMap.put("state", "connecting");
} else {
hashMap.put("state", "disconnected");
}
ah.A(new 2(this, i$a.a("onWXDeviceStateChange", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onExdeviceStateChange fail, not ready");
}
public final void an(Map<String, Object> map) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onVoicePlayEnd");
final String a = i$a.a("onVoicePlayEnd", (Map) map, this.qhs, this.qht);
ah.A(new Runnable() {
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + a + ")", null);
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "onVoicePlayEnd fail, ex = %s", new Object[]{e.getMessage()});
}
}
});
return;
}
x.e("MicroMsg.JsApiHandler", "onVoicePlayEnd fail, not ready");
}
public final void ao(Map<String, Object> map) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onVoiceRecordEnd");
x.i("MicroMsg.JsApiHandler", "onVoiceRecordEnd event : %s", new Object[]{i$a.a("onVoiceRecordEnd", (Map) map, this.qhs, this.qht)});
ah.A(new 9(this, r0));
return;
}
x.e("MicroMsg.JsApiHandler", "onVoiceRecordEnd fail, not ready");
}
public final void cC(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onImageUploadProgress, local id : %s, percent : %d", new Object[]{str, Integer.valueOf(i)});
Map hashMap = new HashMap();
hashMap.put("localId", str);
hashMap.put("percent", Integer.valueOf(i));
ah.A(new 11(this, i$a.a("onImageUploadProgress", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onImageUploadProgress fail, not ready");
}
public final void cD(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onImageDownloadProgress, serverId id : %s, percent : %d", new Object[]{str, Integer.valueOf(i)});
Map hashMap = new HashMap();
hashMap.put("serverId", str);
hashMap.put("percent", Integer.valueOf(i));
ah.A(new 13(this, i$a.a("onImageDownloadProgress", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onImageDownloadProgress fail, not ready");
}
public final void cE(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onVoiceUploadProgress, local id : %s, percent : %d", new Object[]{str, Integer.valueOf(i)});
Map hashMap = new HashMap();
hashMap.put("localId", str);
hashMap.put("percent", Integer.valueOf(i));
ah.A(new 14(this, i$a.a("onVoiceUploadProgress", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onVoiceUploadProgress fail, not ready");
}
public final void cF(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onVoiceDownloadProgress, serverId id : %s, percent : %d", new Object[]{str, Integer.valueOf(i)});
Map hashMap = new HashMap();
hashMap.put("serverId", str);
hashMap.put("percent", Integer.valueOf(i));
ah.A(new 15(this, i$a.a("onVoiceDownloadProgress", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onVoiceDownloadProgress fail, not ready");
}
public final void cG(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onVideoUploadoadProgress, local id : %s, percent : %d", new Object[]{str, Integer.valueOf(i)});
Map hashMap = new HashMap();
hashMap.put("localId", str);
hashMap.put("percent", Integer.valueOf(i));
ah.A(new 16(this, i$a.a("onVideoUploadProgress", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onVideoUploadoadProgress fail, not ready");
}
public final void RF(String str) {
try {
Bundle bundle = new Bundle();
JsapiPermissionWrapper bVR = this.qhr.bVR();
if (bVR != null) {
bVR.toBundle(bundle);
}
this.gcO.a(str, bundle, this.pUz);
} catch (Exception e) {
x.w("MicroMsg.JsApiHandler", "doProfile, ex = " + e.getMessage());
}
}
public final void Bc(int i) {
Map hashMap = new HashMap();
hashMap.put("height", Integer.valueOf(a.ag(ad.getContext(), i)));
ah.A(new 20(this, i$a.a("onGetKeyboardHeight", hashMap, this.qhs, this.qht)));
}
public final void kk(boolean z) {
Map hashMap = new HashMap();
hashMap.put("success", Boolean.valueOf(z));
ah.A(new 22(this, i$a.a("onAddShortcutStatus", hashMap, this.qhs, this.qht)));
}
public final void RG(String str) {
Map hashMap = new HashMap();
hashMap.put("err_msg", str);
ah.A(new 24(this, i$a.a("onBeaconMonitoring", hashMap, this.qhs, this.qht)));
}
public final void q(final String str, final Map<String, String> map) {
x.d("MicroMsg.JsApiHandler", "onGetA8KeyUrl, fullUrl = %s", new Object[]{str});
if (!bi.oW(str)) {
this.qhw = str;
if (map == null || map.size() == 0) {
this.qhx = 0;
} else {
this.qhx = 1;
}
final String cH = cH(str, this.qhx);
ah.A(new Runnable() {
public final void run() {
try {
if (!(map == null || map.size() == 0)) {
com.tencent.xweb.c.ij(ad.getContext());
com.tencent.xweb.b cIi = com.tencent.xweb.b.cIi();
for (String str : map.keySet()) {
cIi.setCookie(bi.Xl(str), str + "=" + ((String) map.get(str)));
}
cIi.setCookie(bi.Xl(str), "httponly");
com.tencent.xweb.c.cIk();
com.tencent.xweb.c.sync();
x.i("MicroMsg.JsApiHandler", "cookies:%s", new Object[]{cIi.getCookie(bi.Xl(str))});
}
d.this.qhk.evaluateJavascript(String.format("javascript:(function(){ window.getA8KeyUrl='%s'; })()", new Object[]{str}), null);
d.this.qhk.evaluateJavascript("javascript:(function(){ window.isWeixinCached=true; })()", null);
if (d.this.qhq) {
d.this.qhk.evaluateJavascript(cH, null);
d.this.qhw = null;
d.this.qhx = 0;
}
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "onGetA8KeyUrl fail, ex = %s", new Object[]{e.getMessage()});
}
}
});
}
}
final String cH(String str, int i) {
Map hashMap = new HashMap(2);
hashMap.put("url", str);
hashMap.put("set_cookie", Integer.valueOf(i));
return RI(i$a.a("onGetA8KeyUrl", hashMap, this.qhs, this.qht));
}
public final synchronized void a(String str, int i, int i2, double d, double d2, float f) {
if (this.qhB.ciq()) {
this.qhB.J(1000, 1000);
}
JSONObject jSONObject = new JSONObject();
int i3 = 0;
if (d > 0.0d && d < 0.5d) {
i3 = 1;
}
try {
if (!this.qhA.contains(String.valueOf(str) + String.valueOf(i) + String.valueOf(i2))) {
this.qhA.add(String.valueOf(str) + String.valueOf(i) + String.valueOf(i2));
jSONObject.put("uuid", String.valueOf(str));
jSONObject.put("major", String.valueOf(i));
jSONObject.put("minor", String.valueOf(i2));
jSONObject.put("accuracy", String.valueOf(d));
jSONObject.put("rssi", String.valueOf(d2));
jSONObject.put("heading", String.valueOf(f));
jSONObject.put("proximity", String.valueOf(i3));
this.qhz.put(jSONObject);
this.qhy.put("beacons", this.qhz);
this.qhy.put("err_msg", "onBeaconsInRange:ok");
}
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "parse json error in onBeaconsInRange!! ", new Object[]{e.getMessage()});
}
i$a.a("onBeaconsInRange", this.qhy, this.qhs, this.qht);
return;
}
public final void a(String str, String str2, Map<String, Object> map, boolean z) {
if (!bi.oW(str)) {
if (str2 == null || str2.length() == 0 || str == null) {
x.e("MicroMsg.JsApiHandler", "doCallback, invalid args, ret = " + str2);
} else {
Map hashMap = new HashMap();
hashMap.put("err_msg", str2);
if (map != null && map.size() > 0) {
x.i("MicroMsg.JsApiHandler", "doCallback, retValue size = " + map.size());
hashMap.putAll(map);
}
String a = i$a.a("callback", str, hashMap, null, this.qhs, this.qht);
x.i("MicroMsg.JsApiHandler", "doCallback, ret = " + str2 + ", cb = " + a);
if (!(a == null || this.qhk == null)) {
ah.A(new 28(this, a));
}
}
}
if (z) {
bVo();
}
}
public final void bVo() {
if (this.qhn != null) {
this.qhn.post(new 27(this));
}
}
public final void bVn() {
if (this.qhm != null) {
this.qhm.clear();
}
}
public final void ap(Map<String, Object> map) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSelectContact success, ready");
ah.A(new 29(this, i$a.a("onSelectContact", (Map) map, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSelectContact fail, not ready");
}
public final void d(String str, boolean z, String str2) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchDataReady success, ready");
Map hashMap = new HashMap();
hashMap.put("json", str);
hashMap.put("newQuery", Boolean.valueOf(z));
hashMap.put("requestId", str2);
ah.A(new 35(this, i$a.a("onSearchDataReady", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchDataReady fail, not ready");
}
public final void a(String str, boolean z, String str2, String str3) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchWAWidgetOnTapCallback success, ready");
Map hashMap = new HashMap();
hashMap.put("eventId", str);
hashMap.put("widgetId", str3);
hashMap.put("hitTest", Boolean.valueOf(z));
hashMap.put("err_msg", str2);
ah.A(new 38(this, i$a.a("onSearchWAWidgetOnTapCallback", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchWAWidgetOnTapCallback fail, not ready");
}
public final void cI(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchWAWidgetStateChange success, ready");
Map hashMap = new HashMap();
hashMap.put("widgetId", str);
hashMap.put("state", Integer.valueOf(i));
ah.A(new 42(this, i$a.a("onSearchWAWidgetStateChange", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchWAWidgetStateChange fail, not ready");
}
public final void a(String str, String str2, JSONArray jSONArray, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchInputChange success, ready %s %s %s", new Object[]{str, str2, jSONArray.toString()});
Map hashMap = new HashMap();
hashMap.put("query", str);
hashMap.put("custom", str2);
hashMap.put("tagList", jSONArray);
hashMap.put("isCancelButtonClick", Integer.valueOf(i));
ah.A(new 45(this, i$a.a("onSearchInputChange", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchInputChange fail, not ready");
}
public final void a(String str, String str2, JSONArray jSONArray) {
Map hashMap = new HashMap();
hashMap.put("query", str);
hashMap.put("custom", str2);
hashMap.put("tagList", jSONArray);
a("onSearchInputChange", hashMap, null);
}
public final boolean a(String str, String str2, String str3, String str4, String str5, Map<String, Object> map, Map<String, Object> map2) {
JSONObject jSONObject = new JSONObject();
if (map2 != null) {
for (Entry entry : map2.entrySet()) {
if (entry.getValue() != null) {
try {
jSONObject.put((String) entry.getKey(), new JSONObject(entry.getValue().toString()));
} catch (Throwable e) {
Throwable th = e;
try {
jSONObject.put((String) entry.getKey(), new JSONArray(entry.getValue().toString()));
} catch (JSONException e2) {
try {
jSONObject.put((String) entry.getKey(), entry.getValue());
} catch (JSONException e3) {
x.printErrStackTrace("MicroMsg.JsApiHandler", th, "", new Object[0]);
}
}
}
}
}
}
try {
for (Entry entry2 : map.entrySet()) {
jSONObject.put((String) entry2.getKey(), entry2.getValue());
}
} catch (Throwable e4) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e4, "", new Object[0]);
}
try {
jSONObject.put("scene", str);
jSONObject.put("type", str2);
jSONObject.put("isSug", str3);
jSONObject.put("isLocalSug", str4);
jSONObject.put("sessionId", str5);
} catch (Throwable e42) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e42, "", new Object[0]);
}
a("switchToTabSearch", null, jSONObject);
return true;
}
public final void a(String str, Map<String, Object> map, JSONObject jSONObject) {
if (!this.qhq || (map == null && jSONObject == null)) {
x.e("MicroMsg.JsApiHandler", "onSendEventToJSBridge fail, event=%s", new Object[]{str});
return;
}
String a;
String str2 = "MicroMsg.JsApiHandler";
String str3 = "onSendEventToJSBridge success, event=%s, params=%s, jsonParams=%s";
Object[] objArr = new Object[3];
objArr[0] = str;
objArr[1] = map == null ? "" : map.toString();
objArr[2] = jSONObject == null ? "" : jSONObject.toString();
x.i(str2, str3, objArr);
if (map != null) {
a = i$a.a(str, (Map) map, this.qhs, this.qht);
} else {
a = i$a.a(str, jSONObject, this.qhs, this.qht);
}
ah.A(new 46(this, a, str));
}
public final boolean a(String str, String str2, String str3, String str4, String str5, String str6, String str7, JSONArray jSONArray, String str8, int i, Map<String, Object> map) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "switchToTabSearch success, ready %s %s %s %s %s", new Object[]{str, str2, str3, str4, str5});
JSONObject jSONObject = new JSONObject();
if (map != null) {
for (Entry entry : map.entrySet()) {
if (entry.getValue() != null) {
try {
jSONObject.put((String) entry.getKey(), new JSONObject(entry.getValue().toString()));
} catch (Throwable e) {
Throwable th = e;
try {
jSONObject.put((String) entry.getKey(), new JSONArray(entry.getValue().toString()));
} catch (JSONException e2) {
try {
jSONObject.put((String) entry.getKey(), entry.getValue());
} catch (JSONException e3) {
x.printErrStackTrace("MicroMsg.JsApiHandler", th, "", new Object[0]);
}
}
}
}
}
}
try {
jSONObject.put("type", str);
jSONObject.put("isMostSearchBiz", str2);
jSONObject.put("isSug", str3);
jSONObject.put("isLocalSug", str5);
jSONObject.put("scene", str4);
jSONObject.put("query", str6);
jSONObject.put("custom", str7);
jSONObject.put("tagList", jSONArray);
jSONObject.put("isBackButtonClick", 0);
jSONObject.put("sugId", str8);
jSONObject.put("sugClickType", i);
} catch (Throwable e4) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e4, "", new Object[0]);
}
final String a = i$a.a("switchToTabSearch", jSONObject, this.qhs, this.qht);
ah.A(new Runnable() {
public final void run() {
try {
d.this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + a + ")", null);
} catch (Exception e) {
x.e("MicroMsg.JsApiHandler", "switchToTabSearch fail, ex = %s", new Object[]{e.getMessage()});
}
}
});
return true;
}
x.e("MicroMsg.JsApiHandler", "switchToTabSearch fail, not ready");
return false;
}
public final void a(String str, String str2, JSONArray jSONArray, int i, Map<String, Object> map) {
String str3 = "";
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchInputConfirm success, ready %s %s %s", new Object[]{str, str2, jSONArray.toString()});
JSONObject jSONObject = new JSONObject();
if (map != null) {
for (Entry entry : map.entrySet()) {
if (entry.getValue() != null) {
try {
jSONObject.put((String) entry.getKey(), new JSONObject(entry.getValue().toString()));
} catch (Throwable e) {
Throwable th = e;
try {
jSONObject.put((String) entry.getKey(), new JSONArray(entry.getValue().toString()));
} catch (JSONException e2) {
try {
jSONObject.put((String) entry.getKey(), entry.getValue());
} catch (JSONException e3) {
x.printErrStackTrace("MicroMsg.JsApiHandler", th, "", new Object[0]);
}
}
}
}
}
}
try {
jSONObject.put("query", str);
jSONObject.put("custom", str2);
jSONObject.put("tagList", jSONArray);
jSONObject.put("isBackButtonClick", i);
jSONObject.put("sugId", str3);
jSONObject.put("sugClickType", 0);
} catch (Throwable e4) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e4, "", new Object[0]);
}
ah.A(new 48(this, i$a.a("onSearchInputConfirm", jSONObject, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchInputConfirm fail, not ready");
}
public final void RH(String str) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onSearchSuggestionDataReady success, ready");
Map hashMap = new HashMap();
hashMap.put("json", str);
ah.A(new 49(this, i$a.a("onSearchSuggestionDataReady", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchSuggestionDataReady fail, not ready");
}
public final void aV(int i, String str) {
if (this.qhq) {
Map hashMap = new HashMap();
hashMap.put("ret", Integer.valueOf(i));
hashMap.put("data", str);
ah.A(new 50(this, i$a.a("onSearchImageListReady", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onSearchImageListReady fail, not ready");
}
public final void i(int i, String str, int i2) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onTeachSearchDataReady success, ready");
Map hashMap = new HashMap();
hashMap.put("requestType", Integer.valueOf(i));
hashMap.put("json", str);
hashMap.put("isCacheData", Integer.valueOf(i2));
ah.A(new 51(this, i$a.a("onTeachSearchDataReady", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onTeachSearchDataReady fail, not ready");
}
public final void cJ(String str, int i) {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onMusicStatusChanged success, ready");
Map hashMap = new HashMap();
hashMap.put("snsid", str);
hashMap.put("status", Integer.valueOf(i));
ah.A(new 53(this, i$a.a("onMusicStatusChanged", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onMusicStatusChanged fail, not ready");
}
public static String RI(String str) {
return String.format("javascript:WeixinJSBridge._handleMessageFromWeixin(%s)", new Object[]{bi.oV(str)});
}
public final void kl(boolean z) {
x.i("MicroMsg.JsApiHandler", "getHtmlContent, ready(%s).", new Object[]{Boolean.valueOf(this.qhq)});
if (this.qhk != null && this.gcO != null && this.qhq) {
if (z) {
this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + i$a.a("sys:get_html_content", new HashMap(), this.qhs, this.qht) + ")", null);
return;
}
List bVB;
try {
bVB = this.gcO.bVB();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e, "", new Object[0]);
bVB = null;
}
Uri parse = Uri.parse(this.qhk.getUrl());
if (parse != null) {
x.d("MicroMsg.JsApiHandler", "wv hijack url host" + parse.getHost());
}
if (bVB != null && parse != null && bVB.contains(parse.getHost())) {
this.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + i$a.a("sys:get_html_content", new HashMap(), this.qhs, this.qht) + ")", null);
}
}
}
public final void bXW() {
if (this.qhq) {
x.i("MicroMsg.JsApiHandler", "onEmojiStoreShowLoading success, ready");
Map hashMap = new HashMap();
hashMap.put("needShow", Boolean.valueOf(true));
ah.A(new 57(this, i$a.a("showLoading", hashMap, this.qhs, this.qht)));
return;
}
x.e("MicroMsg.JsApiHandler", "onEmojiStoreShowLoading fail, not ready");
}
public final void RJ(String str) {
if (!bi.oW(str)) {
Map hashMap = new HashMap();
hashMap.put("netType", str);
ah.A(new 59(this, i$a.a("onNetWorkChange", hashMap, this.qhs, this.qht)));
}
}
public final long bXX() {
x.d("MicroMsg.JsApiHandler", "cpan emoji get SearchID:%d", new Object[]{Long.valueOf(this.qhC)});
return this.qhC;
}
private String RK(String str) {
String url = this.qhk.getUrl();
try {
x.i("MicroMsg.JsApiHandler", "generate upload file name, url=%s, tag=%s, fullName=%s", new Object[]{url, str, com.tencent.mm.compatible.util.e.dgo + m.cw(url + str)});
return com.tencent.mm.compatible.util.e.dgo + m.cw(url + str);
} catch (Throwable e) {
x.e("MicroMsg.JsApiHandler", "generating temp file name failed, url is " + url);
x.printErrStackTrace("MicroMsg.JsApiHandler", e, "", new Object[0]);
return null;
}
}
private static boolean r(String str, Map<String, Integer> map) {
Throwable e;
if (bi.oW(str) || map == null) {
x.w("MicroMsg.JsApiHandler", "write to file error, path is null or empty, or data is empty");
return false;
}
File file = new File(str);
if (!file.exists()) {
try {
file.createNewFile();
} catch (Throwable e2) {
x.e("MicroMsg.JsApiHandler", "creating file failed, filePath is " + str);
x.printErrStackTrace("MicroMsg.JsApiHandler", e2, "", new Object[0]);
return false;
}
}
OutputStream outputStream = null;
OutputStream bufferedOutputStream;
try {
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(str, true));
try {
for (String str2 : map.keySet()) {
bufferedOutputStream.write((((Integer) map.get(str2)).intValue() + " " + str2).getBytes());
bufferedOutputStream.write(13);
bufferedOutputStream.write(10);
}
bufferedOutputStream.flush();
try {
bufferedOutputStream.close();
} catch (Throwable e22) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e22, "", new Object[0]);
}
x.d("MicroMsg.JsApiHandler", "writeToFile ok! " + str);
return true;
} catch (Exception e3) {
e22 = e3;
outputStream = bufferedOutputStream;
try {
x.printErrStackTrace("MicroMsg.JsApiHandler", e22, "", new Object[0]);
x.w("MicroMsg.JsApiHandler", "write to file error");
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable e222) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e222, "", new Object[0]);
}
}
return false;
} catch (Throwable th) {
e222 = th;
bufferedOutputStream = outputStream;
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Throwable e4) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e4, "", new Object[0]);
}
}
throw e222;
}
} catch (Throwable th2) {
e222 = th2;
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Throwable e42) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e42, "", new Object[0]);
}
}
throw e222;
}
} catch (Exception e5) {
e222 = e5;
x.printErrStackTrace("MicroMsg.JsApiHandler", e222, "", new Object[0]);
x.w("MicroMsg.JsApiHandler", "write to file error");
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable e2222) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e2222, "", new Object[0]);
}
}
return false;
} catch (Throwable th3) {
e2222 = th3;
bufferedOutputStream = null;
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Throwable e422) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e422, "", new Object[0]);
}
}
throw e2222;
}
}
private static boolean ft(String str, String str2) {
Throwable e;
if (bi.oW(str) || bi.oW(str2)) {
x.w("MicroMsg.JsApiHandler", "write to file error, path is null or empty, or data is empty");
return false;
}
File file = new File(str);
if (!file.exists()) {
try {
file.createNewFile();
} catch (Throwable e2) {
x.e("MicroMsg.JsApiHandler", "creating file failed, filePath is " + str);
x.printErrStackTrace("MicroMsg.JsApiHandler", e2, "", new Object[0]);
return false;
}
}
OutputStream outputStream = null;
try {
OutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(str, true));
try {
outputStream = new FileOutputStream(str);
outputStream.write(str2.getBytes());
outputStream.write(13);
outputStream.write(10);
outputStream.flush();
try {
outputStream.close();
} catch (Throwable e3) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e3, "", new Object[0]);
}
x.d("MicroMsg.JsApiHandler", "writeToFile ok! " + str);
return true;
} catch (Exception e4) {
e2 = e4;
outputStream = bufferedOutputStream;
try {
x.printErrStackTrace("MicroMsg.JsApiHandler", e2, "", new Object[0]);
x.w("MicroMsg.JsApiHandler", "write to file error");
if (outputStream != null) {
return false;
}
try {
outputStream.close();
return false;
} catch (Throwable e22) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e22, "", new Object[0]);
return false;
}
} catch (Throwable th) {
e22 = th;
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable e32) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e32, "", new Object[0]);
}
}
throw e22;
}
} catch (Throwable th2) {
e22 = th2;
outputStream = bufferedOutputStream;
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable e322) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e322, "", new Object[0]);
}
}
throw e22;
}
} catch (Exception e5) {
e22 = e5;
x.printErrStackTrace("MicroMsg.JsApiHandler", e22, "", new Object[0]);
x.w("MicroMsg.JsApiHandler", "write to file error");
if (outputStream != null) {
return false;
}
try {
outputStream.close();
return false;
} catch (Throwable e222) {
x.printErrStackTrace("MicroMsg.JsApiHandler", e222, "", new Object[0]);
return false;
}
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package comparaison;
import java.util.Scanner;
/**
*
* @author 80010-92-01
*/
public class Comparaison {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int nX = 7, nY = 11, nZ = 11 ;
Scanner lectureClavier = new Scanner(System.in);
System.out.println("Entrez le nombre X");
nX = lectureClavier.nextInt();
System.out.println(nX) ;
System.out.println(nY) ;
System.out.println(nX < nY) ;
System.out.println(nX > nZ) ;
System.out.println(nY <= nZ) ;
System.out.println(nX >= nY) ;
System.out.println(nY == nZ) ;
System.out.println(nX != nZ) ;
}
}
|
package SwordOffer;
import Tree.TreeNode;
import Tree.bianliTreeWith3order;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName serializeTree_37.java
* @Description
* 分别用来序列化和反序列化二叉树。
* 序列化二叉树
* * *
* * * 题目描述:
* * * 请实现两个函数,分别用于序列化和反序列化二叉树。
* * *
* * * 思路一:递归+先序遍历
* * * 0. 序列化后的字符串其实是二叉树的层序遍历结果,但是通常使用的先序、中序、后序、层序遍历记录二叉树的信息不完整,
* * * 也就是可能对应多种二叉树的结果。题目要求是可逆的,因此序列化的字符串需要携带完整的二叉树信息,需要拥有单独
* * * 表示二叉树的能力;
* * * 序列化:
* * * 1. 先序遍历二叉树,如果当前节点不为空,则采用 “节点_” 的形式记录;如果当前节点为空,则采用 “#_” 记录;
* * * 1.1 用 “#” 占据空位置的目的就是防止二叉树节点有相同值的情况下造成的歧义。
* * * 1.2 用 “_” 的目的是为了区分每个节点的值,如节点 12 和 3,节点 1 和 23。
* * * 反序列化:
* * * 1. 将字符串用 “_” 进行分割,保存到数组中;
* * * 2. 将数组中的每个值都入队(或者将队列用数组和索引代替);
* * * 3. 采用先序遍历进行反序列化。
* * *
* * * 思路二:
* * * 1. 使用层次遍历,然后需要使用队列。
* @createTime 2021年08月21日 22:34:00
*/
public class serializeTree_37 {
public static void main(String[] args) {
TreeNode head1 = new TreeNode(1);
head1.left = new TreeNode(2);
head1.right = new TreeNode(3);
head1.left.left = new TreeNode(4);
head1.left.right = new TreeNode(5);
head1.right.left = new TreeNode(6);
head1.right.right = new TreeNode(7);
util.PrintTree.printTree(head1);
System.out.println("先序遍历的结果是");
bianliTreeWith3order.preOrderRecursion(head1);
System.out.println("序列化后的结果:");
String preStr = seriaByPre(head1);
System.out.println(preStr);
System.out.println("逆序列化后的结果:");
util.PrintTree.printTree(unseria(preStr));
}
//序列化
public static String seriaByPre(TreeNode root){
if (root == null){
return "#_";
}
String res = root.val + "_"; //在先序遍历的位置设置字符串
res=res+seriaByPre(root.left);
res = res + seriaByPre(root.right);
return res;
}
//反序列化
public static TreeNode unseria(String preStr){
//首先拆分
String[] values = preStr.split("_");
//先进先出,所以用个队列
Queue<String> queue = new LinkedList<>();
for (int i = 0; i < values.length; i++) {
queue.add(values[i]);
}
//这个队列整好了,放给先序的方式去消费
return unseriaByPre(queue);
}
private static TreeNode unseriaByPre(Queue<String> queue) {
//先弹出来 在先序遍历的位置操作
String val = queue.poll();
if (val.equals("#")){
return null;
}
TreeNode head = new TreeNode(Integer.valueOf(val));
head.left = unseriaByPre(queue);
head.right = unseriaByPre(queue);
return head;
}
//这里补充序列化和反序列化bfs的做法
//序列化
public static String serialize(TreeNode root){
if(root == null){
return "[]";
}
StringBuilder result = new StringBuilder("[");
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode curr = queue.poll();
if(curr!=null){
result.append(curr.val+",");
queue.add(curr.left);
queue.add(curr.right);
}else{
result.append("null,");
}
}
result.deleteCharAt(result.length()-1);
result.append("]");
return result.toString();
}
//反序列化
public static TreeNode unserilaize(String data) {
if (data.equals("[]")) {
return null;
}
int index = 1;
String[] dataChar = data.substring(1, data.length() - 1).split(",");
TreeNode root = new TreeNode(new Integer(dataChar[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode curr = queue.poll();
if (!dataChar[index].equals("[]")) {
curr.left = new TreeNode(new Integer(dataChar[index]));
queue.add(curr.left);
}
index++;
if (!dataChar[index].equals("[]")) {
curr.right = new TreeNode(new Integer(dataChar[index]));
queue.add(curr.right);
}
index++;
}
return root;
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.c.a;
import java.util.LinkedList;
public final class bg extends bhd {
public String bssid;
public String egF;
public int rbC;
public bf rbD;
public bi rbE;
public int rbF;
public int rbG;
public int rbH;
public String rbn;
public long rbo;
public int rbq;
public String rbs;
public int rbt;
public int scene;
public int source;
public String ssid;
public int type;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.shX != null) {
aVar.fV(1, this.shX.boi());
this.shX.a(aVar);
}
if (this.egF != null) {
aVar.g(2, this.egF);
}
aVar.fT(3, this.scene);
aVar.fT(4, this.type);
aVar.fT(5, this.rbC);
if (this.ssid != null) {
aVar.g(6, this.ssid);
}
if (this.bssid != null) {
aVar.g(7, this.bssid);
}
aVar.T(8, this.rbo);
if (this.rbD != null) {
aVar.fV(9, this.rbD.boi());
this.rbD.a(aVar);
}
if (this.rbE != null) {
aVar.fV(10, this.rbE.boi());
this.rbE.a(aVar);
}
aVar.fT(11, this.rbq);
if (this.rbn != null) {
aVar.g(12, this.rbn);
}
aVar.fT(13, this.source);
if (this.rbs != null) {
aVar.g(14, this.rbs);
}
aVar.fT(15, this.rbF);
aVar.fT(16, this.rbG);
aVar.fT(17, this.rbH);
aVar.fT(18, this.rbt);
return 0;
} else if (i == 1) {
if (this.shX != null) {
fS = f.a.a.a.fS(1, this.shX.boi()) + 0;
} else {
fS = 0;
}
if (this.egF != null) {
fS += f.a.a.b.b.a.h(2, this.egF);
}
fS = ((fS + f.a.a.a.fQ(3, this.scene)) + f.a.a.a.fQ(4, this.type)) + f.a.a.a.fQ(5, this.rbC);
if (this.ssid != null) {
fS += f.a.a.b.b.a.h(6, this.ssid);
}
if (this.bssid != null) {
fS += f.a.a.b.b.a.h(7, this.bssid);
}
fS += f.a.a.a.S(8, this.rbo);
if (this.rbD != null) {
fS += f.a.a.a.fS(9, this.rbD.boi());
}
if (this.rbE != null) {
fS += f.a.a.a.fS(10, this.rbE.boi());
}
fS += f.a.a.a.fQ(11, this.rbq);
if (this.rbn != null) {
fS += f.a.a.b.b.a.h(12, this.rbn);
}
fS += f.a.a.a.fQ(13, this.source);
if (this.rbs != null) {
fS += f.a.a.b.b.a.h(14, this.rbs);
}
return (((fS + f.a.a.a.fQ(15, this.rbF)) + f.a.a.a.fQ(16, this.rbG)) + f.a.a.a.fQ(17, this.rbH)) + f.a.a.a.fQ(18, this.rbt);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bg bgVar = (bg) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
fk fkVar = new fk();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) {
}
bgVar.shX = fkVar;
}
return 0;
case 2:
bgVar.egF = aVar3.vHC.readString();
return 0;
case 3:
bgVar.scene = aVar3.vHC.rY();
return 0;
case 4:
bgVar.type = aVar3.vHC.rY();
return 0;
case 5:
bgVar.rbC = aVar3.vHC.rY();
return 0;
case 6:
bgVar.ssid = aVar3.vHC.readString();
return 0;
case 7:
bgVar.bssid = aVar3.vHC.readString();
return 0;
case 8:
bgVar.rbo = aVar3.vHC.rZ();
return 0;
case 9:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bf bfVar = new bf();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bfVar.a(aVar4, bfVar, bhd.a(aVar4))) {
}
bgVar.rbD = bfVar;
}
return 0;
case 10:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bi biVar = new bi();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = biVar.a(aVar4, biVar, bhd.a(aVar4))) {
}
bgVar.rbE = biVar;
}
return 0;
case 11:
bgVar.rbq = aVar3.vHC.rY();
return 0;
case 12:
bgVar.rbn = aVar3.vHC.readString();
return 0;
case 13:
bgVar.source = aVar3.vHC.rY();
return 0;
case 14:
bgVar.rbs = aVar3.vHC.readString();
return 0;
case 15:
bgVar.rbF = aVar3.vHC.rY();
return 0;
case 16:
bgVar.rbG = aVar3.vHC.rY();
return 0;
case 17:
bgVar.rbH = aVar3.vHC.rY();
return 0;
case 18:
bgVar.rbt = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package iplAnalysis;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class StopWord
{
public static void main(String[] args) throws IOException
{
ArrayList<String> stopwords = new ArrayList();
BufferedReader br1 = new BufferedReader(new FileReader("/home/gaurang/Personal/Big_Data/Twitter/output/stopwords.txt"));
String line1 = "";
while((line1= br1.readLine())!=null)
stopwords.add(line1);
BufferedReader br = new BufferedReader(new FileReader("/home/gaurang/Personal/Big_Data/Twitter/output/Descorder_31.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("/home/gaurang/Personal/Big_Data/Twitter/output/KeyWord_extract_31.txt"));
String line;
while((line = br.readLine()) != null)
{
String words_values[] = line.split("\t");
if(stopwords.contains(words_values[0]))
{
continue;
}
else
{
bw.write(line + "\n");
}
}
br.close();
bw.close();
System.out.println("Stopwords removed.");
}
}
|
package cache.inmemorycache.server.commands;
import com.google.inject.Inject;
import cache.inmemorycache.CacheResponse;
import cache.inmemorycache.server.internal.datastore.IDataStore;
public class DeleteCommand extends BaseCommand {
private static final String INVALID_NUMBER_OF_ARGUMENTS = "Invalid number of arguments";
private String key;
private String transactionId;
@Inject
public DeleteCommand(IDataStore dataStore) {
super(dataStore);
}
@Override
public CacheResponse run() throws CloneNotSupportedException {
if (cacheRequest.getTransactionId() != null) {
dataStore.delete(key, transactionId);
} else {
dataStore.delete(key);
}
cacheResponse.setTransactionId(transactionId);
cacheResponse.setStatus(true);
return cacheResponse;
}
@Override
public void validateCacheRequest() {
if (cacheRequest.getOptions().size() != 1) {
throw new IllegalArgumentException(INVALID_NUMBER_OF_ARGUMENTS);
}
}
@Override
protected void initializeArguments() {
if (cacheRequest.getOptions().size() == 1) {
key = cacheRequest.getOptions().get(0);
transactionId = cacheRequest.getTransactionId();
}
}
}
|
package leetcode;
// 输入:grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
//输出:[[1, 3, 3], [2, 3, 3]]
// [[1,2,1],[1,2,2],[2,2,1]]
//1
//1
//2
// [[1,2,1,2,1,2],[2,2,2,2,1,2],[1,2,2,2,1,2]]
//1
//3
//1
// [[2,1,3,2,1,1,2],[1,2,3,1,2,1,2],[1,2,1,2,2,2,2],[2,1,2,2,2,2,2],[2,3,3,3,2,1,2]]
//4
//4
//3
// 题目意思: 就是连通分量中接触到非连通那部分的正方形染色,还有一点在连通分量中,处于边框边缘区域的地方染色,
// 说白了就是把一个连通分量的边界染色,
public class 边框着色 {
public static void main(String[] args) {
// int[][] grid = new int[][]{{1,2,2},{2,3,2}};
// int[][] grid = new int[][]{{1,2,1},{1,2,2},{2,2,1}};
int[][] grid = new int[][]{{2,1,3,2,1,1,2},{1,2,3,1,2,1,2},{1,2,1,2,2,2,2},
{2,1,2,2,2,2,2},{2,3,3,3,2,1,2}};
int r0 = 4, c0 = 4, color = 3;
test.printInts(grid);
int[][] res = colorBorder(grid, r0, c0, color);
test.printInts(res);
}
public static int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
if(grid == null || grid.length == 0 || r0>grid.length || c0>grid[0].length)
return new int[][]{};
int orignColor = grid[r0][c0];
if(orignColor == color) return grid;
boolean[][] visited = new boolean[grid.length][grid[0].length];
floodFill(grid,r0,c0,orignColor,color,visited);
return grid;
}
public static void floodFill(int[][] img,int sr,int sc,int orignColor,int newColor,boolean[][] visited){
if(sr < 0 || sc < 0 || sr >= img.length || sc >= img[0].length || visited[sr][sc]) return; // 超出边界或已被访问
if(img[sr][sc] != orignColor) return; // 遇到其他区域
// 着色有一定限制
if(sr == 0 || sc == 0 || sr == img.length -1 || sc == img[0].length -1){ // 边界
img[sr][sc] = newColor;
} else if( (img[sr-1][sc] != orignColor && !visited[sr-1][sc]) // 判断该点四周是否被包围
|| (img[sr+1][sc] != orignColor && !visited[sr+1][sc])
|| (img[sr][sc+1] != orignColor && !visited[sr][sc+1])
|| (img[sr][sc-1] != orignColor && !visited[sr][sc-1])){
img[sr][sc] = newColor;
}
visited[sr][sc] = true;
floodFill(img,sr+1,sc,orignColor,newColor,visited);
floodFill(img,sr-1,sc,orignColor,newColor,visited);
floodFill(img,sr,sc+1,orignColor,newColor,visited);
floodFill(img,sr,sc-1,orignColor,newColor,visited);
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class ig extends b {
public a bRH;
public ig() {
this((byte) 0);
}
private ig(byte b) {
this.bRH = new a();
this.sFm = false;
this.bJX = null;
}
}
|
package life;
public class LiveNeigboursNumber {
private final int liveNeigbours;
public LiveNeigboursNumber(int liveNeigbours) {
this.liveNeigbours = liveNeigbours;
}
public int getValue() {
return liveNeigbours;
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.account.ui.RegByMobileVoiceVerifyUI.3;
class RegByMobileVoiceVerifyUI$3$2 implements OnClickListener {
final /* synthetic */ 3 eVP;
RegByMobileVoiceVerifyUI$3$2(3 3) {
this.eVP = 3;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.eVP.eVO.finish();
}
}
|
package com.ybg.quartz.schedule.dao;
import java.util.List;
import com.ybg.base.util.Page;
import com.ybg.quartz.schedule.domain.ScheduleJobEntity;
import com.ybg.quartz.schedule.qvo.ScheduleJobQvo;
/** 定时任务
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年12月1日 下午10:29:57 */
public interface ScheduleJobDao {
/** 批量更新状态 */
int updateBatch(int status, final Long[] job_id);
ScheduleJobEntity queryObject(Long jobId);
void deleteBatch(Long[] jobIds);
void update(ScheduleJobEntity scheduleJob);
void save(ScheduleJobEntity scheduleJob) throws Exception;
List<ScheduleJobEntity> queryList(ScheduleJobQvo qvo);
Page queryList(Page page, ScheduleJobQvo qvo);
}
|
package com.example.ryanbrummet.newaudiosense2.AudioSense.Survey.Content;
import com.example.ryanbrummet.newaudiosense2.AudiologyBaseSurveyCode.AbstractSingleSelectionContent;
/**
* Created by ryanbrummet on 8/25/15.
*/
public class GHABPComponentContent extends AbstractSingleSelectionContent {
private final String contextDescription;
public GHABPComponentContent(String instruction, String contextDescription) {
super(instruction);
this.contextDescription = contextDescription;
}
public String getContextDescription() {
return contextDescription;
}
}
|
//import peip.Server; //import de la classe Server du package peip
import java.io.*;
import java.util.*;
import java.text.* ;
import java.nio.file.*;
public class ServeurHTTP extends Server {
public ServeurHTTP(int port, boolean verbose) throws IOException {
super(port, verbose) ;
}
public static void main(String[] args) {
ServeurHTTP myserver = null;
try {
myserver = new ServeurHTTP(1234, true);
}
catch (IOException e) {
System.out.println("Problem while creating server!");
System.exit(-1); // code erreur <> 0 pour signaler qu'il y a un pbm
}
try {
while (true) {
myserver.dialogue();
}
}
catch (IOException e) {
System.out.println("Problem while talking to the client!");
}
finally {
System.out.println("Killing the server");
myserver.close();
}
}
// methode de dialogue correspondant à l'écho par le serveur d'une (seule) chaine lue cad reçue (envoyée) du client
private void dialogue () throws IOException {
acceptConn();
try {
Requete req=getRequete() ;
if (req!= new Requete(""))
repRequete(req) ;
closeConn();
}
catch (NullPointerException e) {
closeConn() ;
}
}
//Début de la méthode getRequete
private Requete getRequete() throws IOException {
String creply = null;
Requete res = new Requete ("") ;
creply = readline();
String[] listeMots=creply.split(" ") ;
String chemin;
String parametre ;
if ((creply==null)||(creply.equals(""))){
res=new Requete("") ;
}
else if (listeMots[0].equals("GET")) {
while (!(creply.equals(""))) {
creply = readline();
if(creply==null){
res=new Requete ("");
}
else {
chemin = "."+listeMots[1] ;
res=new Requete (reformChemin(chemin)) ;
}
}
}
else if (listeMots[0].equals("POST")){
while (!(creply.equals(""))) {
creply = readline();
if(creply==null){
res=new Requete ("");
}
}
creply=readline() ;
res=new Requete("");
}
else
res=new Requete("") ;
return res ;
}
//Début de la méthode repRequete
private void repRequete(Requete requete) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat ("EE dd MMM yyyy HH:mm:ss") ;
Date date = new Date() ;
String nom=requete.getNom() ;
if (requete.getType()>0){
String mimetype=requete.getMimetype() ;
writeline("HTTP/1.0 200 OK") ;
if (requete.getType()!=5)
// Lorsque la requete demande l'execution d'un script shell (demande de type 5), le content-type y est déjà compris
// il ne faut donc pas le réécrire.
writeline("Content-type :"+mimetype+"\n") ;
// Type 1 lorsque URL est /date
if(requete.getType()==1){
writeline("Date courante : ") ;
writeline(dateFormat.format(date)+"\n") ;
}
else if (requete.getType()==5) {
try {
String[] commande = new String[1] ;
String paramFin ;
commande[0]=requete.getChemin() ;
System.out.println(commande[0]);
if (requete.getParametre()!="") {
String[] param=requete.getParametre().split("&") ;
paramFin=" "+param[0].split("=")[1]+" "+param[1].split("=")[1] ;
}
else
paramFin="" ;
Process myp = Runtime.getRuntime().exec(commande[0]+paramFin);
System.out.println(commande[0]+paramFin);
myp.waitFor();
// attention, cette attente peut bloquer si la commande externe rencontre un problème
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(myp.getInputStream()));
while((line = in.readLine()) != null) {
writeline(line);
}
}
catch(Exception e) {
writeline("error");
}
}
else if (requete.getType()==2){
writeline("<!doctype html>");
writeline("<html lang='fr'>") ;
writeline("<head>") ;
writeline(" <meta charset=utf-8>") ;
writeline(" <title>"+nom+" </title>") ;
writeline(" <link rel='stylesheet' href='style.css'>") ;
writeline("</head>") ;
writeline("<body>") ;
writeline("<h1> Le Répertoire "+String.valueOf(requete)+" contient : </h1>") ;
File repertoire = new File(requete.getChemin());
File[] sousRep = repertoire.listFiles();
writeline("<ul>") ;
for(File s:sousRep){
writeline("<li> <a href=\"http://localhost:1234/."+ s.getPath()+"\">"+s.getName()+"</a> </li>");
System.out.println(s.getPath());
}
writeline("</ul>") ;
writeline("</body>") ;
writeline("</html>") ;
}
else if (requete.getType()==3){
ecrireFichier(requete.getChemin()) ;
}
else if (requete.getType()==4){
writeline("<!DOCTYPE html>");
writeline("<html lang=\"fr_FR\">") ;
writeline("<head>") ;
writeline("<meta charset=\"utf-8\">") ;
writeline("<meta http-equiv=\"refresh\" content=\"0; URL=http://localhost:1234/"+reformChemin(requete.getChemin())+"/Index.html\">") ;
writeline("</head>") ;
writeline("</html>");
}
}
else if (requete.getType()==0) {
System.out.println("Ok type 0");
writeline("HTTP/1.0 404 Not Found") ;
writeline ("Content-type: text/html \n") ;
writeline("<!DOCTYPE html>");
writeline("<html lang=\"fr_FR\">") ;
writeline("<head>") ;
writeline("<meta charset=\"utf-8\">") ;
writeline("<meta http-equiv=\"refresh\" content=\"0; URL=http://localhost:1234/Erreur404/erreur404.html\">") ;
writeline("</head>") ;
writeline("</html>");
/*writeline("<!DOCTYPE html>") ;
writeline("<html lang=\"fr_FR\">") ;
writeline("<head>") ;
writeline("<meta charset=\"utf-8\">") ;
writeline("<title>Erreur 404</title>") ;
writeline("<link rel=\"stylesheet\" type=\"text/css\" href=\"Erreur404/erreur404.css\">") ;
writeline("</head>") ;
writeline("<body>") ;
writeline("<h1>Erreur 404</h1>") ;
writeline("<div class=image>") ;
writeline("<img src=\"Erreur404/Oups.png\" alt=\"image de Oups\">") ;
writeline("</div>") ;
writeline("<div class=texte>") ;
writeline("<p> Le fichier demandé n'existe pas </p>") ;
writeline("</div>") ;
writeline("</body>") ;
writeline("</html>") ;*/
}
}
private void ecrireFichier(String chemin) throws IOException {
try {
int br ;
byte[] b = new byte[1];
File f ;
f=new File(chemin) ;
FileInputStream fis ;
fis = new FileInputStream(f) ;
br=fis.read(b) ;
while (br>=0) {
write(b) ;
br=fis.read(b) ;
}
}
catch (Exception e) {
return ;
}
}
private static String reformChemin(String chemin) {
String[] partiesChemin = chemin.split(" ");
String res=partiesChemin[0] ;
for (int i=1 ; i<partiesChemin.length ; i++) {
res=res+"%20"+partiesChemin[i] ;
}
res=res.replaceAll("é","%C3%A9") ;
res=res.replaceAll("è", "%C3%A8") ;
res=res.replaceAll("ç", "%C3%A7") ;
return res ;
}
}
|
package org.timer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @Description
* * 同时打开eureka-server eureka-client eureka-client2 eureka-client3,启动本服务,
* 浏览器输入 http://localhost:port/consumer,看访问的那个服务方
* @Author: Administrator
* @Date : 2018/7/11 13 48
*/
@RestController
public class Consumer {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "/consumer")
public String consumer(){
return restTemplate.getForObject("http://eureka-client/hello",String.class);
}
}
|
package Leetcode;
import java.util.HashMap;
import java.util.Stack;
/**
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
* @author AD
*
*/
public class IsValid {
//栈
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' ||s.charAt(i) == '{' ||s.charAt(i) == '[') {
stack.push(s.charAt(i));
}else {
if (stack.size() == 0) {
return false;
}
char c = stack.pop();
char match;
if (s.charAt(i) == ')') {
match = '(';
}else if (s.charAt(i) == '}') {
match = '{';
}else {
match = '[';
}
if (c != match) {
return false;
}
}
}
if (stack.size() != 0) {
return false;
}
return true;
}
//时间复杂度不好
public boolean isValid2(String s) {
int length = 0;
do {
length = s.length();
s = s.replace("()", "").replace("{}", "").replace("[]", "");
} while (length != s.length());
return s.length() == 0;
}
}
|
package interfaz;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import logica.Controlador;
import otros.Utilidades;
public class PanelRegistro extends JDialog {
private JPanel contentPane;
private JTextField nombre_textField;;
private JTable table;
private Controlador control;
private JTextField contrasenya_textField;
private PanelFondo panelFondo;
private JButton btnCrear;
/**
* Create the frame.
*/
public PanelRegistro() {
setBounds(0, 0, 637, 399);
setLocationRelativeTo(null);
setModal(true);
setTitle("Registro nuevo usuario");
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setUndecorated(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panelFondo = new PanelFondo("/imagenes/panelPrincipalFondo3.png");
panelFondo.setBounds(0, 0, 637, 396);
panelFondo.setFocusable(false);
contentPane.add(panelFondo);
JLabel lblNombreJug = new JLabel("NOMBRE:");
lblNombreJug.setForeground(Color.WHITE);
lblNombreJug.setFont(new Font("AR CHRISTY", Font.PLAIN, 11));
lblNombreJug.setBounds(230, 115, 78, 14);
panelFondo.add(lblNombreJug);
nombre_textField = new JTextField();
nombre_textField.setOpaque(false);
nombre_textField.setCaretColor(Color.WHITE);
nombre_textField.setBounds(225, 131, 168, 20);
panelFondo.add(nombre_textField);
nombre_textField.setHorizontalAlignment(SwingConstants.CENTER);
nombre_textField.setColumns(10);
contrasenya_textField = new JPasswordField();
contrasenya_textField.setOpaque(false);
contrasenya_textField.setCaretColor(Color.WHITE);
contrasenya_textField.setBounds(225, 200, 168, 20);
panelFondo.add(contrasenya_textField);
contrasenya_textField.setHorizontalAlignment(SwingConstants.CENTER);
contrasenya_textField.setColumns(10);
contrasenya_textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getExtendedKeyCode() == 10){ //Pulsar Intro
btnCrear.doClick();;
}
}
});
JLabel lblContrasenya = new JLabel("CONTRASEÑA:");
lblContrasenya.setForeground(Color.WHITE);
lblContrasenya.setFont(new Font("AR CHRISTY", Font.PLAIN, 11));
lblContrasenya.setBounds(230, 185, 78, 14);
panelFondo.add(lblContrasenya);
JLabel lblmnimoCaracteres = new JLabel("(mínimo 5 caracteres)");
lblmnimoCaracteres.setForeground(Color.WHITE);
lblmnimoCaracteres.setBounds(265, 224, 88, 14);
panelFondo.add(lblmnimoCaracteres);
lblmnimoCaracteres.setFont(new Font("Tahoma", Font.PLAIN, 9));
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.setBounds(180, 298, 115, 23);
btnCancelar.setForeground(Color.WHITE);
btnCancelar.setFont(new Font("AR CHRISTY", Font.PLAIN, 14));
btnCancelar.setContentAreaFilled(false);
btnCancelar.setBorderPainted(false);
panelFondo.add(btnCancelar);
btnCancelar.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/cancelar20.png")));
btnCrear = new JButton("Crear");
btnCrear.setBounds(341, 298, 115, 23);
btnCrear.setForeground(Color.WHITE);
btnCrear.setFont(new Font("AR CHRISTY", Font.PLAIN, 14));
btnCrear.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/sobre32.png")));
btnCrear.setContentAreaFilled(false);
btnCrear.setBorderPainted(false);
panelFondo.add(btnCrear);
btnCrear.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/crear20.png")));
JLabel lblmximo = new JLabel("(entre 5 y 15 caracteres)");
lblmximo.setForeground(Color.WHITE);
lblmximo.setBounds(260, 155, 107, 14);
panelFondo.add(lblmximo);
lblmximo.setFont(new Font("Tahoma", Font.PLAIN, 9));
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnCrear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String nombreJug = nombre_textField.getText();
String contrasenyaJug = contrasenya_textField.getText();
//nombre no vacio o nulo
boolean nombreOK = true;
if(nombre_textField.getText() == null || nombre_textField.getText().equals("")){
nombreOK = false;
}
//contrasenya no vacia,nula o menor de 5 letras
boolean passOK = true;
if(contrasenya_textField.getText() == null || contrasenya_textField.getText().equals("")){
passOK = false;
}
if(!nombreOK && !passOK){ //ambos campos vacios
JOptionPane.showMessageDialog(contentPane, "Los campos usuario y contraseña estan vacios");
}
else if(!nombreOK){//si nombreOK esta vacio o es nulo
JOptionPane.showMessageDialog(contentPane, "Campo nombre vacio");
}
else if(!passOK){//si passOK esta vacio o es nulo
JOptionPane.showMessageDialog(contentPane, "Campo contraseña vacio");
}
else if(nombreOK && passOK && contrasenya_textField.getText().length() < 5){ //nombre y pass introducidos pero pass < 5 chars
JOptionPane.showMessageDialog(contentPane, "La contraseña debe tener al menos 5 caracteres");
passOK = false;
}
else if(nombreOK && passOK && (nombre_textField.getText().length() < 5 || nombre_textField.getText().length() > 15)){
JOptionPane.showMessageDialog(contentPane, "El nombre tiene que contener entre 5 y 15 caracteres");
nombreOK = false;
}
//si los dos campos se rellenan correctamente
if(nombreOK && passOK){
try{
control = new Controlador();
String encriptado = Utilidades.Encriptar(contrasenyaJug);
System.out.println(encriptado);
boolean creado = control.crearJugador(nombreJug, encriptado);
if(creado){
JOptionPane.showMessageDialog(contentPane, "Jugador creado con éxito");
dispose();
}
else{//no creado
JOptionPane.showMessageDialog(contentPane, "El nombre ya existe");
//borrar campos
nombre_textField.setText("");
contrasenya_textField.setText("");
nombre_textField.requestFocus();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
}
|
package com.goldgov.dygl.module.partymemberSh.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.ShConstant;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partymember.service.IPartyMemberService_CI;
import com.goldgov.dygl.module.partymemberSh.dao.ICheckInfoDao;
import com.goldgov.dygl.module.partymemberSh.domain.CheckInfo;
import com.goldgov.dygl.module.partymemberSh.service.CheckInfoQuery;
import com.goldgov.dygl.module.partymemberSh.service.ICheckInfoService;
import com.goldgov.dygl.module.partyorganization.service.PartyOrganization;
import com.goldgov.dygl.module.pmuserinfo.service.IPmUserAwardInfoService;
import com.goldgov.gtiles.api.IUser;
import com.goldgov.gtiles.core.security.AuthorizedDetails;
import com.goldgov.gtiles.core.web.UserHolder;
import com.goldgov.gtiles.module.user.service.User;
@Service("checkinfoServiceImpl")
public class CheckInfoServiceImpl implements ICheckInfoService {
@Autowired
@Qualifier("checkinfoDao")
private ICheckInfoDao checkinfoDao;
@Autowired
@Qualifier("partyMemberService_CI")
private IPartyMemberService_CI partyMemberService_CI;
@Autowired
@Qualifier("pmUserAwardInfoService")
private IPmUserAwardInfoService pmUserAwardInfoService;
@Override
public void addInfo(CheckInfo checkinfo) throws NoAuthorizedFieldException {
checkinfoDao.addInfo(checkinfo);
}
@Override
public void updateInfo(CheckInfo checkinfo) throws NoAuthorizedFieldException {
checkinfoDao.updateInfo(checkinfo);
}
@Override
public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException {
checkinfoDao.deleteInfo(entityIDs);
}
@Override
public List<CheckInfo> findInfoList(CheckInfoQuery query) throws NoAuthorizedFieldException {
return checkinfoDao.findInfoListByPage(query);
}
@Override
public CheckInfo findInfoById(String entityID) throws NoAuthorizedFieldException {
return checkinfoDao.findInfoById(entityID);
}
@Override
public void updateInfoByIds(String[] ids, Integer shStatus,
String shUser, String shUserName, Date shDate, String shOrg,
String shOrgName, String shDescribe) {
checkinfoDao.updateInfoByIds(ids,shStatus,shUser,shUserName,shDate,shOrg,shOrgName,shDescribe);
updateBackInfo(ids,shStatus);
}
@Override
public CheckInfo getPassState(String infoId, String shType) {
//先查询出是否存在审核未通过的信息
Integer[] ss={CheckInfo.SH_STATUS_UNSH,CheckInfo.SH_STATUS_GOBACK};
CheckInfo ci=checkinfoDao.getPassState(infoId,shType,ss);
if(ci==null){
Integer[]ss2={CheckInfo.SH_STATUS_PASS};
ci=checkinfoDao.getPassState(infoId,shType,ss2);
}
return ci;
}
@Override
public void addCheckInfo(String infoId, String shType,String shTitle) {
//首先判断信息是否存在 , 待审核 及 审核驳回 若存在则 修改此审核信息 不存在则新增
Integer[] ss={CheckInfo.SH_STATUS_UNSH,CheckInfo.SH_STATUS_GOBACK};
CheckInfo ci=checkinfoDao.getPassState(infoId,shType,ss);
if(ci==null){
ci=new CheckInfo();
ci.setInfoId(infoId);
ci.setShType(shType);
ci.setShTitle(shTitle==null?CheckInfo.SH_TYPE_MAP.get(shType):shTitle);
ci.setCreateDate(new Date());
}
IUser user = UserHolder.getUser();
AuthorizedDetails details = (AuthorizedDetails)UserHolder.getUserDetails();
PartyOrganization currentOrganzation = (PartyOrganization) details.getCustomDetails(ShConstant.CURRENT_PARTY_ORGANZATION);//获取当前登陆人所属机构
if(currentOrganzation==null)currentOrganzation=new PartyOrganization();
if(user==null)user=new User();
ci.setShStatus(CheckInfo.SH_STATUS_UNSH);//审核状态
ci.setInfoOrg(currentOrganzation.getEntityID());
ci.setInfoOrgName(currentOrganzation.getName());
if(ci.getShId()==null||ci.getShId().equals("")){
checkinfoDao.addInfo(ci);
}else{
checkinfoDao.updateInfo(ci);
}
}
@Override
public void deleteCheckInfo(String infoId, String shType) {
checkinfoDao.deleteCheckInfo(infoId,shType);
}
private void updateBackInfo(String[] ids, Integer shStatus){
List<CheckInfo> infoList = checkinfoDao.findInfoByIds(ids);
if(infoList!=null && infoList.size()>0){
for(CheckInfo info:infoList){
if(CheckInfo.SH_TYPE_PM_CI.equals(info.getShType())){
partyMemberService_CI.updateAuditInfo(info,shStatus);
}
if(CheckInfo.SH_TYPE_PM_USER_AWARD_INFO.equals(info.getShType())){
pmUserAwardInfoService.updateAuditInfo(info,shStatus);
}
}
}
}
}
|
// Generated from src/Cypher.g4 by ANTLR 4.6
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link CypherListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class CypherBaseListener implements CypherListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterCypher(CypherParser.CypherContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitCypher(CypherParser.CypherContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSingleQuery(CypherParser.SingleQueryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSingleQuery(CypherParser.SingleQueryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterClause(CypherParser.ClauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitClause(CypherParser.ClauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMatch(CypherParser.MatchContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMatch(CypherParser.MatchContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterReturn1(CypherParser.Return1Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitReturn1(CypherParser.Return1Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPattern(CypherParser.PatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPattern(CypherParser.PatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPatternPart(CypherParser.PatternPartContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPatternPart(CypherParser.PatternPartContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPatternElement(CypherParser.PatternElementContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPatternElement(CypherParser.PatternElementContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPatternElementChain(CypherParser.PatternElementChainContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPatternElementChain(CypherParser.PatternElementChainContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNodePattern(CypherParser.NodePatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNodePattern(CypherParser.NodePatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRelationshipPattern(CypherParser.RelationshipPatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRelationshipPattern(CypherParser.RelationshipPatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRelationshipDetail(CypherParser.RelationshipDetailContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRelationshipDetail(CypherParser.RelationshipDetailContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterProperties(CypherParser.PropertiesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitProperties(CypherParser.PropertiesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRelationshipTypes(CypherParser.RelationshipTypesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRelationshipTypes(CypherParser.RelationshipTypesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNodeLabels(CypherParser.NodeLabelsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNodeLabels(CypherParser.NodeLabelsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRangeLiteral(CypherParser.RangeLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRangeLiteral(CypherParser.RangeLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLabelName(CypherParser.LabelNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLabelName(CypherParser.LabelNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRelTypeName(CypherParser.RelTypeNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRelTypeName(CypherParser.RelTypeNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExpression(CypherParser.ExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExpression(CypherParser.ExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_not(CypherParser.Exp_notContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_not(CypherParser.Exp_notContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_arithmatic(CypherParser.Exp_arithmaticContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_arithmatic(CypherParser.Exp_arithmaticContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_binary(CypherParser.Exp_binaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_binary(CypherParser.Exp_binaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_muldiv(CypherParser.Exp_muldivContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_muldiv(CypherParser.Exp_muldivContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_xor(CypherParser.Exp_xorContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_xor(CypherParser.Exp_xorContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_unary(CypherParser.Exp_unaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_unary(CypherParser.Exp_unaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp_basic(CypherParser.Exp_basicContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp_basic(CypherParser.Exp_basicContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExpression2(CypherParser.Expression2Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExpression2(CypherParser.Expression2Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAtom(CypherParser.AtomContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAtom(CypherParser.AtomContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLiteral(CypherParser.LiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLiteral(CypherParser.LiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNumberLiteral(CypherParser.NumberLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNumberLiteral(CypherParser.NumberLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterBooleanLiteral(CypherParser.BooleanLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitBooleanLiteral(CypherParser.BooleanLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterListLiteral(CypherParser.ListLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitListLiteral(CypherParser.ListLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMapLiteral(CypherParser.MapLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMapLiteral(CypherParser.MapLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPartialComparisonExpression(CypherParser.PartialComparisonExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPartialComparisonExpression(CypherParser.PartialComparisonExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterParenthesizedExpression(CypherParser.ParenthesizedExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitParenthesizedExpression(CypherParser.ParenthesizedExpressionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRelationshipsPattern(CypherParser.RelationshipsPatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRelationshipsPattern(CypherParser.RelationshipsPatternContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPropertyLookup(CypherParser.PropertyLookupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPropertyLookup(CypherParser.PropertyLookupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPropertyKeyName(CypherParser.PropertyKeyNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPropertyKeyName(CypherParser.PropertyKeyNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVariable(CypherParser.VariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVariable(CypherParser.VariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterIntegerLiteral(CypherParser.IntegerLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitIntegerLiteral(CypherParser.IntegerLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDoubleLiteral(CypherParser.DoubleLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDoubleLiteral(CypherParser.DoubleLiteralContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSymbolicName(CypherParser.SymbolicNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSymbolicName(CypherParser.SymbolicNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLeftArrowHead(CypherParser.LeftArrowHeadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLeftArrowHead(CypherParser.LeftArrowHeadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRightArrowHead(CypherParser.RightArrowHeadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRightArrowHead(CypherParser.RightArrowHeadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDash(CypherParser.DashContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDash(CypherParser.DashContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
}
|
package com.mx.profuturo.bolsa.model.service.dto;
public class ImagenGaleriaDTO {
private int orden;
private String imagen;
public int getOrden() {
return orden;
}
public void setOrden(int orden) {
this.orden = orden;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
|
public class Palindrome {
// Constraints: no extra buffer
public boolean isPalindrome(String str) {
if(str==null || str.length()==0 || str.length()==1)
return true;
int len = str.length();
int begin = 0;
int end = len - 1;
while(begin<end) {
if(str.charAt(begin++)==str.charAt(end--)) continue;
else return false;
}
return true;
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.properties;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Frame;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTDocument;
/**
* HTMLPreview
*
* @author jllort
*
*/
public class HTMLPreview extends Composite{
private Frame iframe;
/**
* HTMLPreview
*/
public HTMLPreview() {
iframe = new Frame("about:blank");
DOM.setElementProperty(iframe.getElement(), "frameborder", "0");
DOM.setElementProperty(iframe.getElement(), "marginwidth", "0");
DOM.setElementProperty(iframe.getElement(), "marginheight", "0");
//DOM.setElementProperty(iframe.getElement(), "scrolling", "yes");
// Commented because on IE show clear if allowtransparency=true
DOM.setElementProperty(iframe.getElement(), "allowtransparency", "false");
iframe.setStyleName("okm-Iframe");
iframe.addStyleName("okm-EnableSelect");
initWidget(iframe);
}
/**
* showHTML
*/
public void showHTML(GWTDocument doc) {
iframe.setUrl(Main.CONTEXT + "/HtmlPreview?mimeType=" + doc.getMimeType() + "&uuid=" + doc.getUuid());
}
/**
* isPreviewAvailable
*/
public static boolean isPreviewAvailable(String mime) {
return mime.equals("text/html") ;
}
}
|
package com.shangcai.entity.common;
import java.util.Date;
import com.irille.core.repository.orm.Column;
import com.irille.core.repository.orm.ColumnBuilder;
import com.irille.core.repository.orm.ColumnFactory;
import com.irille.core.repository.orm.ColumnTemplate;
import com.irille.core.repository.orm.Entity;
import com.irille.core.repository.orm.IColumnField;
import com.irille.core.repository.orm.IColumnTemplate;
import com.irille.core.repository.orm.Table;
import com.irille.core.repository.orm.TableFactory;
import irille.pub.tb.EnumLine;
import irille.pub.tb.IEnumOpt;
public class Member extends Entity {
public static final Table<Member> table = TableFactory.entity(Member.class).column(T.values()).create();
public enum T implements IColumnField {
PKEY(ColumnTemplate.PKEY),
TYPE(ColumnFactory.opt(Type.company).showName("用户类型")),
NAME(ColumnTemplate.STR.length(25).showName("名字").comment("最少一个字符,最多25个字符;不能包含特殊字符。")),
HEAD_PIC(ColumnTemplate.STR__200.nullable(true).showName("头像")),
CONTACT_NUMBER(ColumnTemplate.STR__200_NULL.nullable(true).showName("联系电话")),
QRCODE(ColumnTemplate.STR__200.nullable(true).showName("我的二维码")),
PROVINCE(ColumnFactory.manyToOne(Province.T.PKEY).nullable(true).showName("省份")),
CITY(ColumnFactory.manyToOne(City.T.PKEY).nullable(true).showName("城市")),
PV_COUNT(ColumnTemplate.INT__11_ZERO.showName("浏览量").comment("浏览量,需要加上缓存数据才是实时数据")),
WORKS_COUNT(ColumnTemplate.INT__11_ZERO.showName("作品数").comment("作品数,冗余字段")),
FOLLOWING_COUNT(ColumnTemplate.INT__11_ZERO.showName("关注数").comment("关注数,冗余字段")),
FOLLOWER_COUNT(ColumnTemplate.INT__11_ZERO.showName("粉丝数").comment("粉丝数,冗余字段")),
WX_OPEN_ID(ColumnTemplate.STR__200_NULL.showName("微信openid")),
WX_UNION_ID(ColumnTemplate.STR__200_NULL.showName("微信unionid")),
CREATED_TIME(ColumnTemplate.TIME.showName("注册时间")),
;
private Column column;
T(IColumnTemplate template) {
this.column = template.builder().create(this);
}
T(ColumnBuilder builder) {
this.column = builder.create(this);
}
@Override
public Column column() {
return column;
}
}
public enum Type implements IEnumOpt{
company(1,"鞋企"), designer(2,"设计师");
public static final String NAME="用户类型";
private EnumLine _line;
private Type(int key, String name) {_line=new EnumLine(this,key,name); }
@Override
public EnumLine getLine() {
return _line;
}
}
// >>>以下是自动产生的源代码行--源代码--请保留此行用于识别>>>
// 实例变量定义-----------------------------------------
private Integer pkey; // 主键 INT(11)
private Byte type; // 用户类型<Type> TINYINT(4)
// company:1,鞋企
// designer:2,设计师
private String name; // 名字 VARCHAR(25)
private String headPic; // 头像 VARCHAR(200)<null>
private String contactNumber; // 联系电话 VARCHAR(200)<null>
private String qrcode; // 我的二维码 VARCHAR(200)<null>
private Integer province; // 省份<表主键:Province> INT(11)<null>
private Integer city; // 城市<表主键:City> INT(11)<null>
private Integer pvCount; // 浏览量 INT(11)
private Integer worksCount; // 作品数 INT(11)
private Integer followingCount; // 关注数 INT(11)
private Integer followerCount; // 粉丝数 INT(11)
private String wxOpenId; // 微信openid VARCHAR(200)<null>
private String wxUnionId; // 微信unionid VARCHAR(200)<null>
private Date createdTime; // 注册时间 DATETIME(0)
@Override
public Member init() {
super.init();
type = Type.company.getLine().getKey(); // 用户类型<Type> TINYINT(4)
name = null; // 名字 VARCHAR(25)
headPic = null; // 头像 VARCHAR(200)
contactNumber = null; // 联系电话 VARCHAR(200)
qrcode = null; // 我的二维码 VARCHAR(200)
province = null; // 省份 INT(11)
city = null; // 城市 INT(11)
pvCount = 0; // 浏览量 INT(11)
worksCount = 0; // 作品数 INT(11)
followingCount = 0; // 关注数 INT(11)
followerCount = 0; // 粉丝数 INT(11)
wxOpenId = null; // 微信openid VARCHAR(200)
wxUnionId = null; // 微信unionid VARCHAR(200)
createdTime = null; // 注册时间 DATETIME(0)
return this;
}
// 方法------------------------------------------------
public Integer getPkey() {
return pkey;
}
public void setPkey(Integer pkey) {
this.pkey = pkey;
}
public Byte getType() {
return type;
}
public void setType(Byte type) {
this.type = type;
}
public Type gtType() {
return (Type)(Type.company.getLine().get(type));
}
public void stType(Type type) {
this.type = type.getLine().getKey();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getQrcode() {
return qrcode;
}
public void setQrcode(String qrcode) {
this.qrcode = qrcode;
}
public Integer getProvince() {
return province;
}
public void setProvince(Integer province) {
this.province = province;
}
public Province gtProvince() {
return selectFrom(Province.class, getProvince());
}
public void stProvince(Province province) {
this.province = province.getPkey();
}
public Integer getCity() {
return city;
}
public void setCity(Integer city) {
this.city = city;
}
public City gtCity() {
return selectFrom(City.class, getCity());
}
public void stCity(City city) {
this.city = city.getPkey();
}
public Integer getPvCount() {
return pvCount;
}
public void setPvCount(Integer pvCount) {
this.pvCount = pvCount;
}
public Integer getWorksCount() {
return worksCount;
}
public void setWorksCount(Integer worksCount) {
this.worksCount = worksCount;
}
public Integer getFollowingCount() {
return followingCount;
}
public void setFollowingCount(Integer followingCount) {
this.followingCount = followingCount;
}
public Integer getFollowerCount() {
return followerCount;
}
public void setFollowerCount(Integer followerCount) {
this.followerCount = followerCount;
}
public String getWxOpenId() {
return wxOpenId;
}
public void setWxOpenId(String wxOpenId) {
this.wxOpenId = wxOpenId;
}
public String getWxUnionId() {
return wxUnionId;
}
public void setWxUnionId(String wxUnionId) {
this.wxUnionId = wxUnionId;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
// <<<以上是自动产生的源代码行--源代码--请保留此行用于识别<<<
}
|
package com.worker.framework.python;
import java.util.List;
import com.worker.shared.WorkMessage;
public class PythonResponse {
enum Command {
ACK,
ERROR
}
private Command command;
private String msg;
private List<WorkMessage> triggeredTasks;
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<WorkMessage> getTriggeredTasks() {
return triggeredTasks;
}
public void setTriggeredTasks(List<WorkMessage> triggeredTasks) {
this.triggeredTasks = triggeredTasks;
}
}
|
package net.suntrans.haipopeiwang;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.widget.ImageView;
import android.widget.TableLayout;
import com.bumptech.glide.Glide;
import net.suntrans.haipopeiwang.activity.LoginActivity;
import org.jetbrains.annotations.Nullable;
/**
* Created by Looney on 2018/8/17.
* Des:
*/
public class SplashActivity extends BaseActivity {
@Override
public int getLayoutResId() {
return R.layout.activity_splash;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String access_token = App.Companion.getSharedPreferences().getString("access_token", "-1");
if (access_token == "-1") {
handler.sendEmptyMessageDelayed(MSG_LOGIN, 1800);
} else {
long expires_in = App.Companion.getSharedPreferences().getLong("expires_in", 0l);
long loginedTime = App.Companion.getSharedPreferences().getLong("currentTimeMillis", 0l);
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - 3600 * 1000 >= (loginedTime + expires_in * 1000)) { //token过期了
handler.sendEmptyMessageDelayed(MSG_LOGIN, 1800);
} else {
handler.sendEmptyMessageDelayed(MSG_MAIN, 1800);
}
}
ImageView imageView = findViewById(R.id.imgLauncher);
Glide.with(this)
.load(R.drawable.splash)
.into(imageView);
}
private static final int MSG_LOGIN = 1;
private static final int MSG_MAIN = 2;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOGIN:
LoginActivity.Companion.start(SplashActivity.this);
finish();
break;
case MSG_MAIN:
MainActivity.Companion.start(SplashActivity.this);
finish();
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onDestroy() {
handler.removeCallbacksAndMessages(null);
super.onDestroy();
}
public static void main(String[] args) {
TabLayout tableLayout = null;
int[] s = {11, 5, 6, 8, 2, 1, 3, 4};
for (int i :
s) {
System.out.print(i + ",");
}
bubble_sort(s);
System.out.println();
for (int i :
s) {
System.out.print(i + ",");
}
}
public static void bubble_sort(int[] arr) {
int i, j, temp, len = arr.length;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
|
package com.lubarov.daniel.wedding;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.web.html.AnchorBuilder;
import com.lubarov.daniel.web.html.Element;
import com.lubarov.daniel.web.html.ParagraphBuilder;
import com.lubarov.daniel.web.http.HttpRequest;
import com.lubarov.daniel.web.http.HttpResponse;
import com.lubarov.daniel.web.http.HttpStatus;
import com.lubarov.daniel.web.http.server.PartialHandler;
import com.lubarov.daniel.web.http.server.util.HttpResponseFactory;
public class WeddingGiftsHandler implements PartialHandler {
public static final WeddingGiftsHandler singleton = new WeddingGiftsHandler();
private WeddingGiftsHandler() {}
@Override
public Option<HttpResponse> tryHandle(HttpRequest request) {
if (!request.getResource().equals("/gifts"))
return Option.none();
Element honeyFund = new AnchorBuilder()
.setHref("https://www.honeyfund.com/wedding/DanielVi")
.setTitle("Honeyfund")
.addEscapedText("Honeyfund page")
.build();
Element intro = new ParagraphBuilder()
.addEscapedText("Gifts are totally optional; you can bring something if you like but it isn't expected. We also set up a ")
.addChild(honeyFund)
.addEscapedText(" if you'd like to help fund our honeymoon in Europe!")
.build();
Element document = WeddingLayout.createDocument(Option.some("Gifts"), intro);
return Option.some(HttpResponseFactory.xhtmlResponse(HttpStatus.OK, document));
}
}
|
package com.hp.action;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import com.hp.model.Builds;
import com.hp.utility.DBUtils;
import com.hp.utility.TimeUtils;
import com.opensymphony.xwork2.ActionSupport;
public class BuildAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 2241993631556593099L;
/**
*
*/
private String rows;//every page number from easyui data
private String page;//current page number from easyui data
private String data; //easyui from the front page get the data
private String sort; //the front page sort field
private String order; //desc or asc
public JSONObject latestBuildObj=null;
private JSONObject newBuildObj=null;
private JSONObject deleteBuildObj=null;
private JSONObject searchBuildObj=null;
private Builds build;
//database object
private Connection con=null;
private PreparedStatement ps=null;
private ResultSet rs=null;
private int totalrows=0;
//jdbc database object
String sql="select * from BUILD_SUMMARY t where t.BUILD_STATUS!='invalid' order by t.START_TIME desc LIMIT ?,?";
DBUtils db=new DBUtils();
//new build execution sql
String checkidsql="select count(*) as numbers from build_summary bs WHERE bs.BUILD_ID=?";
String updateidsql="update build_summary bs set bs.BUILD_NAME=?,bs.BUILD_STATUS=?,"
+ "bs.BUILD_TYPE=?,bs.BUILD_COMMENT=?,bs.START_TIME=?,bs.END_TIME=? where bs.BUILD_ID=?";
//String newidsql="insert INTO build_summary (BUILD_ID,BUILD_TYPE,BUILD_NAME,BUILD_STATUS,BUILD_COMMENT,START_TIME,END_TIME) "
// + "values(?,?,?,?,?,?,?)";
String deletesql="delete from build_summary where BUILD_ID=?";
public String latestBuild()
{
System.out.println("**********build list***************************************************************");
// System.out.println("search user name is :"+search.getUser());
System.out.println("Front json page number is :"+page);
System.out.println("Front json total number is :"+rows);
System.out.println("sort field is:"+sort);
System.out.println("sort is:"+order);
//
//current page number 1,2,3,4
int intPage = Integer.parseInt((page == null || page == "0") ? "1":page);
//every page total number
int number = Integer.parseInt((rows == null || rows == "0") ? "20":rows);
//every page start index first is 1 second is number +1
int start = (intPage-1)*number;
// int end=start+number-1;
Map<String, Object> totaldata=new HashMap<String,Object>();
List<Map<String, Object>> totalrecord =new ArrayList<Map<String, Object>>();
System.out.print("Page start:"+start);
System.out.println("Page numbers:"+number);
try{
con=db.getConnection();
ps=db.getPreparedStatement(con, sql);
System.out.println("Get result from :"+start+",select number are :"+number);
ps.setInt(1, start);
ps.setInt(2, number);
rs=ps.executeQuery();
while(rs.next())
{
String starttime,endtime;
// int likenumber,dislikenumber;
Map<String, Object> buildmap=new HashMap<String, Object>();
buildmap.put("build_id",rs.getInt("BUILD_ID"));
System.out.println("build id is:"+rs.getInt("build_id"));
buildmap.put("build_status", rs.getString("BUILD_STATUS"));
System.out.println("build id is:"+rs.getString("build_status"));
buildmap.put("build_type",rs.getString("BUILD_TYPE"));
buildmap.put("build_name", rs.getString("BUILD_NAME"));
buildmap.put("build_comment", rs.getString("BUILD_COMMENT"));
if(rs.getString("START_TIME")==null){
starttime="";
}else{
starttime=rs.getString("START_TIME");
}
if(rs.getString("END_TIME")==null){
endtime="";
}else{
endtime=rs.getString("END_TIME");
}
buildmap.put("build_starttime",starttime);
buildmap.put("build_endtime",endtime);
System.out.println("build id is:"+rs.getString("end_time"));
buildmap.put("likenumber",rs.getInt("LIKE"));
System.out.println("like number is :"+rs.getInt("like"));
buildmap.put("dislikenumber",rs.getInt("DISLIKE"));
totalrecord.add(buildmap);
// System.out.println("totalrecord:"+totalrecord.toString());
}
totalrows=db.getTotalRows(con, "BUILD_SUMMARY");
db.closeResultSet(rs);
db.closePreparedStatement(ps);
db.closeConnction(con);
totaldata.put("success", true);
}
catch(Exception e)
{
System.out.println("the blow is the error exception:");
System.out.println(e);
totaldata.put("errorMsg", e);
totaldata.put("success",false);
}
totaldata.put("rows",totalrecord);
totaldata.put("total",totalrows);
latestBuildObj=JSONObject.fromObject(totaldata);
return SUCCESS;
}
//save a new build from the front page data
public String saveBuild(){
System.out.println("build id:"+build.getId());
System.out.println("build name:"+build.getName());
System.out.println("build type:"+build.getType());
System.out.println("build status:"+build.getStatus());
System.out.println("build start time:"+build.getStarttime());
System.out.println("build end time :"+build.getEndtime());
System.out.println("build new defect:"+build.getNewdefects());
System.out.println("build old defect:"+build.getOlddefects());
System.out.println("build comment:"+build.getComments());
// insert this record
Map<String, Object> newmap=new HashMap<String, Object>();
try {
int buildgot=0;
con=db.getConnection();
ps=db.getPreparedStatement(con, checkidsql);
ps.setInt(1, build.getId());
rs=ps.executeQuery();
while(rs.next()){
buildgot=rs.getInt("numbers");
}
System.out.println("build execution id count is:"+buildgot);
//get the specified execution id,will update it
if(buildgot>0){
System.out.print("this build id is created before ,we just need to update the execution result");
ps=db.getPreparedStatement(con, updateidsql);
ps.setString(1,build.getName() ); //build name
ps.setString(2, build.getStatus());
ps.setString(3,build.getType() );
ps.setString(4,build.getComments() );
System.out.println("format time is :"+TimeUtils.formatTime(build.getStarttime()));
ps.setString(5,TimeUtils.formatTime(build.getStarttime()) );
ps.setString(6,TimeUtils.formatTime(build.getEndtime()) );
ps.setInt(7,build.getId());
int updateresult=ps.executeUpdate();
if(updateresult==1){
newmap.put("success", true);
System.out.println("Insert this record into database correctly now ...");
}else{
newmap.put("success",false);
System.out.println("Failed, cannot insert this record");
}
}else{
newmap.put("success",false);
System.out.println("Sorry ,you need to input the existing exeuction id");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
db.closeResultSet(rs);
db.closePreparedStatement(ps);
db.closeConnction(con);
}
newBuildObj=JSONObject.fromObject(newmap);
System.out.println("get the json object is:"+newBuildObj);
return SUCCESS;
}
public String deleteBuild(){
System.out.println("build id:"+build.getId());
// insert this record
Map<String, Object> newmap=new HashMap<String, Object>();
try {
int buildgot=0;
con=db.getConnection();
ps=db.getPreparedStatement(con, deletesql);
ps.setInt(1, build.getId());
buildgot=ps.executeUpdate();
System.out.println("build execution id count is:"+buildgot);
//get the specified execution id,will update it
if(buildgot==1){
newmap.put("success", true);
System.out.println("Insert this record into database correctly now ...");
}else{
newmap.put("success",false);
System.out.println("Failed, cannot insert this record");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
db.closeResultSet(rs);
db.closePreparedStatement(ps);
db.closeConnction(con);
}
deleteBuildObj=JSONObject.fromObject(newmap);
System.out.println("get the json object is:"+deleteBuildObj);
return SUCCESS;
}
public String searchBuild(){
System.out.println("Front json page number is :"+page);
System.out.println("Front json total number is :"+rows);
System.out.println("sort field is:"+sort);
System.out.println("sort is:"+order);
//
int totalsearchlist=0;
//current page number 1,2,3,4
int intPage = Integer.parseInt((page == null || page == "0") ? "1":page);
//every page total number
int number = Integer.parseInt((rows == null || rows == "0") ? "20":rows);
//every page start index first is 1 second is number +1
int start = (intPage-1)*number;
// int end=start+number-1;
System.out.print("Page start:"+start);
System.out.println("Page numbers:"+number);
System.out.println("start time is:"+build.getStarttime());
System.out.println("end time is:"+build.getEndtime());
System.out.println("type is:"+build.getType());
System.out.println("build id is:"+build.getId());
Map<String, Object> totaldata=new HashMap<String,Object>();
List<Map<String, Object>> newsearchlist =new ArrayList<Map<String, Object>>();
String searchsql="SELECT * FROM BUILD_SUMMARY t WHERE t.BUILD_STATUS != 'invalid' ";
if(!build.getStarttime().equals("")){
searchsql+=" AND date(t.START_TIME) >='"+build.getStarttime()+"'";
}
if(!build.getEndtime().equals("")){
searchsql+=" and date(t.START_TIME) <='"+build.getEndtime()+"'";
}
if(!build.getType().equals("")){
searchsql+=" and t.BUILD_TYPE like '%"+build.getType()+"%'";
}
if(build.getId()!=null){
searchsql+=" and t.BUILD_ID="+build.getId();
}
searchsql+=" ORDER BY t.START_TIME DESC LIMIT ?,?";
System.out.println("search sql is:"+searchsql);
try {
con=db.getConnection();
ps=db.getPreparedStatement(con, searchsql);
ps.setInt(1, start);
ps.setInt(2, number);
rs=ps.executeQuery();
while(rs.next())
{
totalsearchlist=totalsearchlist+1;
String starttime,endtime;
// int likenumber,dislikenumber;
Map<String, Object> buildmap=new HashMap<String, Object>();
buildmap.put("build_id",rs.getInt("BUILD_ID"));
System.out.println("build id is:"+rs.getInt("build_id"));
buildmap.put("build_status", rs.getString("BUILD_STATUS"));
System.out.println("build id is:"+rs.getString("build_status"));
buildmap.put("build_type",rs.getString("BUILD_TYPE"));
buildmap.put("build_name", rs.getString("BUILD_NAME"));
buildmap.put("build_comment", rs.getString("BUILD_COMMENT"));
if(rs.getString("START_TIME")==null){
starttime="";
}else{
starttime=rs.getString("START_TIME");
}
if(rs.getString("END_TIME")==null){
endtime="";
}else{
endtime=rs.getString("END_TIME");
}
buildmap.put("build_starttime",starttime);
buildmap.put("build_endtime",endtime);
System.out.println("build id is:"+rs.getString("end_time"));
buildmap.put("likenumber",rs.getInt("LIKE"));
System.out.println("like number is :"+rs.getInt("like"));
buildmap.put("dislikenumber",rs.getInt("DISLIKE"));
newsearchlist.add(buildmap);
// System.out.println("totalrecord:"+totalrecord.toString());
}
//totalrows=db.getTotalRows(con, "BUILD_SUMMARY");
db.closeResultSet(rs);
db.closePreparedStatement(ps);
db.closeConnction(con);
totaldata.put("success", true);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
db.closeResultSet(rs);
db.closePreparedStatement(ps);
db.closeConnction(con);
}
totaldata.put("rows",newsearchlist);
totaldata.put("total",totalsearchlist);
searchBuildObj=JSONObject.fromObject(totaldata);
return SUCCESS;
}
public String getRows() {
return rows;
}
public void setRows(String rows) {
this.rows = rows;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public JSONObject getLatestBuildObj() {
return latestBuildObj;
}
public void setLatestBuildObj(JSONObject latestBuildObj) {
this.latestBuildObj = latestBuildObj;
}
/**
* @return the newBuildObj
*/
public JSONObject getNewBuildObj() {
return newBuildObj;
}
/**
* @param newBuildObj the newBuildObj to set
*/
public void setNewBuildObj(JSONObject newBuildObj) {
this.newBuildObj = newBuildObj;
}
/**
* @return the build
*/
public Builds getBuild() {
return build;
}
/**
* @param build the build to set
*/
public void setBuild(Builds build) {
this.build = build;
}
public JSONObject getDeleteBuildObj() {
return deleteBuildObj;
}
public void setDeleteBuildObj(JSONObject deleteBuildObj) {
this.deleteBuildObj = deleteBuildObj;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public JSONObject getSearchBuildObj() {
return searchBuildObj;
}
public void setSearchBuildObj(JSONObject searchBuildObj) {
this.searchBuildObj = searchBuildObj;
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class BOJ_19237_어른상어 {
private static StringBuilder sb = new StringBuilder();
private static int[][] dir = {{0,0},{-1,0},{1,0},{0,-1},{0,1}};
private static int N,M,K;
private static Pair[][] map;
private static Pair[][] mapClone;
private static int[][][] prior;
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());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
// map과 clone
map = new Pair[N][N];
mapClone = new Pair[N][N];
// 상어리스트, 쫒아낼 상어 리스트
List<Shark> list = new ArrayList<>();
List<Integer> rmlist = new ArrayList<>();
// 입력된 값을 넣는다
for (int r = 0; r < N; r++) {
st = new StringTokenizer(br.readLine());
for (int c = 0; c < N; c++) {
map[r][c] = new Pair(false,Integer.parseInt(st.nextToken()), 0);
if(map[r][c].shark !=0) {
map[r][c].smell = K;
map[r][c].isIn = true;
list.add(new Shark(r, c, map[r][c].shark ,-1));
}
mapClone[r][c] = map[r][c];
}
}
// 상어를 역순으로 정렬(idx가 큰 상어는 작은 상어한테 쫒겨나기 때문에 먼저 실행하려고)
st = new StringTokenizer(br.readLine());
Collections.sort(list);
for (int i = M-1; i >= 0; i--) {
list.get(i).dir = Integer.parseInt(st.nextToken());
}
// 우선순위 저장
prior = new int[M][4][4];
for (int n = 0; n < M; n++) {
for (int r = 0; r < 4; r++) {
st = new StringTokenizer(br.readLine());
for (int c = 0; c < 4; c++) {
prior[n][r][c] = Integer.parseInt(st.nextToken());
}
}
}
int q =0;
while(true) {
// 1000초가 넘어가면 -1 출력
if(q == 1001) {
q = -1;
break;
}
// 상어 한마리만 남으면 끝!
if(list.size()==1) break;
// 남은 상어를 이동시킨다
for (int i = 0; i < list.size(); i++) {
// 4방향으로 빈칸 유무 flag
boolean noNull = true;
// 현재상어의 4방향 탐색(빈칸찾기)
for (int j = 1; j < dir.length; j++) {
Shark sh = list.get(i);
int px = dir[prior[sh.num-1][sh.dir-1][j-1]][0] + sh.x;
int py = dir[prior[sh.num-1][sh.dir-1][j-1]][1] + sh.y;
// 만약 빈칸이라면(아직 안옮긴것과 비교해서)
if(isIn(px,py) && map[px][py].smell == 0) {
// 냄새를 남긴다
mapClone[sh.x][sh.y].isIn = false;
// 만약 이미 상어가 있다면 쫓아버리게 따로 리스트에 저장해둔다
if(mapClone[px][py].isIn) {
rmlist.add(mapClone[px][py].shark);
}
// 이동한다
mapClone[px][py] = new Pair(true, mapClone[sh.x][sh.y].shark, K+1);
list.set(i, new Shark(px, py, sh.num, prior[sh.num-1][sh.dir-1][j-1]));
noNull=false;
break;
}
}
// 빈칸이 없다면 자신의 냄새가 있는 칸의 방향
if(noNull) {
for (int j = 1; j < dir.length; j++) {
Shark sh = list.get(i);
int px = dir[prior[sh.num-1][sh.dir-1][j-1]][0] + sh.x;
int py = dir[prior[sh.num-1][sh.dir-1][j-1]][1] + sh.y;
// 만약 빈칸이라면(아직 안옮긴것과 비교해서)
if(isIn(px,py) && map[px][py].shark == mapClone[sh.x][sh.y].shark) {
// 냄새를 남긴다
mapClone[sh.x][sh.y].isIn=false;
// 이동한다
mapClone[px][py] = new Pair(true, mapClone[sh.x][sh.y].shark, K+1);
list.set(i, new Shark(px, py, sh.num, prior[sh.num-1][sh.dir-1][j-1]));
break;
}
}
}
}
// 쫒아낼 리스트에 있는 상어를 삭제한다
for (int i = 0; i < rmlist.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if(list.get(j).num == rmlist.get(i)) {
list.remove(j);
break;
}
}
}
// 냄새 카운트를 하나씩 다운
rmSmell();
// map을 mapClone으로 초기화
init();
q++;
}
System.out.println(q);
}
private static void rmSmell() {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if(mapClone[r][c].smell>0) mapClone[r][c].smell--;
}
}
}
private static void init() {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
map[r][c] = mapClone[r][c];
}
}
}
public static class Shark implements Comparable<Shark>{
int x,y,num,dir;
public Shark(int x, int y, int num, int dir) {
super();
this.x = x;
this.y = y;
this.num = num;
this.dir = dir;
}
@Override
public int compareTo(Shark o) {
Integer num1= this.num;
Integer num2 = o.num;
return num2.compareTo(num1);
}
}
public static class Pair{
Boolean isIn;
int shark, smell;
public Pair(Boolean isIn, int shark, int smell) {
super();
this.isIn = isIn;
this.shark = shark;
this.smell = smell;
}
}
public static boolean isIn(int r, int c) {
return r>=0 && c>=0 && r<N && c<N;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.r.a.a;
import com.tencent.mm.plugin.appbrand.r.a.c;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class z extends n {
public static final int CTRL_INDEX = 425;
public static final String NAME = "getBatteryInfo";
public final String a(l lVar, JSONObject jSONObject) {
c aoB = a.gCg.aoB();
Map hashMap = new HashMap();
hashMap.put("level", Integer.valueOf(aoB.gCq));
hashMap.put("isCharging", Boolean.valueOf(aoB.gCp));
return f("ok", hashMap);
}
}
|
package org.pmedv.core.components;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;
/**
* The <code>ClipBoard</code> simply extends the {@link Stack} class and adds a mode to it. Thus the
* stack can be used as a clipboard with cut and copy functions.
*
* @author Matthias Pueski
*
*/
public class ClipBoard<T> extends Stack<T> {
public static enum Mode {
CUT, COPY
}
private static final long serialVersionUID = 3947356818820543009L;
private Mode mode;
public ClipBoard() {
super();
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public void copy(T item) {
clear();
push(item);
}
public void copyAll(List<T> items) {
clear();
for (T item : items)
push(item);
}
public List<T> paste() {
ArrayList<T> items = new ArrayList<T>();
try {
do {
items.add(pop());
} while(true);
}
catch (EmptyStackException e) {
return items;
}
}
}
|
package main.java.com.java4beginners.ex1;
import java.lang.Math;
public class Circunferencia extends Figura {
private double radio = 0D;
// Puedo usar la librería de java o definir una constante con el valor de PI.
// Esta comentado el codigo porque uso la lib de java.
//private final double PI = 3.14D;
Circunferencia(double radio){
this.radio = radio;
super.nombre = "CIRCUNFERENCIA";
}
@Override
public double calcularPerimetro(){
return 2 * Math.PI * radio;
}
@Override
public double calcularArea(){
return Math.PI * radio * radio;
//return Math.PI*(Math.pow(radio,2)
}
}
|
package com.noteshare.mood.services;
import java.util.List;
import javax.servlet.http.HttpSession;
import com.noteshare.common.model.Page;
import com.noteshare.mood.model.Mood;
public interface MoodService {
/**
* @Title: selectNewestMoods
* @Description: 查询最新的心情列表
* @return List<Mood>
* @author xingchen
* @date 2015-12-27 下午04:09:02
* @throws
*/
public List<Mood> selectNewestMoods();
int deleteByPrimaryKey(Integer id);
int insert(Mood record);
int insertSelective(Mood record);
Mood selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Mood record);
int updateByPrimaryKey(Mood record);
/**
* @Title : addMood
* @Description : 添加心情
* @author : xingchen
* @date : 2016-4-3 上午11:28:26
* @param content :心情内容
* @return : String
*/
public String addMood(String content,HttpSession session);
/**
*
* @Title : selectMoodListByPage
* @Description : 分页查询笔记列表
* @param currentPage : 当前页码
* @param startPageNumber : 分页的开始页码
* @param endPageNumber : 分页的结束页码
* @param size :每页的大小
* @return : Page<Mood> 返回分页对象
* @author : xingchen
* @date : 2016年4月9日 下午6:36:43
* @throws
*/
public Page<Mood> selectMoodListByPage(int currentPage, int startPageNumber,int endPageNumber,int size);
}
|
package GUI.windows;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import java.sql.*;
import java.text.NumberFormat;
import GUI.monitor.SelectMonitor;
import GUI.monitor.SignUPButtonMonitor;
public class SignUPWindow extends JFrame {
private IntTextField userid;
private IntPasswordField password;
private JTextField pname;
private JTextField address;
private JTextField branch;
private String type;
private JFormattedTextField amount;
private String[] TypeString = { "Student-Checking", "Interest-Checking","Savings" };
private final JComboBox<String> TypeList = new JComboBox<>(TypeString);
public void launchSignUPWindow() {
// this.getContentPane().setLayout(new BoxLayout(this.getContentPane(),BoxLayout.Y_AXIS));
this.setLayout(new FlowLayout());
this.setTitle("Sign Up");
this.setSize(240, 260);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
SignUPButtonMonitor subm = new SignUPButtonMonitor(this);
JLabel userLabel = new JLabel("Tax ID: ");
JLabel pwdLabel = new JLabel("PIN: ");
JLabel userName = new JLabel("Your Name: ");
JLabel addressName = new JLabel("Address: ");
JLabel firstAccount = new JLabel("----Create Your First Account----");
JLabel branchName = new JLabel("Branch: ");
JLabel depositAmount = new JLabel("Amount: ");
JLabel typeName = new JLabel("Type: ");
Dimension dim = new Dimension(120, 20);
// Tax ID
this.userid = new IntTextField();
this.userid.setPreferredSize(dim);
this.add(userLabel);
this.add(this.userid);
// PIN
this.password = new IntPasswordField();
this.password.setPreferredSize(dim);
password.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (password.getText().length() >= 4)
e.consume();
}
});
this.add(pwdLabel);
this.add(this.password);
// Name
this.pname = new JTextField();
this.pname.setPreferredSize(dim);
pname.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (pname.getText().length() >= 15)
e.consume();
}
});
this.add(userName);
this.add(this.pname);
// address
this.address = new JTextField();
this.address.setPreferredSize(dim);
this.add(addressName);
this.add(this.address);
this.add(firstAccount);
// branch
this.branch = new JTextField();
this.branch.setPreferredSize(dim);
branch.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (branch.getText().length() >= 11)
e.consume();
}
});
this.add(branchName);
this.add(this.branch);
// amount
this.amount = new JFormattedTextField();
amount.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
Runnable format = new Runnable() {
@Override
public void run() {
String text = amount.getText();
if (!text.matches("\\d*(\\.\\d{0,2})?")) {
amount.setText(text.substring(0, text.length() - 1));
}
}
};
SwingUtilities.invokeLater(format);
}
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
this.amount.setPreferredSize(dim);
this.add(depositAmount);
this.add(this.amount);
// Type
TypeList.setPreferredSize(dim);
this.add(typeName);
this.getContentPane().add(TypeList);
// Register Button
JButton Button1 = new JButton("Register");
Button1.setActionCommand("1");
Button1.setAlignmentX(Component.CENTER_ALIGNMENT);
Button1.setHorizontalAlignment(SwingConstants.CENTER);
Button1.setMinimumSize(new Dimension(100, 20));
Button1.setMaximumSize(new Dimension(150, 30));
Button1.addActionListener(subm);
this.getContentPane().add(Button1);
JButton Back = new JButton("Back");
Back.setActionCommand("2");
Back.addActionListener(subm);
this.add(Back);
this.setVisible(true);
}
public String getUserID() {
return this.userid.getText();
}
public String getPIN() {
return this.password.getText();
}
public String getPname() {
return this.pname.getText();
}
public String getaddress() {
return this.address.getText();
}
public String getBranch() {
return this.branch.getText();
}
public float getAmount() {
float myAmount = 0;
try {
myAmount = Float.parseFloat(this.amount.getText());
} catch (NumberFormatException e) {
System.out.print("Incorrect Format!");
}
return myAmount;
}
public String getAccountType() {
return (String) TypeList.getSelectedItem();
}
}
class IntTextField extends JTextField {
public IntTextField() {
super();
}
protected Document createDefaultModel() {
return new IntTextDocument();
}
// public boolean isValid() {
// try {
// Integer.parseInt(this.getText());
// return true;
// } catch (NumberFormatException e) {
// return false;
// }
// }
public int getValue() {
try {
return Integer.parseInt(getText());
} catch (NumberFormatException e) {
return 0;
}
}
class IntTextDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null)
return;
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str + oldString.substring(offs);
try {
Integer.parseInt(newString + "0");
super.insertString(offs, str, a);
} catch (NumberFormatException e) {
}
}
}
}
class IntPasswordField extends JPasswordField {
public IntPasswordField() {
super();
}
protected Document createDefaultModel() {
return new IntTextDocument();
}
// public boolean isValid() {
// try {
// Integer.parseInt(this.getText());
// return true;
// } catch (NumberFormatException e) {
// return false;
// }
// }
public int getValue() {
try {
return Integer.parseInt(getText());
} catch (NumberFormatException e) {
return 0;
}
}
class IntTextDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null)
return;
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str + oldString.substring(offs);
try {
Integer.parseInt(newString + "0");
super.insertString(offs, str, a);
} catch (NumberFormatException e) {
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.tftp;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.commons.io.FileUtils;
/**
* Main class for TFTPServer. This allows CLI use of the server.
*
* @since 3.6
*/
public class TFTPServerMain {
private static final String USAGE = "Usage: TFTPServerMain [options] [port]\n\n" + "port - the port to use (default 6901)\n"
+ "\t-p path to server directory (default java.io.tempdir)\n" + "\t-r randomly introduce errors\n" + "\t-v verbose (trace packets)\n";
public static void main(final String[] args) throws Exception {
int port = 6901;
int argc;
final Map<String, String> opts = new HashMap<>();
opts.put("-p", FileUtils.getTempDirectoryPath());
// Parse options
for (argc = 0; argc < args.length; argc++) {
final String arg = args[argc];
if (!arg.startsWith("-")) {
break;
}
if (arg.equals("-v") || arg.equals("-r")) {
opts.put(arg, arg);
} else if (arg.equals("-p")) {
opts.put(arg, args[++argc]);
} else {
System.err.println("Error: unrecognized option.");
System.err.print(USAGE);
System.exit(1);
}
}
if (argc < args.length) {
port = Integer.parseInt(args[argc]);
argc++;
}
final boolean verbose = opts.containsKey("-v");
final boolean randomErrors = opts.containsKey("-r");
final Random rand = randomErrors ? new Random() : null;
final File serverDirectory = new File(opts.get("-p"));
System.out.println("Server directory: " + serverDirectory);
final TFTPServer tftpS = new TFTPServer(serverDirectory, serverDirectory, port, TFTPServer.ServerMode.GET_AND_PUT, null, null) {
@Override
TFTP newTFTP() {
if (verbose) {
return new TFTP() {
@Override
protected void trace(final String direction, final TFTPPacket packet) {
System.out.println(direction + " " + packet.toString());
}
};
}
return new TFTP();
}
@Override
void sendData(final TFTP tftp, final TFTPPacket packet) throws IOException {
if (rand == null) {
super.sendData(tftp, packet);
return;
}
final int rint = rand.nextInt(10);
switch (rint) {
case 0:
System.out.println("Bump port " + packet);
final int port = packet.getPort();
packet.setPort(port + 5);
super.sendData(tftp, packet);
packet.setPort(port);
break;
case 1:
if (packet instanceof TFTPDataPacket) {
final TFTPDataPacket data = (TFTPDataPacket) packet;
System.out.println("Change data block num");
data.blockNumber--;
super.sendData(tftp, packet);
data.blockNumber++;
}
if (packet instanceof TFTPAckPacket) {
final TFTPAckPacket ack = (TFTPAckPacket) packet;
System.out.println("Change ack block num");
ack.blockNumber--;
super.sendData(tftp, packet);
ack.blockNumber++;
}
break;
case 2:
System.out.println("Drop packet: " + packet);
break;
case 3:
System.out.println("Dupe packet: " + packet);
super.sendData(tftp, packet);
super.sendData(tftp, packet);
break;
default:
super.sendData(tftp, packet);
break;
}
}
};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Server shutting down");
tftpS.close();
System.out.println("Server exit");
}
});
System.out.println("Started the server on " + port);
Thread.sleep(99999999L);
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import com.tencent.mm.pluginsdk.model.app.g.a;
class JsApiLaunchApplication$a implements a {
volatile boolean bSi;
volatile boolean dJP;
volatile boolean fGh;
volatile boolean fGi;
a fGj;
JsApiLaunchApplication$a(a aVar) {
this.fGj = aVar;
}
public final void cI(boolean z) {
this.dJP = true;
this.fGh = z;
if (this.fGi && this.fGj != null) {
this.fGj.r(this.bSi, z);
}
}
final void cJ(boolean z) {
this.bSi = z;
this.fGi = true;
if (this.dJP && this.fGj != null) {
this.fGj.r(z, this.fGh);
}
}
}
|
public class Exame{
private String name;
private String code;
private String obs;
private String duration;
private String timeResult;
Exame(String name, String code, String obs, String duration, String timeR){
setCode(code);
setName(name);
setObs(obs);
setDuration(duration);
setEstResult(timeR);
}
Exame(){
this.name = "";
this.code = "";
this.obs = "";
this.duration = "";
this.timeResult = "";
}
public String getName(){
return this.name;
}
public int setName(String name){
if(name.length() > 0){
this.name = name;
return -1;
}
return 2;
}
public String getCode(){
return this.code;
}
public int setCode(String code){
if(code.length() > 0){
this.code = code;
return -1;
}
return 2;
}
public String getObs(){
return this.obs;
}
public int setObs(String obs){
if(obs.length() > 0){
this.obs = obs;
return -1;
}
return 2;
}
public String getDuration(){
return this.duration;
}
public int setDuration(String dur){
if(dur.length() > 0){
this.duration = dur;
return -1;
}
return 2;
}
public String estResult(){
return this.timeResult;
}
public int setEstResult(String etr){
if(etr.length() > 0){
this.timeResult = etr;
return -1;
}
return 2;
}
}
|
/*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib.jfr;
import static jdk.test.lib.Asserts.assertEquals;
import static jdk.test.lib.Asserts.fail;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import jdk.jfr.Recording;
import jdk.jfr.RecordingState;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;
import jdk.test.lib.Asserts;
import jdk.test.lib.Utils;
/**
* Common helper class.
*/
public final class CommonHelper {
private static RecordedEvent timeStampCounterEvent;
public static void verifyException(VoidFunction f, String msg, Class<? extends Throwable> expectedException) throws Throwable {
try {
f.run();
} catch (Throwable t) {
if (expectedException.isAssignableFrom(t.getClass())) {
return;
}
t.printStackTrace();
assertEquals(t.getClass(), expectedException, "Wrong exception class");
}
fail("Missing Exception for: " + msg);
}
public static Recording verifyExists(long recId, List<Recording> recordings) {
for (Recording r : recordings) {
if (recId == r.getId()) {
return r;
}
}
Asserts.fail("Recording not found, id=" + recId);
return null;
}
public static void waitForRecordingState(Recording r, RecordingState expectedState) throws Exception {
while (r.getState() != expectedState) {
Thread.sleep(20);
}
}
public static void verifyRecordingState(Recording r, RecordingState expectedState) throws Exception {
assertEquals(expectedState, r.getState(), "Wrong state");
}
public static boolean hasFastTimeEnabled() throws Exception {
return getTimeStampCounterEvent().getValue("fastTimeEnabled");
}
private synchronized static RecordedEvent getTimeStampCounterEvent() throws IOException, Exception {
if (timeStampCounterEvent == null) {
try (Recording r = new Recording()) {
r.enable(EventNames.CPUTimeStampCounter);
r.start();
r.stop();
Path p = Utils.createTempFile("timestamo", ".jfr");
r.dump(p);
List<RecordedEvent> events = RecordingFile.readAllEvents(p);
Files.deleteIfExists(p);
if (events.isEmpty()) {
throw new Exception("Could not locate CPUTimeStampCounter event");
}
timeStampCounterEvent = events.get(0);
}
}
return timeStampCounterEvent;
}
public static void waitForSystemCurrentMillisToChange() {
long t = System.currentTimeMillis();
while (t == System.currentTimeMillis()) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
throw new Error("Sleep interupted", e);
}
}
}
}
|
package cn.com.ykse.santa.service.vo;
/**
* Created by youyi on 2016/2/12.
*/
public class PrjDemandCfgVO {
private Integer prjId;
private Integer demandId;
public Integer getDemandId() {
return demandId;
}
public void setDemandId(Integer demandId) {
this.demandId = demandId;
}
public Integer getPrjId() {
return prjId;
}
public void setPrjId(Integer prjId) {
this.prjId = prjId;
}
}
|
package com.company.ch02_stack_and_queue;
public class LoopQueue<E> implements Queue<E> {
private E queue[];
private int front;
private int tail;
private int size;
public LoopQueue(int Capacity) {
queue = (E[]) new Object[Capacity + 1];
front = 0;
tail = 0;
size = 0;
}
public LoopQueue() {
this(10);
}
public int getCapacity() {
return queue.length - 1;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return front == tail;
}
@Override
public void enqueue(E e) {
if ((tail + 1) % queue.length == front) {
resize(2 * getCapacity());
}
queue[tail] = e;
tail = (tail + 1) % queue.length;
size++;
}
@Override
public E dequeue() {
if (isEmpty()) {
throw new IllegalArgumentException("queue is empty");
}
E tmp = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
size--;
if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
resize(getCapacity() / 2);
}
return tmp;
}
public E getFront() {
if (isEmpty()) {
throw new IllegalArgumentException("queue is empty");
}
return queue[front];
}
public void resize(int Capacity) {
E[] newqueue = (E[]) new Object[Capacity + 1];
for (int i = 0; i < size; i++) {
newqueue[i] = queue[(i + front) % queue.length];
}
queue = newqueue;
front = 0;
tail = size;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(String.format("LoopQueue:Size:%d,Capacity:%d\nfront [", getSize(), getCapacity()));
for (int i = front; i != tail; i = (i + 1) % queue.length) {
sb.append(queue[i]);
if (i != tail - 1) {
sb.append(',');
}
}
sb.append("] tail");
return sb.toString();
}
}
|
package com.beiyelin.projectportal.service;
import com.beiyelin.common.reqbody.PageReq;
import com.beiyelin.common.resbody.PageResp;
import com.beiyelin.commonsql.jpa.MasterDataCRUDService;
import com.beiyelin.projectportal.bean.OperationPeriodQuery;
import com.beiyelin.projectportal.bean.ProjectQuery;
import com.beiyelin.projectportal.entity.OperationPeriod;
import java.util.List;
/**
* @Description:
* @Author: newmann
* @Date: Created in 22:29 2018-02-21
*/
public interface OperationPeriodService extends MasterDataCRUDService<OperationPeriod> {
/**
* 判断代码是否可用
* @param code
* @return
*/
boolean checkCodeAvailable(String code);
/**
* 在修改代码的时候使用,所以要带上Id
* @param code
* @return
*/
boolean checkCodeAvailableWithId(String code, String id);
/**
* 判断项目名称是否可用
* @param name
* @return
*/
boolean checkNameAvailable(String name);
/**
* 判断项目名称是否可用
* @param name
* @return
*/
boolean checkNameAvailableWithId(String name, String id);
// /**
// * 获取所有可用的部门
// * @return
// */
// List<OperationPeriod> findAllAvailableDepartments();
List<OperationPeriod> fetchAvailableByCodeOrName(String searchStr);
List<OperationPeriod> fetchByCodeOrName(String searchStr);
/**
* 支持前端的list界面查询
* @param query
* @param pageReq
* @return
*/
PageResp<OperationPeriod> fetchByQuery(OperationPeriodQuery query, PageReq pageReq);
// /**
// * 取消单据
// */
// OperationPeriod cancel(OperationPeriod project);
// /**
// * 提交单据
// */
// OperationPeriod submit(OperationPeriod project);
/**
* 关账
*/
OperationPeriod close(OperationPeriod project);
}
|
package sample.controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
import sample.model.Car;
import sample.service.CarService;
import java.io.IOException;
/**
* klasa conroller pozwalajaca na zarzadzanie widokiem soldCars.fxml
*/
public class SoldCarsController {
@FXML
public ListView<Car> carList;
private CarService carService;
/**
* metoda uruchamiana podczas wlaczenia widoku, zadanie inicjalizacja pol klasy
*/
public void initialize() {
carService = new CarService();
carList.getItems().setAll(carService.soldCars());
}
/**
* metoda pozwalajaca na zmiane widoku na mainView.fxml
*
* @param actionEvent event pozwalajacy na przechwycenie aktualnie otwartego okna
* @throws IOException rzucany w momencie gdy scieżka do pliku fxml jest nie poprawna
*/
public void back(ActionEvent actionEvent) throws IOException {
Parent parent = FXMLLoader.load(getClass().getResource("/fxml/mainView.fxml"));
Scene scene = new Scene(parent);
Stage window = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
}
}
|
/*
* UniTime 3.4 - 3.5 (University Timetabling Application)
* Copyright (C) 2012 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.test;
import java.util.List;
import java.util.Properties;
import org.hibernate.Session;
import org.unitime.commons.hibernate.util.HibernateUtil;
import org.unitime.timetable.model.ExamType;
import org.unitime.timetable.model.Location;
import org.unitime.timetable.model.dao._RootDAO;
/**
* @author Tomas Muller
*/
public class FinalExamRoomFix {
public static void main(String[] args) {
try {
HibernateUtil.configureHibernate(new Properties());
Session hibSession = new _RootDAO().getSession();
ExamType type = ExamType.findByReference("final");
for(Location location: (List<Location>)hibSession.createQuery(
"select distinct p.location from ExamLocationPref p where p.examPeriod.examType.uniqueId = :type"
).setLong("type", type.getUniqueId()).list()) {
if (!location.hasFinalExamsEnabled()) {
System.out.println("Fixing " + location.getLabel() + " (" + location.getSession().getLabel() + ")");
location.setExamEnabled(type, true);
hibSession.saveOrUpdate(location);
}
}
for(Location location: (List<Location>)hibSession.createQuery(
"select distinct r from Exam x inner join x.assignedRooms r where x.examType.uniqueId = :type"
).setLong("type", type.getUniqueId()).list()) {
if (!location.hasFinalExamsEnabled()) {
System.out.println("Fixing " + location.getLabel() + " (" + location.getSession().getLabel() + ")");
location.setExamEnabled(type, true);
hibSession.saveOrUpdate(location);
}
}
hibSession.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateUtil.closeHibernate();
}
}
}
|
package com.homelinux.michele.ipconfig;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.widget.RemoteViews;
public class IpWidgetProvider extends AppWidgetProvider {
private static final String HOME_SSID = "\"michele\"";
private static final String GW_REMOTE = "192.168.1.200";
private static final String GW_LOCAL = "192.168.1.254";
public static String WIDGET_BUTTON = "com.michele.homelinux.WIDGET_BUTTON";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WIDGET_BUTTON)) {
String gw = getCurrentGateway(context);
try {
if (GW_LOCAL.equals(gw)) {
setCurrentGateway(context, InetAddress.getByName(GW_REMOTE));
} else if (GW_REMOTE.equals(gw)) {
setCurrentGateway(context, InetAddress.getByName(GW_LOCAL));
}
// AppWidgetManager appWidgetManager = AppWidgetManager
// .getInstance(context);
// updateView(context, appWidgetManager);
} catch (UnknownHostException e) {
e.printStackTrace();
}
} else {
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
updateView(context, appWidgetManager);
}
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
updateView(context, appWidgetManager);
}
private WifiConfiguration findHomeWifiConfiguration(WifiManager wifiManager) {
List<WifiConfiguration> networks = wifiManager.getConfiguredNetworks();
if (networks != null) {
for (WifiConfiguration wifiConfiguration : networks) {
if (HOME_SSID.equals(wifiConfiguration.SSID)) {
return wifiConfiguration;
}
}
}
return null;
}
private String getCurrentGateway(Context context) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
return "WiFi OFF";
}
WifiConfiguration wifiConfiguration = findHomeWifiConfiguration(wifiManager);
if (wifiConfiguration != null) {
try {
InetAddress gateway = getGateway(wifiConfiguration);
if (gateway == null) {
return "NO GATEWAY";
} else {
return gateway.getHostAddress();
}
} catch (Exception e) {
e.printStackTrace();
return "ERROR";
}
}
return "HOME NOT FOUND";
}
private InetAddress getGateway(WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException,
ClassNotFoundException, NoSuchMethodException,
InstantiationException, InvocationTargetException {
Class<? extends WifiConfiguration> wifiConfClass = wifiConf.getClass();
Method getStaticIpConfiguration = wifiConfClass
.getDeclaredMethod("getStaticIpConfiguration");
Object staticIpConfiguration = getStaticIpConfiguration
.invoke(wifiConf);
if (staticIpConfiguration != null) {
Field field = staticIpConfiguration.getClass().getField("gateway");
return (InetAddress) field.get(staticIpConfiguration);
}
return null;
}
private void setCurrentGateway(Context context, InetAddress gateway) {
try {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null && wifiManager.isWifiEnabled()) {
WifiConfiguration wifiConfiguration = findHomeWifiConfiguration(wifiManager);
setGateway(gateway, wifiConfiguration);
wifiManager.updateNetwork(wifiConfiguration);
wifiManager.setWifiEnabled(false);
wifiManager.setWifiEnabled(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setGateway(InetAddress gateway, WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException,
ClassNotFoundException, NoSuchMethodException,
InstantiationException, InvocationTargetException {
Class<? extends WifiConfiguration> wifiConfClass = wifiConf.getClass();
Method getStaticIpConfiguration = wifiConfClass
.getDeclaredMethod("getStaticIpConfiguration");
Object staticIpConfiguration = getStaticIpConfiguration
.invoke(wifiConf);
if (staticIpConfiguration != null) {
Field field = staticIpConfiguration.getClass().getField("gateway");
field.set(staticIpConfiguration, gateway);
}
}
private void updateView(Context context, AppWidgetManager appWidgetManager) {
// Get all ids
ComponentName thisWidget = new ComponentName(context,
IpWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
String gw = getCurrentGateway(context);
remoteViews.setTextViewText(R.id.update, gw);
// Register an onClickListener
Intent intent = new Intent(context, IpWidgetProvider.class);
intent.setAction(WIDGET_BUTTON);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
|
package com.github.vinja.server;
import java.util.Set;
import com.github.vinja.compiler.CompilerContext;
import com.github.vinja.omni.ClassInfo;
import com.github.vinja.omni.ClassMetaInfoManager;
public class SzjdeLocateSourceCommand extends SzjdeCommand {
public String execute() {
String classPathXml = params.get(SzjdeConstants.PARAM_CLASSPATHXML);
String className = params.get(SzjdeConstants.PARAM_CLASS_NAME);
String sourceType = params.get(SzjdeConstants.PARAM_SOURCE_TYPE);
CompilerContext cc = getCompilerContext(classPathXml);
ClassMetaInfoManager cmm = cc.getClassMetaInfoManager();
if (sourceType != null && sourceType.equals("impl")) {
ClassInfo classInfo = cmm.getMetaInfo(className);
if (classInfo != null) {
Set<String> subNames = classInfo.getSubNames();
if (subNames.size() == 1) {
className = subNames.toArray(new String[]{})[0];
}
}
}
String sourcePath = cc.findSourceOrBinPath(className);
StringBuilder sb = new StringBuilder();
sb.append(sourcePath).append("\n");
if (className.indexOf(".") > -1) {
sb.append(className.substring(className.lastIndexOf(".")+1));
} else {
sb.append(className);
}
return sb.toString();
}
}
|
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2014, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.jmx.expr;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* <p>Title: ResettingIterable</p>
* <p>Description: </p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.jmx.expr.ResettingIterable</code></p>
* @param <T> The expected type iterated by this iterable
*/
public class ResettingIterable<T> implements Iterable<T> {
/** The delegate iterable wrapped by this instance */
protected final Iterable<T> delegateIterable;
/** true if the iterators returned support {@link Iterator#remove()}, false otherwise */
protected final boolean removable;
/** The current iterator */
protected Iterator<T> currentIterator = null;
/**
* Converts the passed array of iterables to one iterables containing iterators for all the passed iterables
* @param resetable true if the returned iterable and the sub iterators should auto-reset on {@link Iterator#hasNext()} = false, false otherwise
* @param removable true if the returned iterable should be removable, false otherwise
* @param iterables The iterables to wrap
* @return An iterable of iterators
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Iterable<Iterator<?>> group(final boolean resetable, final boolean removable, final Iterable<?>...iterables) {
if(iterables==null || iterables.length==0) return (Collection<Iterator<?>>) Collections.emptyIterator();
List<Iterator<?>> iters = new ArrayList<Iterator<?>>(iterables.length);
for(Iterable<?> iterable: iterables) {
if(iterable==null) continue;
iters.add((Iterator<?>) new ResettingIterable(iterable, removable).iterator());
}
return resetable ? new ResettingIterable(iters, removable) : iters;
}
/**
* Converts the passed collection of iterables to one iterables containing iterators for all the passed iterables
* @param resetable true if the returned iterable and the sub iterators should auto-reset on {@link Iterator#hasNext()} = false, false otherwise
* @param removable true if the returned iterable should be removable, false otherwise
* @param iterables The iterables to wrap
* @return An iterable of iterators
*/
public static Iterable<Iterator<?>> group(final boolean resetable, final boolean removable, final Collection<?> iterables) {
return group(resetable, removable, iterables.toArray(new Iterable[0]));
}
/**
* Creates a new ResettingIterable
* @param delegateIterable The delegate iterable wrapped by this instance
* @param removable true if the iterators returned support {@link Iterator#remove()}, false otherwise
*/
public ResettingIterable(final Iterable<T> delegateIterable, final boolean removable) {
this.delegateIterable = delegateIterable;
this.removable = removable;
}
/**
* Creates a new ResettingIterable that supports {@link Iterator#remove()} if the delegate supports it
* @param delegateIterable The delegate iterable wrapped by this instance
*/
public ResettingIterable(final Iterable<T> delegateIterable) {
this(delegateIterable, true);
}
/**
* {@inheritDoc}
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<T> iterator() {
currentIterator = new ResettingIterator(delegateIterable.iterator());
return currentIterator;
}
/**
* <p>Title: ResettingIterator</p>
* <p>Description: The delegate resetting iterator that resets when {@link Iterator#hasNext()} returns false</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.jmx.expr.ResettingIterable.ResettingIterator</code></p>
*/
@SuppressWarnings("hiding")
class ResettingIterator<T> implements Iterator<T> {
private Iterator<T> delegateIterator;
public ResettingIterator(Iterator<T> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
* If false is returned, the iterator is reset.
*
* @return {@code true} if the iteration has more elements
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
final boolean has = delegateIterator.hasNext();
if(!has) {
iterator();
delegateIterator = (Iterator<T>) currentIterator;
}
return has;
}
/**
* @return
* @see java.util.Iterator#next()
*/
public T next() {
return delegateIterator.next();
}
/**
*
* @see java.util.Iterator#remove()
*/
public void remove() {
if(!removable) throw new UnsupportedOperationException("This iterator does not support remove");
delegateIterator.remove();
}
}
}
|
package models.dbmanager;
import models.entity.Buyer;
import models.util.DatabaseTool;
import javax.persistence.Query;
import java.util.List;
/**
* Created by shanmao on 15-12-16.
*/
public class BuyerManager {
/** 插入一个刷手 */
public static boolean insert(String name,String wangwang,String mobilephone,int team){
try {
DatabaseTool.defaultEm.getTransaction().begin(); //启动事务
Buyer entry = new Buyer();
try {
entry.setName(name);
entry.setWangwang(wangwang);
entry.setMobilephone(mobilephone);
entry.setTeam(team);
DatabaseTool.defaultEm.persist(entry);
DatabaseTool.defaultEm.getTransaction().commit(); //提交事务
} catch (Exception e) {
e.printStackTrace();
DatabaseTool.defaultEm.getTransaction().rollback(); //插入失败,回滚
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/** 获取所有刷手 */
public static List<Buyer> getALl(){
try {
Query query = DatabaseTool.defaultEm.createQuery("select u from Buyer u");
List<Buyer> entry =(List<Buyer>)query.getResultList();
return entry;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 获取所有分组 */
public static List<Integer> getALlTeams(){
try {
Query query = DatabaseTool.defaultEm.createQuery("select distinct team from Buyer");
List<Integer> entry =(List<Integer>)query.getResultList();
return entry;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 获取指定小组的所有刷手 */
public static List<Buyer> getALlByTeam(int team){
try {
Query query = DatabaseTool.defaultEm.createQuery("select u from Buyer u where u.team = " + team);
List<Buyer> entry =(List<Buyer>)query.getResultList();
return entry;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 获取指定小组的刷手数量 */
public static Long getBuyerCountByTeam(int team){
try {
Query query = DatabaseTool.defaultEm.createQuery("select count(u) from Buyer u where u.team = " + team);
Long entry =(Long) query.getSingleResult();
return entry;
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/** 获取刷手的总数量 */
public static Long getBuyerCount(){
try {
Query query = DatabaseTool.defaultEm.createQuery("select count(u) from Buyer u");
Long entry =(Long)query.getSingleResult();
return entry;
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
}
|
package com.algaworks.ecommerce.model;
import lombok.Data;
import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Entity
@Table(name = "produto",
uniqueConstraints = { @UniqueConstraint(name = "uk_nome", columnNames = {"nome"}) },
indexes = { @Index(name = "idx_nome", columnList = "nome") })
public class Produto extends EntidadeBaseInteger {
@Column(length = 100, nullable = false)
private String nome;
@Lob
private String descricao;
private BigDecimal preco;
@Lob
private byte[] foto;
@ManyToMany
@JoinTable(name = "produto_categoria",
joinColumns = @JoinColumn(name = "produto_id", nullable = false,
foreignKey = @ForeignKey(name = "fk_produto_categoria_produto")),
inverseJoinColumns = @JoinColumn(name = "categoria_id", nullable = false,
foreignKey = @ForeignKey(name = "fk_produto_categoria_categoria")))
private List<Categoria> categorias;
@OneToOne(mappedBy = "produto")
private Estoque estoque;
@Column(name = "data_criacao", updatable = false, nullable = false)
private LocalDateTime dataCriacao;
@Column(name = "data_atualizacao", insertable = false)
private LocalDateTime dataAtualizacao;
@ElementCollection
@CollectionTable(name = "produto_tag",
joinColumns = @JoinColumn(name = "produto_id",
foreignKey = @ForeignKey(name = "fk_produto_produto_tag")))
@Column(name = "tag", length = 50, nullable = false)
private List<String> tags;
@ElementCollection
@CollectionTable(name = "produto_atributo",
joinColumns = @JoinColumn(name = "produto_id",
foreignKey = @ForeignKey(name = "fk_produto_produto_atributo")))
private List<Atributo> atributos;
@PrePersist
private void preencheDataCriacao() {
this.dataCriacao = LocalDateTime.now();
}
@PreUpdate
private void preencheDataAtualizacao() {
this.dataAtualizacao = LocalDateTime.now();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.